-
Notifications
You must be signed in to change notification settings - Fork 0
/
EGAP.py
2129 lines (1879 loc) · 112 KB
/
EGAP.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 Sun Dec 22 19:57:46 2024
@author: ian.bollinger@entheome.org
EGAP (Entheome Genome Assembly Pipeline) is a versatile bioinformatics pipeline
developed for assembling high-quality hybrid genomes using Oxford Nanopore
Technologies (ONT) and Illumina sequencing data. It also supports de novo and
reference-based assemblies using Illumina data alone. The pipeline encompasses
comprehensive steps for read quality control, trimming, genome assembly, polishing,
and scaffolding. While optimized for fungal genomes, EGAP can be customized to
work with other types of organisms.
Modified From:
Bollinger IM, Singer H, Jacobs J, Tyler M, Scott K, Pauli CS, Miller DR,
Barlow C, Rockefeller A, Slot JC, Angel-Mosti V. High-quality draft genomes
of ecologically and geographically diverse Psilocybe species. Microbiol Resour
Announc 0:e00250-24. https://doi.org/10.1128/mra.00250-24
Muñoz-Barrera A, Rubio-Rodríguez LA, Jáspez D, Corrales A , Marcelino-Rodriguez I,
Lorenzo-Salazar JM, González-Montelongo R, Flores C. Benchmarking of bioinformatics
tools for the hybrid de novo assembly of human whole-genome sequencing data.
bioRxiv 2024.05.28.595812; doi: https://doi.org/10.1101/2024.05.28.595812
CLI EXAMPLE: python EGAP.py ...
Parameters:
--input_csv, -csv (str): Path to a csv containing multiple sample data. (default = None)
--raw_ont_dir, -odir (str): Path to a directory containing all Raw ONT Reads. (if -csv = None; else REQUIRED)
--raw_ont_reads, -i0 (str): Path to the combined Raw ONT fastq reads. (if -csv = None; else REQUIRED)
--raw_illu_dir, -idir (str): Path to a directory containing all Raw Illumina Reads. (if -csv = None; else REQUIRED)
--raw_illu_reads_1, -i1 (str): Path to the Raw Forward Illumina Reads. (if -csv = None; else REQUIRED)
--raw_illu_reads_2, -i2 (str): Path to the Raw Reverse Illumina Reads. (if -csv = None; else REQUIRED)
--species_id, -ID (str): Species ID formatted: <2-letters of Genus>_<full species name>. (if -csv = None; else REQUIRED)
--organism_kingdom, -Kg (str): Phylogenetic Kingdom the current organism data belongs to. (default: Funga)
--organism_karyote, -Ka (str): Karyote type of the organism. (default: Eukaryote)
--compleasm_1, -c1 (str): Name of the first organism compleasm/BUSCO database to compare to. (default: basidiomycota)
--compleasm_2, -c2 (str): Name of the second organism compleasm/BUSCO database to compare to. (default: agaricales)
--est_size, -es (str): Estimaged size of the genome in Mbp (aka million-base-pairs). (default: 60m)
--ref_seq, -rf (str): Path to the reference genome for assembly. (default: None)
--percent_resources, -R (float): Percentage of resources for processing. (default: 1.00)
CSV EXAMPLE:
ONT_RAW_DIR,ONT_RAW_READS,ILLUMINA_RAW_DIR,ILLUMINA_RAW_F_READS,ILLUMINA_RAW_R_READS,SPECIES_ID,ORGANISM_KINGDOM,ORGANISM_KARYOTE,COMPLEASM_1,COMPLEASM_2,EST_SIZE,REF_SEQ
None,/mnt/d/TESTING_SPACE/Ps_zapotecorum/ONT_MinION/SRR25932369.fq.gz,None,/mnt/d/TESTING_SPACE/Ps_zapotecorum/Illumina_PE150/SRR25932370_1.fq.gz,/mnt/d/TESTING_SPACE/Ps_zapotecorum/Illumina_PE150/SRR25932370_2.fq.gz,Ps_zapotecorum,Funga,Eukaryote,basidiomycota,agaricales,60m,None
None,/mnt/d/TESTING_SPACE/Ps_gandalfiana/ONT_MinION/SRR27945396.fq.gz,/mnt/d/TESTING_SPACE/Ps_gandalfiana/Illumina_PE150/B1_3,None,None,Ps_gandalfiana,Funga,Eukaryote,basidiomycota,agaricales,60m,/mnt/d/TESTING_SPACE/Ps_cubensis/GCF_017499595_1_MGC_Penvy_REF_SEQ/GCF_017499595_1_MGC_Penvy_1_genomic.fna
"""
# Python Imports
import math, platform, os, subprocess, multiprocessing, argparse, psutil, shutil, hashlib, re, gzip, glob
from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt
from Bio import SeqIO
from bs4 import BeautifulSoup
# Global Variables
CPU_THREADS = 1
RAM_GB = 1
DEFAULT_LOG_FILE = None
ENVIRONMENT_TYPE = None
# Functions Section
def generate_log_file(log_file_path, use_numerical_suffix=False):
"""
Generates or clears a log file based on the given parameters.
This function either creates a new log file or clears an existing one, depending on the specified parameters.
If the 'use_numerical_suffix' parameter is True, and the file already exists, a new file with a numerical suffix
will be created. Otherwise, the existing file will be cleared.
Parameters:
log_file_path (str): Path to the log file.
use_numerical_suffix (bool): If True, creates new files with numerical suffixes if the file exists; otherwise, clears the existing file.
Returns:
str: Path to the log file.
Notes:
- This function is essential for managing log file versions, especially in long-running applications or in situations where log file preservation is crucial.
- The numerical suffix increments for each new file created in the same location.
- When 'use_numerical_suffix' is False, it refreshes the log file by clearing existing content.
Considerations:
- Ensure the directory for the log file exists, or handle directory creation within the function or externally.
Examples:
log_file_path = "logs/my_log.txt"
generate_log_file(log_file_path, use_numerical_suffix=True)
"""
if os.path.exists(log_file_path) and use_numerical_suffix:
counter = 1
new_log_file_path = f"{log_file_path.rsplit('.', 1)[0]}_{counter}.txt"
while os.path.exists(new_log_file_path):
counter += 1
new_log_file_path = f"{log_file_path.rsplit('.', 1)[0]}_{counter}.txt"
log_file_path = new_log_file_path
else:
open(log_file_path, "w").close()
return log_file_path
def log_print(input_message, log_file=None):
"""
Logs a message to a file and prints it to the console with appropriate coloring.
This function takes a message and logs it to the specified file. Additionally, the message is printed to the
console, potentially with specific coloring depending on the context.
Parameters:
input_message (str): Message to be logged and printed.
log_file (str): Path to the log file.
Notes:
- This function serves as a centralized way to manage both logging and console output, ensuring consistency across the application.
- The function uses a global default log file if none is specified.
- Timestamps each log entry for easy tracking.
- Utilizes color coding in the console to distinguish between different types of messages (e.g., errors, warnings).
- Supports color coding for specific message types: NOTE, CMD, ERROR, WARN, and PASS.
- Falls back to default (white) color if the message type is unrecognized.
Considerations:
- Consider the security implications of logging sensitive information.
Examples:
log_print("NOTE: Starting process")
log_print("ERROR: An error occurred", log_file="error_log.txt")
"""
global DEFAULT_LOG_FILE
COLORS = {"grey": "\033[90m",
"red": "\033[91m",
"green": "\033[92m",
"yellow": "\033[93m",
"blue": "\033[94m",
"magenta": "\033[95m",
"cyan": "\033[96m",
"white": "\033[97m",
"reset": "\033[0m"}
if log_file is None:
log_file = DEFAULT_LOG_FILE
now = datetime.now()
message = f"[{now:%Y-%m-%d %H:%M:%S}]\t{input_message}"
message_type_dict = {"NOTE": "blue",
"CMD": "cyan",
"ERROR": "red",
"WARN": "yellow",
"PASS": "green",
"SKIP": "magenta",
"FAIL": "red"}
print_color = "white" # Default color
for key, value in message_type_dict.items():
if key.lower() in input_message.lower():
print_color = value
break
try:
with open(log_file, "a") as file:
print(message, file=file)
except TypeError:
print(f"UNLOGGED ERROR:\tUnable to load the log file provided: {log_file}")
color_code = COLORS.get(print_color, COLORS["white"])
print(f"{color_code}{message}{COLORS['reset']}")
def initialize_logging_environment(INPUT_FOLDER):
"""
Initializes the logging environment based on the given input file path.
This function sets up the logging environment by adjusting file paths according to the operating system in use,
ensuring file existence, and then generating a log file. It sets the global DEFAULT_LOG_FILE variable to the path
of the generated log file.
Parameters:
INPUT_FOLDER (str): Path to the folder which influences the log file generation.
Global Variables:
DEFAULT_LOG_FILE (str): The default path for the log file used throughout the logging process.
Notes:
- Adapts to different operating systems, making the logging system more flexible.
- Prints unlogged messages to the console regarding environment detection and file existence.
- Modifies the global DEFAULT_LOG_FILE variable.
Considerations:
- Verify the input folder's existence and accessibility before attempting to create a log file.
Examples:
input_folder = "data/input_data"
initialize_logging_environment(input_folder)
"""
global DEFAULT_LOG_FILE, ENVIRONMENT_TYPE
input_file_path = f"{INPUT_FOLDER}/{INPUT_FOLDER.split('/')[-1]}_log.txt"
os_name = platform.system()
if os_name == "Windows":
print("UNLOGGED:\tWINDOWS ENVIRONMENT")
ENVIRONMENT_TYPE = "WIN"
elif os_name in ["Linux", "Darwin"]: # Darwin is the system name for macOS
drive, path_without_drive = os.path.splitdrive(input_file_path)
if drive:
drive_letter = drive.strip(":\\/")
path_without_drive_mod = path_without_drive.replace("\\", "/")
input_file_path = f"/mnt/{drive_letter.lower()}{path_without_drive_mod}"
print("UNLOGGED:\tLINUX/WSL/MAC ENVIRONMENT")
ENVIRONMENT_TYPE = "LINUX/WSL/MAC"
else:
print(f"UNLOGGED ERROR:\tUnsupported OS: {os_name}")
return
run_log = generate_log_file(input_file_path, use_numerical_suffix=False)
DEFAULT_LOG_FILE = run_log
def run_subprocess_cmd(cmd_list, shell_check):
"""
Executes a command using the subprocess.Popen and displays its output in real-time.
This function is designed to execute shell commands from within a Python script. It uses subprocess.Popen to
provide real-time output of the command to the command line window. It also logs the command execution details.
Parameters:
cmd_list (str or list of str): The command to be executed. Can be a single string or a list of strings
representing the command and its arguments.
shell_check (bool): If True, the command is executed through the shell. This is necessary for some
commands, especially those that are built into the shell or involve shell features
like wildcard expansion.
Features:
- Uses subprocess.Popen for more control over command execution.
- Captures the command's standard output and errors in real-time and displays them as they occur.
- Waits for the command to complete, checks the return code to determine success or failure, and returns it.
- Logs the command, its real-time output, and any execution errors.
Usage and Considerations:
- Useful for executing commands where live feedback is important, especially for long-running commands.
- Requires careful use of 'shell_check' due to potential security risks with shell commands.
Example:
result_code = run_subprocess_cmd(["ls", "-l"], shell_check=False)
print("Return code:", result_code)
"""
if isinstance(cmd_list, str):
log_print(f"CMD:\t{cmd_list}")
process = subprocess.Popen(cmd_list, shell=shell_check, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
else:
log_print(f"CMD:\t{' '.join(cmd_list)}")
process = subprocess.Popen(cmd_list, shell=shell_check, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
for line in process.stdout:
print(line, end="")
process.wait()
if process.returncode != 0:
log_print(f"NOTE:\tCommand failed with return code {process.returncode}")
else:
log_print(f"PASS:\tSuccessfully processed command: {' '.join(cmd_list)}" if isinstance(cmd_list, list) else cmd_list)
return process.returncode
def get_resource_values(PERCENT_RESOURCES):
"""
Converts user input PERCENT_RESOURCES into usuable cpu_threads and ram_gb values.
Parameters:
PERCENT_RESOURCES (float): Percentage of resources to use.
Returns:
cpu_threads (str): A count of the CPUs available for processing.
ram_gb (str): A count of the RAM (in GB) available for processing.
Notes:
- Allows dynamic allocation of resources based on the system's current state.
Considerations:
- Ensure that the PERCENT_RESOURCES value is within an acceptable range to avoid over-utilization of system resources.
Examples:
cpu_threads, ram_gb = get_resource_values(0.5) # Use 50% of system resources
"""
num_cpus = multiprocessing.cpu_count()
mem_info = psutil.virtual_memory()
cpu_threads = int(math.floor(num_cpus * PERCENT_RESOURCES))
ram_gb = int(mem_info.total / (1024.0 ** 3) * PERCENT_RESOURCES)
return cpu_threads, ram_gb
def find_file(filename):
"""
Searches for a file within the current working directory.
Parameters:
filename (str): The name of the file to search for.
Returns:
str: The path to the first instance of the file, if found.
None: If the file is not found.
Notes:
- Useful for setups where the exact location of a file might vary.
Considerations:
- This function might take a long time in large file systems.
Examples:
file_path = find_file("config.json")
if file_path:
print(f"Found config at {file_path}")
else:
print("Config file not found")
"""
global ENVIRONMENT_TYPE
log_print(f"Looking for {filename}")
if ENVIRONMENT_TYPE == "WIN":
root_directory = "C:\\" # Adjust if necessary for different drives
elif ENVIRONMENT_TYPE in ["LINUX/WSL/MAC"]:
root_directory = "/"
else:
raise ValueError("Unknown ENVIRONMENT_TYPE")
for root, dirs, files in os.walk(root_directory):
if filename in files:
return os.path.join(root, filename)
return None
def md5_check(illumina_raw_data_dir, illumina_df):
"""
Run MD5 checksums on all `.FQ.GZ` files in the provided directory, referencing expected checksums from an `MD5.txt` file.
Parameters:
illumina_raw_data_dir (str):
Path to the main Illumina Raw Reads Data Directory, which should contain a `MD5.txt` file
and the `.FQ.GZ` files to be checked.
illumina_df (DataFrame):
A pandas DataFrame intended to be populated with `MD5` checksums and filenames.
Returns:
DataFrame:
Updated `illumina_df` containing the original MD5 checksums (from `MD5.txt`) and any newly discovered `.FQ.GZ` files
that match those checksums.
Notes:
- The function reads a `MD5.txt` file, splits its contents into a dictionary, then populates the provided DataFrame.
- It iterates over all `.gz` files, computes the new MD5 and compares it to the original MD5 to detect mismatches.
Considerations:
- This function will raise an error only through log messages (`log_print`) if the MD5 is missing or mismatched.
- If a mismatch is found, the function breaks out of the loop but does not raise an exception.
Adjust logic if you need strict error handling.
Examples:
>>> # Example usage:
>>> illumina_df = pd.DataFrame(columns=["MD5", "Filename"])
>>> updated_df = md5_check("/path/to/illumina/raw_data", illumina_df)
>>> print(updated_df.head())
"""
md5_file_path = os.path.join(illumina_raw_data_dir, "MD5.txt")
if os.path.exists(md5_file_path):
with open(md5_file_path, "r") as f:
md5_data = f.read().splitlines()
md5_dict = dict(line.split() for line in md5_data)
md5_df = pd.DataFrame(md5_dict.items(), columns=["MD5", "Filename"])
illumina_df = pd.concat([illumina_df, md5_df], ignore_index=True)
for file_name in os.listdir(illumina_raw_data_dir):
if file_name.endswith(".gz"):
gz_file_path = os.path.join(illumina_raw_data_dir, file_name)
matching_row = illumina_df[illumina_df["Filename"].str.contains(file_name)].head(1)
original_md5 = matching_row["MD5"].iloc[0] if not matching_row.empty else "None"
if original_md5 != "None":
hash_md5 = hashlib.md5()
with open(gz_file_path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
new_md5 = hash_md5.hexdigest()
if original_md5 != new_md5:
log_print(f"ERROR:\tMD5 checksum mismatch for {gz_file_path}: original {original_md5}, new {new_md5}")
break
else:
log_print(f"PASS:\tOriginal MD5 MATCHES for {file_name.split('/')[-1]}")
else:
log_print(f"ERROR:\tOriginal MD5 checksum not found for {file_name.split('/')[-1]}")
break
def illumina_extract_and_check(folder_name, SPECIES_ID):
"""
Extract and verify Illumina MD5 checksums, then combine paired-end reads into single forward and reverse files.
Parameters:
folder_name (str):
Path to the folder containing Illumina data (`.fq.gz` files and `MD5.txt`).
SPECIES_ID (str):
A unique identifier for the species. Used to name the combined output files.
Returns:
list:
A list of two gzipped combined FASTQ files. The first (`_combined_1.fq.gz`) corresponds to forward reads,
and the second (`_combined_2.fq.gz`) to reverse reads.
Notes:
- This function calls `md5_check` to verify checksums and populate a DataFrame with MD5 data.
- After MD5 verification, if combined files do not already exist, it concatenates raw forward and reverse
FASTQ files, and then gzips them.
Considerations:
- If the combined or gzipped files already exist, the function will skip regeneration steps and simply return
the existing file paths.
- Adjust logging or error-handling logic as needed.
Examples:
>>> # Example usage:
>>> combined_files = illumina_extract_and_check("/path/to/illumina/folder", "MySpecies")
>>> print(combined_files)
['/path/to/illumina/../MySpecies_combined_1.fq.gz',
'/path/to/illumina/../MySpecies_combined_2.fq.gz']
"""
log_print(f"Running MD5 Checksum Analysis on Raw Illumina FASTQ.GZ files in {folder_name}...")
illumina_df = pd.DataFrame(columns=["MD5", "Filename"])
base_data_dir = os.path.dirname(folder_name)
combined_1_file = os.path.join(base_data_dir, f"{SPECIES_ID}_combined_1.fq")
combined_2_file = os.path.join(base_data_dir, f"{SPECIES_ID}_combined_2.fq")
combined_list = [combined_1_file, combined_2_file]
combined_gz_list = [f"{combined_fq}.gz" for combined_fq in combined_list]
if not os.path.isfile(combined_gz_list[0]) or not os.path.isfile(combined_gz_list[0]):
if not os.path.isfile(combined_1_file) or not os.path.isfile(combined_2_file):
md5_check(folder_name, illumina_df)
raw_1_list = []
raw_2_list = []
for filename in os.listdir(folder_name):
if "_1.fq.gz" in filename:
raw_1_list.append(os.path.join(folder_name,filename))
elif "_2.fq.gz" in filename:
raw_2_list.append(os.path.join(folder_name,filename))
fwd_cat_cmd = f"cat {raw_1_list[0]} {raw_1_list[1]} > {combined_1_file}"
_ = run_subprocess_cmd(fwd_cat_cmd, shell_check = True)
rev_cat_cmd = f"cat {raw_2_list[0]} {raw_2_list[1]} > {combined_2_file}"
_ = run_subprocess_cmd(rev_cat_cmd, shell_check = True)
else:
log_print(f"SKIP:\tCombined FASTQ files already exist: {combined_list[0]}; {combined_list[1]}.")
for combined_fq in combined_list:
gzip_cmd = ["gzip", combined_fq]
_ = run_subprocess_cmd(gzip_cmd, shell_check = False)
else:
log_print(f"SKIP:\tGzipped Combined FASTQ files already exist: {combined_gz_list[0]}; {combined_gz_list[1]}.")
return combined_gz_list
def classify_metric(value, thresholds):
"""
Classifies a given value according to specified thresholds for genome assembly metrics.
Parameters:
value (float): The metric value to classify.
thresholds (dict): A dictionary specifying the classification thresholds for AMAZING, GREAT, OK, and POOR.
Returns:
str: A string classification of the value ("AMAZING", "GREAT", "OK", "POOR").
Notes:
- This function simplifies the process of metric evaluation across different genome assembly parameters.
Considerations:
- Ensure that the 'thresholds' dictionary is correctly set up with appropriate limits for each category.
Examples:
n50_classification = classify_metric(1500000, {"AMAZING": 1000000, "GREAT": 100000, "OK": 1000, "POOR": 100})
print(n50_classification) # Output should be "AMAZING"
"""
if value >= thresholds["AMAZING"]:
return "AMAZING"
elif value >= thresholds["GREAT"]:
return "GREAT"
elif value >= thresholds["OK"]:
return "OK"
elif value >= thresholds["POOR"]:
return "POOR"
else:
if value <= thresholds["AMAZING"]:
return "AMAZING"
elif value <= thresholds["GREAT"]:
return "GREAT"
elif value <= thresholds["OK"]:
return "OK"
elif value <= thresholds["POOR"]:
return "POOR"
def classify_assembly(sample_stats):
"""
Classifies the genome assembly quality based on multiple metrics, including BUSCO scores, N50, and number of contigs.
Parameters:
sample_stats (dict): A dictionary containing the values for various assembly metrics such as "FIRST_COMPLEASM_C",
"SECOND_COMPLEASM_C", "ASSEMBLY_N50", and "ASSEMBLY_CONTIGS".
Returns:
dict: A dictionary with the classification for each metric and an overall classification based on combined criteria.
Notes:
- This function utilizes `classify_metric` for individual assessments and determines the overall quality.
- Provides a granular and comprehensive evaluation of genome assembly quality.
Considerations:
- The overall assembly quality heavily depends on the individual classifications. A single "POOR" rating can impact
the overall rating.
- Adjusting the individual thresholds will affect the sensitivity of the classification.
Examples:
sample_stats_dict = {"FIRST_COMPLEASM_C": 99, "SECOND_COMPLEASM_C": 97, "ASSEMBLY_N50": 1500000, "ASSEMBLY_CONTIGS": 50}
assembly_quality = classify_assembly(sample_stats_dict)
print(assembly_quality)
# Output: {"FIRST_COMPLEASM_C": "AMAZING", "SECOND_COMPLEASM_C": "AMAZING", "ASSEMBLY_N50": "AMAZING", "ASSEMBLY_CONTIGS": "AMAZING", "OVERALL": "AMAZING"}
"""
results = {}
busco_thresholds = {"AMAZING": 98.5, "GREAT": 95.0, "OK": 90.0, "POOR": 80.0}
n50_thresholds = {"AMAZING": 1000000, "GREAT": 100000, "OK": 1000, "POOR": 100}
contigs_thresholds = {"AMAZING": 100, "GREAT": 1000, "OK": 10000, "POOR": 100000}
results["FIRST_COMPLEASM_C"] = classify_metric(sample_stats["FIRST_COMPLEASM_C"], busco_thresholds)
results["SECOND_COMPLEASM_C"] = classify_metric(sample_stats["SECOND_COMPLEASM_C"], busco_thresholds)
results["ASSEMBLY_N50"] = classify_metric(sample_stats["ASSEMBLY_N50"], n50_thresholds)
results["ASSEMBLY_CONTIGS"] = classify_metric(sample_stats["ASSEMBLY_CONTIGS"], contigs_thresholds)
if all(value == "AMAZING" for value in results.values()):
results["OVERALL"] = "AMAZING"
elif any(value == "POOR" for value in results.values()):
results["OVERALL"] = "POOR"
elif any(value == "OK" for value in results.values()):
results["OVERALL"] = "OK"
elif any(value == "GREAT" for value in results.values()):
results["OVERALL"] = "GREAT"
return results
def plot_classification_table(df):
"""
Generate a color-coded table from a DataFrame where each cell’s color corresponds to a classification label.
Parameters:
df (DataFrame):
A pandas DataFrame where indices are sample identifiers and columns are metrics.
The cell values should be classification labels (e.g., "AMAZING", "GREAT", "OK", "POOR").
Returns:
None:
This function displays a matplotlib figure showing the table, but does not return a value.
Notes:
- This function uses matplotlib’s table functionality to create a color-mapped table.
- The `color_map` dictionary defines the relationship between classification labels and cell colors.
Considerations:
- Ensure that the cell values in `df` match the keys in `color_map` if you want custom colors.
- Adjust the figure size or layout for optimal display of large tables.
Examples:
>>> # Example usage:
>>> data = {
... "Metric1": ["AMAZING", "GREAT", "POOR"],
... "Metric2": ["OK", "GREAT", "AMAZING"]
... }
>>> sample_df = pd.DataFrame(data, index=["SampleA", "SampleB", "SampleC"])
>>> plot_classification_table(sample_df)
# A matplotlib figure should pop up showing a color-coded table.
"""
color_map = {"AMAZING": "lightorchid",
"GREAT": "green",
"OK": "cornflowerblue",
"POOR": "orange",}
colors = df.applymap(lambda x: color_map.get(x, "white"))
fig, ax = plt.subplots(figsize=(10, 2)) # Adjust the figure size as necessary
ax.axis("tight")
ax.axis("off")
ax.table(cellText = df.values, colLabels = df.columns,
cellColours = colors.values, cellLoc = "center", loc = "center")
plt.show()
def find_ca_folder(input_folder):
"""
Determine the specific location of the MaSuRCA output folder named `CA`.
Parameters:
input_folder (str):
Path to the folder containing MaSuRCA outputs. It may have subdirectories,
one of which might begin with "CA" (e.g., "CA", "CA_12345", etc.).
Returns:
str:
The path to the first subfolder starting with "CA". If none is found,
returns a default path `<input_folder>/CA`.
Notes:
- This function scans the immediate subfolders of `input_folder` and returns
the one that starts with "CA".
- If no subfolder starts with "CA", it defaults to `<input_folder>/CA`.
Considerations:
- Ensure `input_folder` is a valid path containing directories.
- If multiple folders begin with "CA", it returns the first one found.
Examples:
>>> # Example usage:
>>> ca_path = find_ca_folder("/path/to/masurca_outputs")
>>> print(ca_path)
"/path/to/masurca_outputs/CA_20230101"
"""
subfolders = [f.path for f in os.scandir(input_folder) if f.is_dir()]
ca_folder = f"{input_folder}/CA"
for folder in subfolders:
if os.path.basename(folder).startswith("CA"):
ca_folder = folder
break
return ca_folder
def parse_bbmerge_output(insert_size_histogram_txt):
"""
Extract average insert size and standard deviation from a BBMerge insert size histogram.
Parameters:
insert_size_histogram_txt (str):
Path to the `insert_size_histogram.txt` file produced by BBMerge.
Returns:
tuple:
A 2-tuple containing:
- avg_insert (float): The average insert size.
- std_dev (float): The standard deviation of the insert size.
Notes:
- The file is expected to contain lines starting with `#Mean` and `#STDev`.
- If those lines are not found, a ValueError is raised.
Considerations:
- If the insert size file format changes in newer BBMerge versions,
this function may need updating.
Examples:
>>> # Suppose the insert_size_histogram.txt has lines:
>>> #Mean 250.7
>>> #STDev 30.2
>>> avg, std = parse_bbmerge_output("/path/to/insert_size_histogram.txt")
>>> print(avg, std)
(251.0, 30.0)
"""
log_print(f"Processing insert size histogram: {insert_size_histogram_txt}...")
avg_insert = None
std_dev = None
with open(insert_size_histogram_txt, "r") as file:
for line in file:
if "#Mean\t" in line:
avg_insert = round(float(line.replace("#Mean\t", "").replace("\n", "")), 0)
if "#STDev\t" in line:
std_dev = round(float(line.replace("#STDev\t", "").replace("\n", "")), 0)
if avg_insert is None or std_dev is None:
raise ValueError("Could not find average insert size and/or standard deviation in the output.")
return avg_insert, std_dev
def bbmap_stats(input_folder, reads_list):
"""
Use BBMap (specifically BBMerge) to calculate statistics like average insert size and standard deviation.
Parameters:
input_folder (str):
Path to the folder where intermediate outputs (e.g., `bbmap_data.fq.gz`, `insert_size_histogram.txt`)
will be stored or read from.
reads_list (list):
A list of paths to FASTQ files.
- If there are two items, they are treated as forward and reverse reads.
- If there is one item, it is treated as a single-end read.
Returns:
tuple:
A 2-tuple of (avg_insert, std_dev) representing the average insert size and standard deviation.
Notes:
- If an existing `insert_size_histogram.txt` is found, the function reuses it and skips rerunning BBMerge.
- If the file is missing, BBMerge is invoked to generate it.
Considerations:
- By default, if parsing fails, the function logs a note and uses the default `(251, 30)` values.
- Ensure `BBMerge` or `bbmerge.sh` is installed and accessible in `PATH` or specify the full path as needed.
Examples:
>>> # Example usage with paired-end reads:
>>> stats = bbmap_stats("/path/to/folder", ["/path/to/read1.fq.gz", "/path/to/read2.fq.gz"])
>>> print(stats)
(250, 30)
"""
bbmap_out_path = f"{input_folder}/bbmap_data.fq.gz"
insert_size_histogram_txt = f"{input_folder}/insert_size_histogram.txt"
log_print(f"NOTE:\tCurrent bbmap out path: {bbmap_out_path}")
default_bbmerge_path = "bbmerge.sh"
avg_insert = 251
std_dev = 30
if os.path.isfile(insert_size_histogram_txt):
log_print(f"SKIP:\tbbmap insert size histogram output already exists: {insert_size_histogram_txt}")
avg_insert, std_dev = parse_bbmerge_output(insert_size_histogram_txt)
else:
log_print("Processing fastq files for bbmap stats...")
bbmerge_path = find_file(default_bbmerge_path)
print(reads_list)
if len(reads_list) == 3:
bbmerge_cmd = [bbmerge_path,
f"in1={reads_list[1]}",
f"in2={reads_list[2]}",
f"out={bbmap_out_path}",
f"ihist={input_folder}/insert_size_histogram.txt"]
elif len(reads_list) == 2:
bbmerge_cmd = [bbmerge_path,
f"in1={reads_list[0]}",
f"in2={reads_list[1]}",
f"out={bbmap_out_path}",
f"ihist={input_folder}/insert_size_histogram.txt"]
_ = run_subprocess_cmd(bbmerge_cmd, False)
try:
avg_insert, std_dev = parse_bbmerge_output(insert_size_histogram_txt)
except:
log_print("NOTE:\tUnable to parse avg_insert or std_dev, using default values: 251 and 30 respectively.")
avg_insert = 251
std_dev = 30
return avg_insert, std_dev
def skip_gap_closing_section(assembly_sh_path):
"""
Modify a MaSuRCA `assemble.sh` script to skip the gap closing step, forcing the final output to remain at
stage "9-terminator".
Parameters:
assembly_sh_path (str):
Path to the `assemble.sh` script generated by MaSuRCA.
Returns:
None:
This function writes out a modified script named `assemble_skip_gap.sh` in the current working directory
but does not return a value.
Notes:
- Uses a regular expression to locate the `if [ -s $CA_DIR/9-terminator/genome.scf.fasta ];then ... else ... fi`
block and replace its content with a snippet that logs a skip message and sets `TERMINATOR="9-terminator"`.
- The original script is read in full, and only that specific section is replaced.
The rest of the script is left unmodified.
Considerations:
- Ensure the original `assemble.sh` contains the expected pattern. If the pattern changes in newer versions,
this function needs updating.
- The new script is always named `assemble_skip_gap.sh`; be mindful that running this multiple times
might overwrite existing files.
Examples:
>>> # Example usage:
>>> skip_gap_closing_section("/path/to/assemble.sh")
>>> # A file named "assemble_skip_gap.sh" is created with the gap closing step skipped.
"""
with open(assembly_sh_path, "r") as f_in:
original_script = f_in.read()
# Regex Explanation:
#
# (if \[ -s \$CA_DIR/9-terminator/genome\.scf\.fasta \];then)
# Captures the exact `if [ -s $CA_DIR/9-terminator/genome.scf.fasta ];then` line as group 1
#
# ( .*? )
# Lazily matches everything in between, as group 2
#
# (else\s+fail "Assembly stopped or failed, see \$CA_DIR\.log"\nfi)
# Captures the part from `else` down to the `fi` as group 3, preserving that code
#
# We use DOTALL so that `.` also matches newlines.
pattern = re.compile(r"(if \[ -s \$CA_DIR/9-terminator/genome\.scf\.fasta \];then)"
r"(.*?)"
r"(else\s+fail 'Assembly stopped or failed, see \$CA_DIR\.log'\nfi)",
re.DOTALL)
replacement_snippet = (r"\1\n"
r" # Force the final terminator to remain '9-terminator'\n"
r" log \"Skipping gap closing step; using 9-terminator as final.\"\n"
r" TERMINATOR='9-terminator'\n"
r"\3")
modified_text = re.sub(pattern, replacement_snippet, original_script)
with open("assemble_skip_gap.sh", "w") as f_out:
f_out.write(modified_text)
def masurca_config_gen(input_folder, output_folder, input_fq_list, clump_f_dedup_path, clump_r_dedup_path, CPU_THREADS, ram_gb, ref_seq=None):
"""
DESCRIPTION:
Generates a MaSuRCA configuration file and runs a genome assembly workflow.
This includes creating a config file based on input parameters, optionally skipping
gap closing, and running the assembly. The assembled output is moved or renamed
depending on whether a reference sequence is used.
Parameters:
input_folder (str):
The directory where input data (and possibly the CA sub-folder) is located.
output_folder (str):
The directory where the MaSuRCA config file and assembly scripts will be generated.
input_fq_list (list of str):
A list of input FASTQ files (often 2 for paired-end reads).
clump_f_dedup_path (str):
The path to the forward de-duplicated FASTQ file (e.g., from Clumpify).
clump_r_dedup_path (str):
The path to the reverse de-duplicated FASTQ file (e.g., from Clumpify).
CPU_THREADS (int):
The number of threads available for the assembly process.
ram_gb (int):
The amount of RAM (in GB) available to the assembly process.
ref_seq (str, optional):
An optional path to a reference genome. If provided, the assembled output
will be renamed to "primary.genome.ref.fasta".
Returns:
tuple:
A tuple of strings indicating:
(1) `default_assembly_path`: The default path to the primary assembled genome
(e.g., "CAfolder/primary.genome.scf.fasta").
(2) `assembly_path`: The path to the primary assembled genome if reference
is not used (e.g., "input_folder/primary.genome.scf.fasta").
(3) `ref_assembly_path` (or None if `ref_seq` is not provided).
Notes:
- The function relies on a correct folder structure where a "CA" sub-folder
(created by MaSuRCA or another pipeline step) is located in `input_folder`.
- Adjustments to the JF_SIZE parameter are made based on available RAM
to potentially improve efficiency.
Considerations:
- The function skips re-running MaSuRCA if it detects that the assembled output
files already exist.
- It modifies the `assemble.sh` script via `skip_gap_closing_section` to skip
certain gap-closing steps, which can shorten runtime but may reduce assembly contiguity.
- Error handling for MaSuRCA is performed by checking the return code of
the assembly command; if it’s 1, an error is logged, but no further exception is raised.
Examples:
>>> # Example usage:
>>> input_folder = "/path/to/input_data"
>>> output_folder = "/path/to/output_data"
>>> input_fq_list = ["reads_1.fastq", "reads_2.fastq"]
>>> clump_f_dedup_path = "/path/to/reads_forward_dedup.fastq"
>>> clump_r_dedup_path = "/path/to/reads_reverse_dedup.fastq"
>>> CPU_THREADS = 16
>>> ram_gb = 64
>>> ref_seq = "/path/to/reference.fna"
>>> result_paths = masurca_config_gen(
... input_folder, output_folder, input_fq_list,
... clump_f_dedup_path, clump_r_dedup_path,
... CPU_THREADS, ram_gb, ref_seq
... )
>>> print(result_paths)
("/path/to/CAfolder/primary.genome.scf.fasta",
"/path/to/input_data/primary.genome.scf.fasta",
"/path/to/input_data/primary.genome.ref.fasta")
"""
avg_insert, std_dev = bbmap_stats(input_folder, input_fq_list)
os.chdir(output_folder)
jf_size = 2500000000 # BASED ON estimated_genome_size*20
max_ram_tested = 62
if ram_gb < max_ram_tested:
adjustment_ratio = ram_gb / max_ram_tested
jf_size = int(round(jf_size * adjustment_ratio, 0))
ca_folder = find_ca_folder(input_folder)
default_assembly_path = os.path.join(ca_folder, "primary.genome.scf.fasta")
assembly_path = os.path.join(input_folder, "primary.genome.scf.fasta")
ref_assembly_path = os.path.join(input_folder, "primary.genome.ref.fasta")
if len(input_fq_list) == 2:
illu_only_mates = 1
illu_only_gaps = 1
illu_only_soap = 0
elif len(input_fq_list) >= 2:
illu_only_mates = 0
illu_only_gaps = 0
illu_only_soap = 1
if os.path.exists(default_assembly_path):
log_print("PASS:\tSkipping MaSuRCA, moving output files")
if ref_seq:
shutil.move(default_assembly_path, ref_assembly_path)
else:
shutil.move(default_assembly_path, assembly_path)
elif os.path.exists(assembly_path):
log_print(f"SKIP:\tMaSuRCA Assembly, scaffolded assembly already exists: {assembly_path}.")
else:
config_content = ["DATA\n",
f"PE= pe {avg_insert} {std_dev} {clump_f_dedup_path} {clump_r_dedup_path}\n"]
if ref_seq:
config_content.append(f"REFERENCE={ref_seq.replace('.gbff','.fna.gz')}\n")
config_content.append("END\n")
config_content.append("PARAMETERS\n")
config_content.append("GRAPH_KMER_SIZE=auto\n")
config_content.append(f"USE_LINKING_MATES={illu_only_mates}\n") # IF ILLUMINA ONLY SET TO 1, ELSE 0
config_content.append(f"CLOSE_GAPS={illu_only_gaps}\n") # IF ILLUMINA ONLY SET TO 1, ELSE 0
config_content.append("MEGA_READS_ONE_PASS=0\n")
config_content.append("LIMIT_JUMP_COVERAGE=300\n")
config_content.append("CA_PARAMETERS=cgwErrorRate=0.15\n")
config_content.append(f"NUM_THREADS={CPU_THREADS}\n")
config_content.append(f"JF_SIZE={jf_size}\n")
config_content.append(f"SOAP_ASSEMBLY={illu_only_soap}\n") # IF ILLUMINA ONLY SET TO 0, ELSE 1
config_content.append("END\n")
config_path = f"{output_folder}/masurca_config_file.txt"
with open(config_path, "w") as file:
for entry in config_content:
file.write(entry)
masurca_config_cmd = ["masurca", "masurca_config_file.txt"]
_ = run_subprocess_cmd(masurca_config_cmd, False)
assemble_sh_path = f"{output_folder}/assemble.sh"
skip_gap_closing_section(assemble_sh_path)
masurca_assemble_cmd = ["bash", assemble_sh_path]
return_code = run_subprocess_cmd(masurca_assemble_cmd, False)
if return_code == 1:
log_print("NOTE:\tMaSuRCA assembly interrupted intentionally; Gap Closing will be performed later.")
ca_folder = find_ca_folder(input_folder)
default_assembly_path = os.path.join(ca_folder, os.path.basename(default_assembly_path))
return default_assembly_path, assembly_path, ref_assembly_path if ref_seq else None
return default_assembly_path, assembly_path, ref_assembly_path if ref_seq else None
def bbduk_map(trimmo_f_pair_path, trimmo_r_pair_path):
"""
DESCRIPTION:
Runs BBDuk to perform quality trimming and adapter removal on paired-end FASTQ files.
The function will generate two new FASTQ files (forward and reverse) with "_mapped"
in their file names to indicate they have been processed by BBDuk.
Parameters:
trimmo_f_pair_path (str):
The file path to the forward paired FASTQ file (e.g., "sample_1_paired.fastq").
trimmo_r_pair_path (str):
The file path to the reverse paired FASTQ file (e.g., "sample_2_paired.fastq").
Returns:
tuple of str:
A tuple containing the paths to the forward and reverse mapped FASTQ files
(e.g., "sample_forward_mapped.fastq", "sample_reverse_mapped.fastq").
Notes:
- This function assumes your forward reads end in "_1_paired.{extension}"
and your reverse reads end in "_2_paired.{extension}".
- It also expects that BBDuk ("bbduk.sh") and a file of adapters ("adapters.fa")
are accessible via the `find_file` utility function.
- The BBDuk command used here includes parameters for trimming based on quality score (qtrim=rl, trimq=20)
and adapter removal (ktrim=r, ref=adapters.fa, etc.). Adjust them as needed.
Considerations:
- If BBDuk or the adapters file are not found, the function will fail unless handled in `find_file`.
- If the output mapped files already exist, the function skips re-processing and logs a message.
- Ensure the user has read/write access to the specified paths.
Examples:
>>> # Example usage:
>>> forward_in = "sample_1_paired.fastq"
>>> reverse_in = "sample_2_paired.fastq"
>>> f_mapped, r_mapped = bbduk_map(forward_in, reverse_in)
>>> print(f_mapped, r_mapped)
sample_forward_mapped.fastq sample_reverse_mapped.fastq
"""
file_extension = trimmo_f_pair_path.split("_1_paired.")[1]
bbduk_f_map_path = trimmo_f_pair_path.replace(f"_1_paired.{file_extension}", f"_forward_mapped.{file_extension}")
bbduk_r_map_path = trimmo_r_pair_path.replace(f"_2_paired.{file_extension}", f"_reverse_mapped.{file_extension}")
if os.path.exists(bbduk_f_map_path) and os.path.exists(bbduk_r_map_path):
log_print(f"SKIP:\tbbduk Mapped outputs already exist: {bbduk_f_map_path}; {bbduk_r_map_path}.")
else:
default_adapters_path = "adapters.fa"
default_bbduk_path = "bbduk.sh"
adapters_path = find_file(default_adapters_path)
bbduk_path = find_file(default_bbduk_path)
bbduk_cmd = [bbduk_path,
f"in1={trimmo_f_pair_path}", f"in2={trimmo_r_pair_path}",
f"out1={bbduk_f_map_path}", f"out2={bbduk_r_map_path}",
f"ref={adapters_path}", "ktrim=r", "k=23", "mink=11", "hdist=1",
"tpe", "tbo", "qtrim=rl", "trimq=20"]
_ = run_subprocess_cmd(bbduk_cmd, False)
return bbduk_f_map_path, bbduk_r_map_path
def clumpify_dedup(bbduk_f_map_path, bbduk_r_map_path):
"""
DESCRIPTION:
De-duplicates paired-end FASTQ files using Clumpify. If the output files already exist,
the command is skipped, otherwise Clumpify is invoked to generate de-duplicated versions.
Parameters:
bbduk_f_map_path (str):
The path to the forward mapped FASTQ file (e.g., "reads_forward_mapped.fastq").
bbduk_r_map_path (str):
The path to the reverse mapped FASTQ file (e.g., "reads_reverse_mapped.fastq").
Returns:
tuple of str:
A tuple containing the paths to the forward and reverse de-duplicated FASTQ files.
Notes:
- This function assumes that the forward file name contains "_forward_mapped."
and the reverse file name contains "_reverse_mapped." within their paths.
- Relies on the external Clumpify program ("clumpify.sh") being accessible in the
system's PATH or in a known location that `find_file` can discover.
Considerations:
- Ensure that the user has permission to read and write to the specified paths.
- The deduplicated output files will replace "mapped" with "dedup" in their file names.
- If Clumpify is not found, the process will likely fail unless handled by `find_file`.
Examples:
>>> # Example usage:
>>> # Suppose we have two mapped FASTQ files: