#!/bin/bash
#SBATCH --job-name=r1_meme
#SBATCH --partition=datamonkey
#SBATCH --cpus-per-task=16
#SBATCH --mem=48G
#SBATCH --time=04:00:00
#SBATCH --output=/home/sweaver/programming/axomeme/reviews/moncla_h3nx_hoststrategy_REVIEW/REPRODUCTION/slurm_logs/%A_%a.out
#SBATCH --error=/home/sweaver/programming/axomeme/reviews/moncla_h3nx_hoststrategy_REVIEW/REPRODUCTION/slurm_logs/%A_%a.err
#
# R1: hyphaeon meme site-level episodic selection, one array task per host×gene (manifest_r1.csv).
# Tests PEER_REVIEW M2: is "no adaptive evolution in birds" real, or a persistence-dependent-estimator artifact?
# --no-tree (TN93) per Steven's call: supplied trees have ~2x extra tips; we test signal presence, not their exact tree.
# NOT set -e: one failing task must not poison the array; each task records its own status.

REPRO="/home/sweaver/programming/axomeme/reviews/moncla_h3nx_hoststrategy_REVIEW/REPRODUCTION"
MANIFEST="${REPRO}/scripts/manifest_r1.csv"
HYPHAEON="/home/sweaver/.local/bin/hyphaeon"   # system-py3.9 launcher; deps now complete in ~/.local (pytz, packaging)

echo "[$(date '+%F %T')] host=$(hostname) job=${SLURM_ARRAY_JOB_ID} task=${SLURM_ARRAY_TASK_ID}"
LINE_NO=$(( SLURM_ARRAY_TASK_ID + 1 ))   # +1 to skip header
ROW="$(sed -n "${LINE_NO}p" "${MANIFEST}")"
[ -z "${ROW}" ] && { echo "no row ${LINE_NO}"; exit 0; }

IFS=, read -r GENE HOST ALN OUT_JSON OUT_CSV <<< "${ROW}"
echo "  gene=${GENE} host=${HOST} aln=${ALN}"

# idempotent: skip if already done
if [ -s "${OUT_CSV}" ] && [ -s "${OUT_JSON}" ]; then
  echo "  [skip] outputs exist"; exit 0
fi

"${HYPHAEON}" meme -a "${ALN}" --no-tree --cpu -o "${OUT_JSON}" -c "${OUT_CSV}"
echo "  [$(date '+%F %T')] exit=$? -> ${OUT_CSV}"
exit 0
