# Implementation sketch — `package_sentdhiomr_formal_outputs` rule

Goal: fold the post-processing scripts into a first-class daylily-omics-analysis rule
that packages the **per-sample delivery tree** for the `sentdhiomr` caller family,
satisfying the SeqOne ONT-VCF delivery requirements + the CN-track spec.

Target repo: `/Users/michael.kennemer/git-pinned/dayoa/daylily-omics-analysis` (`main`).
The scripts are implemented and verified against the Coriell proxy run
(`check_compliance.py` → 38/38) and are ready to port to `workflow/scripts/`.

---

## 1. Output tree (per sample; `<sample>` = short alias, e.g. HG002 / NA00232)
```
<sample>/
  results/      <sample>.snv.sort.vcf.gz(.tbi)   decompose + FILTER=PASS + confidence TAG
                <sample>.cnv.vcf.gz(.tbi)         depth CNV (tagged) + folded SMN CNV records
                <sample>.sv.vcf.gz(.tbi)          Sentieon SV only (delta #1)
                <sample>.mito.vcf.gz(.tbi)        multi-allelic split
                <sample>.eh.vcf.gz(.tbi)          EH: +GRCh38 contigs, NO decomposition
                <sample>.ploidy.tsv               idxstats-derived ploidy
                <sample>.cn.tsv.gz                CN track (GATK denoised-CR schema)
                <sample>.cram(.crai)              pipeline CRAM, <sample>-named (delta #2)
  qc/           <sample>.manifest.txt             delivered-file manifest (size/sha256/n_records)
                <sample>.metrics.json             consolidated QC metrics
  experimental/ <sample>.SMN.vcf.gz(.tbi)         full SMN detail (incl g.27134T>G)
                <sample>.tiddit.sv.vcf.gz(.tbi)   TIDDIT SV (kept separate)
                <sample>.<TARGET>.vcf.gz(.tbi)    per-gene segdup results (GBA1, NCF1, PMS2,
                                                  CFH, CYP11B1, STRC, HBA, CYP2D6, CYP21A2…)
```

## 2. Verified input paths (`MDIR` results root; wildcards `{sample}/{alnr}/{ddup}`)
| Source | Template (file:line in `sent_hybrid_ilmn_ont_modular.refactored.smk` unless noted) |
|---|---|
| SNV | `…/{alnr}/{ddup}/snv/sentdhiomr/{sample}.{alnr}.{ddup}.sentdhiomr.snv.sort.vcf.gz` (1596) |
| CNV | `…/cnv/sentdhiomr/…cnv.vcf.gz` (1806) — has INFO `CN`,`END`,`SVLEN`,`SVTYPE`,`##contig` |
| Sentieon SV | `…/sv/sentdhiomr/…sv.vcf.gz` (1698) — DEL/INS only |
| mito | `…/mito/sentdhiomr/…mito.vcf.gz` (2142) |
| segdup results | `…/segdup/sentdhiomr/results/<GENE>/{sample}.<GENE>.result.vcf.gz` |
| TIDDIT SV | `…/align/sent/{ddup}/sv/tiddit/{sample}.sent.tiddit.sv.sort.vcf.gz` |
| EH | `…/align/sent/{ddup}/htd/expansionhunter/{sample}.sent.{ddup}.eh.vcf` (no contigs!) |
| SMN12 | `…/align/sent/{ddup}/htd/smn12/{sample}.sent.{ddup}.smn12.summary.json` (`smn_copynumbercaller.smk:9`) |
| samtmetrics | `…/align/sent/{ddup}/alignqc/samtmetrics/{sample}.sent.{ddup}.{flagstat,stats,idxstat}.tsv` |
| CRAM | `…/align/{aln}/…{sample}*.cram` |

## 3. Scripts → `workflow/scripts/` (all implemented & verified)
| Script | Role |
|---|---|
| `vcf_utils.py` | `index_vcf`/`ensure_bgzf`/`bgzip_sort_index`/`norm_split`/`sample_alias` (NA/HG regex) |
| `tag_vcf.py` | SNV decompose + FILTER=PASS + INFO/TAG (BGZF out) |
| `tag_cnv_vcf.py` | CNV confidence TAG via SV support + rescue |
| `make_smn1_result_vcf.py` | `build_full_smn_records` (experimental) + `build_smn_cnv_records` (fold; per-metric abnormal-only, full-gene <DEL>/<DUP>, CN in INFO, base-ALT dropped) |
| `cn_track.py` | CN track from cnv PASS records (`LINEAR_COPY_RATIO=DPS[0]/autosomal-median`) |
| `eh_prep.py` | inject GRCh38 `##contig` into EH header, bgzip+tabix, NO decomposition |
| `cnv_to_ploidy.py` | ploidy.tsv from idxstats |
| `make_sample_metrics.py` | parse flagstat/stats/idxstat(+smn12) → nested metrics.json |
| `package_delivery_tree.py` | per-sample orchestrator (becomes the rule's `script:`) |
| `check_compliance.py` | SeqOne checklist validator (CI / post-rule check) |

Per-sample build steps (orchestrator): snv→decompose/PASS/TAG; cnv→tag → `norm -m -any`
→ fold SMN (`build_smn_cnv_records`) → `bcftools sort` → index; sv→Sentieon `norm`+reheader;
mito→`norm`+reheader; eh→`eh_prep`; ploidy→idxstats; cn track; SMN full + tiddit + per-target
→ experimental; metrics + manifest → qc.

## 4. Snakemake rules
```python
rule package_sentdhiomr_formal_outputs:        # per-sample
    input:  unpack(_package_inputs)            # snv, cnv, sentieon-sv, tiddit-sv, mito, eh,
                                               #   smn12, idxstat, flagstat, stats, segdup results
    output: done = MDIR + "{sample}/align/{alnr}/{ddup}/delivery/{sample}.delivery.done",
            manifest = MDIR + "{sample}/align/{alnr}/{ddup}/delivery/{sample}/qc/{sample}.manifest.txt"
    params: outdir=…, sample_alias=get_sample_alias, cluster_sample=ret_sample
    wildcard_constraints: alnr="|".join(ALIGNERS_DHIOMR)
    conda:  "../envs/bcftools_v0.1.yaml"
    log/benchmark/resources: house style
    script: "../scripts/package_delivery_tree.py"   # reads snakemake.input/params

localrules: produce_sentdhiomr_formal_outputs
rule produce_sentdhiomr_formal_outputs:        # TARGET
    input: expand(<…delivery.done>, sample=SSAMPS, alnr=ALIGNERS_DHIOMR, ddup=DDUP)
    output: "gatheredall.sentdhiomr_formal_outputs"
```
Separate **optional prerequisite** (config-gated) for the SeqOne BAM variant:
```python
rule sentdhiomr_cram_to_bam:                   # per technology
    input:  cram=…{sample}*.cram
    output: bam=…/{sample}.bam, bai=…/{sample}.bam.bai
    params: ref=config["supporting_files"]["files"]["huref"]["fasta"]["name"]
    conda:  "../envs/samtools_v0.1.yaml"
    shell:  "samtools view -b -T {params.ref} {input.cram} | samtools sort -o {output.bam}; samtools index {output.bam}"
```
Wire `include: "rules/package_sentdhiomr_formal_outputs.smk"` near the other aggregators.

Config block `config["sentdhiomr"]["package"]`: `enable`, `deliver_bam`, `cn_track`,
`experimental_targets` (gene list incl. CYP21A2), cnv-tag thresholds, `sample_alias_source`.

## 5. ⚠ Intentional deltas from the SeqOne doc (confirm before upload)
1. **SV not merged** — `results/sv` is Sentieon-only; TIDDIT in `experimental/`. SeqOne
   expects ONE merged SV file. (A merge step can run at upload, or flip to merged in results.)
2. **CRAM not BAM** — `results/` ships CRAM; the optional `sentdhiomr_cram_to_bam` rule
   produces the BAM variant SeqOne prefers.
S3 upload to `s3://seqone-prod-us-s3-uploads/im-transfer-giab/` remains a separate ops step.
Everything else (naming, bgzip+tabix, SMN-in-CNV, EH contigs+no-decompose, multi-allelic
split, CN track, exactly-the-emitted SMN records) is compliant — verified by
`check_compliance.py` (38/38 on the Coriell proxy).

## 6. Notes / open items
- `make_smn1_result_vcf.py` lives in the experiment dir for the prototype; move to
  `workflow/scripts/` (or a `daylily_omics_analysis` submodule) when porting.
- bcftools warns "INFO/SVLEN must be Number=A" on Sentieon SV `norm` — benign here
  (few multiallelic SVs); a one-line `bcftools reheader` SVLEN→Number=A clears it.
- Short alias: prefer a manifest/`SampleSheet` `sample_alias` column; regex `(?:NA|HG)\d+`
  is the fallback (handles GIAB HG00x and Coriell NA#####).
- GT mapping for SMN CN3/CN4 uses 0/1 and 1/1 (doc specifies only CN0→1/1, CN1→0/1).
