-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnakefile
More file actions
2075 lines (1889 loc) · 84.9 KB
/
Copy pathSnakefile
File metadata and controls
2075 lines (1889 loc) · 84.9 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
'''
Author: Delaney K. Sullivan
Aim: A Snakemake workflow to process SWIFT-seq data
'''
import json
import re
import os
import sys
import datetime
import gzip
from os.path import basename, splitext
from pathlib import Path
wildcard_constraints:
chunk="(?:\.part_.*|[^.].*)?" # Permits us to have empty string as a wildcard; disallows leading periods w/ exception of .part_
################################################################################
#Load config.yaml file and other general settings
################################################################################
#Copy config file into logs
v = datetime.datetime.now()
run_date = v.strftime('%Y.%m.%d.')
try:
config_path = config["config_path"]
except:
config_path = 'config.yaml'
configfile: config_path
try:
num_chunks = int(config["num_chunks"])
if num_chunks <= 0:
num_chunks = 1
print("Number of chunks specified:", num_chunks, file=sys.stderr)
except:
num_chunks = 1
print("No valid 'num_chunks' in config file. Defaulting to 1 (no chunking).", file=sys.stderr)
try:
keep_fastq_chunks = config["keep_fastq_chunks"]
if num_chunks > 1 and keep_fastq_chunks:
print("Will keep chunked FASTQ files", file=sys.stderr)
else:
keep_fastq_chunks = False
except:
keep_fastq_chunks = False
try:
chunk_star_alignment = config["chunk_star_alignment"]
if num_chunks > 1 and chunk_star_alignment:
print("Using chunks when performing STAR alignment", file=sys.stderr)
else:
chunk_star_alignment = False
except:
chunk_star_alignment = False
try:
thread_factor = int(config["thread_factor"])
print("Thread factor specified:", num_chunks, file=sys.stderr)
except:
thread_factor = 1
print("No valid 'thread_factor' in config file. Defaulting to 1.", file=sys.stderr)
try:
email = config['email']
except:
print("Won't send email on error")
email = None
try:
samples = os.path.abspath(config["samples"])
print("Using samples file: ", samples, file=sys.stderr)
except:
samples = "./samples.json"
print("Defaulting to samples JSON file: ", samples, file=sys.stderr)
try:
R1_adapter = config["R1_adapter"]
R2_adapter = config["R2_adapter"]
print("Using R1 adapter: ", R1_adapter, file=sys.stderr)
print("Using R2 adapter: ", R2_adapter, file=sys.stderr)
except:
R1_adapter = "AGATCGGAAGAGCACACGTCTGAACTCCAGTCA"
R2_adapter = "AGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGT"
print("Defaulting to R1 adapter: ", R1_adapter, file=sys.stderr)
print("Defaulting to R2 adapter: ", R2_adapter, file=sys.stderr)
try:
splitcode_bID = os.path.abspath(config["bID"])
print("Using splitcode config file: ", splitcode_bID, file=sys.stderr)
except:
splitcode_bID = "config.txt"
print("Defaulting to splitcode file: ", splitcode_bID, file=sys.stderr)
umi_extraction_pattern = "0:0<R1>0:-1,<R1[10]>{adapter},{adapter}<R1[1-65]>,2:0<R2[1-65]>"
try:
if config["umi_extraction_pattern"].strip():
umi_extraction_pattern = config["umi_extraction_pattern"].strip()
print("Using UMI extraction pattern: ", umi_extraction_pattern, file=sys.stderr)
except:
print("Defaulting to UMI extraction pattern: ", umi_extraction_pattern, file=sys.stderr)
try:
tag_prefix_order=config["tag_prefix_order"]
print("Using tag prefix order: ", tag_prefix_order, file=sys.stderr)
except:
tag_prefix_order=""
print("Skipping calculating ligation efficiency", file=sys.stderr)
try:
temp_dir = os.path.abspath(config["temp_dir"])
print("Using temporary directory: ", temp_dir, file=sys.stderr)
except:
temp_dir = "tmp/"
print("Defaulting to temporary directory: ", temp_dir, file=sys.stderr)
try:
subset_n = int(config["subset_n"])
if subset_n > 0:
print("SUBSETTING: ", str(subset_n), " reads", file=sys.stderr)
else:
subset_n = 0
except:
subset_n = 0
try:
fastqs_dir = config["fastqs"]
if not fastqs_dir or fastqs_dir == "./":
fastqs_dir=""
print("Location of FASTQS file is the current directory", file=sys.stderr)
else:
print("Location of FASTQS file: ", temp_dir, file=sys.stderr)
except:
fastqs_dir = ""
print("Default to current directory for location of FASTQS file: ", file=sys.stderr)
try:
align_id = config["align_id"]
print("Alignment ID: ", align_id, file=sys.stderr)
except:
align_id="default"
print("Using default alignment ID", file=sys.stderr)
try:
genome_fasta = config["genome_fasta"]
genome_gtf = config["genome_gtf"]
except:
genome_fasta = ""
genome_gtf = ""
try:
use_features = config["use_features"]
except:
use_Features = False
try:
features_fasta_file = ""
if use_features:
features_fasta_file = config["features_fasta_file"]
if features_fasta_file:
print("Using features: ", features_fasta_file, file=sys.stderr)
else:
use_features = False
except:
use_features = False
try:
features_kmer_length = 0
if use_features:
features_kmer_length = int(config["features_kmer_length"])
if not features_kmer_length or features_kmer_length < 3:
features_kmer_length = 31
print("Invalid features k-mer length supplied, defaulting to ", features_kmer_length, file=sys.stderr)
else:
print("Features k-mer length set to ", features_kmer_length, file=sys.stderr)
except:
if use_features:
features_kmer_length = 31
print("No features k-mer length supplied, defaulting to ", features_kmer_length, file=sys.stderr)
try:
features_start = 0
if use_features:
features_start = int(config["features_start"])
if not features_start or features_start <= 0:
features_start = 0
else:
print("Features start position set to ", features_start, file=sys.stderr)
except:
features_start = 0
try:
features_length = -1
if use_features:
features_length = int(config["features_length"])
if not features_length or features_length <= 0:
features_length = -1
else:
print("Features sequence length set to ", features_length, file=sys.stderr)
except:
features_length = -1
try:
use_vcf_wasp_workflow = config["use_vcf_wasp_workflow"]
if use_vcf_wasp_workflow:
print("Variant-specific mapping (WASP) enabled", file=sys.stderr)
except:
use_vcf_wasp_workflow = False
try:
vcf_file = config["vcf_file"]
print("VCF file: ", vcf_file, file=sys.stderr)
if not use_vcf_wasp_workflow:
print("Not using VCF file", file=sys.stderr)
vcf_file = ""
except:
vcf_file = ""
try:
vcf_s1 = config["vcf_s1"]
vcf_s2 = config["vcf_s2"]
except:
vcf_s1 = ""
vcf_s2 = ""
vcf_s1_ = "REF"
if vcf_file and use_vcf_wasp_workflow:
if vcf_s1:
vcf_s1_ = vcf_s1
print("VCF sample 1: ", vcf_s1_, file=sys.stderr)
if not vcf_s2:
print("Must supply VCF sample 2 for variant-specific mapping workflow", file=sys.stderr)
sys.exit()
else:
print("VCF sample 2: ", vcf_s2, file=sys.stderr)
try:
split_allele_analysis = config["split_allele_analysis"]
if split_allele_analysis and vcf_file and use_vcf_wasp_workflow:
print("Turning on split allele analysis", file=sys.stderr)
else:
split_allele_analysis = False
except:
split_allele_analysis = False
try:
use_exclusion_filter = config["use_exclusion_filter"]
exclusion_fasta_file = ""
if use_exclusion_filter:
exclusion_fasta_file = config["exclusion_fasta_file"]
if exclusion_fasta_file:
print("Enabling exclusion-filtering for reads that align to file: ", exclusion_fasta_file, file=sys.stderr)
else:
use_exclusion_filter = False
except:
use_exclusion_filter = False
exclusion_fasta_file = ""
# STAR settings:
try:
use_star = False
if config["use_star"]:
print("STAR aligner enabled", file=sys.stderr)
use_star=True
except:
use_star = False
try:
star_index = config["star_index"]
except:
star_index = None
if use_star:
if star_index:
star_index = os.path.abspath(star_index)
print("Using provided STAR index: ", star_index, file=sys.stderr)
elif genome_fasta and genome_gtf:
genome_fasta = os.path.abspath(genome_fasta)
genome_gtf = os.path.abspath(genome_gtf)
print("STAR index generation from FASTA and GTF: ", genome_fasta, " ", genome_gtf, file=sys.stderr)
else:
print("Disabling STAR because index not supplied, and FASTA+GTF also not supplied", file=sys.stderr)
use_star = False
try:
star_additional_params = ""
if config["use_star"] and config["star_additional_params"]:
star_additional_params = config["star_additional_params"]
print("STAR aligner set to run with additional parameters: ", star_additional_params, file=sys.stderr)
except:
star_additional_params = ""
# kallisto settings:
try:
use_kallisto = False
if config["use_kallisto"]:
print("kallisto enabled", file=sys.stderr)
use_kallisto=True
except:
use_kallisto = False
try:
kallisto_index = config["kallisto_index"]
kallisto_index_t2g = config["kallisto_index_t2g"]
kallisto_index_c1 = config["kallisto_index_c1"]
kallisto_index_c2 = config["kallisto_index_c2"]
if not (kallisto_index and kallisto_index_t2g and kallisto_index_c1 and kallisto_index_c2):
kallisto_index = None
kallisto_index_t2g = None
kallisto_index_c1 = None
kallisto_index_c2 = None
else:
kallisto_index = os.path.abspath(kallisto_index)
kallisto_index_t2g = os.path.abspath(kallisto_index_t2g)
kallisto_index_c1 = os.path.abspath(kallisto_index_c1)
kallisto_index_c2 = os.path.abspath(kallisto_index_c2)
except:
kallisto_index = None
kallisto_index_t2g = None
kallisto_index_c1 = None
kallisto_index_c2 = None
if use_kallisto:
if kallisto_index:
print("Using provided kallisto index: ", kallisto_index, file=sys.stderr)
print("Using provided kallisto transcripts-to-gene mapping file: ", kallisto_index_t2g, file=sys.stderr)
elif genome_fasta and genome_gtf:
genome_fasta = os.path.abspath(genome_fasta)
genome_gtf = os.path.abspath(genome_gtf)
print("kallisto index generation from FASTA and GTF: ", genome_fasta, " ", genome_gtf, file=sys.stderr)
else:
print("Disabling kallisto because index not supplied, and FASTA+GTF also not supplied", file=sys.stderr)
use_kallisto = False
try:
kallisto_dlist = config["kallisto_dlist"]
if use_kallisto and not kallisto_index:
if kallisto_dlist and kallisto_dlist.upper() == "NONE":
kallisto_dlist = "None"
print("kallisto index d-list disabled", file=sys.stderr)
elif kallisto_dlist:
kallisto_dlist = ','.join([os.path.abspath(x) for x in kallisto_dlist.split(",")]) # Allow multiple files
print("kallisto index d-list set to: ", kallisto_dlist, file=sys.stderr)
else:
kallisto_dlist = genome_fasta
print("kallisto index d-list not provided; defaulting to genome FASTA provided", file=sys.stderr)
except:
kallisto_dlist = None
if use_kallisto and not kallisto_index:
kallisto_dlist = genome_fasta
print("kallisto index d-list not provided; defaulting to genome FASTA provided", file=sys.stderr)
# Other settings:
try:
select_tags = ""
if config["select_tags"]:
select_tags = config["select_tags"]
print("Only including barcodes with the following tags in the final AnnData: ", select_tags, file=sys.stderr)
except:
select_tags = ""
try:
merge_anndata_files = False
if config["merge_anndata"]:
merge_anndata_files = True
print("Outputting a merged anndata object file is enabled", file=sys.stderr)
except:
merge_anndata_files = False
try:
out_dir = config["output_dir"]
print("All data will be written to: ", out_dir, file=sys.stderr)
except:
out_dir = os.getcwd()
print("Defaulting to working directory as output directory", file=sys.stderr)
try:
conda_env = config["conda_env"]
except:
print("No conda environment specified. Defaulting to envs/swiftseq.yaml", file=sys.stderr)
conda_env = "envs/swiftseq.yaml"
if conda_env.lower().endswith(".yaml") or conda_env.lower().endswith(".yml"):
print("Will create new conda environment from", conda_env, file=sys.stderr)
else:
print("Using existing conda environment:", conda_env, file=sys.stderr)
adata_filename="adata.h5ad"
##############################################################################
# Location of scripts
##############################################################################
try:
DIR_SCRIPTS = config["scripts_dir"]
except:
print("Scripts directory not specificed in config.yaml", file=sys.stderr)
sys.exit() # no default, exit
split_fastq = os.path.join(DIR_SCRIPTS, "bash/split_fastq.sh")
ligeff = os.path.join(DIR_SCRIPTS, "bash/ligeff.sh")
merge_ligeff = os.path.join(DIR_SCRIPTS, "python/merge_ligeff.py")
merge_exclusion_stats = os.path.join(DIR_SCRIPTS, "python/merge_exclusion_stats.py")
barcodes_to_ids = os.path.join(DIR_SCRIPTS, "bash/barcodes_to_ids.sh")
prep_anndata = os.path.join(DIR_SCRIPTS, "python/prep_anndata.py")
merge_anndata = os.path.join(DIR_SCRIPTS, "python/merge_anndata.py")
prep_vcf = os.path.join(DIR_SCRIPTS, "python/prep_vcf.py")
decode_barcode = os.path.join(DIR_SCRIPTS, "python/decode_barcode.py")
split_bam_by_snp = os.path.join(DIR_SCRIPTS, "java/SplitBAMBySNP.jar")
html_report_gen = os.path.join(DIR_SCRIPTS, "python/html/report.py")
################################################################################
#make output directories (aren't created automatically on cluster)
################################################################################
DIR_WORKUP = os.path.join(out_dir, "workup")
DIR_LOGS = os.path.join(DIR_WORKUP, "logs")
DIR_LOGS_CLUSTER = os.path.join(DIR_LOGS, "cluster")
os.makedirs(DIR_LOGS_CLUSTER, exist_ok=True)
out_created = os.path.exists(DIR_LOGS_CLUSTER)
print("Output logs path created:", out_created, file=sys.stderr)
DIR_TRIMMED_CLUSTER = os.path.join(DIR_WORKUP, "trimmed", "cluster")
os.makedirs(DIR_TRIMMED_CLUSTER, exist_ok=True)
out_created = os.path.exists(DIR_TRIMMED_CLUSTER)
print("Output trimming path created:", out_created, file=sys.stderr)
################################################################################
#Setup out files
################################################################################
if num_chunks == 1:
# Single chunk => chunk wildcard will be an empty string
CHUNK_LIST = [""]
else:
# Multi-chunk => chunk wildcard has suffixes .part_001, .part_002, etc.
CHUNK_LIST = [f".part_{i:03}" for i in range(0, num_chunks)]
#get all samples from fastq Directory using the fastq2json.py scripts, then just
#load the json file with the samples
FILES = json.load(open(samples))
READS = ["R1", "R2"] # Paired-end reads
ALL_FASTQ = []
pattern = re.compile(r'[ ._]')
# Normalize sample names by removing underscores
normalized_keys = {}
NEW_FILES = {}
for key in FILES.keys():
new_key = key.replace("_", "") # Remove underscores
if new_key in normalized_keys:
print(f"Error: Sample name conflict after removing underscores: '{key}' and '{normalized_keys[new_key]}' both map to '{new_key}'", file=sys.stderr)
sys.exit(1)
normalized_keys[new_key] = key
NEW_FILES[new_key] = FILES[key]
FILES = NEW_FILES
ALL_SAMPLES = sorted(FILES.keys())
if fastqs_dir:
for key in FILES.keys():
FILES[key]["R1"] = [os.path.abspath(os.path.join(fastqs_dir, i)) for i in FILES[key]["R1"]]
FILES[key]["R2"] = [os.path.abspath(os.path.join(fastqs_dir, i)) for i in FILES[key]["R2"]]
invalid_keys = [key for key in FILES.keys() if pattern.search(key)]
if invalid_keys:
print("Error: The following JSON file sample names contain invalid characters (spaces, periods, or underscores):\n" + "\n".join(invalid_keys), file=sys.stderr)
sys.exit()
# Subset FASTQ files if requested by the user (note: these files aren't removed after processing)
if temp_dir and subset_n:
os.makedirs(temp_dir, exist_ok=True)
SUBSET_FILES = {}
def subset_fastq(input_file, output_file, n, buffer_size=100000):
"""Subset a FASTQ file to the first n reads and write to output efficiently."""
is_gz = input_file.endswith('.gz')
open_in = gzip.open if is_gz else open
open_out = lambda f, mode: gzip.open(f, mode, compresslevel=1) if f.endswith('.gz') else open(f, mode)
with open_in(input_file, 'rt') as infile, open_out(output_file, 'wt') as outfile:
buffer = []
read_count = 0
while read_count < n:
lines = [infile.readline() for _ in range(4)] # Read one full read (4 lines)
if not lines[0]: # End of file
break
buffer.extend(lines)
read_count += 1
if len(buffer) >= buffer_size: # Write in chunks to optimize I/O
outfile.writelines(buffer)
buffer = []
if buffer: # Write any remaining data in the buffer
outfile.writelines(buffer)
for SAMPLE, file in FILES.items():
SUBSET_FILES[SAMPLE] = {"R1": [], "R2": []}
for read_type in READS:
for fastq_file in file.get(read_type, []):
subset_fastq_path = os.path.join(temp_dir, "subset" + os.path.basename(fastq_file))
subset_fastq(fastq_file, subset_fastq_path, subset_n)
SUBSET_FILES[SAMPLE][read_type].append(subset_fastq_path)
FILES = SUBSET_FILES # Replace FILES with the subsetted versions
for SAMPLE, file in FILES.items():
ALL_FASTQ.extend(
[i for i in file.get('R1')]
)
ALL_FASTQ.extend(
[i for i in file.get('R2')]
)
def get_fileids(sample):
"""Numbered indices for R1 files in that sample (should be the same as R2)."""
return range(len(FILES[sample]["R1"]))
def get_input_r1(wc):
"""
If wc.chunk == "", return the original R1 file from FILES.
If wc.chunk != "", return a chunk in split_fastq/...
"""
# e.g. original path = data/sampleA_R1.fastq.gz
original = FILES[wc.sample]["R1"][int(wc.fileid)]
if wc.chunk == "":
return original
else:
# chunked file path
return f"split_fastq/{wc.sample}_{wc.fileid}_R1{wc.chunk}.fastq.gz"
def get_input_r2(wc):
"""
Same logic for R2.
"""
original = FILES[wc.sample]["R2"][int(wc.fileid)]
if wc.chunk == "":
return original
else:
return f"split_fastq/{wc.sample}_{wc.fileid}_R2{wc.chunk}.fastq.gz"
# Check if any string in the list of samples has a space
if any(" " in string for string in ALL_SAMPLES):
print("Sample names in json file cannot contain spaces", file=sys.stderr)
sys.exit()
def get_file_count(sample):
return len(FILES[sample]["R1"])
def chunked_fastq_path(sample, fileid, read, chunk):
"""
Final path of chunked FASTQ: e.g. workup/split_fastq/sample_0_R1.part_001.fastq.gz
If chunk="" => workup/split_fastq/sample_0_R1.fastq.gz (no .part_001 suffix).
"""
base = f"{sample}_{fileid}_{read}{chunk}.fastq.gz"
return os.path.join(DIR_WORKUP, "split_fastq", base)
# We create expansions for the final pigz-compressed chunked fastqs for R1 + R2:
SPLIT_FASTQ_GZ = []
for s in ALL_SAMPLES:
for i in range(get_file_count(s)):
# R1 expansions
for c in CHUNK_LIST:
SPLIT_FASTQ_GZ.append(chunked_fastq_path(s, i, "R1", c))
for i in range(get_file_count(s)):
# R2 expansions
for c in CHUNK_LIST:
SPLIT_FASTQ_GZ.append(chunked_fastq_path(s, i, "R2", c))
if num_chunks == 1 or not keep_fastq_chunks:
SPLIT_FASTQ_GZ = []
CONFIG = [os.path.join(DIR_LOGS, "config_" + run_date + "yaml")]
TRIM = [
os.path.join(DIR_WORKUP, "trimmed", f"{sample}_{fileid}_{read}{chunk}.trimmed.fastq.gz")
for sample in ALL_SAMPLES
for fileid in get_fileids(sample)
for read in READS
for chunk in CHUNK_LIST
]
# Function to standardize the output file base name
def standardize_name(fq):
base = os.path.basename(fq)
if base.endswith('.gz'):
base = os.path.splitext(base)[0] # Strip .gz
base = os.path.splitext(base)[0] # Strip .fastq, .fq, etc.
return base
outputs_FASTQC = {fq: standardize_name(fq) for fq in ALL_FASTQ}
FASTQC = expand(os.path.join(DIR_WORKUP, "qc", "{sample}_fastqc.html"), sample=outputs_FASTQC.values())
FASTQC_POST_TRIM = [
os.path.join(DIR_WORKUP, "qc", "post_trim", f"{sample}_{fileid}_R1{chunk}.trimmed_fastqc.html")
for sample in ALL_SAMPLES
for fileid in get_fileids(sample)
for read in READS
for chunk in CHUNK_LIST
]
BARCODEID = []
BARCODEID.extend([
os.path.join(DIR_WORKUP, "fastqs", f"{sample}_{fileid}_R1{chunk}.fastq.gz")
for sample in ALL_SAMPLES
for fileid in get_fileids(sample)
for chunk in CHUNK_LIST
])
BARCODEID.extend([
os.path.join(DIR_WORKUP, "fastqs", f"{sample}_{fileid}_R2{chunk}.fastq.gz")
for sample in ALL_SAMPLES
for fileid in get_fileids(sample)
for chunk in CHUNK_LIST
])
BARCODEID_MAP = [
os.path.join(DIR_WORKUP, "assigned", f"{sample}_mapping.txt")
for sample in ALL_SAMPLES
]
LIGEFF = [
os.path.join(DIR_WORKUP, f"{sample}.ligation_efficiency.txt")
for sample in ALL_SAMPLES
]
if not tag_prefix_order:
LIGEFF = []
EXCLUSION_LOG = []
if use_exclusion_filter:
EXCLUSION_LOG.extend([
os.path.join(DIR_WORKUP, "exclusion", f"{sample}_{fileid}.exclusion_alignments{chunk}.log")
for sample in ALL_SAMPLES
for fileid in get_fileids(sample)
for chunk in CHUNK_LIST
])
EXCLUSION_LOG.extend([
os.path.join(DIR_WORKUP, f"{sample}.exclusion_stats.txt")
for sample in ALL_SAMPLES
])
OUT_FASTQS = [
os.path.join(DIR_WORKUP, "fastqs", f"{sample}_{fileid}_R1{chunk}.fastq.gz")
for sample in ALL_SAMPLES
for fileid in get_fileids(sample)
for chunk in CHUNK_LIST
]
OUT_FASTQS.extend([
os.path.join(DIR_WORKUP, "fastqs", f"{sample}_{fileid}_R2{chunk}.fastq.gz")
for sample in ALL_SAMPLES
for fileid in get_fileids(sample)
for chunk in CHUNK_LIST
])
OUT_STAR = expand(
os.path.join(DIR_WORKUP, "results", "output_{sample}_starsolo_" + align_id, "Aligned.sortedByCoord.out.bam"),
sample=ALL_SAMPLES
)
OUT_STAR.extend(expand(os.path.join(DIR_WORKUP, "results", "output_{sample}_starsolo_" + align_id, "Solo.out", "Gene", "raw", "barcodes.tsv"), sample=ALL_SAMPLES))
OUT_STAR.extend(expand(os.path.join(DIR_WORKUP, "results", "output_{sample}_starsolo_" + align_id, "Solo.out", "GeneFull", "raw", "barcodes.tsv"), sample=ALL_SAMPLES))
OUT_STAR.extend(expand(os.path.join(DIR_WORKUP, "results", "output_{sample}_starsolo_" + align_id, "Solo.out", "SJ", "raw", "barcodes.tsv"), sample=ALL_SAMPLES))
OUT_STAR_BARCODE_MAPPING = []
OUT_STAR_BARCODE_MAPPING.extend(expand(os.path.join(DIR_WORKUP, "results", "output_{sample}_starsolo_" + align_id, "Solo.out", "Gene", "raw", "barcodes.ids.txt"), sample=ALL_SAMPLES))
OUT_STAR_BARCODE_MAPPING.extend(expand(os.path.join(DIR_WORKUP, "results", "output_{sample}_starsolo_" + align_id, "Solo.out", "GeneFull", "raw", "barcodes.ids.txt"), sample=ALL_SAMPLES))
OUT_STAR_BARCODE_MAPPING.extend(expand(os.path.join(DIR_WORKUP, "results", "output_{sample}_starsolo_" + align_id, "Solo.out", "SJ", "raw", "barcodes.ids.txt"), sample=ALL_SAMPLES))
if not use_star:
OUT_STAR = []
OUT_STAR_BARCODE_MAPPING = []
if use_star:
if split_allele_analysis:
OUT_STAR.extend(expand(os.path.join(DIR_WORKUP, "results", "output_{sample}_starsolo_" + align_id, vcf_s1_), sample=ALL_SAMPLES))
OUT_STAR.extend(expand(os.path.join(DIR_WORKUP, "results", "output_{sample}_starsolo_" + align_id, vcf_s2), sample=ALL_SAMPLES))
OUT_ANNDATA = expand(
[os.path.join(
DIR_WORKUP,
"results",
"anndatas",
"{sample}_anndata",
"starsolo_" + align_id,
"Gene",
adata_filename),
os.path.join(
DIR_WORKUP,
"results",
"anndatas",
"{sample}_anndata",
"starsolo_" + align_id,
"GeneFull",
adata_filename)],
sample=ALL_SAMPLES
)
if merge_anndata_files:
OUT_ANNDATA.extend([os.path.join(DIR_WORKUP, "results", "anndatas", "merged", "starsolo_" + align_id, "Gene", adata_filename)])
OUT_ANNDATA.extend([os.path.join(DIR_WORKUP, "results", "anndatas", "merged", "starsolo_" + align_id, "GeneFull", adata_filename)])
OUT_ANNDATA.extend([os.path.join(DIR_WORKUP, "results", "anndatas", "merged", "starsolo_" + align_id, "Gene", "sample_order.txt")])
OUT_ANNDATA.extend([os.path.join(DIR_WORKUP, "results", "anndatas", "merged", "starsolo_" + align_id, "GeneFull", "sample_order.txt")])
if split_allele_analysis:
OUT_ANNDATA.extend(expand(
[os.path.join(
DIR_WORKUP,
"results",
"anndatas",
"{sample}_anndata",
"starsolo_" + align_id,
vcf_s1_,
"Gene",
adata_filename),
os.path.join(
DIR_WORKUP,
"results",
"anndatas",
"{sample}_anndata",
"starsolo_" + align_id,
vcf_s1_,
"GeneFull",
adata_filename)],
sample=ALL_SAMPLES
))
OUT_ANNDATA.extend(expand(
[os.path.join(
DIR_WORKUP,
"results",
"anndatas",
"{sample}_anndata",
"starsolo_" + align_id,
vcf_s2,
"Gene",
adata_filename),
os.path.join(
DIR_WORKUP,
"results",
"anndatas",
"{sample}_anndata",
"starsolo_" + align_id,
vcf_s2,
"GeneFull",
adata_filename)],
sample=ALL_SAMPLES
))
if merge_anndata_files:
OUT_ANNDATA.extend([os.path.join(DIR_WORKUP, "results", "anndatas", "merged", "starsolo_" + align_id, vcf_s1_, "Gene", adata_filename)])
OUT_ANNDATA.extend([os.path.join(DIR_WORKUP, "results", "anndatas", "merged", "starsolo_" + align_id, vcf_s1_, "GeneFull", adata_filename)])
OUT_ANNDATA.extend([os.path.join(DIR_WORKUP, "results", "anndatas", "merged", "starsolo_" + align_id, vcf_s2, "Gene", adata_filename)])
OUT_ANNDATA.extend([os.path.join(DIR_WORKUP, "results", "anndatas", "merged", "starsolo_" + align_id, vcf_s2, "GeneFull", adata_filename)])
OUT_ANNDATA.extend([os.path.join(DIR_WORKUP, "results", "anndatas", "merged", "starsolo_" + align_id, vcf_s1_, "Gene", "sample_order.txt")])
OUT_ANNDATA.extend([os.path.join(DIR_WORKUP, "results", "anndatas", "merged", "starsolo_" + align_id, vcf_s1_, "GeneFull", "sample_order.txt")])
OUT_ANNDATA.extend([os.path.join(DIR_WORKUP, "results", "anndatas", "merged", "starsolo_" + align_id, vcf_s2, "Gene", "sample_order.txt")])
OUT_ANNDATA.extend([os.path.join(DIR_WORKUP, "results", "anndatas", "merged", "starsolo_" + align_id, vcf_s2, "GeneFull", "sample_order.txt")])
else:
OUT_ANNDATA = []
STAR_GENOME_FASTA = []
STAR_GENOME_GTF = []
if use_star and genome_fasta and genome_gtf and not star_index:
STAR_GENOME_FASTA = [genome_fasta]
STAR_GENOME_GTF = [genome_gtf]
# features files:
OUT_FEATURES = []
if use_features:
OUT_FEATURES = expand(
os.path.join(DIR_WORKUP, "results", "output_{sample}_features", "counts_unfiltered", "cells_x_genes.mtx"),
sample=ALL_SAMPLES
)
OUT_FEATURES.extend(expand(os.path.join(DIR_WORKUP, "results", "output_{sample}_features", "counts_unfiltered", "cells_x_genes.barcodes.ids.txt"), sample=ALL_SAMPLES))
OUT_ANNDATA.extend(expand(os.path.join(DIR_WORKUP, "results", "anndatas", "{sample}_anndata", "features", adata_filename), sample=ALL_SAMPLES))
if merge_anndata_files:
OUT_ANNDATA.extend([os.path.join(DIR_WORKUP, "results", "anndatas", "merged", "features", adata_filename)])
OUT_ANNDATA.extend([os.path.join(DIR_WORKUP, "results", "anndatas", "merged", "features", "sample_order.txt")])
# kallisto files:
OUT_KALLISTO = expand(
os.path.join(DIR_WORKUP, "results", "output_{sample}_kallisto_" + align_id, "counts_unfiltered"),
sample=ALL_SAMPLES
)
if not use_kallisto:
OUT_KALLISTO = []
################################################################################
#Functions for formatting of input file names and output file names
################################################################################
#returns path to supplied pre-generated index or a newly created index
star_index_dir_new = os.path.join(DIR_WORKUP, "index", "star", "genome")
def get_star_index(wildcards):
if star_index:
return star_index
else:
return star_index_dir_new
#kallisto
kallisto_index_dir_new = os.path.join(DIR_WORKUP, "index", "kallisto")
kallisto_index_new = os.path.join(kallisto_index_dir_new, "index.idx")
kallisto_t2g_new = os.path.join(kallisto_index_dir_new, "t2g.txt")
kallisto_c1_new = os.path.join(kallisto_index_dir_new, "cdna.txt")
kallisto_c2_new = os.path.join(kallisto_index_dir_new, "nascent.txt")
kallisto_f1_new = os.path.join(kallisto_index_dir_new, "cdna.fa")
kallisto_f2_new = os.path.join(kallisto_index_dir_new, "nascent.fa")
def get_kallisto_index(wildcards):
if kallisto_index:
return kallisto_index
else:
return kallisto_index_new
def get_kallisto_t2g(wildcards):
if kallisto_index:
return kallisto_index_t2g
else:
return kallisto_t2g_new
def get_kallisto_c1(wildcards):
if kallisto_index:
return kallisto_index_c1
else:
return kallisto_c1_new
def get_kallisto_c2(wildcards):
if kallisto_index:
return kallisto_index_c2
else:
return kallisto_c2_new
#returns path to VCF file
def get_vcf_file(wildcards):
if not vcf_file:
return []
if use_vcf_wasp_workflow and vcf_s1 and vcf_s2:
return [os.path.join(DIR_WORKUP, "hybrid.vcf")]
return [vcf_file]
#variable describing how the VCF file should be inputted
vcf_file_input_param = "\"" + os.path.join(DIR_WORKUP, "hybrid.vcf") + "\"" if vcf_s1 and vcf_s2 and use_vcf_wasp_workflow else "<(zcat -f \"" + vcf_file + "\")"
#retrieves the fully preprocessed paired-end reads files to be used in read mapping
def get_mapping_input_r1(wildcards):
"""
Returns a list of all R1 FASTQ files for the given sample across all fileids and chunks.
"""
sample = wildcards.sample
r1_files = []
for fileid in get_fileids(sample):
for chunk in CHUNK_LIST:
if not use_exclusion_filter:
filepath = os.path.join(DIR_WORKUP, "fastqs", f"{sample}_{fileid}_R1{chunk}.fastq.gz")
else:
filepath = os.path.join(DIR_WORKUP, "fastqs", f"{sample}_{fileid}_R1{chunk}.filtered.fastq.gz")
r1_files.append(filepath)
return r1_files
def get_mapping_input_r2(wildcards):
"""
Returns a list of all R2 FASTQ files for the given sample across all fileids and chunks.
"""
sample = wildcards.sample
r2_files = []
for fileid in get_fileids(sample):
for chunk in CHUNK_LIST:
if not use_exclusion_filter:
filepath = os.path.join(DIR_WORKUP, "fastqs", f"{sample}_{fileid}_R2{chunk}.fastq.gz")
else:
filepath = os.path.join(DIR_WORKUP, "fastqs", f"{sample}_{fileid}_R2{chunk}.filtered.fastq.gz")
r2_files.append(filepath)
return r2_files
def get_mapping_input_names(wildcards):
"""
Returns a list of all "chunk names" for a given pair of read files.
"""
sample = wildcards.sample
chunk_names = []
for fileid in get_fileids(sample):
for chunk in CHUNK_LIST:
chunk_name = f"ID:{sample}" # f"ID:{sample}\tXF:{fileid}\tXP:{chunk.lstrip('.')}"
chunk_names.append(chunk_name)
return chunk_names
def get_group_from_input_r2_name(input_string):
"""
Returns a list of all "chunk names" for a given R2 read file.
"""
match = re.match(r"(?P<sample>[^_]+)_(?P<fileid>[^_]+)_R2(?P<chunk>\.[^.]+)?(\..+)?", os.path.basename(input_string))
if match:
sample = match.group("sample")
fileid = match.group("fileid")
chunk = match.group("chunk")
return f"ID:{sample}" # f"ID:{sample}\tXF:{fileid}\tXP:{chunk.lstrip('.')}"
else:
return "ID:undefined"
#retrieves the fully preprocessed paired-end reads files to be used for split allele analysis
def get_mapping_input_r1_split1(wildcards):
"""
Returns a list of all R1 FASTQ files for the given sample across all fileids and chunks.
"""
sample = wildcards.sample
r1_files = []
for fileid in get_fileids(sample):
for chunk in CHUNK_LIST:
filepath = os.path.join(DIR_WORKUP, "chunks", f"{sample}_{fileid}_R1{chunk}.split1.fastq.gz")
r1_files.append(filepath)
return r1_files
def get_mapping_input_r2_split1(wildcards):
"""
Returns a list of all R2 FASTQ files for the given sample across all fileids and chunks.
"""
sample = wildcards.sample
r2_files = []
for fileid in get_fileids(sample):
for chunk in CHUNK_LIST:
filepath = os.path.join(DIR_WORKUP, "chunks", f"{sample}_{fileid}_R2{chunk}.split1.fastq.gz")
r2_files.append(filepath)
return r2_files
def get_mapping_input_r1_split2(wildcards):
"""
Returns a list of all R1 FASTQ files for the given sample across all fileids and chunks.
"""
sample = wildcards.sample
r1_files = []
for fileid in get_fileids(sample):
for chunk in CHUNK_LIST:
filepath = os.path.join(DIR_WORKUP, "chunks", f"{sample}_{fileid}_R1{chunk}.split2.fastq.gz")
r1_files.append(filepath)
return r1_files
def get_mapping_input_r2_split2(wildcards):
"""
Returns a list of all R2 FASTQ files for the given sample across all fileids and chunks.
"""
sample = wildcards.sample
r2_files = []
for fileid in get_fileids(sample):
for chunk in CHUNK_LIST:
filepath = os.path.join(DIR_WORKUP, "chunks", f"{sample}_{fileid}_R2{chunk}.split2.fastq.gz")
r2_files.append(filepath)
return r2_files
#formats path to only consist of the filename
def get_basename():
return splitext(basename(file_path))[0]
################################################################################
################################################################################
#Rule all
################################################################################
################################################################################
rule all:
input: CONFIG + FASTQC + FASTQC_POST_TRIM + BARCODEID_MAP + SPLIT_FASTQ_GZ + EXCLUSION_LOG + \
LIGEFF + OUT_FASTQS + OUT_STAR + OUT_ANNDATA + OUT_KALLISTO + OUT_FEATURES + OUT_STAR_BARCODE_MAPPING
#Send and email if an error occurs during execution
onerror:
shell('mail -s "an error occurred" ' + email + ' < {log}')
################################################################################
#Trimming and barcode identification
################################################################################
rule log_config:
'''Copy config.yaml and place in logs folder with the date run
'''
input:
config_path
output:
os.path.join(DIR_LOGS, "config_" + run_date + "yaml")
shell:
'''
cp "{input}" "{output}"
'''
if num_chunks > 1:
rule split_fastq_into_parts_r1:
"""
Splits original FASTQ (R1) into chunks.
"""
input:
r1=lambda wc: FILES[wc.sample]['R1'][int(wc.fileid)]
output:
temp(expand([os.path.join(DIR_WORKUP, "split_fastq", "{{sample}}_{{fileid}}_R1{splitid}.fastq")], splitid=CHUNK_LIST))
threads:
4
priority:
8
params:
dir=os.path.join(DIR_WORKUP, "split_fastq")
log:
os.path.join(DIR_LOGS, "{sample}_{fileid}_split_r1_fastq.log")
shell:
"""