-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSnakefile
5114 lines (4595 loc) · 213 KB
/
Snakefile
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
###########################################################
# Experimental procedure for evaluating Long Read Giraffe #
###########################################################
import parameter_search
import functools
import tempfile
import os
import numpy as np
# Set a default config file. This can be overridden with --configfile.
# See the config file for how to define experiments.
configfile: "lr-config.yaml"
# Where are the input graphs?
#
# For each reference (here "chm13"), this directory must contain:
#
# hprc-v1.1-mc-chm13.d9.gbz
# hprc-v1.1-mc-chm13.d9.dist
#
# Also, it must either be writable, or already contain zipcode and minimizer
# indexes for each set of minimizer indexing parameters (here "k31.w50.W"),
# named like:
#
# hprc-v1.1-mc-chm13.d9.k31.w50.W.withzip.min
# hprc-v1.1-mc-chm13.d9.k31.w50.W.zipcodes
#
# For comparing against old vg versions, it must also ber writable or have a
# non-zipcode-based minimizer index for each graph:
#
# hprc-v1.1-mc-chm13.d9.k31.w50.W.nozip.min
#
# It must also either be writable or contain an unchopped hg and gfa file
# for running GraphAligner, named like:
#
# hprc-v1.1-mc-chm13.unchopped.hg
# hprc-v1.1-mc-chm13.unchopped.gfa
#
# And for haplotype sampling, the full graph (without any .dXX) must be available:
#
# hprc-v1.1-mc-chm13.gbz
#
# A top-level chains only "distance" index will be made if not present:
#
# hprc-v1.1-mc-chm13.tcdist
#
# As will the haplotype sampling indexes:
#
# hprc-v1.1-mc-chm13.ri
# hprc-v1.1-mc-chm13.hapl
#
GRAPHS_DIR = config.get("graphs_dir", None) or "/private/groups/patenlab/anovak/projects/hprc/lr-giraffe/graphs"
#
# For SV calling, we need a truth vcf and a BED file with confident regions
#
# giab6_chm13.vcf.gz
# giab6_chm13.confreg.bed
#
# And a tandem repeat bed for sniffles
# human_chm13v2.0_maskedY_rCRS.trf.bed (from https://raw.githubusercontent.com/PacificBiosciences/pbsv/refs/heads/master/annotations/human_chm13v2.0_maskedY_rCRS.trf.bed)
#
# TODO: For HG001 we might need https://platinum-pedigree-data.s3.amazonaws.com/variants/merged_sv_truthset/GRCh38/merged_hg38.svs.sort.oa.vcf.gz
SV_DATA_DIR = config.get("sv_data_dir", None) or "/private/home/jmonlong/workspace/lreval/data"
# Where are the reads to use?
#
# This directory must have "real" and "sim" subdirectories. Within each, there
# must be a subdirectory for the sequencing technology, and within each of
# those, a subdirectory for the sample.
#
# For real reads, each sample directory must have a ".fq.gz" or ".fastq.gz" file.
# The name of the file must contain the sample name. If the directory is not
# writable, and you want to trim adapters off nanopore reads, there must also
# be a ".trimmed.fq.gz" or ".trimmed.fastq.gz" version of this file, with the
# first 100 and last 10 bases trimmed off. The workflow will generate
# "{basename}.{subset}.fq.gz" files for each subset size in reads ("1k", "1m:,
# etc.) that you want to work with.
#
# For simulated reads, each sample directory must have files
# "{sample}-sim-{tech}-{subset}.gam" for each subset size as a number (100, 1000,
# 1000000, etc.) that you want to work with. If the directory is not writable,
# it must already have abbreviated versions ("1k" or "1m" instead of the full
# number) of the GAM files, and the corresponding extracted ".fq" files.
#
# There can also be a "{sample}-sim-{tech}.{category}.txt" file with the names
# of reads in a gategory (like "centromeric") for analysis of different subsets
# of reads.
#
# Simulated reads should be made with the "make_pbsim_reads.sh" script in this
# repository, or, for paired-end read simulation for Illumina reads:
#
# vg sim -r -n 2500000 -a -s 12345 -p 570 -v 165 -i 0.00029 --multi-position
#
# Using an XG and a GBWT for the target sample-and-reference graph,
# --sample-name with the target sample's name, and the full real read set for
# the training FASTQ.
#
# A fully filled out reads directory might look like:
#.
#├── real
#│ ├── hifi
#│ │ └── HG002
#│ │ ├── HiFi_DC_v1.2_HG002_combined_unshuffled.1k.fq
#│ │ └── HiFi_DC_v1.2_HG002_combined_unshuffled.fq.gz
#│ └── r10
#│ └── HG002
#│ ├── HG002_1_R1041_UL_Guppy_6.3.7_5mc_cg_sup_prom_pass.fastq.gz
#│ ├── HG002_1_R1041_UL_Guppy_6.3.7_5mc_cg_sup_prom_pass.trimmed.fastq.gz
#│ ├── HG002_1_R1041_UL_Guppy_6.3.7_5mc_cg_sup_prom_pass.trimmed.10k.fq.gz
#│ ├── HG002_1_R1041_UL_Guppy_6.3.7_5mc_cg_sup_prom_pass.trimmed.1k.fq.gz
#│ └── HG002_1_R1041_UL_Guppy_6.3.7_5mc_cg_sup_prom_pass.trimmed.1m.fq.gz
#└── sim
# ├── hifi
# │ └── HG002
# │ ├── HG002-sim-hifi.centromeric.txt
# │ ├── HG002-sim-hifi-1000.gam
# │ ├── HG002-sim-hifi-10000.gam
# │ ├── HG002-sim-hifi-1000000.gam
# │ ├── HG002-sim-hifi-10k.fq
# │ ├── HG002-sim-hifi-10k.gam
# │ ├── HG002-sim-hifi-1k.fq
# │ ├── HG002-sim-hifi-1k.gam
# │ ├── HG002-sim-hifi-1m.fq
# │ └── HG002-sim-hifi-1m.gam
# └── r10
# └── HG002
# ├── HG002-sim-r10.centromeric.txt
# ├── HG002-sim-r10-1000.gam
# ├── HG002-sim-r10-10000.gam
# ├── HG002-sim-r10-1000000.gam
# ├── HG002-sim-r10-10k.fq
# ├── HG002-sim-r10-10k.gam
# ├── HG002-sim-r10-1k.fq
# ├── HG002-sim-r10-1k.gam
# ├── HG002-sim-r10-1m.fq
# └── HG002-sim-r10-1m.gam
#
READS_DIR = config.get("reads_dir", None) or "/private/groups/patenlab/anovak/projects/hprc/lr-giraffe/reads"
# Where are the linear reference files?
#
# For each reference name (here "chm13") this directory must contain:
#
# A FASTA file with PanSN-style (CHM13#0#chr1) contig names:
# chm13-pansn.fa
#
# Index files for Minimap2 for each preset (here "hifi", can also be "ont" or "sr", and can be generated from the FASTA):
# chm13-pansn.hifi.mmi
#
# A Winnowmap repetitive kmers file:
# chm13-pansn.repetitive_k15.txt
#
# For the calling references (chm13v2.0 and grch38) we also need a plain .fa
# and .fa.fai without pansn names, and _PAR.bed files with the pseudo-autosomal
# regions.
#
# TODO: Right now these indexes must be manually generated.
#
REFS_DIR = config.get("refs_dir", None) or "/private/groups/patenlab/anovak/projects/hprc/lr-giraffe/references"
# Where are variant call truth set files kept (for when there isn't a handy hosted URL somewhere).
# These are organized by reference and then sample
TRUTH_DIR = config.get("truth_dir", None) or "/private/groups/patenlab/anovak/projects/hprc/lr-giraffe/truth-sets"
# When we "snakemake all_paper_figures", where should the results go?
ALL_OUT_DIR = config.get("all_out_dir", None) or "/private/groups/patenlab/project-lrg"
# What stages does the Giraffe mapper report times for?
STAGES = ["minimizer", "seed", "tree", "fragment", "chain", "align", "winner"]
# What stages does the Giraffe mapper report times for on the non-chainign codepath?
NON_CHAINING_STAGES = ["minimizer", "seed", "cluster", "extend", "align", "pairing", "winner"]
# What aligner and read part combinations does Giraffe report statistics for?
ALIGNER_PARTS = ["wfa_tail", "dozeu_tail", "wfa_middle", "bga_middle"]
# To allow for splitting and variable numbers of output files, we need to know
# the available subset values to generate rules.
KNOWN_SUBSETS = ["100", "1k", "10k", "100k", "1m"]
CHUNK_SIZE = 10000
# For each Slurm partition name, what is its max wall time in minutes?
# TODO: Put this in the config
SLURM_PARTITIONS = [
("short", 60),
("medium", 12 * 60),
("long", 7 * 24 * 60)
]
# How many threads do we want mapping to use?
MAPPER_THREADS=64
# How many threads do we want to use for big mapping jobs?
PARAM_SEARCH = parameter_search.ParameterSearch()
# Where is a large temp directory?
LARGE_TEMP_DIR = config.get("large_temp_dir", "/data/tmp")
#Different phoenix nodes seem to run at different speeds, so we can specify which node to run
#This gets added as a slurm_extra for all the real read runs
REAL_SLURM_EXTRA = config.get("real_slurm_extra", None) or ""
# If set to True, jobs where we care about speed will demand entire nodes.
# If False, they will just use one thread per core.
EXCLUSIVE_TIMING = config.get("exclusive_timing", True)
# Figure out what columns to put in a table comparing all the conditions in an experiment.
# TODO: Make this be per-experiment and let multiple tables be defined
IMPORTANT_STATS_TABLE_COLUMNS=config.get("important_stats_table_columns", ["speed_from_log", "softclipped_or_unmapped", "accuracy", "indel_f1", "snp_f1"])
# What versions of Giraffe should be run with the old, non-zipcode-aware indexes
NON_ZIPCODE_GIRAFFE_VERSIONS = set(config.get("non_zipcode_giraffe_versions")) if "non_zipcode_giraffe_versions" in config else set()
wildcard_constraints:
expname="[^/]+",
refgraphbase="[^/]+?",
reference="chm13|grch38",
# We can have multiple versions of graphs with different modifications and clipping regimes
modifications="(-[^.-]+(.trimmed)?)*",
clipping="\\.d[0-9]+|",
chopping="\\.unchopped|",
trimmedness="\\.trimmed|",
sample=".+(?<!\\.trimmed)",
basename=".+(?<!\\.trimmed)",
subset="([0-9]+[km]?|full)",
category="((not_)?(centromeric))?|",
# We can restrict calling to a small region for testing
region="(|chr21)",
# We use this for an optional separating dot, so we can leave it out if we also leave the field empty
dot="\\.?",
tech="[a-zA-Z0-9]+",
statname="[a-zA-Z0-9_]+(?<!compared)(.mean|.total)?",
statnamex="[a-zA-Z0-9_]+(?<!compared)(.mean|.total)?",
statnamey="[a-zA-Z0-9_]+(?<!compared)(.mean|.total)?",
realness="(real|sim)",
realnessx="(real|sim)",
realnessy="(real|sim)",
def auto_mapping_threads(wildcards):
"""
Choose the number of threads to use map reads, from subset.
"""
number = subset_to_number(wildcards["subset"])
mapping_threads = 0
if number >= 100000:
mapping_threads= MAPPER_THREADS
elif number >= 10000:
mapping_threads= 16
else:
mapping_threads= 8
if wildcards.get("mapper", "").startswith("graphaligner"):
#Graphaligner is really slow so for simulated reads where we don't care about time
#double the number of threads
#At most 128 because it errors with too many threads sometimes
return min(mapping_threads * 2, 128)
else:
return mapping_threads
def auto_mapping_slurm_extra(wildcards):
"""
Determine Slurm extra arguments for a timed, real-read mapping job.
"""
if EXCLUSIVE_TIMING:
return "--exclusive " + REAL_SLURM_EXTRA
else:
return "--threads-per-core 1 " + REAL_SLURM_EXTRA
def auto_mapping_full_cluster_nodes(wildcards):
"""
Determine number of full cluster nodes for a timed, real-read mapping job.
TODO: Is this really used by Slurm?
"""
number = subset_to_number(wildcards["subset"])
if EXCLUSIVE_TIMING:
return 1
else:
return 0
def auto_mapping_memory(wildcards):
"""
Determine the memory to use for Giraffe mapping, in MB, from subset and tech.
"""
thread_count = auto_mapping_threads(wildcards)
base_mb = 60000
if wildcards["tech"] == "illumina":
scale_mb = 200000
elif wildcards["tech"] == "hifi":
scale_mb = 300000
else:
scale_mb = 600000
# Scale down memory with threads
return scale_mb / MAPPER_THREADS * thread_count + base_mb
def choose_partition(minutes):
"""
Get a Slurm partition that can fit a job running for the given number of
minutes, or raise an error.
"""
for name, limit in SLURM_PARTITIONS:
if minutes <= limit:
return name
raise ValueError(f"No Slurm partition accepts jobs that run for {minutes} minutes")
import snakemake
if int(snakemake.__version__.split(".")[0]) >= 8:
# Remote providers have been replaced with storage plugins.
# TODO: test this on Snakemake 8
# TODO: Really depend on snakemake-storage-plugin-http
def remote_or_local(url):
"""
Wrap a URL as a Snakemake "remote file", but pass a local path through.
"""
if url.startswith("https://"):
# Looks like a remote.
return storage.http(url)
else:
return url
def to_local(possibly_remote_file):
"""
Given a result of remote_or_local, turn it into a local filesystem path.
Snakemake must have already downloaded it for us if needed.
"""
# TODO: Do we still have the list problem in Python code with storage
# plugins?
if isinstance(possibly_remote_file, list):
return possibly_remote_file[0]
else:
return possibly_remote_file
else:
# This is for Snakemake 7 and below. Snakemake 8 replaces Snakemake 7
# remote providers with storage plugins, which aren't available in
# Snakemake 7.
# Also, Snakemake remote providers are terrible, and can fail a successful job with something like:
# Error recording metadata for finished job (HTTPSConnectionPool(host='ftp-trace.ncbi.nlm.nih.gov', port=443): Max retries exceeded with url: /ReferenceSamples/giab/release/AshkenazimTrio/HG002_NA24385_son/NISTv4.2.1/GRCh38/HG002_GRCh38_1_22_v4.2.1_benchmark_noinconsistent.bed (Caused by SSLError(SSLEOFError(8, '[SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1007)')))). Please ensure write permissions for the directory /private/home/anovak/workspace/lr-giraffe/.snakemake
# Because for some reason they want to run web requests at the end of a job.
# So we just use a magic local "remote_cache_https" directory
rule remote_cache_https:
output:
"remote_cache_https/{host}/{path}"
wildcard_constraints:
host="[^/]*"
threads: 1
resources:
mem_mb=2000,
runtime=30,
slurm_partition=choose_partition(30)
shell:
"wget https://{wildcards.host}/{wildcards.path} -O {output}"
def remote_or_local(url):
"""
Wrap a URL as a usable Snakemake input, but pass a local path through.
"""
if url.startswith("https://"):
# Looks like a remote.
return "remote_cache_https/" + url[8:]
else:
return url
def to_local(possibly_remote_file):
"""
Given a result of remote_or_local, turn it into a local filesystem path.
Snakemake must have already downloaded it for us if needed.
"""
return possibly_remote_file
def subset_to_number(subset):
"""
Take a subset like 1m or full and turn it into a number.
"""
if subset == "full":
return float("inf")
elif subset.endswith("m"):
multiplier = 1000000
subset = subset[:-1]
elif subset.endswith("k"):
multiplier = 1000
subset = subset[:-1]
else:
multiplier = 1
return int(subset) * multiplier
def repetitive_kmers(wildcards):
"""
Find the Winnowmap repetitive kmers file from a reference.
"""
return os.path.join(REFS_DIR, wildcards["reference"] + "-pansn.repetitive_k15.txt")
def minimap_derivative_mode(wildcards):
"""
Determine the right Minimap2/Winnowmap preset (map-pb, etc.) from minimapmode or tech.
"""
explicit_mode = wildcards.get("minimapmode", None)
if explicit_mode is not None:
return explicit_mode
MODE_BY_TECH = {
"r9": "map-ont",
"r10": "map-ont",
"hifi": "map-pb",
"illumina": "sr" # Only Minimap2 has this one, Winnowmap doesn't.
}
return MODE_BY_TECH[wildcards["tech"]]
def minimap2_index(wildcards):
"""
Find the minimap2 index from reference and tech.
"""
mode_part = minimap_derivative_mode(wildcards)
return os.path.join(REFS_DIR, wildcards["reference"] + "-pansn." + mode_part + ".mmi")
def reference_fasta(wildcards):
"""
Find the linear reference FASTA from a reference.
"""
return os.path.join(REFS_DIR, wildcards["reference"] + "-pansn.fa")
def reference_dict(wildcards):
"""
Find the linear reference FASTA dictionary from a reference.
"""
return reference_fasta(wildcards) + ".dict"
def reference_path_list_callable(wildcards):
"""
Find the path list file for a linear reference that we can actually call on, from reference and region.
We "can't" call on chrY for CHM13 because the one we use in the graphs
isn't the same as the one in CHM13v2.0 where the calling happens.
"""
return reference_fasta(wildcards) + ".paths" + wildcards.get("region", "") + ".callable.txt"
def reference_path_dict_callable(wildcards):
"""
Find the path dict file for a linear reference that we can actually call on, from reference and region.
We need this because when surjecting to a non-base reference we can't infer path lengths from the graph.
"""
return reference_fasta(wildcards) + ".paths" + wildcards.get("region", "") + ".callable.dict"
def reference_prefix(wildcards):
"""
Find the PanSN prefix we need to remove to convert form PanSN names to
non-PanSN names, from reference.
"""
return {
"chm13": "CHM13#0#",
"grch38": "GRCh38#0#"
}[wildcards["reference"]]
def reference_sample(wildcards):
"""
Get the reference as a sample name
"""
return {
"chm13": "CHM13",
"grch38": "GRCh38"
}[wildcards["reference"]]
def calling_reference_fasta(wildcards):
"""
Find the linear reference FASTA with non-PanSN names from a reference (for
interpreting VCFs).
For CHM13, we always use CHM13v2.0 as the calling reference since that's
the one we can get a truth on.
"""
match wildcards["reference"]:
case "chm13":
return os.path.join(REFS_DIR, "chm13v2.0.fa")
case reference:
return os.path.join(REFS_DIR, reference + ".fa")
def calling_reference_fasta_index(wildcards):
"""
Find the index for the linear calling (non-PanSN) reference, from reference.
"""
return calling_reference_fasta(wildcards) + ".fai"
def calling_reference_restrict_bed(wildcards):
"""
Find the BED for the linear calling (non-PanSN) reference region we think we can call on, from reference.
"""
return calling_reference_fasta(wildcards) + ".callable.from." + wildcards["reference"] + ".bed"
def calling_reference_par_bed(wildcards):
"""
Find the BED for the psuedo-autosomal regions of a reference, from reference.
"""
return os.path.splitext(calling_reference_fasta(wildcards))[0] + "_PAR.bed"
def uncallable_contig_regex(wildcards):
"""
Get a grep regex matching a substring in all uncallable contigs in the calling or PanSN reference, from reference.
This will be a regec compatible with non-E grep.
"""
match wildcards["reference"]:
case "chm13":
# TODO: We don't want to try and call on Y on CHM13 because it's
# not the same Y as CHM13v2.0, where the truth set is and where we
# will do the calling.
return "chr[YM]"
case "grch38":
# We don't want to try and call on the _random/Un/EBV contigs that
# probably aren't in the graph at all.
return "chrM\\|.*_random\\|chrUn\\|chrEBV"
case _:
return "chrM"
def haploid_contigs(wildcards):
"""
Get a list of all haploid contigs in a sample, with no prefixes, from sample.
Will be either [] or ["chrX", "chrY"].
"""
XX_SAMPLES = {"HG001"}
XY_SAMPLES = {"HG002"}
if wildcards["sample"] in XX_SAMPLES:
return []
elif wildcards["sample"] in XY_SAMPLES:
return ["chrX", "chrY"]
else:
raise RuntimeError(f"Unknown karyotype for {wildcards['sample']}")
def wdl_cache(wildcards):
"""
Get a WDL workflow step cache directory path from root.
"""
return os.path.join(os.path.abspath("."), wildcards["root"], "miniwdl-cache")
def truth_vcf_url(wildcards):
"""
Find the URL or local file for the variant calling truth VCF, from reference and sample.
"""
if wildcards["sample"] == "HG002":
# These are available online directly
return {
"chm13": "https://ftp-trace.ncbi.nlm.nih.gov/ReferenceSamples/giab/data/AshkenazimTrio/analysis/NIST_HG002_DraftBenchmark_defrabbV0.018-20240716/CHM13v2.0_HG2-T2TQ100-V1.1.vcf.gz",
"grch38": "https://ftp-trace.ncbi.nlm.nih.gov/ReferenceSamples/giab/release/AshkenazimTrio/HG002_NA24385_son/NISTv4.2.1/GRCh38/HG002_GRCh38_1_22_v4.2.1_benchmark.vcf.gz"
}[wildcards["reference"]]
elif wildcards["sample"] == "HG001":
return {
# On CHM13 we don't have a real benchmark set, so we have to use the raw Platinum Pedigree dipcall calls.
"chm13": os.path.join(TRUTH_DIR, wildcards["reference"], wildcards["sample"], wildcards["sample"] + ".dip.vcf.gz"),
# On GRCh38 there's a GIAB truth set
"grch38": "https://ftp-trace.ncbi.nlm.nih.gov/ReferenceSamples/giab/release/NA12878_HG001/NISTv4.2.1/GRCh38/HG001_GRCh38_1_22_v4.2.1_benchmark.vcf.gz"
}[wildcards["reference"]]
else:
raise RuntimeError("Unsupported sample: " + wildcards["sample"])
def truth_vcf_index_url(wildcards):
"""
Find the URL or local file for the variant calling truth VCF index, from reference and sample.
"""
return truth_vcf_url(wildcards) + ".tbi"
def truth_bed_url(wildcards):
"""
Find the URL or local file for the variant calling truth high confidence BED, from reference.
If compressed, must end in ".gz".
"""
if wildcards["sample"] == "HG002":
# For HG002, these are available online directly.
return {
"chm13": "https://ftp-trace.ncbi.nlm.nih.gov/ReferenceSamples/giab/data/AshkenazimTrio/analysis/NIST_HG002_DraftBenchmark_defrabbV0.018-20240716/CHM13v2.0_HG2-T2TQ100-V1.1_smvar.benchmark.bed",
"grch38": "https://ftp-trace.ncbi.nlm.nih.gov/ReferenceSamples/giab/release/AshkenazimTrio/HG002_NA24385_son/NISTv4.2.1/GRCh38/HG002_GRCh38_1_22_v4.2.1_benchmark_noinconsistent.bed"
}[wildcards["reference"]]
elif wildcards["sample"] == "HG001":
return {
# TODO: On CHM13 we don't have Platinum Pedigree high-confidence regions, so
# we need to just use the HG002 ones for other samples and hope they're close enough.
"chm13": "https://ftp-trace.ncbi.nlm.nih.gov/ReferenceSamples/giab/data/AshkenazimTrio/analysis/NIST_HG002_DraftBenchmark_defrabbV0.018-20240716/CHM13v2.0_HG2-T2TQ100-V1.1_smvar.benchmark.bed",
# On GRCh38 there's a GIAB truth set
"grch38": "https://ftp-trace.ncbi.nlm.nih.gov/ReferenceSamples/giab/release/NA12878_HG001/NISTv4.2.1/GRCh38/HG001_GRCh38_1_22_v4.2.1_benchmark.bed"
}[wildcards["reference"]]
else:
raise RuntimeError("Unsupported sample: " + wildcards["sample"])
def surjectable_gam(wildcards):
"""
Find a GAM mapped to a graph built on a reference that we can use to
surject to the reference we're interested in.
"""
# TODO: Make similar redirects for the benchmarks!
format_data = dict(wildcards)
return "{root}/aligned/{reference}/{refgraph}/{mapper}/{realness}/{tech}/{sample}{trimmedness}.{subset}.gam".format(**format_data)
def graph_base(wildcards):
"""
Find the base name for a collection of graph files from reference and either refgraph or all of refgraphbase, modifications, and clipping.
For graphs ending in "-sampled" and sampling parameters, autodetects the right haplotype-sampled full graph name to use from tech and sample.
For GraphAligner, selects an unchopped version of the graph based on mapper.
"""
# For membership testing, we need a set of wildcard keys
wc_keys = set(wildcards.keys())
reference = wildcards["reference"]
modifications = []
if "refgraphbase" in wc_keys and "modifications" in wc_keys:
# We already have the reference graph base (hprc-v1.1-mc) and clipping (.d9) and chopping (.unchopped) if allowed cut apart.
refgraphbase = wildcards["refgraphbase"]
modifications.append(wildcards["modifications"])
if "clipping" in wc_keys:
modifications.append(wildcards["clipping"])
if "chopping" in wc_keys:
modifications.append(wildcards["chopping"])
else:
assert "refgraph" in wc_keys, f"No refgraph wildcard in: {wc_keys}"
# We need to handle hprc-v1.1-mc and hprc-v1.1-mc-d9 and hprc-v2.prereease-mc-R2-d32 and hprc-v2.prereease-mc-R2-sampled10d.
# Also probaby primary.
# They need the reference inserted after the -mc. but before the other stuff, and -d32 needs to become .d32.
# And -sampled10d needs to be expanded to say what sample and read set we are haplotype sampling from.
# TODO: If it's not -mc, where would the reference go?
refgraph = wildcards["refgraph"]
parts = refgraph.split("-")
last = parts[-1]
if re.fullmatch("unchopped", last):
# We have a choppedness modifier, which gets a dot.
modifications.append("." + last)
parts.pop()
last = parts[-1]
if re.fullmatch("sampled[0-9]+d?(_[^-]*)?", last):
# We have a generic haplotype sampling flag.
# Autodetect the right haplotype-sampled graph to use.
# We need to convert this into the graph sampled for the right sample.
# Which means we need some info about the sample we are working on.
assert "tech" in wc_keys, "No tech known for haplotype sampling graph " + wildcards["refgraph"]
assert "sample" in wc_keys, "No sample known for haplotype sampling graph " + wildcards["refgraph"]
# TODO: We always sample for the full real trimmed-if-R10 version
# of whatever reads we're going to map, so we can consistently use
# one graph.
sampling_trimmedness = ".trimmed" if wildcards["tech"] == "r10" else ""
modifications.append(f"-{last}-for-real-{wildcards['tech']}-{wildcards['sample']}{sampling_trimmedness}-full")
parts.pop()
elif re.fullmatch("d[0-9]+", last):
# We have a clipping modifier, which gets a dot.
modifications.append("." + last)
parts.pop()
while len(parts) > 3:
# We have more than just the 3-tuple of name, version, algorithm. Take the last thing into modifications.
modifications.append("-" + parts[-1])
parts.pop()
# Now we have all the modifications. Flip them around the right way.
modifications.reverse()
# The first 3 or fewer parts are the graph base name.
refgraphbase = "-".join(parts)
result = os.path.join(GRAPHS_DIR, refgraphbase + "-" + reference + "".join(modifications))
return result
def gbz(wildcards):
"""
Find a graph GBZ file from reference.
"""
return graph_base(wildcards) + ".gbz"
def hg(wildcards):
"""
Find a graph hg file from reference.
"""
return graph_base(wildcards) + ".hg"
def gfa(wildcards):
"""
Find a graph GFA file from reference.
"""
return graph_base(wildcards) + ".gfa"
def snarls(wildcards):
"""
Find a graph snarls file from reference.
"""
return graph_base(wildcards) + ".snarls"
def minimizer_k(wildcards):
"""
Find the minimizer kmer size from mapper.
"""
if wildcards["mapper"].startswith("giraffe"):
# Looks like "giraffe-k31.w50.W-lr-default-noflags".
# So get second part on - and first part of that on . and number-ify it after the k.
return int(wildcards["mapper"].split("-")[1].split(".")[0][1:])
else:
mode = minimap_derivative_mode(wildcards)
match mode:
# See minimap2 man page
case "map-ont":
return 15
case "map-pb":
return 19
case "sr":
return 21
raise RuntimeError("Unimplemented mode: " + mode)
def dist_indexed_graph(wildcards):
"""
Find a GBZ and its dist index from reference.
"""
base = graph_base(wildcards)
return {
"gbz": gbz(wildcards),
"dist": base + ".dist"
}
def indexed_graph(wildcards):
"""
Find an indexed graph and all its indexes from reference and minparams.
Also checks vgversion to see if we need a no-zipcodes index for old vg.
"""
base = graph_base(wildcards)
indexes = dist_indexed_graph(wildcards)
# Some versions of Giraffe can't use zipcodes. But all the Giraffe versions
# we test can use the same distance indexes.
if "vgversion" in dict(wildcards).keys() and wildcards["vgversion"] in NON_ZIPCODE_GIRAFFE_VERSIONS:
# Don't use zipcodes
new_indexes = {
"minfile": base + "." + wildcards["minparams"] + ".nozip.min",
}
else:
# Use zipcodes
new_indexes = {
"minfile": base + "." + wildcards["minparams"] + ".withzip.min",
"zipfile": base + "." + wildcards["minparams"] + ".zipcodes"
}
new_indexes.update(indexes)
return new_indexes
def r_and_snarl_indexed_graph(wildcards):
"""
Find a GBZ and its snarl/distance and ri indexes.
Uses the full distance index if present or the snarls-only one otherwise.
"""
base = graph_base(wildcards)
return {
"gbz": gbz(wildcards),
"ri": base + ".ri",
"snarls": base + ".dist" if os.path.exists(base + ".dist") else base + ".tcdist"
}
def haplotype_indexed_graph(wildcards):
"""
Find a GBZ and its hapl index.
Uses samplingparams to get haplotype sampling subchain length.
Distance and ri indexes are not needed for haplotype sampling.
"""
base = graph_base(wildcards)
subchain_length = get_subchain_length(wildcards)
if subchain_length != 10000:
# If using a non-default subchain length for haplotype sampling we need to put it in the filename.
subchain_length_part = f".subchain{subchain_length}"
else:
subchain_length_part = ""
return {
"gbz": gbz(wildcards),
"hapl": base + subchain_length_part + ".hapl"
}
return result
def base_fastq_gz(wildcards):
"""
Find a full compressed FASTQ for a real sample, based on realness, sample,
tech, and trimmedness.
If an untrimmed version exists and the trimmed version does not, returns
the name of the trimmed version to make.
"""
import glob
full_gz_pattern = os.path.join(READS_DIR, "{realness}/{tech}/{sample}/*{sample}*{trimmedness}.f*q.gz".format(**wildcards))
results = glob.glob(full_gz_pattern)
if wildcards["trimmedness"] != ".trimmed":
# Don't match trimmed files when not trimmed.
results = [r for r in results if ".trimmed" not in r]
# Skip any subset files
subset_regex = re.compile("([0-9]+[km]?|full)")
results = [r for r in results if not subset_regex.fullmatch(r.split(".")[-3])]
# Skip any chunk files
chunk_regex = re.compile("chunk[0-9]*")
results = [r for r in results if not chunk_regex.fullmatch(r.split(".")[-3])]
if len(results) == 0:
# Can't find it
if wildcards["trimmedness"] == ".trimmed":
# Look for an untrimmed version
untrimmed_pattern = os.path.join(READS_DIR, "{realness}/{tech}/{sample}/*{sample}*.f*q.gz".format(**wildcards))
results = glob.glob(untrimmed_pattern)
# Skip any subset files
results = [r for r in results if not subset_regex.fullmatch(r.split(".")[-3])]
if len(results) == 1:
# We can use this untrimmed one to make a trimmed one
without_gz = os.path.splitext(results[0])[0]
without_fq, fq_ext = os.path.splitext(without_gz)
trimmed_base = without_fq + ".trimmed" + fq_ext + ".gz"
return trimmed_base
raise FileNotFoundError(f"No non-chunk, non-subset files found matching {full_gz_pattern}")
elif len(results) > 1:
raise RuntimeError("Multiple non-chunk, non-subset files matched " + full_gz_pattern)
return results[0]
def fastq_finder(wildcards, compressed = False):
"""
Find a FASTQ or compressed FASTQ from realness, tech, sample, trimmedness, and subset.
Works even if there is extra stuff in the name besides sample. Accounts for
being able to make a FASTQ from a GAM.
"""
extra_ext = ".gz" if compressed else ""
#If we chunked the reads, we need to add it. Otherwise there isn't a chunk
readchunk = wildcards.get("readchunk", "")
import glob
fastq_by_sample_pattern = os.path.join(READS_DIR, ("{realness}/{tech}/{sample}/*{sample}*{trimmedness}[._-]{subset}" + readchunk+ ".f*q" + extra_ext).format(**wildcards))
results = glob.glob(fastq_by_sample_pattern)
if wildcards["trimmedness"] != ".trimmed":
# Don't match trimmed files when not trimmed.
results = [r for r in results if ".trimmed" not in r]
if len(results) == 0:
if wildcards["realness"] == "real":
# Make sure there's a full .fq.gz to extract from (i.e. this doesn't raise)
full_file = base_fastq_gz(wildcards)
# And compute the subset name
without_gz = os.path.splitext(full_file)[0]
without_fq = os.path.splitext(without_gz)[0]
return without_fq + (".{subset}" + readchunk+ ".fq" + extra_ext).format(**wildcards)
elif wildcards["realness"] == "sim":
# Assume we can get this FASTQ.
# For simulated reads we assume the right subset GAM is there. We
# don't want to deal with the 1k/1000 difference here.
return os.path.join(READS_DIR, ("{realness}/{tech}/{sample}/{sample}-{realness}-{tech}{trimmedness}-{subset}" + readchunk+ ".fq" + extra_ext).format(**wildcards))
else:
raise FileNotFoundError(f"No files found matching {fastq_by_sample_pattern}")
elif len(results) > 1:
raise AmbiguousRuleException("Multiple files matched " + fastq_by_sample_pattern)
return results[0]
def fastq(wildcards):
"""
Find a FASTQ from realness, tech, sample, trimmedness, and subset.
Works even if there is extra stuff in the name besides sample. Accounts for
being able to make a FASTQ from a GAM.
"""
return fastq_finder(wildcards, compressed=False)
def fastq_gz(wildcards):
"""
Find a compressed FASTQ from realness, tech, sample, trimmedness, and subset.
Works even if there is extra stuff in the name besides sample. Accounts for
being able to make a FASTQ from a GAM.
"""
return fastq_finder(wildcards, compressed=True)
def kmer_counts(wildcards):
"""
Find a compressed FASTQ from realness, tech, sample, trimmedness, and subset, and get the corresponding kmer file name.
"""
result = re.sub("\\.f.*?q.gz$", ".kff", fastq_gz(wildcards))
assert result.endswith(".kff")
return result
def kmer_counts_benchmark(wildcards):
return re.sub(".kff", ".kmer_counting.benchmark", kmer_counts(wildcards))
def mapper_stages(wildcards):
"""
Find the list of mapping stages from mapper.
"""
if wildcards["mapper"].startswith("giraffe"):
parts = wildcards["mapper"].split("-")
assert len(parts) >= 3
# Should be giraffe, then the minimizer parameters, then the parameter preset.
if parts[3] == "default":
# Default mapping preset is non-chaining
return NON_CHAINING_STAGES
else:
return STAGES
else:
return []
def all_experiment_conditions(expname, filter_function=None, debug=False):
"""
Yield dictionaries of all conditions for the given experiment.
The config file should have a dict in "experiments", of which the given
expname should be a key. The value is the experiment dict.
The experiment dict should have a "control" dict, listing names and values
of variables to keep constant.
The experiment dict should have a "vary" dict, listing names and values
lists of variables to vary. All combinations will be generated.
The experiment dict should have a "constrain" list. Each item in the list
is a "pass", which is a list of constraints. Each item in the pass is a
dict of variable names and values (or lists of values). A condition must
match *at least* one of these dicts on *all* values in the dict in order to
survive the pass. And it must survive all passes in order to be run.
If filter_function is provided, only yields conditions that the filter
function is true for.
Yields variable name to value dicts for all passing conditions for the
given experiment.
"""
if "experiments" not in config:
raise RuntimeError(f"No experiments section in configuration; cannot run experiment {expname}")
all_experiments = config["experiments"]
if expname not in all_experiments:
raise RuntimeError(f"Experiment {expname} not in configuration")
exp_dict = all_experiments[expname]
# Make a base dict of all controlled variables.
base_condition = exp_dict.get("control", {})
to_vary = exp_dict.get("vary", {})
constraint_passes = exp_dict.get("constrain", [])
total_conditions = 0
for condition in augmented_with_all(base_condition, to_vary):
# For each combination of independent variables on top of the base condition
# We need to see if this is a combination we want to do
if matches_all_constraint_passes(condition, constraint_passes):
if not filter_function or filter_function(condition):
total_conditions += 1
yield condition
else:
if debug:
print(f"Condition {condition} does not match requested filter function")
else:
if debug:
print(f"Condition {condition} does not match a constraint in some pass")
print(f"Experiment {expname} has {total_conditions} eligible conditions")
def augmented_with_each(base_dict, new_key, possible_values):
"""
Yield copies of base_dict with each value from possible_values under new_key.
"""
for value in sorted(possible_values):
clone = dict(base_dict)
clone[new_key] = value
yield clone