-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
3234 lines (2803 loc) · 177 KB
/
Copy pathmain.py
File metadata and controls
3234 lines (2803 loc) · 177 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
import subprocess
import time
import copy
from ete3 import Tree
import math
import dendropy
from dendropy.calculate import treecompare
import os.path
import csv
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from multiprocessing import Process
import os
import psutil
import socket
import itertools
from collections import Counter
def run_mafft(args, cpu_id):
result_addr = "/shared/mt100/6_book_chapter_final/iqtree/result_mafft.txt"
pid = os.getpid() # Get the current process ID
os.sched_setaffinity(pid, {cpu_id}) # Set CPU affinity to bind the process to a specific core
lst_result = []
for command in args:
# Run MAFFT alignment command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)
stdout, stderr = process.communicate()
# Extract MAFFT output file path
mafft_addr = command.split(" ")[-1]
assert os.path.isfile(mafft_addr) # Ensure the output file exists
# Get path to the original unmodified alignment
original_addr = mafft_addr.split("estimated")[0] + "original.fas"
assert os.path.isfile(original_addr)
# Compute alignment distance metrics using FastSP
command_distance_ca = f"/shared/mt100/ml_env/bin/java -jar /shared/mt100/6_book_chapter_final/FastSP/FastSP.jar -r {original_addr} -e {mafft_addr}"
process1 = subprocess.Popen(command_distance_ca, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)
distances, stderr1 = process1.communicate()
distances = distances.strip().split("\n")
# Extract SP and TC scores from FastSP output
sp_score = float(distances[0].split(" ")[1].strip())
tc_score = float(distances[6].split(" ")[1].strip())
# Parse timing information from stderr
time_command = stderr.split("Command being timed")[1]
time_command = time_command.strip().split("\n")
assert "User time" in time_command[1]
assert "System time" in time_command[2]
user_time = float(time_command[1].split(":")[1].strip())
system_time = float(time_command[2].split(":")[1].strip())
elased_time = str(user_time + system_time)
# Append results in custom format
lst_result.append(mafft_addr + "::" + elased_time + "::" + str(sp_score) + "::" + str(tc_score) + "\n")
# Write results to output file
with open(result_addr, "a") as h:
h.write("\n".join(lst_result))
print(f"Reported: {len(args)} mafft, cpu_id:{cpu_id}")
def config_mafft(scenarios, root_folder, mafft_pkg, iqtree_folder, mafft_result_addr, INDEL_RATE_LST, error_rate_lst, gap_penalty, cpu_cores, numbsim, start_replica ):
os.makedirs(iqtree_folder, exist_ok=True) # Ensure output folder exists
for scenario in scenarios:
scenario_folder = f"{root_folder}{scenario}/"
for i, num_species in enumerate(num_tip_lst):
if os.path.isfile(mafft_result_addr):
os.remove(mafft_result_addr) # Clear old results
commands = []
for sim in range(start_replica, numbsim):
sim_folder = scenario_folder + f"net_{num_species}_species/{sim}/"
for num_gt in num_gt_lst:
gt_folder = sim_folder + f"{num_gt}_gene_trees/"
alignments_folder = gt_folder + "alignments/"
for sites in sites_per_gt_lst:
for j in range(num_gt):
for error_rate in error_rate_lst:
for indel_rate in INDEL_RATE_LST:
# Construct input and output paths for MAFFT
erroneous_not_aligned_addr = f"{alignments_folder}length_{sites}_alignment_{j}_indel_rate_{indel_rate}_error_{error_rate}_alignment_estimated.fas"
output_addr = erroneous_not_aligned_addr.split((".fas"))[0] + "_mafft.fas"
# Create MAFFT command
command = f"/usr/bin/time -v {mafft_pkg} --globalpair --maxiterate 1000 --ep {gap_penalty} {erroneous_not_aligned_addr} > {output_addr}"
commands.append(command)
# Run MAFFT commands in parallel
run_parallel(commands, run_mafft, max_parallel_processes=cpu_cores, batch_size=round(len(commands)/cpu_cores) + 1)
# Parse and store MAFFT results
parse_mafft_result(scenario_folder, mafft_result_addr, num_species, numbsim, start_replica, num_gt_lst, sites_per_gt_lst, INDEL_RATE_LST, error_rate_lst)
print(f"Species {num_species} is finished")
def parse_mafft_result(scenario_folder, mafft_result_addr, num_species, numbsim, start_replica, num_gt_lst, sites_per_gt_lst, INDEL_RATE_LST, error_rate_lst):
result_dict = {}
# Read MAFFT results from file
with open(mafft_result_addr, "r") as h:
result = h.read()
result = result.split()
for line in result:
addr, elased_time, sp_score, tc_score = line.split("::")
result_dict[addr] = [elased_time, sp_score, tc_score]
# Store metrics for each alignment
for sim in range(start_replica, numbsim):
sim_folder = scenario_folder + f"net_{num_species}_species/{sim}/"
for num_gt in num_gt_lst:
gt_folder = sim_folder + f"{num_gt}_gene_trees/"
for sites in sites_per_gt_lst:
alignments_folder = gt_folder + "alignments/"
mafft_folder = gt_folder + f"maffts/"
os.makedirs(mafft_folder, exist_ok=True)
for error_rate in error_rate_lst:
for indel_rate in INDEL_RATE_LST:
# Output file paths for scores and timing
mafft_file_addr = mafft_folder + f"mafft_length_{sites}_indel_rate_{indel_rate}_error_{error_rate}"
mafft_times_addr = f"{mafft_file_addr}_times"
mafft_sp_scores_addr = f"{mafft_file_addr}_sp_scores"
mafft_tc_scores_addr = f"{mafft_file_addr}_tc_scores"
lst_sp_score = []
lst_tc_score = []
lst_times = []
for j in range(num_gt):
file_temp = f"{alignments_folder}length_{sites}_alignment_{j}_indel_rate_{indel_rate}_error_{error_rate}_alignment_estimated_mafft.fas"
elased_time, sp_score, tc_score = result_dict[file_temp]
lst_sp_score.append(sp_score)
lst_tc_score.append(tc_score)
lst_times.append(elased_time)
# Write SP scores, TC scores, and times to files
with open(mafft_sp_scores_addr, "w") as h:
h.write("\n".join(lst_sp_score))
with open(mafft_tc_scores_addr, "w") as h:
h.write("\n".join(lst_tc_score))
with open(mafft_times_addr, "w") as h:
h.write("\n".join(lst_times))
def run_iqtree(args, cpu_id):
result_addr = "/shared/mt100/6_book_chapter_final/iqtree/result.txt"
pid = os.getpid() # Get the current process ID
os.sched_setaffinity(pid, {cpu_id}) # Bind the process to a specific CPU core
lst_result = []
for command in args:
# Run IQ-TREE command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)
stdout, stderr = process.communicate()
# Extract alignment file path from command
alignment_addr = command.split(" ")[4]
tree_addr = alignment_addr + ".treefile"
assert os.path.isfile(tree_addr) # Ensure the tree file exists
# Read inferred unrooted tree
with open(tree_addr, "r") as h:
infered_tree = h.read()
# Root the inferred tree using specified outgroup
command_rooting = f"/shared/mt100/ml_env/bin/nw_reroot {tree_addr} OUT"
process1 = subprocess.Popen(command_rooting, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)
rooted_tree, stderr1 = process1.communicate()
assert stderr1 == "" # Ensure no error in rooting
rooted_tree = rooted_tree.strip()
# Parse timing information from stderr
time_command = stderr.strip().split("\n")
assert "User time" in time_command[1]
assert "System time" in time_command[2]
user_time = float(time_command[1].split(":")[1].strip())
system_time = float(time_command[2].split(":")[1].strip())
elased_time = str(user_time + system_time)
# Append result to list
lst_result.append(alignment_addr + "::" + rooted_tree.strip() + "::" + elased_time + "::" + infered_tree + "\n")
# Clean up intermediate files generated by IQ-TREE
os.remove(alignment_addr + ".bionj")
os.remove(alignment_addr + ".ckp.gz")
os.remove(alignment_addr + ".iqtree")
os.remove(alignment_addr + ".log")
os.remove(alignment_addr + ".mldist")
os.remove(alignment_addr + ".model.gz")
os.remove(alignment_addr + ".treefile")
# Write results to file
with open(result_addr, "a") as h:
h.write("\n".join(lst_result))
print(f"Reported: {len(args)} iqtree, cpu_id:{cpu_id}")
def config_iqtree(scenarios, root_folder, iqtree_pkg, iqtree_folder, error_rate_lst, iqtree_result_addr, INDEL_RATE_LST, cpu_cores, numbsim, start_replica):
os.makedirs(iqtree_folder, exist_ok=True) # Create output folder if not exists
for scenario in scenarios:
if os.path.isfile(iqtree_result_addr):
os.remove(iqtree_result_addr) # Remove previous results
scenario_folder = f"{root_folder}{scenario}/"
commands = []
for i, num_species in enumerate(num_tip_lst):
for sim in range(start_replica, numbsim):
sim_folder = scenario_folder + f"net_{num_species}_species/{sim}/"
for num_gt in num_gt_lst:
gt_folder = sim_folder + f"{num_gt}_gene_trees/"
alignments_folder = gt_folder + "alignments/"
for sites in sites_per_gt_lst:
for indel_rate in INDEL_RATE_LST:
for error_rate in error_rate_lst:
for j in range(num_gt):
for erroneous in ["original", "estimated_mafft"]:
# Skip redundant original if repeated error model
if error_rate == "repeat" and erroneous == "original":
continue
# Construct alignment file path
addr_seq = f"{alignments_folder}length_{sites}_alignment_{j}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}.fas"
assert os.path.isfile(addr_seq) # Ensure alignment file exists
# Build IQ-TREE command
model = "MFP"
type_of_seq = "DNA"
command = f"/usr/bin/time -v {iqtree_pkg} -s {addr_seq} -m {model} -st {type_of_seq} -redo"
commands.append(command)
# Run IQ-TREE in parallel on multiple CPUs
run_parallel(commands, run_iqtree, max_parallel_processes=cpu_cores, batch_size=round(len(commands)/cpu_cores) + 1)
# Parse and save IQ-TREE outputs
parse_iqtree_result(scenario_folder, iqtree_result_addr, num_species, numbsim, start_replica, num_gt_lst, sites_per_gt_lst, error_rate_lst, INDEL_RATE_LST)
print(f"Species {num_species} is finished")
def parse_iqtree_result(scenario_folder, iqtree_result_addr, num_species, numbsim, start_replica, num_gt_lst,
sites_per_gt_lst, error_rate_lst, INDEL_RATE_LST):
result_dict = {}
# Read and split raw result file
with open(iqtree_result_addr, "r") as h:
result = h.read()
result = result.split()
# Parse result lines into dictionary
for line in result:
addr, rooted_tree, elased_time, unrooted_tree = line.split("::")
result_dict[addr] = [rooted_tree, elased_time, unrooted_tree]
# For each simulation, write rooted/unrooted trees and timings
for sim in range(start_replica, numbsim):
sim_folder = scenario_folder + f"net_{num_species}_species/{sim}/"
for num_gt in num_gt_lst:
gt_folder = sim_folder + f"{num_gt}_gene_trees/"
iqtree_folder = gt_folder + f"iqtrees/"
os.makedirs(iqtree_folder, exist_ok=True)
alignments_folder = gt_folder + "alignments/"
for sites in sites_per_gt_lst:
for error_rate in error_rate_lst:
for indel_rate in INDEL_RATE_LST:
for erroneous in ["original", "estimated_mafft"]:
if error_rate == "repeat" and erroneous == "original":
continue
# Define output paths for each metric
iqtree_rooted_addr = iqtree_folder + f"iqtree_{sites}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}_rooted"
iqtree_unrooted_addr = iqtree_folder + f"iqtree_{sites}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}_unrooted"
iqtree_times_addr = iqtree_folder + f"iqtree_{sites}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}_times"
lst_rooted_trees = []
lst_unrooted_trees = []
lst_times = []
for j in range(num_gt):
# Build alignment key and extract stored metrics
addr_res = f"{alignments_folder}length_{sites}_alignment_{j}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}.fas"
rooted_tree, elased_time, unrooted_tree = result_dict[addr_res]
lst_rooted_trees.append(rooted_tree)
lst_unrooted_trees.append(unrooted_tree)
lst_times.append(elased_time)
# Write per-alignment results to files
with open(iqtree_rooted_addr, "w") as h:
h.write("\n".join(lst_rooted_trees))
with open(iqtree_unrooted_addr, "w") as h:
h.write("\n".join(lst_unrooted_trees))
with open(iqtree_times_addr, "w") as h:
h.write("\n".join(lst_times))
def run_iqtree_bootstrap(args, cpu_id):
result_addr = "/shared/mt100/6_book_chapter_final/iqtree/result.txt"
pid = os.getpid() # Get the current process ID
os.sched_setaffinity(pid, {cpu_id}) # Set affinity to the specified CPU core
lst_result = []
for command in args:
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)
stdout, stderr = process.communicate()
alignment_addr = command.split(" ")[4]
tree_addr = alignment_addr + ".treefile"
assert os.path.isfile(tree_addr)
with open(tree_addr, "r") as h:
infered_tree = h.read()
command_collapsing = f"/shared/mt100/ml_env/bin/nw_ed {tree_addr} 'i & b <= 70' o "
process2 = subprocess.Popen(command_collapsing, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)
collapsed_tree, stderr2 = process2.communicate()
assert stderr2==""
collapsed_tree = collapsed_tree.strip()
with open(tree_addr, "w") as h:
h.write(collapsed_tree + '\n')
command_rooting = f"/shared/mt100/ml_env/bin/nw_reroot {tree_addr} OUT"
process1 = subprocess.Popen(command_rooting, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)
rooted_collapsed_tree, stderr1 = process1.communicate()
assert stderr1==""
rooted_collapsed_tree = rooted_collapsed_tree.strip()
time_command = stderr.strip().split("\n")
assert "User time" in time_command[1]
assert "System time" in time_command[2]
user_time = float(time_command[1].split(":")[1].strip())
system_time = float(time_command[2].split(":")[1].strip())
elased_time = str(user_time + system_time)
lst_result.append(alignment_addr + "::" + rooted_collapsed_tree.strip() + "::" + elased_time + "::" + infered_tree +"\n")
os.remove(alignment_addr + ".bionj")
os.remove(alignment_addr + ".ckp.gz")
os.remove(alignment_addr + ".iqtree")
os.remove(alignment_addr + ".log")
os.remove(alignment_addr + ".mldist")
os.remove(alignment_addr + ".model.gz")
os.remove(alignment_addr + ".treefile")
os.remove(alignment_addr + ".splits.nex")
os.remove(alignment_addr + ".contree")
with open(result_addr, "a") as h:
h.write("\n".join(lst_result))
print(f"Reported: {len(args)} iqtree, cpu_id:{cpu_id}")
def config_iqtree_bootstrap(scenarios, root_folder, iqtree_pkg, iqtree_folder, error_rate_lst, iqtree_result_addr, INDEL_RATE_LST, cpu_cores, numbsim, start_replica):
os.makedirs(iqtree_folder, exist_ok=True)
for scenario in scenarios:
if os.path.isfile(iqtree_result_addr):
os.remove(iqtree_result_addr)
scenario_folder = f"{root_folder}{scenario}/"
commands = []
for i, num_species in enumerate(num_tip_lst):
for sim in range(start_replica, numbsim):
sim_folder = scenario_folder + f"net_{num_species}_species/{sim}/"
for num_gt in num_gt_lst:
gt_folder = sim_folder + f"{num_gt}_gene_trees/"
alignments_folder = gt_folder + "alignments/"
for sites in sites_per_gt_lst:
# batch = []
for indel_rate in INDEL_RATE_LST:
for error_rate in error_rate_lst:
for j in range(num_gt):
for erroneous in ["original", "estimated_mafft"]:
addr_seq = f"{alignments_folder}length_{sites}_alignment_{j}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}.fas"
assert os.path.isfile(addr_seq)
model = "MFP"
type_of_seq = "DNA"
command = f"/usr/bin/time -v {iqtree_pkg} -s {addr_seq} -m {model} -st {type_of_seq} -B 1000 -redo"
commands.append(command)
run_parallel(commands, run_iqtree_bootstrap, max_parallel_processes=cpu_cores, batch_size=round(len(commands)/cpu_cores) + 1)
parse_iqtree_bootstrap_result(scenario_folder, iqtree_result_addr, num_species, numbsim, start_replica, num_gt_lst, sites_per_gt_lst, error_rate_lst, INDEL_RATE_LST)
print(f"Species {num_species} is finished")
def parse_iqtree_bootstrap_result(scenario_folder, iqtree_result_addr, num_species, numbsim, start_replica, num_gt_lst, sites_per_gt_lst, error_rate_lst, INDEL_RATE_LST):
result_dict = {}
with open(iqtree_result_addr, "r") as h:
result = h.read()
result = result.split()
for line in result:
addr, rooted_collapsed_tree, elased_time, unrooted_tree= line.split("::")
result_dict[addr] = [rooted_collapsed_tree, elased_time, unrooted_tree]
for sim in range(start_replica, numbsim):
sim_folder = scenario_folder + f"net_{num_species}_species/{sim}/"
for num_gt in num_gt_lst:
gt_folder = sim_folder + f"{num_gt}_gene_trees/"
iqtree_folder = gt_folder + f"iqtrees/"
os.makedirs(iqtree_folder, exist_ok=True)
alignments_folder = gt_folder + "alignments/"
for sites in sites_per_gt_lst:
for error_rate in error_rate_lst:
for indel_rate in INDEL_RATE_LST:
for erroneous in ["original", "estimated_mafft"]:
iqtree_rooted_collapsed_addr = iqtree_folder + f"bootstrap_iqtree_{sites}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}_rooted"
iqtree_unrooted_addr = iqtree_folder + f"bootstrap_iqtree_{sites}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}_unrooted"
iqtree_times_addr = iqtree_folder + f"bootstrap_iqtree_{sites}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}_times"
lst_rooted_collapsed_trees = []
lst_unrooted_trees = []
lst_times = []
for j in range(num_gt):
addr_res = f"{alignments_folder}length_{sites}_alignment_{j}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}.fas"
rooted_collapsed_tree, elased_time, unrooted_tree = result_dict[addr_res]
lst_rooted_collapsed_trees.append(rooted_collapsed_tree)
lst_unrooted_trees.append(unrooted_tree)
lst_times.append(elased_time)
with open(iqtree_rooted_collapsed_addr, "w") as h:
h.write("\n".join(lst_rooted_collapsed_trees))
with open(iqtree_unrooted_addr, "w") as h:
h.write("\n".join(lst_unrooted_trees))
with open(iqtree_times_addr, "w") as h:
h.write("\n".join(lst_times))
def calc_different_distance(estimated_network, target_network, results_folder):
if "#" not in estimated_network and "#" not in target_network: # if both networks are tree then calculate RF distance
distance_RF = calc_RF_distance(estimated_network, target_network)
num_inferred_reticulations = 0
num_real_reticulations = 0
distance_luay, distance_rnbs, distance_normwapd = "", "", ""
else:
count = estimated_network.count("#")
assert count % 2 == 0
num_inferred_reticulations = int(count / 2)
count = target_network.count("#")
assert count % 2 == 0
num_real_reticulations = int(count / 2)
distance_luay, distance_rnbs, distance_normwapd = calc_net_distance( estimated_network, target_network, results_folder)
distance_RF = ""
return distance_RF, distance_luay, distance_rnbs, distance_normwapd, num_inferred_reticulations, num_real_reticulations
def run_infer_net(args, cpu_id):
"""Run the command and append the output to the specified file."""
for command, infer_net_out_addr, gt_folder in args:
pid = os.getpid() # Get the current process ID
os.sched_setaffinity(pid, {cpu_id}) # Set affinity to the specified CPU core
print(f"core_{cpu_id}:{command}")
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)
stdout, stderr = process.communicate()
addr_species = f"{gt_folder}species.nw"
with open(addr_species, "r") as h:
net = h.read()
# remove first line
result = stdout.strip().split("\n")[1:]
method = infer_net_out_addr.split("/")[-2]
assert method in ['InferNetwork_MPL', 'InferNetwork_ML', 'MCMC_GT', 'MCMC_GT_pseudo']
if method =='MCMC_GT' or method=='MCMC_GT_pseudo':
lst_estimations = []
for idx, elm in enumerate(result):
if elm.startswith("Rank ="):
rec = result[idx].split(";")
percentage = float(rec[2].split("=")[1].strip())
prob = float(rec[3].split(":")[0].split("=")[1].strip())
estimated_especies = ":".join(rec[3].split(":")[1:]) + ";"
lst_estimations.append([percentage, prob, estimated_especies])
assert lst_estimations[0][0] == max([i[0] for i in lst_estimations])
percent, prob, estim = lst_estimations[0]
distance_RF, distance_luay, distance_rnbs, distance_normwapd, num_inferred_reticulations, num_real_reticulations = calc_different_distance(estim, net, gt_folder)
result.insert(len(result), f"\nEstimated_network:\t {estim} \nTarget_network:\t {net}\nPercentage: {percent}\nLog Probability: {prob}\ndistance_RF: {distance_RF}\ndistance_luay: {distance_luay}\ndistance_rnbs: {distance_rnbs}\ndistance_normwapd: {distance_normwapd}\nnum_inferred_reticulations: {num_inferred_reticulations}\nnum_real_reticulations: {num_real_reticulations}\n")
elif method == 'InferNetwork_MPL' or method == 'InferNetwork_ML':
lst_estimations = []
for idx, elm in enumerate(result):
if elm.startswith("Inferred Network "):
num_net = int(result[idx].split("#")[1][0:-1])
prob = float(result[idx+2].split(":")[1].strip("Running time"))
estimated_species = result[idx+1]
lst_estimations.append([prob, estimated_species])
assert lst_estimations[0][0] == max([i[0] for i in lst_estimations])
prob, estim = lst_estimations[0]
distance_RF, distance_luay, distance_rnbs, distance_normwapd, num_inferred_reticulations, num_real_reticulations = calc_different_distance(estim, net, gt_folder)
result.insert(len(result), f"\nEstimated_network:\t {estim} \nTarget_network:\t {net}\nLog Probability: {prob}\ndistance_RF: {distance_RF}\ndistance_luay: {distance_luay}\ndistance_rnbs: {distance_rnbs}\ndistance_normwapd: {distance_normwapd}\nnum_inferred_reticulations: {num_inferred_reticulations}\nnum_real_reticulations: {num_real_reticulations}\n")
result1 = "\n".join(result)
result1 += "\n"
result1 += stderr
with open(infer_net_out_addr, "w") as h:
h.write(result1)
print(f"Reported: {infer_net_out_addr}")
def run_parallel(commands, target_func, max_parallel_processes, batch_size):
active_processes = []
threshold_percentage = 10.0
enough_cores = False
num_batches = len(commands) / batch_size
if round(num_batches) == num_batches:
num_batches = int(num_batches)
else:
num_batches = int(num_batches) + 1
max_parallel_processes = min(num_batches, max_parallel_processes)
while enough_cores == False:
# Get the CPU utilization for each core
cpu_percentages = psutil.cpu_percent(percpu=True, interval=1)
free_cpus = [i for i, usage in enumerate(cpu_percentages) if usage < threshold_percentage]
if len(free_cpus) > max_parallel_processes:
enough_cores = True
else:
print(f"Number of Cores is {len(free_cpus)} while we need {max_parallel_processes}")
time.sleep(1)
lst_cores_ids = free_cpus[0:max_parallel_processes]
batches = []
for i in range(num_batches):
start = i * batch_size
end = (i + 1) * batch_size
batches.append(commands[start:end])
print(f"Number of batches: {num_batches}, size each batches: {batch_size}, Number of commands: {len(commands)}")
for args in batches:
while len(active_processes) >= max_parallel_processes:
# Check if any process has finished
for process, id in active_processes:
if not process.is_alive():
cpu_id_removed = id
active_processes.remove([process, id])
else:
time.sleep(1) # Sleep for a short time before checking again
temp_cores_ids = copy.deepcopy(lst_cores_ids)
for process, id in active_processes:
temp_cores_ids.remove(id)
assert len(temp_cores_ids) > 0
cpu_id = temp_cores_ids[0]
process = Process(target=target_func, args=(args, cpu_id))
active_processes.append([process, cpu_id])
process.start()
time.sleep(0.1)
# Wait for all processes to finish
for process, id in active_processes:
process.join()
def config_infer_net(root_folder, scenarios, phylonet, num_tip_lst, numbsim, start_replica, num_gt_lst, lst_max_reticulation, error_rate_lst, INDEL_RATE_LST, methods, params_mcmc_gt, cpu_cores):
commands = []
for scenario in scenarios:
scenario_folder = f"{root_folder}{scenario}/"
for i, num_species in enumerate(num_tip_lst):
for sim in range(start_replica, numbsim):
sim_folder = scenario_folder + f"net_{num_species}_species/{sim}/"
for num_gt in num_gt_lst:
gt_folder = sim_folder + f"{num_gt}_gene_trees/"
for method in methods:
method_folder = gt_folder + f"{method}/"
os.makedirs(method_folder, exist_ok=True)
for max_reticulation in lst_max_reticulation:
for iqtree_flag in [False, True]:
if iqtree_flag==False:
command, infer_net_out_addr = produce_commands_infer_net(phylonet, gt_folder, method_folder, num_gt, iqtree_flag, 0, max_reticulation, method, params_mcmc_gt, 0, 0, 0)
if command != "":
commands.append((command, infer_net_out_addr, gt_folder))
else:
for sites in sites_per_gt_lst:
for error_rate in error_rate_lst:
for indel_rate in INDEL_RATE_LST:
for erroneous in ["original", "estimated_mafft"]:
if error_rate == "repeat" and erroneous == "original":
continue
command, infer_net_out_addr = produce_commands_infer_net(phylonet, gt_folder, method_folder, num_gt, iqtree_flag, sites, max_reticulation, method, params_mcmc_gt, error_rate, indel_rate, erroneous)
if command != "":
commands.append((command, infer_net_out_addr, gt_folder))
print(scenario, sim, num_gt, method)
print(f"started, {methods}")
run_parallel(commands, run_infer_net, max_parallel_processes=cpu_cores, batch_size=1)
print(f"Species {num_species} is finished")
def produce_commands_infer_net(phylonet, gt_folder, method_folder, num_gt, iqtree_flag, sites, max_reticulation, method, params_mcmc_gt, error_rate, indel_rate, erroneous):
iqtree_folder = gt_folder + f"iqtrees/"
if iqtree_flag:
gt_addr = iqtree_folder + f"iqtree_{sites}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}_rooted"
else:
gt_addr = f"{gt_folder}genetrees_scaled.txt"
with open(gt_addr, "r") as h:
gene_trees = h.read()
gene_trees = gene_trees.strip().split("\n")
assert num_gt == len(gene_trees)
gene_trees = [f"Tree gt{i} = " + gt for i, gt in enumerate(gene_trees)]
gene_trees = '\n'.join(gene_trees)
if method == 'InferNetwork_MPL':
if iqtree_flag:
infer_net_addr = f"{method_folder}iqtree_reticulation_{max_reticulation}_length_{sites}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}.nex"
infer_net_out_addr = f"{method_folder}iqtree_reticulation_{max_reticulation}_length_{sites}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}_out.txt"
nex_file = f"#NEXUS\n BEGIN TREES;\n{gene_trees}\nEND;\n" + f"\nBEGIN PHYLONET;\nInferNetwork_MPL (gt0-gt{num_gt - 1}) {max_reticulation} -di -pl 1; \nEND;\n "
else:
infer_net_addr = f"{method_folder}reticulation_{max_reticulation}.nex"
infer_net_out_addr = f"{method_folder}reticulation_{max_reticulation}_out.txt"
nex_file = f"#NEXUS\n BEGIN TREES;\n{gene_trees}\nEND;\n" + f"\nBEGIN PHYLONET;\nInferNetwork_MPL (gt0-gt{num_gt - 1}) {max_reticulation} -di -pl 1; \nEND;\n "
elif method == 'InferNetwork_ML':
if iqtree_flag:
infer_net_addr = f"{method_folder}iqtree_reticulation_{max_reticulation}_length_{sites}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}.nex"
infer_net_out_addr = f"{method_folder}iqtree_reticulation_{max_reticulation}_length_{sites}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}_out.txt"
nex_file = f"#NEXUS\n BEGIN TREES;\n{gene_trees}\nEND;\n" + f"\nBEGIN PHYLONET;\nInferNetwork_ML (gt0-gt{num_gt - 1}) {max_reticulation} -di -pl 1; \nEND;\n "
else:
infer_net_addr = f"{method_folder}reticulation_{max_reticulation}.nex"
infer_net_out_addr = f"{method_folder}reticulation_{max_reticulation}_out.txt"
nex_file = f"#NEXUS\n BEGIN TREES;\n{gene_trees}\nEND;\n" + f"\nBEGIN PHYLONET;\nInferNetwork_ML (gt0-gt{num_gt - 1}) {max_reticulation} -di -pl 1; \nEND;\n "
elif method == 'MCMC_GT':
cl = params_mcmc_gt["cl"]
bl = params_mcmc_gt["bl"]
sf = params_mcmc_gt["sf"]
if iqtree_flag:
infer_net_addr = f"{method_folder}iqtree_reticulation_{max_reticulation}_length_{sites}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}.nex"
infer_net_out_addr = f"{method_folder}iqtree_reticulation_{max_reticulation}_length_{sites}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}_out.txt"
nex_file = f"#NEXUS\n BEGIN TREES;\n{gene_trees}\nEND;\n" + f"\nBEGIN PHYLONET;\nMCMC_GT (gt0-gt{num_gt-1}) -cl {cl} -bl {bl} -sf {sf} -mr {max_reticulation} -pl 1 ; \nEND;\n "
else:
infer_net_addr = f"{method_folder}reticulation_{max_reticulation}.nex"
infer_net_out_addr = f"{method_folder}reticulation_{max_reticulation}_out.txt"
nex_file = f"#NEXUS\n BEGIN TREES;\n{gene_trees}\nEND;\n" + f"\nBEGIN PHYLONET;\nMCMC_GT (gt0-gt{num_gt - 1}) -cl {cl} -bl {bl} -sf {sf} -mr {max_reticulation} -pl 1 ; \nEND;\n "
elif method == 'MCMC_GT_pseudo':
cl = params_mcmc_gt["cl"]
bl = params_mcmc_gt["bl"]
sf = params_mcmc_gt["sf"]
if iqtree_flag:
infer_net_addr = f"{method_folder}iqtree_reticulation_{max_reticulation}_length_{sites}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}.nex"
infer_net_out_addr = f"{method_folder}iqtree_reticulation_{max_reticulation}_length_{sites}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}_out.txt"
nex_file = f"#NEXUS\n BEGIN TREES;\n{gene_trees}\nEND;\n" + f"\nBEGIN PHYLONET;\nMCMC_GT (gt0-gt{num_gt - 1}) -cl {cl} -bl {bl} -sf {sf} -mr {max_reticulation} -pl 1 -pseudo ; \nEND;\n "
else:
infer_net_addr = f"{method_folder}reticulation_{max_reticulation}.nex"
infer_net_out_addr = f"{method_folder}reticulation_{max_reticulation}_out.txt"
nex_file = f"#NEXUS\n BEGIN TREES;\n{gene_trees}\nEND;\n" + f"\nBEGIN PHYLONET;\nMCMC_GT (gt0-gt{num_gt - 1}) -cl {cl} -bl {bl} -sf {sf} -mr {max_reticulation} -pl 1 -pseudo ; \nEND;\n "
if os.path.isfile(infer_net_out_addr):
return "", ""
with open(infer_net_addr, "w") as h:
h.write(nex_file)
command = f"/usr/bin/time -v java -jar {phylonet} {infer_net_addr}"
return command, infer_net_out_addr
def calc_variables(infer_net_out_addr, iqtree_time, mafft_time, sites, scenario, num_species, sim, max_reticulation, num_gt, method, error_rate, indel_rate, mafft_flag, data, iqtree_flag, normalized_distance_truth_vs_mafft_false, normalized_distance_truth_vs_mafft_true, normalized_distance_mafft_true_vs_mafft_false, mafft_sp_scores, mafft_tc_scores, ground_truth_network_likelihood, likelihoods, num_topologies, mismatches, bootstrap_true_vs_original_refinement, bootstrap_true_vs_estimated_refinement, kl_true_vs_original, kl_true_vs_estimated, l1_true_vs_original, l1_true_vs_estimated):
if os.path.isfile(infer_net_out_addr):
with open(infer_net_out_addr, "r") as h:
res = h.read()
res = res.strip().split("\n")
temp = {}
for idx, elm in enumerate(res):
elm = elm.strip()
if method == 'MCMC_GT' or method == 'MCMC_GT_pseudo':
if elm.startswith("Percentage:"):
temp["percentage"] = float(elm.split(":")[1].strip())
elif method == 'InferNetwork_MPL' or method == 'InferNetwork_ML':
temp["percentage"] = ""
if elm.startswith("distance_RF:"):
string_temp = elm.split(":")[1].strip()
temp["distance_RF"] = float(string_temp) if string_temp != "" else string_temp
if elm.startswith("distance_luay"):
string_temp = elm.split(":")[1].strip()
temp["distance_luay"] = float(string_temp) if string_temp != "" else string_temp
if elm.startswith("distance_rnbs:"):
string_temp = elm.split(":")[1].strip()
temp["distance_rnbs"] = float(string_temp) if string_temp != "" else string_temp
if elm.startswith("distance_normwapd:"):
string_temp = elm.split(":")[1].strip()
temp["distance_normwapd"] = float(string_temp) if string_temp != "" else string_temp
if elm.startswith("num_inferred_reticulations:"):
temp["num_inferred_reticulations"] = float(elm.split(":")[1].strip())
if elm.startswith("num_real_reticulations:"):
temp["num_real_reticulations"] = float(elm.split(":")[1].strip())
if elm.startswith("Log Probability:"):
temp["log_probability"] = float(elm.split(":")[1].strip())
if elm.startswith("Estimated_network:"):
temp["estimated_network"] = elm.split(" ")[1].strip()
if elm.startswith("Target_network:"):
temp1 = elm.split(" ")
if len(temp1) == 2:
temp["target_network"] = elm.split(" ")[1].strip()
elif len(temp1) == 3:
temp["target_network"] = elm.split("\t")[1].strip().replace(" ", "")
if elm.strip().startswith("User time (seconds):"):
user_time = float(elm.split(":")[1].strip())
if elm.strip().startswith("System time (seconds):"):
system_time = float(elm.split(":")[1].strip())
temp["time_infer_net"] = user_time + system_time
temp["scenario"] = scenario
temp["alignment_length"] = str(sites)
temp["num_species"] = num_species
temp["replica"] = sim
temp["likelihoods"] = likelihoods
temp["num_topologies"] = num_topologies
temp["ground_truth_network_likelihood"] = ground_truth_network_likelihood
temp["mismatches"] = mismatches
temp["max_reticulation"] = max_reticulation
temp["error_rate"] = error_rate
temp["num_gt"] = num_gt
temp["iqtree"] = str(iqtree_flag)
temp["iqtree_time"] = iqtree_time
temp["method"] = method
temp["indel_rate"] = indel_rate
temp["mafft"] = str(mafft_flag)
temp["mafft_time"] = mafft_time
temp["norm_avg_dis_truth_vs_mafft_false"] = normalized_distance_truth_vs_mafft_false
temp["norm_avg_dis_truth_vs_mafft_true"] = normalized_distance_truth_vs_mafft_true
temp["norm_avg_dis_mafft_true_vs_mafft_false"] = normalized_distance_mafft_true_vs_mafft_false
temp["mafft_avg_sp_scores"] =mafft_sp_scores
temp["mafft_avg_tc_scores"] = mafft_tc_scores
temp["bootstrap_true_vs_original_refinement"] = bootstrap_true_vs_original_refinement
temp["bootstrap_true_vs_estimated_refinement"] = bootstrap_true_vs_estimated_refinement
temp["kl_true_vs_original"] = kl_true_vs_original
temp["kl_true_vs_estimated"] = kl_true_vs_estimated
temp["l1_true_vs_original"] = l1_true_vs_original
temp["l1_true_vs_estimated"] = l1_true_vs_estimated
else:
print(f"not available: {infer_net_out_addr}")
temp = {}
temp["log_probability"] = temp["estimated_network"] = temp["target_network"] = temp["time_infer_net"] = temp[
"iqtree_time"] = temp["scenario"] = \
temp["iqtree"] = temp["alignment_length"] = temp["num_species"] = temp["max_reticulation"] = temp[
"num_gt"] = temp["distance_RF"] = \
temp["distance_luay"] = temp["distance_rnbs"] = temp["distance_normwapd"] = temp["num_real_reticulations"] = \
temp["num_inferred_reticulations"] = temp["mafft_time"] = temp["error_rate"] = temp["method"]= temp["indel_rate"]= temp["mafft"] = temp["percentage"] = temp["replica"] =\
temp["norm_avg_dis_truth_vs_mafft_false"] = temp["norm_avg_dis_truth_vs_mafft_true"] = temp["norm_avg_dis_mafft_true_vs_mafft_false"] = temp["mafft_avg_sp_scores"] = \
temp["mafft_avg_tc_scores"] = temp["ground_truth_network_likelihood"] = temp["likelihoods"] = temp["num_topologies"] =temp["mismatches"]= \
temp["bootstrap_true_vs_original_refinement"] = temp["bootstrap_true_vs_estimated_refinement"] = \
temp["kl_true_vs_original"] = temp["kl_true_vs_estimated"] = temp["l1_true_vs_original"] = temp["l1_true_vs_estimated"] = ""
data.append(temp)
return data
def calc_likelihood(infer_net_out_addr, method):
if os.path.isfile(infer_net_out_addr):
with open(infer_net_out_addr, "r") as h:
res = h.read()
res = res.strip().split("\n")
temp = {}
if method in ['InferNetwork_MPL', 'InferNetwork_ML']:
num_topologies = 1
for idx, elm in enumerate(res):
if elm.startswith("Results after run"):
run_number = int(elm.split("#")[1])
temp[run_number] = []
elif elm.startswith("-"):
temp[run_number].append(float(elm.split(":")[0]))
elif elm.startswith("Total log probability:"):
if "Running time:" in elm:
best_likelihood = float(elm.split(":")[1].strip().split("Running time")[0].strip())
else:
best_likelihood = float(elm.split(":")[1].strip())
log_liklihood_lst = [val[0] for _, val in temp.items()]
# assert max(log_liklihood_lst) <= round(best_likelihood, 4), print(infer_net_out_addr) #TODO check this
val_str = ""
for idx in range(1, max(temp.keys()) + 1):
val_str += str(temp[idx]) + ";"
val_str = val_str[:-1]
elif method=='MCMC_GT_pseudo':
num_topologies = 0
for idx, elm in enumerate(res):
line = elm.strip().split(";")
if len(line)==8 and line[0][0] >= "0" and line[0][0] <= "9":
temp2 = {}
iter = int(line[0].strip())
if iter != 0:
temp2["Iteration"] = float(line[0].strip())
temp2["Posterior"] = float(line[1].strip())
temp2["ESS"] = float(line[2].strip())
temp2["Likelihood"] = float(line[3].strip())
temp2["Prior"] = float(line[4].strip())
temp2["ESS_prior"] = float(line[5].strip())
temp2["Reticulation"] = float(line[6].strip())
temp[iter] = temp2
elif elm.startswith("Rank ="):
num_topologies += 1
best_likelihood = float(line[3].strip().split("=")[1].strip().split(":")[0].strip())
log_liklihood_lst = [val["Posterior"] for _, val in temp.items()]
# assert max([val["Posterior"] for _, val in temp.items()]) <= round(best_likelihood, 4) , print(infer_net_out_addr) #TODO check this
assert 1 in temp.keys() and 1000 in temp.keys()
val_str = ""
for idx in range(1, max(temp.keys()) + 1):
val_str += str([temp[idx]["Posterior"]]) + ";"
val_str = val_str[:-1]
else:
raise Exception("method is wrong")
else:
print(f"not available: {infer_net_out_addr}")
val_str = ""
return val_str, num_topologies
def calc_sum_times(addr):
if os.path.isfile(addr):
with open(addr, "r") as h:
lst_times = h.read()
sum_time = sum(
[float(item) for item in lst_times.strip().split("\n")])
else:
raise Exception(f"why this file is not available: {addr}")
return sum_time
def calc_average_items(addr):
if os.path.isfile(addr):
with open(addr, "r") as h:
lst_times = h.read()
average = np.mean([float(item) for item in lst_times.strip().split("\n")])
else:
raise Exception(f"why this file is not available: {addr}")
return average
def get_num_mismatches(gt_folder, sites, indel_rate, error_rate):
if error_rate == 0:
mismatch_addr = f"{gt_folder}alignments/mismatch_length_{sites}_indel_rate_{indel_rate}_error_{error_rate}_alignment_original.txt"
with open(mismatch_addr, "r") as h:
mismatches = float(h.read().strip())
else:
mismatches = ""
return mismatches
def calc_kl_l1(addr):
if os.path.isfile(addr):
with open(addr, "r") as h:
kl_l1 = h.read()
kl_lst = kl_l1.splitlines()[0].split('\t')
kl_lst = [i.split(":") for i in kl_lst]
kl_dic = {key.strip():float(val) for key, val in kl_lst}
kl_true_vs_original = kl_dic['true_vs_original_kl']
kl_true_vs_estimated = kl_dic['true_vs_estimated_kl']
kl_original_vs_estimated = kl_dic['original_vs_estimated_kl']
l1_lst = kl_l1.splitlines()[1].split('\t')
l1_lst = [i.split(":") for i in l1_lst]
l1_dic = {key.strip():float(val) for key, val in l1_lst}
l1_true_vs_original = l1_dic['true_vs_original_l1']
l1_true_vs_estimated = l1_dic['true_vs_estimated_l1']
l1_original_vs_estimated = l1_dic['original_vs_estimated_l1']
return kl_true_vs_original, kl_true_vs_estimated, kl_original_vs_estimated, l1_true_vs_original, l1_true_vs_estimated, l1_original_vs_estimated
def create_output(scenarios, root_folder, num_tip_lst, numbsim, start_replica, num_gt_lst, sites_per_gt_lst, lst_max_reticulation, error_rate_lst, INDEL_RATE_LST, methods):
data = []
results_folder = f"{root_folder}results/"
os.makedirs(results_folder, exist_ok=True)
csv_addr = f"{results_folder}final_result.csv"
for scenario in scenarios:
scenario_folder = f"{root_folder}{scenario}/"
for i, num_species in enumerate(num_tip_lst):
for sim in range(start_replica, numbsim):
sim_folder = scenario_folder + f"net_{num_species}_species/{sim}/"
for num_gt in num_gt_lst:
gt_folder = sim_folder + f"{num_gt}_gene_trees/"
iqtree_folder = gt_folder + f"iqtrees/"
mafft_folder = gt_folder + f"maffts/"
for method in methods:
method_folder = gt_folder + f"{method}/"
for sites in sites_per_gt_lst:
for iqtree_flag in [False, True]:
for max_reticulation in lst_max_reticulation:
if iqtree_flag:
for error_rate in error_rate_lst:
for indel_rate in INDEL_RATE_LST:
for erroneous in ["original", "estimated_mafft"]:
mafft_flag = True if erroneous=="estimated_mafft" else False
iqtree_time_addr = iqtree_folder + f"iqtree_{sites}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}_times"
iqtree_time = calc_sum_times(iqtree_time_addr)
iqtree_gt_addr = iqtree_folder + f"distance_iqtree_{sites}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}_rooted"
if mafft_flag == False :
true_vs_original_addr = iqtree_folder + f"distance_iqtree_{sites}_indel_rate_{indel_rate}_error_{error_rate}_true_vs_original"
normalized_distance_truth_vs_mafft_false = calc_average_items(true_vs_original_addr)
normalized_distance_truth_vs_mafft_true = ""
normalized_distance_mafft_true_vs_mafft_false = ""
mafft_time = ""
mafft_sp_scores = ""
mafft_tc_scores = ""
bootstrap_true_vs_original_refinement, bootstrap_true_vs_estimated_refinement, _ = calc_refinement_gene_trees(gt_folder, num_gt, sites, iqtree_folder, indel_rate, error_rate)
bootstrap_true_vs_estimated_refinement = ""
kl_file_addr = iqtree_folder + f"distance_kl_l1_iqtree_{sites}_indel_rate_{indel_rate}_error_{error_rate}.txt"
kl_true_vs_original, kl_true_vs_estimated, _, l1_true_vs_original, l1_true_vs_estimated, _ = calc_kl_l1(kl_file_addr)
kl_true_vs_estimated = ""
l1_true_vs_estimated = ""
elif mafft_flag == True:
truth_vs_mafft_false_addr = iqtree_folder + f"distance_iqtree_{sites}_indel_rate_{indel_rate}_error_{error_rate}_true_vs_original"
truth_vs_mafft_true_addr = iqtree_folder + f"distance_iqtree_{sites}_indel_rate_{indel_rate}_error_{error_rate}_true_vs_estimated"
mafft_true_vs_mafft_false_addr = iqtree_folder + f"distance_iqtree_{sites}_indel_rate_{indel_rate}_error_{error_rate}_original_vs_estimated"
normalized_distance_truth_vs_mafft_false = calc_average_items(truth_vs_mafft_false_addr)
normalized_distance_truth_vs_mafft_true = calc_average_items(truth_vs_mafft_true_addr)
normalized_distance_mafft_true_vs_mafft_false = calc_average_items(mafft_true_vs_mafft_false_addr)
mafft_times_addr = mafft_folder + f"mafft_length_{sites}_indel_rate_{indel_rate}_error_{error_rate}_times"
mafft_time = calc_sum_times(mafft_times_addr)
mafft_sp_scores_addr = mafft_folder + f"mafft_length_{sites}_indel_rate_{indel_rate}_error_{error_rate}_sp_scores"
mafft_tc_scores_addr = mafft_folder + f"mafft_length_{sites}_indel_rate_{indel_rate}_error_{error_rate}_tc_scores"
mafft_sp_scores = calc_average_items(mafft_sp_scores_addr)
mafft_tc_scores = calc_average_items(mafft_tc_scores_addr)
bootstrap_true_vs_original_refinement, bootstrap_true_vs_estimated_refinement, _ = calc_refinement_gene_trees(gt_folder, num_gt, sites, iqtree_folder, indel_rate, error_rate)
bootstrap_true_vs_original_refinement = ""
kl_file_addr = iqtree_folder + f"distance_kl_l1_iqtree_{sites}_indel_rate_{indel_rate}_error_{error_rate}.txt"
kl_true_vs_original, kl_true_vs_estimated, _, l1_true_vs_original, l1_true_vs_estimated, _ = calc_kl_l1(kl_file_addr)
kl_true_vs_original = ""
l1_true_vs_original = ""
mismatches = get_num_mismatches(gt_folder, sites, indel_rate, error_rate)
infer_net_out_addr = f"{method_folder}iqtree_reticulation_{max_reticulation}_length_{sites}_indel_rate_{indel_rate}_error_{error_rate}_alignment_{erroneous}_out.txt"
ground_truth_network_likelihood = ""
likelihoods, num_topologies = calc_likelihood(infer_net_out_addr, method)
data = calc_variables(infer_net_out_addr, iqtree_time, mafft_time, sites,
scenario, num_species, sim, max_reticulation, num_gt, method,
error_rate, indel_rate, mafft_flag, data, iqtree_flag, normalized_distance_truth_vs_mafft_false, normalized_distance_truth_vs_mafft_true,
normalized_distance_mafft_true_vs_mafft_false, mafft_sp_scores, mafft_tc_scores, ground_truth_network_likelihood, likelihoods, num_topologies, mismatches,
bootstrap_true_vs_original_refinement, bootstrap_true_vs_estimated_refinement,
kl_true_vs_original, kl_true_vs_estimated, l1_true_vs_original, l1_true_vs_estimated)
else:
error_rate = 0
indel_rate = 0
iqtree_time = ""
normalized_distance_truth_vs_mafft_false = ""
normalized_distance_truth_vs_mafft_true = ""
normalized_distance_mafft_true_vs_mafft_false = ""
mafft_time = ""
mafft_sp_scores = ""
mafft_tc_scores = ""
mafft_flag = False
bootstrap_true_vs_original_refinement = ""
bootstrap_true_vs_estimated_refinement = ""
kl_true_vs_original = ""
kl_true_vs_estimated = ""
l1_true_vs_original = ""
l1_true_vs_estimated = ""
mismatches = get_num_mismatches(gt_folder, sites, indel_rate, error_rate)
infer_net_out_addr = f"{method_folder}reticulation_{max_reticulation}_out.txt"
ground_truth_network_likelihood = calc_ground_truth_network_likelihood(gt_folder, method_folder, max_reticulation, num_gt, phylonet, method)
likelihoods, num_topologies = calc_likelihood(infer_net_out_addr, method)
data = calc_variables(infer_net_out_addr, iqtree_time, mafft_time, sites, scenario,
num_species, sim, max_reticulation, num_gt, method, error_rate, indel_rate, mafft_flag,
data, iqtree_flag, normalized_distance_truth_vs_mafft_false, normalized_distance_truth_vs_mafft_true,
normalized_distance_mafft_true_vs_mafft_false, mafft_sp_scores, mafft_tc_scores, ground_truth_network_likelihood, likelihoods, num_topologies, mismatches,
bootstrap_true_vs_original_refinement, bootstrap_true_vs_estimated_refinement,
kl_true_vs_original, kl_true_vs_estimated, l1_true_vs_original, l1_true_vs_estimated)
print(f"scenario:{scenario} sim:{sim} num_gt:{num_gt} method:{method} sites:{sites} iqtree_flag:{iqtree_flag} max_reticulation:{max_reticulation}")
print(f"Scenario: {scenario} is finished")
for row in data:
if "iqtree" not in row.keys():
print()
with open(csv_addr, 'w', newline='') as csvfile:
fieldnames = ['scenario', 'method', 'num_species', 'replica', 'num_gt', 'alignment_length', 'indel_rate', 'error_rate', 'max_reticulation', 'mafft',
'iqtree', 'num_real_reticulations', 'num_inferred_reticulations', 'distance_RF',
'distance_luay', 'distance_rnbs', 'distance_normwapd', 'percentage', 'ground_truth_network_likelihood', 'log_probability', 'time_infer_net',
'iqtree_time', "mafft_time", 'norm_avg_dis_truth_vs_mafft_false', 'norm_avg_dis_truth_vs_mafft_true', 'norm_avg_dis_mafft_true_vs_mafft_false',
'mafft_avg_sp_scores', 'mafft_avg_tc_scores', 'num_topologies', 'mismatches', 'bootstrap_true_vs_original_refinement', 'bootstrap_true_vs_estimated_refinement',
'kl_true_vs_original', 'kl_true_vs_estimated', 'l1_true_vs_original', 'l1_true_vs_estimated','estimated_network', 'target_network', 'likelihoods']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)
def prepare_network_for_distance(net):
temp = net.split("::")
if len(temp) != 1:
for i in temp[1:]:
remove_val = "::" + i.split(",")[0].split(")")[0]
net = net.replace(remove_val, "")
return net
def calc_ground_truth_network_likelihood(gt_folder, method_folder, max_reticulation, num_gt, phylonet, method):
ground_truth_net_addr = f"{gt_folder}species.nw"
with open(ground_truth_net_addr, "r") as h:
ground_truth_net = h.read()
gt_addr = f"{gt_folder}genetrees_scaled.txt"
with open(gt_addr, "r") as h:
gene_trees = h.read()
gene_trees = gene_trees.strip().split("\n")
gene_trees = [f"Tree gt{i} = " + gt for i, gt in enumerate(gene_trees)]
gene_trees = '\n'.join(gene_trees)
likelihood_net_nex_addr = f"{method_folder}reticulation_{max_reticulation}_likelihood.nex"
likelihood_net_out_addr = f"{method_folder}reticulation_{max_reticulation}_likelihood_out.txt"
if method== "MCMC_GT_pseudo":
nex_file = f"#NEXUS\n BEGIN NETWORKS; \n Network net = {ground_truth_net} \n END;\n\n BEGIN TREES;\n{gene_trees}\nEND;\n" + f"\nBEGIN PHYLONET;\nCalGTProb net (gt0-gt{num_gt - 1}) -pseudo -pl 1; \nEND;\n "
else:
nex_file = f"#NEXUS\n BEGIN NETWORKS; \n Network net = {ground_truth_net} \n END;\n\n BEGIN TREES;\n{gene_trees}\nEND;\n" + f"\nBEGIN PHYLONET;\nCalGTProb net (gt0-gt{num_gt - 1}) -pl 1; \nEND;\n "
with open(likelihood_net_nex_addr, "w") as h:
h.write(nex_file)
command = f"java -jar {phylonet} {likelihood_net_nex_addr}"
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)
stdout, stderr = process.communicate()
if stderr!="":
print("")
likelihood_net = float(stdout.strip().split("\n")[3].split(":")[1].strip())
return str(likelihood_net)
def calc_net_distance(estimated_network, Target_network, results_folder):
T1 =copy.deepcopy(Target_network)
estimated_network = prepare_network_for_distance(estimated_network)
Target_network = prepare_network_for_distance(Target_network)
import uuid