-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathmain.rs
More file actions
2746 lines (2581 loc) · 96.5 KB
/
Copy pathmain.rs
File metadata and controls
2746 lines (2581 loc) · 96.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::fs::File;
use std::io::{self, BufRead, BufReader, Write};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Instant;
use anyhow::{anyhow, bail, Context, Result};
use clap::{Parser, Subcommand, ValueEnum};
use rosalind::core::MemoryBudget;
use rosalind::genomics::{
compare_callsets, create_bam_writer, estimate_build_working_set, read_vcf_variants,
render_plan_line, sort_bam_deterministic, AlignedRead, BWTAligner, BedIndex, BuildMemoryModel,
CigarOp, CigarOpKind, GenomeIndex, IndexBuildReport, IndexReader, IndexWriter,
};
use rosalind::io::decompress::open_input;
use rosalind::io::fasta::{FastaReader, FastaRecord};
use rosalind::io::fastq::{FastqReader, FastqRecord};
use rosalind::util::rss::peak_rss_bytes;
use rust_htslib::bam::Read as BamRead;
use rust_htslib::bam::{
self, record::Aux, record::Cigar as BamCigar, record::CigarString, record::Record,
};
#[derive(Parser, Debug)]
#[command(
name = "rosalind",
version,
about = "Deterministic low-memory genomics engine with a verifiable memory contract"
)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
/// Align reads against a reference genome and emit SAM records.
Align {
/// Reference genome in FASTA format (only the first record is used).
#[arg(long)]
reference: PathBuf,
/// Reads file in FASTQ format (single-end).
#[arg(long)]
reads: Option<PathBuf>,
/// Reads R1 file in FASTQ format (paired-end).
#[arg(long)]
reads_r1: Option<PathBuf>,
/// Reads R2 file in FASTQ format (paired-end).
#[arg(long)]
reads_r2: Option<PathBuf>,
/// Maximum mismatches permitted when seeding alignments.
#[arg(long, default_value_t = 2)]
max_mismatches: usize,
/// Offset applied to reported reference positions (1-based in SAM).
#[arg(long, default_value_t = 0)]
reference_offset: u32,
/// Output format for the alignment.
#[arg(long, value_enum, default_value_t = OutputFormat::Sam)]
format: OutputFormat,
/// Optional path to write the output (stdout if omitted for SAM).
#[arg(short, long)]
output: Option<PathBuf>,
},
/// Call germline variants from aligned reads (streaming pileup engine +
/// calibrated, abstention-aware genotype-likelihood caller).
Variants {
/// Persisted index (`rosalind index`); calls all contigs, reference from
/// the index. Mutually exclusive with `--reference`.
#[arg(
long,
conflicts_with = "reference",
required_unless_present = "reference"
)]
index: Option<PathBuf>,
/// Reference genome (FASTA) — single-contig path. Mutually exclusive with `--index`.
#[arg(long, required_unless_present = "index")]
reference: Option<PathBuf>,
/// Alignments in SAM or BAM format (coordinate-sorted for `--index`).
#[arg(long)]
alignments: PathBuf,
/// Chromosome name (single-contig `--reference` path only; defaults to the
/// first FASTA record). Not allowed with `--index`.
#[arg(long)]
chrom: Option<String>,
/// Starting offset (0-based) for the reference region (`--reference` only).
#[arg(long, default_value_t = 0)]
region_start: u32,
/// Minimum MAPQ required for a read to be considered.
#[arg(long, default_value_t = 0)]
mapq_threshold: u8,
/// Optional VCF output path (stdout if omitted).
#[arg(short, long)]
output: Option<PathBuf>,
/// Deprecated and ignored.
#[arg(long, default_value_t = 1024, hide = true)]
block_size: usize,
/// Minimum quality threshold for reporting variants.
#[arg(long, default_value_t = 10.0)]
quality_threshold: f32,
/// Declared memory budget (MiB) for the run — records a plan/peak line.
/// With `--enforce` it is honored (exit 3 refuse / exit 4 breach). (`--index` path.)
#[arg(long)]
memory_budget_mb: Option<u64>,
/// Cap the active read set per position (unbiased min-hash downsampling);
/// the bound `plan`/`--enforce` rely on. `0` = uncapped.
#[arg(long, default_value_t = 1000)]
max_depth: u32,
/// Max read length assumed by the pre-run `--enforce` estimate AND enforced
/// at ingest under `--enforce` (a longer read aborts the run).
#[arg(long, default_value_t = 250)]
max_read_len: u32,
/// Honor the budget: refuse up front if predicted peak exceeds it (exit 3),
/// or fail after the run if the realized peak does (exit 4). Requires
/// `--memory-budget-mb` and `--max-depth > 0`.
#[arg(long, default_value_t = false)]
enforce: bool,
/// Where to write the reproducibility receipt. Default: `<output>.manifest.json`
/// for file output, or `./rosalind.variants.manifest.json` for stdout output.
#[arg(long)]
manifest: Option<PathBuf>,
},
/// Stream a bounded, deterministic per-locus FEATURE table (TSV) over a
/// persisted index — the same memory contract as `variants`, but every
/// callable locus is emitted as ML-ready features. Byte-identical run-to-run.
Features {
/// Persisted index (`rosalind index`); features over all contigs.
#[arg(long)]
index: PathBuf,
/// Coordinate-sorted alignments (BAM).
#[arg(long)]
alignments: PathBuf,
/// Minimum MAPQ required for a read to be considered.
#[arg(long, default_value_t = 0)]
mapq_threshold: u8,
/// Declared memory budget (MiB). With `--enforce` it is honored (exit 3/4).
#[arg(long)]
memory_budget_mb: Option<u64>,
/// Active-set depth cap (unbiased downsampling). `0` = uncapped.
#[arg(long, default_value_t = 1000)]
max_depth: u32,
/// Max read length assumed by the `--enforce` estimate and enforced at ingest.
#[arg(long, default_value_t = 250)]
max_read_len: u32,
/// Honor the budget: refuse up front (exit 3) / fail after (exit 4).
#[arg(long, default_value_t = false)]
enforce: bool,
/// Output TSV path (stdout if omitted).
#[arg(short, long)]
output: Option<PathBuf>,
/// Where to write the reproducibility receipt (default: `<output>.manifest.json`).
#[arg(long)]
manifest: Option<PathBuf>,
},
/// Deterministically coordinate-sort a BAM file using bounded memory.
Sort {
/// Input BAM path.
#[arg(long)]
input: PathBuf,
/// Output BAM path.
#[arg(short, long)]
output: PathBuf,
/// Memory budget (MiB) for in-memory sorting chunks.
#[arg(long, default_value_t = 1024)]
memory_mb: usize,
},
/// End-to-end tumor/normal somatic calling (align + sort + call).
Somatic {
/// Reference FASTA (single-contig for now).
#[arg(long)]
reference: PathBuf,
/// Tumor FASTQ reads (single-end).
#[arg(long)]
tumor: Option<PathBuf>,
/// Tumor FASTQ reads R1 (paired-end).
#[arg(long)]
tumor_r1: Option<PathBuf>,
/// Tumor FASTQ reads R2 (paired-end).
#[arg(long)]
tumor_r2: Option<PathBuf>,
/// Normal FASTQ reads (single-end).
#[arg(long)]
normal: Option<PathBuf>,
/// Normal FASTQ reads R1 (paired-end).
#[arg(long)]
normal_r1: Option<PathBuf>,
/// Normal FASTQ reads R2 (paired-end).
#[arg(long)]
normal_r2: Option<PathBuf>,
/// Output VCF path.
#[arg(short, long)]
output: PathBuf,
/// Working directory for intermediate BAMs.
#[arg(long)]
workdir: Option<PathBuf>,
/// Sorting memory budget (MiB).
#[arg(long, default_value_t = 1024)]
memory_mb: usize,
},
/// Compare a called somatic VCF against a truth VCF (optionally masked by BED).
EvalSomatic {
/// Reference FASTA (single contig slice used by the VCFs).
#[arg(long)]
reference: PathBuf,
/// Called VCF path.
#[arg(long)]
calls: PathBuf,
/// Truth VCF path.
#[arg(long)]
truth: PathBuf,
/// Optional BED mask (0-based half-open).
#[arg(long)]
regions: Option<PathBuf>,
},
/// Compare a called germline VCF against a truth VCF (e.g. a GIAB benchmark),
/// optionally masked by a high-confidence BED. Reports precision/recall/F1.
EvalGermline {
/// Reference FASTA (the contigs the VCFs use).
#[arg(long)]
reference: PathBuf,
/// Called VCF path.
#[arg(long)]
calls: PathBuf,
/// Truth VCF path.
#[arg(long)]
truth: PathBuf,
/// Optional high-confidence BED mask (0-based half-open).
#[arg(long)]
regions: Option<PathBuf>,
},
/// Build a reference index once into a portable, memory-mappable artifact.
Index {
/// Reference genome in FASTA (plain or gzip; `-` for stdin). All contigs.
#[arg(long)]
reference: PathBuf,
/// Output path for the index artifact.
#[arg(short, long)]
output: PathBuf,
/// Declared memory budget (MiB) for the build. Records a plan line; does
/// not enforce (enforcement is a later phase).
#[arg(long)]
memory_budget_mb: Option<u64>,
},
/// Locate exact occurrences of a pattern in a prebuilt index (load + query).
Locate {
/// Index artifact built by `rosalind index`.
#[arg(long)]
index: PathBuf,
/// Pattern to locate (ASCII A/C/G/T/N; case-insensitive).
#[arg(long)]
pattern: String,
/// Maximum number of candidate hits to locate.
#[arg(long, default_value_t = 1024)]
max_hits: usize,
},
/// Predict whether a job fits a declared memory budget, before committing.
Plan {
/// Persisted index (`rosalind index`): predict the bounded whole-genome
/// `variants` peak. Mutually exclusive with `--reference`.
#[arg(
long,
conflicts_with = "reference",
required_unless_present = "reference"
)]
index: Option<PathBuf>,
/// Reference FASTA: predict the index BUILD peak (advisory — build is
/// O(reference); Phase D enforces). Mutually exclusive with `--index`.
#[arg(long, required_unless_present = "index")]
reference: Option<PathBuf>,
/// Max active depth assumed for the `variants` working-set bound.
#[arg(long, default_value_t = 1000)]
max_depth: u32,
/// Max read length assumed for the `variants` working-set bound.
#[arg(long, default_value_t = 250)]
max_read_len: u32,
/// Declared memory budget (MiB) to check feasibility against.
#[arg(long)]
budget_mb: Option<u64>,
},
/// Re-check a reproducibility receipt without re-running: re-hash its inputs
/// and outputs and confirm the realized peak landed within the budget.
Verify {
/// Path to a `*.manifest.json` written by a previous run.
#[arg(long)]
manifest: PathBuf,
/// Budget (MiB) to check the recorded peak against (overrides the
/// `memory_budget_mb` recorded in the manifest, if any).
#[arg(long)]
budget_mb: Option<u64>,
},
}
#[derive(Copy, Clone, Debug, ValueEnum, Eq, PartialEq)]
enum OutputFormat {
Sam,
Bam,
}
#[derive(Debug, Clone)]
struct FastqPair {
name: String,
r1: FastqRecord,
r2: FastqRecord,
}
#[derive(Debug)]
enum ResolvedReads {
Single(Vec<FastqRecord>),
Paired(Vec<FastqPair>),
}
struct AlignmentCandidate {
position: usize,
mismatches: usize,
mapq: u8,
is_reverse: bool,
cigar: Vec<CigarOp>,
as_score: i32,
md: String,
}
fn main() -> Result<()> {
let cli = Cli::parse();
match cli.command {
Commands::Align {
reference,
reads,
reads_r1,
reads_r2,
max_mismatches,
reference_offset,
format,
output,
} => run_align(
reference,
reads,
reads_r1,
reads_r2,
max_mismatches,
reference_offset,
format,
output,
)?,
Commands::Variants {
index,
reference,
alignments,
chrom,
region_start,
mapq_threshold,
output,
block_size: _,
quality_threshold,
memory_budget_mb,
max_depth,
max_read_len,
enforce,
manifest,
} => {
if let Some(index) = index {
if chrom.is_some() || region_start != 0 {
bail!("--chrom/--region-start are not valid with --index (the whole index is called)");
}
run_variants_index(
index,
alignments,
mapq_threshold,
output,
quality_threshold,
memory_budget_mb,
max_depth,
max_read_len,
enforce,
manifest,
)?
} else {
let reference = reference.expect("clap guarantees one of --index/--reference");
run_variants(
reference,
alignments,
chrom,
region_start,
mapq_threshold,
output,
1024,
quality_threshold,
)?
}
}
Commands::Features {
index,
alignments,
mapq_threshold,
memory_budget_mb,
max_depth,
max_read_len,
enforce,
output,
manifest,
} => run_features(
index,
alignments,
mapq_threshold,
memory_budget_mb,
max_depth,
max_read_len,
enforce,
output,
manifest,
)?,
Commands::Sort {
input,
output,
memory_mb,
} => {
let bytes = memory_mb.saturating_mul(1024 * 1024).max(1024 * 1024);
sort_bam_deterministic(input, output, bytes).context("sorting BAM failed")?;
}
Commands::Somatic {
reference,
tumor,
tumor_r1,
tumor_r2,
normal,
normal_r1,
normal_r2,
output,
workdir,
memory_mb,
} => {
run_somatic(
reference, tumor, tumor_r1, tumor_r2, normal, normal_r1, normal_r2, output,
workdir, memory_mb,
)?;
}
Commands::EvalSomatic {
reference,
calls,
truth,
regions,
} => {
run_eval(reference, calls, truth, regions)?;
}
Commands::EvalGermline {
reference,
calls,
truth,
regions,
} => {
run_eval(reference, calls, truth, regions)?;
}
Commands::Index {
reference,
output,
memory_budget_mb,
} => run_index(reference, output, memory_budget_mb)?,
Commands::Locate {
index,
pattern,
max_hits,
} => run_locate(index, pattern, max_hits)?,
Commands::Plan {
index,
reference,
max_depth,
max_read_len,
budget_mb,
} => run_plan(index, reference, max_depth, max_read_len, budget_mb)?,
Commands::Verify {
manifest,
budget_mb,
} => run_verify(manifest, budget_mb)?,
}
Ok(())
}
/// Compare a called VCF against a truth VCF over a reference, optionally masked by
/// a BED. VCF-agnostic — used by both `eval-somatic` and `eval-germline` (and the
/// drop-in interface for a real GIAB germline benchmark).
fn run_eval(
reference_path: PathBuf,
calls_path: PathBuf,
truth_path: PathBuf,
regions_path: Option<PathBuf>,
) -> Result<()> {
let references = read_fasta_map(&reference_path)
.with_context(|| format!("failed to read reference from {}", reference_path.display()))?;
let calls_txt = std::fs::read_to_string(&calls_path)
.with_context(|| format!("failed to read calls VCF {}", calls_path.display()))?;
let truth_txt = std::fs::read_to_string(&truth_path)
.with_context(|| format!("failed to read truth VCF {}", truth_path.display()))?;
let calls = read_vcf_variants(&calls_txt)
.with_context(|| format!("failed to parse calls VCF {}", calls_path.display()))?;
let truth = read_vcf_variants(&truth_txt)
.with_context(|| format!("failed to parse truth VCF {}", truth_path.display()))?;
let bed = if let Some(path) = regions_path {
let bed_txt = std::fs::read_to_string(&path)
.with_context(|| format!("failed to read BED {}", path.display()))?;
Some(BedIndex::from_str(&bed_txt).with_context(|| "failed to parse BED")?)
} else {
None
};
let report = compare_callsets(&references, &calls, &truth, bed.as_ref())?;
println!("truth_total={}", report.total_truth);
println!("calls_total={}", report.total_calls);
println!("tp={}", report.true_positive);
println!("fp={}", report.false_positive);
println!("fn={}", report.false_negative);
let (p, r) = (report.precision(), report.recall());
let f1 = if p + r == 0.0 {
0.0
} else {
2.0 * p * r / (p + r)
};
println!("precision={p:.6}");
println!("recall={r:.6}");
println!("f1={f1:.6}");
for (ty, (tp, fp, fn_)) in report.by_type.iter() {
println!("type={:?} tp={} fp={} fn={}", ty, tp, fp, fn_);
}
Ok(())
}
/// Build a multi-contig index from a FASTA and persist it (B3c).
fn run_index(reference: PathBuf, output: PathBuf, memory_budget_mb: Option<u64>) -> Result<()> {
// Read every FASTA record (all contigs) into (name, sequence) pairs.
let fasta_reader = open_input(&reference)
.with_context(|| format!("failed to open reference {}", reference.display()))?;
let records: Vec<FastaRecord> = FastaReader::new(fasta_reader)
.collect::<std::result::Result<Vec<_>, _>>()
.with_context(|| format!("failed to parse FASTA {}", reference.display()))?;
if records.is_empty() {
bail!(
"reference {} contains no FASTA records",
reference.display()
);
}
let total_bp: u64 = records.iter().map(|r| r.sequence.len() as u64).sum();
// Record-only budget plan line, printed BEFORE the build. Never refuses.
if let Some(mb) = memory_budget_mb {
let estimate = estimate_build_working_set(total_bp);
eprintln!("{}", render_plan_line(estimate, MemoryBudget::from_mb(mb)));
}
let named: Vec<(String, Vec<u8>)> = records.into_iter().map(|r| (r.name, r.sequence)).collect();
let index = GenomeIndex::from_named_sequences(&named)
.with_context(|| format!("failed to build index from {}", reference.display()))?;
IndexWriter::create(&output)
.with_context(|| format!("failed to create index file {}", output.display()))?
.write_genome_index(&index)
.with_context(|| format!("failed to write index to {}", output.display()))?;
// Deterministic build receipt → stdout.
let index_bytes = std::fs::metadata(&output)
.with_context(|| format!("failed to stat index file {}", output.display()))?
.len();
let reference_blake3 = *blake3::hash(index.reference()).as_bytes();
let report = IndexBuildReport {
index_path: output.display().to_string(),
contigs: index
.contigs()
.iter()
.map(|c| (c.name.to_string(), c.length))
.collect(),
total_bp,
reference_blake3,
index_bytes,
};
print!("{}", report.render());
// Build receipt: realized peak RSS vs the modeled n-scale SA-IS build memory —
// the D0 measure-first probe. The realized peak is machine-dependent; the
// breakdown + attribution ratio are the analysis payload.
let peak = peak_rss_bytes();
let model = BuildMemoryModel::from_reference_len(total_bp);
let denom = total_bp.max(1);
eprintln!(
"build: realized peak RSS {} MiB ({} B/base) over {} bp",
peak / (1 << 20),
peak / denom,
total_bp
);
eprint!("{}", model.render(total_bp));
let ratio = if peak > 0 {
model.total_bytes as f64 / peak as f64
} else {
0.0
};
eprintln!(
"build: model/realized attribution = {:.2} [{}]",
ratio,
if ratio >= 0.70 {
"CONFIRM ≥0.70"
} else {
"below 0.70"
}
);
Ok(())
}
/// Predict whether a job fits a declared budget, before committing. `--index`
/// predicts the bounded whole-genome `variants` peak (largest contig + active set
/// @ the declared cap, atop the measured process baseline). `--reference`
/// predicts the index build peak (advisory; build is O(reference)).
fn run_plan(
index: Option<PathBuf>,
reference: Option<PathBuf>,
max_depth: u32,
max_read_len: u32,
budget_mb: Option<u64>,
) -> Result<()> {
use rosalind::call::plan::render_variants_plan;
use rosalind::genomics::IndexReader;
if let Some(index_path) = index {
let loaded = IndexReader::open(&index_path)
.with_context(|| format!("failed to open index {}", index_path.display()))?;
let largest = loaded
.contigs()
.iter()
.map(|c| c.length as u64)
.max()
.unwrap_or(0);
// Measure the process baseline now (binary + libs + index mmap header);
// the per-contig reference decode + active set are modeled on top.
let baseline = peak_rss_bytes();
print!(
"{}",
render_variants_plan(largest, max_depth, max_read_len, baseline, budget_mb)
);
} else {
let reference = reference.expect("clap guarantees one of --index/--reference");
let fasta_reader = open_input(&reference)
.with_context(|| format!("failed to open reference {}", reference.display()))?;
let total_bp: u64 = FastaReader::new(fasta_reader)
.collect::<std::result::Result<Vec<_>, _>>()
.with_context(|| format!("failed to parse FASTA {}", reference.display()))?
.iter()
.map(|r| r.sequence.len() as u64)
.sum();
let estimate = estimate_build_working_set(total_bp);
match budget_mb {
Some(mb) => println!("{}", render_plan_line(estimate, MemoryBudget::from_mb(mb))),
None => println!(
"plan: est. build peak ~{} MiB (advisory; build is O(reference)) [no budget]",
estimate.bytes / (1 << 20)
),
}
}
Ok(())
}
/// Re-check a reproducibility receipt without re-running: parse it, re-hash each
/// listed input/output and confirm the digests match, and confirm the recorded
/// realized peak RSS landed within the budget (supplied, or recorded in the
/// manifest). Exits non-zero with a per-check report on any mismatch.
fn run_verify(manifest_path: PathBuf, budget_mb: Option<u64>) -> Result<()> {
use rosalind::provenance::{blake3_file, RunManifest};
let text = std::fs::read_to_string(&manifest_path)
.with_context(|| format!("failed to read manifest {}", manifest_path.display()))?;
let manifest = RunManifest::from_canonical_json(&text)
.map_err(|e| anyhow!("failed to parse manifest {}: {e}", manifest_path.display()))?;
let mut problems: Vec<String> = Vec::new();
// Re-hash inputs + outputs against the recorded digests.
for (kind, files) in [("input", &manifest.inputs), ("output", &manifest.outputs)] {
for f in files {
match blake3_file(std::path::Path::new(&f.path)) {
Ok(h) if h == f.blake3 => {}
Ok(h) => problems.push(format!(
"{kind} {} hash mismatch: recorded {}, now {}",
f.path, f.blake3, h
)),
Err(e) => problems.push(format!("{kind} {} unreadable: {e}", f.path)),
}
}
}
// Re-check the recorded realized peak against the budget (CLI overrides manifest).
let budget_mb = budget_mb.or_else(|| {
manifest
.params
.get("memory_budget_mb")
.and_then(|v| v.parse::<u64>().ok())
});
match (
budget_mb,
manifest
.params
.get("peak_rss_bytes")
.and_then(|v| v.parse::<u64>().ok()),
) {
(Some(mb), Some(peak)) => {
let budget = rosalind::core::MemoryBudget::from_mb(mb);
if budget.admits(peak) {
println!(
"verify: peak {} MiB within budget {mb} MiB",
peak / (1 << 20)
);
} else {
problems.push(format!(
"recorded peak {} MiB exceeded budget {mb} MiB",
peak / (1 << 20)
));
}
}
(None, _) => println!("verify: no budget to check (none supplied or recorded)"),
(Some(_), None) => problems.push("manifest has no recorded peak_rss_bytes".to_string()),
}
if problems.is_empty() {
println!(
"verify: OK — {} input(s), {} output(s) match",
manifest.inputs.len(),
manifest.outputs.len()
);
Ok(())
} else {
for p in &problems {
eprintln!("verify: FAIL — {p}");
}
std::process::exit(5);
}
}
/// Load a prebuilt index and print exact-match loci for `pattern` (B3c). This is
/// a memory-mapped load + exact match — it never rebuilds the index.
fn run_locate(index: PathBuf, pattern: String, max_hits: usize) -> Result<()> {
let loaded = IndexReader::open(&index)
.with_context(|| format!("failed to open index {}", index.display()))?;
let view = loaded
.genome_view()
.with_context(|| format!("failed to view index {}", index.display()))?;
let loci = view.locate_exact(pattern.as_bytes(), max_hits);
if loci.is_empty() {
eprintln!("no hits");
return Ok(());
}
let mut stdout = io::BufWriter::new(io::stdout().lock());
for locus in loci {
let name = view
.contigs()
.by_id(locus.contig)
.map(|c| c.name.to_string())
.unwrap_or_else(|| locus.contig.to_string());
writeln!(stdout, "{name}\t{}", locus.pos.0)?;
}
stdout.flush()?;
Ok(())
}
fn run_somatic(
reference_path: PathBuf,
tumor_fastq: Option<PathBuf>,
tumor_r1: Option<PathBuf>,
tumor_r2: Option<PathBuf>,
normal_fastq: Option<PathBuf>,
normal_r1: Option<PathBuf>,
normal_r2: Option<PathBuf>,
output_vcf: PathBuf,
workdir: Option<PathBuf>,
memory_mb: usize,
) -> Result<()> {
let start_total = Instant::now();
let fasta = read_fasta(&reference_path)
.with_context(|| format!("failed to read reference from {}", reference_path.display()))?;
let reference: Arc<[u8]> = Arc::from(fasta.sequence.clone().into_boxed_slice());
let workdir = workdir.unwrap_or_else(|| {
output_vcf
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| PathBuf::from("."))
});
std::fs::create_dir_all(&workdir)
.with_context(|| format!("failed to create workdir {}", workdir.display()))?;
let tumor_bam = workdir.join("tumor.bam");
let tumor_sorted = workdir.join("tumor.sorted.bam");
let normal_bam = workdir.join("normal.bam");
let normal_sorted = workdir.join("normal.sorted.bam");
// Align tumor reads.
let start_align_tumor = Instant::now();
{
let mut writer =
create_bam_writer(&tumor_bam, fasta.name.as_str(), fasta.sequence.len())
.with_context(|| format!("failed to create tumor BAM {}", tumor_bam.display()))?;
let mut aligner = BWTAligner::new(&reference)?;
match resolve_reads(
tumor_fastq.clone(),
tumor_r1.clone(),
tumor_r2.clone(),
"tumor",
)? {
ResolvedReads::Single(reads) => {
let alignments = align_reads(&mut aligner, &reads, 10)?;
write_bam_alignments(&mut writer, 0, &reads, &alignments)?;
}
ResolvedReads::Paired(pairs) => {
let alignments = align_pairs(&mut aligner, &pairs, 10)?;
write_bam_alignments_paired(&mut writer, 0, &pairs, &alignments)?;
}
}
}
let dur_align_tumor = start_align_tumor.elapsed();
// Align normal reads.
let start_align_normal = Instant::now();
{
let mut writer = create_bam_writer(&normal_bam, fasta.name.as_str(), fasta.sequence.len())
.with_context(|| format!("failed to create normal BAM {}", normal_bam.display()))?;
let mut aligner = BWTAligner::new(&reference)?;
match resolve_reads(
normal_fastq.clone(),
normal_r1.clone(),
normal_r2.clone(),
"normal",
)? {
ResolvedReads::Single(reads) => {
let alignments = align_reads(&mut aligner, &reads, 10)?;
write_bam_alignments(&mut writer, 0, &reads, &alignments)?;
}
ResolvedReads::Paired(pairs) => {
let alignments = align_pairs(&mut aligner, &pairs, 10)?;
write_bam_alignments_paired(&mut writer, 0, &pairs, &alignments)?;
}
}
}
let dur_align_normal = start_align_normal.elapsed();
// Sort BAMs deterministically.
let start_sort = Instant::now();
let bytes = memory_mb.saturating_mul(1024 * 1024).max(1024 * 1024);
sort_bam_deterministic(&tumor_bam, &tumor_sorted, bytes)?;
sort_bam_deterministic(&normal_bam, &normal_sorted, bytes)?;
let dur_sort = start_sort.elapsed();
// Call somatic SNVs on the new engine (indels deferred to Phase C).
use rosalind::call::{call_somatic_region, SomaticParams};
use rosalind::core::ContigSet;
use rosalind::io::bam::BamSource;
use rosalind::io::vcf::write_somatic_vcf;
use rosalind::pileup::PileupParams;
use rosalind::provenance::{blake3_file, write_manifest, FileHash, RunManifest};
let start_call = Instant::now();
let mut contigs = ContigSet::new();
let contig_id = contigs.push(fasta.name.clone(), reference.len() as u32);
let region = 0..(reference.len() as u32);
let tumor_src = BamSource::new(&tumor_sorted, &contigs)
.map_err(|e| anyhow!("failed to read tumor BAM {}: {e}", tumor_sorted.display()))?;
let normal_src = BamSource::new(&normal_sorted, &contigs)
.map_err(|e| anyhow!("failed to read normal BAM {}: {e}", normal_sorted.display()))?;
let calls = call_somatic_region(
tumor_src,
normal_src,
Arc::clone(&reference),
contig_id,
region,
PileupParams::default(),
&SomaticParams::default(),
)
.map_err(|e| anyhow!("somatic calling failed: {e}"))?;
let dur_call = start_call.elapsed();
// Write spec-valid somatic VCF (TUMOR/NORMAL).
{
let file = File::create(&output_vcf)
.with_context(|| format!("failed to create somatic VCF {}", output_vcf.display()))?;
let mut writer = io::BufWriter::new(file);
write_somatic_vcf(&mut writer, &contigs, &calls)?;
writer.flush()?;
}
// Reproducibility receipt (BLAKE3, canonical JSON).
let tumor_inputs: Vec<PathBuf> = match (&tumor_fastq, &tumor_r1, &tumor_r2) {
(Some(p), None, None) => vec![p.clone()],
(None, Some(r1), Some(r2)) => vec![r1.clone(), r2.clone()],
_ => Vec::new(),
};
let normal_inputs: Vec<PathBuf> = match (&normal_fastq, &normal_r1, &normal_r2) {
(Some(p), None, None) => vec![p.clone()],
(None, Some(r1), Some(r2)) => vec![r1.clone(), r2.clone()],
_ => Vec::new(),
};
let mut manifest = RunManifest::new("somatic");
manifest.inputs.push(FileHash {
path: reference_path.display().to_string(),
blake3: blake3_file(&reference_path)?,
});
for p in tumor_inputs.iter().chain(normal_inputs.iter()) {
if p.exists() {
manifest.inputs.push(FileHash {
path: p.display().to_string(),
blake3: blake3_file(p)?,
});
}
}
manifest.outputs.push(FileHash {
path: output_vcf.display().to_string(),
blake3: blake3_file(&output_vcf)?,
});
manifest
.params
.insert("somatic_snv_only".to_string(), "true".to_string());
let manifest_path = write_manifest(&output_vcf, &manifest)?;
eprintln!("wrote reproducibility receipt: {}", manifest_path.display());
// Performance/RSS report (kept separate from determinism checks).
let perf_path = workdir.join("somatic.perf.txt");
let mut f = io::BufWriter::new(
File::create(&perf_path)
.with_context(|| format!("failed to create perf report {}", perf_path.display()))?,
);
writeln!(f, "align_tumor_ms={}", dur_align_tumor.as_millis())?;
writeln!(f, "align_normal_ms={}", dur_align_normal.as_millis())?;
writeln!(f, "sort_ms={}", dur_sort.as_millis())?;
writeln!(f, "call_ms={}", dur_call.as_millis())?;
writeln!(f, "total_ms={}", start_total.elapsed().as_millis())?;
writeln!(f, "peak_rss_bytes={}", peak_rss_bytes())?;
f.flush()?;
Ok(())
}
fn run_align(
reference_path: PathBuf,
reads_path: Option<PathBuf>,
reads_r1: Option<PathBuf>,
reads_r2: Option<PathBuf>,
max_mismatches: usize,
reference_offset: u32,
format: OutputFormat,
output: Option<PathBuf>,
) -> Result<()> {
let fasta = read_fasta(&reference_path)
.with_context(|| format!("failed to read reference from {}", reference_path.display()))?;
let reads = resolve_reads(reads_path, reads_r1, reads_r2, "reads")
.context("failed to resolve reads inputs")?;
let mut aligner = BWTAligner::new(&fasta.sequence)
.context("failed to initialize the FM-index aligner for the reference")?;
match reads {
ResolvedReads::Single(records) => {
let alignments = align_reads(&mut aligner, &records, max_mismatches)
.context("aligning reads failed")?;
match format {
OutputFormat::Sam => {
if let Some(path) = output {
let file = File::create(&path).with_context(|| {
format!("failed to create SAM file {}", path.display())
})?;
let mut writer = io::BufWriter::new(file);
write_sam_alignments(
&mut writer,
&fasta.name,
fasta.sequence.len(),
reference_offset,
&records,
&alignments,
)?;
} else {
let stdout = io::stdout();
let mut handle = stdout.lock();
write_sam_alignments(
&mut handle,
&fasta.name,
fasta.sequence.len(),
reference_offset,
&records,
&alignments,
)?;
}
}
OutputFormat::Bam => {
let path = output.ok_or_else(|| {
anyhow!("--output <FILE> must be provided when writing BAM output")
})?;
let mut writer = create_bam_writer(&path, &fasta.name, fasta.sequence.len())
.with_context(|| {
format!("failed to create BAM writer for {}", path.display())
})?;
write_bam_alignments(&mut writer, reference_offset, &records, &alignments)?;
}
}