Complete E1-v2 workflow: stage A ladder + control + gate, stage B variants + baseline
- Snakefile: modules -> plain include: (single namespace; fixed cross-module helper resolution), rule all with stage-A/stage-B target sets driven by flat --config stage_b_arch/budget/stride switches. - config/main.yaml: v2 run matrix (ladder 12-grid, control 1M cnn s4), store excludes (DCS spike-in, in-corpus escherichia trap reads), barcoding kit (SQK-RBK114-96 classified during dorado basecalls), removes v1 quota. - baseline_pipeline: CUDA branch streams per-chunk dorado emit-sam through minimap2 (-N 10, tags preserved) and samtools view into per-batch BAMs, merged with samtools cat; ROCm/slorado fallback kept. - ml_pipeline: label parquets -> signal stores (main / windows-ablation w4 / trap store) -> 12 ladder trainings + shuffled control -> custom_models test with the trap store (TP2) -> custom_models gate over the g11 runs; stage B adds windows ablation, holdout/core_clade(/bacillus_group) variants and the dorado-fast alignment baseline on the winner's identical test split. - scripts: bam2annotation now emits source_run (barcoded -> barcodeNN from the dorado tags, dataset fallback); new label_qc.py (TP1 capture counts) and baseline_eval.py. - custom_models submodule: bump to test_split.parquet export commit. - README: two-stage run instructions (dev dry-run vs runner GPU).
This commit is contained in:
@@ -1,70 +1,109 @@
|
||||
def get_model_name(wildcards):
|
||||
config_param=f'{wildcards.model}_model_name'
|
||||
return config[config_param]
|
||||
"""Data pipeline: pod5 download -> dorado basecall (+ barcode classification)
|
||||
-> alignment to the panel -> merged BAM per (dataset, model).
|
||||
|
||||
def get_model_requirement(wildcards):
|
||||
config_param=f'{wildcards.model}_model_name'
|
||||
return config['dorado_model_dir']+'/'+config[config_param]
|
||||
The 'hac' arm supplies the probe labels (stores); the 'fast' arm is the E1-v2
|
||||
alignment baseline (dorad-fast + minimap2 + LCA). On CUDA the label job
|
||||
threads dorado's classified SAM (per-read barcode tags from --kit-name)
|
||||
straight into minimap2 (tags survive alignment, verified on minimap2 2.31)
|
||||
and samtools view; per-batch BAMs are merged per (dataset, model). On ROCm
|
||||
(slorado, non-barcode) the original fastq->align->bam chain is kept as the
|
||||
fallback; barcodes are then unavailable and labels fall back to the dataset
|
||||
name as source_run.
|
||||
|
||||
def get_benchmarking_file(wildcards):
|
||||
config_param = f'{wildcards.model}_benchmarks_file'
|
||||
if config[config_param]:
|
||||
return f'--batchsize-benchmarks-file {config[config_param]}'
|
||||
return ''
|
||||
Host prerequisites: dorado on PATH, aws cli, curl; --resources gpu=N serialises
|
||||
the GPU label jobs.
|
||||
"""
|
||||
|
||||
def get_qscore(wildcards):
|
||||
config_param = f'{wildcards.model}_min_q'
|
||||
if config[config_param]:
|
||||
return f'--min-qscore {config[config_param]}'
|
||||
return ''
|
||||
|
||||
def get_batch_names(input_file):
|
||||
with open(input_file,'rt') as ih:
|
||||
return [line.strip().split('/')[-1].split('.')[0] for line in ih]
|
||||
RUN_NAMES = {
|
||||
"nomiss": "PBK98658_853a956f_57f83f46", # NO-MISS P2i flow cell
|
||||
"trap": "ATCC_25922_202309", # public single-sample E. coli run
|
||||
}
|
||||
|
||||
|
||||
def run_name(dataset):
|
||||
return RUN_NAMES[dataset]
|
||||
|
||||
|
||||
def batch_names(dataset):
|
||||
"""Pod5 chunk names per dataset (nomiss plain ints, trap 'batchN')."""
|
||||
if dataset == "nomiss":
|
||||
return list(range(1, config["pod5_dataset_size"] + 1, config["pod5_stride"]))
|
||||
return [f"batch{x}" for x in range(1, config["trap_dataset_size"] + 1, config["trap_pod5_stride"])]
|
||||
|
||||
|
||||
def get_run_name(wildcards):
|
||||
if wildcards.dataset == 'nomiss':
|
||||
return 'PBK98658_853a956f_57f83f46'
|
||||
if wildcards.dataset == 'trap':
|
||||
return 'ATCC_25922_202309'
|
||||
return run_name(wildcards.dataset)
|
||||
|
||||
|
||||
def get_batch_range(wildcards):
|
||||
if wildcards.dataset == 'nomiss':
|
||||
return range(1,config['pod5_dataset_size']+1,config['pod5_stride'])
|
||||
if wildcards.dataset == 'trap':
|
||||
return [f'batch{x}' for x in range(1,config['trap_dataset_size']+1,config['trap_pod5_stride'])]
|
||||
return batch_names(wildcards.dataset)
|
||||
|
||||
|
||||
def get_model_name(wildcards):
|
||||
return config[f"{wildcards.model}_model_name"]
|
||||
|
||||
|
||||
def get_model_requirement(wildcards):
|
||||
return config["dorado_model_dir"] + "/" + config[f"{wildcards.model}_model_name"]
|
||||
|
||||
|
||||
def get_benchmarking_file(wildcards):
|
||||
bench = config.get(f"{wildcards.model}_benchmarks_file")
|
||||
if bench:
|
||||
return f"--batchsize-benchmarks-file {bench}"
|
||||
return ""
|
||||
|
||||
|
||||
def get_qscore(wildcards):
|
||||
q = config.get(f"{wildcards.model}_min_q")
|
||||
if q:
|
||||
return f"--min-qscore {q}"
|
||||
return ""
|
||||
|
||||
|
||||
def get_kit_flag(wildcards):
|
||||
kit = config["barcoding_kit"].get(wildcards.dataset)
|
||||
if kit:
|
||||
return f"--kit-name {kit}"
|
||||
return ""
|
||||
|
||||
|
||||
wildcard_constraints:
|
||||
batch=r"(batch)?\d+",
|
||||
model=r'hac|fast'
|
||||
model="hac|fast",
|
||||
dataset="nomiss|trap"
|
||||
|
||||
GPU_STACK = config.get('gpu_stack','cuda')
|
||||
GPU_STACK = config.get("gpu_stack", "cuda")
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# pod5 acquisition
|
||||
# -------------------------------------------------------------------------
|
||||
rule download_nomiss_pod5:
|
||||
output:
|
||||
'../data/raw_pod5/nomiss/PBK98658_853a956f_57f83f46_{batch}.pod5'
|
||||
"../data/raw_pod5/nomiss/PBK98658_853a956f_57f83f46_{batch}.pod5"
|
||||
threads: 4
|
||||
|
||||
shell:
|
||||
"""
|
||||
aws s3 cp --no-sign-request s3://ont-open-data/nomiss_96BC_P2I_SUP_2026/raw/pod5/PBK98658_853a956f_57f83f46_{wildcards.batch}.pod5 {output}
|
||||
"""
|
||||
|
||||
|
||||
rule download_trap_tar:
|
||||
output:
|
||||
temp('../data/raw_pod5/trap/all.tar')
|
||||
temp("../data/raw_pod5/trap/all.tar")
|
||||
threads: 4
|
||||
params:
|
||||
tmp='../data/raw_pod5/trap/trap_all.tar'
|
||||
shell:
|
||||
"""
|
||||
curl -L --http1.1 -A "Mozilla/5.0" "https://api.figshare.com/v2/file/download/45408628" -o {output}
|
||||
"""
|
||||
|
||||
|
||||
rule untar_trap_folder:
|
||||
input:
|
||||
'../data/raw_pod5/trap/all.tar'
|
||||
"../data/raw_pod5/trap/all.tar"
|
||||
output:
|
||||
directory('../data/raw_pod5/trap/all')
|
||||
directory("../data/raw_pod5/trap/all")
|
||||
threads: 1
|
||||
shell:
|
||||
"""
|
||||
@@ -72,45 +111,69 @@ rule untar_trap_folder:
|
||||
tar xf {input} -C {output}
|
||||
"""
|
||||
|
||||
|
||||
rule extract_trap_pod5:
|
||||
input:
|
||||
'../data/raw_pod5/trap/all'
|
||||
"../data/raw_pod5/trap/all"
|
||||
output:
|
||||
'../data/raw_pod5/trap/ATCC_25922_202309_{batch}.pod5'
|
||||
"../data/raw_pod5/trap/ATCC_25922_202309_{batch}.pod5"
|
||||
threads: 1
|
||||
params:
|
||||
input_pod5='{input[0]}/ATCC_25922__202309/ATCC_25922__202309_{batch}.pod5'
|
||||
shell:
|
||||
"""
|
||||
mv {params.input_pod5} {output}
|
||||
mv {input}/ATCC_25922__202309/ATCC_25922__202309_{wildcards.batch}.pod5 {output}
|
||||
"""
|
||||
|
||||
if GPU_STACK == 'cuda':
|
||||
rule basecall_pod5_dorado:
|
||||
# -------------------------------------------------------------------------
|
||||
# basecall + align (merged per dataset/model BAM; barcoding is classifier-side)
|
||||
# -------------------------------------------------------------------------
|
||||
if GPU_STACK == "cuda":
|
||||
rule label_pod5_batch:
|
||||
input:
|
||||
pod5='../data/raw_pod5/{dataset}/{run}_{batch}.pod5',
|
||||
model=get_model_requirement
|
||||
pod5="../data/raw_pod5/{dataset}/{run}_{batch}.pod5",
|
||||
model=get_model_requirement,
|
||||
ref="../data/reference_genomes/full_reference.mmi"
|
||||
output:
|
||||
temp('../data/basecalled_reads/{dataset}/{model}/{run}_{batch}.fastq')
|
||||
threads:
|
||||
32
|
||||
bam=temp("../data/aligned_reads/{dataset}/{model}/{run}_{batch}.bam")
|
||||
threads: 32
|
||||
resources:
|
||||
gpu=1
|
||||
params:
|
||||
benchmarking=get_benchmarking_file,
|
||||
min_qscore=get_qscore,
|
||||
dorado_model=get_model_name,
|
||||
benchmarking=get_benchmarking_file,
|
||||
min_q=get_qscore,
|
||||
kit_flag=get_kit_flag,
|
||||
minimap_extra=config["minimap_extra"],
|
||||
conda:
|
||||
"../envs/minimap.yaml"
|
||||
shell:
|
||||
"""
|
||||
dorado basecaller --models-directory {config[dorado_model_dir]} --emit-fastq {params.benchmarking} {params.min_qscore} {params.dorado_model} {input.pod5} > {output}
|
||||
dorado basecaller --models-directory {config[dorado_model_dir]} --emit-sam {params.benchmarking} {params.min_q} {params.kit_flag} {params.dorado_model} {input.pod5} \
|
||||
| minimap2 -a -x map-ont {params.minimap_extra} -t {threads} {input.ref} - \
|
||||
| samtools view -b -@ {threads} > {output}
|
||||
"""
|
||||
elif GPU_STACK == 'rocm':
|
||||
|
||||
rule merge_aligned_reads:
|
||||
input:
|
||||
bams=expand("../data/aligned_reads/{{dataset}}/{{model}}/{run}_{batch}.bam", batch=get_batch_range, run=get_run_name),
|
||||
output:
|
||||
bam=temp("../data/aligned_reads/{dataset}_{model}_to_genome.bam"),
|
||||
threads: 8
|
||||
conda:
|
||||
"../envs/samtools.yaml"
|
||||
shell:
|
||||
"""
|
||||
samtools cat -@ {threads} -o {output.bam} {input.bams}
|
||||
"""
|
||||
|
||||
elif GPU_STACK == "rocm":
|
||||
# slorado emits fastq only: barcode classification is not available on this
|
||||
# branch, so labels fall back to the dataset name as source_run.
|
||||
rule basecall_pod5_slorado:
|
||||
input:
|
||||
pod5='../data/raw_pod5/{dataset}/{run}_{batch}.pod5',
|
||||
pod5="../data/raw_pod5/{dataset}/{run}_{batch}.pod5",
|
||||
model=get_model_requirement
|
||||
output:
|
||||
temp('../data/basecalled_reads/{dataset}/{model}/{run}_{batch}.fastq')
|
||||
fastq=temp("../data/basecalled_reads/{dataset}/{model}/{run}_{batch}.fastq")
|
||||
threads:
|
||||
32
|
||||
resources:
|
||||
@@ -120,43 +183,42 @@ elif GPU_STACK == 'rocm':
|
||||
pod5-slorado basecaller -o {output} -t {threads} --flash=yes {input.model} {input.pod5}
|
||||
"""
|
||||
|
||||
rule concatenate_basecalled_fastq:
|
||||
input:
|
||||
expand('../data/basecalled_reads/{{dataset}}/{{model}}/{run}_{batch}.fastq',batch=get_batch_range,run=get_run_name)
|
||||
output:
|
||||
'../data/basecalled_reads/{dataset}_{model}.fastq.gz'
|
||||
threads: 1
|
||||
wildcard_constraints:
|
||||
model="hac|fast"
|
||||
shell:
|
||||
"""
|
||||
cat {input} | gzip -c > {output}
|
||||
"""
|
||||
rule concatenate_basecalled_fastq:
|
||||
input:
|
||||
expand("../data/basecalled_reads/{{dataset}}/{{model}}/{run}_{batch}.fastq", batch=get_batch_range, run=get_run_name)
|
||||
output:
|
||||
"../data/basecalled_reads/{dataset}_{model}.fastq.gz"
|
||||
threads: 1
|
||||
shell:
|
||||
"""
|
||||
cat {input} | gzip -c > {output}
|
||||
"""
|
||||
|
||||
rule align_reads_to_reference:
|
||||
input:
|
||||
fastq='../data/basecalled_reads/{dataset}_{model}.fastq.gz',
|
||||
ref='../data/reference_genomes/full_reference.mmi'
|
||||
output:
|
||||
'../data/aligned_reads/{dataset}_{model}_to_genome.sam'
|
||||
threads: 32
|
||||
conda:
|
||||
'../envs/minimap.yaml'
|
||||
shell:
|
||||
"""
|
||||
minimap2 -ax map-ont -t {threads} {input.ref} {input.fastq} > {output}
|
||||
"""
|
||||
rule align_reads_to_reference:
|
||||
input:
|
||||
fastq="../data/basecalled_reads/{dataset}_{model}.fastq.gz",
|
||||
ref="../data/reference_genomes/full_reference.mmi"
|
||||
output:
|
||||
temp("../data/aligned_reads/{dataset}_{model}_to_genome.sam")
|
||||
params:
|
||||
minimap_extra=config["minimap_extra"],
|
||||
threads: 32
|
||||
conda:
|
||||
"../envs/minimap.yaml"
|
||||
shell:
|
||||
"""
|
||||
minimap2 -ax map-ont {params.minimap_extra} -t {threads} {input.ref} {input.fastq} > {output}
|
||||
"""
|
||||
|
||||
rule convert_sam_to_bam:
|
||||
input:
|
||||
'../data/aligned_reads/{dataset}_{model}_to_genome.sam'
|
||||
output:
|
||||
'../data/aligned_reads/{dataset}_{model}_to_genome.sorted.bam'
|
||||
threads: 32
|
||||
conda:
|
||||
'../envs/samtools.yaml'
|
||||
shell:
|
||||
"""
|
||||
samtools view -b -@ {threads} {input} | samtools sort -@ {threads} > {output}
|
||||
samtools index -@ {threads} {output}
|
||||
"""
|
||||
rule convert_sam_to_bam:
|
||||
input:
|
||||
"../data/aligned_reads/{dataset}_{model}_to_genome.sam"
|
||||
output:
|
||||
temp("../data/aligned_reads/{dataset}_{model}_to_genome.bam")
|
||||
threads: 16
|
||||
conda:
|
||||
"../envs/samtools.yaml"
|
||||
shell:
|
||||
"""
|
||||
samtools view -b -@ {threads} {input} > {output}
|
||||
"""
|
||||
|
||||
+354
-48
@@ -1,66 +1,372 @@
|
||||
"""ML stage rules: label parquet -> signal stores -> trainings -> evaluation -> gate.
|
||||
|
||||
Stage targets (referenced by the top-level Snakefile `rule all`):
|
||||
STAGE_A_TARGETS — 12-point arch/param ladder + shuffled-label control,
|
||||
per-run test evaluation with the trap store, the gate verdict and the
|
||||
TP1 label-QC report.
|
||||
STAGE_B_TARGETS — only populated once the Stage-A winner is configured
|
||||
(config: stage_b_arch/stage_b_budget/stage_b_stride): windows ablation,
|
||||
robustness variants and the alignment-baseline report on the winner's
|
||||
test split.
|
||||
|
||||
Run directories: ../data/ml_models/{tag}/{arch}_{budget}_{stride} with tag in
|
||||
{ ladder, control, windows4, holdout, core_clade, bacillus_group }. The CLI
|
||||
run ids (params.run_id) carry the v2 suffixes (-shuf, -w4, -holdout, -core,
|
||||
-bacgrp); the gate takes the g11 runs (ladder + windows ablation + holdout)
|
||||
and ignores the restricted-clade diagnostics (class set differs by design).
|
||||
"""
|
||||
|
||||
MODEL_LABELS = "hac" # probe labels come from the HAC arm (fast arm = baseline)
|
||||
N_CLASSES = len(config["species_list"])
|
||||
MAIN_STORE = f"../data/ml_inputs/nomiss_{MODEL_LABELS}_data_store"
|
||||
W4_STORE = f"../data/ml_inputs/nomiss_{MODEL_LABELS}_data_store_w{config['max_windows_per_read']}"
|
||||
TRAP_STORE = f"../data/ml_inputs/trap_{MODEL_LABELS}_data_store"
|
||||
RUNS_DIR = "../data/ml_models"
|
||||
|
||||
STAGE_B_ARCH = str(config.get("stage_b_arch", "") or "")
|
||||
STAGE_B_BUDGET = str(config.get("stage_b_budget", "") or "")
|
||||
STAGE_B_STRIDE = str(config.get("stage_b_stride", "") or "")
|
||||
STAGE_B_READY = bool(STAGE_B_ARCH and STAGE_B_BUDGET and STAGE_B_STRIDE)
|
||||
|
||||
|
||||
def _flag(key):
|
||||
"""Truthy config key reader ('True'/'true' from --config become booleans)."""
|
||||
v = config.get(key)
|
||||
return v is True or str(v).lower() == "true"
|
||||
|
||||
|
||||
if (any(_flag(k) for k in ("windows_ablation", "holdout_runs", "core_clade", "bacillus_group"))
|
||||
and not STAGE_B_READY):
|
||||
raise ValueError(
|
||||
"Stage-B variants are enabled in config but stage_b_arch/stage_b_budget/stage_b_stride "
|
||||
"is not filled in (pick the winner from the Stage-A ladder reports first)"
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# pod5 chunk wiring (wildcard-safe helpers; nomiss values are fixed)
|
||||
# ---------------------------------------------------------------------------
|
||||
def dataset_pod5_list(w):
|
||||
"""Input function: pod5 chunk paths for the rule's dataset wildcard."""
|
||||
return [
|
||||
f"../data/raw_pod5/{w.dataset}/{get_run_name(w)}_{b}.pod5"
|
||||
for b in get_batch_range(w)
|
||||
]
|
||||
|
||||
|
||||
NOMISS_RUN = RUN_NAMES["nomiss"]
|
||||
|
||||
|
||||
def nomiss_pod5_list(w=None):
|
||||
"""Input function: nomiss pod5 chunk paths (dataset fixed, no wildcards)."""
|
||||
return [
|
||||
f"../data/raw_pod5/nomiss/{NOMISS_RUN}_{b}.pod5"
|
||||
for b in batch_names("nomiss")
|
||||
]
|
||||
|
||||
|
||||
def store_exclude_flags(w):
|
||||
"""CLI fragment listing a store's excluded refs/genera from config (wildcards)."""
|
||||
excl = config["store_excludes"][w.dataset]
|
||||
parts = []
|
||||
for ref in excl.get("refs", []):
|
||||
parts += ["--exclude-ref", str(ref)]
|
||||
for genus in excl.get("genera", []):
|
||||
parts += ["--exclude-genus", str(genus)]
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def nomiss_store_excludes(w=None):
|
||||
"""Same as store_exclude_flags for the (fixed) nomiss dataset."""
|
||||
excl = config["store_excludes"]["nomiss"]
|
||||
parts = []
|
||||
for ref in excl.get("refs", []):
|
||||
parts += ["--exclude-ref", str(ref)]
|
||||
for genus in excl.get("genera", []):
|
||||
parts += ["--exclude-genus", str(genus)]
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def fmt_budget(raw: str) -> str:
|
||||
"""Format a nominal budget (wildcard string) as '1.0M' for run ids."""
|
||||
return f"{int(raw) / 1_000_000:.1f}M"
|
||||
|
||||
|
||||
def _csv(genera):
|
||||
return ",".join(str(g) for g in genera)
|
||||
|
||||
|
||||
# tag -> (stage, store, run-id suffix, extra flags, extra genera flag)
|
||||
_CG = _csv(config["core_clade_genera"])
|
||||
_AG = _csv(config["bacillus_group_genera"])
|
||||
TRAIN_TAG_SPECS = {
|
||||
"ladder": {"stage": "ladder_point", "store": MAIN_STORE, "suffix": "", "flags": "", "genera_flag": ""},
|
||||
"control": {"stage": "control", "store": MAIN_STORE, "suffix": "-shuf", "flags": "", "genera_flag": ""},
|
||||
"windows4": {"stage": "windows_ablation", "store": W4_STORE, "suffix": "-w4", "flags": "", "genera_flag": ""},
|
||||
"holdout": {"stage": "robustness", "store": MAIN_STORE, "suffix": "-holdout", "flags": "--holdout-runs", "genera_flag": ""},
|
||||
"core_clade": {"stage": "robustness", "store": MAIN_STORE, "suffix": "-core", "flags": "", "genera_flag": f"--genera {_CG}"},
|
||||
"bacillus_group": {"stage": "robustness", "store": MAIN_STORE, "suffix": "-bacgrp", "flags": "", "genera_flag": f"--genera {_AG}"},
|
||||
}
|
||||
|
||||
|
||||
def train_spec(w):
|
||||
return TRAIN_TAG_SPECS[w.tag]
|
||||
|
||||
|
||||
def train_run_id(w):
|
||||
spec = train_spec(w)
|
||||
if w.tag == "core_clade":
|
||||
n = len(config["core_clade_genera"])
|
||||
elif w.tag == "bacillus_group":
|
||||
n = len(config["bacillus_group_genera"])
|
||||
else:
|
||||
n = N_CLASSES
|
||||
return f"{w.arch}_{fmt_budget(w.budget)}_s{w.stride}_g{n}{spec['suffix']}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# labels + signal stores
|
||||
# ---------------------------------------------------------------------------
|
||||
wildcard_constraints:
|
||||
dataset="nomiss|trap",
|
||||
tag=r"ladder|control|windows4|holdout|core_clade|bacillus_group",
|
||||
arch="cnn|linatt",
|
||||
budget=r"\d+",
|
||||
stride=r"4|8",
|
||||
model="hac|fast"
|
||||
|
||||
rule prepare_read_labels:
|
||||
input:
|
||||
bamfile="../data/aligned_reads/{model}_to_genome.sorted.bam",
|
||||
reference="../data/reference_genomes/full_reference.fasta"
|
||||
bamfile="../data/aligned_reads/{dataset}_{model}_to_genome.bam",
|
||||
reference="../data/reference_genomes/full_reference.fasta",
|
||||
output:
|
||||
'../data/ml_inputs/{model}_label_store.pq'
|
||||
conda:
|
||||
'../envs/bam2parquet.yaml'
|
||||
threads:
|
||||
1
|
||||
"../data/ml_inputs/{dataset}_{model}_label_store.pq",
|
||||
threads: 4
|
||||
conda: "../envs/bam2parquet.yaml"
|
||||
script:
|
||||
'../scripts/bam2annotation.py'
|
||||
"../scripts/bam2annotation.py"
|
||||
|
||||
rule build_data_store:
|
||||
input:
|
||||
pod5=expand('../data/raw_pod5/{{model}}/PBK98658_853a956f_57f83f46_{batch}.pod5',batch=range(1,config["pod5_dataset_size"]+1,config["pod5_stride"])),
|
||||
labels='../data/ml_inputs/{model}_label_store.pq'
|
||||
pod5=dataset_pod5_list,
|
||||
labels="../data/ml_inputs/{dataset}_{model}_label_store.pq",
|
||||
output:
|
||||
directory('../data/ml_inputs/{model}_data_store')
|
||||
conda:
|
||||
config["torch_env"]
|
||||
directory("../data/ml_inputs/{dataset}_{model}_data_store"),
|
||||
params:
|
||||
wpr=1,
|
||||
excludes=store_exclude_flags,
|
||||
threads: 4
|
||||
conda: config["torch_env"]
|
||||
shell:
|
||||
"""
|
||||
python -m custom_models store\
|
||||
--out {output}\
|
||||
--pod5 {input.pod5}\
|
||||
--labels {input.labels}\
|
||||
--reads-per-genus {config[reads_per_genus]}
|
||||
python -m custom_models store \
|
||||
--out {output} \
|
||||
--pod5 {input.pod5} \
|
||||
--labels {input.labels} \
|
||||
--max-windows-per-read {params.wpr} \
|
||||
{params.excludes}
|
||||
"""
|
||||
|
||||
rule train_model:
|
||||
rule build_store_windows_ablation:
|
||||
input:
|
||||
data_store='../data/ml_inputs/{model}_data_store'
|
||||
pod5=nomiss_pod5_list,
|
||||
labels=f"../data/ml_inputs/nomiss_{MODEL_LABELS}_label_store.pq",
|
||||
output:
|
||||
directory('../data/ml_models/run_{arch}_{params}_{stride}_{embed}_{heads}')
|
||||
conda:
|
||||
config["torch_env"]
|
||||
directory(W4_STORE),
|
||||
params:
|
||||
wpr=config["max_windows_per_read"],
|
||||
excludes=nomiss_store_excludes,
|
||||
threads: 4
|
||||
conda: config["torch_env"]
|
||||
shell:
|
||||
"""
|
||||
python -m custom_models train\
|
||||
--arch {wildcards.arch}\
|
||||
--budget {wildcards.params}\
|
||||
--stride {wildcards.stride}\
|
||||
--d-embed {wildcards.embed}\
|
||||
--n-heads {wildcards.heads}\
|
||||
--budget-tol {config[budget_tolerance]}\
|
||||
--store {input.store}\
|
||||
--out-dir {output}\
|
||||
--run-id {wildcards.arch}_{wildcards.params}_s{wildcards.stride}_g{wildcards.classes}\
|
||||
--stage ladder_point\
|
||||
--seed {config[seed]}
|
||||
python -m custom_models store \
|
||||
--out {output} \
|
||||
--pod5 {input.pod5} \
|
||||
--labels {input.labels} \
|
||||
--max-windows-per-read {params.wpr} \
|
||||
{params.excludes}
|
||||
"""
|
||||
|
||||
rule train_control:
|
||||
input:
|
||||
data_store='../data/ml_inputs/{model}_data_store'
|
||||
output:
|
||||
directory('../data/ml_models/control_run__{model}')
|
||||
conda:
|
||||
config["torch_env"]
|
||||
shell:
|
||||
"""
|
||||
python -m custom_models train\
|
||||
--stage control
|
||||
|
||||
"""
|
||||
# ---------------------------------------------------------------------------
|
||||
# training (Stage-A ladder, control, Stage-B variants)
|
||||
# ---------------------------------------------------------------------------
|
||||
rule train_probe:
|
||||
input:
|
||||
store=lambda w: train_spec(w)["store"],
|
||||
output:
|
||||
# run-dir marker files (the CLI writes config/ckpt/history inside the
|
||||
# run dir); further files (report/test_split) are produced by test_probe
|
||||
config=f"{RUNS_DIR}/{{tag}}/{{arch}}_{{budget}}_{{stride}}/config.json",
|
||||
ckpt=f"{RUNS_DIR}/{{tag}}/{{arch}}_{{budget}}_{{stride}}/ckpt.pt",
|
||||
history=f"{RUNS_DIR}/{{tag}}/{{arch}}_{{budget}}_{{stride}}/history.parquet",
|
||||
params:
|
||||
run_dir=lambda w: f"{RUNS_DIR}/{w.tag}/{w.arch}_{w.budget}_{w.stride}",
|
||||
run_id=train_run_id,
|
||||
stage=lambda w: train_spec(w)["stage"],
|
||||
flags=lambda w: train_spec(w)["flags"],
|
||||
genera_flag=lambda w: train_spec(w)["genera_flag"],
|
||||
threads: 8
|
||||
resources:
|
||||
gpu=1
|
||||
conda: config["torch_env"]
|
||||
shell:
|
||||
"""
|
||||
python -m custom_models train \
|
||||
--arch {wildcards.arch} \
|
||||
--budget {wildcards.budget} \
|
||||
--stride {wildcards.stride} \
|
||||
--budget-tol {config[budget_tolerance]} \
|
||||
{params.flags} {params.genera_flag} \
|
||||
--store {input.store} \
|
||||
--out-dir {params.run_dir} \
|
||||
--run-id {params.run_id} \
|
||||
--stage {params.stage} \
|
||||
--seed {config[seed]}
|
||||
"""
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# evaluation: val-calibrated tau + test artifacts + trap eval (TP2)
|
||||
# ---------------------------------------------------------------------------
|
||||
rule test_probe:
|
||||
input:
|
||||
ckpt=f"{RUNS_DIR}/{{tag}}/{{arch}}_{{budget}}_{{stride}}/ckpt.pt",
|
||||
trap_store=TRAP_STORE,
|
||||
output:
|
||||
report=f"{RUNS_DIR}/{{tag}}/{{arch}}_{{budget}}_{{stride}}/report.json",
|
||||
test_split=f"{RUNS_DIR}/{{tag}}/{{arch}}_{{budget}}_{{stride}}/test_split.parquet",
|
||||
params:
|
||||
run_dir=lambda w: f"{RUNS_DIR}/{w.tag}/{w.arch}_{w.budget}_{w.stride}",
|
||||
threads: 8
|
||||
resources:
|
||||
gpu=1
|
||||
conda: config["torch_env"]
|
||||
shell:
|
||||
"""
|
||||
python -m custom_models test \
|
||||
--run-dir {params.run_dir} \
|
||||
--trap-store {input.trap_store} \
|
||||
--n-boot {config[bootstrap_n]}
|
||||
"""
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# gate (v2 §6): PASS/MARGINAL/MARGINAL-TRAP/FAIL over the g11 runs
|
||||
# ---------------------------------------------------------------------------
|
||||
LADDER_RUNS = expand(
|
||||
f"{RUNS_DIR}/ladder/{{arch}}_{{budget}}_{{stride}}",
|
||||
arch=[str(a) for a in config["ladder"]["arches"]],
|
||||
budget=[str(b) for b in config["ladder"]["budgets"]],
|
||||
stride=[str(s) for s in config["ladder"]["strides"]],
|
||||
)
|
||||
|
||||
GATE_RUN_DIRS = list(LADDER_RUNS)
|
||||
|
||||
CONTROL_RUN_DIR = f"{RUNS_DIR}/control/{config['control']['arch']}_{config['control']['budget']}_{config['control']['stride']}"
|
||||
CONTROL_REPORT = f"{CONTROL_RUN_DIR}/report.json"
|
||||
|
||||
if STAGE_B_READY:
|
||||
if _flag("windows_ablation"):
|
||||
_va = [STAGE_B_BUDGET]
|
||||
if config.get("windows_ablation_secondary_budget"):
|
||||
_va.append(str(config.get("windows_ablation_secondary_budget")))
|
||||
GATE_RUN_DIRS += expand(
|
||||
f"{RUNS_DIR}/windows4/{{arch}}_{{budget}}_{{stride}}",
|
||||
arch=[STAGE_B_ARCH], budget=_va, stride=[STAGE_B_STRIDE],
|
||||
)
|
||||
if _flag("holdout_runs"):
|
||||
GATE_RUN_DIRS.append(f"{RUNS_DIR}/holdout/{STAGE_B_ARCH}_{STAGE_B_BUDGET}_{STAGE_B_STRIDE}")
|
||||
|
||||
|
||||
rule gate_verdict:
|
||||
input:
|
||||
reports=[f"{d}/report.json" for d in GATE_RUN_DIRS],
|
||||
control_report=CONTROL_REPORT,
|
||||
output:
|
||||
f"{RUNS_DIR}/gate_verdict.json",
|
||||
params:
|
||||
runs=" ".join(GATE_RUN_DIRS), # run dirs (config-static)
|
||||
control=CONTROL_RUN_DIR,
|
||||
chance_tol=config["gate_chance_tol"],
|
||||
threads: 1
|
||||
conda: config["torch_env"]
|
||||
shell:
|
||||
"""
|
||||
python -m custom_models gate \
|
||||
--runs {params.runs} \
|
||||
--control {params.control} \
|
||||
--chance-tol {params.chance_tol}
|
||||
"""
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TP1 label-side QC: trap captures counted from the labelled corpus
|
||||
# (trap reads are excluded from training at the store; their count here is
|
||||
# the read-side evidence the v2 doc requires to be reported).
|
||||
# ---------------------------------------------------------------------------
|
||||
rule trap_capture_qc:
|
||||
input:
|
||||
labels="../data/ml_inputs/nomiss_hac_label_store.pq",
|
||||
output:
|
||||
"../data/ml_inputs/nomiss_hac_trap_capture_qc.json",
|
||||
params:
|
||||
trap_genera=config["trap_genera"],
|
||||
threads: 1
|
||||
conda: "../envs/bam2parquet.yaml"
|
||||
script:
|
||||
"../scripts/label_qc.py"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Stage-A target set
|
||||
# ---------------------------------------------------------------------------
|
||||
STAGE_A_TARGETS = (
|
||||
[f"{d}/report.json" for d in LADDER_RUNS]
|
||||
+ [
|
||||
CONTROL_REPORT,
|
||||
f"{RUNS_DIR}/gate_verdict.json",
|
||||
"../data/ml_inputs/nomiss_hac_trap_capture_qc.json",
|
||||
]
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Stage-B target set (only after the Stage-A winner is configured)
|
||||
# ---------------------------------------------------------------------------
|
||||
STAGE_B_TARGETS = []
|
||||
|
||||
if STAGE_B_READY:
|
||||
_sb_run_dir = f"{RUNS_DIR}/ladder/{STAGE_B_ARCH}_{STAGE_B_BUDGET}_{STAGE_B_STRIDE}"
|
||||
_sb_budgets = [STAGE_B_BUDGET]
|
||||
if config.get("windows_ablation_secondary_budget"):
|
||||
_sb_budgets.append(str(config.get("windows_ablation_secondary_budget")))
|
||||
|
||||
if _flag("windows_ablation"):
|
||||
STAGE_B_TARGETS += expand(
|
||||
f"{RUNS_DIR}/windows4/{{arch}}_{{budget}}_{{stride}}/report.json",
|
||||
arch=[STAGE_B_ARCH], budget=_sb_budgets, stride=[STAGE_B_STRIDE],
|
||||
)
|
||||
if _flag("holdout_runs"):
|
||||
STAGE_B_TARGETS.append(
|
||||
f"{RUNS_DIR}/holdout/{STAGE_B_ARCH}_{STAGE_B_BUDGET}_{STAGE_B_STRIDE}/report.json"
|
||||
)
|
||||
if _flag("core_clade"):
|
||||
STAGE_B_TARGETS.append(
|
||||
f"{RUNS_DIR}/core_clade/{STAGE_B_ARCH}_{STAGE_B_BUDGET}_{STAGE_B_STRIDE}/report.json"
|
||||
)
|
||||
if _flag("bacillus_group"):
|
||||
STAGE_B_TARGETS.append(
|
||||
f"{RUNS_DIR}/bacillus_group/{STAGE_B_ARCH}_{STAGE_B_BUDGET}_{STAGE_B_STRIDE}/report.json"
|
||||
)
|
||||
|
||||
# alignment baseline (dorado-fast + minimap2 + LCA) on the identical test set
|
||||
rule baseline_eval:
|
||||
input:
|
||||
test_split=f"{_sb_run_dir}/test_split.parquet",
|
||||
truth_labels="../data/ml_inputs/nomiss_hac_label_store.pq",
|
||||
baseline_labels="../data/ml_inputs/nomiss_fast_label_store.pq",
|
||||
output:
|
||||
f"{_sb_run_dir}/baseline_report.json",
|
||||
params:
|
||||
run_id=f"{STAGE_B_ARCH}_{fmt_budget(STAGE_B_BUDGET)}_s{STAGE_B_STRIDE}_g{N_CLASSES}",
|
||||
threads: 1
|
||||
conda: "../envs/bam2parquet.yaml"
|
||||
script:
|
||||
"../scripts/baseline_eval.py"
|
||||
|
||||
STAGE_B_TARGETS.append(f"{_sb_run_dir}/baseline_report.json")
|
||||
|
||||
Reference in New Issue
Block a user