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
+54 -4
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)
@@ -88,4 +135,7 @@ if __name__ == '__main__':
print(f'\t{n_secondary+n_supplementary} non-primary alignments')
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())
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')