-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonify_db.py
executable file
·2068 lines (1918 loc) · 90.6 KB
/
jsonify_db.py
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
#!/usr/bin/env python3
import json
import glob
import re
import csv
import os
import hashlib
import logging
from datetime import datetime
import numpy as np
import h5py
logging.basicConfig(format='%(levelname)s: %(asctime)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
def main():
"""
Main function to run the script.
"""
# prefix_path = "/Users/pstretenowich/Mount_points/beluga"
prefix_path = "/lustre03/project/6007512"
main_raw_reads_folder = os.path.join(prefix_path, "C3G/projects/MOH_PROCESSING/MAIN/raw_reads")
# patient_dict = get_patient_dict("CheckBeluga.txt") #For the recraft of only the missing runs 08/2024 . Adapt acordg to the input
patient_dict = get_patient_dict(main_raw_reads_folder)
_, sample_dict = jsonify_run_processing(patient_dict, prefix_path)
jsonify_transfer(sample_dict, prefix_path)
jsonify_genpipes_tumourpair_ensemble(sample_dict, prefix_path)
jsonify_genpipes_rnaseqlight(sample_dict, prefix_path)
jsonify_genpipes_tumourpair_ensemble(sample_dict,prefix_path)
jsonify_genpipes_tumourpair_sv(sample_dict, prefix_path)
jsonify_genpipes_rnaseqlight(sample_dict, prefix_path)
jsonify_genpipes_rnaseq_cancer(sample_dict, prefix_path)
def jsonify_run_processing(patient_dict, prefix_path):
"""
Create a json file for each run in the run_metrics folder.
Return: dict, dict
"""
readset_dict = {}
sample_dict = {}
run_metrics_csv = os.path.join(prefix_path, "C3G/projects/MOH_PROCESSING/MAIN/metrics/run_metrics/*.csv")
# run_metrics_csv = "/Users/pstretenowich/Mount_points/beluga/C3G/projects/MOH_PROCESSING/MAIN/metrics/run_metrics/220128_A00266_0620_BH527LDSX3_MOHRun01_Q008401-novaseq-run.align_bwa_mem.csv"
for run_file in glob.glob(run_metrics_csv):
run_list = []
with open(run_file, 'rt') as run_file_in:
reader = csv.DictReader(run_file_in)
for row in reader:
run_list.append(row)
json_output = {
"operation_platform": "abacus",
"project_fms_id": None,
"project_name": "MOH-Q",
"run_fms_id": None,
"run_name": f"{run_list[0]['Processing Folder Name']}",
"run_instrument": "novaseq",
"run_date": f"{datetime.strptime(run_list[0]['Processing Folder Name'][0:6], '%y%m%d')}",
"patient": []
}
for run_row in run_list:
sample = run_row['Sample Name']
if sample.startswith("MoHQ"):
result = re.search(r"^((MoHQ-(JG|CM|GC|IQ|HM|MU|MR|XX|CQ)-\w+)-\w+)-\w+-\w+(D|R)(T|N)", sample)
patient = result.group(1)
try:
existing_patient = None
for position, element in enumerate(json_output["patient"]):
if f"{patient_dict[patient][sample][0]}" == element["patient_name"]:
existing_patient = element
existing_patient_pos = position
if existing_patient:
patient_json = existing_patient
del json_output["patient"][existing_patient_pos]
else:
patient_json = {
"patient_fms_id": None,
"patient_name": f"{patient_dict[patient][sample][0]}",
"patient_cohort": f"{patient_dict[patient][sample][3]}",
"patient_institution": f"{patient_dict[patient][sample][4]}",
"sample": []
}
existing_sample = None
sample_name = f"{patient_dict[patient][sample][1]}"
for _, element in enumerate(patient_json["sample"]):
if sample_name == element["sample_name"]:
existing_sample = element
if existing_sample:
sample_json = existing_sample
else:
sample_tumour = patient_dict[patient][sample][2].endswith("T")
sample_json = {
"sample_fms_id": None,
"sample_name": sample_name,
"sample_tumour": sample_tumour,
"readset": []
}
transfer_folder = os.path.join(prefix_path, 'C3G/projects/MOH_PROCESSING/DATABASE/log_files/transfer/*')
# transfer_folder = 'transfer/*'
fastq1 = fastq2 = ""
for filename in glob.glob(transfer_folder):
with open(filename, 'r') as file:
for line in file:
if patient_dict[patient][sample][1] in line and run_row['Processing Folder Name'] in line:
fields = line.split(",")
if ".bam" in line:
file_json = [
{
"location_uri": f"abacus://{fields[0]}",
"file_name": f"{os.path.basename(fields[0])}",
"file_deliverable": True
}
]
break
if ".fastq" in line:
if "R1.fastq" in line:
fastq1 = os.path.basename(fields[0])
fastq1_location_uri = fields[0]
elif "R2.fastq" in line:
fastq2 = os.path.basename(fields[0])
fastq2_location_uri = fields[0]
if fastq1 and fastq2:
file_json = [
{
"location_uri": f"abacus://{fastq1_location_uri}",
"file_name": f"{fastq1}",
"file_extra_metadata": {"read_type": "R1"},
"file_deliverable": True
},
{
"location_uri": f"abacus://{fastq2_location_uri}",
"file_name": f"{fastq2}",
"file_extra_metadata": {"read_type": "R2"},
"file_deliverable": True
}
]
break
if not run_row['Clusters']:
raw_reads_count_flag = "MISSING"
if run_row['Clusters'] =='0':
raw_reads_count_flag = "FAILED"
else:
raw_reads_count_flag = "PASS"
if run_row['Library Type'] == "RNASeq":
raw_reads_count_flag = rna_raw_reads_count_check(run_row['Clusters'])
raw_duplication_rate_flag = "PASS"
if run_row['Library Type'] != "RNASeq":
raw_duplication_rate_flag = dna_raw_duplication_rate_check(run_row['Dup. Rate (%)'])
raw_median_insert_size_flag = median_insert_size_check(run_row['Mapped Insert Size (median)'])
raw_mean_insert_size_flag = "PASS"
raw_mean_coverage_flag = "PASS"
if run_row['Library Type'] != "RNASeq":
raw_mean_coverage_flag = dna_raw_mean_coverage_check(run_row['Mean Coverage'], sample_tumour)
metric_json = [
{
"metric_name": "raw_reads_count",
"metric_value": f"{run_row['Clusters']}",
"metric_flag": raw_reads_count_flag,
"metric_deliverable": True
},
{
"metric_name": "raw_duplication_rate",
"metric_value": f"{run_row['Dup. Rate (%)']}",
"metric_flag": raw_duplication_rate_flag
},
{
"metric_name": "raw_median_insert_size",
"metric_value": f"{run_row['Mapped Insert Size (median)']}",
"metric_flag": raw_median_insert_size_flag
},
{
"metric_name": "raw_mean_insert_size",
"metric_value": f"{run_row['Mapped Insert Size (mean)']}",
"metric_flag": raw_mean_insert_size_flag
},
{
"metric_name": "raw_mean_coverage",
"metric_value": f"{run_row['Mean Coverage']}",
"metric_flag": raw_mean_coverage_flag
}
]
readset_name = f"{run_row['Sample Name']}.{run_row['Run ID']}_{run_row['Lane']}"
readset_dict[readset_name] = (patient, sample)
readset_json = {
"experiment_sequencing_technology": None,
"experiment_type": f"{run_row['Library Type']}",
"experiment_library_kit": None,
"experiment_kit_expiration_date": None,
"readset_name": readset_name,
"readset_lane": f"{run_row['Lane']}",
"readset_adapter1": f"{run_row['i7 Adapter Sequence']}",
"readset_adapter2": f"{run_row['i5 Adapter Sequence']}",
"readset_sequencing_type": f"{run_row['Run Type']}",
"readset_quality_offset": "33",
"file": file_json,
"metric": metric_json
}
sample_json["readset"].append(readset_json)
if sample_name in sample_dict:
sample_dict[sample_name].append((patient, readset_name))
else:
sample_dict[sample_name] = [(patient, readset_name)]
patient_json["sample"].append(sample_json)
json_output["patient"].append(patient_json)
# for sample in patient_json["sample"]:
# print(sample, "\n")
# print(sample["sample_name"], "\n")
except KeyError:
pass
with open(f"jsons/{run_list[0]['Processing Folder Name']}.json", 'w', encoding='utf-8') as f:
json.dump(json_output, f, ensure_ascii=False, indent=4)
return readset_dict, sample_dict
def jsonify_transfer(sample_dict, prefix_path):
"""
Create a json file for each transfer log file in the transfer folder.
"""
transfer_folder = os.path.join(prefix_path, 'C3G/projects/MOH_PROCESSING/DATABASE/log_files/transfer/*')
for filename in glob.glob(transfer_folder):
transfer_dict = {}
json_output = {
"operation_platform": "beluga",
"operation_cmd_line": f"globus transfer --submission-id $sub_id --label $label --batch /lb/project/mugqic/projects/MOH/TEMP/{os.path.basename(filename)} 6c66d53d-a79d-11e8-96fa-0a6d4e044368 278b9bfe-24da-11e9-9fa2-0a06afd4a22e",
"readset": []
}
with open(filename, 'r') as file:
for line in file:
if line.startswith("/"):
fields = line.split(",")
sample = os.path.dirname(fields[1])
if sample in sample_dict:
abacus_uri = "abacus://"
beluga_uri = "beluga:///lustre03/project/6007512/C3G/projects/MOH_PROCESSING/raw_reads/" + sample
if ".bam" in line:
readset_name = sample + "." + fields[0].split("/")[11].replace("run", "")
bam_src_location_uri = abacus_uri + fields[0]
bam_dest_location_uri = os.path.join(beluga_uri, os.path.basename(fields[1].strip()))
if readset_name in transfer_dict:
transfer_dict[readset_name]["bam_dest_location_uri"] = bam_dest_location_uri
else:
transfer_dict[readset_name] = {
"bam_dest_location_uri": bam_dest_location_uri
}
transfer_dict[readset_name]["bam_src_location_uri"] = bam_src_location_uri
elif ".fastq" in line:
run_name = fields[0].split("/")[7]
readset_name = sample + "." + run_name.split("_")[1] + "_" + run_name.split("_")[2] + "_" + fields[0].split("/")[8].split(".")[1]
if "R1.fastq" in line:
fastq1_src_location_uri = abacus_uri + fields[0]
fastq1_dest_location_uri = os.path.join(beluga_uri, os.path.basename(fields[1].strip()))
if readset_name in transfer_dict:
transfer_dict[readset_name]["fastq1_dest_location_uri"] = fastq1_dest_location_uri
else:
transfer_dict[readset_name] = {
"fastq1_dest_location_uri": fastq1_dest_location_uri
}
transfer_dict[readset_name]["fastq1_src_location_uri"] = fastq1_src_location_uri
elif "R2.fastq" in line:
fastq2_src_location_uri = abacus_uri + fields[0]
fastq2_dest_location_uri = os.path.join(beluga_uri, os.path.basename(fields[1].strip()))
if readset_name in transfer_dict:
transfer_dict[readset_name]["fastq2_dest_location_uri"] = fastq2_dest_location_uri
else:
transfer_dict[readset_name] = {
"fastq2_dest_location_uri": fastq2_dest_location_uri
}
transfer_dict[readset_name]["fastq2_src_location_uri"] = fastq2_src_location_uri
for readset in transfer_dict:
if "bam_src_location_uri" in transfer_dict[readset]:
file_json = [
{
"src_location_uri": transfer_dict[readset]["bam_src_location_uri"],
"dest_location_uri": transfer_dict[readset]["bam_dest_location_uri"]
}
]
elif "fastq1_src_location_uri" in transfer_dict[readset]:
file_json = [
{
"src_location_uri": transfer_dict[readset]["fastq1_src_location_uri"],
"dest_location_uri": transfer_dict[readset]["fastq1_dest_location_uri"]
},
{
"src_location_uri": transfer_dict[readset]["fastq2_src_location_uri"],
"dest_location_uri": transfer_dict[readset]["fastq2_dest_location_uri"],
}
]
else:
file_json = []
readset_json = {
"readset_name": readset,
"file": file_json,
}
json_output["readset"].append(readset_json)
# print(json.dumps(readset_json, indent=4))
if transfer_dict:
with open(f"jsons/{os.path.basename(filename).replace('.txt', '.json')}", 'w', encoding='utf-8') as f:
json.dump(json_output, f, ensure_ascii=False, indent=4)
def jsonify_genpipes_tumourpair_sv(sample_dict, prefix_path):
"""
Create a json file for each patient in the sample_dict for the TumorPair SV pipeline.
"""
ini_file = os.path.join(prefix_path, "C3G/projects/MOH_PROCESSING/MAIN/TumorPair.config.trace.ini")
to_parse = False
ini_content = []
with open(ini_file, 'r') as file:
for line in file:
if "base.ini" in line:
genpipes_version = re.findall(r"/genpipes-.+?/", line)[0].split("-")[-1][:-1]
else:
genpipes_version = "unknown"
if "[DEFAULT]" in line:
to_parse = True
if to_parse:
ini_content.append(line)
# From where to parse genpipes version and cmd line
json_output = {
"project_name": "MOH-Q",
"operation_config_name": "genpipes_ini",
"operation_config_version": f"{genpipes_version}",
"operation_config_md5sum": f"{md5(ini_file)}",
"operation_config_data": f"{''.join(ini_content)}",
"operation_platform": "beluga",
"operation_cmd_line": "tumor_pair.py -s 1-13,15-38 -j slurm -r readset.txt -c $MUGQIC_PIPELINES_HOME/pipelines/tumor_pair/tumor_pair.base.ini $MUGQIC_PIPELINES_HOME/pipelines/common_ini/beluga.ini $MUGQIC_PIPELINES_HOME/pipelines/tumor_pair/tumor_pair.extras.ini $MUGQIC_PIPELINES_HOME/resources/genomes/config/Homo_sapiens.GRCh38.ini Custom_ini/Custom_MOH_topups.ini -g TP_run.sh",
"operation_name": "GenPipes_TumorPair.sv",
"sample": []
}
sample_dict_dna = {}
for sample in sample_dict:
if not sample.endswith("RT"):
sample_dict_dna[sample] = sample_dict[sample]
length = len(sample_dict_dna)
i = 0
for sample in sample_dict_dna:
i += 1
eta = round(float(100*i/length), 2)
logger.info(f"jsonify_genpipes_tumourpair_sv - {eta}%")
patient = sample_dict_dna[sample][0][0]
tumour = sample.endswith("DT")
sample_json = {
"sample_name": f"{sample}",
"readset": []
}
job_jsons = []
job_jsons.append(gridss_paired_somatic(patient, sample, prefix_path))
job_jsons.append(gripss_filter_somatic(patient, sample, prefix_path))
job_jsons.append(gripss_filter_germline(patient, sample, prefix_path))
job_jsons.append(purple_purity_sv(patient, sample, prefix_path))
if tumour:
job_jsons.append(linx_annotations_germline(patient, sample, prefix_path))
job_jsons.append(linx_annotations_somatic(patient, sample, prefix_path))
job_jsons.append(linx_plot(patient, prefix_path))
for (_, readset) in sample_dict_dna[sample]:
readset_json = {
"readset_name": f"{readset}",
"job": []
}
job_jsons = list(filter(lambda job_json: job_json is not None, job_jsons))
for job_json in job_jsons:
readset_json["job"].append(job_json)
if readset_json["job"]:
sample_json["readset"].append(readset_json)
if sample_json["readset"]:
json_output["sample"].append(sample_json)
if json_output["sample"]:
with open("jsons/genpipes_tumourpair_sv.json", 'w', encoding='utf-8') as f:
json.dump(json_output, f, ensure_ascii=False, indent=4)
def jsonify_genpipes_tumourpair_ensemble(sample_dict, prefix_path):
"""
Create a json file for each patient in the sample_dict for the TumorPair ensemble pipeline.
"""
ini_file = os.path.join(prefix_path, "C3G/projects/MOH_PROCESSING/MAIN/TumorPair.config.trace.ini")
to_parse = False
ini_content = []
with open(ini_file, 'r') as file:
for line in file:
if "base.ini" in line:
genpipes_version = re.findall(r"/genpipes-.+?/", line)[0].split("-")[-1][:-1]
else:
genpipes_version = "unknown"
if "[DEFAULT]" in line:
to_parse = True
if to_parse:
ini_content.append(line)
# From where to parse genpipes version and cmd line
json_output = {
"project_name": "MOH-Q",
"operation_config_name": "genpipes_ini",
"operation_config_version": f"{genpipes_version}",
"operation_config_md5sum": f"{md5(ini_file)}",
"operation_config_data": f"{''.join(ini_content)}",
"operation_platform": "beluga",
"operation_cmd_line": "tumor_pair.py -s 1-13,15-38 -j slurm -r readset.txt -c $MUGQIC_PIPELINES_HOME/pipelines/tumor_pair/tumor_pair.base.ini $MUGQIC_PIPELINES_HOME/pipelines/common_ini/beluga.ini $MUGQIC_PIPELINES_HOME/pipelines/tumor_pair/tumor_pair.extras.ini $MUGQIC_PIPELINES_HOME/resources/genomes/config/Homo_sapiens.GRCh38.ini Custom_ini/Custom_MOH_topups.ini -g TP_run.sh",
"operation_name": "GenPipes_TumorPair.ensemble",
"sample": []
}
sample_dict_dna = {}
for sample in sample_dict:
if not sample.endswith("RT"):
sample_dict_dna[sample] = sample_dict[sample]
length = len(sample_dict_dna)
i = 0
for sample in sample_dict_dna:
i += 1
eta = round(float(100*i/length), 2)
logger.info(f"jsonify_genpipes_tumourpair - {eta}%")
patient = sample_dict_dna[sample][0][0]
tumour = sample.endswith("DT")
sample_json = {
"sample_name": f"{sample}",
"readset": []
}
job_jsons = []
job_jsons.append(sym_link_final_bam_tumourpair(patient, sample, tumour, prefix_path))
job_jsons.append(gatk_variant_annotator_germline_tumourpair(patient, prefix_path))
job_jsons.append(gatk_variant_annotator_somatic_tumourpair(patient, prefix_path))
job_jsons.append(paired_mutect2_tumourpair(patient, prefix_path))
job_jsons.append(vardict_paired_tumourpair(patient, prefix_path))
job_jsons.append(paired_varscan2_tumourpair(patient, prefix_path))
job_jsons.append(cnvkit_batch_tumourpair(patient, prefix_path))
job_jsons.append(recalibration_tumourpair(patient,sample, prefix_path))
job_jsons.append(strelka2_paired_germline_tumourpair(patient, prefix_path))
job_jsons.append(report_pcgr_tumourpair(patient, prefix_path))
job_jsons.append(tumour_pair_multiqc(patient, prefix_path))
# Conpair
job_jsons.append(extract_conpair(patient, sample, tumour, prefix_path))
# Purple
job_jsons.append(extract_purple(sample, patient, prefix_path))
# Qualimap
job_jsons.append(extract_qualimap(patient,sample, prefix_path))
# Picard
job_jsons.append(extract_picard_tumourpair(patient,sample, prefix_path))
for (_, readset) in sample_dict_dna[sample]:
readset_json = {
"readset_name": f"{readset}",
"job": []
}
job_jsons = list(filter(lambda job_json: job_json is not None, job_jsons))
for job_json in job_jsons:
readset_json["job"].append(job_json)
if readset_json["job"]:
sample_json["readset"].append(readset_json)
if sample_json["readset"]:
json_output["sample"].append(sample_json)
if json_output["sample"]:
with open("jsons/genpipes_tumourpair_en.json", 'w', encoding='utf-8') as f:
json.dump(json_output, f, ensure_ascii=False, indent=4)
def jsonify_genpipes_rnaseqlight(sample_dict, prefix_path):
"""
Create a json file for each patient in the sample_dict for the RnaSeqLight pipeline.
"""
ini_file = os.path.join(prefix_path, "C3G/projects/MOH_PROCESSING/MAIN/RnaSeqLight.config.trace.ini")
to_parse = False
ini_content = []
with open(ini_file, 'r') as file:
for line in file:
if "base.ini" in line:
genpipes_version = re.findall(r"/genpipes-.+?/", line)[0].split("-")[-1][:-1]
else:
genpipes_version = "unknown"
if "[DEFAULT]" in line:
to_parse = True
if to_parse:
ini_content.append(line)
# From where to parse genpipes version and cmd line
json_output = {
"project_name": "MOH-Q",
"operation_config_name": "genpipes_ini",
"operation_config_version": f"{genpipes_version}",
"operation_config_md5sum": f"{md5(ini_file)}",
"operation_config_data": f"{''.join(ini_content)}",
"operation_platform": "beluga",
"operation_cmd_line": "rnaseq_light.py -s 1-4 -j slurm -r readset.txt -c $MUGQIC_PIPELINES_HOME/pipelines/rnaseq_light/rnaseq_light.base.ini $MUGQIC_PIPELINES_HOME/pipelines/common_ini/beluga.ini $MUGQIC_PIPELINES_HOME/resources/genomes/config/Homo_sapiens.GRCh38.ini RNA_light.custom.ini -g RNASeq_light_run.sh",
"operation_name": "GenPipes_RnaSeqLight",
"sample": []
}
sample_dict_rna = {}
for sample in sample_dict:
if sample.endswith("RT"):
sample_dict_rna[sample] = sample_dict[sample]
for sample in sample_dict_rna:
sample_json = {
"sample_name": f"{sample}",
"readset": []
}
job_jsons = []
# Picard
job_jsons.append(extract_picard_rna(sample, prefix_path))
# Kallisto
job_jsons.append(extract_kallisto_rnaseqlight(sample, prefix_path))
for (_, readset) in sample_dict_rna[sample]:
readset_json = {
"readset_name": f"{readset}",
"job": []
}
job_jsons = list(filter(lambda job_json: job_json is not None, job_jsons))
for job_json in job_jsons:
readset_json["job"].append(job_json)
if readset_json["job"]:
sample_json["readset"].append(readset_json)
if sample_json["readset"]:
json_output["sample"].append(sample_json)
if json_output["sample"]:
with open("jsons/genpipes_rnaseqlight.json", 'w', encoding='utf-8') as f:
json.dump(json_output, f, ensure_ascii=False, indent=4)
def jsonify_genpipes_rnaseq_cancer(sample_dict, prefix_path):
"""
Create a json file for each patient in the sample_dict for the RnaSeqCancer pipeline.
"""
ini_file = os.path.join(prefix_path, "C3G/projects/MOH_PROCESSING/MAIN/RnaSeq.config.trace.ini")
to_parse = False
ini_content = []
with open(ini_file, 'r') as file:
for line in file:
if "base.ini" in line:
genpipes_version = re.findall(r"/genpipes-.+?/", line)[0].split("-")[-1][:-1]
else:
genpipes_version = "unknown"
if "[DEFAULT]" in line:
to_parse = True
if to_parse:
ini_content.append(line)
# From where to parse genpipes version and cmd line
json_output = {
"project_name": "MOH-Q",
"operation_config_name": "genpipes_ini",
"operation_config_version": f"{genpipes_version}",
"operation_config_md5sum": f"{md5(ini_file)}",
"operation_config_data": f"{''.join(ini_content)}",
"operation_platform": "beluga",
"operation_cmd_line": "rnaseq.py -s 1-7,10-23 -j slurm -r readset.txt -c $MUGQIC_PIPELINES_HOME/pipelines/rnaseq/rnaseq.base.ini $MUGQIC_PIPELINES_HOME/pipelines/common_ini/beluga.ini /lustre03/project/6007512/C3G/projects/MOH_PROCESSING/MAIN/Custom_ini/tumor_rna.moh.ini $MUGQIC_PIPELINES_HOME/resources/genomes/config/Homo_sapiens.GRCh38.ini -g RNASeq_run.sh -t cancer",
"operation_name": "GenPipes_RnaSeq.cancer",
"sample": []
}
sample_dict_rna = {}
for sample in sample_dict:
if sample.endswith("RT"):
sample_dict_rna[sample] = sample_dict[sample]
# if sample == "MoHQ-MU-17-1251-OC1-1DT":
# sample_dict_rna[sample] = sample_dict[sample]
for sample in sample_dict_rna:
sample_json = {
"sample_name": f"{sample}",
"readset": []
}
job_jsons = []
# Rnaseqc2
job_jsons.append(extract_rnaseqc2_rna(sample, prefix_path))
job_jsons.append(filter_gatk_rnaseqc2(sample, prefix_path))
job_jsons.append(recalibration_rnaseqc2(sample, prefix_path))
job_jsons.append(rnaseqc2_multiqc(sample, prefix_path))
job_jsons.append(report_pcgr_rnaseqc2(sample, prefix_path))
for (_, readset) in sample_dict_rna[sample]:
readset_json = {
"readset_name": f"{readset}",
"job": []
}
job_jsons = list(filter(lambda job_json: job_json is not None, job_jsons))
for job_json in job_jsons:
readset_json["job"].append(job_json)
if readset_json["job"]:
sample_json["readset"].append(readset_json)
if sample_json["readset"]:
json_output["sample"].append(sample_json)
if json_output["sample"]:
with open("jsons/genpipes_rnaseqcancer.json", 'w', encoding='utf-8') as f:
json.dump(json_output, f, ensure_ascii=False, indent=4)
def md5(fname):
"""
Calculate the md5 hash of a file.
Return: str
"""
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def get_patient_dict(main_raw_reads_folder):
"""
Create a dictionary with patient as key and a dictionary with sample as key and a tuple with patient, sample, sample type, cohort and institution as value.
Return: dict
"""
patient_dict = {}
for sample in os.listdir(main_raw_reads_folder):
if sample.startswith("MoHQ"):
result = re.search(r"^((MoHQ-(JG|CM|GC|MU|MR|XX|CQ)-\w+)-\w+)-\w+-\w+(D|R)(T|N)", sample)
patient = result.group(1)
cohort = result.group(2)
institution = result.group(3)
sample_type = sample[-2:]
try:
patient_dict[patient][sample] = (patient, sample, sample_type, cohort, institution)
except KeyError:
patient_dict[patient] = {sample: (patient, sample, sample_type, cohort, institution)}
return patient_dict
def extract_conpair(patient, sample, tumour, prefix_path):
"""
Extract conpair job, files and metrics from the job_output/conpair_concordance_contamination/conpair_concordance_contamination.pileup.*{sample}*.o file.
Return: dict
"""
job_status = None
job_start = None
job_stop = None
try:
latest = sorted(glob.glob(os.path.join(prefix_path, f"C3G/projects/MOH_PROCESSING/MAIN/job_output/conpair_concordance_contamination/conpair_concordance_contamination.pileup.*{sample}*.o")), key=os.path.getmtime)[-1]
job_status, job_start, job_stop = parse_o_file(latest)
except IndexError:
logger.warning(f"No job_output/conpair_concordance_contamination/conpair_concordance_contamination.pileup.*{sample}*.o file found")
job_json_conpair = {
"job_name": f"conpair.{patient}",
"job_start": job_start,
"job_stop": job_stop,
"job_status": job_status,
"file": [],
"metric": []
}
# Contamination
no_contamination = False
# The file is named after tumour sample only
contamination_file = glob.glob(os.path.join(prefix_path, 'C3G/projects/MOH_PROCESSING/MAIN/metrics', patient + '-*DT.contamination.tsv'))
# Test if unsure about finding more than 1 contamination file for normal sample based on the glob above.
# It has to print nothing to be ok, otherwise it means a manual check is required.
if len(contamination_file) > 1:
print(f" WARNING: Manual check reauired for patient {patient} as more than 1 contamination file is found: {contamination_file}")
try:
with open(contamination_file[0], 'r', encoding="utf-8") as file:
job_json_conpair["job_status"] = "COMPLETED"
for line in file:
if line.startswith('Normal') and not tumour:
value = line.split(" ")[-1][:-2]
if float(value)>5:
flag = "FAILED"
else:
flag = "PASS"
job_json_conpair["metric"].append({
"metric_name": "contamination",
"metric_value": f"{value}",
"metric_flag": f"{flag}",
"metric_deliverable": True
})
job_json_conpair["file"].append({
"location_uri": f"beluga://{contamination_file[0]}",
"file_name": f"{os.path.basename(contamination_file[0])}"
})
elif line.startswith('Tumor') and tumour:
value = line.split(" ")[-1][:-2]
if float(value)>5:
flag = "FAILED"
else:
flag = "PASS"
job_json_conpair["metric"].append({
"metric_name": "contamination",
"metric_value": f"{value}",
"metric_flag": f"{flag}",
"metric_deliverable": True
})
job_json_conpair["file"].append({
"location_uri": f"beluga://{contamination_file[0]}",
"file_name": f"{os.path.basename(contamination_file[0])}"
})
except (FileNotFoundError, IndexError):
no_contamination = True
# Concordance
no_concordance = False
# The file is named after tumour sample only
filename = glob.glob(os.path.join(prefix_path, 'C3G/projects/MOH_PROCESSING/MAIN/metrics', f"{patient}-*DT.concordance.tsv"))
# Test if unsure about finding more than 1 concordance file for normal sample based on the glob above.
# It has to print nothing to be ok, otherwise it means a manual check is required.
if len(filename) > 1:
print(f" WARNING: Manual check reauired for patient {patient} as more than 1 concordance file is found: {filename}")
try:
with open(filename[0], 'r', encoding="utf-8") as file:
job_json_conpair["job_status"] = "COMPLETED"
for line in file:
if line.startswith('Concordance'):
value = line.split(" ")[-1][:-2]
if float(value)<99:
flag = "FAILED"
else:
flag = "PASS"
job_json_conpair["metric"].append({
"metric_name": "concordance",
"metric_value": f"{value}",
"metric_flag": f"{flag}",
"metric_deliverable": True
})
job_json_conpair["file"].append({
"location_uri": f"beluga://{filename[0]}",
"file_name": f"{os.path.basename(filename[0])}"
})
except (FileNotFoundError, IndexError):
no_concordance = True
if no_concordance and no_contamination:
job_json_conpair = None
return job_json_conpair
def extract_purple(sample, patient, prefix_path):
"""
Extract purple job, files and metrics from the job_output/purple/purple.purity.*{patient}*.o file.
Return: dict
"""
job_status = None
job_start = None
job_stop = None
try:
latest = sorted(glob.glob(os.path.join(prefix_path, f"C3G/projects/MOH_PROCESSING/MAIN/job_output/purple/purple.purity.*{patient}*.o")), key=os.path.getmtime)[-1]
job_status, job_start, job_stop = parse_o_file(latest)
except IndexError:
logger.warning(f"No job_output/purple/purple.purity.*{patient}*.o file found")
job_json = {
"job_name": f"purple.{patient}",
"job_start": job_start,
"job_stop": job_stop,
"job_status": job_status,
"file": [],
}
filename = os.path.join(prefix_path, 'C3G/projects/MOH_PROCESSING/MAIN/pairedVariants', patient, f'{patient}.strelka2.somatic.purple.vcf.gz')
job_json = add_output_file(filename, job_json, True)
filename = os.path.join(prefix_path, 'C3G/projects/MOH_PROCESSING/MAIN/pairedVariants', patient, f'{patient}.strelka2.somatic.purple.vcf.gz.tbi')
job_json = add_output_file(filename, job_json)
try:
filename = os.path.join(prefix_path, 'C3G/projects/MOH_PROCESSING/MAIN/pairedVariants', patient, 'purple', sample + '.purple.purity.tsv')
with open(filename, 'r', encoding="utf-8") as file:
lines = file.readlines()
line = lines[1]
fields = line.split("\t")
value = float(fields[0])*100
if float(value)<30:
flag = "FAILED"
else:
flag = "PASS"
try:
job_json["metric"].append({
"metric_name": "purity",
"metric_value": f"{value}",
"metric_flag": f"{flag}",
"metric_deliverable": True
})
except KeyError:
job_json["metric"] = [{
"metric_name": "purity",
"metric_value": f"{value}",
"metric_flag": f"{flag}",
"metric_deliverable": True
}]
job_json["file"].append({
"location_uri": f"beluga://{filename}",
"file_name": f"{os.path.basename(filename)}"
})
except FileNotFoundError:
pass
if not job_json["file"]:
job_json = None
return job_json
def extract_rnaseqc2_rna(sample, prefix_path):
"""
Extract rnaseqc2 job, files and metrics from the job_output/rnaseqc2/rnaseqc2.*{sample}*.o file.
Return: dict
"""
job_status = None
job_start = None
job_stop = None
try:
latest = sorted(glob.glob(os.path.join(prefix_path, f"C3G/projects/MOH_PROCESSING/MAIN/job_output/rnaseqc2/rnaseqc2.*{sample}*.o")), key=os.path.getmtime)[-1]
job_status, job_start, job_stop = parse_o_file(latest)
except IndexError:
logger.warning(f"No job_output/rnaseqc2/rnaseqc2.*{sample}*.o file found")
job_json = {
"job_name": f"rnaseqc2.{sample}",
"job_start": job_start,
"job_stop": job_stop,
"job_status": job_status,
"file": [],
"metric": []
}
try:
no_expression_profiling_efficiency = no_ribosomal_contamination_count = False
filename = os.path.join(prefix_path, 'C3G/projects/MOH_PROCESSING/MAIN/metrics/rna', sample, "rnaseqc2", f'{sample}.sorted.mdup.bam.metrics.tsv')
with open(filename, 'r', encoding="utf-8") as file:
job_json["job_status"] = "COMPLETED"
for line in file:
if line.startswith("Expression Profiling Efficiency"):
value = line.split("\t")[1]
job_json["metric"].append({
"metric_name": "expression_profiling_efficiency",
"metric_value": f"{value}",
"metric_flag": "PASS",
"metric_deliverable": True
})
elif line.startswith("rRNA Rate"):
value = line.split("\t")[1]
if float(value)>0.35:
flag = "FAILED"
elif float(value)>0.1:
flag = "WARNING"
else:
flag = "PASS"
job_json["metric"].append({
"metric_name": "ribosomal_contamination_count",
"metric_value": f"{value}",
"metric_flag": f"{flag}",
"metric_deliverable": True
})
job_json["file"].append({
"location_uri": f"beluga://{filename}",
"file_name": f"{os.path.basename(filename)}"
})
except FileNotFoundError:
no_expression_profiling_efficiency = no_ribosomal_contamination_count = True
if no_expression_profiling_efficiency and no_ribosomal_contamination_count:
job_json = None
return job_json
def extract_picard_rna(sample, prefix_path):
"""
Extract picard job, files and metrics from the job_output/picard_rna_metrics/picard_rna_metrics.*{sample}*.o file.
Return: dict
"""
job_status = None
job_start = None
job_stop = None
try:
latest = sorted(glob.glob(os.path.join(prefix_path, f"C3G/projects/MOH_PROCESSING/MAIN/job_output/picard_rna_metrics/picard_rna_metrics.*{sample}*.o")), key=os.path.getmtime)[-1]
job_status, job_start, job_stop = parse_o_file(latest)
except IndexError:
logger.warning(f"No job_output/picard_rna_metrics/picard_rna_metrics.*{sample}*.o file found")
job_json = {
"job_name": f"picard.{sample}",
"job_start": job_start,
"job_stop": job_stop,
"job_status": job_status,
"file": [],
"metric": []
}
try:
no_bases_over_q30_percent = False
filename = os.path.join(prefix_path, 'C3G/projects/MOH_PROCESSING/MAIN/metrics/rna', sample + '.quality_distribution_metrics')
tester = re.compile(r'(\d+)\W+(\d+)')
with open(filename, 'r', encoding="utf-8") as file:
job_json["job_status"] = "COMPLETED"
above_30 = 0
below_30 = 0
for line in file:
if line[:1].isdigit():
test = tester.match(line)
qual = test.group(1)
count = test.group(2)
if int(qual) < 30:
below_30 += int(count)
else :
above_30 += int(count)
value = round((above_30/(above_30+below_30))*100, 2)
if int(value)<75:
flag = "FAILED"
elif int(value)<80:
flag = "WARNING"
else:
flag = "PASS"
job_json["metric"].append({
"metric_name": "bases_over_q30_percent",
"metric_value": f"{value}",
"metric_flag": f"{flag}",
"metric_deliverable": True
})
job_json["file"].append({
"location_uri": f"beluga://{filename}",
"file_name": f"{os.path.basename(filename)}"
})
except FileNotFoundError:
no_bases_over_q30_percent = True
if no_bases_over_q30_percent:
job_json = None
return job_json
def extract_kallisto_rnaseqlight(sample, prefix_path):
"""
Extract kallisto job, files and metrics from the job_output/kallisto/kallisto.*{sample}*.o file.
Return: dict
"""
job_status = None
job_start = None
job_stop = None
try:
latest = sorted(glob.glob(os.path.join(prefix_path, f"C3G/projects/MOH_PROCESSING/MAIN/job_output/kallisto/kallisto.*{sample}*.o")), key=os.path.getmtime)[-1]
job_status, job_start, job_stop = parse_o_file(latest)
except IndexError:
logger.warning(f"No job_output/kallisto/kallisto.*{sample}*.o file found")
job_json = {
"job_name": f"kallisto.{sample}",
"job_start": job_start,
"job_stop": job_stop,
"job_status": job_status,
"file": [],
"metric": []
}
filename = os.path.join(prefix_path, 'C3G/projects/MOH_PROCESSING/MAIN/kallisto', sample, 'abundance_transcripts.tsv')
job_json = add_output_file(filename, job_json, True)
filename = os.path.join(prefix_path, 'C3G/projects/MOH_PROCESSING/MAIN/kallisto', sample, 'abundance_genes.tsv')
job_json = add_output_file(filename, job_json, True)
try:
filename = os.path.join(prefix_path, 'C3G/projects/MOH_PROCESSING/MAIN/kallisto', sample, 'abundance.h5')
job_json["file"].append({
"location_uri": f"beluga://{filename}",
"file_name": f"{os.path.basename(filename)}"
})
with h5py.File(filename, 'r') as h5file:
frequencies = np.asarray(h5file['aux']['fld'])
values = np.arange(0, len(frequencies), 1)
# Calculus coming from https://stackoverflow.com/questions/46086663/how-to-get-mean-and-standard-deviation-from-a-frequency-distribution-table
ord = np.argsort(values)
cdf = np.cumsum(frequencies[ord])
median_insert_size = values[ord][np.searchsorted(cdf, cdf[-1] // 2)].astype('float64')
mean_insert_size = np.around(np.average(values, weights=frequencies), decimals=1)
job_json["job_status"] = "COMPLETED"
job_json["metric"].append({
"metric_name": "mean_insert_size",
"metric_value": f"{mean_insert_size}",
"metric_flag": "PASS",
"metric_deliverable": True
})
job_json["metric"].append({
"metric_name": "median_insert_size",
"metric_value": f"{median_insert_size}",
"metric_flag": "PASS",
"metric_deliverable": True
})
except FileNotFoundError:
logger.warning(f"{filename} not found, no kallisto metrics will be stored.")
if not job_json["file"]:
job_json = None
return job_json
def run_annofuse_rnaseqlight(patient, sample, prefix_path):
"""
Extract annofuse job and files from the job_output/run_annofuse/run_annoFuse.*{sample}*.o file.
Return: dict
"""
job_status = None
job_start = None
job_stop = None
try:
latest = sorted(glob.glob(os.path.join(prefix_path, f"C3G/projects/MOH_PROCESSING/MAIN/job_output/run_annofuse/run_annoFuse.*{sample}*.o")), key=os.path.getmtime)[-1]
job_status, job_start, job_stop = parse_o_file(latest)
except IndexError:
logger.warning(f"No job_output/run_annofuse/run_annoFuse.*{sample}*.o file found")
job_json = {
"job_name": f"run_annofuse.{patient}",
"job_start": job_start,
"job_stop": job_stop,
"job_status": job_status,
"file": []
}
filename = os.path.join(prefix_path, 'C3G/projects/MOH_PROCESSING/MAIN/fusion', sample, 'annoFuse', f'{sample}.putative_driver_fusions.tsv')
job_json = add_output_file(filename, job_json)
if not job_json["file"]:
job_json = None
return job_json
def tumour_pair_multiqc(patient, prefix_path):
"""
Extract multiqc job, files and metrics from the job_output/run_pair_multiqc/multiqc.*{patient}*.o file.
Return: dict
"""