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:
Tom Kasper
2026-10-15 19:54:51 +01:00
parent 5e95ea9476
commit 820863a9c7
10 changed files with 858 additions and 212 deletions
+71 -18
View File
@@ -1,30 +1,83 @@
# eDNA_Stream_E01
# eDNA_Stream_E01 — E1 (v2) squiggle-probe experiment
## Scope
- Establish whether squiggle-based taxonomy is feasible on the small computational budget that is available
- Establish whether squiggle-based taxonomy is feasible on the small computational budget that is available.
- Design: `planning/design_docs/preliminary_experiments/E1_v2_eleven_taxa_redesign.md` (+ the dataset / torch-model spec docs).
## Dataset:
- NO-MISS bacterial isolates, v10.4.1 chemistry on PromethION flow cells (https://epi2me.nanoporetech.com/nomiss_96bc_p2i_sup_2026/)
- Downsampling at the pod5 level intended for compute/time reasons -> the full dataset is 293 pod5 / 1.6 TB of raw data
## Experiment (v2)
- Fixed 11-taxa NO-MISS probe (species list in `reference/species_list.yaml`; genus labels with
strain-exact reference assemblies in the panel) + the Escherichia false-positive trap
(Paenibacillus / Aeromonas traps are deferred until read sources exist — `unused_trap_species`).
- Stage A: pod5 download (1-in-12 chunk downsampling) → dorado basecall (HAC, barcodes classified
via `--kit-name SQK-RBK114-96`) → minimap2 → labels parquet → signal store (trap reads excluded
from training) → 12-point arch/param ladder ({cnn, linatt} × {1M, 5M, 20M} × stride {4, 8}) →
shuffled-label control → per-run test evaluation with the trap store (`custom_models test`)
→ gate verdict (`custom_models gate` → `../data/ml_models/gate_verdict.json`).
- Stage B (after picking the Stage-A winner from the ladder `report.json`): windows ablation
(store with `--max-windows-per-read 4`), robustness variants (barcode-level `holdout_runs`,
`core_clade` 8-genera / optional `bacillus_group` restricted trainings) and the alignment
baseline (dorado-fast + minimap2 + LCA) evaluated on the winner's identical test read set.
- TP1 label QC (trap-capture counts) is always produced:
`../data/ml_inputs/nomiss_hac_trap_capture_qc.json`.
## Dependencies:
- dorado >= v 2.0.0
## Dependencies
- dorado >= 2.1 (host binary on PATH; conda envs only carry minimap2 + samtools)
- aws CLI
- conda/mamba (mamba recommended)
- python env with:
- python 3.14
- snakemake
- python-dotenv
- custom-models package: live in a separate repo (`git@git.tk-ai.eu:Tom/eDNA_Stream_E01_custom_models.git`) included here as the `custom_models` git submodule; the workflow pip-installs it from that checkout (see `workflow/envs/torch_*.yaml`)
- python env with: python 3.14, snakemake, python-dotenv
- custom-models package: lives in a separate repo (`git@git.tk-ai.eu:Tom/eDNA_Stream_E01_custom_models.git`)
included here as the `custom_models` git submodule; the workflow pip-installs it from that checkout
(see `workflow/envs/torch_*.yaml`).
- clone with: `git clone --recurse-submodules ...` (or `git submodule update --init` on an existing clone)
- update to a newer version: `git submodule update --remote custom_models`, then commit the new pinned commit
- .env file with NCBI API key -> slightly speeds up reference fasta download
- update to a newer version: `git submodule update --remote custom_models`, then commit the new pin
- `.env` file in `workflow/` with NCBI API key (copy from `.env_example`) — speeds up reference download only
## Running
Development / dry-run (this box, no usable GPU):
## Running:
```bash
cd workflow
snakemake --cores <cores> --resources gpu=<n_gpus> --use-conda
snakemake -n --cores <cores> # stage A only until stage_b_* is configured
```
## Notes:
- Reads aligned to the FP traps by minimap are excluded for training -> esp. the E. coli reads are highly represented and should not be there, but are stable even when only using stringent alignment
Runner system (NVIDIA GPU, host dorado, aws cli):
```bash
cd workflow
snakemake --cores <cores> --resources gpu=<n_gpus> --use-conda \
--config torch_env=../envs/torch_cuda.yaml
```
Stage A runs the ladder + control + tests + gate. Then pick the winner from
`../data/ml_models/ladder/*/report.json` (gate's `gate_verdict.json` picks the best run
automatically) and run Stage B:
```bash
snakemake --cores <cores> --resources gpu=<n_gpus> --use-conda \
--config torch_env=../envs/torch_cuda.yaml \
stage_b_arch=cnn stage_b_budget=5000000 stage_b_stride=4 \
windows_ablation=True holdout_runs=True core_clade=True
```
(Booleans need the `True`/`False` spelling; the values become part of the DAG.)
The ROCm branch (`--config gpu_stack=rocm`, slorado) is kept as a fallback; barcodes are not
classified there, so labels fall back to the dataset name and the holdout variant would rely on a
single source_run.
## Conda envs
- `torch_cpu`/`torch_cuda` — training/inference (probe trainings, store building, test/eval) with the
custom_models package; switch via `--config torch_env=...`
- `minimap` — minimap2 + samtools for the streaming label jobs (dorado stays on the host PATH)
- `bam2parquet` — labels from BAM + TP1 QC + the baseline report (pandas/pyarrow/pysam/biopython)
## Notes
- Reads whose best alignment lands on the trap refs are excluded from the training store
(`--exclude-genus escherichia`), and the DCS control spike-in is `--exclude-ref dcs`ed.
The in-corpus E. coli reads are the trap evidence (TP1) — counted in
`nomiss_hac_trap_capture_qc.json` (they are stable even under stringent alignment).
- Queues for hardware: basecall/label jobs carry `resources gpu=1`, so `--resources gpu=N` keeps at
most N GPU jobs in flight (1 on a single-GPU workstation trains/labels sequentially).
- The probe labels come from the HAC arm; the dorado-*fast* arm is the v2 alignment baseline and
only feeds `baseline_report.json` in Stage B.
+24 -27
View File
@@ -1,3 +1,22 @@
"""E1 (v2) squiggle-probe workflow — eDNA_Stream_E01.
Invoke from `workflow/` (see the repo README). The rule modules are brought
into a single namespace with plain `include:` (Snakemake modules would give
each file its own globals and the ML rules would lose the shared helpers).
Run matrix (E1_v2_eleven_taxa_redesign.md §4.1):
Stage A: data (download pod5 -> basecall+align -> label parquet -> signal
store, incl. the trap store), label-side QC (TP1), the 12-point
arch/param ladder, the shuffled-label control, per-run test
evaluation with the trap store (TP2), and the gate verdict.
Stage B: after the Stage-A winner is picked (report.json of the ladder
runs), rerun with --config stage_b...=... to add the windows
ablation (store with max_windows_per_read=4 when requested), the
robustness variants (holdout_runs / core_clade / bacillus_group)
and the alignment baseline (dorado-fast + minimap2 + LCA) on the
identical test read set of the winner.
"""
import os
from dotenv import load_dotenv
@@ -7,33 +26,11 @@ configfile: "config/main.yaml"
configfile: "config/dependencies.yaml"
configfile: "../reference/species_list.yaml"
module preparation:
snakefile: "rules/preparation.smk"
config: config
include: "rules/preparation.smk"
include: "rules/baseline_pipeline.smk"
include: "rules/ml_pipeline.smk"
module baseline:
snakefile: "rules/baseline_pipeline.smk"
config: config
module ml:
snakefile: 'rules/ml_pipeline.smk'
config: config
# Pulldown
rule all:
default_target: True
input:
#"binaries/datasets",
#f"{config['dorado_model_dir']}/{config['fast_model_name']}",
#f"{config['dorado_model_dir']}/{config['hac_model_name']}",
#'../data/reference_genomes/full_reference.mmi',
#'../data/raw_pod5/'
#'../data/pod5_files_to_pull',
#'../data/basecalled_reads/hac.fastq.gz'
#expand('../data/raw_pod5/PBK98658_853a956f_57f83f46_{batch}.pod5',batch=range(1,config["pod5_dataset_size"]+1,config["pod5_stride"]))
'../data/aligned_reads/nomiss_hac_to_genome.sorted.bam',
'../data/aligned_reads/trap_hac_to_genome.sorted.bam'
#'../data/ml_inputs/hac_label_store.pq'
#'../data/ml_inputs/model_layouts/cnn_512_4_100000_11_4.json'
use rule * from preparation
use rule * from baseline
use rule * from ml
STAGE_A_TARGETS + STAGE_B_TARGETS
+64 -16
View File
@@ -1,28 +1,76 @@
# Hardware: 'cuda' (host dorado) is the runner-system path. This box has no
# usable GPU, so development/dry-runs stay on the torch-cpu env; the runner
# executes the GPU trainings with:
# snakemake ... --config torch_env=../envs/torch_cuda.yaml
gpu_stack: "cuda" # 'cuda' or 'rocm'
torch_env: "../envs/torch_cpu.yaml" # swap to ../envs/torch_cuda.yaml on the runner
tmp_dir: "/tmp"
seed: 0
#gpu
gpu_stack : 'cuda' #'cuda' or 'rocm'
# dorado
# basecalling / labelling (host dorado >= 2.0; conda env only adds minimap2/samtools)
dorado_model_dir: "../dorado_models"
hac_model_name: "dna_r10.4.1_e8.2_400bps_hac@v6.0.0"
hac_benchmarks_file: "../reference/dorado_batchsize_files/rtx4060ti_16gb_hac6.benchmarks" # add path if available
hac_min_q: 9 # empty string or 0 to disable
fast_model_name: "dna_r10.4.1_e8.2_400bps_fast@v5.2.0"
hac_model_name: "dna_r10.4.1_e8.2_400bps_hac@v6.0.0" # probe labels / stores
hac_benchmarks_file: "../reference/dorado_batchsize_files/rtx4060ti_16gb_hac6.benchmarks" # empty to disable
hac_min_q: 9 # "" or 0 to disable
fast_model_name: "dna_r10.4.1_e8.2_400bps_fast@v5.2.0" # v2 alignment baseline
fast_benchmarks_file: "" # add path if available
fast_min_q: 8 # empty string or 0 to disable
fast_min_q: 8 # "" or 0 to disable
minimap_extra: "-N 10" # secondary alignments kept for label-QC visibility
# squiqqle dataset
# dataset wiring
pod5_dataset: "nomiss_96BC_P2I_SUP_2026"
pod5_dataset_size : 293
pod5_stride : 12 # Use 1 in x pod5 files from the ONT NO-MISS dataset to reduce dataset size / compute requirements
pod5_dataset_size: 293 # pod5 chunks in the ONT open-data set
pod5_stride: 12 # pod5-level downsampling (1-in-x chunks)
trap_dataset_size: 1717
trap_pod5_stride: 72
barcoding_kit:
nomiss: "SQK-RBK114-96" # classification during basecaller -> per-read barcode tags
trap: "" # public single-sample E. coli run, no barcoding
# custom ML
torch_env : '../envs/torch_cpu.yaml'
# signal-store building (custom_models ExtractConfig)
store_excludes:
nomiss:
refs: ["dcs"] # ONT DCS spike-in contig (would rack up no-class reads)
genera: ["escherichia"] # in-corpus trap-genus reads (E. coli) -> TP1 positives only, never training data
trap:
refs: ["dcs"]
genera: []
max_windows_per_read: 4 # windows-ablation (A') store; headline store keeps 1
# probe / compute
budget_tolerance: 0.1
reads_per_genus : 5000
bootstrap_n: 10000
gate_chance_tol: 1.5
min_test_windows: 300 # v2 near-clade safety rule
# E1 v2 run matrix (E1_v2_eleven_taxa_redesign.md §4.1)
ladder:
arches: ["cnn", "linatt"]
budgets: [1000000, 5000000, 20000000]
strides: [4, 8]
control: # v2: shuffled-label control = 1M cnn, s4, g11
arch: "cnn"
budget: 1000000
stride: 4
# Stage B: leave empty until the Stage-A winner is picked from the ladder
# reports, then rerun the workflow with e.g.
# snakemake ... --config stage_b_arch=cnn stage_b_budget=5000000 stage_b_stride=4 \
# windows_ablation=True holdout_runs=True core_clade=True
stage_b_arch: ""
stage_b_budget: ""
stage_b_stride: ""
windows_ablation: false
windows_ablation_secondary_budget: "" # optional extra ablation row
holdout_runs: false # barcode-level holdout robustness variant
core_clade: false # 8-genera Pseudomonadota-only training (family-block diagnosis)
bacillus_group: false # optional 3-genera Bacillota-only training
# genus lists as they appear in labels (lowercase, from the panel FASTA headers);
# the 6-way Enterobacteriaceae block inside the core clade is the monopoliser probe
core_clade_genera: [cronobacter, citrobacter, enterobacter, klebsiella, pseudomonas, salmonella, shigella, vibrio]
bacillus_group_genera: [bacillus, listeria, staphylococcus]
# trap genera present as references in the panel (TP1); Paenibacillus/Aeromonas deferred
trap_genera: ["escherichia"]
+1
View File
@@ -2,3 +2,4 @@ channels:
- bioconda
dependencies:
- minimap2
- samtools
+131 -69
View File
@@ -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:
@@ -122,12 +185,10 @@ elif GPU_STACK == 'rocm':
rule concatenate_basecalled_fastq:
input:
expand('../data/basecalled_reads/{{dataset}}/{{model}}/{run}_{batch}.fastq',batch=get_batch_range,run=get_run_name)
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'
"../data/basecalled_reads/{dataset}_{model}.fastq.gz"
threads: 1
wildcard_constraints:
model="hac|fast"
shell:
"""
cat {input} | gzip -c > {output}
@@ -135,28 +196,29 @@ rule concatenate_basecalled_fastq:
rule align_reads_to_reference:
input:
fastq='../data/basecalled_reads/{dataset}_{model}.fastq.gz',
ref='../data/reference_genomes/full_reference.mmi'
fastq="../data/basecalled_reads/{dataset}_{model}.fastq.gz",
ref="../data/reference_genomes/full_reference.mmi"
output:
'../data/aligned_reads/{dataset}_{model}_to_genome.sam'
temp("../data/aligned_reads/{dataset}_{model}_to_genome.sam")
params:
minimap_extra=config["minimap_extra"],
threads: 32
conda:
'../envs/minimap.yaml'
"../envs/minimap.yaml"
shell:
"""
minimap2 -ax map-ont -t {threads} {input.ref} {input.fastq} > {output}
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'
"../data/aligned_reads/{dataset}_{model}_to_genome.sam"
output:
'../data/aligned_reads/{dataset}_{model}_to_genome.sorted.bam'
threads: 32
temp("../data/aligned_reads/{dataset}_{model}_to_genome.bam")
threads: 16
conda:
'../envs/samtools.yaml'
"../envs/samtools.yaml"
shell:
"""
samtools view -b -@ {threads} {input} | samtools sort -@ {threads} > {output}
samtools index -@ {threads} {output}
samtools view -b -@ {threads} {input} > {output}
"""
+339 -33
View File
@@ -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]}
--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 store \
--out {output} \
--pod5 {input.pod5} \
--labels {input.labels} \
--max-windows-per-read {params.wpr} \
{params.excludes}
"""
# ---------------------------------------------------------------------------
# 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.params}\
--budget {wildcards.budget} \
--stride {wildcards.stride} \
--d-embed {wildcards.embed}\
--n-heads {wildcards.heads}\
--budget-tol {config[budget_tolerance]} \
{params.flags} {params.genera_flag} \
--store {input.store} \
--out-dir {output}\
--run-id {wildcards.arch}_{wildcards.params}_s{wildcards.stride}_g{wildcards.classes}\
--stage ladder_point\
--out-dir {params.run_dir} \
--run-id {params.run_id} \
--stage {params.stage} \
--seed {config[seed]}
"""
rule train_control:
# ---------------------------------------------------------------------------
# evaluation: val-calibrated tau + test artifacts + trap eval (TP2)
# ---------------------------------------------------------------------------
rule test_probe:
input:
data_store='../data/ml_inputs/{model}_data_store'
ckpt=f"{RUNS_DIR}/{{tag}}/{{arch}}_{{budget}}_{{stride}}/ckpt.pt",
trap_store=TRAP_STORE,
output:
directory('../data/ml_models/control_run__{model}')
conda:
config["torch_env"]
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 train\
--stage control
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")
+53 -3
View File
@@ -1,18 +1,62 @@
"""Build the labels parquet for one (dataset, model) arm from its merged BAM.
Contract (custom_models store.py LABEL_COLUMNS): one row per read with
read_id / genus / species / ref_name / identity / aligned_len / query_len /
source_run. `source_run` carries the dorado-classified barcode tag
(RG:Z:<...>_barcodeNN from `dorado basecaller --kit-name SQK-RBK114-96 --
emit-sam`); it falls back to the dataset tag for un-barcode flows (the trap
dataset, or the non-CUDA/slorado branch). Downstream consumers:
`custom_models store` (labels -> signal store) and DataConfig.holdout_runs,
which groups reads by source_run (= the v2 barcode-level holdout unit).
"""
import pysam
from Bio import SeqIO
import pandas as pd
from pydantic import BaseModel
class ReferenceMetadata(BaseModel):
ref_id : str
genus : str
species : str
ref_len : int
def _source_run(record, fallback):
"""Derive the read's source_run from its tags.
Args:
record: pysam AlignedSegment
fallback: dataset tag used when no barcode tag is present
Returns:
'barcodeNN' — the substring of the record's tag value starting at
'barcode' — from the RG tag when possible, else from any other Z tag
mentioning a barcode. The fallback dataset tag verifies un-barcode
flow cells (the trap dataset / non-CUDA branch).
"""
candidates = {}
for tag in record.get_tags(with_value_type=True):
key, value_type, value = tag[0], tag[1], tag[2]
if value_type == 'Z' and isinstance(value, str):
idx = value.lower().find('barcode')
if idx != -1:
candidates[key] = value[idx:].split()[0]
for key in ('RG',):
if key in candidates:
return candidates[key]
for value in candidates.values():
return value
return fallback
if __name__ == '__main__':
input_bamfile = snakemake.input[0]
reference_genomes = snakemake.input[1]
output_parquet = snakemake.output[0]
dataset_tag = snakemake.wildcards.dataset
# Get Reference Sequence ID -> Taxonomy mapping
ref_tax_data = {}
@@ -23,12 +67,14 @@ if __name__ == '__main__':
'ref_length' : len(ref.seq)
}
# Open Bamfile for reading
# Open Bamfile for reading (unsorted BAM -> plain iteration, no index needed)
bamfile = pysam.AlignmentFile(input_bamfile,'rb')
# Transcribe Taxonomy from Sequnce ID dict to bam header position list for fast lookup
# Transcribe Taxonomy from Sequence ID dict to bam header position list for fast lookup
ref_data = []
for ref_id in bamfile.header.references:
if ref_id not in ref_tax_data:
raise KeyError(f'reference {ref_id} from BAM header missing in {reference_genomes}')
ref_data.append(
ReferenceMetadata(
ref_id = ref_id,
@@ -45,7 +91,7 @@ if __name__ == '__main__':
n_secondary = 0
n_supplementary = 0
n_primary = 0
for record in bamfile.fetch():
for record in bamfile:
n_records += 1
if record.is_unmapped:
n_unmapped += 1
@@ -77,6 +123,7 @@ if __name__ == '__main__':
'identity' : 1 - (nm_count / qlen),
'aligned_len' : qlen,
'query_len' : rlen,
'source_run' : _source_run(record, dataset_tag),
}
)
df = pd.DataFrame(data)
@@ -89,3 +136,6 @@ if __name__ == '__main__':
print(f'\t{df.shape[0]} alignment records written to disk')
print('Per-Genus counts:')
print(df.groupby('genus').aggregate(n_reads=('read_id','nunique')).reset_index())
if 'source_run' in df.columns:
print('Per-source_run counts:')
print(df.groupby('source_run').aggregate(n_reads=('read_id','nunique')).reset_index())
+78
View File
@@ -0,0 +1,78 @@
"""Alignment baseline on the identical test read set of one run (E1-v2 §4.1).
Inputs: a run's test_split.parquet (exported by `custom_models test`), the
HAC label parquet (the probe's genus truth) and the FAST label parquet (the
dorado-fast + minimap2 + LCA baseline predictions). Reads missing from the
baseline parquet (below its min-qscore / not basecalled) count as failures
while also being reported separately. Writes the baseline report next to
the run's report.json.
"""
import json
import pandas as pd
if __name__ == '__main__':
test_split_path = snakemake.input[0]
truth_labels_path = snakemake.input[1]
baseline_labels_path = snakemake.input[2]
output_path = snakemake.output[0]
run_id = str(snakemake.params.run_id)
test_split = pd.read_parquet(test_split_path)
truth_labels = pd.read_parquet(
truth_labels_path, columns=['read_id', 'genus', 'identity']
).rename(columns={'genus': 'truth_genus', 'identity': 'hac_identity'})
baseline_labels = pd.read_parquet(
baseline_labels_path, columns=['read_id', 'genus', 'identity']
).rename(columns={'genus': 'baseline_genus', 'identity': 'fast_identity'})
# identical read set: probe test reads; missing baseline calls count as failures
df = test_split.merge(truth_labels, on='read_id', how='left')
df = df.merge(baseline_labels, on='read_id', how='left')
n_test = int(df.shape[0])
n_missing = int(df['baseline_genus'].isna().sum())
df['baseline_genus'] = df['baseline_genus'].fillna('<missing>')
per_genus = {}
for genus, group in df.groupby('truth_genus'):
n = int(group.shape[0])
tp = int((group['baseline_genus'] == genus).sum())
per_genus[genus] = {
'n_reads': n,
'n_correct': tp,
'recall': tp / n if n else 0.0,
}
confusion = {}
for (truth, pred), n in df.groupby(['truth_genus', 'baseline_genus']).size().items():
confusion.setdefault(truth, {})[pred] = int(n)
payload = {
'run_id': run_id,
'baseline': 'dorado-fast + minimap2 + LCA (single best-hit genus)',
'n_test_reads': n_test,
'n_missing_baseline_calls': n_missing,
'missing_call_rate': n_missing / n_test if n_test else 0.0,
'closed': {
'recall_micro': (
float(((df['baseline_genus'] == df['truth_genus'])).sum()) / n_test
if n_test else 0.0
),
'recall_macro': float(pd.Series({g: m['recall'] for g, m in per_genus.items()}).mean()),
'per_genus': per_genus,
},
'confusion': confusion,
'fast_identity': {
'mean': float(df['fast_identity'].mean()),
'min': float(df['fast_identity'].min()),
'max': float(df['fast_identity'].max()),
},
}
with open(output_path, 'w') as out:
json.dump(payload, out, indent=2, sort_keys=True)
print(f'baseline report -> {output_path}')
print(f' recall_macro: {payload["closed"]["recall_macro"]:.3f} '
f'(micro {payload["closed"]["recall_micro"]:.3f}, '
f'{n_missing}/{n_test} missing calls counted as failures)')
+51
View File
@@ -0,0 +1,51 @@
"""TP1 label-side QC: trap-capture counts from a labelled corpus.
Any read whose best alignment lands on a trap-genus reference is a *trap
capture* — direct evidence that the labeller itself pulled a read into a
genus that carries no real data in the corpus (v2 §3; expected count 0,
which the in-corpus E. coli barcode reads consciously violate as the trap
source-one pool). Counts/breakdown are reported for the owner review.
"""
import json
import pandas as pd
if __name__ == '__main__':
labels_path = snakemake.input[0]
output_path = snakemake.output[0]
trap_genera = [str(g).lower() for g in snakemake.params.trap_genera]
df = pd.read_parquet(labels_path)
payload = {
'labels_path': str(labels_path),
'n_labelled_reads': int(df.shape[0]),
'n_unique_reads': int(df['read_id'].nunique()),
'per_genus': {
genus: int(n) for genus, n in df.groupby('genus')['read_id'].nunique().items()
},
'trap_expected_captures': 0,
'trap_captures': {},
}
captures = df[df['genus'].isin(trap_genera)]
for genus, group in captures.groupby('genus'):
payload['trap_captures'][genus] = {
'n_reads': int(group['read_id'].nunique()),
'n_source_runs': int(group['source_run'].nunique()),
'per_ref_name': {
ref: int(n) for ref, n in group.groupby('ref_name')['read_id'].nunique().items()
},
'identity': {
'mean': float(group['identity'].mean()),
'min': float(group['identity'].min()),
'max': float(group['identity'].max()),
},
}
with open(output_path, 'w') as out:
json.dump(payload, out, indent=2, sort_keys=True)
print(f'TP1 label QC -> {output_path}')
print(f' labelled reads: {payload["n_labelled_reads"]} ({payload["n_unique_reads"]} unique)')
for genus, stats in payload['trap_captures'].items():
print(f' trap captures {genus}: {stats["n_reads"]} reads over {stats["n_source_runs"]} source runs')