-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbucket_delivery.py
More file actions
executable file
·1558 lines (1372 loc) · 84.2 KB
/
bucket_delivery.py
File metadata and controls
executable file
·1558 lines (1372 loc) · 84.2 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
#!/usr/bin/env python3
# standard import
import argparse
import json
import datetime
import logging
import os
import re
import csv
from collections import defaultdict
from io import StringIO
from pathlib import Path
import signal
import sys
import time
import botocore
import boto3
import globus_sdk
import markdown
from pymdownx import emoji
from bs4 import BeautifulSoup
from dateutil.parser import parse
from retry import retry
extensions = [
'markdown.extensions.tables',
'pymdownx.magiclink',
'pymdownx.betterem',
'pymdownx.tilde',
'pymdownx.emoji',
'pymdownx.tasklist',
'pymdownx.superfences',
'pymdownx.saneheaders',
'footnotes'
]
extension_configs = {
"pymdownx.magiclink": {
"repo_url_shortener": True,
"repo_url_shorthand": True,
"provider": "github",
"user": "facelessuser",
"repo": "pymdown-extensions"
},
"pymdownx.tilde": {
"subscript": False
},
"pymdownx.emoji": {
"emoji_index": emoji.emojione,
"emoji_generator": emoji.to_png_sprite,
}
}
logger = logging.getLogger(__name__)
# To remove extra logging messages with Globus > v4
logging.getLogger("globus_sdk").setLevel(logging.WARNING)
def main():
"""
Main function to prepare delivery to the bucket.
"""
parser = argparse.ArgumentParser(prog=__name__, description="Prepare delivery to the bucket.")
parser.add_argument('-i', '--input', required=True, help="The json file returned by pt_cli digest delivery.")
parser.add_argument('-l', '--list_file', required=True, help="The name of the list file for transferred files.")
# parser.add_argument('-f', '--force', required=False, help="Ignores thresholds over metrics to deliver.", action='store_true')
parser.add_argument('--ignore_alignment', required=False, help="Ignores alignments for delivery; aka doesn't deliver it.", action='store_true')
parser.add_argument('--update_metrics', required=False, help="Forces Key_metrics.csv and Warnings.html files generation.", action='store_true')
parser.add_argument('--update_methods', required=False, help="Forces Methods.html file generation.", action='store_true')
parser.add_argument('--update_readme', required=False, help="Forces Readme.html file generation.", action='store_true')
parser.add_argument('--loglevel', help='Sets logging level', choices=['ERROR', 'WARNING', 'INFO', 'DEBUG'], default='INFO')
parser.add_argument('--missing_vardict', required=False, help="Adds a message in README if all callers except cvardict are present in the ensemble vcf.", action='store_true')
args = parser.parse_args()
log_level = getattr(logging, args.loglevel.upper(), None)
if log_level is not None:
logger.setLevel(log_level)
logging.basicConfig(level=log_level, format='%(levelname)s: %(message)s')
else:
logger.setLevel(logging.INFO)
logging.basicConfig(level=log_level, format='%(levelname)s: %(message)s')
# Path to environment variables file
globus_env_file_path = find_globus_env_file()
boto3_env_file_path = os.path.expanduser('~/.config/openstack/boto3_env.sh')
# Read the environment variables from the file
read_env_file(globus_env_file_path)
read_env_file(boto3_env_file_path)
# Now you can access the environment variables
client_id = os.getenv('GLOBUS_CLI_CLIENT_ID')
client_secret = os.getenv('GLOBUS_CLI_CLIENT_SECRET')
secret_id = os.getenv('OPENSTACK_SECRET_ID')
secret_key = os.getenv('OPENSTACK_SECRET_KEY')
# Initialize the Globus SDK client
client = globus_sdk.ConfidentialAppAuthClient(client_id, client_secret)
token_response = client.oauth2_client_credentials_tokens()
# Initialize the S3 client
s3_client = boto3.client('s3',
endpoint_url='https://objets.juno.calculquebec.ca',
aws_access_key_id=secret_id,
aws_secret_access_key=secret_key,
verify=True
)
# S3 bucket details
bucket_name = 'MOH-Q'
transfer_tokens = token_response.by_resource_server['transfer.api.globus.org']
transfer_authorizer = globus_sdk.AccessTokenAuthorizer(transfer_tokens['access_token'])
transfer_client = globus_sdk.TransferClient(authorizer=transfer_authorizer)
with open(args.input, 'r') as json_file:
json_content = json.load(json_file)
experiment_nucleic_acid_type = json_content["experiment_nucleic_acid_type"]
location_endpoint = json_content["location_endpoint"]
operation_list = json_content["operation"]
now = datetime.datetime.today().strftime("%Y-%m-%dT%H.%M.%S")
for patient in json_content["specimen"]:
patient_name = patient["name"]
cohort = patient["cohort"]
institution = patient["institution"]
sample_name_dna_n = sample_name_dna_t = sample_name_rna = patient_name
dna = rna = False
for sample in patient["sample"]:
sample_name = sample["name"]
tumour = sample["tumour"]
if experiment_nucleic_acid_type == "DNA":
dna = True
if tumour:
sample_name_dna_t = sample_name
else:
sample_name_dna_n = sample_name
dedup_coverage = extract_metrics(sample, "dedup_coverage")
if not isinstance(dedup_coverage, list):
if float(dedup_coverage) <= 30 and not tumour:
logger.warning(f"Metric dedup_coverage for Sample {sample_name} is <= 30")
# if not args.force:
# dna = False
if float(dedup_coverage) <= 80 and tumour:
logger.warning(f"Metric dedup_coverage for Sample {sample_name} is <= 80")
# if not args.force:
# dna = False
else:
logger.warning(f"Multiple dedup_coverage values for Sample {sample_name}: {dedup_coverage}.")
# if not args.force:
# logger.warning(f"Skipping delivery for Sample {sample_name}. To force delivery, use '-f' option.")
# dna = False
elif experiment_nucleic_acid_type == "RNA":
rna = True
sample_name_rna = sample_name
raw_reads_count = extract_metrics(sample, "raw_reads_count")
if not isinstance(raw_reads_count, list):
if float(raw_reads_count) <= 80000000:
logger.warning(f"Metric raw_reads_count for Sample {sample_name} is <= 80.000.000")
# if not args.force:
# rna = False
else:
logger.warning(f"Multiple raw_reads_count values for Sample {sample_name}: {raw_reads_count}.")
# if not args.force:
# logger.warning(f"Skipping delivery for Sample {sample_name}. To force delivery, use '-f' option.")
# rna = False
# Folders used for Delivery
with open(f"{os.path.join(os.path.dirname(os.path.abspath(__file__)), 'globus_collections.json')}", "r") as globus_collection_file:
globus_collection = json.load(globus_collection_file)
# Input UUID
in_uuid = globus_collection["robot_endpoints"][location_endpoint]["uuid"]
# Input Folder
in_base_path = globus_collection["robot_endpoints"][location_endpoint]["base_path"]
if location_endpoint == "abacus":
# Abacus RawData is located somewhere else
# It can be /lb/robot/research/freezeman-processing
in_uuid_abacus_rawdata_freezeman = globus_collection["robot_endpoints"]["abacus_rawdata_freezeman-processing"]["uuid"]
in_base_path_abacus_rawdata_freezeman = globus_collection["robot_endpoints"]["abacus_rawdata_freezeman-processing"]["base_path"][0]
# Or /lb/robot/research/processing
in_uuid_abacus_rawdata_processing = globus_collection["robot_endpoints"]["abacus_rawdata_processing"]["uuid"]
in_base_path_abacus_rawdata_processing = globus_collection["robot_endpoints"]["abacus_rawdata_processing"]["base_path"][0]
else:
in_uuid_abacus_rawdata_freezeman = None
in_base_path_abacus_rawdata_freezeman = None
in_uuid_abacus_rawdata_processing = None
in_base_path_abacus_rawdata_processing = None
# Output UUID
out_uuid = globus_collection["robot_endpoints"]["sd4h"]["uuid"]
# Output Folder
out_base_path = globus_collection["robot_endpoints"]["sd4h"]["base_path"][0]
# Contains Warnings.txt Readme.txt Log.txt and all subfolders
out_folder = os.path.join(out_base_path, institution, cohort, patient_name)
# Contains raw bams and fastqs
raw_folder = os.path.join(out_folder, "raw_data")
# Contains all variants the subfolder
var_folder = os.path.join(out_folder, "variants")
# Contains all the vcfs from the callers
cal_folder = os.path.join(var_folder, "caller_vcfs")
# Contains raw cnv
raw_cnv_folder = os.path.join(out_folder, "raw_cnv")
# Contains the analysis bams
alignment_folder = os.path.join(out_folder, "alignment")
# Contains the ini files
param_folder = os.path.join(out_folder, "parameters")
# Contains the reports
reports_folder = os.path.join(out_folder, "reports")
pcgr_folder = os.path.join(reports_folder, "pcgr")
# Contains expression from Kallisto
expression_folder = os.path.join(out_folder, "expression")
# Contains all svariants
svar_folder = os.path.join(out_folder, "svariants")
linx_folder = os.path.join(svar_folder, "linx")
warning_file = os.path.join(out_folder, "Warnings.html")
readme_file = os.path.join(out_folder, "Readme.html")
methods_file = os.path.join(out_folder, "Methods.html")
key_metrics_file = os.path.join(out_folder, "Key_metrics.csv")
vardict_note_file = os.path.join(var_folder, "README.txt")
file_dict = {}
# For Abacus rawdata special handling
file_dict_rawdata_freezeman = {}
file_dict_rawdata_processing = {}
ini_dict = {}
metrics_dict = defaultdict(lambda: None)
src_abs_by_dest = {}
# Check if the key metrics file exists
key_metrics_file_outpath = remove_path_parts(key_metrics_file, out_base_path)
if file_exists(s3_client, bucket_name, key_metrics_file_outpath):
response = s3_client.get_object(Bucket=bucket_name, Key=key_metrics_file_outpath)
file_content = response['Body'].read().decode('utf-8')
existing_metrics = parse_csv(file_content)
if existing_metrics and 'Readset' not in existing_metrics[0]:
for row in existing_metrics:
row['Readset'] = 'NA'
else:
existing_metrics = []
# Check if the warning file exists
warning_file_outpath = remove_path_parts(warning_file, out_base_path)
if file_exists(s3_client, bucket_name, warning_file_outpath):
response = s3_client.get_object(Bucket=bucket_name, Key=warning_file_outpath)
warnings_content = response['Body'].read().decode('utf-8')
else:
warnings_content = ""
# Populates dna data
if dna:
deliver_dna(
args.ignore_alignment,
raw_folder,
var_folder,
svar_folder,
linx_folder,
cal_folder,
raw_cnv_folder,
alignment_folder,
reports_folder,
pcgr_folder,
patient,
out_base_path,
in_base_path,
in_base_path_abacus_rawdata_freezeman,
in_base_path_abacus_rawdata_processing,
location_endpoint,
file_dict,
file_dict_rawdata_freezeman,
file_dict_rawdata_processing,
metrics_dict,
src_abs_by_dest
)
for index, operation_object in enumerate(operation_list):
ini_dict[os.path.join(param_folder, f"{patient_name}.TumourPair.{index+1}.ini")] = operation_object["config_data"]
# Populates rna data
elif rna:
deliver_rna(
args.ignore_alignment,
raw_folder,
expression_folder,
var_folder,
alignment_folder,
reports_folder,
pcgr_folder,
patient,
out_base_path,
in_base_path,
in_base_path_abacus_rawdata_freezeman,
in_base_path_abacus_rawdata_processing,
location_endpoint,
file_dict,
file_dict_rawdata_freezeman,
file_dict_rawdata_processing,
metrics_dict,
src_abs_by_dest
)
for index, operation_object in enumerate(operation_list):
match = re.search(r'-t (\w+)', operation_object["cmd_line"])
protocol = match.group(1) if match else None
if protocol == "cancer":
ini_dict[os.path.join(param_folder, f"{patient_name}.RNA.Variants.{index+1}.ini")] = operation_object["config_data"]
else:
ini_dict[os.path.join(param_folder, f"{patient_name}.RNA.Light.{index+1}.ini")] = operation_object["config_data"]
# Not implemented yet
# if rna and dna:
# os.makedirs(var_folder, exist_ok=True)
# final_vcf = extract_fileloc_field(connection, sample.sample, "Final_VCF")
# updated = get_link_log(final_vcf, var_folder, f"{sample.sample_true}.vcf.gz", log, updated, old_log)
already_delivered_files = list_s3_files(s3_client, bucket_name, remove_path_parts(out_folder, out_base_path))
# for src_file, dest_file in file_dict.items():
# print(f"Transferring {src_file} to {dest_file}")
transfer_label = f"Delivery_{patient_name}_{experiment_nucleic_acid_type}_{now}"
logger.debug(f"Transfer label: {transfer_label}")
# list_file = os.path.join(args.list_file, f"Delivery_{patient_name}_{experiment_nucleic_acid_type}_{now}.list")
transferred_files = []
# Transfer for Abacus rawdata only
if file_dict_rawdata_freezeman or file_dict_rawdata_processing:
if file_dict_rawdata_freezeman:
logger.debug(f"Transferring Abacus rawdata files: {file_dict_rawdata_freezeman}")
task_id = transfer_files_with_sync(in_uuid_abacus_rawdata_freezeman, out_uuid, file_dict_rawdata_freezeman, transfer_client, f"{transfer_label}_rawdata")
if file_dict_rawdata_processing:
logger.debug(f"Transferring Abacus rawdata files: {file_dict_rawdata_processing}")
task_id = transfer_files_with_sync(in_uuid_abacus_rawdata_processing, out_uuid, file_dict_rawdata_processing, transfer_client, f"{transfer_label}_rawdata")
# display_transfer_status(transfer_client, task_id, s3_client, bucket_name)
# transferred_files, _ = get_transfer_event_log(transfer_client, task_id, s3_client, bucket_name)
try:
transferred_files, _ = display_transfer_status(transfer_client, task_id, s3_client, bucket_name)
if not transferred_files:
logger.warning("No new Abacus raw data file were transferred.")
else:
already_delivered_files.extend(format_timestamps(transferred_files))
except Exception as e:
logger.exception("Error during transfer or monitoring")
print(f"ERROR: {e}")
sys.exit(1)
# Transfer for all endpoints (including abacus after rawdata split)
if file_dict:
logger.debug(f"Transferring files: {file_dict}")
try:
task_id = transfer_files_with_sync(in_uuid, out_uuid, file_dict, transfer_client, transfer_label)
# display_transfer_status(transfer_client, task_id, s3_client, bucket_name)
# transferred_files, _ = get_transfer_event_log(transfer_client, task_id, s3_client, bucket_name)
transferred_files, _ = display_transfer_status(transfer_client, task_id, s3_client, bucket_name)
if not transferred_files:
logger.warning("No new file were transferred.")
else:
already_delivered_files.extend(format_timestamps(transferred_files))
# already_delivered_files.extend(format_timestamps(transferred_files))
except Exception as e:
logger.exception("Error during transfer or monitoring")
print(f"ERROR: {e}")
sys.exit(1)
# task_id = transfer_files_with_sync(in_uuid, out_uuid, file_dict, transfer_client, transfer_label)
# display_transfer_status(transfer_client, task_id, s3_client, bucket_name)
# transferred_files, _ = get_transfer_event_log(transfer_client, task_id, s3_client, bucket_name)
# transferred_files = format_timestamps(transferred_files)
# already_delivered_files.extend(transferred_files)
all_delivered_files = list(set(already_delivered_files))
if transferred_files:
lines = []
for dest_path, _ in transferred_files:
src_abs = src_abs_by_dest.get(dest_path)
if src_abs:
lines.append(f"{src_abs} {os.path.join(out_base_path, dest_path)}")
else:
logger.warning(f"Missing source mapping for destination: {dest_path}")
with open(args.list_file, 'w') as list_file:
list_file.write('\n'.join(lines))
for ini_file_name, ini_content in ini_dict.items():
s3_client.put_object(Bucket=bucket_name, Key=remove_path_parts(ini_file_name, out_base_path), Body=ini_content)
# Read already delivered warnings
existing_warnings_dict, soup = parse_existing_warnings(warnings_content)
updated_warnings_dict = update_warnings(existing_warnings_dict, metrics_dict, soup)
updated_warnings_content = generate_updated_warnings_content(updated_warnings_dict, soup)
s3_client.put_object(Bucket=bucket_name, Key=remove_path_parts(warning_file, out_base_path), Body=updated_warnings_content)
else:
logger.warning("No new file were transferred. Skipping...")
# Add methods file
if args.update_methods or transferred_files:
methods_content = generate_methods()
s3_client.put_object(Bucket=bucket_name, Key=remove_path_parts(methods_file, out_base_path), Body=methods_content)
if args.update_metrics or transferred_files:
# Read already delivered key metrics
updated_metrics_list = update_metrics(existing_metrics, metrics_dict)
metrics_content = generate_csv_content(updated_metrics_list)
s3_client.put_object(Bucket=bucket_name, Key=remove_path_parts(key_metrics_file, out_base_path), Body=metrics_content)
if args.update_readme or transferred_files:
readme_content = generate_readme(patient_name, sample_name_dna_n, sample_name_dna_t, sample_name_rna, all_delivered_files, args.missing_vardict)
s3_client.put_object(Bucket=bucket_name, Key=remove_path_parts(readme_file, out_base_path), Body=readme_content)
if args.missing_vardict:
vardict_note_content = "Please note that VarDict was not included among the callers in the ensemble approach due to its high resource usage."
s3_client.put_object(Bucket=bucket_name, Key=remove_path_parts(vardict_note_file, out_base_path), Body=vardict_note_content)
print("Transfer script completed successfully.")
def extract_metrics(sample_content, metric_name):
"""Extracts a metric from a sample content dictionary.
Returns a float if all values are the same, otherwise returns a list of unique float values.
"""
metric_values = [
metric["value"]
for readset in sample_content["readset"]
for metric in readset["metric"]
if metric["name"] == metric_name
]
if not metric_values:
raise ValueError(f"No values found for metric '{metric_name}' and sample '{sample_content['name']}' for none of its readsets.")
unique_values = sorted(set(float(v) for v in metric_values))
if len(unique_values) == 1:
return unique_values[0]
return unique_values
def get_abacus_rawdata_name_counts(sample, in_base_path_abacus_rawdata_freezeman, in_base_path_abacus_rawdata_processing):
"""Count Abacus rawdata file names for a sample to detect duplicate destination names."""
duplicate_name_counts = defaultdict(int)
for readset in sample["readset"]:
for file in readset["file"]:
file_location = file["location"]
if (
in_base_path_abacus_rawdata_freezeman
and file_location.startswith(in_base_path_abacus_rawdata_freezeman)
) or (
in_base_path_abacus_rawdata_processing
and file_location.startswith(in_base_path_abacus_rawdata_processing)
):
duplicate_name_counts[file["name"]] += 1
return duplicate_name_counts
def maybe_rename_abacus_rawdata_file(file_name, readset_name, duplicate_name_counts):
"""Rename duplicated Abacus .sorted.bam/.sorted.bai files to include readset name."""
if duplicate_name_counts.get(file_name, 0) <= 1:
return file_name
match = re.search(r"\.sorted\.(bam|bai)$", file_name)
if not match:
return file_name
extension = match.group(1)
return f"{readset_name}.sorted.{extension}"
def deliver_dna(
ignore_alignment,
raw_folder,
var_folder,
svar_folder,
linx_folder,
cal_folder,
raw_cnv_folder,
alignment_folder,
reports_folder,
pcgr_folder,
patient,
out_base_path,
in_base_path,
in_base_path_abacus_rawdata_freezeman,
in_base_path_abacus_rawdata_processing,
location_endpoint,
file_dict,
file_dict_rawdata_freezeman,
file_dict_rawdata_processing,
metrics_dict,
src_abs_by_dest
):
metric_mapping = {
"raw_mean_coverage": "Raw_Mean_Coverage",
"raw_duplication_rate": "Raw_Duplication_Rate",
"raw_median_insert_size": "Raw_Median_Insert_Size",
"raw_mean_insert_size": "Raw_Mean_Insert_Size",
"raw_reads_count": "Raw_Reads_Count",
"median_insert_size": "Median_Insert_Size",
"bases_over_q30_percent": "WGS_Bases_Over_Q30",
"aligned_reads_count": "WGS_Min_Aligned_Reads_Delivered",
"dedup_coverage": "WGS_Dedup_Coverage",
"contamination": "WGS_Contamination",
"concordance": "Concordance",
"purity": "Purity"
}
# Compile the regex patterns
variant_pattern = re.compile(r"\.ensemble\.(germline|somatic)\.vt\.annot\.vcf\.gz|\.purple_ensemble\.zip$")
cal_pattern = re.compile(r"(mutect2|strelka2|vardict|varscan2)\.(somatic|germline)\.vt\.vcf\.gz")
svar_pattern = re.compile(
r"(gridss|gripss\.filtered\.(somatic|germline))\.vcf\.gz|driver\.catalog\.(somatic|germline)\.tsv|circos\.png$|\.purple_sv\.zip$"
)
reports_pattern = re.compile(r"(\.multiqc|\.pcgr_acmg\.grch38\.flexdb)\.html$|\.(cpsr|pcgr)\.zip$")
pcgr_pattern = re.compile(r"(\.pcgr_acmg\.grch38\.(maf|vcf\.gz|snvs_indels\.tiers\.tsv|cna_segments\.tsv\.gz))$")
for sample in patient["sample"]:
sample_name = sample["name"]
duplicate_name_counts = get_abacus_rawdata_name_counts(
sample,
in_base_path_abacus_rawdata_freezeman,
in_base_path_abacus_rawdata_processing,
) if location_endpoint == "abacus" else {}
for readset in sample["readset"]:
readset_name = readset["name"]
for file in readset["file"]:
file_name = file["name"]
# Handle Abacus rawdata path located in /lb/robot/research/freezeman-processing/novaseqx/
if location_endpoint == "abacus":
if file["location"].startswith(in_base_path_abacus_rawdata_freezeman):
file_location = remove_path_parts(file["location"], in_base_path_abacus_rawdata_freezeman)
file_name = maybe_rename_abacus_rawdata_file(file_name, readset_name, duplicate_name_counts)
# To workaround issue with RP naming regarding raw data being non unique we have to use file_location for file_name
dest_path = os.path.join(remove_path_parts(raw_folder, out_base_path), file_name)
file_dict_rawdata_freezeman[file_location] = dest_path
src_abs_by_dest[dest_path] = file["location"]
continue
if file["location"].startswith(in_base_path_abacus_rawdata_processing):
file_location = remove_path_parts(file["location"], in_base_path_abacus_rawdata_processing)
file_name = maybe_rename_abacus_rawdata_file(file_name, readset_name, duplicate_name_counts)
# To workaround issue with RP naming regarding raw data being non unique we have to use file_location for file_name
dest_path = os.path.join(remove_path_parts(raw_folder, out_base_path), file_name)
file_dict_rawdata_processing[file_location] = dest_path
src_abs_by_dest[dest_path] = file["location"]
continue
# Usual case
used_base = None
for base_path in in_base_path:
if file["location"].startswith(base_path):
file_location = remove_path_parts(file["location"], base_path)
used_base = base_path
break
# raw_data
if "MAIN/raw_reads/" in file_location or "GQ_STAGING" in file_location:
# To workaround issue with RP naming regarding raw data being non unique we have to use file_location for file_name
dest_path = os.path.join(remove_path_parts(raw_folder, out_base_path), os.path.basename(file_location))
file_dict[file_location] = dest_path
if used_base is not None:
src_abs_by_dest[dest_path] = os.path.join(used_base, file_location)
# variants
elif variant_pattern.search(file_name):
dest_path = os.path.join(remove_path_parts(var_folder, out_base_path), file_name)
file_dict[file_location] = dest_path
if used_base is not None:
src_abs_by_dest[dest_path] = os.path.join(used_base, file_location)
# variants/caller_vcfs
elif cal_pattern.search(file_name):
dest_path = os.path.join(remove_path_parts(cal_folder, out_base_path), file_name)
file_dict[file_location] = dest_path
if used_base is not None:
src_abs_by_dest[dest_path] = os.path.join(used_base, file_location)
# raw_cnv
elif "cnvkit.vcf.gz" in file_name:
dest_path = os.path.join(remove_path_parts(raw_cnv_folder, out_base_path), file_name)
file_dict[file_location] = dest_path
if used_base is not None:
src_abs_by_dest[dest_path] = os.path.join(used_base, file_location)
# alignment
elif "MAIN/alignment/" in file_location and not ignore_alignment:
# Rename to remove extra part from dna bams
file_name = file_name.replace(".sorted.dup.recal", "")
dest_path = os.path.join(remove_path_parts(alignment_folder, out_base_path), file_name)
file_dict[file_location] = dest_path
if used_base is not None:
src_abs_by_dest[dest_path] = os.path.join(used_base, file_location)
# svariants
elif svar_pattern.search(file_name):
dest_path = os.path.join(remove_path_parts(svar_folder, out_base_path), file_name)
file_dict[file_location] = dest_path
if used_base is not None:
src_abs_by_dest[dest_path] = os.path.join(used_base, file_location)
# svariants/linx
elif "linx" in file_location:
dest_path = os.path.join(remove_path_parts(linx_folder, out_base_path), file_name)
file_dict[file_location] = dest_path
if used_base is not None:
src_abs_by_dest[dest_path] = os.path.join(used_base, file_location)
# reports
elif reports_pattern.search(file_name):
match = reports_pattern.search(file_name)
if match:
# Insert '_D' before the matched part to differentiate between DNA and RNA reports
start = match.start()
file_name = file_name[:start] + "_D" + file_name[start:]
# Rename pcgr report
if "pcgr_acmg" in file_name:
file_name = file_name.replace("_acmg.grch38.flexdb", "")
dest_path = os.path.join(remove_path_parts(reports_folder, out_base_path), file_name)
file_dict[file_location] = dest_path
if used_base is not None:
src_abs_by_dest[dest_path] = os.path.join(used_base, file_location)
# reports/pcgr
elif pcgr_pattern.search(file_name):
match = pcgr_pattern.search(file_name)
if match:
# Insert '_D' before the matched part to differentiate between DNA and RNA reports
start = match.start()
file_name = file_name[:start] + "_D" + file_name[start:]
dest_path = os.path.join(remove_path_parts(pcgr_folder, out_base_path), file_name)
file_dict[file_location] = dest_path
if used_base is not None:
src_abs_by_dest[dest_path] = os.path.join(used_base, file_location)
for metric in readset["metric"]:
metric_name = metric["name"]
metric_value = metric["value"]
metric_flag = metric["flag"]
# metric_aggregate = metric["aggregate"]
# update_metrics(metrics_dict, metric_mapping, sample_name, readset_name, metric_name, metric_value, metric_flag)
update_metrics_dict(metrics_dict, metric_mapping, sample_name, readset_name, metric_name, metric_value, metric_flag)
def deliver_rna(
ignore_alignment,
raw_folder,
expression_folder,
var_folder,
alignment_folder,
reports_folder,
pcgr_folder,
patient,
out_base_path,
in_base_path,
in_base_path_abacus_rawdata_freezeman,
in_base_path_abacus_rawdata_processing,
location_endpoint,
file_dict,
file_dict_rawdata_freezeman,
file_dict_rawdata_processing,
metrics_dict,
src_abs_by_dest
):
metric_mapping = {
"raw_mean_coverage": "Raw_Mean_Coverage",
"raw_duplication_rate": "Raw_Duplication_Rate",
"raw_median_insert_size": "Raw_Median_Insert_Size",
"raw_mean_insert_size": "Raw_Mean_Insert_Size",
"raw_reads_count": "Raw_Reads_Count",
"median_insert_size": "Median_Insert_Size",
"mean_insert_size": "Mean_Insert_Size",
"expression_profiling_efficiency": "WTS_Expression_Profiling_Efficiency",
"aligned_reads_ratio": "WTS_Aligned_Reads",
"rrna_rate": "WTS_rRNA_contamination",
}
# Compile the regex patterns
expression_pattern = re.compile(r"abundance_(transcripts|genes)\.tsv$")
variant_pattern = re.compile(r"\.hc\.vt\.annot(\.flt)?\.vcf\.gz")
reports_pattern = re.compile(r"(\.multiqc|\.pcgr_acmg\.grch38\.flexdb)\.html$|\.putative_driver_fusions\.tsv$")
pcgr_pattern = re.compile(r"(\.pcgr_acmg\.grch38\.(maf|snvs_indels\.tiers\.tsv))$")
for sample in patient["sample"]:
sample_name = sample["name"]
duplicate_name_counts = get_abacus_rawdata_name_counts(
sample,
in_base_path_abacus_rawdata_freezeman,
in_base_path_abacus_rawdata_processing,
) if location_endpoint == "abacus" else {}
for readset in sample["readset"]:
readset_name = readset["name"]
for file in readset["file"]:
file_name = file["name"]
# Handle Abacus rawdata path located in /lb/robot/research/freezeman-processing/novaseqx/
if location_endpoint == "abacus":
if file["location"].startswith(in_base_path_abacus_rawdata_freezeman):
file_location = remove_path_parts(file["location"], in_base_path_abacus_rawdata_freezeman)
file_name = maybe_rename_abacus_rawdata_file(file_name, readset_name, duplicate_name_counts)
# To workaround issue with RP naming regarding raw data being non unique we have to use file_location for file_name
dest_path = os.path.join(remove_path_parts(raw_folder, out_base_path), file_name)
file_dict_rawdata_freezeman[file_location] = dest_path
src_abs_by_dest[dest_path] = file["location"]
continue
if file["location"].startswith(in_base_path_abacus_rawdata_processing):
file_location = remove_path_parts(file["location"], in_base_path_abacus_rawdata_processing)
file_name = maybe_rename_abacus_rawdata_file(file_name, readset_name, duplicate_name_counts)
# To workaround issue with RP naming regarding raw data being non unique we have to use file_location for file_name
dest_path = os.path.join(remove_path_parts(raw_folder, out_base_path), file_name)
file_dict_rawdata_freezeman[file_location] = dest_path
src_abs_by_dest[dest_path] = file["location"]
continue
# Usual case
used_base = None
for base_path in in_base_path:
if file["location"].startswith(base_path):
file_location = remove_path_parts(file["location"], base_path)
used_base = base_path
break
# raw_data
if "MAIN/raw_reads/" in file_location or "GQ_STAGING" in file_location:
dest_path = os.path.join(remove_path_parts(raw_folder, out_base_path), file_name)
file_dict[file_location] = dest_path
if used_base is not None:
src_abs_by_dest[dest_path] = os.path.join(used_base, file_location)
# expression
elif expression_pattern.search(file_name):
# Rename to include sample name in file
file_name = f"{sample_name}.{file_name}"
dest_path = os.path.join(remove_path_parts(expression_folder, out_base_path), file_name)
file_dict[file_location] = dest_path
if used_base is not None:
src_abs_by_dest[dest_path] = os.path.join(used_base, file_location)
# variants
elif variant_pattern.search(file_name):
# Rename as it's delivered as filt and not flt
file_name = file_name.replace("flt", "filt")
dest_path = os.path.join(remove_path_parts(var_folder, out_base_path), file_name)
file_dict[file_location] = dest_path
if used_base is not None:
src_abs_by_dest[dest_path] = os.path.join(used_base, file_location)
# reports
elif reports_pattern.search(file_name):
if "putative_driver_fusions" in file_name:
file_name = file_name.replace("putative_driver_fusions", "anno_fuse")
# Anno Fuse is not renamed by patient but keeping sample name
else:
# Rename to patient name instead of sample name
file_name = file_name.replace(sample_name, patient["name"])
match = reports_pattern.search(file_name)
if match:
# Insert '_R' before the matched part to differentiate between DNA and RNA reports
start = match.start()
file_name = file_name[:start] + "_R" + file_name[start:]
# Rename pcgr report
if "pcgr_acmg" in file_name:
file_name = file_name.replace("_acmg.grch38.flexdb", "")
dest_path = os.path.join(remove_path_parts(reports_folder, out_base_path), file_name)
file_dict[file_location] = dest_path
if used_base is not None:
src_abs_by_dest[dest_path] = os.path.join(used_base, file_location)
# reports/pcgr
elif pcgr_pattern.search(file_name):
match = pcgr_pattern.search(file_name)
if match:
# Insert '_D' before the matched part to differentiate between DNA and RNA reports
start = match.start()
file_name = file_name[:start] + "_R" + file_name[start:]
# Rename to patient name instead of sample name
file_name = file_name.replace(sample_name, patient["name"])
dest_path = os.path.join(remove_path_parts(pcgr_folder, out_base_path), file_name)
file_dict[file_location] = dest_path
if used_base is not None:
src_abs_by_dest[dest_path] = os.path.join(used_base, file_location)
# alignment has to go as last if because otehr regex files are located under alignment folder
elif "MAIN/alignment/" in file_location and not ignore_alignment:
# Rename to remove extra part from rna bams
file_name = file_name.replace("sorted.mdup.split.recal", "variants")
dest_path = os.path.join(remove_path_parts(alignment_folder, out_base_path), file_name)
file_dict[file_location] = dest_path
if used_base is not None:
src_abs_by_dest[dest_path] = os.path.join(used_base, file_location)
for metric in readset["metric"]:
metric_name = metric["name"]
metric_value = metric["value"]
metric_flag = metric["flag"]
# metric_aggregate = metric["aggregate"]
# update_metrics(metrics_dict, metric_mapping, sample_name, readset_name, metric_name, metric_value, metric_flag)
update_metrics_dict(metrics_dict, metric_mapping, sample_name, readset_name, metric_name, metric_value, metric_flag)
def initialize_metrics(metric_mapping):
metrics = {key: "NA" for key in metric_mapping.values()}
metrics["Flags"] = "NA"
metrics["Fails"] = "NA"
return metrics
def update_metrics(existing_metrics, new_metrics_dict):
updated_metrics = {row['Readset']: row for row in existing_metrics}
for readset_name, metrics in new_metrics_dict.items():
if readset_name in updated_metrics:
updated_metrics[readset_name].update(metrics)
else:
new_row = {
'Sample': metrics.get('sample_name', 'NA'),
'Readset': readset_name,
'WGS_Bases_Over_Q30': metrics.get('WGS_Bases_Over_Q30', 'NA'),
'WGS_Min_Aligned_Reads_Delivered': metrics.get('WGS_Min_Aligned_Reads_Delivered', 'NA'),
'Raw_Mean_Coverage': metrics.get('Raw_Mean_Coverage', 'NA'),
'WGS_Dedup_Coverage': metrics.get('WGS_Dedup_Coverage', 'NA'),
'Raw_Duplication_Rate': metrics.get('Raw_Duplication_Rate', 'NA'),
'Raw_Median_Insert_Size': metrics.get('Raw_Median_Insert_Size', 'NA'),
'Raw_Mean_Insert_Size': metrics.get('Raw_Mean_Insert_Size', 'NA'),
'Median_Insert_Size': metrics.get('Median_Insert_Size', 'NA'),
'Mean_Insert_Size': metrics.get('Mean_Insert_Size', 'NA'),
'WGS_Contamination': metrics.get('WGS_Contamination', 'NA'),
'Concordance': metrics.get('Concordance', 'NA'),
'Purity': metrics.get('Purity', 'NA'),
'Raw_Reads_Count': metrics.get('Raw_Reads_Count', 'NA'),
'WTS_Exonic_Rate': metrics.get('WTS_Exonic_Rate', 'NA'),
'WTS_Aligned_Reads': metrics.get('WTS_Aligned_Reads', 'NA'),
'WTS_rRNA_contamination': metrics.get('WTS_rRNA_contamination', 'NA'),
'WTS_Expression_Profiling_Efficiency': metrics.get('WTS_Expression_Profiling_Efficiency', 'NA'),
'Flags': metrics.get('Flags', 'NA'),
'Fails': metrics.get('Fails', 'NA')
}
updated_metrics[readset_name] = new_row
return list(updated_metrics.values())
def update_metrics_dict(metrics_dict, metric_mapping, sample_name, readset_name, metric_name, metric_value, metric_flag):
if readset_name not in metrics_dict:
metrics_dict[readset_name] = initialize_metrics(metric_mapping)
metrics_dict[readset_name]["Sample"] = sample_name
if metric_name in metric_mapping:
metrics_dict[readset_name][metric_mapping[metric_name]] = metric_value
if metric_flag == "WARNING":
# print(f"Sample name: {sample_name}, Metric name: {metric_name}, Metric flag: {metric_flag}")
if metrics_dict[readset_name]["Flags"] == "NA":
metrics_dict[readset_name]["Flags"] = metric_mapping[metric_name]
else:
metrics_dict[readset_name]["Flags"] += f";{metric_mapping[metric_name]}"
elif metric_flag == "FAILED":
if metrics_dict[readset_name]["Fails"] == "NA":
metrics_dict[readset_name]["Fails"] = metric_mapping[metric_name]
else:
metrics_dict[readset_name]["Fails"] += f";{metric_mapping[metric_name]}"
def generate_key_metrics(metrics_dict):
metrics_csv = []
headers = "Sample,Readset,WGS_Bases_Over_Q30,WGS_Min_Aligned_Reads_Delivered,Raw_Mean_Coverage,WGS_Dedup_Coverage,Raw_Duplication_Rate,Raw_Median_Insert_Size,Raw_Mean_Insert_Size,Median_Insert_Size,Mean_Insert_Size,WGS_Contamination,Concordance,Purity,Raw_Reads_Count,WTS_Exonic_Rate,WTS_Aligned_Reads,WTS_rRNA_contamination,WTS_Expression_Profiling_Efficiency,Flags,Fails"
metrics_csv.append(headers)
for readset_name, metrics in metrics_dict.items():
metrics_csv.append(",".join([
metrics.get('sample_name', 'NA'),
readset_name,
metrics.get('WGS_Bases_Over_Q30', 'NA'),
metrics.get('WGS_Min_Aligned_Reads_Delivered', 'NA'),
metrics.get('Raw_Mean_Coverage', 'NA'),
metrics.get('WGS_Dedup_Coverage', 'NA'),
metrics.get('Raw_Duplication_Rate', 'NA'),
metrics.get('Raw_Median_Insert_Size', 'NA'),
metrics.get('Raw_Mean_Insert_Size', 'NA'),
metrics.get('Median_Insert_Size', 'NA'),
metrics.get('Mean_Insert_Size', 'NA'),
metrics.get('WGS_Contamination', 'NA'),
metrics.get('Concordance', 'NA'),
metrics.get('Purity', 'NA'),
metrics.get('Raw_Reads_Count', 'NA'),
metrics.get('WTS_Exonic_Rate', 'NA'),
metrics.get('WTS_Aligned_Reads', 'NA'),
metrics.get('WTS_rRNA_contamination', 'NA'),
metrics.get('WTS_Expression_Profiling_Efficiency', 'NA'),
metrics.get('Flags', 'NA'),
metrics.get('Fails', 'NA')
]))
return "\n".join(metrics_csv)
def parse_existing_warnings(warnings_content):
# If the content is empty or just whitespace, use a minimal fallback
if not warnings_content.strip():
warnings_content = "<table></table>"
# Wrap the content in a full HTML structure to ensure soup.body exists
wrapped_content = f"<html><head></head><body>{warnings_content}</body></html>"
soup = BeautifulSoup(wrapped_content, 'html.parser')
table = soup.find('table')
warnings_dict = {}
if table:
rows = table.find_all('tr')[1:] # Skip header row
for row in rows:
cols = row.find_all('td')
if len(cols) >= 3:
sample_name = cols[0].text.strip()
flags = cols[1].text.strip()
fails = cols[2].text.strip()
for col in cols:
col.string = col.text.replace('\xa0', '').strip()
warnings_dict[sample_name] = {
'Flags': flags,
'Fails': fails,
'row': row
}
return warnings_dict, soup
def update_warnings(existing_warnings_dict, metrics_dict, soup):
for _, metrics in metrics_dict.items():
sample_name = metrics.get('sample_name', 'NA')
if sample_name in existing_warnings_dict:
existing_warnings_dict[sample_name]['Flags'] = metrics.get('Flags', 'NA')
existing_warnings_dict[sample_name]['Fails'] = metrics.get('Fails', 'NA')
existing_warnings_dict[sample_name]['row'].find_all('td')[1].string = metrics.get('Flags', 'NA')
existing_warnings_dict[sample_name]['row'].find_all('td')[2].string = metrics.get('Fails', 'NA')
else:
new_row = soup.new_tag('tr')
new_row.append(soup.new_tag('td', style="text-align: left; padding: 8px; border: 1px solid #ddd;"))
new_row.append(soup.new_tag('td', style="text-align: left; padding: 8px; border: 1px solid #ddd;"))
new_row.append(soup.new_tag('td', style="text-align: left; padding: 8px; border: 1px solid #ddd;"))
new_row.contents[0].string = sample_name
new_row.contents[1].string = metrics.get('Flags', 'NA')
new_row.contents[2].string = metrics.get('Fails', 'NA')
existing_warnings_dict[sample_name] = {
'Flags': metrics.get('Flags', 'NA'),
'Fails': metrics.get('Fails', 'NA'),
'row': new_row
}
return existing_warnings_dict
def generate_updated_warnings_content(warnings_dict, soup):
table = soup.find('table')
if not table:
# Create a new table if it doesn't exist
table = soup.new_tag('table')
thead = soup.new_tag('thead')
header_row = soup.new_tag('tr')
for header in ['Sample Name', 'Flags', 'Fails']:
th = soup.new_tag('th')
th.string = header
header_row.append(th)
thead.append(header_row)
table.append(thead)
tbody = soup.new_tag('tbody')
table.append(tbody)
soup.body.append(table) # Or insert it appropriately
else:
# Ensure thead exists
thead = table.find('thead')
if not thead:
thead = soup.new_tag('thead')
header_row = soup.new_tag('tr')
for header in ['Sample Name', 'Flags', 'Fails']:
th = soup.new_tag('th')
th.string = header
header_row.append(th)
thead.append(header_row)
table.insert(0, thead) # Insert before tbody
# Ensure tbody exists
tbody = table.find('tbody')
if not tbody:
tbody = soup.new_tag('tbody')
table.append(tbody)
else:
tbody.clear()
for metrics in warnings_dict.values():
tbody.append(metrics['row'])
# Ensure the <head> element exists
if not soup.head:
head = soup.new_tag('head')
soup.insert(0, head)
else:
head = soup.head
# Add CSS styles for better readability
style = soup.new_tag('style')
style.string = """
table {
width: 100%;
border-collapse: collapse;
margin: 25px 0;
font-size: 18px;
text-align: left;
}
th, td {
padding: 12px;
border: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
tr:hover {
background-color: #f1f1f1;
}
"""
head.append(style)
return str(soup)