From b53ddf0962d99e2dcdbf5210a4b64846ab6241b0 Mon Sep 17 00:00:00 2001 From: Tom Kasper Date: Fri, 16 Oct 2026 20:05:43 +0100 Subject: [PATCH] Emit per-batch CRAM from dorado's native aligner; drop the merge step --emit-cram (reference FASTA required) shrinks the per-chunk alignment artifacts to roughly half of BAM, and the label job now consumes the per-batch CRAMs directly, so the dataset-sized merged BAM intermediate is gone entirely. pysam opens the CRAMs with reference_filename; the rocm fallback keeps the fastq->minimap2->bam chain and the merged BAM. --- README.md | 9 ++- workflow/rules/baseline_pipeline.smk | 42 ++++------ workflow/rules/ml_pipeline.smk | 17 +++- workflow/scripts/bam2annotation.py | 116 ++++++++++++++------------- 4 files changed, 95 insertions(+), 89 deletions(-) diff --git a/README.md b/README.md index 03b4a66..915f54e 100644 --- a/README.md +++ b/README.md @@ -9,10 +9,11 @@ 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`). + via `--kit-name SQK-RBK114-96`) with native alignment (`--reference` → per-batch CRAM, no merge + step) → 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 diff --git a/workflow/rules/baseline_pipeline.smk b/workflow/rules/baseline_pipeline.smk index c457f90..bc46a3a 100644 --- a/workflow/rules/baseline_pipeline.smk +++ b/workflow/rules/baseline_pipeline.smk @@ -1,16 +1,18 @@ """Data pipeline: pod5 download -> dorado basecall (+ barcode classification, -native alignment via --reference) -> merged BAM per (dataset, model). +native alignment via --reference) -> label-ready alignment artifacts. The 'hac' arm supplies the probe labels (stores); the 'fast' arm is the E1-v2 alignment baseline (dorado-fast + minimap2 + LCA). On CUDA, alignment runs -inside dorado (--reference + --mm2-opts): the external -minimap2-over-SAM pipe was dropped because htslib rejected minimap2's -re-emitted dorado records ("CIGAR and query sequence are of different -length"); dorado's own aligned writer keeps the per-record BC/RG barcode -tags that bam2annotation needs for source_run. Per-batch BAMs are merged -per (dataset, model) with samtools cat. On ROCm (slorado, non-barcode) the -fastq->minimap2->bam chain is kept as the fallback; barcodes are then -unavailable and labels fall back to the dataset name as source_run. +inside dorado (--reference + --mm2-opts) and each pod5 chunk is +written straight to CRAM (space-efficient; no merge step — the label job +consumes the per-batch CRAMs directly, so no dataset-sized intermediate +exists at all). The external minimap2-over-SAM pipe was dropped because +htslib rejected minimap2's re-emitted dorado records ("CIGAR and query +sequence are of different length"); dorado's own aligned writer keeps the +per-record BC/RG barcode tags that bam2annotation needs for source_run. +On ROCm (slorado, non-barcode) the fastq->minimap2->bam chain is kept as +the fallback; barcodes are then unavailable and labels fall back to the +dataset name as source_run. Host prerequisites: dorado on PATH, aws cli, curl; --resources gpu=N serialises the GPU label jobs. @@ -133,9 +135,9 @@ if GPU_STACK == "cuda": input: pod5="../data/raw_pod5/{dataset}/{run}_{batch}.pod5", model=get_model_requirement, - ref="../data/reference_genomes/full_reference.mmi" + ref="../data/reference_genomes/full_reference.fasta" output: - bam=temp("../data/aligned_reads/{dataset}/{model}/{run}_{batch}.bam") + alignments=temp("../data/aligned_reads/{dataset}/{model}/{run}_{batch}.cram") threads: 32 resources: gpu=1 @@ -145,25 +147,9 @@ if GPU_STACK == "cuda": min_q=get_qscore, kit_flag=get_kit_flag, mm2_opts=config["dorado_mm2_opts"], - conda: - "../envs/minimap.yaml" shell: """ - dorado basecaller --models-directory {config[dorado_model_dir]} --emit-sam {params.benchmarking} {params.min_q} {params.kit_flag} --reference {input.ref} --mm2-opts "{params.mm2_opts}" {params.dorado_model} {input.pod5} \ - | samtools view -b -@ {threads} > {output} - """ - - 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} + dorado basecaller --models-directory {config[dorado_model_dir]} --emit-cram {params.benchmarking} {params.min_q} {params.kit_flag} --reference {input.ref} --mm2-opts "{params.mm2_opts}" {params.dorado_model} {input.pod5} > {output} """ elif GPU_STACK == "rocm": diff --git a/workflow/rules/ml_pipeline.smk b/workflow/rules/ml_pipeline.smk index cddab01..7dc429b 100644 --- a/workflow/rules/ml_pipeline.smk +++ b/workflow/rules/ml_pipeline.smk @@ -134,9 +134,24 @@ wildcard_constraints: stride=r"4|8", model="hac|fast" +def label_alignments(w): + """Input function: alignment artifacts feeding the label parquet. + + CUDA branch: the per-batch CRAMs written by dorado's native aligner + (consumed directly, no merge step -> no dataset-sized intermediate). + ROCm fallback: the single merged BAM from the fastq->minimap2 chain. + """ + if GPU_STACK == "cuda": + return [ + f"../data/aligned_reads/{w.dataset}/{w.model}/{run_name(w.dataset)}_{b}.cram" + for b in batch_names(w.dataset) + ] + return f"../data/aligned_reads/{w.dataset}_{w.model}_to_genome.bam" + + rule prepare_read_labels: input: - bamfile="../data/aligned_reads/{dataset}_{model}_to_genome.bam", + alignments=label_alignments, reference="../data/reference_genomes/full_reference.fasta", output: "../data/ml_inputs/{dataset}_{model}_label_store.pq", diff --git a/workflow/scripts/bam2annotation.py b/workflow/scripts/bam2annotation.py index d71dff4..f9b913b 100644 --- a/workflow/scripts/bam2annotation.py +++ b/workflow/scripts/bam2annotation.py @@ -53,8 +53,8 @@ def _source_run(record, fallback): if __name__ == '__main__': - input_bamfile = snakemake.input[0] - reference_genomes = snakemake.input[1] + alignment_paths = [str(p) for p in snakemake.input.alignments] + reference_genomes = snakemake.input.reference output_parquet = snakemake.output[0] dataset_tag = snakemake.wildcards.dataset @@ -67,68 +67,72 @@ if __name__ == '__main__': 'ref_length' : len(ref.seq) } - # Open Bamfile for reading (unsorted BAM -> plain iteration, no index needed) - bamfile = pysam.AlignmentFile(input_bamfile,'rb') - - # 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, - genus = ref_tax_data[ref_id]['genus'], - species = ref_tax_data[ref_id]['species'], - ref_len = ref_tax_data[ref_id]['ref_length'] - ) - ) - - # Parse alignments + # Parse alignments (per-batch CRAMs on the cuda branch, one merged BAM on rocm; + # CRAM decoding needs the reference fasta) data = [] n_records = 0 n_unmapped = 0 n_secondary = 0 n_supplementary = 0 n_primary = 0 - for record in bamfile: - n_records += 1 - if record.is_unmapped: - n_unmapped += 1 - continue - if record.is_secondary: - n_secondary += 1 - continue - if record.is_supplementary: - n_supplementary += 1 - continue - n_primary += 1 - nm_count = -1 - for tag in record.get_tags(): - if tag[0] == 'NM': - nm_count = tag[1] - assert nm_count != -1 - assert isinstance(nm_count,int) - rlen = record.infer_read_length() - assert rlen is not None - qlen = record.infer_query_length() - assert qlen is not None - ref = ref_data[record.reference_id] - data.append( - { - 'read_id' : record.query_name, - 'ref_name' : ref.ref_id, - 'genus' : ref.genus, - 'species' : ref.species, - 'identity' : 1 - (nm_count / qlen), - 'aligned_len' : qlen, - 'query_len' : rlen, - 'source_run' : _source_run(record, dataset_tag), - } - ) + for path in alignment_paths: + if path.endswith('.cram'): + bamfile = pysam.AlignmentFile(path, 'rc', reference_filename=str(reference_genomes)) + else: + bamfile = pysam.AlignmentFile(path, 'rb') + + # 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 alignment header missing in {reference_genomes}') + ref_data.append( + ReferenceMetadata( + ref_id = ref_id, + genus = ref_tax_data[ref_id]['genus'], + species = ref_tax_data[ref_id]['species'], + ref_len = ref_tax_data[ref_id]['ref_length'] + ) + ) + + for record in bamfile: + n_records += 1 + if record.is_unmapped: + n_unmapped += 1 + continue + if record.is_secondary: + n_secondary += 1 + continue + if record.is_supplementary: + n_supplementary += 1 + continue + n_primary += 1 + nm_count = -1 + for tag in record.get_tags(): + if tag[0] == 'NM': + nm_count = tag[1] + assert nm_count != -1 + assert isinstance(nm_count,int) + rlen = record.infer_read_length() + assert rlen is not None + qlen = record.infer_query_length() + assert qlen is not None + ref = ref_data[record.reference_id] + data.append( + { + 'read_id' : record.query_name, + 'ref_name' : ref.ref_id, + 'genus' : ref.genus, + 'species' : ref.species, + 'identity' : 1 - (nm_count / qlen), + 'aligned_len' : qlen, + 'query_len' : rlen, + 'source_run' : _source_run(record, dataset_tag), + } + ) df = pd.DataFrame(data) df.to_parquet(output_parquet,index=False) - print(f'Processed {input_bamfile}:') + print(f'Processed {len(alignment_paths)} alignment file(s): {", ".join(alignment_paths)}') print(f'\t{n_records} alignment records') print(f'\t{n_primary} primary alignments') print(f'\t{n_unmapped} unmapped reads')