forked from thh32/MiMiC2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMiMiC2.py
More file actions
4770 lines (3660 loc) · 238 KB
/
MiMiC2.py
File metadata and controls
4770 lines (3660 loc) · 238 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3.11
import sys
import glob
import pandas as pd
import operator
import collections
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
import itertools
import subprocess
import random
from tqdm import tqdm
import pandas
import matplotlib
from matplotlib import rc
import seaborn as sns
sns.set_palette("hls",15)
matplotlib.rcParams['pdf.fonttype'] = 42
from statistics import mean
import os
import argparse
import warnings
from time import process_time
warnings.filterwarnings("ignore")
location_of_file = os.path.dirname(os.path.realpath(__file__))
location_of_call = os.getcwd()
version = '2025-02-20'
# User input
parser = argparse.ArgumentParser(description='MiMiC2 v' + version)
# Options for Sample data
parser.add_argument('-s','--samples', metavar='{INPUT}', required=True, help='Pfam vector file of all metagenomic samples to be studied.')
parser.add_argument('-m','--metadata', metavar='{INPUT}', required=False, help='Metadata file detailing the group assignment of each sample.')
parser.add_argument('--group', metavar='{INPUT}', required=False, help='Name of the group of interest for SynCom creation.')
# Option for Function database
parser.add_argument('-p','--pfam', metavar='{INPUT}',required=True, help='Pfam file e.g. Pfam-A.clans.csv, provided for Pfam v32 in `datasets/core/`')
# Options for Genome database
parser.add_argument('-g','--genomes', metavar='{INPUT}',required=True, help='Pfam vector file of genome collection.')
parser.add_argument('--models', metavar='{INPUT}', required=False, help='Folder containing metabolic models for each genome. Must be provided as RDS files such as those provided by GapSeq. If no folder is provided, than the metabolic modelling step (step 4) will be skipped.')
parser.add_argument('-t','--taxonomy', metavar='{INPUT}',required=False, help='Taxonomic assignment of each genome.')
parser.add_argument('--taxonomiclevel', metavar='{INPUT}',required=False, help='Taxonomic level for filtering (species = s,genus = g, class = c, order = o, phyla = p).')
# Options for SynCom design
parser.add_argument('-c','--consortiasize', metavar='{INT}',required=True,default=10, help='Define the SynCom size the user is after.')
parser.add_argument('--corebias', metavar='{FLOAT}', required=False,default=0.0005, help='The additional weighting provided to Pfams core to the studied group (default = 0.0005).')
parser.add_argument('--groupbias', metavar='{FLOAT}', required=False,default=0.0012, help='The additional weighting provided to Pfams significantly enriched in the studied group (default = 0.0012).')
parser.add_argument('--prevfilt', metavar='{FLOAT}', required=False,default=33.3, help='Prevalence filtering threshold for shortlisting genomes for inclusion in the final SynCom selection (default = 33.3).')
# Options for output
parser.add_argument('-o','--output', metavar='{OUTPUT}', required=True, help='Prefix for all output files e.g. HuSynCom.')
# Advanced user options
parser.add_argument('--iterations', metavar='{INT}',required=False,default=20, help='Change the number of iterations to select sample specific strains in step 1.')
parser.add_argument('--exclusion', metavar='{INPUT}', required=False, help='Provide a list of genome names to be excluded during SynCom selection (in tsv format). Genome names must be the same as the ones included in the genome collection vector file (--genome).')
parser.add_argument('--forced', metavar='{INPUT}', required=False, help='Provide a list of genome names to be forced into consideration during SynCom selection (in tsv format). Genome names must be the same as the ones included in the genome collection vector file (--genome).')
args, unknown = parser.parse_known_args()
start_time = process_time()
#Variable assignments
consortia_size_wanted = int(args.consortiasize)
reduce_genome_list_number = int(args.iterations)
pfam_file = args.pfam
sample_file = args.samples
genome_file = args.genomes
grouping_file = args.metadata
models_folder = args.models
if args.taxonomy is not None:
taxonomic_filtering = True
taxonomic_file = args.taxonomy
taxonomic_level = args.taxonomiclevel
else:
taxonomic_filtering = False
core_bias = float(args.corebias)
pfam_bias = args.groupbias
prevalence_for_shortlisting = args.prevfilt
group_to_be_studied = args.group # Defines the group we predict for ##### Optional
output_prefix = args.output
print ("Reading in pfam vector files. ")
## Read in files
pfams = []
for line in open(pfam_file,'r'):
timber = line.split('\t')
pfams.append(timber[0])
print ('Number of pfams studied; ' + str(len(pfams))) #number of pfams in the pfam-clans file used
samples = pd.read_csv(sample_file, sep='\t', index_col='PfamID')
#if exclusion list is provided, genomes (of pathogens) will be exluded from the final vector here.
genomes = pd.read_csv(genome_file, sep='\t', index_col='PfamID')
# Give an option that people can state species to be ignored, but names must be the same as those in the file
if args.exclusion is not None:
with open(args.exclusion,'r') as file:
pathogens = [line.rstrip() for line in file]
genomes = genomes.drop(pathogens, axis=1)
print ("The following genomes will be excluded from the analysis:", ", ".join(pathogens))
else:
pathogens = []
# Give an option that people can state species to be forced into inclusion, but names must be the same as those in the file
if args.forced is not None:
with open(args.forced,'r') as file:
forced_inclusion = [line.rstrip() for line in file]
genomes = genomes.drop(pathogens, axis=1)
print ("The following genomes will be forced into consideration during SynCom selection:", ", ".join(pathogens))
else:
forced_inclusion = []
# if grouping file is assigned
if grouping_file is not None:
if grouping_file.endswith("tsv"):
groups = pd.read_csv(grouping_file, sep='\t', index_col='SampleID')
else:
groups = pd.read_csv(grouping_file, sep=',', index_col='SampleID')
samples_to_be_studied = list(groups.loc[groups['Group'] == group_to_be_studied].index)
else:
groups = ''
samples_to_be_studied = list(samples.columns)
print ('Number of genomes studied; ' + str(len(genomes.keys())))
find_models = {}
if models_folder is not None and models_folder != " ":
for cfile in glob.glob(models_folder + '*.RDS'):
model_name = cfile.split('/')[-1]
find_models[model_name] = cfile
print ('Number of GEMs; ' + str(len(find_models.keys())))
else:
print ('Number of GEMs; ' + str(len(find_models.keys())))
print (':: Metabolic modelling not assigned. Terminating at Step 4 ::')
print (':: Reading in pfam and vector files')
## Determine sample groups
if isinstance(groups, str):
print ('Total samples = ', str(len(samples.columns)))
print ('All samples will be studied as a single group, without comparative weighting.')
group_to_be_studied = list(samples.columns)
g1_samples = list(samples.columns)
g1_bias = []
else:
g1_bias = []
g2_bias = []
g1_samples = []
g2_samples = []
group1_is = list(groups['Group'].unique())[0]
group2_is = list(groups['Group'].unique())[1]
for SampleID, info in groups.iterrows():
grouping = info['Group']
if grouping == group1_is:
g1_samples.append(SampleID)
if grouping == group2_is:
g2_samples.append(SampleID)
print ('Total samples = ', str(len(samples.columns)))
print ('Group 1 = ', group1_is)
print ('Number of samples = ', str(len(g1_samples)) + '\n')
print ('Group 2 = ', group2_is)
print ('Number of samples = ', str(len(g2_samples)))
# Set the group to be studied and a consortia predicted for
group_to_be_used = ''
if group1_is == group_to_be_studied:
group_to_be_studied == g1_samples
if group2_is == group_to_be_studied:
group_to_be_studied == g2_samples
for i, j in samples.iterrows():
g1_pres = 0
g1_abs = 0
g2_pres = 0
g2_abs = 0
for sample in g1_samples:
if j[sample] == 1:
g1_pres +=1
else:
g1_abs +=1
for sample in g2_samples:
if j[sample] == 1:
g2_pres +=1
else:
g2_abs +=1
oddsratio, pvalue = stats.fisher_exact([[g1_pres, g1_abs], [g2_pres, g2_abs]])
#print ([g1_pres, g1_abs], [g2_pres, g2_abs])
#print (pvalue)
if pvalue <0.05:
g1_ratio = g1_pres / (g1_pres+g1_abs)
g2_ratio = g2_pres / (g2_pres+g2_abs)
if g1_ratio > g2_ratio:
g1_bias.append(j.name)
else:
g2_bias.append(j.name)
print ('Number of Group 1 enriched Pfams; ', len(g1_bias))
print ('Number of Group 2 enriched Pfams; ',len(g2_bias))
if isinstance(groups, str):
g1_core_bias = []
for pfam, samples_info in samples.iterrows():
g1_pres = 0
g1_abs = 0
for sample in g1_samples: # only show info for this group
if samples_info[sample] == 1: # If Pfam present in sample
g1_pres +=1
else:
g1_abs +=1
g1_ratio = g1_pres / (g1_pres+g1_abs)
if g1_ratio > 0.5:
g1_core_bias.append(pfam)
print ('Core proteins in Group 1 = ' , len(g1_core_bias))
else:
g1_core_bias = []
for pfam, samples_info in samples.iterrows():
g1_pres = 0
g1_abs = 0
for sample in g1_samples: # only show info for this group
if samples_info[sample] == 1: # If Pfam present in sample
g1_pres +=1
else:
g1_abs +=1
g1_ratio = g1_pres / (g1_pres+g1_abs)
if g1_ratio > 0.5:
g1_core_bias.append(pfam)
print ('Core proteins in Group 1 = ' , len(g1_core_bias))
g2_core_bias = []
if len (g2_samples) > 0:
for pfam, samples_info in samples.iterrows():
g2_pres = 0
g2_abs = 0
for sample in g2_samples: # only show info for this group
if samples_info[sample] == 1: # If Pfam present in sample
g2_pres +=1
else:
g2_abs +=1
g2_ratio = g2_pres / (g2_pres+g2_abs)
if g2_ratio > 0.5:
g2_core_bias.append(pfam)
print ('Core proteins in Group 2 = ' , len(g2_core_bias))
print ('::: Determined functions weight.')
## Step 1
print (':::: Step 1: Iterative sample-specific selection of strains. ::::')
wanted_pfams = []
iterations_wanted = reduce_genome_list_number
Stored_first_round_consortia = {}
for column in tqdm(samples[samples_to_be_studied].columns): # For each sample ###########
sample_data = samples[column]
sample_specific_genomes = genomes[list((set(genomes.keys())-set(pathogens)))]
consortia = []
consortia_matches = []
consortia_mismatches = []
cul_accounted = []
accouted_pfams = []
accouted_pfams_percentage = 0.0
samples_pfams = list(sample_data.loc[sample_data > 0].index)
samples_remaining_pfams = samples_pfams
#print ('Minimal consortia for sample; ', column)
#print ('Sample contains this many pfams; ', str(len(samples_pfams)) )
for iteration in range(0,iterations_wanted): # Create an initial list of 50 consortia members
genome_scores = {}
#print ('Genome selection started; ', datetime.now())
#print ('Number of genomes;', str(len(sample_specific_genomes.columns)))
for genome in sample_specific_genomes: # Iterate over the remaining genomes each time
genome_data = sample_specific_genomes[genome] # This section creates the single genome file
# This is the key difference, here we select to study only those present in the genome
genome_pfams = list(genome_data.loc[genome_data == 1].index)
#!!!!!!!!!!!!!!!! This is the time intensive step
#t1 = [x for x in genome_pfams if x not in accouted_pfams] # Removes those pfams already accounted for
#genome_pfams = t1
match_list = list(set(samples_remaining_pfams).intersection(genome_pfams))
match = 0.0
# Bias based on core sample functions
if samples_to_be_studied == g1_samples:
bias_core_score = len(list(set(g1_core_bias).intersection(genome_pfams))) * core_bias
bias_spef_score = len(list(set(g1_bias).intersection(genome_pfams))) * pfam_bias
elif samples_to_be_studied == g2_samples:
bias_core_score = len(list(set(g2_core_bias).intersection(genome_pfams))) * core_bias
bias_spef_score = len(list(set(g2_bias).intersection(genome_pfams))) * pfam_bias
# Bias based on core genome functions
for i in match_list:
#match += pfams_prev[i]
match +=1
#print (match)
mismatch = len(list(genome_data.loc[genome_data == 1].index))-len(match_list)
#print (mismatch)
try:
score = (match/ (match+mismatch)) + bias_core_score + bias_spef_score
genome_scores[genome] = [score, match, mismatch]
except:
#print ("FAILED to be studied.")
#print (column, len(accouted_pfams), len(samples_remaining_pfams))
#print (genome, len(genome_pfams),match, mismatch)
failed_genome_analysis = True
#print ('Genome selection ended; ', datetime.now())
max_match = max(genome_scores, key=genome_scores.get) # Identify the best consortia member this round
consortia.append(max_match) # Add to list
#print ('Added consortia member; ', max_match)
# At this point we have selected the consortia member so the remainder readies the datasets for the next round
# Obtain best matches data
genome_data = sample_specific_genomes[max_match] # This section creates the single genome file
genome_pfams = list(genome_data.loc[genome_data == 1].index)
score, match, mismatch = genome_scores[max_match]
#print (match, mismatch, score)
# Calculate cul. accounted pfams %
for i in list(set(samples_remaining_pfams).intersection(genome_pfams)):
accouted_pfams.append(i)
try:
accouted_pfams_percentage = (len(accouted_pfams)/ float(len(samples_pfams)))*100
except ZeroDivisionError:
if len(accouted_pfams) == 0:
if len(samples_pfams) == 0:
accouted_pfams_percentage = 0.0
#print ('Culumalative pfams accounted for; ', str(accouted_pfams_percentage))
# Remove included genome from genome list
t1 = sample_specific_genomes.drop(list(set(samples_remaining_pfams).intersection(genome_pfams)))
t2 = t1.drop(columns=[max_match])
sample_specific_genomes = t2
# This section removes pfams already counted for and the selected taxa
s1 = [x for x in samples_remaining_pfams if x not in list(set(samples_pfams).intersection(genome_pfams))]
samples_remaining_pfams = s1
#print ("Unaccounted for pfams; ", str(len(samples_remaining_pfams)))
# Store statistics
consortia_matches.append(match)
consortia_mismatches.append(mismatch)
cul_accounted.append(accouted_pfams_percentage)
#print ('Selection made for round; ', str(iteration))
cul_mismatches = []
tot_mismatch = 0
for i in consortia_mismatches:
tot_mismatch += i
cul_mismatches.append(tot_mismatch)
#print(round(kneedle.knee, 3))
#print(round(kneedle.elbow, 3))
#kneedle.plot_knee_normalized()
#kneedle.plot_knee()
Stored_first_round_consortia[column] = [consortia_matches, consortia_mismatches, cul_accounted,cul_mismatches, consortia]
#fig = plt.figure()
#ax = plt.axes()
#ax.plot(consortia_mismatches)
#fig = plt.figure()
#ax = plt.axes()
#ax.plot(cul_mismatches)
print (':::: Step 1 complete: Iterative sample-specific selection of strains.')
## Step 2
print ('::::: Step 2: Strain reduction and consortia filtering.')
genome_prev = {}
for sample, data in Stored_first_round_consortia.items():
sample_Db = []
#print (line.split('\t'))
min_size = data[4]
numbs = 0
for gen in data[4]:
numbs +=1
#print (numbs)
if numbs <= reduce_genome_list_number:
#print (numbs)
if gen in genome_prev:
genome_prev[gen] +=1
else:
genome_prev[gen] = 1
print ('Total space of seleted species;' + str(len(genome_prev)))
#### Determine number of samples required to be positive in
if samples_to_be_studied == g1_samples:
samples_needed_in = float(float(prevalence_for_shortlisting)/100)*len(g1_samples)
elif samples_to_be_studied == g2_samples:
samples_needed_in = float(float(prevalence_for_shortlisting)/100)*len(g2_samples)
wanted_prev = []
for k,v in genome_prev.items():
if v >= samples_needed_in: # Filter samples based on percentage stated
wanted_prev.append(k)
print ('Prevalence filtered species;' + str(len(wanted_prev)))
wanted = list((set(wanted_prev))-set(pathogens))
have_to_be_forced = set(forced_inclusion) - set(wanted)
wanted_inclusion = wanted + list(have_to_be_forced)
wanted_prev = wanted_inclusion
print ('Strains to be considered after force inclusion / exclusion; ' + str(len(wanted_prev)))
outputting_filt = location_of_call + '/'+ output_prefix + '-Studied_strains.tsv'
with open(outputting_filt, 'w') as file:
for species in wanted_prev:
file.write(species + '\n')
consortia_size = consortia_size_wanted
if len(wanted_prev) < consortia_size:
print ('ERROR: Insufficient strains have passed filtering, change the prevalence filter to retain sufficient diversity for consortia creation.')
sys.exit()
all_consortia_combinations = itertools.combinations(genomes[wanted_prev].keys(), consortia_size) ###############
consortia_scores = {}
for consortia in all_consortia_combinations:
consortia_scores[consortia] = []
print ('Number of combinations; ', str(len(consortia_scores.keys())))
if taxonomic_filtering == True:
print ('Filtered based on taxonomic level; ', taxonomic_level)
filtered_consortia_scores = {}
taxonomy = pd.read_csv(taxonomic_file,sep='\t',index_col='user_genome')
for comb in consortia_scores:
taxonomies = []
#print (comb)
for i in comb:
d, p, c, o, f, g, s = taxonomy.loc[i]['classification'].split(';')
#print (i, s)
if taxonomic_level == 's':
taxonomies.append(s)
if taxonomic_level == 'g':
taxonomies.append(g)
if taxonomic_level == 'f':
taxonomies.append(f)
if taxonomic_level == 'o':
taxonomies.append(o)
if taxonomic_level == 'c':
taxonomies.append(c)
if taxonomic_level == 'p':
taxonomies.append(p)
#print (taxonomies)
#print (len(set(taxonomies)))
if len(set(taxonomies)) == len(comb): #
filtered_consortia_scores[tuple(comb)] = []
consortia_scores = filtered_consortia_scores
print ('Number of combinations after filtering; ', len(consortia_scores.keys()))
print ('::::: Step 2 complete: Strain reduction and consortia filtering.')
## Step 3
print (':::::: Step 3: Group scoring of consortia.')
for column in tqdm(list(samples[samples_to_be_studied].columns)): # For each sample ###########
consortia_studied = 0
redundancies_removed = 0
sample_data = samples[column]
matches = []
mismatches = []
consortia = []
consortia_matches = []
consortia_mismatches = []
cul_accounted = []
accouted_pfams = []
accouted_pfams_percentage = 0.0
samples_pfams = list(sample_data.loc[sample_data == 1].index)
samples_remaining_pfams = samples_pfams
#print ('Total number of Pfams; ', len(samples_pfams), ' Remaining Pfams; ', len(samples_remaining_pfams))
sample_specific_genomes = genomes
best_consortia = {}
failed_consortia = []
for combination in consortia_scores.keys(): ###########
# Prevent redundant analysis!!!!!!!!
combinations_pfams = []
for genome in combination:
genome_data = genomes[genome] # This section creates the single genome file
redundant_functional_list = combinations_pfams + list(genome_data.loc[genome_data == 1].index)
combinations_pfams = list(set(redundant_functional_list))
match = 0
mismatch = 0
match = len(list(set(samples_remaining_pfams).intersection(combinations_pfams))) # Identifies the common
#for i in combinations_pfams:
#match += pfams_prev[i]
# Bias based on core sample functions
if samples_to_be_studied == g1_samples:
bias_core_score = len(list(set(g1_core_bias).intersection(combinations_pfams))) * core_bias
bias_spef_score = len(list(set(g1_bias).intersection(combinations_pfams))) * pfam_bias
elif samples_to_be_studied == g2_samples:
bias_core_score = len(list(set(g2_core_bias).intersection(combinations_pfams))) * core_bias
bias_spef_score = len(list(set(g2_bias).intersection(combinations_pfams))) * pfam_bias
mismatch = len(combinations_pfams)-match
score = (match/ (match+mismatch)) + bias_core_score + bias_spef_score
prev = consortia_scores[combination]
prev.append(score)
consortia_scores[combination] = prev
consortia_mean_Scores = {}
for k,v in consortia_scores.items():
consortia_mean_Scores[k] = np.mean(v)
max_match = max(consortia_mean_Scores, key=consortia_mean_Scores.get) # Identify the best consortia member this round
print (":::::: Consortia Summary ::::::")
print ('Best consortia is; ' + str(max_match))
print ('Consortia-wide score; ', consortia_mean_Scores[max_match])
print ('Consortia tested; ' + str(len(consortia_mean_Scores.keys())))
consortia_selected = max_match ##############
outputting_all_Scores = location_of_call + '/'+ output_prefix + '-Consortia_scores.tsv'
with open(outputting_all_Scores, 'w') as file:
file.write('SynCom_members\tGroup_score\n')
for k,v in consortia_mean_Scores.items():
file.write(str(k) + '\t' + str(v) + '\n')
end_time = process_time()
step4_start_time = process_time()
print (':::::: Step 3 complete: Group scoring of consortia.')
# Step 4
print ('::::::: Step 4: Metabolic modelling and interaction analysis.')
# Need to write a for loop so only when these two flags are True, does it end the code
# This week mean iterations occur until a stable consortia is found
passed_phase_one_stability = False
passed_phase_two_stability = False
#output files
community_outputfile = location_of_call + '/'+ output_prefix + '-Community-wide_response.tsv'
paired_outputfile = location_of_call + '/'+ output_prefix +'-Paired_Interactions.tsv'
paired_title = "\t".join(["taxa1 and taxa2", "interaction"])+"\n"
community_title = "\t".join(["species", "consortia_vs_single_growth"])+"\n"
modelling_iteration = 0
individual_growths = {}
if models_folder is not None and models_folder != " ":
while passed_phase_two_stability == False:
#max_match = max(consortia_mean_Scores, key=consortia_mean_Scores.get) # Identify the best consortia member this round
#consortia_selected = max_match ##############
models = [] # list of models for the selected consortia
for species in consortia_selected:
models.append(find_models[species + '.RDS'])
all_data_stored = {} # Store consortia predictions
if consortia_size_wanted == 2:
for listi,individual in enumerate(models):
tmp_models = list(models)
tmp_models.pop(listi)
name1 = models[listi].split('/')[-1:][0].split('.RDS')[0]
name2 = tmp_models[0].split('/')[-1:][0].split('.RDS')[0]
print ('Currently growing; ', name1)
# !!!!!!!!!!!!! Here, the species being studied is given first, then the other ones, then all the names
subprocess.run(['Rscript', location_of_file + '/' + 'scripts/Modelling/Size2/Single_Growth.R', location_of_call + '/' , models[listi], tmp_models[0], name1,name2])
# Commands must be Rscript Single_Growth.R working_directory model1 model2 model3 model4 Name1 Name2 Name3 Name4
growth_curve = []
ln_num = 0
for line in open(location_of_call + '/' + 'statistics.csv', 'r'): #change
ln_num +=1
if ln_num >1:
print (",".join(line.split(',')[:-1][1:]))
species = line.split(',')[1]
growth_curve.append(int(line.replace('\n','').split(',')[3]))
individual_growths[name1] = growth_curve
subprocess.run(['rm', location_of_call + '/' + 'statistics.csv '])
print ('Individual growth curves generated for ;' + str(len(individual_growths)))
all_consortia_combinations = list(itertools.combinations(models, 2))
Paired_growths = {}
for comb in all_consortia_combinations:
tmp_models = list(models[:])
tmp_models.remove(list(comb)[0])
tmp_models.remove(list(comb)[1])
name1 = list(comb)[0].split('/')[-1:][0].split('.RDS')[0]
name2 = list(comb)[1].split('/')[-1:][0].split('.RDS')[0]
print ('Strains being grown together;')
print( list(comb)[0].replace('"','').split('/')[-1:][0].split('.RDS')[0], list(comb)[1].replace('"','').split('/')[-1:][0].split('.RDS')[0], '; names=(', name1,',',name2,')') # Only highlighting those species being paired
subprocess.run(['Rscript', location_of_file + '/' + 'scripts/Modelling/Size2/Paired_Growth.R', location_of_call + '/' , list(comb)[0], list(comb)[1], name1,name2])
# Commands must be Rscript Single_Growth.R working_directory model1 model2 model3 model4 Name1 Name2 Name3 Name4
ln_num = 0
growth_info = {}
growth_info[list(comb)[0].split('/')[-1:][0].split('.RDS')[0]] = []
growth_info[list(comb)[1].split('/')[-1:][0].split('.RDS')[0]] = []
for line in open(location_of_call + '/' + 'statistics.csv', 'r'): #change
ln_num +=1
if ln_num >1:
print (",".join(line.split(',')[:-1][1:]))
species = line.split(',')[1].replace('"','').split('/')[-1:][0].split('.RDS')[0]
growth = int(line.replace('\n','').split(',')[3])
growth_info[species].append(growth)
Paired_growths[comb] = growth_info
subprocess.run(['rm', location_of_call + '/' + 'statistics.csv '])
### Identify paired interactions
with open(paired_outputfile, 'w') as outputting:
outputting.write(paired_title)
for comb, data in Paired_growths.items():
print ('Calculating interaction between; ')
#print (comb)
species_1 = list(comb)[0].split('/')[-1:][0].split('.RDS')[0]
species_2 = list(comb)[1].split('/')[-1:][0].split('.RDS')[0]
print (species_1)
print (species_2)
# Calculate interaction type for species1
single1 = individual_growths[species_1][-1:][0]
paired1 = data[species_1][-1:][0]
perc1 = ((single1/paired1)*100)-100
if perc1 >10.0:
interaction1 = 'positive'
elif perc1 < -10.0:
interaction1 = 'negative'
else:
interaction1 = 'none'
# Calculate interaction type for species2
single2 = individual_growths[species_2][-1:][0]
paired2 = data[species_2][-1:][0]
perc2 = ((single2/paired2)*100)-100
print (perc1, perc2)
if perc2 >10.0:
interaction2 = 'positive'
elif perc2 < -10.0:
interaction2 = 'negative'
else:
interaction2 = 'none'
# Overall interaction type
if interaction1 == 'positive':
if interaction2 == 'positive':
overall_interaction = 'mutualism'
elif interaction2 == 'negative':
overall_interaction = 'parasitism'
elif interaction2 == 'none':
overall_interaction = 'commensalism'
elif interaction1 == 'negative':
if interaction2 == 'positive':
overall_interaction = 'parasitism'
elif interaction2 == 'negative':
overall_interaction = 'competition'
elif interaction2 == 'none':
overall_interaction = 'amensalism'
elif interaction1 == 'none':
if interaction2 == 'positive':
overall_interaction = 'commensalism'
elif interaction2 == 'negative':
overall_interaction = 'amensalism'
elif interaction2 == 'none':
overall_interaction = 'neutralism'
outputting.write(species_1 + ' and ' + species_2 + '\t ' + overall_interaction + '\n')
print (species_1 + ' and ' + species_2 + '; ' + overall_interaction + '\n')
print ('Running whole community model.')
Community_growth = {}
name1 = models[0].split('/')[-1:][0].split('.RDS')[0]
name2 = models[1].split('/')[-1:][0].split('.RDS')[0]
try:
subprocess.run(['rm', location_of_call + '/' + 'statistics.csv'])
except FileNotFoundError:
lol = 0
#print( list(comb)[0], list(comb)[1],tmp_models[0],tmp_models[1], name1,name2,name3,name4)
subprocess.run(['Rscript', location_of_file + '/' + 'scripts/Modelling/Size2/Combined_Growth.R', location_of_call + '/' , models[0], models[1], name1,name2])
# Commands must be Rscript Single_Growth.R working_directory model1 model2 model3 model4 Name1 Name2 Name3 Name4
ln_num = 0
growth_info = {}
Community_growth[models[0].split('/')[-1:][0].split('.RDS')[0]] = []
Community_growth[models[1].split('/')[-1:][0].split('.RDS')[0]] = []
for line in open(location_of_call + '/' + 'statistics.csv', 'r'): #change
ln_num +=1
if ln_num >1:
print (",".join(line.split(',')[:-1][1:]))
species = line.split(',')[1].replace('"','')
growth = int(line.replace('\n','').split(',')[3])
Community_growth[species].append(growth)
#subprocess.run(['rm ' + location_of_call + '/' + 'statistics.csv'])
with open(community_outputfile, 'w') as outputting:
outputting.write(community_title)
species_1 = models[0].split('/')[-1:][0].split('.RDS')[0]
species_2 = models[1].split('/')[-1:][0].split('.RDS')[0]
for species in [species_1,species_2]:
single1 = individual_growths[species][-1:][0]
paired1 = Community_growth[species][-1:][0]
perc1 = ((single1/paired1)*100)-100
outputting.write(species + '\t' + str(perc1) + '%\n')
## Store the data
all_data_stored[tuple(models)] = [individual_growths,Paired_growths,Community_growth]
#print ('Completed consortia; ', str(len(all_data_stored.keys())))
# ## Three species
# In[45]:
if consortia_size_wanted == 3:
for listi,individual in enumerate(models):
tmp_models = list(models)
tmp_models.pop(listi)
name1 = models[listi].split('/')[-1:][0].split('.RDS')[0]
name2 = tmp_models[0].split('/')[-1:][0].split('.RDS')[0]
name3 = tmp_models[1].split('/')[-1:][0].split('.RDS')[0]
print ('Currently growing; ', name1)
# !!!!!!!!!!!!! Here, the species being studied is given first, then the other ones, then all the names
subprocess.run(['Rscript', location_of_file + '/' + 'scripts/Modelling/Size3/Single_Growth.R', location_of_call + '/' , models[listi], tmp_models[0],tmp_models[1], name1,name2,name3])
# Commands must be Rscript Single_Growth.R working_directory model1 model2 model3 model4 Name1 Name2 Name3 Name4
growth_curve = []
ln_num = 0
for line in open(location_of_call + '/' + 'statistics.csv', 'r'): #change
ln_num +=1
if ln_num >1:
print (",".join(line.split(',')[:-1][1:]))
species = line.split(',')[1]
growth_curve.append(int(line.replace('\n','').split(',')[3]))
individual_growths[name1] = growth_curve
subprocess.run(['rm', location_of_call + '/' + 'statistics.csv '])
print ('Individual growth curves generated for ;' + str(len(individual_growths)))
all_consortia_combinations = list(itertools.combinations(models, 2))
Paired_growths = {}
for comb in all_consortia_combinations:
tmp_models = list(models[:])
tmp_models.remove(list(comb)[0])
tmp_models.remove(list(comb)[1])
name1 = list(comb)[0].split('/')[-1:][0].split('.RDS')[0]
name2 = list(comb)[1].split('/')[-1:][0].split('.RDS')[0]
name3 = tmp_models[0].split('/')[-1:][0].split('.RDS')[0]
print ('Strains being grown together;')
print( list(comb)[0].replace('"','').split('/')[-1:][0].split('.RDS')[0], list(comb)[1].replace('"','').split('/')[-1:][0].split('.RDS')[0], '; names=(', name1,',',name2,')') # Only highlighting those species being paired
subprocess.run(['Rscript', location_of_file + '/' + 'scripts/Modelling/Size3/Paired_Growth.R', location_of_call + '/' , list(comb)[0], list(comb)[1],tmp_models[0], name1,name2,name3])
# Commands must be Rscript Single_Growth.R working_directory model1 model2 model3 model4 Name1 Name2 Name3 Name4
ln_num = 0
growth_info = {}
growth_info[list(comb)[0].split('/')[-1:][0].split('.RDS')[0]] = []
growth_info[list(comb)[1].split('/')[-1:][0].split('.RDS')[0]] = []
for line in open(location_of_call + '/' + 'statistics.csv', 'r'): #change
ln_num +=1
if ln_num >1:
print (",".join(line.split(',')[:-1][1:]))
species = line.split(',')[1].replace('"','').split('/')[-1:][0].split('.RDS')[0]
growth = int(line.replace('\n','').split(',')[3])
growth_info[species].append(growth)
Paired_growths[comb] = growth_info
subprocess.run(['rm', location_of_call + '/' + 'statistics.csv '])
### Identify paired interactions
with open(paired_outputfile, 'w') as outputting:
outputting.write(paired_title)
for comb, data in Paired_growths.items():
print ('Calculating interaction between; ')
#print (comb)
species_1 = list(comb)[0].split('/')[-1:][0].split('.RDS')[0]
species_2 = list(comb)[1].split('/')[-1:][0].split('.RDS')[0]
print (species_1)
print (species_2)
# Calculate interaction type for species1
single1 = individual_growths[species_1][-1:][0]
paired1 = data[species_1][-1:][0]
perc1 = ((single1/paired1)*100)-100
if perc1 >10.0:
interaction1 = 'positive'
elif perc1 < -10.0:
interaction1 = 'negative'
else:
interaction1 = 'none'
# Calculate interaction type for species2
single2 = individual_growths[species_2][-1:][0]
paired2 = data[species_2][-1:][0]
perc2 = ((single2/paired2)*100)-100
print (perc1, perc2)
if perc2 >10.0:
interaction2 = 'positive'
elif perc2 < -10.0:
interaction2 = 'negative'
else:
interaction2 = 'none'
# Overall interaction type
if interaction1 == 'positive':
if interaction2 == 'positive':
overall_interaction = 'mutualism'
elif interaction2 == 'negative':
overall_interaction = 'parasitism'
elif interaction2 == 'none':
overall_interaction = 'commensalism'
elif interaction1 == 'negative':
if interaction2 == 'positive':
overall_interaction = 'parasitism'
elif interaction2 == 'negative':
overall_interaction = 'competition'
elif interaction2 == 'none':
overall_interaction = 'amensalism'
elif interaction1 == 'none':
if interaction2 == 'positive':
overall_interaction = 'commensalism'
elif interaction2 == 'negative':
overall_interaction = 'amensalism'
elif interaction2 == 'none':
overall_interaction = 'neutralism'
outputting.write(species_1 + ' and ' + species_2 + '\t ' + overall_interaction + '\n')
print (species_1 + ' and ' + species_2 + '; ' + overall_interaction + '\n')
print ('Running whole community model.')
Community_growth = {}
name1 = models[0].split('/')[-1:][0].split('.RDS')[0]
name2 = models[1].split('/')[-1:][0].split('.RDS')[0]
name3 = models[2].split('/')[-1:][0].split('.RDS')[0]
try:
subprocess.run(['rm', location_of_call + '/' + 'statistics.csv'])
except FileNotFoundError:
lol = 0
#print( list(comb)[0], list(comb)[1],tmp_models[0],tmp_models[1], name1,name2,name3,name4)
subprocess.run(['Rscript', location_of_file + '/' + 'scripts/Modelling/Size3/Combined_Growth.R', location_of_call + '/' , models[0], models[1],models[2], name1,name2,name3])
# Commands must be Rscript Single_Growth.R working_directory model1 model2 model3 model4 Name1 Name2 Name3 Name4
ln_num = 0
growth_info = {}
Community_growth[models[0].split('/')[-1:][0].split('.RDS')[0]] = []
Community_growth[models[1].split('/')[-1:][0].split('.RDS')[0]] = []
Community_growth[models[2].split('/')[-1:][0].split('.RDS')[0]] = []
for line in open(location_of_call + '/' + 'statistics.csv''r'): #change
ln_num +=1
if ln_num >1:
print (",".join(line.split(',')[:-1][1:]))
species = line.split(',')[1].replace('"','')
growth = int(line.replace('\n','').split(',')[3])
Community_growth[species].append(growth)
#subprocess.run(['rm ' + location_of_call + '/' + 'statistics.csv'])