-
Notifications
You must be signed in to change notification settings - Fork 36
/
PyRate.py
7375 lines (6525 loc) · 344 KB
/
PyRate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# Created by Daniele Silvestro on 02/03/2012 => pyrate.help@gmail.com
import argparse, os,sys, platform, time, csv, glob
import random as rand
import warnings, importlib
import importlib.util
import copy as copy_lib
import json
version= "PyRate"
build = "v3.1.3 - 20230825"
if platform.system() == "Darwin": sys.stdout.write("\x1b]2;%s\x07" % version)
citation= """Silvestro, D., Antonelli, A., Salamin, N., & Meyer, X. (2019).
Improved estimation of macroevolutionary rates from fossil data using a Bayesian framework.
Paleobiology, doi: 10.1017/pab.2019.23.
"""
# check python version
V=list(sys.version_info[0:3])
if V[0]<3: sys.exit("""\nYou need Python v.3 to run this version of PyRate""")
# LOAD LIBRARIES
import argparse
try:
os.environ["OMP_NUM_THREADS"] = "1"
os.environ["OPENBLAS_NUM_THREADS"] = "1"
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["VECLIB_MAXIMUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
from numpy import *
import numpy as np
except(ImportError):
sys.exit("\nError: numpy library not found.\nYou can install numpy using: 'pip install numpy'\n")
try:
import scipy
from scipy.special import gamma
from scipy.special import beta as f_beta
from scipy.special import gdtr, gdtrix
from scipy.special import betainc
import scipy.stats
from scipy.optimize import fmin_powell as Fopt1
except(ImportError):
sys.exit("\nError: scipy library not found.\nYou can install scipy using: 'pip install scipy'\n")
try:
import pandas as pd
except(ImportError):
print("\nWarning: pandas library not found.\nYou can install pandas using: 'pip install pandas'\n")
try:
import multiprocessing, _thread
import multiprocessing.pool
class NoDaemonProcess(multiprocessing.Process):
# make 'daemon' attribute always return False
def _get_daemon(self): return False
def _set_daemon(self, value): pass
daemon = property(_get_daemon, _set_daemon)
class mcmcMPI(multiprocessing.pool.Pool):
# We sub-class multiprocessing.pool.Pool instead of multiprocessing.Pool
# because the latter is only a wrapper function, not a proper class.
Process = NoDaemonProcess
use_seq_lik= 0
if platform.system() == "Windows" or platform.system() == "Microsoft": use_seq_lik= 1
except(ImportError):
print("\nWarning: library multiprocessing not found.\n")
use_seq_lik= 1
if platform.system() == "Windows" or platform.system() == "Microsoft": use_seq_lik= 1
version_details="PyRate %s; OS: %s %s; Python version: %s; Numpy version: %s; Scipy version: %s" \
% (build, platform.system(), platform.release(), sys.version, np.version.version, scipy.version.version)
### numpy print options ###
np.set_printoptions(suppress= 1, precision=3) # prints floats, no scientific notation
numpy_major_version = int(np.__version__[0])
if numpy_major_version > 1:
np.set_printoptions(legacy='1.25') # avoid printing data type ine.g. BDNN when using numpy >= 2.0
original_stderr = sys.stderr
NO_WARN = original_stderr #open('pyrate_warnings.log', 'w')
small_number= 1e-50
def get_self_path():
self_path = -1
path_list = [os.path.dirname(sys.argv[0]) , os.getcwd()]
for path in path_list:
try:
self_path=path
importlib.util.spec_from_file_location("test", "%s/pyrate_lib/lib_updates_priors.py" % (self_path))
break
except:
self_path = -1
if self_path== -1:
print(os.getcwd(), os.path.dirname(sys.argv[0]))
sys.exit("pyrate_lib not found.\n")
return self_path
# Search for the module
hasFoundPyRateC = 0
try:
if platform.system()=="Darwin":
os_spec_lib="macOS"
try:
from pyrate_lib.fastPyRateC.macOS._FastPyRateC import PyRateC_BD_partial_lik, PyRateC_HOMPP_lik, PyRateC_setFossils, \
PyRateC_getLogGammaPDF, PyRateC_initEpochs, PyRateC_HPP_vec_lik, \
PyRateC_NHPP_lik, PyRateC_FBD_T4
except:
from pyrate_lib.fastPyRateC.macOS_arm._FastPyRateC import PyRateC_BD_partial_lik, PyRateC_HOMPP_lik, PyRateC_setFossils, \
PyRateC_getLogGammaPDF, PyRateC_initEpochs, PyRateC_HPP_vec_lik, \
PyRateC_NHPP_lik, PyRateC_FBD_T4
elif platform.system() == "Windows" or platform.system() == "Microsoft":
os_spec_lib="Windows"
py_version = sys.version_info.minor
if py_version < 7:
from pyrate_lib.fastPyRateC.Windows.py36._FastPyRateC import PyRateC_BD_partial_lik, PyRateC_HOMPP_lik, PyRateC_setFossils, \
PyRateC_getLogGammaPDF, PyRateC_initEpochs, PyRateC_HPP_vec_lik, \
PyRateC_NHPP_lik, PyRateC_FBD_T4
elif py_version == 7:
from pyrate_lib.fastPyRateC.Windows.py37._FastPyRateC import PyRateC_BD_partial_lik, PyRateC_HOMPP_lik, PyRateC_setFossils, \
PyRateC_getLogGammaPDF, PyRateC_initEpochs, PyRateC_HPP_vec_lik, \
PyRateC_NHPP_lik, PyRateC_FBD_T4
elif py_version == 8:
from pyrate_lib.fastPyRateC.Windows.py38._FastPyRateC import PyRateC_BD_partial_lik, PyRateC_HOMPP_lik, PyRateC_setFossils, \
PyRateC_getLogGammaPDF, PyRateC_initEpochs, PyRateC_HPP_vec_lik, \
PyRateC_NHPP_lik, PyRateC_FBD_T4
elif py_version == 9:
from pyrate_lib.fastPyRateC.Windows.py39._FastPyRateC import PyRateC_BD_partial_lik, PyRateC_HOMPP_lik, PyRateC_setFossils, \
PyRateC_getLogGammaPDF, PyRateC_initEpochs, PyRateC_HPP_vec_lik, \
PyRateC_NHPP_lik, PyRateC_FBD_T4
elif py_version == 10:
from pyrate_lib.fastPyRateC.Windows.py310._FastPyRateC import PyRateC_BD_partial_lik, PyRateC_HOMPP_lik, PyRateC_setFossils, \
PyRateC_getLogGammaPDF, PyRateC_initEpochs, PyRateC_HPP_vec_lik, \
PyRateC_NHPP_lik, PyRateC_FBD_T4
elif py_version == 11:
from pyrate_lib.fastPyRateC.Windows.py311._FastPyRateC import PyRateC_BD_partial_lik, PyRateC_HOMPP_lik, PyRateC_setFossils, \
PyRateC_getLogGammaPDF, PyRateC_initEpochs, PyRateC_HPP_vec_lik, \
PyRateC_NHPP_lik, PyRateC_FBD_T4
elif py_version == 12:
from pyrate_lib.fastPyRateC.Windows.py312._FastPyRateC import PyRateC_BD_partial_lik, PyRateC_HOMPP_lik, PyRateC_setFossils, \
PyRateC_getLogGammaPDF, PyRateC_initEpochs, PyRateC_HPP_vec_lik, \
PyRateC_NHPP_lik, PyRateC_FBD_T4
elif py_version == 13:
from pyrate_lib.fastPyRateC.Windows.py313._FastPyRateC import PyRateC_BD_partial_lik, PyRateC_HOMPP_lik, PyRateC_setFossils, \
PyRateC_getLogGammaPDF, PyRateC_initEpochs, PyRateC_HPP_vec_lik, \
PyRateC_NHPP_lik, PyRateC_FBD_T4
else:
os_spec_lib = "Other"
from pyrate_lib.fastPyRateC.Other._FastPyRateC import PyRateC_BD_partial_lik, PyRateC_HOMPP_lik, PyRateC_setFossils, \
PyRateC_getLogGammaPDF, PyRateC_initEpochs, PyRateC_HPP_vec_lik, \
PyRateC_NHPP_lik, PyRateC_FBD_T4
#c_lib_path = "pyrate_lib/fastPyRateC/%s" % (os_spec_lib)
#sys.path.append(os.path.join(self_path,c_lib_path))
#print self_path, sys.path
#import pyrate_lib.fastPyRateC.macOS._FastPyRateC
hasFoundPyRateC = 1
# print("Module FastPyRateC was loaded.")
# Set that to true to enable sanity check (comparing python and c++ results)
sanityCheckForPyRateC = 0
sanityCheckThreshold = 1e-10
if sanityCheckForPyRateC == 1:
print("Sanity check for FastPyRateC is enabled.")
print("Python and C results will be compared and any divergence greater than ", sanityCheckThreshold, " will be reported.")
except:
# print("Module FastPyRateC was not found.")
hasFoundPyRateC = 0
sanityCheckForPyRateC = 0
########################## CALC PROBS ##############################
def calcHPD(data, level) :
assert (0 < level < 1)
d = list(data)
d.sort()
nData = len(data)
nIn = int(round(level * nData))
if nIn < 2 :
raise RuntimeError("not enough data")
i = 0
r = d[i+nIn-1] - d[i]
for k in range(len(d) - (nIn - 1)) :
rk = d[k+nIn-1] - d[k]
if rk < r :
r = rk
i = k
assert 0 <= i <= i+nIn-1 < len(d)
return (d[i], d[i+nIn-1])
def check_burnin(b,I):
#print b, I
if b<1:burnin=int(b*I)
else: burnin=int(b)
if burnin>=(I-10) and b > 0:
print("Warning: burnin too high! Excluding 10% instead.")
burnin=int(0.1*I)
return burnin
def calc_model_probabilities(f,burnin):
print("parsing log file...\n")
t=loadtxt(f, skiprows=1)
num_it=shape(t)[0]
if num_it<10: sys.exit("\nNot enough samples in the log file!\n")
burnin=check_burnin(burnin, num_it)
print(("First %s samples excluded as burnin.\n" % (burnin)))
file1=open(f, 'r')
L=file1.readlines()
head= L[0].split()
PAR1=["k_birth","k_death"]
k_ind= [head.index(s) for s in head if s in PAR1]
if len(k_ind)==0: k_ind =[head.index(s) for s in head if s in ["K_l","K_m"]]
z1=t[burnin:,k_ind[0]] # list of shifts (lambda)
z2=t[burnin:,k_ind[1]] # list of shifts (mu)
y1= np.maximum(np.max(z1),np.max(z2))
print("Model Probability")
print(" Speciation Extinction")
for i in range(1,int(y1)+1):
k_l=float(len(z1[z1==i]))/len(z1)
k_m=float(len(z2[z2==i]))/len(z2)
print(("%s-rate %s %s" % (i,round(k_l,4),round(k_m,4))))
print("\n")
try:
import collections,os
d = collections.OrderedDict()
def count_BD_config_freq(A):
for a in A:
t = tuple(a)
if t in d: d[t] += 1
else: d[t] = 1
result = []
for (key, value) in list(d.items()): result.append(list(key) + [value])
return result
BD_config = t[burnin:,np.array(k_ind)]
B = np.asarray(count_BD_config_freq(BD_config))
B[:,2]=B[:,2]/sum(B[:,2])
B = B[B[:,2].argsort()[::-1]]
cum_prob = np.cumsum(B[:,2])
print("Best BD/ID configurations (rel.pr >= 0.05)")
print(" B/I D Rel.pr")
print(B[(np.round(B[:,2],3)>=0.05).nonzero()[0],:])
except: pass
quit()
def calc_ts_te(f, burnin):
if f=="null": return FA,LO
else:
t_file=np.loadtxt(f, skiprows=1)
head = np.array(next(open(f)).split())
# if t_file.shape[0]==1: sys.exit("\nNot enough samples in the log file!\n")
# if shape_f[1]<10: sys.exit("\nNot enough samples in the log file!\n")
ind_start=np.where(head=="tot_length")[0][0]
indexes= np.array([ind_start+1, ind_start+(t_file.shape[1]-ind_start)/2]).astype(int)
# fixes the case of missing empty column at the end of each row
if t_file[0,-1] != "False":
indexes = indexes+np.array([0,1])
ind_ts0 = indexes[0]
ind_te0 = indexes[1]
meanTS,meanTE=list(),list()
burnin=check_burnin(burnin, t_file.shape[0])
burnin+=1
j=0
for i in range(ind_ts0,ind_te0):
meanTS.append(np.mean(t_file[burnin:,i]))
meanTE.append(np.mean(t_file[burnin:,ind_te0+j]))
j+=1
return array(meanTS),array(meanTE)
def calc_BF(f1, f2):
input_file_raw = [os.path.basename(f1),os.path.basename(f2)]
def get_ML(FILE):
file1=open(FILE, 'r')
L=file1.readlines()
for i in range(len(L)):
if "Marginal likelihood" in L[i]:
x=L[i].split("Marginal likelihood: ")
ML= float(x[1])
return ML
BF= 2*(get_ML(f1)-get_ML(f2))
if abs(BF)<2: support="negligible"
elif abs(BF)<6: support="positive"
elif abs(BF)<10: support="strong"
else: support="very strong"
if BF>0: best=0
else: best=1
print(("\nModel A: %s\nModelB: %s" % (input_file_raw[best],input_file_raw[abs(best-1)])))
print(("\nModel A received %s support against Model B\nBayes Factor: %s\n\n" % (support, round(abs(BF), 4))))
def calc_BFlist(f1):
#f1 = os.path.basename(f1)
#print f1
tbl = np.genfromtxt(f1,"str")
file_list = tbl[:,tbl[0]=="file_name"]
f_list, l_list = list(), list()
for i in range(1, len(file_list)):
fn = str(file_list[i][0])
f_list.append(fn)
l_list.append(float(tbl[i,tbl[0]=="likelihood"][0]))
ml = l_list[l_list.index(max(l_list))]
l_list = np.array(l_list)
bf = 2*(ml - l_list)
print("Found %s models:" % (len(bf)))
for i in range(len(bf)): print("model %s: '%s'" % (i,f_list[i]))
print("\nBest model:", f_list[(bf==0).nonzero()[0][0]], ml, "\n")
for i in range(len(bf)):
BF = bf[i]
if abs(BF)==0: pass
else:
if abs(BF)<2: support="negligible"
elif abs(BF)<6: support="positive"
elif abs(BF)<10: support="strong"
else: support="very strong"
print("Support in favor of model %s: %s (%s)" % (i, BF, support))
def get_DT(T,s,e): # returns the Diversity Trajectory of s,e at times T (x10 faster)
B=np.sort(np.append(T,T[0]+1))+.000001 # the + .0001 prevents problems with identical ages
ss1 = np.histogram(s,bins=B)[0]
ee2 = np.histogram(e,bins=B)[0]
DD=(ss1-ee2)[::-1]
#return np.insert(np.cumsum(DD),0,0)[0:len(T)]
return np.cumsum(DD)[0:len(T)]
########################## PLOT RTT ##############################
def plot_RTT(infile,burnin, file_stem="",one_file= 0, root_plot=0,plot_type=1):
burnin = int(burnin)
if burnin<=1:
print("Burnin must be provided in terms of number of samples to be excluded.")
print("E.g. '-b 100' will remove the first 100 samples.")
print("Assuming burnin = 1.\n")
def print_R_vec(name,v):
new_v=[]
for j in range(0,len(v)):
value=v[j]
if isnan(v[j]): value="NA"
new_v.append(value)
vec="%s=c(%s, " % (name,new_v[0])
for j in range(1,len(v)-1): vec += "%s," % (new_v[j])
vec += "%s)" % (new_v[j+1])
return vec
path_dir = infile
sys.path.append(infile)
plot_title = file_stem.split('_')[0]
print("FILE STEM:",file_stem, plot_title)
if file_stem=="": direct="%s/*_marginal_rates.log" % infile
else: direct="%s/*%s*marginal_rates.log" % (infile,file_stem)
files=glob.glob(direct)
files=sort(files)
if one_file== 1: files=["%s/%smarginal_rates.log" % (infile,file_stem)]
stem_file=files[0]
name_file = os.path.splitext(os.path.basename(stem_file))[0]
wd = "%s" % os.path.dirname(stem_file)
#print(name_file, wd)
print("found", len(files), "log files...\n")
########################################################
###### DETERMINE MIN ROOT AGE ######
########################################################
if root_plot==0:
min_age=np.inf
print("determining min age...", end=' ')
for f in files:
file_name = os.path.splitext(os.path.basename(f))[0]
sys.stdout.write(".")
sys.stdout.flush()
head = next(open(f)).split() # should be faster
sp_ind= [head.index(s) for s in head if "l_" in s]
min_age=min(min_age,len(sp_ind))
print("Min root age:", min_age)
max_ind=min_age-1
else: max_ind = int(root_plot-1)
print(max_ind, root_plot)
########################################################
###### COMBINE ALL LOG FILES ######
########################################################
print("\ncombining all files...", end=' ')
file_n=0
for f in files:
file_name = os.path.splitext(os.path.basename(f))[0]
print(file_name)
try:
t=np.loadtxt(f, skiprows=np.maximum(1,burnin))
sys.stdout.write(".")
sys.stdout.flush()
head = next(open(f)).split()
l_ind= [head.index(s) for s in head if "l_" in s]
m_ind= [head.index(s) for s in head if "m_" in s]
r_ind= [head.index(s) for s in head if "r_" in s]
l_ind=l_ind[0:max_ind]
m_ind=m_ind[0:max_ind]
r_ind=r_ind[0:max_ind]
if file_n==0:
L_tbl=t[:,l_ind]
M_tbl=t[:,m_ind]
R_tbl=t[:,r_ind]
file_n=1
#if np.min([np.max(L_tbl),np.max(M_tbl)])>0.1: no_decimals = 3
#elif np.min([np.max(L_tbl),np.max(M_tbl)])>0.01: no_decimals = 5
#else:
no_decimals = 15
else:
L_tbl=np.concatenate((L_tbl,t[:,l_ind]),axis=0)
M_tbl=np.concatenate((M_tbl,t[:,m_ind]),axis=0)
R_tbl=np.concatenate((R_tbl,t[:,r_ind]),axis=0)
except:
print("skipping file:", f)
########################################################
###### CALCULATE HPDs ######
########################################################
print("\ncalculating HPDs...", end=' ')
def get_HPD(threshold=.95):
L_hpd_m,L_hpd_M=[],[]
M_hpd_m,M_hpd_M=[],[]
R_hpd_m,R_hpd_M=[],[]
sys.stdout.write(".")
sys.stdout.flush()
for time_ind in range(shape(L_tbl)[1]):
hpd1=np.around(calcHPD(L_tbl[:,time_ind],threshold),decimals=no_decimals)
hpd2=np.around(calcHPD(M_tbl[:,time_ind],threshold),decimals=no_decimals)
if len(r_ind)>0:
hpd3=np.around(calcHPD(R_tbl[:,time_ind],threshold),decimals=no_decimals)
else:
hpd3 = hpd1- hpd2
L_hpd_m.append(hpd1[0])
L_hpd_M.append(hpd1[1])
M_hpd_m.append(hpd2[0])
M_hpd_M.append(hpd2[1])
R_hpd_m.append(hpd3[0])
R_hpd_M.append(hpd3[1])
return [L_hpd_m,L_hpd_M,M_hpd_m,M_hpd_M,R_hpd_m,R_hpd_M]
def get_CI(threshold=.95):
threshold = (1-threshold)/2.
L_hpd_m,L_hpd_M=[],[]
M_hpd_m,M_hpd_M=[],[]
R_hpd_m,R_hpd_M=[],[]
sys.stdout.write(".")
sys.stdout.flush()
for time_ind in range(shape(R_tbl)[1]):
l=np.sort(L_tbl[:,time_ind])
m=np.sort(M_tbl[:,time_ind])
r=np.sort(R_tbl[:,time_ind])
hpd1=np.around(np.array([l[int(threshold*len(l))] , l[int(len(l) - threshold*len(l))] ]),decimals=no_decimals)
hpd2=np.around(np.array([m[int(threshold*len(m))] , m[int(len(m) - threshold*len(m))] ]),decimals=no_decimals)
hpd3=np.around(np.array([r[int(threshold*len(r))] , r[int(len(r) - threshold*len(r))] ]),decimals=no_decimals)
L_hpd_m.append(hpd1[0])
L_hpd_M.append(hpd1[1])
M_hpd_m.append(hpd2[0])
M_hpd_M.append(hpd2[1])
R_hpd_m.append(hpd3[0])
R_hpd_M.append(hpd3[1])
return [L_hpd_m,L_hpd_M,M_hpd_m,M_hpd_M,R_hpd_m,R_hpd_M]
hpds95 = np.array(get_HPD(threshold=.95))
hpds50 = np.array(get_CI(threshold=.50))
#hpds10 = get_CI(threshold=.10)
L_tbl_mean=np.around(np.mean(L_tbl,axis=0),no_decimals)
M_tbl_mean=np.around(np.mean(M_tbl,axis=0),no_decimals)
if len(r_ind)>0: R_tbl_mean=np.around(np.mean(R_tbl,axis=0),no_decimals)
else:
R_tbl_mean= L_tbl_mean-M_tbl_mean
mean_rates=np.array([L_tbl_mean,L_tbl_mean,M_tbl_mean,M_tbl_mean,R_tbl_mean,R_tbl_mean] )
nonzero_rate = L_tbl_mean+ M_tbl_mean
NA_ind = (nonzero_rate==0).nonzero()[0]
hpds95[:,NA_ind] = np.nan
#hpds50[:,NA_ind] = np.nan
print(mean_rates)
mean_rates[:,NA_ind] = np.nan
print("HPD", hpds95)
#print(np.shape(np.array(hpds50) ), np.shape(L_tbl_mean))
########################################################
###### PLOT RTTs ######
########################################################
print("\ngenerating R file...", end=' ')
out="%s/%s_RTT.r" % (wd,name_file)
newfile = open(out, "w")
Rfile="# %s files combined:\n" % (len(files))
for f in files: Rfile+="# \t%s\n" % (f)
Rfile+= """\n# 95% HPDs calculated using code from Biopy (https://www.cs.auckland.ac.nz/~yhel002/biopy/)"""
if plot_type==1: n_plots=4
else: n_plots=3
if platform.system() == "Windows" or platform.system() == "Microsoft":
wd_forward = os.path.abspath(wd).replace('\\', '/')
Rfile+= "\n\npdf(file='%s/%s_RTT.pdf',width=10.8, height=8.4)\npar(mfrow=c(2,2))" % (wd_forward,name_file)
else:
Rfile+= "\n\npdf(file='%s/%s_RTT.pdf',width=10.8, height=8.4)\npar(mfrow=c(2,2))" % (wd,name_file)
Rfile+= "\nlibrary(scales)"
if plot_type==2: Rfile+= """\nplot_RTT <- function (age,hpd_M,hpd_m,mean_m,color){
N=100
beta=(1:(N-1))/N
alpha_shape=0.25
cat=1-(beta^(1./alpha_shape))
for (i in 1:(N-1)){
trans= 1/N + 2/N
polygon(c(age, rev(age)), c(hpd_M-((hpd_M-mean_m)*cat[i]), rev(hpd_m+((mean_m-hpd_m)*cat[i]))), col = alpha(color,trans), border = NA)
}
lines(rev(age), rev(mean_m), col = color, lwd=3)\n}
"""
def RTT_plot_in_R(args, alpha):
count=0
data=""
name=['95','_mean'] # ,'50'
for hpd_list in args:
sys.stdout.write(".")
sys.stdout.flush()
[L_hpd_m,L_hpd_M,M_hpd_m,M_hpd_M,R_hpd_m,R_hpd_M]=hpd_list
if name[count]=="_mean":
data += print_R_vec('\nL_mean',L_hpd_m)
data += print_R_vec('\nM_mean',M_hpd_m)
data += print_R_vec('\nR_mean',R_hpd_m)
else:
data += print_R_vec('\nL_hpd_m%s',L_hpd_m) % name[count]
data += print_R_vec('\nL_hpd_M%s',L_hpd_M) % name[count]
data += print_R_vec('\nM_hpd_m%s',M_hpd_m) % name[count]
data += print_R_vec('\nM_hpd_M%s',M_hpd_M) % name[count]
data += print_R_vec('\nR_hpd_m%s',R_hpd_m) % name[count]
data += print_R_vec('\nR_hpd_M%s',R_hpd_M) % name[count]
if count==0:
max_x_axis,min_x_axis = -len(L_hpd_m), 0 # root to the present
max_x_axis,min_x_axis = -(len(L_hpd_m)+.05*len(L_hpd_m)), -(len(L_hpd_m)-len(L_hpd_m[np.isfinite(L_hpd_m)]))+.05*len(L_hpd_m)
plot_L = "\ntrans=%s\nage=(0:(%s-1))* -1" % (alpha, len(L_hpd_m))
plot_L += "\nplot(age,age,type = 'n', ylim = c(%s, %s), xlim = c(%s,%s), ylab = 'Speciation rate', xlab = 'Ma',main='%s' )" \
% (0,1.1*np.nanmax(L_hpd_M),max_x_axis,min_x_axis,plot_title)
plot_M = "\nplot(age,age,type = 'n', ylim = c(%s, %s), xlim = c(%s,%s), ylab = 'Extinction rate', xlab = 'Ma' )" \
% (0,1.1*np.nanmax(M_hpd_M),max_x_axis,min_x_axis)
plot_R = "\nplot(age,age,type = 'n', ylim = c(%s, %s), xlim = c(%s,%s), ylab = 'Net diversification rate', xlab = 'Ma' )" \
% (-abs(1.1*np.nanmin(R_hpd_m)),1.1*np.nanmax(R_hpd_M),max_x_axis,min_x_axis)
plot_R += """\nabline(h=0,lty=2,col="darkred")""" # \nabline(v=-c(65,200,251,367,445),lty=2,col="darkred")
if name[count]=="_mean":
plot_L += """\nlines(rev(age), rev(L_mean), col = "#4c4cec", lwd=3)"""
plot_M += """\nlines(rev(age), rev(M_mean), col = "#e34a33", lwd=3)"""
plot_R += """\nlines(rev(age), rev(R_mean), col = "#504A4B", lwd=3)"""
else:
if plot_type==1:
plot_L += """\npolygon(c(age, rev(age)), c(L_hpd_M%s, rev(L_hpd_m%s)), col = alpha("#4c4cec",trans), border = NA)""" % (name[count],name[count])
plot_M += """\npolygon(c(age, rev(age)), c(M_hpd_M%s, rev(M_hpd_m%s)), col = alpha("#e34a33",trans), border = NA)""" % (name[count],name[count])
plot_R += """\npolygon(c(age, rev(age)), c(R_hpd_M%s, rev(R_hpd_m%s)), col = alpha("#504A4B",trans), border = NA)""" % (name[count],name[count])
elif plot_type==2:
plot_L += """\nplot_RTT(age,L_hpd_M95,L_hpd_m95,L_mean,"#4c4cec")"""
plot_M += """\nplot_RTT(age,M_hpd_M95,M_hpd_m95,M_mean,"#e34a33")"""
plot_R += """\nplot_RTT(age,R_hpd_M95,R_hpd_m95,R_mean,"#504A4B")"""
count+=1
R_code=data+plot_L+plot_M+plot_R
if plot_type==1:
R_code += "\nplot(age,rev(1/M_mean),type = 'n', xlim = c(%s,%s), ylab = 'Longevity (Myr)', xlab = 'Ma' )" % (max_x_axis,min_x_axis)
R_code += """\nlines(rev(age), rev(1/M_mean), col = "#504A4B", lwd=3)"""
#R_code += """\npolygon(c(age, rev(age)), c((1/M_hpd_m95), rev(1/M_hpd_M95)), col = alpha("#504A4B",trans), border = NA)"""
return R_code
Rfile += RTT_plot_in_R([hpds95,mean_rates],.5) # ,hpds50
Rfile += "\nn <- dev.off()"
newfile.writelines(Rfile)
newfile.close()
print("\nAn R script with the source for the RTT plot was saved as: %s_RTT.r\n(in %s)" % (name_file, wd))
if platform.system() == "Windows" or platform.system() == "Microsoft":
cmd="cd %s & Rscript %s_RTT.r" % (wd,name_file)
else:
cmd="cd %s; Rscript %s/%s_RTT.r" % (wd,wd,name_file)
os.system(cmd)
print("done\n")
def plot_ltt(tste_file,plot_type=1,rescale= 1,step_size=1.): # change rescale to change bin size
# plot_type=1 : ltt + min/max range
# plot_type=2 : log10 ltt + min/max range
#step_size=int(step_size)
# read data
print("Processing data...")
tbl = np.loadtxt(tste_file,skiprows=1)
j_max=int((np.shape(tbl)[1]-1)/2)
j_range=np.arange(j_max)
ts = tbl[:,2+2*j_range]*rescale
te = tbl[:,3+2*j_range]*rescale
time_vec = np.sort(np.linspace(np.min(te),np.max(ts),int((np.max(ts)-np.min(te))/float(step_size)) ))
# create out file
wd = "%s" % os.path.dirname(tste_file)
out_file_name = os.path.splitext(os.path.basename(tste_file))[0]
out_file="%s/%s" % (wd,out_file_name+"_ltt.txt")
ltt_file = open(out_file , "w", newline="")
ltt_log=csv.writer(ltt_file, delimiter='\t')
# calc ltt
print(time_vec)
dtraj = []
for rep in j_range:
sys.stdout.write(".")
sys.stdout.flush()
dtraj.append(get_DT(time_vec,ts[:,rep],te[:,rep])[::-1])
dtraj = np.array(dtraj)
div_mean = np.mean(dtraj,axis=0)
div_m = np.min(dtraj,axis=0)
div_M = np.max(dtraj,axis=0)
Ymin,Ymax,yaxis = 0,np.max(div_M)+1,""
if np.min(div_m)>5: Ymin = np.min(div_m)-1
if plot_type==2:
div_mean = np.log10(div_mean)
div_m = np.log10(div_m )
div_M = np.log10(div_M )
Ymin,Ymax,yaxis = np.min(div_m),np.max(div_M), " (Log10)"
# write to file
if plot_type==1 or plot_type==2:
ltt_log.writerow(["time","diversity","m_div","M_div"])
for i in range(len(time_vec)):
ltt_log.writerow([time_vec[i]/rescale,div_mean[i],div_m[i],div_M[i]])
ltt_file.close()
plot2 = """polygon(c(time, rev(time)), c(tbl$M_div, rev(tbl$m_div)), col = alpha("#504A4B",0.5), border = NA)"""
# write multiple LTTs to file
if plot_type==3:
header = ["time","diversity"]+["rep%s" % (i) for i in j_range]
ltt_log.writerow(header)
plot2=""
for i in range(len(time_vec)):
d = dtraj[:,i]
ltt_log.writerow([time_vec[i]/rescale,div_mean[i]]+list(d))
plot2 += """\nlines(time,tbl$rep%s, type="l",lwd = 1,col = alpha("#504A4B",0.5))""" % (i)
ltt_file.close()
###### R SCRIPT
R_file_name="%s/%s" % (wd,out_file_name+"_ltt.R")
R_file=open(R_file_name, "w")
if platform.system() == "Windows" or platform.system() == "Microsoft":
tmp_wd = os.path.abspath(wd).replace('\\', '/')
else: tmp_wd = wd
R_script = """
setwd("%s")
tbl = read.table(file = "%s_ltt.txt",header = T)
pdf(file='%s_ltt.pdf',width=12, height=9)
time = -tbl$time
library(scales)
plot(time,tbl$diversity, type="n",ylab= "Number of lineages%s", xlab="Time (Ma)", main="Range-through diversity through time", ylim=c(%s,%s),xlim=c(min(time),0))
%s
lines(time,tbl$diversity, type="l",lwd = 2)
n<-dev.off()
""" % (tmp_wd, out_file_name,out_file_name, yaxis, Ymin,Ymax,plot2)
R_file.writelines(R_script)
R_file.close()
print("\nAn R script with the source for the stat plot was saved as: \n%s" % (R_file_name))
if platform.system() == "Windows" or platform.system() == "Microsoft":
cmd="cd %s & Rscript %s" % (wd,out_file_name+"_ltt.R")
else:
cmd="cd %s; Rscript %s" % (wd,out_file_name+"_ltt.R")
os.system(cmd)
sys.exit("done\n")
########################## PLOT TS/TE STAT ##############################
def plot_tste_stats(tste_file, EXT_RATE, step_size,no_sim_ex_time,burnin,rescale,ltt_only=1):
step_size=int(step_size)
# read data
print("Processing data...")
tbl = np.loadtxt(tste_file,skiprows=1)
j_max=(np.shape(tbl)[1]-1)/2
j=np.arange(j_max)
ts = tbl[:,2+2*j]*rescale
te = tbl[:,3+2*j]*rescale
root = int(np.max(ts)+1)
if EXT_RATE==0:
EXT_RATE = len(te[te>0])/np.sum(ts-te) # estimator for overall extinction rate
print("estimated extinction rate:", EXT_RATE)
wd = "%s" % os.path.dirname(tste_file)
# create out file
out_file_name = os.path.splitext(os.path.basename(tste_file))[0]
out_file="%s/%s" % (wd,out_file_name+"_stats.txt")
out_file=open(out_file, "w", newline="")
out_file.writelines("time\tdiversity\tm_div\tM_div\tmedian_age\tm_age\tM_age\tturnover\tm_turnover\tM_turnover\tlife_exp\tm_life_exp\tM_life_exp\t")
no_sim_ex_time = int(no_sim_ex_time)
def draw_extinction_time(te,EXT_RATE):
te_mod = np.zeros(np.shape(te))
ind_extant = (te[:,0]==0).nonzero()[0]
te_mod[ind_extant,:] = -np.random.exponential(1/EXT_RATE,(len(ind_extant),len(te[0]))) # sim future extinction
te_mod += te
return te_mod
def calc_median(arg):
if len(arg)>1: return np.median(arg)
else: return np.nan
extant_at_time_t_previous = [0]
for i in range(0,root+1,step_size):
time_t = root-i
up = time_t+step_size
lo = time_t
extant_at_time_t = [np.intersect1d((ts[:,rep] >= lo).nonzero()[0], (te[:,rep] <= up).nonzero()[0]) for rep in j]
extinct_in_time_t =[np.intersect1d((te[:,rep] >= lo).nonzero()[0], (te[:,rep] <= up).nonzero()[0]) for rep in j]
diversity = [len(extant_at_time_t[rep]) for rep in j]
try:
#turnover = [1-len(np.intersect1d(extant_at_time_t_previous[rep],extant_at_time_t[rep]))/float(len(extant_at_time_t[rep])) for rep in j]
turnover = [(len(extant_at_time_t[rep])-len(np.intersect1d(extant_at_time_t_previous[rep],extant_at_time_t[rep])))/float(len(extant_at_time_t[rep])) for rep in j]
except:
turnover = [np.nan for rep in j]
if min(diversity)<=1:
age_current_taxa = [np.nan for rep in j]
else:
ext_age = [calc_median(ts[extinct_in_time_t[rep],rep]-te[extinct_in_time_t[rep],rep]) for rep in j]
age_current_taxa = [calc_median(ts[extant_at_time_t[rep],rep]-time_t) for rep in j]
# EMPIRICAL/PREDICTED LIFE EXPECTANCY
life_exp=list()
try:
ex_rate = [float(EXT_RATE)]
r_ind = np.repeat(0,no_sim_ex_time)
except(ValueError):
t=np.loadtxt(EXT_RATE, skiprows=np.maximum(1,int(burnin)))
head = next(open(EXT_RATE)).split()
m_ind= [head.index(s) for s in head if "m_0" in s]
ex_rate= [mean(t[:,m_ind])]
r_ind = np.random.randint(0,len(ex_rate),no_sim_ex_time)
if min(diversity)<=1:
life_exp.append([np.nan for rep in j])
else:
for sim in range(no_sim_ex_time):
#print ex_rate[r_ind[sim]]
te_mod = draw_extinction_time(te,ex_rate[r_ind[sim]])
te_t = [te_mod[extant_at_time_t[rep],:] for rep in j]
life_exp.append([median(time_t-te_t[rep]) for rep in j])
life_exp= np.array(life_exp)
STR= "\n%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s" \
% (time_t, np.median(diversity),np.min(diversity),np.max(diversity),
np.median(age_current_taxa),np.min(age_current_taxa),np.max(age_current_taxa),
np.median(turnover),np.min(turnover),np.max(turnover),
np.median(life_exp),np.min(life_exp),np.max(life_exp))
extant_at_time_t_previous = extant_at_time_t
STR = STR.replace("nan","NA")
sys.stdout.write(".")
sys.stdout.flush()
out_file.writelines(STR)
out_file.close()
###### R SCRIPT
R_file_name="%s/%s" % (wd,out_file_name+"_stats.R")
R_file=open(R_file_name, "w")
if platform.system() == "Windows" or platform.system() == "Microsoft":
tmp_wd = os.path.abspath(wd).replace('\\', '/')
else: tmp_wd = wd
R_script = """
setwd("%s")
tbl = read.table(file = "%s_stats.txt",header = T)
pdf(file='%s_stats.pdf',width=12, height=9)
time = -tbl$time
par(mfrow=c(2,2))
library(scales)
plot(time,tbl$diversity, type="l",lwd = 2, ylab= "Number of lineages", xlab="Time (Ma)", main="Diversity through time", ylim=c(0,max(tbl$M_div,na.rm =T)+1),xlim=c(min(time),0))
polygon(c(time, rev(time)), c(tbl$M_div, rev(tbl$m_div)), col = alpha("#504A4B",0.5), border = NA)
plot(time,tbl$median_age, type="l",lwd = 2, ylab = "Median age", xlab="Time (Ma)", main= "Taxon age", ylim=c(0,max(tbl$M_age,na.rm =T)+1),xlim=c(min(time),0))
polygon(c(time, rev(time)), c(tbl$M_age, rev(tbl$m_age)), col = alpha("#504A4B",0.5), border = NA)
plot(time,tbl$turnover, type="l",lwd = 2, ylab = "Fraction of new taxa", xlab="Time (Ma)", main= "Turnover", ylim=c(0,max(tbl$M_turnover,na.rm =T)+.1),xlim=c(min(time),0))
polygon(c(time, rev(time)), c(tbl$M_turnover, rev(tbl$m_turnover)), col = alpha("#504A4B",0.5), border = NA)
plot(time,tbl$life_exp, type="l",lwd = 2, ylab = "Median longevity", xlab="Time (Ma)", main= "Taxon (estimated) longevity", ylim=c(0,max(tbl$M_life_exp,na.rm =T)+1),xlim=c(min(time),0))
polygon(c(time, rev(time)), c(tbl$M_life_exp, rev(tbl$m_life_exp)), col = alpha("#504A4B",0.5), border = NA)
n<-dev.off()
""" % (tmp_wd, out_file_name,out_file_name)
R_file.writelines(R_script)
R_file.close()
print("\nAn R script with the source for the stat plot was saved as: \n%s" % (R_file_name))
if platform.system() == "Windows" or platform.system() == "Microsoft":
cmd="cd %s & Rscript %s" % (wd,out_file_name+"_stats.R")
else:
cmd="cd %s; Rscript %s" % (wd,out_file_name+"_stats.R")
os.system(cmd)
print("done\n")
########################## COMBINE LOG FILES ##############################
def read_rates_log(f, burnin):
f_temp = open(f, 'r')
x_temp = [line for line in f_temp.readlines()]
num_it = len(x_temp)
b = check_burnin(burnin, num_it)
f_temp = open(f, 'r')
x_temp = [line for line in f_temp.readlines()]
x_temp = x_temp[b:]
x_temp = np.array(x_temp)
return x_temp
def comb_rj_rates(infile, files, burnin, tag, resample, rate_type):
j=0
for f in files:
x_temp = read_rates_log(f, burnin)
if 2>1: #try:
if resample>0:
r_ind = np.sort(np.random.randint(0,len(x_temp),resample))
x_temp = x_temp[r_ind]
if j==0:
comb = x_temp
else:
comb = np.concatenate((comb,x_temp))
j+=1
#except:
# print "Could not process file:",f
outfile = "%s/combined_%s%s_%s.log" % (infile,len(files),tag,rate_type)
with open(outfile, 'w') as f:
for i in comb: f.write(i)
def comb_mcmc_files(infile, files,burnin,tag,resample,col_tag,file_type="", keep_q=False):
j=0
if file_type=="mcmc" and keep_q:
n_q_shifts = np.zeros(len(files))
for k in range(len(files)):
f = files[k]
if platform.system() == "Windows" or platform.system() == "Microsoft":
f = f.replace("\\","/")
head = np.array(next(open(f)).split())
if len(col_tag) == 0:
n_q_shifts[k] = len([i for i in range(len(head)) if head[i].startswith('q_')])
max_q_shifts = int(np.max(n_q_shifts))
for f in files:
if platform.system() == "Windows" or platform.system() == "Microsoft":
f = f.replace("\\","/")
if 2>1: #try:
file_name = os.path.splitext(os.path.basename(f))[0]
print(file_name, end=' ')
num_it = np.loadtxt(f, skiprows=1).shape[0]
b = check_burnin(burnin, num_it)
t_file=np.loadtxt(f, skiprows=b + 1)
shape_f=shape(t_file)
print(shape_f)
#t_file = t[burnin:shape_f[0],:]#).astype(str)
# only sample from cold chain
head = np.array(next(open(f)).split()) # should be faster\
if j == 0:
tbl_header = '\t'.join(head)
if "temperature" in head or "beta" in head:
try:
temp_index = np.where(head=="temperature")[0][0]
except(IndexError):
temp_index = np.where(head=="beta")[0][0]
temp_values = t_file[:,temp_index]
t_file = t_file[temp_values==1,:]
print("removed heated chains:",np.shape(t_file))
if len(col_tag) == 0 and file_type == "mcmc":
q_ind = np.array([i for i in range(len(head)) if head[i].startswith('q_')])
if len(q_ind)>0 and not keep_q:
# exclude preservation rates under TPP model (they can mismatch)
mean_q = np.mean(t_file[:,q_ind],axis=1)
t_file = np.delete(t_file,q_ind,axis=1)
t_file = np.insert(t_file,q_ind[0],mean_q,axis=1)
elif len(q_ind) < max_q_shifts:
missing_q = np.full((t_file.shape[0], max_q_shifts - len(q_ind)), np.nan)
idx = np.min(q_ind)
t_file = np.c_[t_file[:, :idx], missing_q, t_file[:, idx:]]
shape_f=shape(t_file)
if resample>0:
r_ind= sort(np.random.randint(0,shape_f[0],resample))
t_file = t_file[r_ind,:]
#except: print "ERROR in",f
if len(col_tag) == 0:
if j==0:
head_temp = np.array(next(open(f)).split())
if file_type == "mcmc":
q_not_ind = np.array([i for i in range(len(head)) if not head[i].startswith('q_')])
q_ind = np.array([i for i in range(len(head)) if head[i].startswith('q_')])
if len(q_ind)>0 and not keep_q:
head_temp = head_temp[q_not_ind]
head_temp = np.insert(head_temp,q_ind[0],"mean_q")
else:
head_temp = head_temp[q_not_ind]
q_names = np.array(["q_" + str(i) for i in range(max_q_shifts)])
head_temp = np.insert(head_temp, q_ind[0], q_names)
tbl_header=""
for i in head_temp: tbl_header = tbl_header + i + "\t"
tbl_header+="\n"
comb = t_file
else:
comb = np.concatenate((comb,t_file),axis=0)
else:
head_temp = next(open(f)).split() # should be faster
sp_ind_list=[]
for TAG in col_tag:
if TAG in head_temp:
sp_ind_list+=[head_temp.index(s) for s in head_temp if s == TAG]
try:
col_tag_ind = np.array([int(tag_i) for tag_i in col_tag])
sp_ind= np.array(col_tag_ind)
except:
sp_ind= np.array(sp_ind_list)
#print "COLTAG",col_tag, sp_ind, head_temp
#sys.exit()
#print "INDEXES",sp_ind
if j==0:
head_temp= np.array(head_temp)
head_t= ["%s\t" % (i) for i in head_temp[sp_ind]]
tbl_header="it\t"
for i in head_t: tbl_header+=i
tbl_header+="\n"
print("found", len(head_t), "columns")
comb = t_file[:,sp_ind]
else:
comb = np.concatenate((comb,t_file[:,sp_ind]),axis=0)
j+=1
#print shape(comb)
if len(col_tag) == 0:
sampling_freq= comb[1,0]-comb[0,0]
comb[:,0] = (np.arange(0,len(comb))+1)*sampling_freq
fmt_list=['%i']
for i in range(1,np.shape(comb)[1]): fmt_list.append('%4f')
else:
fmt_list=['%i']
for i in range(1,np.shape(comb)[1]+1): fmt_list.append('%4f')
comb = np.concatenate((np.zeros((len(comb[:,0]),1)),comb),axis=1)
comb[:,0] = (np.arange(0,len(comb)))
print(np.shape(comb), len(fmt_list))
outfile = "%s/combined_%s%s_%s.log" % (infile,len(files),tag,file_type)
with open(outfile, 'w') as f:
f.write(tbl_header)
if platform.system() == "Windows" or platform.system() == "Microsoft":
np.savetxt(f, comb, delimiter="\t",fmt=fmt_list,newline="\r") #)
else:
np.savetxt(f, comb, delimiter="\t",fmt=fmt_list,newline="\n") #)
def comb_log_files_smart(path_to_files,burnin=0,tag="",resample=0,col_tag=[], keep_q=False):
infile=path_to_files
sys.path.append(infile)