PyamilySeq 1.0.0__py3-none-any.whl → 1.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- PyamilySeq/Cluster_Summary.py +163 -0
- PyamilySeq/Group_Splitter.py +571 -0
- PyamilySeq/PyamilySeq.py +316 -0
- PyamilySeq/PyamilySeq_Genus.py +242 -0
- PyamilySeq/PyamilySeq_Species.py +309 -0
- PyamilySeq/Seq_Combiner.py +66 -0
- PyamilySeq/Seq_Extractor.py +64 -0
- PyamilySeq/Seq_Finder.py +56 -0
- PyamilySeq/__init__.py +0 -0
- PyamilySeq/clusterings.py +452 -0
- PyamilySeq/constants.py +2 -0
- PyamilySeq/utils.py +566 -0
- PyamilySeq-1.0.1.dist-info/METADATA +381 -0
- PyamilySeq-1.0.1.dist-info/RECORD +18 -0
- PyamilySeq-1.0.1.dist-info/entry_points.txt +7 -0
- PyamilySeq-1.0.1.dist-info/top_level.txt +1 -0
- PyamilySeq-1.0.0.dist-info/METADATA +0 -17
- PyamilySeq-1.0.0.dist-info/RECORD +0 -6
- PyamilySeq-1.0.0.dist-info/entry_points.txt +0 -2
- PyamilySeq-1.0.0.dist-info/top_level.txt +0 -1
- {PyamilySeq-1.0.0.dist-info → PyamilySeq-1.0.1.dist-info}/LICENSE +0 -0
- {PyamilySeq-1.0.0.dist-info → PyamilySeq-1.0.1.dist-info}/WHEEL +0 -0
PyamilySeq/PyamilySeq.py
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
try:
|
|
5
|
+
from .PyamilySeq_Species import cluster as species_cluster
|
|
6
|
+
from .PyamilySeq_Genus import cluster as genus_cluster
|
|
7
|
+
from .constants import *
|
|
8
|
+
from .utils import *
|
|
9
|
+
except (ModuleNotFoundError, ImportError, NameError, TypeError) as error:
|
|
10
|
+
from PyamilySeq_Species import cluster as species_cluster
|
|
11
|
+
from PyamilySeq_Genus import cluster as genus_cluster
|
|
12
|
+
from constants import *
|
|
13
|
+
from utils import *
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def run_cd_hit(options, input_file, clustering_output, clustering_mode):
|
|
19
|
+
cdhit_command = [
|
|
20
|
+
clustering_mode,
|
|
21
|
+
'-i', input_file,
|
|
22
|
+
'-o', clustering_output,
|
|
23
|
+
'-c', str(options.pident),
|
|
24
|
+
'-s', str(options.len_diff),
|
|
25
|
+
'-T', str(options.threads),
|
|
26
|
+
'-M', str(options.mem),
|
|
27
|
+
'-d', "0",
|
|
28
|
+
'-g', str(options.fast_mode),
|
|
29
|
+
'-sc', "1",
|
|
30
|
+
'-sf', "1"
|
|
31
|
+
]
|
|
32
|
+
if options.verbose == True:
|
|
33
|
+
subprocess.run(cdhit_command)
|
|
34
|
+
else:
|
|
35
|
+
subprocess.run(cdhit_command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def main():
|
|
39
|
+
parser = argparse.ArgumentParser(description=f"PyamilySeq {PyamilySeq_Version}: A tool for gene clustering and analysis.")
|
|
40
|
+
|
|
41
|
+
# Add subparsers for Full and Partial modes
|
|
42
|
+
subparsers = parser.add_subparsers(dest="run_mode", required=True, help="Choose a mode: 'Full' or 'Partial'.")
|
|
43
|
+
|
|
44
|
+
# Full Mode Subparser
|
|
45
|
+
full_parser = subparsers.add_parser("Full",
|
|
46
|
+
help="Full mode: PyamilySeq to cluster with CD-HIT and process output.")
|
|
47
|
+
#full_parser.add_argument("-clustering_format", choices=['CD-HIT', 'MMseqs', 'BLAST'], required=True,
|
|
48
|
+
# help="Clustering format to use: CD-HIT, MMseqs2, or BLAST.")
|
|
49
|
+
full_parser.add_argument("-output_dir", required=True,
|
|
50
|
+
help="Directory for all output files.")
|
|
51
|
+
full_parser.add_argument("-input_type", choices=['separate', 'combined', 'fasta'], required=True,
|
|
52
|
+
help="Type of input files: 'separate' for matching FASTA and GFF files, 'combined' for GFF+FASTA, or 'fasta' for a prepared FASTA file.")
|
|
53
|
+
full_parser.add_argument("-input_dir", required=False,
|
|
54
|
+
help="Directory containing GFF/FASTA files - Use with -input_type separate/combined.")
|
|
55
|
+
full_parser.add_argument("-input_fasta", required=False,
|
|
56
|
+
help="Input FASTA file - Use with - input_type fasta.")
|
|
57
|
+
full_parser.add_argument("-name_split", required=False,
|
|
58
|
+
help="Substring to split filenames and extract genome names (e.g., '_combined.gff3') - Use with -input_type separate/combined.")
|
|
59
|
+
full_parser.add_argument("-sequence_type", choices=['AA', 'DNA'], default="AA", required=False,
|
|
60
|
+
help="Clustering mode: 'DNA' or 'AA'.")
|
|
61
|
+
full_parser.add_argument("-gene_ident", default="CDS", required=False,
|
|
62
|
+
help="Gene identifiers to extract sequences (e.g., 'CDS, tRNA').")
|
|
63
|
+
full_parser.add_argument("-c", type=float, dest="pident", default=0.90, required=False,
|
|
64
|
+
help="Sequence identity threshold for clustering (default: 0.90) - CD-HIT parameter '-c'.")
|
|
65
|
+
full_parser.add_argument("-s", type=float, dest="len_diff", default=0.80, required=False,
|
|
66
|
+
help="Length difference threshold for clustering (default: 0.80) - CD-HIT parameter '-s'.")
|
|
67
|
+
full_parser.add_argument("-fast_mode", action="store_true", required=False,
|
|
68
|
+
help="Enable fast mode for CD-HIT (not recommended) - CD-HIT parameter '-g'.")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# Partial Mode Subparser
|
|
72
|
+
partial_parser = subparsers.add_parser("Partial", help="Partial mode: PyamilySeq to process pre-clustered data.")
|
|
73
|
+
partial_parser.add_argument("-clustering_format", choices=['CD-HIT', 'MMseqs', 'BLAST'], required=True,
|
|
74
|
+
help="Clustering format used: CD-HIT, MMseqs2, or BLAST.")
|
|
75
|
+
partial_parser.add_argument("-cluster_file", required=True,
|
|
76
|
+
help="Cluster file containing pre-clustered groups from CD-HIT, MMseqs, BLAST etc.")
|
|
77
|
+
partial_parser.add_argument("-original_fasta", required=True,
|
|
78
|
+
help="FASTA file used in pre-clustering (Provide sequences in DNA form).")
|
|
79
|
+
partial_parser.add_argument("-output_dir", required=True,
|
|
80
|
+
help="Directory for all output files.")
|
|
81
|
+
partial_parser.add_argument("-reclustered", required=False,
|
|
82
|
+
help="Clustering output file from a second round of clustering.")
|
|
83
|
+
partial_parser.add_argument("-seq_tag", default="StORF", dest="sequence_tag", required=False,
|
|
84
|
+
help="Tag for distinguishing reclustered sequences.")
|
|
85
|
+
|
|
86
|
+
# Common Grouping Arguments
|
|
87
|
+
for subparser in [full_parser, partial_parser]:
|
|
88
|
+
subparser.add_argument("-group_mode", choices=['Species', 'Genus'], default="Species", required=False,
|
|
89
|
+
help="Grouping mode: 'Species' or 'Genus'.")
|
|
90
|
+
subparser.add_argument("-species_groups", default="99,95,15", required=False,
|
|
91
|
+
help="Gene groupings for 'Species' mode (default: '99,95,15').")
|
|
92
|
+
subparser.add_argument("-genus_groups", default="1,2,3,4,5,6,7,8,9,10", required=False,
|
|
93
|
+
help="Gene groupings for 'Genus' mode (default: '1-10').")
|
|
94
|
+
subparser.add_argument("-w", default=None, dest="write_groups", required=False,
|
|
95
|
+
help="Output gene groups as a single FASTA file (specify levels: e.g., '-w 99,95').")
|
|
96
|
+
subparser.add_argument("-wi", action="store_true", dest="write_individual_groups", required=False,
|
|
97
|
+
help="Output individual FASTA files for each group.")
|
|
98
|
+
subparser.add_argument("-a", action="store_true", dest="align_core", required=False,
|
|
99
|
+
help="Align and concatenate sequences for 'core' groups.")
|
|
100
|
+
subparser.add_argument("-align_aa", action="store_true", required=False,
|
|
101
|
+
help="Align sequences as amino acids.")
|
|
102
|
+
subparser.add_argument("-no_gpa", action="store_false", dest="gene_presence_absence_out", required=False,
|
|
103
|
+
help="Skip creation of gene_presence_absence.csv.")
|
|
104
|
+
subparser.add_argument("-M", type=int, default=4000, dest="mem", required=False,
|
|
105
|
+
help="Memory allocation for clustering (MB) - CD-HIT parameter '-M'.")
|
|
106
|
+
subparser.add_argument("-T", type=int, default=8, dest="threads", required=False,
|
|
107
|
+
help="Number of threads for clustering/alignment - CD-HIT parameter '-T' | MAFFT parameter '--thread'.")
|
|
108
|
+
|
|
109
|
+
# Miscellaneous Arguments
|
|
110
|
+
subparser.add_argument("-verbose", action="store_true", required=False,
|
|
111
|
+
help="Print verbose output.")
|
|
112
|
+
subparser.add_argument("-v", "--version", action="version",
|
|
113
|
+
version=f"PyamilySeq {PyamilySeq_Version}: Exiting.", help="Print version number and exit.")
|
|
114
|
+
|
|
115
|
+
# Parse Arguments
|
|
116
|
+
options = parser.parse_args()
|
|
117
|
+
|
|
118
|
+
# Example of conditional logic based on selected mode
|
|
119
|
+
print(f"Running PyamilySeq {PyamilySeq_Version} in {options.run_mode} mode:")
|
|
120
|
+
if options.run_mode == "Full" and options.verbose == True:
|
|
121
|
+
print("Processing Full mode with options:", vars(options))
|
|
122
|
+
elif options.run_mode == "Partial" and options.verbose == True:
|
|
123
|
+
print("Processing Partial mode with options:", vars(options))
|
|
124
|
+
|
|
125
|
+
### Checking all required parameters are provided by user #!!# Doesn't seem to work
|
|
126
|
+
if options.run_mode == 'Full':
|
|
127
|
+
options.clustering_format = 'CD-HIT'
|
|
128
|
+
if getattr(options, 'reclustered', None) is not None:
|
|
129
|
+
sys.exit("Currently reclustering only works on Partial Mode.")
|
|
130
|
+
required_full_mode = [options.input_type, options.pident, options.len_diff]
|
|
131
|
+
if options.input_type != 'fasta':
|
|
132
|
+
required_full_mode.extend([options.input_dir, options.name_split])
|
|
133
|
+
if all(required_full_mode):
|
|
134
|
+
# Proceed with the Full mode
|
|
135
|
+
pass
|
|
136
|
+
else:
|
|
137
|
+
missing_options = [opt for opt in
|
|
138
|
+
['input_type', 'input_dir', 'name_split', 'clustering_format', 'pident', 'len_diff'] if
|
|
139
|
+
not options.__dict__.get(opt)]
|
|
140
|
+
sys.exit(f"Missing required options for Full mode: {', '.join(missing_options)}")
|
|
141
|
+
if options.align_core:
|
|
142
|
+
options.write_individual_groups = True
|
|
143
|
+
if options.write_groups == None:
|
|
144
|
+
sys.exit('Must provide "-w" to output gene groups before alignment "-a" can be done.')
|
|
145
|
+
elif options.run_mode == 'Partial':
|
|
146
|
+
required_partial_mode = [options.cluster_file, options.original_fasta]
|
|
147
|
+
if all(required_partial_mode):
|
|
148
|
+
# Proceed with the Partial mode
|
|
149
|
+
pass
|
|
150
|
+
else:
|
|
151
|
+
missing_options = [opt for opt in
|
|
152
|
+
['cluster_file','original_fasta'] if
|
|
153
|
+
not options.__dict__[opt]]
|
|
154
|
+
sys.exit(f"Missing required options for Partial mode: {', '.join(missing_options)}")
|
|
155
|
+
if options.align_core:
|
|
156
|
+
options.write_individual_groups = True
|
|
157
|
+
if options.write_groups == None or options.original_fasta == None:
|
|
158
|
+
sys.exit('Must provide "-w" to output gene groups before alignment "-a" can be done.')
|
|
159
|
+
|
|
160
|
+
if options.clustering_format == 'CD-HIT':
|
|
161
|
+
clust_affix = '.clstr'
|
|
162
|
+
elif options.clustering_format == 'TSV':
|
|
163
|
+
clust_affix = '.tsv'
|
|
164
|
+
elif options.clustering_format == 'CSV':
|
|
165
|
+
clust_affix = '.csv'
|
|
166
|
+
|
|
167
|
+
###External tool checks:
|
|
168
|
+
##MAFFT
|
|
169
|
+
if options.align_core == True:
|
|
170
|
+
if is_tool_installed('mafft'):
|
|
171
|
+
if options.verbose == True:
|
|
172
|
+
print("mafft is installed. Proceeding with alignment.")
|
|
173
|
+
else:
|
|
174
|
+
exit("mafft is not installed. Please install mafft to proceed.")
|
|
175
|
+
##CD-HIT
|
|
176
|
+
if options.run_mode == 'Full':
|
|
177
|
+
if is_tool_installed('cd-hit'):
|
|
178
|
+
if options.verbose == True:
|
|
179
|
+
print("cd-hit is installed. Proceeding with clustering.")
|
|
180
|
+
if options.sequence_type == 'DNA':
|
|
181
|
+
clustering_mode = 'cd-hit-est'
|
|
182
|
+
elif options.sequence_type == 'AA':
|
|
183
|
+
clustering_mode = 'cd-hit'
|
|
184
|
+
if options.fast_mode == True:
|
|
185
|
+
options.fast_mode = 0
|
|
186
|
+
if options.verbose == True:
|
|
187
|
+
print("Running CD-HIT in fast mode.")
|
|
188
|
+
else:
|
|
189
|
+
options.fast_mode = 1
|
|
190
|
+
if options.verbose == True:
|
|
191
|
+
print("Running CD-HIT in slow mode.")
|
|
192
|
+
else:
|
|
193
|
+
exit("cd-hit is not installed. Please install cd-hit to proceed.")
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
# if options.write_groups != None and options.original_fasta == False:
|
|
197
|
+
# exit("-fasta must br provided if -w is used")
|
|
198
|
+
|
|
199
|
+
if hasattr(options, 'cluster_file') and options.cluster_file:
|
|
200
|
+
options.cluster_file = fix_path(options.cluster_file)
|
|
201
|
+
if hasattr(options, 'reclustered') and options.reclustered:
|
|
202
|
+
options.reclustered = fix_path(options.reclustered)
|
|
203
|
+
if hasattr(options, 'input_dir') and options.input_dir:
|
|
204
|
+
options.input_dir = fix_path(options.input_dir)
|
|
205
|
+
if hasattr(options, 'output_dir') and options.output_dir:
|
|
206
|
+
options.output_dir = fix_path(options.output_dir)
|
|
207
|
+
|
|
208
|
+
output_path = os.path.abspath(options.output_dir)
|
|
209
|
+
combined_out_file = os.path.join(output_path, "combined_sequences_dna.fasta")
|
|
210
|
+
clustering_output = os.path.join(output_path, 'clustering_' + options.clustering_format)
|
|
211
|
+
|
|
212
|
+
if options.group_mode == 'Species':
|
|
213
|
+
options.species_groups = options.species_groups + ',0'
|
|
214
|
+
groups_to_use = options.species_groups
|
|
215
|
+
elif options.group_mode == 'Genus':
|
|
216
|
+
options.genus_groups = options.genus_groups + ',>'
|
|
217
|
+
groups_to_use = options.genus_groups
|
|
218
|
+
if options.align_core != None:
|
|
219
|
+
sys.exit("-a align_core not a valid option in Genus mode.")
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
if options.run_mode == 'Full':
|
|
223
|
+
if options.clustering_format != 'CD-HIT':
|
|
224
|
+
sys.exit('Only CD-HIT clsutering works in Full Mode')
|
|
225
|
+
|
|
226
|
+
if not os.path.exists(output_path):
|
|
227
|
+
os.makedirs(output_path)
|
|
228
|
+
if options.sequence_type == 'AA':
|
|
229
|
+
clustering_mode = 'cd-hit'
|
|
230
|
+
file_to_cluster = combined_out_file.replace('_dna.fasta','_aa.fasta')
|
|
231
|
+
translate = True
|
|
232
|
+
elif options.sequence_type == 'DNA':
|
|
233
|
+
clustering_mode = 'cd-hit-est'
|
|
234
|
+
translate = False
|
|
235
|
+
file_to_cluster = combined_out_file
|
|
236
|
+
if options.input_type == 'separate':
|
|
237
|
+
read_separate_files(options.input_dir, options.name_split, options.gene_ident, combined_out_file, translate)
|
|
238
|
+
run_cd_hit(options, file_to_cluster, clustering_output, clustering_mode)
|
|
239
|
+
elif options.input_type == 'combined':
|
|
240
|
+
read_combined_files(options.input_dir, options.name_split, options.gene_ident, combined_out_file, translate)
|
|
241
|
+
run_cd_hit(options, file_to_cluster, clustering_output, clustering_mode)
|
|
242
|
+
elif options.input_type == 'fasta':
|
|
243
|
+
combined_out_file = options.input_fasta
|
|
244
|
+
### FIX write code to detect if DNA or AA and if sequence tpye is AA then translate
|
|
245
|
+
# Detect if the input FASTA file contains DNA or AA sequences
|
|
246
|
+
is_dna = detect_sequence_type(options.input_fasta)
|
|
247
|
+
# If the sequence type is AA and the input is DNA, translate the DNA to AA
|
|
248
|
+
if options.sequence_type == 'AA' and is_dna:
|
|
249
|
+
translated_fasta = os.path.join(output_path, os.path.splitext(os.path.basename(options.input_fasta))[0] + '_aa.fasta')
|
|
250
|
+
translate_dna_to_aa(options.input_fasta, translated_fasta)
|
|
251
|
+
file_to_cluster = translated_fasta
|
|
252
|
+
else:
|
|
253
|
+
file_to_cluster = options.input_fasta
|
|
254
|
+
run_cd_hit(options, file_to_cluster, clustering_output, clustering_mode)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
class clustering_options:
|
|
258
|
+
def __init__(self):
|
|
259
|
+
self.run_mode = options.run_mode
|
|
260
|
+
self.cluster_format = options.clustering_format
|
|
261
|
+
self.sequence_type = options.sequence_type
|
|
262
|
+
self.reclustered = None
|
|
263
|
+
self.sequence_tag = None
|
|
264
|
+
self.species_groups = groups_to_use
|
|
265
|
+
self.clusters = clustering_output + clust_affix
|
|
266
|
+
self.output_dir = options.output_dir
|
|
267
|
+
self.gene_presence_absence_out = options.gene_presence_absence_out
|
|
268
|
+
self.write_groups = options.write_groups
|
|
269
|
+
self.write_individual_groups = options.write_individual_groups
|
|
270
|
+
self.threads = options.threads
|
|
271
|
+
self.align_core = options.align_core
|
|
272
|
+
self.align_aa = options.align_aa
|
|
273
|
+
self.fasta = combined_out_file
|
|
274
|
+
self.verbose = options.verbose
|
|
275
|
+
|
|
276
|
+
clustering_options = clustering_options()
|
|
277
|
+
|
|
278
|
+
elif options.run_mode == 'Partial':
|
|
279
|
+
class clustering_options:
|
|
280
|
+
def __init__(self):
|
|
281
|
+
self.run_mode = options.run_mode
|
|
282
|
+
self.cluster_format = options.clustering_format
|
|
283
|
+
self.sequence_type = None
|
|
284
|
+
self.reclustered = options.reclustered
|
|
285
|
+
self.sequence_tag = options.sequence_tag
|
|
286
|
+
self.species_groups = groups_to_use
|
|
287
|
+
self.clusters = options.cluster_file
|
|
288
|
+
self.output_dir = options.output_dir
|
|
289
|
+
self.gene_presence_absence_out = options.gene_presence_absence_out
|
|
290
|
+
self.write_groups = options.write_groups
|
|
291
|
+
self.write_individual_groups = options.write_individual_groups
|
|
292
|
+
self.threads = options.threads
|
|
293
|
+
self.align_core = options.align_core
|
|
294
|
+
self.align_aa = options.align_aa
|
|
295
|
+
self.fasta = options.original_fasta
|
|
296
|
+
self.verbose = options.verbose
|
|
297
|
+
|
|
298
|
+
clustering_options = clustering_options()
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
if options.group_mode == 'Species':
|
|
302
|
+
species_cluster(clustering_options)
|
|
303
|
+
elif options.group_mode == 'Genus':
|
|
304
|
+
genus_cluster((clustering_options))
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
# Save arguments to a text file
|
|
308
|
+
with open(output_path+"/PyamilySeq_params.txt", "w") as outfile:
|
|
309
|
+
for arg, value in vars(options).items():
|
|
310
|
+
outfile.write(f"{arg}: {value}\n")
|
|
311
|
+
|
|
312
|
+
print("Thank you for using PyamilySeq -- A detailed user manual can be found at https://github.com/NickJD/PyamilySeq\n"
|
|
313
|
+
"Please report any issues to: https://github.com/NickJD/PyamilySeq/issues\n#####")
|
|
314
|
+
|
|
315
|
+
if __name__ == "__main__":
|
|
316
|
+
main()
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
#from line_profiler_pycharm import profile
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
try:
|
|
5
|
+
from .constants import *
|
|
6
|
+
from .clusterings import *
|
|
7
|
+
from .utils import *
|
|
8
|
+
except (ModuleNotFoundError, ImportError, NameError, TypeError) as error:
|
|
9
|
+
from constants import *
|
|
10
|
+
from clusterings import *
|
|
11
|
+
from utils import *
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def gene_presence_absence_output(options, genus_dict, pangenome_clusters_First_sorted, pangenome_clusters_First_sequences_sorted):
|
|
15
|
+
print("Outputting gene_presence_absence file")
|
|
16
|
+
output_dir = os.path.abspath(options.output_dir)
|
|
17
|
+
#in_name = options.clusters.split('.')[0].split('/')[-1]
|
|
18
|
+
gpa_outfile = os.path.join(output_dir, 'gene_presence_absence.csv')
|
|
19
|
+
gpa_outfile = open(gpa_outfile, 'w')
|
|
20
|
+
gpa_outfile.write('"Gene","Non-unique Gene name","Annotation","No. isolates","No. sequences","Avg sequences per isolate","Genome Fragment","Order within Fragment","'
|
|
21
|
+
'"Accessory Fragment","Accessory Order with Fragment","QC","Min group size nuc","Max group size nuc","Avg group size nuc","')
|
|
22
|
+
gpa_outfile.write('","'.join(genus_dict.keys()))
|
|
23
|
+
gpa_outfile.write('"\n')
|
|
24
|
+
for cluster, sequences in pangenome_clusters_First_sequences_sorted.items():
|
|
25
|
+
average_sequences_per_genome = len(sequences) / len(pangenome_clusters_First_sorted[cluster])
|
|
26
|
+
gpa_outfile.write('"group_'+str(cluster)+'","","",'+str(len(pangenome_clusters_First_sorted[cluster]))+'","'+str(len(sequences))+'","'+str(average_sequences_per_genome)+
|
|
27
|
+
'","","","","","","","","",""')
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
for genus in genus_dict.keys():
|
|
31
|
+
full_out = ''
|
|
32
|
+
tmp_list = []
|
|
33
|
+
for value in sequences:
|
|
34
|
+
if value.split('_')[0] == genus:
|
|
35
|
+
tmp_list.append(value)
|
|
36
|
+
if tmp_list:
|
|
37
|
+
full_out += ',"'+''.join(tmp_list)+'"'
|
|
38
|
+
else:
|
|
39
|
+
full_out = ',""'
|
|
40
|
+
gpa_outfile.write(full_out)
|
|
41
|
+
gpa_outfile.write('\n')
|
|
42
|
+
|
|
43
|
+
### Below is some unfinished code
|
|
44
|
+
# edge_list_outfile = open(in_name+'_edge_list.csv','w')
|
|
45
|
+
# for cluster, sequences in pangenome_clusters_First_sequences_sorted.items():
|
|
46
|
+
# output = []
|
|
47
|
+
# for entry in sequences:
|
|
48
|
+
# # Split each entry at '|'
|
|
49
|
+
# genome, gene = entry.split('|')
|
|
50
|
+
# # Format the result as "gene genome"
|
|
51
|
+
# output.append(f"{gene}\t{genome}")
|
|
52
|
+
# for line in output:
|
|
53
|
+
# edge_list_outfile.write(line + '\n')
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def get_cores(options):
|
|
59
|
+
##Calculate core groups
|
|
60
|
+
groups = OrderedDict()
|
|
61
|
+
cores = OrderedDict()
|
|
62
|
+
for group in options.core_groups.split(','):
|
|
63
|
+
first_core_group = 'First_genera_' + group
|
|
64
|
+
cores[first_core_group] = []
|
|
65
|
+
if options.reclustered != None:
|
|
66
|
+
extended_core_group = 'extended_genera_' + group
|
|
67
|
+
cores[extended_core_group] = []
|
|
68
|
+
combined_core_group = 'combined_genera_' + group
|
|
69
|
+
cores[combined_core_group] = []
|
|
70
|
+
second_core_group = 'Second_genera_' + group
|
|
71
|
+
cores[second_core_group] = []
|
|
72
|
+
only_second_core_group = 'only_Second_genera_' + group
|
|
73
|
+
cores[only_second_core_group] = []
|
|
74
|
+
return cores, groups
|
|
75
|
+
|
|
76
|
+
#@profile
|
|
77
|
+
def calc_First_only_core(cluster, First_num, cores):
|
|
78
|
+
try:
|
|
79
|
+
cores['First_genera_' + str(First_num)].append(cluster)
|
|
80
|
+
except KeyError:
|
|
81
|
+
cores['First_genera_>'].append(cluster)
|
|
82
|
+
#@profile
|
|
83
|
+
def calc_single_First_extended_Second_only_core(cluster, First_num, cores, Second_num): # Count gene families extended with StORFs
|
|
84
|
+
group = First_num + Second_num
|
|
85
|
+
try:
|
|
86
|
+
cores['extended_genera_' + str(group)].append(cluster)
|
|
87
|
+
except KeyError:
|
|
88
|
+
cores['extended_genera_>'].append(cluster)
|
|
89
|
+
#@profile
|
|
90
|
+
def calc_multi_First_extended_Second_only_core(cluster, First_num, cores, Second_num): # Count seperately those gene families extended with StORF_Reporter but combined >1 PEP
|
|
91
|
+
group = First_num + Second_num
|
|
92
|
+
try:
|
|
93
|
+
cores['combined_genera_' + str(group)].append(cluster)
|
|
94
|
+
except KeyError:
|
|
95
|
+
cores['combined_genera_>'].append(cluster)
|
|
96
|
+
#@profile
|
|
97
|
+
def calc_Second_only_core(cluster, cores, Second_num):
|
|
98
|
+
try:
|
|
99
|
+
cores['Second_genera_' + str(Second_num)].append(cluster)
|
|
100
|
+
except KeyError:
|
|
101
|
+
cores['Second_genera_>'].append(cluster)
|
|
102
|
+
#@profile
|
|
103
|
+
def calc_only_Second_only_core(cluster, cores, Second_num): # only count the true storf onlies
|
|
104
|
+
try:
|
|
105
|
+
cores['only_Second_genera_' + str(Second_num)].append(cluster)
|
|
106
|
+
except:
|
|
107
|
+
cores['only_Second_genera_>'].append(cluster)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
#@profile
|
|
112
|
+
def cluster(options):
|
|
113
|
+
|
|
114
|
+
if options.cluster_format == 'CD-HIT':
|
|
115
|
+
genus_dict, pangenome_clusters_First, pangenome_clusters_First_genomes, pangenome_clusters_First_sequences, reps = cluster_CDHIT(options, '_')
|
|
116
|
+
elif 'TSV' in options.cluster_format or 'CSV' in options.cluster_format:
|
|
117
|
+
genus_dict, pangenome_clusters_First, pangenome_clusters_First_genomes, pangenome_clusters_First_sequences, reps = cluster_EdgeList(options, '_')
|
|
118
|
+
|
|
119
|
+
###
|
|
120
|
+
cores, groups = get_cores(options)
|
|
121
|
+
###
|
|
122
|
+
|
|
123
|
+
if options.reclustered != None:
|
|
124
|
+
if options.cluster_format == 'CD-HIT':
|
|
125
|
+
combined_pangenome_clusters_First_Second_clustered,not_Second_only_cluster_ids,combined_pangenome_clusters_Second, combined_pangenome_clusters_Second_sequences = combined_clustering_CDHIT(options, genus_dict, '_')
|
|
126
|
+
elif 'TSV' in options.cluster_format or 'CSV' in options.cluster_format:
|
|
127
|
+
combined_pangenome_clusters_First_Second_clustered,not_Second_only_cluster_ids,combined_pangenome_clusters_Second, combined_pangenome_clusters_Second_sequences = combined_clustering_Edge_List(options, '_')
|
|
128
|
+
pangenome_clusters_Type = combined_clustering_counting(options, pangenome_clusters_First, reps, combined_pangenome_clusters_First_Second_clustered, pangenome_clusters_First_genomes, '_')
|
|
129
|
+
else:
|
|
130
|
+
pangenome_clusters_Type = single_clustering_counting(pangenome_clusters_First, reps)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
Number_Of_Second_Extending_But_Same_Genomes = 0
|
|
135
|
+
|
|
136
|
+
sorted_first_keys = sort_keys_by_values(pangenome_clusters_First, pangenome_clusters_First_sequences)
|
|
137
|
+
pangenome_clusters_First_sorted = reorder_dict_by_keys(pangenome_clusters_First, sorted_first_keys)
|
|
138
|
+
pangenome_clusters_First_sequences_sorted = reorder_dict_by_keys(pangenome_clusters_First_sequences, sorted_first_keys)
|
|
139
|
+
pangenome_clusters_Type_sorted = reorder_dict_by_keys(pangenome_clusters_Type, sorted_first_keys)
|
|
140
|
+
|
|
141
|
+
print("Calculating Groups")
|
|
142
|
+
seen_groupings = []
|
|
143
|
+
for cluster, numbers in pangenome_clusters_Type_sorted.items():
|
|
144
|
+
############################### Calculate First only
|
|
145
|
+
cluster = str(cluster)
|
|
146
|
+
for grouping in numbers[2]: #!!# Could do with a more elegant solution
|
|
147
|
+
current_cluster = grouping[0].split(':')[0]
|
|
148
|
+
if current_cluster not in seen_groupings:
|
|
149
|
+
seen_groupings.append(current_cluster)
|
|
150
|
+
current_cluster_size = grouping[0].split(':')[1]
|
|
151
|
+
calc_First_only_core(current_cluster, current_cluster_size, cores)
|
|
152
|
+
############################# Calculate First and Reclustered-Second
|
|
153
|
+
if numbers[0] == 1 and numbers[3] >= 1: # If Seconds did not combine First reps
|
|
154
|
+
calc_single_First_extended_Second_only_core(cluster, numbers[1], cores, numbers[3])
|
|
155
|
+
elif numbers[0] > 1 and numbers[3] >= 1: # If unique Seconds combined multiple Firsts
|
|
156
|
+
calc_multi_First_extended_Second_only_core(cluster, numbers[1], cores, numbers[3])
|
|
157
|
+
elif numbers[4] >= 1:
|
|
158
|
+
Number_Of_Second_Extending_But_Same_Genomes += 1
|
|
159
|
+
else:
|
|
160
|
+
if options.verbose == True:
|
|
161
|
+
print("First cluster " + current_cluster + " already processed - This is likely because it was clustered with another First representative.")
|
|
162
|
+
|
|
163
|
+
if options.reclustered != None:
|
|
164
|
+
combined_pangenome_clusters_ONLY_Second_Type = defaultdict(list)
|
|
165
|
+
combined_pangenome_clusters_Second_Type = defaultdict(list)
|
|
166
|
+
for cluster, genomes in combined_pangenome_clusters_Second.items():
|
|
167
|
+
if cluster in not_Second_only_cluster_ids:
|
|
168
|
+
combined_pangenome_clusters_Second_Type[cluster] = [cluster, len(genomes)]
|
|
169
|
+
else:
|
|
170
|
+
combined_pangenome_clusters_ONLY_Second_Type[cluster] = [cluster, len(genomes)]
|
|
171
|
+
for cluster, data in combined_pangenome_clusters_Second_Type.items():
|
|
172
|
+
if data[1] >= 1:
|
|
173
|
+
calc_Second_only_core(cluster, cores, data[1])
|
|
174
|
+
for cluster, data in combined_pangenome_clusters_ONLY_Second_Type.items():
|
|
175
|
+
if data[1] >= 1:
|
|
176
|
+
calc_only_Second_only_core(cluster, cores, data[1])
|
|
177
|
+
###########################
|
|
178
|
+
### Output
|
|
179
|
+
output_path = os.path.abspath(options.output_dir)
|
|
180
|
+
if not os.path.exists(output_path):
|
|
181
|
+
os.makedirs(output_path)
|
|
182
|
+
stats_out = os.path.join(output_path,'summary_statistics.txt')
|
|
183
|
+
key_order = list(cores.keys())
|
|
184
|
+
with open(stats_out,'w') as outfile:
|
|
185
|
+
print("Genus Groups:")
|
|
186
|
+
outfile.write("Genus Groups\n")
|
|
187
|
+
for key in key_order:
|
|
188
|
+
print(key+':\t'+str(len(cores[key])))
|
|
189
|
+
outfile.write(key + ':\t' + str(len(cores[key]))+'\n')
|
|
190
|
+
print("Total Number of First Gene Groups (Including Singletons): " + str(len(pangenome_clusters_First_sequences_sorted)))
|
|
191
|
+
outfile.write("Total Number of Gene Groups (Including Singletons): " + str(len(pangenome_clusters_First_sequences_sorted)))
|
|
192
|
+
if options.reclustered!= None:
|
|
193
|
+
print("Total Number of Second Gene Groups (Including Singletons): " + str(
|
|
194
|
+
len(combined_pangenome_clusters_Second_sequences)))
|
|
195
|
+
print("Total Number of First Gene Groups That Had Additional Second Sequences But Not New Genomes: " + str(
|
|
196
|
+
Number_Of_Second_Extending_But_Same_Genomes))
|
|
197
|
+
outfile.write("\nTotal Number of Second Gene Groups (Including Singletons): " + str(
|
|
198
|
+
len(combined_pangenome_clusters_Second_sequences)))
|
|
199
|
+
outfile.write("\nTotal Number of First Gene Groups That Had Additional Second Sequences But Not New Genomes: " + str(
|
|
200
|
+
Number_Of_Second_Extending_But_Same_Genomes))
|
|
201
|
+
|
|
202
|
+
if options.gene_presence_absence_out != False:
|
|
203
|
+
gene_presence_absence_output(options,genus_dict, pangenome_clusters_First_sorted, pangenome_clusters_First_sequences_sorted)
|
|
204
|
+
|
|
205
|
+
if options.run_mode == 'Full':
|
|
206
|
+
if options.reclustered == None:
|
|
207
|
+
combined_pangenome_clusters_Second_sequences = None
|
|
208
|
+
if options.write_groups != None:
|
|
209
|
+
print("Outputting gene group FASTA files")
|
|
210
|
+
sequences = read_fasta(options.fasta)
|
|
211
|
+
#output_dir = os.path.dirname(os.path.abspath(options.output_dir))
|
|
212
|
+
output_dir = os.path.join(options.output_dir, 'Gene_Groups_Output')
|
|
213
|
+
write_groups_func(options,output_dir, key_order, cores, sequences,
|
|
214
|
+
pangenome_clusters_First_sequences_sorted, combined_pangenome_clusters_Second_sequences)
|
|
215
|
+
|
|
216
|
+
elif options.run_mode == 'Partial':
|
|
217
|
+
if options.reclustered == None:
|
|
218
|
+
combined_pangenome_clusters_Second_sequences = None
|
|
219
|
+
if options.write_groups != None and options.fasta != None:
|
|
220
|
+
print("Outputting gene group FASTA files")
|
|
221
|
+
sequences = read_fasta(options.fasta)
|
|
222
|
+
#output_dir = os.path.dirname(os.path.abspath(options.output_dir))
|
|
223
|
+
output_dir = os.path.join(options.output_dir, 'Gene_Groups_Output')
|
|
224
|
+
write_groups_func(options,output_dir, key_order, cores, sequences,
|
|
225
|
+
pangenome_clusters_First_sequences_sorted, combined_pangenome_clusters_Second_sequences)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
# if options.write_groups != None and options.fasta != None:
|
|
229
|
+
# sequences = read_fasta(options.fasta)
|
|
230
|
+
# output_dir = os.path.join(output_path, 'Gene_Families_Output')
|
|
231
|
+
#
|
|
232
|
+
# write_groups(options,output_dir, key_order, cores, sequences,
|
|
233
|
+
# pangenome_clusters_First_sequences_sorted, combined_pangenome_clusters_Second_sequences)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
#!!# - Currently only align in Species Mode
|
|
237
|
+
#if options.align_core != None and options.fasta != None and options.write_groups != None:
|
|
238
|
+
# process_gene_families(options, os.path.join(output_path, 'Gene_Families_Output'), 'concatenated_genes_aligned.fasta')
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
|