-
Notifications
You must be signed in to change notification settings - Fork 0
/
dare.py
executable file
·3813 lines (3072 loc) · 160 KB
/
dare.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
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 15 12:27:07 2020
@author: rjovelin
"""
import argparse
import os
import matplotlib.pyplot as plt
import numpy as np
import time
import math
import requests
import gzip
import sys
import json
import pathlib
import sqlite3
from jinja2 import Environment, FileSystemLoader
from weasyprint import HTML
from weasyprint import CSS
import re
def get_libraries(library_file):
'''
(str) -> dict
Returns a dictionary with library, run or libray, lane, run key, value pairs.
Note: runs need to be specified for all libraries
Parameters
----------
- sample_file (str): Path to sample file. Sample file is a tab delimited file
that includes 2 or 3 columns columns. The first column is always
the library alias, and the second is lane or run id
'''
D = {}
infile = open(library_file)
content = infile.read().strip().split('\n')
for i in range(len(content)):
content[i] = content[i].split('\t')
infile.close()
# check that all lines have the same number of columns
if all(map(lambda x: len(x) == 2 or len(x) == 3 , content)) == False:
raise ValueError('File must have 2 or 3 columns')
if all(map(lambda x: '_' in x[-1], content)) == False:
raise ValueError('Run id must be the last column')
for i in content:
library = i[0]
run = i[-1]
if len(i) == 2:
lane = ''
elif len(i) == 3:
lane = int(i[1])
if library not in D:
D[library] = {}
if run not in D[library]:
D[library][run] = []
D[library][run].append(lane)
return D
def get_FPR_records(project, provenance):
'''
(str, str) -> list
Returns a list with all the records from the File Provenance Report for a given project.
Each individual record in the list is a list of fields
Parameters
----------
- project (str): Name of a project or run as it appears in File Provenance Report
- provenance (str): Path to File Provenance Report.
'''
# get the records for a single project
records = []
# open provenance for reading. allow gzipped file or not
if is_gzipped(provenance):
infile = gzip.open(provenance, 'rt', errors='ignore')
else:
infile = open(provenance)
for line in infile:
if project in line:
line = line.rstrip().split('\t')
if project == line[1]:
records.append(line)
infile.close()
return records
def parse_fpr_records(provenance, project, workflow, prefix=None):
'''
(str, str, list, str | None) -> dict
Returns a dictionary with file info extracted from FPR for a given project
and a given workflow if workflow is speccified.
Parameters
----------
- provenance (str): Path to File Provenance Report
- project (str): Project name as it appears in File Provenance Report.
- workflow (list): List of workflows used to generate the output files.
- prefix (str | None): Prefix used to recover file full paths when File Provevance contains relative paths.
'''
# create a dict {file_swid: {file info}}
D = {}
# get all the records for a single project
records = get_FPR_records(project, provenance)
# parse the records and get all the files for a given project
for i in records:
# keep records for project
if project == i[1]:
pipeline_workflow = i[30]
# check workflow
if len(workflow) == 1:
if workflow[0].lower() == 'bcl2fastq':
# skip if not fastq-related workflows
if pipeline_workflow.lower() not in ['casava', 'bcl2fastq', 'fileimportforanalysis', 'fileimport', 'import_fastq']:
continue
else:
# skip if not provided workflow
if workflow[0].lower() != pipeline_workflow.lower():
continue
else:
if pipeline_workflow.lower() not in list(map(lambda x: x.lower(), workflow)):
continue
# get file path
if prefix:
file_path = os.path.join(prefix, i[46])
else:
file_path = i[46]
# get file name
file_name = os.path.basename(file_path)
# get sample name
sample_name = i[7]
# get parent sample name
parent_sample = i[9].split(':')[0]
# get time stamp and convert to epoch
creation_date = i[0]
# remove milliseconds
creation_date = creation_date.split('.')[0]
pattern = '%Y-%m-%d %H:%M:%S'
creation_date = int(time.mktime(time.strptime(creation_date, pattern)))
# record platform
platform = i[22]
# get md5sum
md5 = i[47]
# get workdlow swid
workflow_run_id = i[36]
# get workflow version
workflow_version = i[31]
# get file swid
file_swid = i[44]
# for merging workflows there will be multiple values for the variables below
# get library aliquot
aliquot = i[56].split('_')[-1]
# get library aliases
library = i[13]
# get lims key
limskey = i[56]
# get run id
run_id = i[18]
# get run
run = i[23]
# get lane
lane = i[24]
# get barcode
barcode = i[27]
geo = i[12]
if geo:
geo = {k.split('=')[0]:k.split('=')[1] for k in geo.split(';')}
else:
geo = {}
for j in ['geo_external_name', 'geo_group_id', 'geo_group_id_description',
'geo_targeted_resequencing', 'geo_library_source_template_type',
'geo_tissue_type', 'geo_tissue_origin']:
if j not in geo:
geo[j] = 'NA'
if j == 'geo_group_id':
# removes misannotations
geo[j] = geo[j].replace('&2011-04-19', '').replace('2011-04-19&', '')
read_count = i[45]
if read_count:
read_count = {k.split('=')[0]:k.split('=')[1] for k in i[45].split(';')}
if 'read_count' in read_count:
read_count = int(read_count['read_count'])
else:
read_count = -1
sample_id = sample_name + '_' + geo['geo_tissue_origin']+ '_' + geo['geo_tissue_type'] + '_' + geo['geo_library_source_template_type'] + '_' + geo['geo_group_id']
d = {'workflow': pipeline_workflow, 'file_path': file_path, 'file_name': file_name,
'sample_name': sample_name, 'creation_date': creation_date, 'platform': platform,
'md5': md5, 'workflow_run_id': workflow_run_id, 'workflow_version': workflow_version,
'file_swid': file_swid, 'external_name': geo['geo_external_name'],
'panel': geo['geo_targeted_resequencing'], 'library_source': [geo['geo_library_source_template_type']],
'parent_sample': [parent_sample], 'run_id': [run_id], 'run': [run],
'limskey': [limskey], 'aliquot': [aliquot], 'library': [library],
'barcode': [barcode], 'tissue_type': [geo['geo_tissue_type']],
'tissue_origin': [geo['geo_tissue_origin']], 'groupdesc': [geo['geo_group_id_description']],
'groupid': [geo['geo_group_id']], 'read_count': read_count, 'sample_id': [sample_id], 'lane': [lane]}
if file_swid not in D:
D[file_swid] = d
else:
assert D[file_swid]['file_path'] == file_path
assert D[file_swid]['external_name'] == geo['geo_external_name']
assert D[file_swid]['read_count'] == read_count
D[file_swid]['sample_id'].append(sample_id)
D[file_swid]['parent_sample'].append(parent_sample)
D[file_swid]['run_id'].append(run_id)
D[file_swid]['run'].append(run)
D[file_swid]['limskey'].append(limskey)
D[file_swid]['aliquot'].append(aliquot)
D[file_swid]['library'].append(library)
D[file_swid]['barcode'].append(barcode)
D[file_swid]['tissue_type'].append(geo['geo_tissue_type'])
D[file_swid]['tissue_origin'].append(geo['geo_tissue_origin'])
D[file_swid]['library_source'].append(geo['geo_library_source_template_type'])
D[file_swid]['groupdesc'].append(geo['geo_group_id_description'])
D[file_swid]['groupid'].append(geo['geo_group_id'])
D[file_swid]['lane'].append(lane)
return D
def select_most_recent_workflow(files):
'''
(dict) -> dict
Returns a new dictionary keeping files from the most recent workflow iteration if duplicate files exist
Parameters
----------
- files (dict): Dictionary with file records obtained from parsing FPR
'''
# find files with the same file name
file_names = {}
for file_swid in files:
# get the file name
file_name = files[file_swid]['file_name']
creation_time = files[file_swid]['creation_date']
if file_name in file_names:
# compare creation times
if creation_time >= file_names[file_name][0]:
# keep the most recent file
file_names[file_name] = [creation_time, file_swid]
else:
file_names[file_name] = [creation_time, file_swid]
# select the most files
D = {}
# make a list of file swids to keep
to_keep = list(map(lambda x: x[1], list(file_names.values())))
for file_swid in files:
if file_swid in to_keep:
D[file_swid] = files[file_swid]
return D
def exclude_miseq_secords(files):
'''
(dict) -> dict
Returns a new dictionary removing file records in files if sequencing was performed on a MiSeq platform.
Parameters
----------
- files (dict): Dictionary with file records obtained from parsing FPR
'''
D = {}
exclude = [file_swid for file_swid in files if 'miseq' in files[file_swid]['platform'].lower()]
for file_swid in files:
if file_swid not in exclude:
D[file_swid] = files[file_swid]
return D
def exclude_non_specified_runs(files, runs):
'''
(dict, list) -> dict
Returns a new dictionary removing file records in files if sequencing was performed during a run not specified in runs,
Parameters
----------
- files (dict) : Dictionary with file records obtained from parsing FPR
- runs (list): List of run ids to keep
'''
D = {}
exclude = [file_swid for file_swid in files if set(files[file_swid]['run_id']).intersection(set(runs)) != set(files[file_swid]['run_id'])]
for file_swid in files:
if file_swid not in exclude:
D[file_swid] = files[file_swid]
return D
def exclude_non_specified_libraries(files, valid_libraries):
'''
(dict, dict) -> dict
Returns a new dictionary removing file records corresponding to libraries not specified in libraries
Parameters
----------
- files (dict) : Dictionary with file records obtained from parsing FPR
- valid_libraries (dict): Dictionary with libraries tagged for release
'''
D = {}
exclude = []
for file_swid in files:
libraries = files[file_swid]['library']
runs = files[file_swid]['run_id']
lanes = files[file_swid]['lane']
if len(libraries) != 1 and len(runs) != 1 and len(lanes) != 1:
sys.exit('Use option -a to link merging-workflows output files')
library, run, lane = libraries[0], runs[0], int(lanes[0])
# exclude file if libraries is not included in the input sheet
if library not in valid_libraries:
exclude.append(file_swid)
# exclude file if run is not included in the input sheet
elif run not in valid_libraries[library]:
exclude.append(file_swid)
# exclude file if lane is specified but not included
elif '' not in valid_libraries[library][run] and lane not in valid_libraries[library][run]:
exclude.append(file_swid)
exclude = list(set(exclude))
for file_swid in files:
if file_swid not in exclude:
D[file_swid] = files[file_swid]
return D
def get_libraries_for_non_release(files, exclude):
'''
(dict, dict) -> dict
Returns a dictionary with file records corresponding to libraries tagged for non-release
Parameters
----------
- files (dict) : Dictionary with file records obtained from parsing FPR
- exclude (dict): Dictionary with libraries tagged for non-release
'''
# make a list of files to exclude
L = []
D = {}
for file_swid in files:
libraries = files[file_swid]['library']
runs = files[file_swid]['run_id']
if len(libraries) != 1 and len(runs) != 1:
sys.exit('Use option -a to link merging-workflows output files')
library, run = libraries[0], runs[0]
if library in exclude and run in exclude[library]:
L.append(file_swid)
if file_swid in L:
D[file_swid] = files[file_swid]
return D
def create_working_dir(project, project_dir, project_name=None):
'''
(str, str, str | None) -> str
Creates and returns path to a sub-directory in project_dir named iether after project or after project_name if defined
Parameters
----------
- project (str): Project name as it appears in File Provenance Report.
- projects_dir (str): Parent directory containing the project subdirectories with file links. Default is /.mounts/labs/gsiprojects/gsi/Data_Transfer/Release/PROJECTS/
- project_name (str | None): Project name used to create the project directory in gsi space
'''
# use project as project name if not specified
if project_name:
name = project_name
else:
name = project
working_dir = os.path.join(project_dir, name)
os.makedirs(working_dir, exist_ok=True)
return working_dir
def generate_links(files, release, project, working_dir, suffix):
'''
(dict, bool, str, str, str) -> None
Link fastq files to run directories under the project dir
Parameters
----------
- files_release (dict): Dictionary with file information
- release (bool): True if files were tagged for release and False otherwise
- project (str): Name of the project as it appears in FPR
- working_dir (str): Path to the project sub-directory in GSI space
- suffix (str): Indicates fastqs or datafiles
'''
for file_swid in files:
if len(files[file_swid]['run_id']) != 1:
sys.exit('Use parameter -a to specify how files should be linked')
assert len(files[file_swid]['run_id']) == 1
run = files[file_swid]['run_id'][0]
run_name = run + '.{0}.{1}'.format(project, suffix)
if release == False:
run_name += '.withold'
run_dir = os.path.join(working_dir, run_name)
os.makedirs(run_dir, exist_ok=True)
filename = files[file_swid]['file_name']
link = os.path.join(run_dir, filename)
file = files[file_swid]['file_path']
if os.path.isfile(link) == False:
os.symlink(file, link)
def link_pipeline_data(pipeline_data, working_dir):
'''
(dict, str) -> None
Link pipeline files according to hierarchy encoded in pipeline_data structure under working_dir
Parameters
----------
- pipeline_data (dict): Dictionary with files for each sample and workflow
- working_dir (str): Path to the project sub-directory in GSI space
'''
for donor in pipeline_data:
for sample_name in pipeline_data[donor]:
# create sample dir
donor_dir = os.path.join(working_dir, donor)
sample_dir = os.path.join(donor_dir, sample_name)
os.makedirs(donor_dir, exist_ok=True)
os.makedirs(sample_dir, exist_ok=True)
for workflow_name in pipeline_data[donor][sample_name]:
# create workflow dir
workflow_dir = os.path.join(sample_dir, workflow_name)
os.makedirs(workflow_dir, exist_ok=True)
# create worfkflow run id dir
for wf_id in pipeline_data[donor][sample_name][workflow_name]:
wfrun_dir = os.path.join(workflow_dir, wf_id)
os.makedirs(wfrun_dir, exist_ok=True)
# loop over files within each workflow
for i in pipeline_data[donor][sample_name][workflow_name][wf_id]:
file = i['file_path']
filename = i['file_name']
link = os.path.join(wfrun_dir, filename)
if os.path.isfile(link) == False:
os.symlink(file, link)
def exclude_non_specified_files(files, file_names):
'''
(dict, list) -> dict
Returns a new dictionary with file records keeping only the files listed in file_names
Parameters
----------
- files (dict) : Dictionary with file records obtained from parsing FPR
- file_names (list): List of valid file names for release
'''
D = {}
for file_swid in files:
file_name = files[file_swid]['file_name']
if file_name in file_names:
D[file_swid] = files[file_swid]
return D
def collect_files_for_release(files, release_files, nomiseq, runs, libraries, exclude):
'''
(dict, str | None, bool, list | None, str | None, str | None) -> (dict, dict)
Returns dictionaries with file records for files tagged for release and files that should not be released, if any, or an empty dictionary.
Parameters
----------
- files (str): Dictionary with file records for a entire project or a specific workflow for a given project
Default is '/.mounts/labs/seqprodbio/private/backups/seqware_files_report_latest.tsv.gz'
- release_files (str | None): Path to file with file names to be released
- nomiseq (bool): Exclude MiSeq runs if True
- runs (list | None): List of run IDs. Include one or more run Id separated by white space.
Other runs are ignored if provided
- libraries (str | None): Path to 2 or 3 columns tab-delimited file with library IDs.
The first column is always the library alias.
The second column is the lane number or the run identifier.
The last column is always the run identifier
Only the samples with these library aliases are used if provided'
- exclude (str | None): File with sample name or libraries to exclude from the release
'''
# keep most recent workflows
files = select_most_recent_workflow(files)
# check if a list of valid file names is provided
if release_files:
infile = open(release_files)
file_names = infile.read().rstrip().split('\n')
file_names = list(map(lambda x: os.path.basename(x), file_names))
infile.close()
else:
file_names = []
if file_names:
files = exclude_non_specified_files(files, file_names)
# remove files sequenced on miseq if miseq runs are excluded
if nomiseq:
files = exclude_miseq_secords(files)
# keep only files from specified runs
if runs:
files = exclude_non_specified_runs(files, runs)
# keep only files for specified libraries
# parse library file if exists
valid_libraries = get_libraries(libraries) if libraries else {}
if valid_libraries:
files = exclude_non_specified_libraries(files, valid_libraries)
# find files corresponding to libraries tagged for non-release
excluded_libraries = get_libraries(exclude) if exclude else {}
if excluded_libraries:
files_non_release = get_libraries_for_non_release(files, excluded_libraries)
else:
files_non_release = {}
return files, files_non_release
def get_pipeline_data(data_structure, files):
'''
(dict, dict) -> dict
Returns a dictionary with the files for each sample and workflow specified in the data_structure
Parameters
----------
- data_structure (str): Dictionary with samples, workflows and workflow_run_id hierarchical structure
- files (dict): Dictionary with all file records for a given project extracted from FPR
'''
D = {}
for donor in data_structure:
for sample_id in data_structure[donor]:
for file_swid in files:
sample = files[file_swid]['sample_name']
workflow = files[file_swid]['workflow']
version = files[file_swid]['workflow_version']
wf_id = files[file_swid]['workflow_run_id']
if donor == sample and sample in sample_id and workflow in data_structure[donor][sample_id]:
for d in data_structure[donor][sample_id][workflow]:
if version == d['workflow_version'] and wf_id == d['workflow_id']:
if donor not in D:
D[donor] = {}
if sample_id not in D[donor]:
D[donor][sample_id] = {}
# check if workflow name needs to be replaced
if 'name' in d:
workflow_name = d['name']
else:
workflow_name = workflow
if workflow_name not in D[donor][sample_id]:
D[donor][sample_id][workflow_name] = {}
if wf_id not in D[donor][sample_id][workflow_name]:
D[donor][sample_id][workflow_name][wf_id] = []
# check which files are collected
if 'extension' in d:
# files are collected based on file extension
# get the file extension
extension = pathlib.Path(files[file_swid]['file_path']).suffix
if extension in d['extension']:
D[donor][sample_id][workflow_name][wf_id].append({'file_path': files[file_swid]['file_path'],
'md5': files[file_swid]['md5'],
'file_name': os.path.basename(files[file_swid]['file_path'])})
elif 'files' in d:
# files are collected based on file name
if os.path.basename(files[file_swid]['file_path']) in list(map(lambda x: os.path.basename(x), d['files'])):
D[donor][sample_id][workflow_name][wf_id].append({'file_path': files[file_swid]['file_path'],
'md5': files[file_swid]['md5'],
'file_name': os.path.basename(files[file_swid]['file_path'])})
elif 'rename_files' in d:
# files are collected based on file name and renamed
# make a list of file names
file_paths, file_names = [], []
for i in d['rename_files']:
file_paths.append(os.path.basename(i['file_path']))
file_names.append(i['file_name'])
if os.path.basename(files[file_swid]['file_path']) in file_paths:
# collect file path, md5 and new file name used to name the link
j = file_paths.index(os.path.basename(files[file_swid]['file_path']))
D[donor][sample_id][workflow_name][wf_id].append({'file_path': files[file_swid]['file_path'],
'md5': files[file_swid]['md5'],
'file_name': file_names[j]})
else:
D[donor][sample_id][workflow_name][wf_id].append({'file_path': files[file_swid]['file_path'],
'md5': files[file_swid]['md5'],
'file_name': os.path.basename(files[file_swid]['file_path'])})
return D
def write_md5sum(data, outputfile):
'''
(dict, str) -> None
Write a file in working_dir with md5sums for all files contained in data
Parameters
----------
- data (dict): Dictionary holding data from a single workflow
- outpufile (str): Path to the outputfile with md5sums
'''
newfile = open(outputfile, 'w')
for file_swid in data:
md5 = data[file_swid]['md5']
file_path = data[file_swid]['file_path']
newfile.write('\t'.join([file_path, md5]) + '\n')
newfile.close()
def write_pipeline_md5sum(data, outputfile):
'''
(dict, str) -> None
Write a file in working_dir with md5sums for all files contained in data
Parameters
----------
- data (dict): Dictionary holding pipeline data
- outpufile (str): Path to the outputfile with md5sums
'''
newfile = open(outputfile, 'w')
# pipeline data
for donor in data:
for sample in data[donor]:
for workflow_name in data[donor][sample]:
for workflow_run in data[donor][sample][workflow_name]:
for i in data[donor][sample][workflow_name][workflow_run]:
newfile.write('\t'.join([i['file_path'], i['md5']]) + '\n')
newfile.close()
def link_files(args):
'''
(str, str, str, str | None, str | None, bool, list | None, str | None, str | None, str, str, str, str | None)
Parameters
----------
- provenance (str): Path to File Provenance Report.
Default is /.mounts/labs/seqprodbio/private/backups/seqware_files_report_latest.tsv.gz
- project (str): Project name as it appears in File Provenance Report.
- workflow (str): Worflow used to generate the output files
- prefix (str | None): Use of prefix assumes that file paths in File Provenance Report are relative paths.
Prefix is added to the relative path in FPR to determine the full file path.
- release_files (str | None): Path to file with file names to be released
- nomiseq (bool): Exclude MiSeq runs if True
- runs (list | None): List of run IDs. Include one or more run Id separated by white space.
Other runs are ignored if provided
- libraries (str | None): Path to 2 columns tab-delimited file with library IDs.
The first column is always the library alias (TGL17_0009_Ct_T_PE_307_CM).
The second column is the run ID. Only the samples with these library aliases are used if provided
- exclude (str | None): File with sample name or libraries to exclude from the release
- suffix (str): Indicates map for fastqs or datafiles in the output file name
- project_name (str): Project name used to create the project directory in gsi space
- projects_dir (str): Parent directory containing the project subdirectories with file links. Default is /.mounts/labs/gsiprojects/gsi/Data_Transfer/Release/PROJECTS/
- analysis (str): Path to file with json structure of samples, workflows, workflow run ids hierarchy
'''
if args.runs and args.libraries:
sys.exit('-r and -l are exclusive parameters')
if args.analysis and args.workflow:
sys.exit('-w and -a are exclusive parameters. Specify a single worklow or use a json structure to collect files')
if not args.analysis:
if not args.workflow:
sys.exit('Use -w to specify the workflow')
if not args.workflow:
if not args.analysis:
sys.exit('Use -a to indicate the pipeline workflows')
# create a working directory to link files and save md5sums
working_dir = create_working_dir(args.project, args.projects_dir, args.project_name)
# dereference link to FPR
provenance = os.path.realpath(args.provenance)
if args.workflow:
if not args.suffix:
sys.exit('Suffix -s is required')
# parse FPR records
files = parse_fpr_records(provenance, args.project, [args.workflow], args.prefix)
print('Extracted files from File Provenance Report')
# get file information for release and eventually for files that should not be released
files, files_non_release = collect_files_for_release(files, args.release_files, args.nomiseq, args.runs, args.libraries, args.exclude)
# link files to project dir
if args.suffix == 'fastqs':
assert args.workflow.lower() in ['bcl2fastq', 'casava', 'fileimport', 'fileimportforanalysis', 'import_fastq']
generate_links(files, True, args.project, working_dir, args.suffix)
# generate links for files to be witheld from release
if files_non_release:
generate_links(files_non_release, False, args.project, working_dir, args.suffix)
elif args.analysis:
infile = open(args.analysis)
data_structure = json.load(infile)
infile.close()
# parse FPR records
# make a list of workflows
workflows = []
for i in data_structure:
for j in data_structure[i]:
workflows.extend(list(data_structure[i][j].keys()))
workflows = list(set(workflows))
print('workflows', workflows)
files = parse_fpr_records(provenance, args.project, workflows, args.prefix)
print('Extracted files from File Provenance Report')
pipeline_data = get_pipeline_data(data_structure, files)
link_pipeline_data(pipeline_data, working_dir)
# write summary md5sums
# create a dictionary {run: [md5sum, file_path]}
current_time = time.strftime('%Y-%m-%d_%H:%M', time.localtime(time.time()))
if args.workflow:
outputfile = os.path.join(working_dir, '{0}.release.{1}.{2}.md5sums'.format(args.project, current_time, args.suffix))
write_md5sum(files, outputfile)
elif args.analysis:
outputfile = os.path.join(working_dir, '{0}.release.{1}.pipeline.md5sums'.format(args.project, current_time))
write_pipeline_md5sum(pipeline_data, outputfile)
print('Files were extracted from FPR {0}'.format(provenance))
def group_sample_info_mapping(files, add_panel):
'''
(dict, bool) -> dict
Returns a dictionary of sample information organized by run
Parameters
----------
- files (dict) : Dictionary with file records obtained from parsing FPR
- add_panel (bool): Add panel if True
'''
# group info by run id
D = {}
for file_swid in files:
file_path = files[file_swid]['file_path']
assert len(files[file_swid]['run']) == 1
run = files[file_swid]['run'][0]
assert len(files[file_swid]['run_id']) == 1
run_id = files[file_swid]['run_id'][0]
sample = files[file_swid]['sample_name']
assert len(files[file_swid]['library']) == 1
library = files[file_swid]['library'][0]
assert len(files[file_swid]['library_source']) == 1
library_source = files[file_swid]['library_source'][0]
assert len(files[file_swid]['tissue_type']) == 1
tissue_type = files[file_swid]['tissue_type'][0]
assert len(files[file_swid]['tissue_origin']) == 1
tissue_origin = files[file_swid]['tissue_origin'][0]
assert len(files[file_swid]['barcode']) == 1
barcode = files[file_swid]['barcode'][0]
external_id = files[file_swid]['external_name']
assert len(files[file_swid]['groupdesc']) == 1
group_description = files[file_swid]['groupdesc'][0]
assert len(files[file_swid]['groupid']) == 1
group_id = files[file_swid]['groupid'][0]
panel = files[file_swid]['panel']
# group files by sample, library, run and lane
key = '_'.join([sample, library, run, barcode])
L = [sample, external_id, library, library_source, tissue_type, tissue_origin, run, barcode, group_id, group_description]
if add_panel:
L.append(panel)
if key not in D:
D[key] = {'info': L, 'files': [file_path]}
else:
assert D[key]['info'] == L
D[key]['files'].append(file_path)
return D
def map_external_ids(args):
'''
(str, str, str | None, str | None, bool, list | None, str | None, str | None, str, str, bool) -> None
Generate sample maps with sample and sequencing information
Parameters
----------
- provenance (str): Path to File Provenance Report.
- project (str): Project name as it appears in File Provenance Report.
- prefix (str | None): Use of prefix assumes that file paths in File Provenance Report are relative paths.
Prefix is added to the relative path in FPR to determine the full file path.
- release_files (str | None): Path to file with file names to be released
- nomiseq (bool): Exclude MiSeq runs if True
- runs (list | None): List of run IDs. Include one or more run Id separated by white space.
Other runs are ignored if provided
- libraries (str | None): Path to 1 or 2 columns tab-delimited file with library IDs.
The first column is always the library alias (TGL17_0009_Ct_T_PE_307_CM).
The second and optional column is the library aliquot ID (eg. LDI32439).
Only the samples with these library aliases are used if provided'
- exclude (str | None): File with sample name or libraries to exclude from the release
- project_name (str): Project name used to create the project directory in gsi space
- projects_dir (str): Parent directory containing the project subdirectories with file links. Default is /.mounts/labs/gsiprojects/gsi/Data_Transfer/Release/PROJECTS/
- add_panel (bool): Add panel column to sample map if True
'''
if args.runs and args.libraries:
sys.exit('-r and -l are exclusive parameters')
# dereference link to FPR
provenance = os.path.realpath(args.provenance)
# sample maps are generated using fastq-generating workflows
workflow, suffix = 'bcl2fastq', 'fastqs'
# create a working directory to link files and save md5sums
working_dir = create_working_dir(args.project, args.projects_dir, args.project_name)
# parse FPR records
files = parse_fpr_records(provenance, args.project, [workflow], args.prefix)
print('Extracted files from File Provenance Report')
# get raw sequence file info
files, files_non_release = collect_files_for_release(files, args.release_files, args.nomiseq, args.runs, args.libraries, args.exclude)
# group sample information by run
sample_info = group_sample_info_mapping(files, args.add_panel)
# write sample maps
current_time = time.strftime('%Y-%m-%d_%H:%M', time.localtime(time.time()))
outputfile = os.path.join(working_dir, '{0}.release.{1}.{2}.map.tsv'.format(args.project, current_time, suffix))
newfile = open(outputfile, 'w')
header = ['sample', 'sample_id', 'library', 'library_source', 'tissue_type', 'tissue_origin', 'run', 'barcode', 'group_id', 'group_description', 'files']
if args.add_panel:
#header.append('panel')
header.insert(-1, 'panel')
newfile.write('\t'.join(header) + '\n')
# make a list of sorted samples
keys = sorted(list(sample_info.keys()))
for k in keys:
files = ';'.join(list(map(lambda x: os.path.basename(x), sample_info[k]['files'])))
info = sample_info[k]['info']
info.append(files)
newfile.write('\t'.join(list(map(lambda x: str(x), info))) + '\n')
newfile.close()
print('Generated sample maps in {0}'.format(working_dir))
print('Information was extracted from FPR {0}'.format(provenance))
def list_files_release_folder(directories):
'''
(list) -> list
Returns a list of full file paths for all fastqs located in each folder of the list of directories
Parameters
----------
- directories (list): A list of full paths to directories containining released fastqs
'''
# make a list of files
files = []
for run in directories:
# make a list of links for the directory
links = [os.path.join(run, i) for i in os.listdir(run) if os.path.isfile(os.path.join(run, i)) and '.fastq.gz' in i]
files.extend(links)
# expect only paired fastqs
if len(links) % 2 != 0:
sys.exit('Odd number of fastqs in {0}: {1}'.format(run, len(links)))
return files
def resolve_links(filenames):
'''
(list) -> list
Returns a list of file paths with links resolved
Parameters
----------
- filenames(list): List of file paths
'''
files = [os.path.realpath(i) for i in filenames]
return files
def is_gzipped(file):
'''
(str) -> bool
Return True if file is gzipped
Parameters
----------
- file (str): Path to file
'''
# open file in rb mode
infile = open(file, 'rb')
header = infile.readline()
infile.close()
if header.startswith(b'\x1f\x8b\x08'):
return True
else:
return False
def compute_on_target_rate(bases_mapped, total_bases_on_target):
'''
(int, int) -> float
Returns the percent on target rate
Parameters
----------
- bases_mapped (int): Number of bases mapping the reference
- total_bases_on_target (int): Number of bases mapping the target
'''
try:
on_target = round(total_bases_on_target / bases_mapped * 100, 2)
except:
on_target = 'NA'
finally:
if on_target != 'NA':
if math.ceil(on_target) == 100:
on_target = math.ceil(on_target)
return on_target
def count_released_fastqs_by_instrument(FPR_info, reads):
'''
(dict, str) -> dict
Returns the count of released fastqs for each run and instrument
Parameters
----------