-
Notifications
You must be signed in to change notification settings - Fork 34
/
PyRateDES.py
4209 lines (3913 loc) · 198 KB
/
PyRateDES.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 04/04/2018 => pyrate.help@gmail.com
import os, csv, platform
# Prevent blas from using all CPU cores
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"
import argparse, sys, glob, time
import math
import fnmatch
import numpy as np
import scipy
import scipy.linalg
linalg = scipy.linalg
import scipy.stats
import random as rand
import nlopt
from scipy.integrate import odeint
from scipy.optimize import minimize
import multiprocessing, threading
import multiprocessing.pool
#use_seq_lik = False
#try:
# import multiprocessing, thread
# import multiprocessing.pool
# use_seq_lik=False
# if platform.system() == "Windows" or platform.system() == "Microsoft": use_seq_lik=True
#except(ImportError):
# print("\nWarning: library multiprocessing not found.\nPyRateDES will use (slower) sequential likelihood calculation. \n")
# use_seq_lik=True
self_path=os.getcwd()
# DES libraries
self_path= os.path.dirname(sys.argv[0])
from importlib.machinery import SourceFileLoader
try:
self_path= os.path.dirname(sys.argv[0])
des_model_lib = SourceFileLoader("des_model_lib", "%s/pyrate_lib/des_model_lib.py" % (self_path)).load_module()
mcmc_lib = SourceFileLoader("mcmc_lib", "%s/pyrate_lib/des_mcmc_lib.py" % (self_path)).load_module()
lib_DD_likelihood = SourceFileLoader("lib_DD_likelihood", "%s/pyrate_lib/lib_DD_likelihood.py" % (self_path)).load_module()
lib_utilities = SourceFileLoader("lib_utilities", "%s/pyrate_lib/lib_utilities.py" % (self_path)).load_module()
except:
self_path=os.getcwd()
des_model_lib = SourceFileLoader("des_model_lib", "%s/pyrate_lib/des_model_lib.py" % (self_path)).load_module()
mcmc_lib = SourceFileLoader("mcmc_lib", "%s/pyrate_lib/des_mcmc_lib.py" % (self_path)).load_module()
lib_DD_likelihood = SourceFileLoader("lib_DD_likelihood", "%s/pyrate_lib/lib_DD_likelihood.py" % (self_path)).load_module()
lib_utilities = SourceFileLoader("lib_utilities", "%s/pyrate_lib/lib_utilities.py" % (self_path)).load_module()
from des_model_lib import *
from mcmc_lib import *
from lib_DD_likelihood import *
from lib_utilities import *
np.set_printoptions(suppress=True) # prints floats, no scientific notation
np.set_printoptions(precision=3) # rounds all array elements to 3rd digit
small_number= 1e-5
def rescale_and_center_time_var(time_var, rescale_factor):
unscaled_min = np.min(time_var)
unscaled_max = np.max(time_var)
unscaled_mean = np.mean(time_var)
if rescale_factor > 0.0:
time_var = time_var * rescale_factor
else:
denom = np.max(time_var) - np.min(time_var)
if denom == 0.0:
denom = 1.0
time_var = time_var/denom
time_var = time_var - np.min(time_var) # curve rescaled between 0 and 1
mean_before_centering = np.mean(time_var)
time_var = time_var - mean_before_centering
return time_var, mean_before_centering, unscaled_min, unscaled_max, unscaled_mean
def read_timevar(args_var, time_series, rescale_factor):
all_files_area_1 = "%s/*" % (args_var[0])
all_files_area_2 = "%s/*" % (args_var[-1])
list_files = list()
list_files.append(list(sort(glob.glob(all_files_area_1))))
list_files.append(list(sort(glob.glob(all_files_area_2))))
num_files = len(list_files[0])
time_var = np.ones((2, len(time_series) - 1, num_files))
mean_var_before_centering = np.zeros((2, num_files))
time_var_unscmin = np.ones((2, num_files))
time_var_unscmax = np.ones((2, num_files))
time_var_unscmean = np.ones((2, num_files))
for j in range(2):
timevar_names = list() # names of time series should be the same
for i in range(num_files):
time_var_temp = get_binned_continuous_variable(time_series, list_files[j][i])
time_var[j, :, i], mean_var_before_centering[j, i], time_var_unscmin[j, i], time_var_unscmax[j, i], time_var_unscmean[j, i] = rescale_and_center_time_var(time_var_temp, rescale_factor)
timevar_names.append(os.path.splitext(os.path.basename(list_files[j][i]))[0])
covar_mean = np.mean(time_var, axis=1)
return time_var, mean_var_before_centering, time_var_unscmin, time_var_unscmax, time_var_unscmean, covar_mean, timevar_names
def get_idx_symCov(symCov, num_var):
sym_cov_idx = list()
counter = 0
for i in range(2 * num_var):
if ((i + 1)/2 in symCov) is False:
sym_cov_idx.append(counter)
counter += 1
else:
counter -= 1
sym_cov_idx.append(counter)
counter += 1
return np.array(sym_cov_idx)
def read_trait(path_var, taxa_input):
var = np.loadtxt(path_var, dtype=str, delimiter='\t', skiprows=1)
# Filter and sort for the species in the input file - there should be no missing trait data
idx = []
for ta in taxa_input:
pos = np.where(var[:, 0] == ta)[0]
if len(pos) > 0:
idx.append(int(pos))
idx = np.array(idx).reshape(-1)
var = var[idx, :]
var_shape = var.shape
var = np.reshape(var[:,1:], (var_shape[0], var_shape[1] - 1))
var = var.astype(float)
return var
def logtransf_traits(var, transfTrait):
var_shape = var.shape
var2 = np.zeros(var_shape)
transfTrait = np.array([transfTrait]).reshape(-1)
if transfTrait.shape[0] < var_shape[1]:
transfTrait = np.repeat(transfTrait[0], var_shape[1])
var2[:, transfTrait == 0] = var[:, transfTrait == 0]
var2[:, transfTrait == 1] = np.log(var[:, transfTrait == 1])
var2 = var2 - np.mean(var2, axis = 0)
return var2, transfTrait
def div_dt(div, t, d12, d21, mu1, mu2, k_d1, k_d2, k_e1, k_e2):
div1 = div[0]
div2 = div[1]
div3 = div[2]
lim_d1 = np.maximum(0.0, 1.0 - (div1 + div3)/k_d1) # Limit dispersal into area 1
lim_d2 = np.maximum(0.0, 1.0 - (div2 + div3)/k_d2) # Limit dispersal into area 2
lim_e1 = np.maximum(1e-05, 1.0 - (div1 + div3)/k_e1) # Increases extinction in area 1
lim_e2 = np.maximum(1e-05, 1.0 - (div2 + div3)/k_e2) # Increases extinction in area 2
dS = np.zeros(5)
dS[3] = d21 * div2 * lim_d1 # Gain area 1
dS[4] = d12 * div1 * lim_d2 # Gain area 2
mu1 = mu1/lim_e1
mu2 = mu2/lim_e2
dS[0] = -mu1 * div1 + mu2 * div3 - dS[4]
dS[1] = -mu2 * div2 + mu1 * div3 - dS[3]
dS[2] = -(mu1 + mu2) * div3 + dS[3] + dS[4]
return dS
def div_traitcat_dt(div, t, d12, d21, mu1, mu2, k_d1, k_d2, k_e1, k_e2, covar_mu1, covar_mu2,
trait_parD, traitD, trait_parE, traitE,
cat_parD, catD, cat_parE, catE,
do_DdE, argstraitD, argstraitE, argscatD, argscatE,
pres1_idx, pres2_idx, pres3_idx, gainA_idx, gainB_idx, nTaxa):
div1 = div[pres1_idx]
div2 = div[pres2_idx]
div3 = div[pres3_idx]
div13 = np.sum(div1) + np.sum(div3)
div23 = np.sum(div1) + np.sum(div3)
lim_d1 = np.maximum(0.0, 1.0 - div13/k_d1) # Limit dispersal into area 1
lim_d2 = np.maximum(0.0, 1.0 - div23/k_d2) # Limit dispersal into area 2
dS = np.zeros(5 * nTaxa)
if argstraitD: # Cont trait dis
cont_modi = np.exp(np.sum(trait_parD * traitD, axis=1))
d12 = d12 * cont_modi
d21 = d21 * cont_modi
if argscatD: # Cat trait dis
m = np.sum(np.exp(cat_parD[catD]), axis=1)
d12 = d12 * m
d21 = d21 * m
dS[gainA_idx] = d21 * div[pres2_idx] * lim_d1 # Gain area 1
dS[gainB_idx] = d12 * div[pres1_idx] * lim_d2 # Gain area 2
if argstraitE: # Cont trait
cont_modi = np.exp(np.sum(trait_parE * traitE, axis=1))
mu1 = mu1 * cont_modi
mu2 = mu2 * cont_modi
if argscatE: # Cat trait
m = np.sum(np.exp(cat_parE[catE]), axis=1)
mu1 = mu1 * m
mu2 = mu2 * m
if do_DdE: # Dispersal induced extinction
mu1 = mu1 + covar_mu1 * dS[gainA_idx] / (div13 + 1.)
mu2 = mu2 + covar_mu2 * dS[gainB_idx] / (div23 + 1.)
lim_e1 = np.maximum(1e-05, 1.0 - div13/k_e1) # Increases extinction in area 1
lim_e2 = np.maximum(1e-05, 1.0 - div23/k_e2) # Increases extinction in area 2
mu1 = mu1 / lim_e1
mu2 = mu2 / lim_e2
dS[pres1_idx] = -mu1 * div[pres1_idx] + mu2 * div[pres3_idx] - dS[gainB_idx]
dS[pres2_idx] = -mu2 * div[pres2_idx] + mu1 * div[pres3_idx] - dS[gainA_idx]
dS[pres3_idx] = -(mu1 + mu2) * div[pres3_idx] + dS[gainA_idx] + dS[gainB_idx]
return dS
def dis_dep_ext_dt(div, t, d12, d21, mu1, mu2, k_d1, k_d2, covar_mu1, covar_mu2):
div1 = div[0]
div2 = div[1]
div3 = div[2]
div13 = div[0] + div[2]
div23 = div[1] + div[2]
lim_d1 = np.maximum(0.0, 1.0 - (div13)/k_d1) # Limit dispersal into area 1
lim_d2 = np.maximum(0.0, 1.0 - (div23)/k_d2) # Limit dispersal into area 2
dS = np.zeros(5)
dS[3] = d21 * div2 * lim_d1 # Gain area 1
dS[4] = d12 * div1 * lim_d2 # Gain area 2
mu1 = mu1 + covar_mu1 * dS[3] / (div13 + 1.)
mu2 = mu2 + covar_mu2 * dS[4] / (div23 + 1.)
dS[0] = -mu1 * div1 + mu2 * div3 - dS[4]
dS[1] = -mu2 * div2 + mu1 * div3 - dS[3]
dS[2] = -(mu1 + mu2) * div3 + dS[3] + dS[4]
return dS
#div_int = odeint(div_dep_ext_dt, np.array([1., 1., 0., 0., 0.]), [0, 1], args = (0.2, 0.2, 0.1, 0.1, np.inf, np.inf, 0.2, 0.2))
#div_int
def rates_at_t(i, transf_d, transf_e, dis_rate_vec, ext_rate_vec,
covar_parD, idx_covar_parD1, idx_covar_parD2,
covar_parE, idx_covar_parE1, idx_covar_parE2,
covar_par, offset_dis_div1, offset_dis_div2):
k_d1 = np.inf
k_d2 = np.inf
if transf_d == 0: # Skyline or constant dispersal
idx = i - 1
if dis_rate_vec.shape[0] == 1:
idx = 0
d12 = dis_rate_vec[idx, 0]
d21 = dis_rate_vec[idx, 1]
elif transf_d == 1: # Environmental-dependent dispersal
# dispersal from area 1 to area 2 depends on environment in area 2 (i.e. time_varD[1, :, :])
d12 = dis_rate_vec[0, 0] * np.exp(np.sum(covar_parD[idx_covar_parD1] * time_varD[1, i - 1, :]))
d21 = dis_rate_vec[0, 1] * np.exp(np.sum(covar_parD[idx_covar_parD2] * time_varD[0, i - 1, :]))
elif transf_d == 4: # Linear diversity-dependence
k_d1 = covar_par[0]
k_d2 = covar_par[1]
d12 = dis_rate_vec[0, 0] / (1. - offset_dis_div2 / k_d1)
d21 = dis_rate_vec[0, 1] / (1. - offset_dis_div1 / k_d2)
elif transf_d == 5: # Combination of environment and diversity dependent dispersal
env_d12 = dis_rate_vec[0, 0] * np.exp(np.sum(covar_parD[idx_covar_parD1] * time_varD[1, i - 1, :]))
env_d21 = dis_rate_vec[0, 1] * np.exp(np.sum(covar_parD[idx_covar_parD1] * time_varD[0, i - 1, :]))
k_d1 = covar_par[0]
k_d2 = covar_par[1]
d12 = env_d12 / (1. - offset_dis_div2 / k_d1)
d21 = env_d21 / (1. - offset_dis_div1 / k_d2)
elif transf_d == 8: # Skyline + environmental-dependent dispersal
idx = i - 1
d12 = dis_rate_vec[idx, 0] * np.exp(np.sum(covar_parD[idx_covar_parD1] * time_varD[1, i - 1, :]))
d21 = dis_rate_vec[idx, 1] * np.exp(np.sum(covar_parD[idx_covar_parD2] * time_varD[0, i - 1, :]))
k_e1 = np.inf
k_e2 = np.inf
covar_mu1 = None
covar_mu2 = None
if transf_e == 0: # Skyline or constant extinction
idx = i - 1
if ext_rate_vec.shape[0] == 1:
idx = 0
e1 = ext_rate_vec[idx, 0]
e2 = ext_rate_vec[idx, 1]
elif transf_e == 1: # Environmental-dependent extinction
e1 = ext_rate_vec[0, 0] * np.exp(np.sum(covar_parE[idx_covar_parE1] * time_varE[0, i - 1, :]))
e2 = ext_rate_vec[0, 1] * np.exp(np.sum(covar_parE[idx_covar_parE2] * time_varE[1, i - 1, :]))
elif transf_e == 3: # Linear dependence on dispersal fraction
e1 = ext_rate_vec[0, 0]
e2 = ext_rate_vec[0, 1]
covar_mu1 = covar_par[2]
covar_mu2 = covar_par[3]
if transf_e == 4: # Linear diversity dependence
k_e1 = covar_par[2]
k_e2 = covar_par[3]
e1 = ext_rate_vec[0, 0] * (1. - offset_ext_div1 / k_e1)
e2 = ext_rate_vec[0, 1] * (1. - offset_ext_div2 / k_e2)
if not np.isfinite(e1):
e1 = 1e-5
if not np.isfinite(e2):
e2 = 1e-5
elif transf_e == 5: # Combination of environment and diversity dependent extinction
env_e1 = ext_rate_vec[0, 0] * np.exp(np.sum(covar_parE[idx_covar_parE1] * time_varE[0, i - 1, :]))
env_e2 = ext_rate_vec[0, 1] * np.exp(np.sum(covar_parE[idx_covar_parE2] * time_varE[1, i - 1, :]))
k_e1 = covar_par[2]
k_e2 = covar_par[3]
e1 = env_e1 * (1. - offset_dis_div2 / k_e1)
e2 = env_e2 * (1. - offset_dis_div1 / k_e2)
elif transf_e == 8: # Skyline + environmental-dependent extinction
idx = i - 1
e1 = ext_rate_vec[idx, 0] * np.exp(np.sum(covar_parE[idx_covar_parE1] * time_varE[0, i - 1, :]))
e2 = ext_rate_vec[idx, 1] * np.exp(np.sum(covar_parE[idx_covar_parE2] * time_varE[1, i - 1, :]))
ext_rate_vec_i = ext_rate_vec[i - 1, :]
return d12, d21, e1, e2, k_d1, k_d2, k_e1, k_e2, covar_mu1, covar_mu2
def approx_div_traj(nTaxa, dis_rate_vec, ext_rate_vec,
transf_d, transf_e,
argsG, r_vec, alpha, YangGammaQuant, pp_gamma_ncat, bin_size, Q_index, Q_index_first_occ, weight_per_taxon,
covar_par, covar_parD, covar_parE, offset_dis_div1, offset_dis_div2, offset_ext_div1, offset_ext_div2,
time_series, len_time_series, bin_first_occ, first_area, time_varD, time_varE, data_temp,
trait_parD, traitD, trait_parE, traitE,
cat_parD, catD, cat_parE, catE, argstraitD, argstraitE, argscatD, argscatE, argslogdistr,
pres1_idx, pres2_idx, pres3_idx, gainA_idx, gainB_idx):
if argsG:
YangGamma = get_gamma_rates(alpha, YangGammaQuant, pp_gamma_ncat)
sa = np.zeros((pp_gamma_ncat, nTaxa))
sb = np.zeros((pp_gamma_ncat, nTaxa))
for i in range(pp_gamma_ncat):
sa[i,:] = np.exp(-bin_size * YangGamma[i] * -np.log(r_vec[Q_index_first_occ, 1])/bin_size)
sb[i,:] = np.exp(-bin_size * YangGamma[i] * -np.log(r_vec[Q_index_first_occ, 2])/bin_size)
sa = sa * weight_per_taxon
sb = sb * weight_per_taxon
# print("sb", sb)
sa = np.nansum(sa, axis = 0)
sb = np.nansum(sb, axis = 0)
# print("sum sb", sb)
else:
sa = r_vec[Q_index_first_occ, 1]
sb = r_vec[Q_index_first_occ, 2]
sa[first_area == 1.] = 0. # No false absence if taxon is observed in 1
sb[first_area == 2.] = 0. # No false absence if taxon is observed in 2
sa[first_area == 3.] = 0. # No false absence if taxon is observed in 3
sb[first_area == 3.] = 0. # No false absence if taxon is observed in 3
# Add artificial bin before start of the time series
time_series_pad = time_series
time_varD_pad = time_varD
time_varE_pad = time_varE
idx_covar_parD1 = np.arange(0, len(covar_parD), 2, dtype=int)
idx_covar_parD2 = np.arange(1, len(covar_parD), 2, dtype=int)
idx_covar_parE1 = np.arange(0, len(covar_parE), 2, dtype=int)
idx_covar_parE2 = np.arange(1, len(covar_parE), 2, dtype=int)
if (traits is False and cat is False) and argslogdistr is False:
div_1 = np.zeros(len_time_series)
div_2 = np.zeros(len_time_series)
div_3 = np.zeros(len_time_series)
gain_1 = np.zeros(len_time_series)
gain_2 = np.zeros(len_time_series)
pres = np.ones((len_time_series, 3 * nTaxa))
for i in range(1, len_time_series):
d12, d21, mu1, mu2, k_d1, k_d2, k_e1, k_e2, covar_mu1, covar_mu2 = rates_at_t(i, transf_d, transf_e,
dis_rate_vec, ext_rate_vec,
covar_parD,
idx_covar_parD1, idx_covar_parD2,
covar_parE,
idx_covar_parE1, idx_covar_parE2,
covar_par,
offset_dis_div1, offset_dis_div2)
# Preservation stuff
occ_i = bin_first_occ == i # Only taxa occuring at that time for the first time
sa_i = sa[occ_i]
sb_i = sb[occ_i]
sum_sa_i = np.sum(sa_i) # Summed probability of false absences in area 1
sum_sb_i = np.sum(sb_i)
first_area_i = first_area[occ_i]
new_1 = np.sum(first_area_i == 1.) - sum_sb_i # Observed area 1 - false absences in area 1 (which are then in 3)
new_2 = np.sum(first_area_i == 2.) - sum_sa_i
new_3 = np.sum(first_area_i == 3.) + sum_sa_i + sum_sb_i
dt = [0., time_series_pad[i - 1] - time_series_pad[i] ]
div_t = np.zeros(5)
div_t[0] = div_1[i - 1]
div_t[1] = div_2[i - 1]
div_t[2] = div_3[i - 1]
if transf_e == 3:
div_int = odeint(dis_dep_ext_dt, div_t, dt, args = (d12, d21, mu1, mu2, k_d1, k_d2, covar_mu1, covar_mu2), mxstep=100)
else:
div_int = odeint(div_dt, div_t, dt, args = (d12, d21, mu1, mu2, k_d1, k_d2, k_e1, k_e2))
div_1[i] = div_int[1,0] + new_1
div_2[i] = div_int[1,1] + new_2
div_3[i] = div_int[1,2] + new_3
gain_1[i] = div_int[1,3]
gain_2[i] = div_int[1,4]
else: # Traits and categorical
pres = np.zeros((len_time_series, 5 * nTaxa)) # time x probability of taxa presence - all presences could be case for a 3D array
for i in range(1, len_time_series):
d12, d21, mu1, mu2, k_d1, k_d2, k_e1, k_e2, covar_mu1, covar_mu2 = rates_at_t(i, transf_d, transf_e,
dis_rate_vec, ext_rate_vec,
covar_parD,
idx_covar_parD1, idx_covar_parD2,
covar_parE,
idx_covar_parE1, idx_covar_parE2,
covar_par,
offset_dis_div1, offset_dis_div2)
# Preservation stuff
occ_i = bin_first_occ == i # Only taxa occuring at that time for the first time
new_1 = np.zeros(nTaxa)
new_2 = np.zeros(nTaxa)
new_3 = np.zeros(nTaxa)
if any(occ_i):
occ_area_1 = np.logical_and(occ_i, first_area == 1.)
occ_area_2 = np.logical_and(occ_i, first_area == 2.)
occ_area_3 = np.logical_and(occ_i, first_area == 3.)
false_absence_area_2 = sb * occ_area_1
# print(i, "false_absence_area_2", false_absence_area_2)
false_absence_area_1 = sa * occ_area_2
new_1 = occ_area_1 - false_absence_area_2
new_2 = occ_area_2 - false_absence_area_1
new_3 = occ_area_3 + false_absence_area_1 + false_absence_area_2
dt = [0., time_series_pad[i - 1] - time_series_pad[i] ]
div_t = pres[i - 1,:]
div_dt_args = (d12, d21, mu1, mu2, k_d1, k_d2, k_e1, k_e2, covar_mu1, covar_mu2,
trait_parD, traitD, trait_parE, traitE,
cat_parD, catD, cat_parE, catE,
do_DdE, argstraitD, argstraitE, argscatD, argscatE,
pres1_idx, pres2_idx, pres3_idx, gainA_idx, gainB_idx, nTaxa)
div_int = odeint(div_traitcat_dt, div_t, dt, args=div_dt_args, mxstep=100)
pres[i, pres1_idx] = div_int[1, pres1_idx] + new_1
pres[i, pres2_idx] = div_int[1, pres2_idx] + new_2
pres[i, pres3_idx] = div_int[1, pres3_idx] + new_3
pres[i, gainA_idx] = div_int[1, gainA_idx]
pres[i, gainB_idx] = div_int[1, gainB_idx]
div_1 = np.sum(pres[:, pres1_idx], axis=1) # rowsums are axis 1!
div_2 = np.sum(pres[:, pres2_idx], axis=1)
div_3 = np.sum(pres[:, pres3_idx], axis=1)
gain_1 = np.sum(pres[:, gainA_idx], axis=1)
gain_2 = np.sum(pres[:, gainB_idx], axis=1)
pres[-1, pres1_idx] = 0
pres[-1, pres2_idx] = 0
pres[-1, pres3_idx] = 0
pres[-1, pres1_idx[np.isin(data_temp[:, -1], 1)]] = 1
pres[-1, pres2_idx[np.isin(data_temp[:, -1], 2)]] = 1
pres[-1, pres3_idx[np.isin(data_temp[:, -1], 3)]] = 1
div_13 = div_1 + div_3
div_23 = div_2 + div_3
gain_1_rescaled = gain_1 / (div_1 + 1.)
gain_2_rescaled = gain_2 / (div_2 + 1.)
gain_1_rescaled[np.isnan(gain_1_rescaled)] = np.nanmax(gain_1_rescaled)
gain_2_rescaled[np.isnan(gain_2_rescaled)] = np.nanmax(gain_2_rescaled)
div_13[-1] = np.sum(np.isin(data_temp[:, -1], [1., 3.]))
div_23[-1] = np.sum(np.isin(data_temp[:, -1], [2., 3.]))
div_13 = div_13[1:]
div_23 = div_23[1:]
gain_1_rescaled = gain_1_rescaled[1:]
gain_2_rescaled = gain_2_rescaled[1:]
return div_13, div_23, gain_1_rescaled, gain_2_rescaled, pres[1:,:]
# Calculate difference from a given diversity to the equilibrium diversity for two areas
# (in case of covariate dependent dispersal or extinction,
# the equilibrium is calculated for the covariate mean)
def calc_diff_equil_two_areas(div):
div1 = div[0]
div2 = div[1]
div3 = div[2]
div13 = div1 + div3
div23 = div2 + div3
if div13 > k_d[0] or div23 > k_d[1] or div13 >= k_e[0] or div23 >= k_e[1] or (div1 + div3 < 1) or (div2 + div3 < 1):
diff_equil = 1e10
else:
lim_d2 = np.maximum(0.0, 1.0 - div13/k_d[0]) # Limit dispersal into area 2
lim_d1 = np.maximum(0.0, 1.0 - div23/k_d[1]) # Limit dispersal into area 1
gain1 = dis[1] * div2 * lim_d1
gain2 = dis[0] * div1 * lim_d2
if do_DdE: # Dispersal dependent extinction
mu1 = ext[0] + covar_par[2] * gain1 / (div13 + 1.)
mu2 = ext[1] + covar_par[3] * gain2 / (div23 + 1.)
else: # Diversity dependent extinction
lim_e1 = np.maximum(1e-10, 1.0 - div13/k_e[0]) # Increases extinction in area 2
lim_e2 = np.maximum(1e-10, 1.0 - div23/k_e[1]) # Increases extinction in area 1
mu1 = ext[0]/lim_e1
mu2 = ext[1]/lim_e2
loss1 = mu1 * div1 + mu1 * div3
loss2 = mu2 * div2 + mu2 * div3
diff_equil = abs(gain1 - loss1) + abs(gain2 - loss2)
return diff_equil
# Calculate difference from a given diversity to the equilibrium diversity for one area
def calc_diff_equil_one_area(div):
div_both = div[0] + div[1]
if div_both > k_d or div_both >= k_e or div_both < 1:
diff_equil = 1e10
else:
lim_d = np.maximum(0.0, 1.0 - div_both/k_d) # Limit dispersal into focal area
gain = dis * div[0] * lim_d
if do_DdE: # Dispersal dependent extinction
mu = ext + covar_par_equil * gain / (div_both + 1.)
else: # Diversity dependent extinction
lim_e = np.maximum(1e-10, 1.0 - div_both/k_e)
mu = ext/lim_e
loss = mu * div_both
diff_equil = np.abs(gain - loss)
return diff_equil
def get_num_dispersals(dis_rate_vec, r_vec):
Pr1 = 1 - r_vec[Q_index[0:-1], 1] # remove last value (time zero)
Pr2 = 1 - r_vec[Q_index[0:-1], 2]
# get dispersal rates through time
#d12 = dis_rate_vec[0][0] *exp(covar_par[0]*time_var)
#d21 = dis_rate_vec[0][1] *exp(covar_par[1]*time_var)
dr = dis_rate_vec
d12 = dr[:, 0]
d21 = dr[:, 1]
numD12 = (div_traj_1/Pr1) * d12
numD21 = (div_traj_2/Pr2) * d21
return numD12, numD21
def get_marginal_traitrate(baserate, nTaxa, pres,
traits, cont_trait, cont_trait_par,
cat, cat_trait, cat_trait_par,
pres1_idx, pres2_idx, pres3_idx,
rate_type='extinction'):
pres1 = pres[:, pres1_idx] # exclusively area 1
pres2 = pres[:, pres2_idx] # exclusively area 2
if rate_type == 'extinction':
pres1 += pres[:, pres3_idx]
pres2 += pres[:, pres3_idx]
div1 = np.sum(pres1, axis=1)
div2 = np.sum(pres2, axis=1)
div1[div1 == 0.0] = 1e-5
div2[div2 == 0.0] = 1e-5
weight1 = pres1 / div1[:, np.newaxis]
weight2 = pres2 / div2[:, np.newaxis]
baserate1 = baserate[:, 0][::-1].reshape(-1, 1)
baserate2 = baserate[:, 1][::-1].reshape(-1, 1)
if traits:
cont_modi = np.exp(np.sum(cont_trait_par * cont_trait, axis=1))
rate_taxa1 = baserate1 * cont_modi
rate_taxa2 = baserate2 * cont_modi
baserate1 = rate_taxa1
baserate2 = rate_taxa2
if cat:
cat_modi = np.sum(np.exp(cat_trait_par[cat_trait]), axis=1) # One value per taxon
rate_taxa1 = baserate1 * cat_modi
rate_taxa2 = baserate2 * cat_modi
rate_taxa1 = rate_taxa1 * weight1
rate_taxa2 = rate_taxa2 * weight2
rate1 = np.sum(rate_taxa1, axis=1)
rate2 = np.sum(rate_taxa2, axis=1)
margrate = np.array([rate1, rate2])
return margrate
def get_lik_input(dis_vec, ext_vec, repeats_de, repeats_d, repeats_e,
time_var_d1, time_var_d2, time_var_e1, time_var_e2,
diversity_d1, diversity_d2, diversity_e1, diversity_e2, dis_into_1, dis_into_2,
covar_par, covar_parD, covar_parE, x0_logisticD, x0_logisticE,
transf_d, transf_e,
offset_dis_div1, offset_dis_div2, offset_ext_div1, offset_ext_div2,
traits, trait_parD, traitD, trait_parE, traitE,
cat, cat_parD, catD, catE, cat_parE,
use_Pade_approx):
w_list = np.zeros(1)
vl_list = np.zeros(1)
vl_inv_list = np.zeros(1)
Pt = np.zeros(1)
if transf_d > 0 or transf_e > 0:
dis_vec = dis_vec[repeats_d, :]
ext_vec = ext_vec[repeats_e, :]
Q_list, marginal_rates = make_Q_Covar4VDdE(dis_vec, ext_vec, repeats_d, repeats_e,
time_var_d1, time_var_d2, time_var_e1, time_var_e2,
diversity_d1, diversity_d2, diversity_e1, diversity_e2, dis_into_1, dis_into_2,
covar_par, covar_parD, covar_parE, x0_logisticD, x0_logisticE,
transf_d, transf_e,
offset_dis_div1, offset_dis_div2, offset_ext_div1, offset_ext_div2)
if traits or cat:
len_Q_list = len(Q_list)
Q_list = np.tile(Q_list, (nTaxa, 1, 1)) # Q lists over time, repeated and stacked for all taxa
if traits:
trait_parD_rep = np.repeat(np.exp(np.sum(trait_parD * traitD, axis=1)), len_Q_list)
trait_parE_rep = np.repeat(np.exp(np.sum(trait_parE * traitE, axis=1)), len_Q_list)
Q_list[:, 3, 1] = Q_list[:, 3, 1] * trait_parD_rep
Q_list[:, 3, 2] = Q_list[:, 3, 2] * trait_parD_rep
Q_list[:, 0, 1] = Q_list[:, 0, 1] * trait_parE_rep
Q_list[:, 2, 3] = Q_list[:, 2, 3] * trait_parE_rep
Q_list[:, 0, 2] = Q_list[:, 0, 2] * trait_parE_rep
Q_list[:, 1, 3] = Q_list[:, 1, 3] * trait_parE_rep
if cat:
cat_parD_rep = np.repeat(np.sum(np.exp(cat_parD[catD]), axis=1), len_Q_list)
cat_parE_rep = np.repeat(np.sum(np.exp(cat_parE[catE]), axis=1), len_Q_list)
Q_list[:, 3, 1] = Q_list[:, 3, 1] * cat_parD_rep
Q_list[:, 3, 2] = Q_list[:, 3, 2] * cat_parD_rep
Q_list[:, 0, 1] = Q_list[:, 0, 1] * cat_parE_rep
Q_list[:, 2, 3] = Q_list[:, 2, 3] * cat_parE_rep
Q_list[:, 0, 2] = Q_list[:, 0, 2] * cat_parE_rep
Q_list[:, 1, 3] = Q_list[:, 1, 3] * cat_parE_rep
l = len(repeats_de)
s = np.max(repeats_de) + 1
repeats_de = np.tile(repeats_de, nTaxa) + np.repeat(np.arange(0, s * nTaxa, s), l)
# Fill diagonals of transition matrix
col_sum = -np.einsum('ijk->ik', Q_list) # Colsum per slice
s0, _, s2 = Q_list.shape
Q_list.reshape(s0, -1)[:, ::s2 + 1] = col_sum
if use_Pade_approx in [0, 2]:
w_list, vl_list, vl_inv_list = get_eigen_list(Q_list)
if (transf_d == 0 and transf_e == 0):
w_list, vl_list, vl_inv_list = w_list[repeats_de, :], vl_list[repeats_de, :, :], vl_inv_list[repeats_de, :, :]
if use_Pade_approx == 2:
Pt = precompute_Pt(delta_t, w_list, vl_list, vl_inv_list, nTaxa, traits, cat)
else:
Q_list = Q_list[repeats_de, :, :]
return Q_list, marginal_rates, w_list, vl_list, vl_inv_list, Pt
def lik_DES_taxon(args):
[l, w_list, vl_list, vl_inv_list, Q_list, Q_index_temp,
delta_t, r_vec, rho_at_present_LIST, r_vec_indexes_LIST, sign_list_LIST, recursive_LIST, Q_index,
traits, cat, Pt, use_Pade_approx] = args
len_delta_t = len(delta_t)
qwvl_idx = np.arange(0, len_delta_t)
if traits or cat:
qwvl_idx = np.arange(0 + l * len_delta_t, len_delta_t + l * len_delta_t)
if use_Pade_approx == 0:
rho_gamma = r_vec[0].ndim > 1
if rho_gamma:
gamma_ncat = r_vec[0].shape[0]
l_temp = np.zeros(gamma_ncat)
for i in range(gamma_ncat):
l_temp[i] = calc_likelihood_mQ_eigen([delta_t, r_vec[:, i, :],
w_list[qwvl_idx,:], vl_list[qwvl_idx, :], vl_inv_list[qwvl_idx, :], rho_at_present_LIST[l],
r_vec_indexes_LIST[l],sign_list_LIST[l], recursive_LIST[l],
Q_index, Q_index_temp])
else:
l_temp = calc_likelihood_mQ_eigen([delta_t, r_vec,
w_list[qwvl_idx, :], vl_list[qwvl_idx, :], vl_inv_list[qwvl_idx, :], rho_at_present_LIST[l],
r_vec_indexes_LIST[l],sign_list_LIST[l], recursive_LIST[l],
Q_index, Q_index_temp])
elif use_Pade_approx == 1:
rho_gamma = r_vec[0].ndim > 1
if rho_gamma:
gamma_ncat = r_vec[0].shape[0]
l_temp = np.zeros(gamma_ncat)
for i in range(gamma_ncat):
l_temp[i] = calc_likelihood_mQ([delta_t, r_vec[:, i, :], Q_list[qwvl_idx, :], rho_at_present_LIST[l],
r_vec_indexes_LIST[l], sign_list_LIST[l], recursive_LIST[l],
Q_index, Q_index_temp])
else:
l_temp = calc_likelihood_mQ([delta_t, r_vec, Q_list[qwvl_idx, :], rho_at_present_LIST[l],
r_vec_indexes_LIST[l], sign_list_LIST[l], recursive_LIST[l],
Q_index, Q_index_temp])
if use_Pade_approx == 2:
l_temp = calc_likelihood_mQ_eigen_precompute([r_vec, rho_at_present_LIST[l],
r_vec_indexes_LIST[l], sign_list_LIST[l], recursive_LIST[l],
Pt[qwvl_idx , :, :]])
return l_temp
def lik_DES(Q_list, w_list, vl_list, vl_inv_list, Pt,
r_vec, bin_size,
rho_at_present_LIST, r_vec_indexes_LIST, sign_list_LIST, recursive_LIST, Q_index, Q_index_temp,
alpha, YangGammaQuant, pp_gamma_ncat,
do_traitS, trait_parS, traitS, list_taxa_index, nTaxa,
use_Pade_approx, num_processes):
# weight per gamma cat per species: multiply
weight_per_taxon = np.ones((pp_gamma_ncat, nTaxa)) / pp_gamma_ncat
if num_processes == 0:
lik = 0
idx_r_vec_traits = [1, 2]
if argsG is False:
for l in list_taxa_index:
r_vec2 = np.copy(r_vec)[Q_index]
r_vec_traits = np.copy(r_vec2)
if do_traitS:
r_vec2_rate = -np.log(r_vec_traits[:,idx_r_vec_traits])/bin_size
r_vec2_rate = r_vec2_rate * np.exp(np.sum(trait_parS * traitS[l]))
r_vec2[:,idx_r_vec_traits] = np.exp(-bin_size * r_vec2_rate)
lik_tmp = lik_DES_taxon([l, w_list, vl_list, vl_inv_list, Q_list, Q_index_temp, delta_t,
r_vec2, rho_at_present_LIST, r_vec_indexes_LIST, sign_list_LIST, recursive_LIST, Q_index,
traits, cat, Pt, use_Pade_approx])
lik += np.log(lik_tmp)
else:
liktmp = np.zeros((pp_gamma_ncat, nTaxa)) # row: ncat column: species
YangGamma = get_gamma_rates(alpha, YangGammaQuant, pp_gamma_ncat)
r_vec2 = np.copy(r_vec)[Q_index]
r_vec_Gamma_all = np.zeros((r_vec2.shape[0], pp_gamma_ncat, 4)) # sampling strata (-qtimes), gamma cats, 4
for i in range(pp_gamma_ncat):
r_vec_Gamma_all[:, i, :] = np.exp(-bin_size * YangGamma[i] * -np.log(r_vec2)/bin_size)
r_vec_Gamma_all[:, :, 0] = 0.0
r_vec_Gamma_all[:, :, 3] = 1.0
if args.data_in_area == 1:
r_vec_Gamma_all[:, :, 2] = small_number
elif args.data_in_area == 2:
r_vec_Gamma_all[:, :, 1] = small_number
r_vec_Gamma_traits = np.copy(r_vec_Gamma_all)
for l in list_taxa_index:
if do_traitS:
r_vec_Gamma_all[:, :, idx_r_vec_traits] = np.exp(-bin_size * np.exp(np.sum(trait_parS * traitS[l])) * -np.log(r_vec_Gamma_traits[:,:,idx_r_vec_traits])/bin_size)
liktmp[:, l] = lik_DES_taxon([l, w_list, vl_list, vl_inv_list, Q_list, Q_index_temp, delta_t,
r_vec_Gamma_all, # Only difference to homogeneous sampling
rho_at_present_LIST, r_vec_indexes_LIST, sign_list_LIST, recursive_LIST, Q_index,
traits, cat, Pt, use_Pade_approx])
liktmp = np.log(liktmp)
liktmpmax = np.amax(liktmp, axis=0)
liktmp2 = liktmp - liktmpmax
lik = np.sum(np.log(np.sum( np.exp(liktmp2), axis=0 ) / pp_gamma_ncat) + liktmpmax)
weight_per_taxon = liktmp / np.sum(liktmp, axis=0)
else: # multi=processing
sys.exit("Multi-threading not available") # Not working on windows and massive slow down on linux
pool_lik = multiprocessing.Pool(num_processes) # likelihood
if argsG is False:
r_vec2 = np.copy(r_vec)[Q_index]
args_mt_lik = [ [l, w_list, vl_list, vl_inv_list, Q_list, Q_index_temp, delta_t,
r_vec2,
rho_at_present_LIST, r_vec_indexes_LIST, sign_list_LIST, recursive_LIST, Q_index,
traits, cat, Pt, use_Pade_approx] for l in list_taxa_index ]
lik = np.sum(np.array(pool_lik.map(lik_DES_taxon, args_mt_lik)))
else:
liktmp = np.zeros((pp_gamma_ncat, nTaxa)) # row: ncat column: species
YangGamma = get_gamma_rates(alpha, YangGammaQuant, pp_gamma_ncat)
r_vec2 = np.copy(r_vec)[Q_index]
r_vec_Gamma_all = np.zeros((r_vec2.shape[0], pp_gamma_ncat, 4)) # sampling strata (-qtimes), gamma cats, 4
for i in range(pp_gamma_ncat):
r_vec_Gamma_all[:,i,:] = np.exp(-bin_size * YangGamma[i] * -np.log(r_vec2)/bin_size)
r_vec_Gamma_all[:,:,0] = 0.0
r_vec_Gamma_all[:,:,3] = 1.0
if args.data_in_area == 1:
r_vec_Gamma_all[:,:,2] = small_number
elif args.data_in_area == 2:
r_vec_Gamma_all[:,:,1] = small_number
args_mt_lik = [ [l, w_list, vl_list, vl_inv_list, Q_list, Q_index_temp, delta_t,
r_vec_Gamma_all, # Only difference to homogeneous sampling
rho_at_present_LIST, r_vec_indexes_LIST, sign_list_LIST, recursive_LIST, Q_index,
traits, cat, Pt, use_Pade_approx] for l in list_taxa_index ]
liktmp = np.array(pool_lik.map(lik_DES_taxon, args_mt_lik))
liktmp = np.log(liktmp)
liktmp = liktmp.T
liktmpmax = np.amax(liktmp, axis = 0)
liktmp2 = liktmp - liktmpmax
lik = np.sum(np.log(np.sum( np.exp(liktmp2), axis = 0 )/pp_gamma_ncat) + liktmpmax)
weight_per_taxon = liktmp / np.sum(liktmp, axis = 0)
pool_lik.close()
pool_lik.join()
return lik, weight_per_taxon
def make_x0_and_bounds(TdD, TdE):
if TdD:
n_Q_times_dis = n_Q_times
else:
n_Q_times_dis = 1
opt_ind_dis = np.arange(0, n_Q_times_dis * nareas)
if equal_d:
if constraints_01:
# symmetric and constant dispersal while other rates may shift
opt_ind_dis = np.zeros(1, dtype = int)
else:
opt_ind_dis = np.repeat(np.arange(0, n_Q_times_dis), 2)
if data_in_area != 0:
opt_ind_dis = np.arange(0, n_Q_times_dis)
if TdD and constraints_01 and equal_d is False:
if len(constraints[constraints < 2]) == 1:
opt_ind_dis = np.arange(0, n_Q_times_dis + 1)
else:
opt_ind_dis = np.arange(0, nareas)
if data_in_area != 0:
opt_ind_dis = np.arange(0, 1)
if TdE:
n_Q_times_ext = n_Q_times
else:
n_Q_times_ext = 1
opt_ind_ext = np.max(opt_ind_dis) + 1 + np.arange(0, n_Q_times_ext * nareas)
if equal_e:
if constraints_23:
opt_ind_ext = np.array([np.max(opt_ind_dis) + 1])
else:
opt_ind_ext = np.max(opt_ind_dis) + 1 + np.repeat(np.arange(0, n_Q_times_ext), 2)
if data_in_area != 0:
opt_ind_ext = np.max(opt_ind_dis) + 1 + np.arange(0, n_Q_times_ext)
if TdE and constraints_23 and equal_e:
if np.all(np.isin(np.array([2, 3]), constraints)):
opt_ind_ext = np.max(opt_ind_dis) + 1 + np.arange(0, nareas)
else:
opt_ind_ext = np.max(opt_ind_dis) + 1 + np.arange(0, n_Q_times_ext + 1)
if data_in_area != 0:
opt_ind_ext = np.max(opt_ind_dis) + 1 + np.arange(0, 1)
opt_ind_r_vec = np.max(opt_ind_ext) + 1 + np.arange(0, n_Q_times*nareas)
if equal_q:
if constraints_45:
opt_ind_r_vec = np.array([np.max(opt_ind_ext) + 1])
else:
opt_ind_r_vec = np.max(opt_ind_ext) + 1 + np.repeat(np.arange(0, n_Q_times), 2)
if data_in_area != 0:
opt_ind_r_vec = np.max(opt_ind_ext) + 1 + np.arange(0, n_Q_times)
if constraints_45 and equal_q:
if np.all(np.isin(np.array([4, 5]), constraints)):
opt_ind_r_vec = np.max(opt_ind_ext) + 1 + np.arange(0, nareas)
else:
opt_ind_r_vec = np.max(opt_ind_ext) + 1 + np.arange(0, n_Q_times + 1)
if data_in_area != 0:
opt_ind_r_vec = np.max(opt_ind_ext) + 1 + np.arange(0, 1)
x0 = np.zeros(1 + np.max(opt_ind_r_vec)) # Initial values
x0[opt_ind_dis] = np.random.uniform(0.1, 0.2, len(opt_ind_dis))
x0[opt_ind_ext] = np.random.uniform(0.01, 0.05, len(opt_ind_ext))
x0[opt_ind_r_vec] = np.random.uniform(0.1, 0.5, len(opt_ind_r_vec))
lower_bounds = [small_number] * len(x0)
upper_bounds = [100] * len(x0)
upper_bounds[-len(opt_ind_r_vec):] = [1 - small_number] * len(opt_ind_r_vec)
# Preservation heterogeneity
alpha_ind = None
ind_counter = np.max(opt_ind_r_vec) + 1
if argsG:
alpha_ind = ind_counter
ind_counter += 1
x0 = np.concatenate((x0, 10.), axis=None)
lower_bounds = lower_bounds + [small_number]
upper_bounds = upper_bounds + [100]
# Covariates
opt_ind_covar_dis = None
opt_ind_covar_ext = None
opt_ind_lg_dis = None
opt_ind_lg_ext = None
opt_ind_divd_dis = None
opt_ind_divd_ext = None
opt_ind_trait_dis = None
opt_ind_trait_ext = None
opt_ind_cat_dis = None
opt_ind_cat_ext = None
opt_ind_trait_samp = None
if do_varD or do_DivdD:
if do_varD:
opt_ind_covar_dis = np.arange(ind_counter, ind_counter + 2 * num_varD)
ind_counter += 2 * num_varD
x0 = np.concatenate((x0, np.zeros(2 * num_varD)), axis=None)
lower_bounds = lower_bounds + (-bound_covar_d).tolist() + (-bound_covar_d).tolist()
upper_bounds = upper_bounds + (bound_covar_d).tolist() + (bound_covar_d).tolist()
if do_symCovD or data_in_area != 0 or len(constrCovD_0) > 0:
if do_symCovD:
until = len(symCovD)
elif len(constrCovD_0) > 0:
until = len(constrCovD_0)
else:
until = num_varD # for data_in_area
opt_ind_covar_dis = opt_ind_covar_dis[0:-until]
ind_counter = ind_counter - until
x0 = x0[0:-until]
lower_bounds = lower_bounds[0:-until]
upper_bounds = upper_bounds[0:-until]
if lgD:
opt_ind_lg_dis = np.arange(ind_counter, ind_counter + 2 * num_varD)
ind_counter += 2 * num_varD
x0 = np.concatenate((x0, np.mean(time_varD, axis=(0, 1)), np.mean(time_varD, axis=(0, 1))), axis=None)
lower_bounds = lower_bounds + np.min(time_varD, axis=(0, 1)).tolist() + np.min(time_varD, axis=(0, 1)).tolist()
upper_bounds = upper_bounds + np.max(time_varD, axis=(0, 1)).tolist() + np.max(time_varD, axis=(0, 1)).tolist()
if do_symCovD or data_in_area != 0 or len(constrCovD_0) > 0:
if do_symCovD:
until = len(symCovD)
elif len(constrCovD_0) > 0:
until = len(constrCovD_0)
else:
until = num_varD # for data_in_area
opt_ind_lg_dis = opt_ind_lg_dis[0:-until]
ind_counter = ind_counter - until
x0 = x0[0:-until]
lower_bounds = lower_bounds[0:-until]
upper_bounds = upper_bounds[0:-until]
if do_DivdD:
opt_ind_divd_dis = np.array([ind_counter, ind_counter + 1])
ind_counter += 2
x0 = np.concatenate((x0, nTaxa + 0., nTaxa + 0.), axis=None)
lower_bounds = lower_bounds + [np.max(div_traj_2)] + [np.max(div_traj_1)]
upper_bounds = upper_bounds + [np.inf] + [np.inf]
if do_symDivdD or data_in_area != 0 or len(constrDivdD_0) > 0:
opt_ind_divd_dis = opt_ind_divd_dis[0:-1]
ind_counter = ind_counter - 1
x0 = x0[0:-1]
lower_bounds[-2] = np.max((np.max(div_traj_2), np.max(div_traj_1)))
lower_bounds = lower_bounds[0:-1]
upper_bounds = upper_bounds[0:-1]
if do_varE or do_DivdE or do_DdE:
if do_varE:
opt_ind_covar_ext = np.arange(ind_counter, ind_counter + 2 * num_varE)
ind_counter += 2 * num_varE
x0 = np.concatenate((x0, np.zeros(2 * num_varE)), axis = None)
lower_bounds = lower_bounds + (-bound_covar_e).tolist() + (-bound_covar_e).tolist()
upper_bounds = upper_bounds + bound_covar_e.tolist() + bound_covar_e.tolist()
if do_symCovE or data_in_area != 0 or len(constrCovE_0) > 0:
if do_symCovE:
until = len(symCovE)
elif len(constrCovE_0) > 0:
until = len(constrCovE_0)
else:
until = num_varE # for data_in_area
opt_ind_covar_ext = opt_ind_covar_ext[0:-until]
ind_counter = ind_counter - until
x0 = x0[0:-until]
lower_bounds = lower_bounds[0:-until]
upper_bounds = upper_bounds[0:-until]
if lgE:
opt_ind_lg_ext = np.arange(ind_counter, ind_counter + 2 * num_varE)
ind_counter += 2 * num_varE
x0 = np.concatenate((x0, np.mean(time_varE, axis=0), np.mean(time_varE, axis=0)), axis=None)
lower_bounds = lower_bounds + np.min(time_varE, axis=0).tolist() + np.min(time_varE, axis=0).tolist()
upper_bounds = upper_bounds + np.max(time_varE, axis=0).tolist() + np.max(time_varE, axis=0).tolist()
if do_symCovE or data_in_area != 0 or len(constrCovE_0) > 0:
if do_symCovE:
until = len(symCovE)
elif len(constrCovE_0) > 0:
until = len(constrCovE_0)
else:
until = num_varE # for data_in_area
opt_ind_lg_ext = opt_ind_lg_ext[0:-until]
ind_counter = ind_counter - until
x0 = x0[0:-until]
lower_bounds = lower_bounds[0:-until]
upper_bounds = upper_bounds[0:-until]
if do_DivdE or do_DdE:
opt_ind_divd_ext = np.array([ind_counter, ind_counter + 1])
ind_counter += 2
if do_DivdE:
x0 = np.concatenate((x0, nTaxa + 0., nTaxa + 0.), axis=None)
lower_bounds = lower_bounds + [np.max(div_traj_1)] + [np.max(div_traj_2)]
upper_bounds = upper_bounds + [np.inf] + [np.inf]
else:
x0 = np.concatenate((x0, 0., 0.), axis = None)
lower_bounds = lower_bounds + [0.] + [0.]
upper_bounds = upper_bounds + [50.] + [50.]
if do_symDivdE or data_in_area != 0 or len(constrDivdE_0) > 0:
opt_ind_divd_ext = opt_ind_divd_ext[0:-1]
ind_counter = ind_counter - 1
x0 = x0[0:-1]
if do_DivdE:
lower_bounds[-2] = np.max((np.max(div_traj_2), np.max(div_traj_1)))
lower_bounds = lower_bounds[0:-1]
upper_bounds = upper_bounds[0:-1]
# Trait-dependence
if argstraitD != "":
opt_ind_trait_dis = np.arange(ind_counter, ind_counter + num_traitD)
ind_counter += num_traitD
x0 = np.concatenate((x0, np.zeros(num_traitD)), axis=None)
lower_bounds = lower_bounds + (-bound_traitD).tolist()
upper_bounds = upper_bounds + bound_traitD.tolist()
if argstraitE != "":
opt_ind_trait_ext = np.arange(ind_counter, ind_counter + num_traitE)
ind_counter += num_traitE
x0 = np.concatenate((x0, np.zeros(num_traitE)), axis=None)
lower_bounds = lower_bounds + (-bound_traitE).tolist()
upper_bounds = upper_bounds + (bound_traitE).tolist()
if do_traitS:
opt_ind_trait_samp = np.arange(ind_counter, ind_counter + num_traitS)
ind_counter += num_traitS
x0 = np.concatenate((x0, np.zeros(num_traitS)), axis=None)
lower_bounds = lower_bounds + (-bound_traitS).tolist()
upper_bounds = upper_bounds + (bound_traitS).tolist()
# Categories
if argscatD != "":
len_catD = len(unique_catD) - len(num_catD) # Deviation from a common mean
opt_ind_cat_dis = np.arange(ind_counter, ind_counter + len_catD)
ind_counter += len_catD
x0 = np.concatenate((x0, np.zeros(len_catD)), axis=None)
lower_bounds = lower_bounds + [-5] * len_catD
upper_bounds = upper_bounds + [3] * len_catD
if argscatE != "":
len_catE = len(unique_catE) - len(num_catE) # Deviation from a common mean
opt_ind_cat_ext = np.arange(ind_counter, ind_counter + len_catE)
ind_counter += len_catE
x0 = np.concatenate((x0, np.zeros(len_catE)), axis=None)
lower_bounds = lower_bounds + [-5] * len_catE
upper_bounds = upper_bounds + [3] * len_catE
if len(args.A3init) > 0:
A3init = np.array(args.A3init)
A3init[opt_ind_r_vec] = np.exp(-A3init[opt_ind_r_vec] * bin_size)
if do_DivdD:
A3init[opt_ind_dis] = A3init[opt_ind_dis] * (1. - ([offset_dis_div2, offset_dis_div1] / A3init[opt_ind_covar_dis]))
if do_DivdE:
A3init[opt_ind_ext] = A3init[opt_ind_ext] / (1. - ([offset_ext_div2, offset_ext_div1]/A3init[opt_ind_covar_ext]))
x0 = A3init