-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpart3_cleanup.py
executable file
·1321 lines (1141 loc) · 50.2 KB
/
part3_cleanup.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
#! /local/projects-t3/MSL/pipelines/packages/miniconda3/envs/interactive/bin/python3
import argparse, sys, os, glob, re, shlex, json, shutil, gzip, getpass, stat, tempfile, time, csv, linecache
from pathlib import Path # Use of Paths as os.pathlike objects requires Python3.6
import PyInquirer # MUST USE PYTHON3.6 FOUND IN interactive TO USE THIS
import examples
from subprocess import run, Popen, PIPE
from enum import Enum
import scripts.synology_client as synology # MUST BE IN SAME DIRECTORY AS THIS SCRIPT
from jira import JIRA
from jira.exceptions import JIRAError
pipeline_dir = os.path.dirname(os.path.realpath(__file__))
with (Path(pipeline_dir) / Path("config.json")).open("r") as fh:
CONFIG = json.load(fh)
pathfinder = {
"intermediate_taxonomies": Path("TAXONOMY_INTERMEDIATES"),
"final_taxonomies": Path("TAXONOMY_FINAL"),
"counts-by-taxon": Path("COUNTS_BY_TAXON"),
"counts-by-ASV": Path("COUNTS_BY_ASV"),
"report": Path("REPORT"),
"fastqs": Path("FASTQ")
}
def main(args):
args.project = choose_project(default=args.project)
while True:
questions = [
{
"type": "list",
"name": "chooser",
"message": "Choose operation:",
"choices": [
{
"name": "PREPARE FOR DELIVERY - Reorganize files and delete pipeline artifacts",
"value": "D",
},
{
"name": "UPLOAD TO JIRA - Upload select files to MSL JIRA ticket",
"value": "J",
},
# {
# 'name': "ARCHIVE - copy to Rosalind",
# 'value': 'A'
# },
{"name": "BACK", "value": "B"},
{"name": "QUIT"},
],
}
]
choice = inquire(questions)
if choice == "A":
upload_to_synology(args.project)
elif choice == "D":
ans = get_runs(args.project)
if ans["status"]:
run_paths = ans["runs"]
else:
continue
proj_map = choose_map()
#if not organize_trimmed(args.project, run_paths): continue
if not organize_counts_by_asv(args.project): continue
if not organize_counts_by_taxon(args.project): continue
if not organize_logs(args.project, run_paths): continue
if not organize_taxonomies_final(args.project): continue
if not organize_taxonomies_intermediates(args.project): continue
if not add_index(): continue
if not add_references(args.project, run_paths): continue
if not organize_reads(args.project, proj_map, run_paths): continue
if not share_unix_perms(args.project): continue
if not remove_trash(args.project, run_paths): continue
elif choice == "J":
upload_to_jira(args.project)
elif choice == "QUIT":
sys.exit(0)
elif choice == "B":
args.project = choose_project()
return
def ask_continue():
if not confirm("Continue?"):
return False
return True
def ask_and_move(dirpath, filepaths):
if len(filepaths) > 0:
print()
for filepath in filepaths:
print(filepath)
if confirm("Press y to move the above files:"):
for filepath in filepaths:
Path(filepath).rename(Path(dirpath) / Path(filepath))
else:
return False
return True
# def archive(proj):
# barcodes = []
# for run in run_paths:
# barcodes += glob.glob(str(run.resolve() / Path("barcodes.fastq")))
# print(f"Found {len(barcodes)} barcode files in {len(run_paths)} runs.")
# if(len(barcodes) > 0):
# if not confirm("Delete?"):
# return()
# for barcode_filename in barcodes:
# os.unlink(barcode_filename)
# upload_to_synology(str(args.project))
# return
# untested. takes one filepath string
def gz(filepath):
with open(filepath, "rb") as f_in:
with gzip.open(f"{filepath}.gz", "wb") as f_out:
shutil.copyfileobj(f_in, f_out)
Path(filepath).unlink()
return
# untested. returns list of strings
def find_trimmed(run):
files = glob.glob(str(run / Path("*.fastq")))
return files
# choose_upload_dest is a misnomer becaues it actually follows up by guiding user
# through the upload.
def upload_to_synology(dirpath):
done = False
while not done:
questions = [
{
"type": "list",
"name": "chooser",
"message": "Upload project to Synology?",
"choices": ["Upload", "Back"],
}
]
if inquire(questions) != "Upload":
return
user = getuser("Synology user: ")
dirs_to_upload = [
str(pathfinder['counts-by-ASV']),
str(pathfinder['counts-by-taxon']),
"REPORT",
"FASTQ",
str(pathfinder['final_taxonomies']),
str(pathfinder['intermediate_taxonomies']),
]
try:
synology.archive_project(
user,
dirpath.name,
dirs_to_upload
)
done = True
except Exception as e:
print(e)
return
def share_unix_perms(path):
print("Expanding owner file permissions to group file permissions...")
pathlist = Path(str(path)).rglob("*")
user_to_group_divisor = int(stat.S_IRUSR / stat.S_IRGRP)
for path in pathlist:
try:
st = path.stat()
except Exception as e:
print(str(e))
if not ask_continue():
return False
else:
continue
usr_perms = st.st_mode & stat.S_IRWXU
try:
path.chmod(st.st_mode | int(usr_perms / user_to_group_divisor))
except Exception as e:
# Likely PermissionError
if os.geteuid() == st.st_uid:
print(f"Cannot process {str(path)}. The problem may be lack of ownership\n")
elif usr_perms <= 0:
print(f"Cannot process {str(path)}. Owner has no permissions on {str(path)}.\n")
else:
print(f"Unable to expand permissions to group for: {str(path)}\n{str(e)}")
# don't ask if the user wants to "continue". this is the last step,
# so the user's choice doesn't make a difference
if not ask_continue():
return False
return True
def getuser(prompt="User: "):
try:
default = os.getlogin()
except OSError:
default = os.environ["USER"]
questions = [
{"type": "input", "name": "user_prompt", "message": prompt, "default": default}
]
return inquire(questions)
def upload_to_jira(proj):
# CONNECT ##########################################################################
options = {"server": "https://jira.igs.umaryland.edu/"}
kerberos_options = {"mutual_authentication": "DISABLED"}
connected = False
while not connected:
jira_user = getuser("Jira user:")
jira_passwd = getpass.getpass(f"Password for {jira_user}:")
basic_auth = (jira_user, jira_passwd)
try:
j_connection = JIRA(
options=options,
basic_auth=basic_auth,
kerberos=True,
kerberos_options=kerberos_options,
max_retries=0,
)
connected = True
except JIRAError as e:
if e.status_code == 401:
print("Unable to authenticate.")
return
else:
print(e.response)
except Exception as e:
print(e)
return
# IDENTIFY TICKET ##################################################################
issue_name = None
while issue_name is None:
questions = [
{
"type": "list",
"name": "chooser",
"message": "Find ticket to which to attach files:",
"choices": [
{"name": "BROWSE OPEN MSL TICKETS", "value": "browse"},
{"name": "ENTER TICKET ID", "value": "enter"},
{"name": "BACK", "value": "back"},
],
}
]
choice = inquire(questions)
if choice == "browse":
print("Looking up issues...")
issue_name = jira_choose_issue_from_list(j_connection)
elif choice == "enter":
issue_name = jira_find_issue_from_input(j_connection)
else:
return
# UPLOAD ###########################################################################
done = False
while not done:
files = sorted([str(child) for child in Path(".").iterdir() if child.is_file()])
questions = [
{
"type": "checkbox",
"name": "chooser",
"message": "",
"choices": [{"name": file} for file in files],
}
]
choices = inquire(questions, "Choose map(s) to upload:")
if len(choices) == 0:
if confirm("You selected 0 files. Continue?"):
done = True
else:
for choice in choices:
filepath = str(proj / Path(choice))
if not attach_to_issue(j_connection, issue_name, filepath):
return
done = True
done = False
while not done:
files = sorted([str(child) for child in pathfinder["counts-by-taxon"].iterdir() if child.is_file()])
# process = Popen(
# ["ls", "-al", str(proj / pathfinder["counts-by-taxon"])],
# stdin=PIPE,
# stdout=PIPE,
# stderr=PIPE,
# )
# tree = process.stdout.read().decode(encoding="utf8").split("\n")
# if len(tree) < 5:
# print("Cannot read contents of current directory.")
# return
questions = [
{
"type": "checkbox",
"name": "chooser",
"message": "",
"choices": [{"name": file} for file in files],
}
]
choices = inquire(questions, "Choose count tables to upload:")
if len(choices) == 0:
if confirm("You selected 0 files. Continue?"):
done = True
else:
for choice in choices:
filepath = str(proj / Path(choice))
if not attach_to_issue(j_connection, issue_name, filepath):
return
done = True
return
def jira_choose_issue_from_list(j_connection):
block_size = 100
block_num = 0
issues = {}
while True:
start_idx = block_num * block_size
results = j_connection.search_issues(
'project="MSL" AND (status="To Do" OR status="in progress") order by updated',
start_idx,
block_size,
)
if len(results) == 0:
# Retrieve issues until there are no more to come
break
for res in results:
issues[f"{res.key}: {res.fields.summary}"] = res.key
block_num += 1
questions = [
{
"type": "list",
"name": "chooser",
"message": "Choose ticket:",
"choices": ["BACK"] + list(issues.keys()),
}
]
choice = inquire(questions)
if choice != "BACK":
return issues[choice]
else:
return None
def jira_find_issue_from_input(j_connection):
# input prompt
questions = [
{
"type": "input",
"name": "user_prompt",
"message": "Issue ID:",
"default": "MSL-",
}
]
issue_name = inquire(questions)
try:
echo = j_connection.search_issues(f"id={issue_name}")
except JIRAError as e:
if e.status_code == 400:
print("Unable to find issue.")
else:
print(e.text)
return
if len(echo) == 1:
if echo[0].key == issue_name:
if confirm(f"Use {echo[0].key}: {echo[0].fields.summary}?"):
return issue_name
else:
print("Can't find issue.")
return None
else:
print("Can't find issue.")
return None
def attach_to_issue(j_connection, issue_name, filepath):
file_path = Path(filepath).resolve()
jira_issue = j_connection.issue(issue_name, expand="attachment")
dupes = sum(
[file_path.name == att.filename for att in jira_issue.fields.attachment]
)
if dupes > 0:
prompt = (
f"{dupes} file(s) named {file_path.name} already attached to {issue_name}."
)
questions = [
{
"type": "list",
"name": "chooser",
"message": prompt,
"choices": [
"CANCEL",
"DELETE EXISTING/OVERWRITE",
"RENAME NEW ATTACHMENT",
],
}
]
choice = inquire(questions)
if choice == "CANCEL":
return False
elif choice == "DELETE EXISTING/OVERWRITE":
for att in jira_issue.fields.attachment:
if file_path.name == att.filename:
j_connection.delete_attachment(att.id)
elif choice == "RENAME NEW ATTACHMENT":
questions = [
{
"type": "input",
"name": "user_prompt",
"message": "New filename:",
"default": f"{file_path.name}.1",
}
]
with tempfile.TemporaryDirectory() as tmpdirname:
new_file_path = Path(tmpdirname) / Path(inquire(questions))
shutil.copy(file_path, new_file_path)
with new_file_path.open(mode="rb") as f:
j_connection.add_attachment(
issue_name, f
) # Please check if attachment already exists, and if so, ask to delete
print(
f"Uploaded {str(file_path.relative_to(args.project))} to {issue_name} as {new_file_path.name}"
)
return True
with file_path.open(mode="rb") as f:
j_connection.add_attachment(
issue_name, f
) # Please check if attachment already exists, and if so, ask to delete
print(f"Uploaded {str(file_path.relative_to(args.project))} to {issue_name}")
return True
def inquire(questions, extra_prompt=None):
print("\n")
if extra_prompt is not None:
print(extra_prompt)
answers = PyInquirer.prompt(questions, style=examples.custom_style_2)
if answers:
for answer in answers.values():
return answer # only one answer expected
else:
sys.exit(0)
def choose_project(default=None):
def helper():
# simple browser, chooses from current working directory with no navigation allowed
if confirm("Is the project in the current directory?"):
return Path.cwd()
else:
while True:
process = Popen(
["ls", "-al", str(Path.cwd())], stdin=PIPE, stdout=PIPE, stderr=PIPE
)
tree = process.stdout.read().decode(encoding="utf8").split("\n")
if len(tree) < 5:
print("Cannot read contents of current directory. Exiting...")
sys.exit(0)
questions = [
{
"type": "list",
"name": "chooser",
"message": "Please choose project directory.",
"choices": ["QUIT"] + tree[3 : len(tree) - 1],
}
]
choice = inquire(questions)
if choice[0] == "d":
basename = choice.split()[8]
fullname = (Path.cwd() / Path(basename)).resolve()
return fullname
elif choice[0] == "l":
target = Path(choice.split()[8]).resolve()
if target.is_dir():
return target
elif choice == "QUIT":
sys.exit(0)
print("\nNot a directory!\n")
if default is None:
project = helper()
else:
try:
project = Path(default).resolve() # May raise FileNotFoundError
except FileNotFoundError as e:
print(e)
sys.exit(1)
os.chdir(str(project))
return project
def choose_map():
files = sorted([str(child) for child in Path(".").iterdir() if child.is_file()])
questions = [
{
"type": "list",
"name": "chooser",
"message": "",
"choices": [{"name": file} for file in files],
}
]
return inquire(questions, "Choose project map:")
def confirm(prompt, default=False):
questions = [
{"type": "confirm", "name": "response", "message": prompt, "default": default}
]
return inquire(questions)
def get_runs(proj_path):
ans = {
"status": True,
"runs": []
}
subdirs = [x for x in Path(proj_path).iterdir() if x.is_dir()]
if len(subdirs) == 0:
if confirm("Project contains no subdirectories. Continue?"):
return []
else:
return ()
choices = []
for subdir in subdirs:
choice = {"name": subdir.name}
if subdir.name in list(project_metadata()['runs'].keys()):
choice["checked"] = True
else:
choice["checked"] = False
choices.append(choice)
choices.sort(key=(lambda choice: choice["name"]))
prompt = "Use <SPACE> to choose runs. Press <ENTER> to confirm."
questions = [
{"type": "checkbox", "name": "chooser", "message": "", "choices": choices}
]
response = inquire(questions, prompt)
if len(response) == 0:
if confirm("You selected 0 runs. Continue?"):
pass
else:
ans["status"] = False
else:
ans["runs"] = [proj_path / Path(subdir) for subdir in response]
return ans
def project_metadata():
try:
with Path(".meta.json").open("r") as fh:
metadata = json.load(fh)
except FileNotFoundError:
raise Exception("Cannot find project metadata from Part 2. Re-run Part 2.")
if not type(metadata) is dict:
raise Exception("Project metadata not a JSON dictionary")
return metadata
def read_metadata(run_path):
with (run_path / Path(".meta.json")).open("r") as fh:
run_info = json.load(fh)
if not type(run_info) is dict:
raise Exception("Run metadata not a JSON dictionary")
if not "params" in run_info.keys() or not "checkpoints" in run_info.keys():
raise Exception("Run metadata doesn't contain 'checkpoints' and 'params'")
if not type(run_info["params"]) is dict or not type(run_info["checkpoints"]) is dict:
raise Exception("Run metadata 'params' or 'checkpoints' is not a JSON dictionary")
return run_info
def organize_reads(proj_path, map, run_paths):
try:
organized_dir = "FASTQ"
filepaths = []
any_files = False
run_paths_dict = {Path(path).name: path for path in run_paths}
# for file in map, find where it should be, and copy in if present
transfers = {}
warnings = 0
to_transfer = 0
with open(map) as fd:
dr = csv.DictReader(fd, delimiter="\t", quotechar='"')
for row in dr:
run_platepos = row["RUN.PLATEPOSITION"]
sample = row["sampleID"]
possible_paths = []
transfers[sample] = []
for run_name, run_path in run_paths_dict.items():
possible_paths_run = {}
if (run_path / Path("fwdSplit")).exists():
# pre-2023 format, might or might not be renamed
possible_paths_run.update({
str(run_path / Path("fwdSplit") / Path("split_by_sample_out")): [re.escape(sample) + "(_R1)?\.fastq(\.gz)?", re.escape(run_platepos) + "(_R1)?\.fastq(\.gz)?"],
str(run_path / Path("revSplit") / Path("split_by_sample_out")): [re.escape(sample) + "(_R2)?\.fastq(\.gz)?", re.escape(run_platepos) + "(_R2)?\.fastq(\.gz)?"]
}
)
# if "." in sample: # this is not a valid way of determining if the FASTQ's have already been renamed
# # also pre-2023 format, already renamed
# possible_paths_run[str(run_path / Path("fwdSplit") / Path("split_by_sample_out"))].append(".*" + re.escape(sample.split(".")[1]) + "(_R[12])?\.fastq(\.gz)?") # these are both found in fwdSplit??
# current format, paired-end or unpaired
elif (run_path / Path("R1split")).exists():
possible_paths_run.update({
str(run_path / Path("R1split") / Path("split_by_sample_out")): [re.escape(sample) + "(_R1)?\.fastq(\.gz)?", re.escape(run_platepos) + "(_R1)?\.fastq(\.gz)?"],
str(run_path / Path("R4split") / Path("split_by_sample_out")): [re.escape(sample) + "(_R2)?\.fastq(\.gz)?", re.escape(run_platepos) + "(_R2)?\.fastq(\.gz)?"]
}
)
elif (run_path / Path("demultiplexed")).exists():
possible_paths_run[str(run_path / Path("demultiplexed"))] = [re.escape(run_platepos) + "(_R[12])?\.fastq.gz"]
else:
print(f"Couldn't find demultiplexed files directory for run {run_path}")
# do regex search (we need regex functionality that isn't in glob.glob)
reads = []
for rootdir in possible_paths_run.keys():
possible_paths += [os.path.join(rootdir, patt) for patt in possible_paths_run[rootdir]]
for patt in possible_paths_run[rootdir]:
regex = re.compile(patt)
for root, dirs, files in os.walk(rootdir):
for file in files:
if regex.match(file):
reads.append(os.path.join(root, file))
# R1 and R2 files for Illumina, just one file for PacBio
if(len(reads) > 0):
# If the same sample is found in multiple runs, only gets the files from the last run (not sure what the desired behavior is here)
transfers[sample].append({"srcs": reads, "run": run_name})
if len(transfers[sample]) == 0:
format_msg = ("WARNING: No read files for sample %s with plate position \n" +
"%s could be found. This is probably a sample that didn't\n" +
"pass demux; if expected, please continue.\n")
print(format_msg % (sample, run_platepos))
print("Search patterns:\n%s \n" % "\n".join(possible_paths))
warnings += 1
if warnings > 0:
print("These are probably samples that didn't pass demux; if expected, please continue.\n")
print("%s samples will be moved to %s/.\n" % (len(transfers) - warnings, organized_dir))
print("%s samples were not found.\n" % warnings)
# can we fix this to look at the project dada2 stats file and check the number sampels found is same as number demuxed?
if warnings > 0:
if not ask_continue():
return False
samples_to_transfer = [len(run_matches) > 0 for run_matches in transfers.values()]
nSamples = sum(samples_to_transfer)
if any(samples_to_transfer):
make_for_contents(organized_dir)
else:
raise Exception(f"Skipping creation of {organized_dir} (no demuxed reads found)")
for run_path in run_paths_dict.values():
subdir_destination = str(proj_path / Path(organized_dir) / Path(run_path.name))
make_for_contents(subdir_destination)
executor = CONFIG['executor']
external_exec = False
print("\nThis pipeline's default executor is:\n\n" + executor)
if confirm("Use executor to transfer large files? (Choose yes if not using screen or tmux)", default=True):
external_exec = True
if external_exec:
print(f"Using executor to copy raw read files for {nSamples} samples to {organized_dir}.\n")
print("\nRemember to delete any stray STDOUT and STDERR files from the working directory.\n")
time.sleep(5)
else:
print(f"Copying raw read files for {nSamples} samples to {organized_dir}.")
for sample, data in transfers.items():
if len(data) > 0:
for run_files in data:
run_dir_name = run_files["run"]
for source in run_files["srcs"]:
if source.endswith("_R1.fastq.gz"):
ext = "_R1.fastq.gz"
elif source.endswith("_R2.fastq.gz"):
ext = "_R2.fastq.gz"
elif re.search("fwdSplit", source):
ext = "_R1.fastq.gz"
elif re.search("revSplit", source):
ext = "_R2.fastq.gz"
elif source.endswith(".fastq.gz"):
ext = ".fastq.gz"
else:
ext = os.path.splitext(source)[1]
dest = str(Path(organized_dir) / run_dir_name / Path(sample + ext))
if external_exec:
cmd = "module load sge && " + executor + " -N copy -V \'cp -f %s %s\'"
this_cmd = cmd % (source, dest)
print(this_cmd)
run(this_cmd, shell=True)
else:
shutil.copy2(source, dest)
# gzip all if needed
for f in Path(subdir_destination).iterdir():
if f.suffix != ".gz":
gz(str(f))
except Exception as e:
PrintException()
# print(str(type(e)) + ": " + str(e))
if not ask_continue():
return False
return True
# def organize_trimmed(proj_path, run_paths):
# try:
# organized_dir = "FASTQ_TRIMMED"
# filepaths = []
# any_files = False
# for run_path in run_paths:
# filepaths += glob.glob(str(proj_path / run_path / Path("*_tc.fastq*")))
# filepaths += glob.glob(
# str(proj_path / run_path / Path("tagcleaned") / Path("*.fastq*"))
# )
# if len(filepaths) > 0:
# make_for_contents(organized_dir, any_files)
# any_files = True
# subdir_destination = str(Path(organized_dir) / run_path.name)
# make_for_contents(subdir_destination)
# print(
# f"Copying {len(filepaths)} adapter-trimmed read files to {subdir_destination}."
# )
# for filepath in filepaths:
# shutil.copy2(filepath, Path(subdir_destination) / Path(filepath).name)
# for f in Path(subdir_destination).iterdir(): # gzip if necessary
# if f.suffix != ".gz":
# gz(str(f))
# if not any_files:
# print(f"Skipping creation of {organized_dir} (no adapter-trimmed reads found)")
# except Exception as e:
# print(str(e))
# if not ask_continue():
# return False
# return True
def organize_counts_by_asv(proj_path):
try:
organized_dir = str(pathfinder['counts-by-ASV'])
filepaths = glob.glob(str(proj_path / Path("*all_runs_dada2_abundance_table.rds")))
filepaths += glob.glob(str(proj_path / Path("*all_runs_dada2_abundance_table.csv")))
filepaths += glob.glob(str(proj_path / Path("*asvs+taxa.csv")))
if len(filepaths) > 0:
make_for_contents(organized_dir)
print(f"Moving {len(filepaths)} sample-ASV count tables to {organized_dir}/.")
for filepath in filepaths:
Path(filepath).rename(Path(organized_dir) / Path(filepath).name)
else:
print(f"Skipping creation of {organized_dir} (no count-by-ASV tables found)")
except Exception as e:
print(str(e))
if not ask_continue():
return False
return True
def organize_counts_by_taxon(proj_path):
try:
organized_dir = str(pathfinder['counts-by-taxon'])
filepaths = glob.glob(str(proj_path / Path("*taxa-merged.csv")))
if len(filepaths) > 0:
make_for_contents(organized_dir)
print(f"Moving {len(filepaths)} sample-taxon count tables to {organized_dir}/.")
for filepath in filepaths:
Path(filepath).rename(Path(organized_dir) / Path(filepath).name)
else:
print(f"Skipping creation of {organized_dir} (no count-by-taxon tables found)")
except Exception as e:
print(str(e))
if not ask_continue():
return False
return True
def make_for_contents(dir, silent=False):
try:
os.makedirs(dir)
print(f"Creating {dir}/")
except FileExistsError:
if not silent:
print(f"Directory {dir}/ already exists")
except Exception as e:
raise e
def organize_logs(proj_path, run_paths):
try:
organized_dir = "LOGS"
# Part 1 logs found in the run directories. Just copy.
filepaths = glob.glob(str(proj_path / Path("*pipeline_log.txt")))
filepaths += glob.glob(str(proj_path / Path("*.R.stderr")))
if len(filepaths) > 0:
make_for_contents(organized_dir)
print(f"Moving {len(filepaths)} log files to LOGS/.")
for filepath in filepaths:
Path(filepath).rename(Path(organized_dir) / Path(filepath).name)
filepaths = []
for run in run_paths:
filepaths += glob.glob(str(proj_path / run / Path("*pipeline_log.txt")))
if len(filepaths) > 0:
make_for_contents(organized_dir)
print(f"Copying {len(filepaths)} log files to LOGS/.")
for filepath in filepaths:
shutil.copy2(filepath, Path(organized_dir) / Path(filepath).name)
if Path(organized_dir).exists():
print(f"Skipping creation of {organized_dir} (no logs found)")
except Exception as e:
print(str(e))
if not ask_continue():
return False
return True
def organize_taxonomies_final(proj_path):
try:
organized_dir = str(pathfinder['final_taxonomies'])
filepaths = glob.glob(str(proj_path / "cmb_tx.txt"))
if len(filepaths) > 0:
make_for_contents(organized_dir)
print(f"Moving cmb_tx.txt to {organized_dir}/.")
for filepath in filepaths:
Path(filepath).rename(Path(organized_dir) / Path("final_taxonomy.txt"))
else:
print(f"Skipping creation of {organized_dir} (no final taxonomy files found)")
except Exception as e:
print(str(e))
if not ask_continue():
return False
return True
def organize_taxonomies_intermediates(proj_path):
try:
organized_dir = str(pathfinder['intermediate_taxonomies'])
any_files = False
filepaths = glob.glob(str(proj_path / Path("MC_order7_results.txt"))) + glob.glob(str(proj_path / Path("MC_order7_results.clean.txt")))
if len(filepaths) > 0:
any_files = True
make_for_contents(organized_dir)
print(f"Moving MC_order7_results.txt to {organized_dir}/PECAN_raw.txt.")
for filepath in filepaths:
Path(filepath).rename(Path(organized_dir) / Path("PECAN_raw.txt"))
filepaths = glob.glob(str(proj_path / Path("*SILVA*.classification.csv")))
filepaths += glob.glob(str(proj_path / Path("*HOMD*.classification.csv")))
filepaths += glob.glob(str(proj_path / Path("*UNITE*.classification.csv")))
if len(filepaths) > 0:
any_files = True
make_for_contents(organized_dir, any_files)
print(f"Moving {len(filepaths)} raw RDP classifier files to {organized_dir}/")
for filepath in filepaths:
newname = re.sub(
r"^.*?([^_]*)\.classification\.csv$", r"\1_raw.csv", Path(filepath).name
)
Path(filepath).rename(
Path(organized_dir) / Path(newname)
)
filepaths = glob.glob(str(proj_path / Path("silva_condensed.txt")))
filepaths += glob.glob(str(proj_path / Path("homd_condensed.txt")))
filepaths += glob.glob(str(proj_path / Path("unite_condensed.txt")))
if len(filepaths) > 0:
make_for_contents(organized_dir, any_files)
print(f"Moving {len(filepaths)} condensed taxonomy file to {organized_dir}/.")
for filepath in filepaths:
match = re.match(r"^([^_]*)_condensed\.txt$", Path(filepath).name)
tax_name = match.group(1)
Path(filepath).rename(Path(organized_dir) / Path(f"{tax_name.upper()}.txt"))
if not any_files:
print(
f"Skipping creation of {organized_dir} (no intermediate taxonomy files found)"
)
except Exception as e:
print(str(e))
if not ask_continue():
return False
return True
def add_index():
try:
with open("_INDEX.txt", "w") as outfile:
outfile.write(index_contents)
except Exception as e:
print(str(e))
if not ask_continue():
return False
return True
def add_references(proj_path, run_paths):
# get illumina references as orderedDict
references = Citations()
print('')
try: # ugh I don't like this huge try catch block, but it works...and I don't
# know what exceptions to catch any way
# add starter references for illumina or pacbio runs
run_types = set()
for run_path in run_paths:
try:
run_info = read_metadata(proj_path / run_path)
run_type = run_info['params']['platform'].upper()
if run_type not in CITATION_GROUPS.keys():
print(f"Unrecognized run type: {run_type}. Don't know what citations to add.")
else:
run_types.add(run_type)
except Exception as e:
print(f"WARNING: Unable to determine what platform was used in {run_path.name}. Cannot add required citations.")
if len(run_types) > 0:
print(f"Adding citations for the following run types:")
for run_type in run_types:
print("\t" + run_type)
references.merge(CITATION_GROUPS[run_type])
print("")
else:
print(f"No recognized run types found.\n")
# add citations for any taxonomy/classifiers used
directory = str(pathfinder['intermediate_taxonomies'])
taxonomy_files = glob.glob(os.path.join(directory, "*_raw.*"))
for my_file in taxonomy_files:
match = re.match('^(.*?)_raw.(?:csv|txt)$', Path(my_file).name)
if match:
taxonomy = match.group(1)
if taxonomy not in CITATION_GROUPS.keys():
print(f"Unrecognized taxonomy: {taxonomy} inferred from file {my_file}, unable to add citations.")