-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackup.py.bkp
1552 lines (1274 loc) · 67.3 KB
/
backup.py.bkp
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/python
# Using CapWords for function, method, and class names
# Using underscored_names for variable names, module and package names.
# Using ALL_CAPS_WITH_UNDERSCORES for file handles
# levels=tree.levels
# current_level=levels[level_number]
# event_history=current_level.event_history
# lineage_names=event_history[0].keys()
# j=level_num
# allcomb=[]
# next_coalesce=CombinationChoose2(lineage_names,allcomb,j)
from is_classes import Level
from is_classes import Tree
from is_classes import Node
from levels import DemarcateLevels
from scipy.misc import comb
from scipy.misc import factorial
import sys
import math
#sys.path=[sys.path,'/Network/Servers/orrorin.nescent.org/Volumes/xraid/home/alexandrabalaban/Documents/Summer2008']
#sys.path=[sys.path,'C:\Documents and Settings\Perry Zheng\workspace\Summer2008\src']
#sys.path.append('C:\Users\Lonnie\Desktop\Summer2008_2\Summer2008\src')
#sys.path.append('C:\Users\Lonnie\Desktop\Summer2008_2\Summer2008\src')
sys.path.append('C:\Documents and Settings\Owner\Desktop\Summer2008\src')
def CombinationChoose2(list,allcomb,j):
"""
Returns all the j choose 2 combinations of a list of j
items.
Input parameters
---------------
list the list from which to create combinations
allcomb an empty list which the function will return filled
with the combinations
j the length of list
Return value
------------
a list containing all possible j choose 2 combinations
Details
-------
Input: list=[1,2,3], allperm=[], j=3
Output: [[1, 3], [2, 3], [1, 2]]
"""
if j==1:
return allcomb
j=j-1
for i in range(j):
allcomb.append([list[i],list[j]])
CombinationChoose2(list,allcomb,j)
def LogFactorialOfNegative(z,terms=100):
"""
Returns an approximation of the factorial of a negative number less than -1.
Input paramters
---------------
n the negative number less than one
terms the number of terms for which to carry out the approximation
Return value
------------
An approximation of the factorial. Uses the Euler infinite product
definition of the Gamma function
"""
z=float(z)
fact=0
for n in range(terms):
n=n+1
n=float(n)
fact=fact+math.log(float(pow((1+1/n),z))/float(1+z/n))
return(fact)
def CombOfNegative(n,k):
"""
An approximation of the Combination function using FactorialOfNegative\
Input
-----
n,k Any real number that is not a negative integer
Output
------
n choose k
"""
log_n=LogFactorialOfNegative(n)
log_k=LogFactorialOfNegative(k)
n_fact_over_k_fact=pow(10,log_n-log_k)
n_minus_k_fact=pow(10,LogFactorialOfNegative(n-k))
return n_fact_over_k_fact/n_minus_k_fact
def GetEvents():
"""
Returns sets of various types of events (or equivalently, state
transitions) that could happen in the conditional jump chain described
in Section 5.3 of mossEqModel.pdf.
No Input Parameters
Return value
------------
a 3-tuple consisting of 3 sets: (bigbig_K, bigbig_M, bigbig_H).
bigbig_K is the set of various types of speciation events.
bigbig_M is the set of various types of migration events.
bigbig_H is the union of the above two sets.
See Page 19, segment entitled "Events as operators on states".
Also see 'Details' below.
Details
-------
Possible transitions (i.e., events) of the condition jump chain.
See Page 19, segment entitled "Events as operators on states".
The events can be one of the following:
1. a speciation event involving the two next-coalescing lineages
2a, 2b, 2c. a speciation that does not involve one or both of the
next-coalescing lineages. These can be three types,
as noted in Section 3. (Note that in page 19, segment
titled 'Events as operators on states, 2a, 2b and 2c
are all lumped into one category, which is not quite
accurate. My apologies - Ganesh).
3a, 3b. a migration (i.e., state transition) of one of the two
next-coalescing lineages.
4. Any other migration event.
1, 2a, 2b, 2c together will make bigbig_K.
3a, 3b and 4 will make bigbig_M
bigbig_H is the union of the above two sets.
"""
#sys.path=[sys.path,'/Network/Servers/orrorin.nescent.org/Volumes/xraid/home/alexandrabalaban/Documents/Summer2008']
#sys.path=[sys.path,'C:\Documents and Settings\Perry Zheng\workspace\Summer2008\src']
# 'kappa' is the speciation
# involving the two next-coalescing species. The other three follow
# notation from Section 3, bullet point entitled 'Events', page 5.
# Also see Figure 1, page 6.
# set() is a python command for creating a set from a list.
bigbig_K = set(['kappa', 's_tt', 's_bb', 's_bt'])
# m_1 is the migration of next_coalescing_lineage1: i.e., lineage whose
# state is state_of_next_coalescing_lineages_1;
# m_2 is the migration of next_coalescing_lineage1: i.e., lineage whose
# state is state_of_next_coalescing_lineages_2;
# 's_b_arrow_t' is any other migration
bigbig_M = set(['m_1', 'm_2', 's_b_arrow_t'])
# bigbig_H = bigbig_K union bigbig_M.
bigbig_H = bigbig_K.union(bigbig_M)
return((bigbig_K, bigbig_M, bigbig_H))
def GetCondJumpChainStateSpace(level_number):
"""
Input parameters
-----
level_number The level for which the conditional jump chain space is calculated
Output
------
A list of all the possible states, where the state's index in the array corresponds to the state's index
in the state_to_index_in_transistion_matrix dictionary
"""
state_space=range(4*(level_number+1))
state_map=ReverseMap(level_number)
for i in range(len(state_space)):
state_space[i]=state_map[i]
return(state_space)
def GetLinearEquation(z, state_of_cond_jump_chain):
"""
"""
q_t=z[0]
r_t=z[1]
x1=z[2]
x2=z[3]
speciation=''
if ((x1==1)&(x2==0))|((x1==0)&(x2==1)):
speciation='s_bt'
if(x1==1):
speciation='s_tt'
if(x1==0):
speciation='s_bb'
return([])
def LinearEquationSolver(system_of_equations):
"""
"""
return([])
def Make2DimensionalArray(dimension):
"""
"""
return([[]])
def ApplyEvent(z, w):
"""
"""
return(())
def CalculateLogPi(j_species, sigma):
"""
Calculates p_j, or the probability that the equilibrium number of species equals j given
sigma
Input Parameters
----------------
@param j_species
j species; a nonnegative integer
@param sigma set of all parameters for the model
For the model in mossEqModel.pdf,
sigma = (lambda, b, B, alpha, mu), where
lambda is the turnover rate in state 0 (the boreal region),
b = the effective migration rate from state 0 to 1 (boreal to tropical),
B = the total number of species in state 0 (the boreal region)
alpha = the per lineage speciation rate in state 1 (the neotropical region), and
mu = the per lineage extinction rate in state 1 (the neotropical region).
Details
--------
Only 3 components of sigma are needed:
alpha sigma[3] = per species birth rate in neotropical region; positive constant
b sigma[1] = migration rate
mu sigma[4] = death rate of species in neotropical region when number of species is i; positive constant
Important!! b/a+j-1 must be nonegative, so should be j
if alpha=mu, pi will be always zero, and CalculateLogPi returns -1, a flag that alpha=mu
Returns value
-------------
p_j = C(b/alpha + j - 1,j)*(alpha/mu)^j*(1-alpha/mu)^(-b/alpha); a float
if alpha=mu, -1, a flag is returned
"""
alpha = sigma[3]
b = sigma[1]
mu = sigma[4]
if (alpha==mu):
return -1
elif (b/alpha<1):
coefficient = math.log(float(CombOfNegative(b/alpha+j_species-1,j_species)),alpha/mu)
ratio = float(j_species)
ratio2 = math.log(pow(float(1-alpha/mu),-b/alpha),alpha/mu)
return coefficient+ratio+ratio2
else:
coefficient = math.log(float(comb(b/alpha+j_species-1,j_species,exact=0)),alpha/mu)
ratio = float(j_species)
ratio2 = math.log(pow(float(1-alpha/mu),-b/alpha),alpha/mu)
return coefficient+ratio+ratio2
def CalculatePi(j_species, sigma):
"""
Calculates p_j, or the probability that the equilibrium number of species equals j given
sigma
Input Parameters
----------------
@param j_species
j species; a nonnegative integer
@param sigma set of all parameters for the model
For the model in mossEqModel.pdf,
sigma = (lambda, b, B, alpha, mu), where
lambda is the turnover rate,
b = the effective migration rate,
B = the total number of species in state 0 (the boreal region)
alpha = the speciation rate in state 1 (the neotropical region), and
mu = the extinction rate in state 1 (the neotropical region).
Details
--------
Only 3 components of sigma are needed:
alpha sigma[3] = per species birth rate in neotropical region; positive constant
b sigma[1] = migration rate
mu sigma[4] = death rate of species in neotropical region when number of species is i; positive constant
Important!! b/a+j-1 must be nonegative, so should be j
Returns value
-------------
pi_j = C(b/alpha + j - 1,j)*(alpha/mu)^j*(1-alpha/mu)^(-b/alpha); a float
"""
alpha = sigma[3]
b = sigma[1]
mu = sigma[4]
coefficient = comb(b/alpha+j_species-1,j_species,exact=0)
ratio = pow(float(alpha/mu),j_species)
ratio2 = pow(float(1-alpha/mu),-b/alpha)
return coefficient*ratio*ratio2
def CalculatePiStar(n_t, current_state_for_uncond_probs, upper, sigma):
"""
Calculates p(n_t | q_t, r_t) = pi_star, or eqn (10) in mossEqModel.pdf
Input parameters
-----------------
@param n_t total number of neotropical species in the POPULATION
at time t
@param current_state_for_uncond_probs
the current state for unconditional probability
current_state_for_uncond_probs[0] = q_t - number of ancestral species in boreal in sample history at time t
current_state_for_uncond_probs[1] = r_t - number of ancestral species in neotropics in sameple history at time t
Note: only [1]=r_t is needed.
@param upper an upper limit in the summation
@param sigma set of all parameters for the model
sigma = (lambda, b, B, alpha, mu)
See CalculatePi for more details.
Details
--------
Only 3 components of sigma are used:
alpha sigma[3] = the speciation rate in state 1 (the neotropical region)
b sigma[1] = the migration rate
mu sigma[4] = the extinction rate in state 1 (the neotropical region)
Return value
-------------
p(n_t | q_t, r_t)= pi_n_t / \sum_{k>=r_t}(pi_k); a float
This is called the stead-state frequency of n_t, normalized to condition
on the fact that at least r_t neotropical species are known to exist at time t.
"""
r_t = current_state_for_uncond_probs[1]
#numerator = CalculatePi(n_t,sigma)
#denominator=0.0
#for i in range(r_t, upper):
# denominator=denominator+CalculatePi(i,sigma)
#return numerator/denominator
alpha = sigma[3]
mu = sigma[4]
log_numerator = CalculateLogPi(n_t,sigma)
log_denominator=CalculateLogPi(r_t,sigma)
if(log_numerator==-1):
#the flag that both the numerator and denominator will be zero
return 0.0
else:
for i in range(r_t,upper):
log_denominator=LogSum(CalculateLogPi(i,sigma),log_denominator,alpha/mu)
temp=log_numerator-log_denominator
return pow(alpha/mu,temp)
#I got this function from R documentation
def LogSum(log_x,log_y,base):
"""
Input Parameters
----------------
log_x the log of x with base=base
log_y the log of y with base=base
base the base of the logs of x and y
Return Value
------------
log(x+y) with base=base
Details
-------
This equality and function were obtained from the R function logSum in the package TileHMM
"""
temp=1+pow(base,log_y-log_x)
return log_x+math.log(temp,base)
def UncondProbSTT(current_state_for_uncond_probs, upper, sigma):
"""
Calculates p(S_TT|q_t,r_t), probability of speciation event within
the neotropics that is captured in the history of the sample,
conditioned on the fact that at time t the numbers of ancestral
species in boreal and neotrpoics regions are q_t and r_t, respectively. (actually, only r_t matters)
See eqn (13) in mossEqnModel.pdf
Input parameters
----------------
@param current_state_for_uncond_probs
the current state for unconditional probability
current_state_for_uncond_probs[0] = q_t - number of ancestral species in boreal in sample history at time t
current_state_for_uncond_probs[1] = r_t - number of ancestral species in neotropics in sameple history at time t
Only [1] = r_t is needed for this method.
@param upper an upper limit in the summation series
@param sigma set of all parameters for the model
for the model in mossEqModel.pdf, sigma = (lambda, b, B, alpha, mu), where
lambda is the turnover rate,
b = the migration rate,
B = the total number of species in state 0 (the boreal region)
alpha = the speciation rate in state 1 (the neotropical region), and
mu = the extinction rates in state 1 (the neotropical region).
Details
---------
Only 3 components of sigma are used (some are used ONLY to call CalculatePiStar and are
marked with *):
alpha sigma[3] = the speciation rate in state 1 (the neotropical region)
b *sigma[1] = the migration rate
mu *sigma[4] = the extinction rate in state 1 (the neotropical region)
Return value
------------
p(S_TT|q_t,r_t) = 2*alpha*C(r_t,2)*\sum_{k>=r_t}(PiStar_{k-1}/k)
"""
r_t=current_state_for_uncond_probs[1]
alpha=sigma[3]
coefficient = 2*alpha*comb(r_t,2)
sum=0
for k in range(r_t,upper):
sum=sum+ float(CalculatePiStar(k-1,current_state_for_uncond_probs,upper,sigma))/k
return coefficient*sum
def UncondProbSBB(current_state_for_uncond_probs, upper, sigma):
"""
Calculates p(S_BB | q_t), the probability of speciation event in the boreal region
that is captured in the history of the sample. This is simple
since boreal region maintains a constant fixed number of species,
conditioned on the fact that at time t, the number of ancestral species
in boreal region is q_t.
See eqn (17) in mossEqnModel.pdf
Input parameters
----------------
@param current_state_for_uncond_probs
[0] = q_t and [1] = r_t, see UncondProbSTT for details
@param upper upper limit in summation series, this is NOT needed.
I created this just so the method parameters are identical
@param sigma set of all parameters for the model
sigma = (lambda, b, B, alpha, mu)
See uncondProbSTT for more details
Details
--------
Only 2 components of sigma are used:
lam sigma[0] = rate of turnover in boreal region
B sigma[2] = the total number of species in boreal community (or state 0); an assumption
Return value
-------------
p(S_BB | q_t) = 2*lam*C(q_t,2)/B^2
"""
q_t=current_state_for_uncond_probs[0]
lam=sigma[0]
B=sigma[2]
return 2*lam*comb(q_t,2)/(B*B)
def UncondProbSBarrowT(current_state_for_uncond_probs, upper, sigma):
"""
Calculates p(S_{B->T}), the probability of migration of species
from the boreal to the neotropics region when the duplicate in the
boreal region does NOT appear in the sample.
See eqn (21) in mossEqModel.pdf
Input Parameters
----------------
@param current_state_for_uncond_probs
[0] = q_t and [1] = r_t, see UncondProbSTT for details
Both q_t and r_t are needed for this method.
Recall:
q_t = number of ancestral species in boreal region in the sample
history at time t
r_t = number of ancestral species in the neotropics
region in the sample history at time t
@param upper an upper limit in the summation series
@param sigma set of all parameters for the model
sigma = (lambda, b, B, alpha, mu)
See uncondProbSTT for more details
Details
--------
Only 4 components of sigma are needed (for instance, some are used only to call CalculatePi; they're marked with *):
B sigma[2] = the total number of species in boreal community (or state 0); an assumption
alpha *sigma[3] = birth rate of species in neotropical region when the number of species is i; positive constant
b **sigma[1] = migration rate (used in both methods)
mu *sigma[4] = death rate of species in neotropical region when number of species is i; positive constant
Return Value
-----------_
Returns p(S_{B->T}) = b*r_t*(1-q_t/B)*\sum_{k>=r_t}(pi_{k-1}/k)
"""
q_t = current_state_for_uncond_probs[0]
r_t = current_state_for_uncond_probs[1]
B = sigma[2]
b = sigma[1]
coef = b*r_t*(1-float(q_t/B))
sum=0
for k in range(r_t,upper):
sum=sum+CalculatePi(k-1,sigma)/k
return coef*sum
def UncondProbSBT(current_state_for_uncond_probs, upper, sigma):
"""
Calculates p(S_{BT} | n_t,q_t,r_t), the probability of migration
of species from the boreal to the neotropics region when the duplicate
in the boreal region also appears in the sample history, aka a
"pseudo-speciation" event in the history of the sample, conditioned
on n_t, q_t, r_t.
See eqn (22) in mossEqnModel.pdf
Input Parameters
----------------
@param current_state_for_uncond_probs
[0] = q_t and [1] = r_t, see UncondProbSTT for details
Both q_t and r_t are needed for this method.
Recall:
q_t = number of ancestral species in boreal region in the sample
history at time t
r_t = number of ancestral species in the neotropics
region in the sample history at time t
@param upper an upper limit in the summation series
@param sigma set of all parameters for the model
sigma = (lambda, b, B, alpha, mu)
See uncondProbSTT for more details
Details
--------
Only 4 components of sigma are needed (for instance, some are used only to call CalculatePi; they're marked with *. Those
marked with ** are used for both CalculatePi and UncondProbSBT):
B sigma[2] = the total number of species in boreal community (or state 0); an assumption
alpha *sigma[3] = birth rate of species in neotropical region when the number of species is i; positive constant
b **sigma[1] = migration rate (used in both methods)
mu *sigma[4] = death rate of species in neotropical region when number of species is i; positive constant
Return Value
-----------_
Returns p{S_{BT} | n_t,q_t,r_t} = b*r_t*q_t/B * \sum_{k>=r_t}(pi_{k-1}/k)
"""
q_t=current_state_for_uncond_probs[0]
r_t=current_state_for_uncond_probs[1]
B=sigma[2]
b=sigma[1]
coef = b*r_t*q_t/float(B)
sum=0
for k in range(r_t,r_t+ upper):
sum=sum+CalculatePi(k-1,sigma)/k
return coef*sum
def UnconditionalTransitionProbability(event, current_state_of_cond_jump_chain, sigma):
"""
Calculates the unconditioned probability (i.e., not conditioned on the
tree) of an event at the current state, based on Equation 23 (page 18).
Input parameters
----------------
current_state_of_cond_jump_chain is a 4-tuple (n_lineages_in_state_zero, n_lineages_in_state_one, state_of_next_coalescing_lineages_1, state_of_next_coalescing_lineages_2)
equivalent to (q, r, x_1, x_2) in
paragraph 3, page 19.
The next-coalescing
lineages are the two that are involved in the
next (going back in time) speciation event,
based on the input phylogenetic tree. See
paragraph entitled 'State spaces of conditional
jump chains' on page 19.
BUT NOTE THAT ONLY THE FIRST TWO
ELEMENTS, n_lineages_in_state_zero
and n_lineages_in_state_one, ARE
RELEVANT TO THIS FUNCTION, SINCE
ONLY UNCONDITIONAL PROBABILITIES
ARE BEING CALCULATED HERE.
event is one of the events in bigbig_H (see function GetEvents,
and also segment entitled "Events as operators", page 19.
basically, an event could be either:
'kappa' denoting a speciation involving the two
next-coalescing lineages.
's_bb' speciation events not involving both the
's_bt' next-coalescing lineages (see Section 3, bullet
's_tt' point entitled "Events", and also Figure 1 on page 6
'm_1' migration events involving the first and the
'm_2' second of the next-coalescing lineages
respectively.
's_b_arrow_t' any other migration event. The model in
mossEqModel allows only migrations of a
lineage from character state 0 to character
sigma is the set of model all parameters.
for the model in mossEqModel.pdf, sigma = (lambda, b, B, alpha, mu), where lambda is the
turnover rate, b is the migration rate, B is the total number of
species in state 0 (the boreal region, according to
mossEqModel.pdf), and alpha and mu are the speciation and
extinction rates, respectively, in state 1 (i.e., the
neotropical region).
Return value
------------
The probability of the given event happening when the chain is in state
current_state_of_cond_jump_chain, computed based on Equation 23 on page
18.
But note that the probability calculated is Pr(event | n_lineages_in_state_zero, n_lineages_in_state_one)
i.e., the probability is not conditioned on the state of the next-coalescing lineages.
Details
-------
Since the function calculates unconditioned probabilities,
event 'kappa' is treated as (a) 's_tt' if the state of the two
next-coalescing lineages is (1, 1).
(b) 's_bb' if the state of the
next-coalescing lineages is (0, 0)
(c) 's_bt' is the state of the
next-coalescing lineages is (1, 0) or
(0, 1)
events 'm_1' and 'm_2' are both treated as 's_b_arrow_t'.
"""
# current state that's relevent for the computation of unconditional
# probabilities. Assuming n_lineages_in_state_zero and
# n_lineages_in_state_one are the first two elements in
# current_state_of_cond_jump_chain
##I fixed a typo
current_state_for_uncond_probs = current_state_of_cond_jump_chain[0:2]
# In python the set() statement makes a set from a list.
set_of_events = set(['s_tt', 's_bb', 's_b_arrow_t', 's_bt'])
# This is a map from events to *instantaneous rates*
# I am suggesting a python dictionary implementation.
# This is just an initialization. Eventually
# these are to be calculated using Equations 13, 17, 21, 22 in Section 5.1
dictionary_event_to_instantaneous_rate = {'s_tt': 1.0, 's_bb': 1.0, 's_b_arrow_t': 1.0, 's_bt': 1.0}
# dictionary_event_to_function is a map from events to the functions that will calculate the
# instantaneous rate for the event.
# python allows these kind of dictionaries. But any way, I am using
# features that are really specific to python because it is easy to
# express the intuition in python syntax. But it doesn't mean we have
# to stick to this implementation.
# UncondProbSTT implements Equation 13.
# UncondProbSBB implements Equation 17.
# UncondProbSBarrowT implements Equation 21.
# UncondProbSBT implements Equation 22.
dictionary_event_to_function = {'s_tt': UncondProbSTT, 's_bb': UncondProbSBB, 's_b_arrow_t': UncondProbSBarrowT, 's_bt': UncondProbSBT}
# e loops over events in set(['s_tt', 's_bb', 's_b_arrow_t', 's_bt'])
# we will also need the sum of all rates, for calculating the
# probabilities from rates (basically, the sum is the denominator is
# Eq. 23).
sum_of_rates = 0.0
for e in set_of_events:
# Call UncondProbSTT, UncondProbSBB, UncondProbSBarrowT or
# UncondProbSBT depending on what the event is.
uncond_rate = dictionary_event_to_function[e](current_state_for_uncond_probs, sigma)
dictionary_event_to_instantaneous_rate[e] = uncond_rate
sum_of_rates += uncond_rate
# This is basically Eqn. 23, with the numerator and denominator.
probability_of_event = dictionary_event_to_instantaneous_rate[event]/sum_of_rates
return(probability_of_event)
def MakeState2IndexDictionary(level_number):
"""
Returns a dictionary (or map) between the state (key) and the index (value)
for a given level
The state is the four-element tuple (q_t, r_t, x_1, x_2), represented by ().
Since tuples are immutable objects, they can be used as keys.
The index is the numerical index used in MakeTupleList.
Input parameters
----------------
1.level number The level for which the state to index dictionary
is computed
Details
--------
So when this method is called:
x = MakeState2IndexDictionary(2)
print x #Prints {'0,2,0,1': 3, '0,2,0,0': 0, '2,0,1,0': 11,
'2,0,1,1': 8, '1,1,0,1': 4, '1,1,0,0': 1, '0,2,1,0': 9,
'0,2,1,1': 6, '1,1,1,0': 10, '1,1,1,1': 7, '2,0,0,1': 5,
'2,0,0,0': 2}
y = x['1,1,1,0']
print y #Prints 10
Return value (s)
---------------
A dictionary matching strings representing states of the conditional
jump chain to indices in the transition matrix
Details
-------
Here, strings represent states which correspond to 4-tuples.
For example, state=4-tuple=[0,3,0,1] is represented by '[0,3,0,1]'
"""
tuple_list=MakeTupleList(level_number)
tuple_string_dictionary={}
for i in range(len(tuple_list)):
tuple_string_dictionary[tuple_list[i]]=i
return(tuple_string_dictionary)
def MakeTupleList(level_number):
"""
Creates a list of all the possible 4-tuples states for a given level
and then creates a one-to-one correspondence between state numbers and
the all possible 4-tuple states
Input parameters
----------------
1. level number The level for which the dictionary is computed
Return value (s)
----------------
A array matching indices to 4-tuple states
"""
tuples=range(4*(level_number+1))
j=0
for i in range(level_number+1):
tuples[i]=(i,level_number-i,0,0) #A tuple is represented by (), not [], as before
for i in range(level_number+1):
j=i+1*(level_number+1)
tuples[j]=(i,level_number-i,0,1)
for i in range(level_number+1):
j=i+2*(level_number+1)
tuples[j]=(i,level_number-i,1,1)
for i in range(level_number+1):
j=i+3*(level_number+1)
tuples[j]=(i,level_number-i,1,0)
return(tuples)
def ReverseMap(level_number):
"""
Returns a dictionary (or map) between the index (key) and the state (value)
for a given level
The index is the numerical index used in the list MakeTupleList.
The state is the four-element tuple (q_t, r_t, x_1, x_2)
Makes and returns the index to state dictionary for a given level
Input parameters
----------------
1.level number The level for which the state to index dictionary
is computed
Return value (s)
---------------
A dictionary matching indices in the transition matrix to strings representing states of
the conditional jump chain
***in this case indices could be matched to lists representing states of the conditional
jump chain instead of strings representing states of the conditional jump chain
Details
-------
Here, strings represent states which correspond to 4-tuples.
For example, state=4-tuple=[0,3,0,1] is represented by '0,3,0,1'
"""
tuple_list=MakeTupleList(level_number)
tuple_string_dictionary={}
for i in range(len(tuple_list)):
tuple_string_dictionary[i] = tuple_list[i]
return(tuple_string_dictionary)
def PickNextStateofChain(row_of_transition_matrix):
"""
"""
return((0, 0.0))
def WhetherInTheSameLevel(state1, state2):
"""
"""
return(False)
def ChooseLineageandUpdateDelta(current_delta):
"""
"""
return(None)
def MovetoNextLevel(current_delta, current_level, next_level):
"""
"""
return(())
def MakeTransitionMatrixForLevel(level_number, sigma):
"""
Makes and returns the transition probability matrix for a given level
Section 5 of mossEqModel.pdf is devoted to this.
Input parameters
----------------
1. level number The level for which the transition matrix is
computed.
2. sigma is the set of model all parameters.
for the model in mossEqModel.pdf, sigma = (lambda, b, B, alpha, mu), where lambda is the
turnover rate, b is the migration rate, B is the total number of
species in state 0 (the boreal region, according to
mossEqModel.pdf), and alpha and mu are the speciation and
extinction rates, respectively, in state 1 (i.e., the
neotropical region).
Return value(s)
---------------
a 3-tuple: (transition_matrix, state_to_index_in_transition_matrix, index_in_transition_matrix_to_state)
transition_matrix 4(k+1)+1 x 4(k+1)+1 matrix of floats, where
k = level number
state_to_index_in_transition_matrix is a map from the states of the
jump chain (but only those that are relevant
at the given le
vel) to
integers, i.e., basically a numbering of the states.
This is so that the transition matrix can be
indexed with integers.
index_in_transition_matrix_to_state is the inverse map of
state_to_index_in_transition_matrix
Details
-------
When the conditional jump chain is in level k (i.e., the total
number of lineages = k), the number of states at that level is 4(k+1) (see
paragraph 3, page 19). Besides transitioning within level k, i.e.,
among its 4(k+1) states, the chain can also effect precisely one
transition to a state in level k-1, representing the speciation involving the two
next_coalescing_lineages whose character states (whether 0/1) are
represented in state_of_cond_jump_chain. We add this state as the
4(k+1)+1-th state in the transition matrix.
The precise identity of this state in level k-1 does not matter.
All that we need is to be able calculate the probability of the
above-mentioned speciation event from each of the 4(k+1) states in level k.
"""
# k is just an alias for level_number
k = level_number
# first create a map between the states and their indices in the
# transition matrix. In python, this can be implemented as a
# dictionary. All the states in a level can be figured out from the
# level number.
state_to_index_in_transition_matrix = MakeState2IndexDictionary(level_number)
# also make the reverse map.
##I changed input of the next function from state_to_index_in_transition_matrix to level_number
index_in_transition_matrix_to_state = ReverseMap(level_number)
# The set of possible types of events.
# bigbig_K is the set of various types of speciation events.
# bigbig_M is the set of various types of migration events.
# bigbig_H is the union of the above two sets.
# See function GetEvents() for more details.
# Also see Page 19, segment entitled "Events as operators on states".
(bigbig_K, bigbig_M, bigbig_H) = GetEvents()
# ========================================================================
# Begin Task: Solving the system of equations represented by Equation 25 #
# ========================================================================
# Equation 25 is a system of 4(k+1) equations in 4(k+1) unknowns.
# The unknowns are Pr(F|z) for each state z in the level-k state space,
# where F is the event that no speciation events occur prior to the
# one involving the two known next-coalescing lineages.
#
#
# For ease of description, let the states in Z_k be states z_0
# through z_{4(k+1)-1}. Now, if we look at Equation 25, each unknown z_i
# occurs with a coefficient of 1 in exactly one equation. In all
# other equations, its coefficient is either 0 or negative. We will
# call the one equation where the coefficient of z_i is positive
# "the equation corresponding to z_i" or simply "equation z_i." In
# Equation 25, what comes after "for all z in Z_k" is the equation
# corresponding to z.
# _0 through z_{4(k+1)-1} and for each
# state we generate its corresponding equation. We will then
# collect all the equations and stick them in an equations-solver
# and get out the answers.
# first get the entire state space of the conditional jump chain at
# level k. The state space depends only on k, the total number of lineages, and
# can be calculated from state_to_index_in_transition_matrix
#
# Note: state_space_at_the_current_level must be such that:
# 1. length(state_space_at_the_current_level) = 4(k+1)
# 2. if state_space_at_the_current_level[j] = z, then state_to_index_in_transition_matrix[z] = j
# Basically, the states should be listed in
# state_space_at_the_current_level according to their indices in
# state_to_index_in_transition_matrix.
# The asserts following this statement verifies this.
# If the condition inside the assert statement fails, the program
# will exit at this point.
state_space_at_the_current_level = GetCondJumpChainStateSpace(level_number)
assert(len(state_space_at_the_current_level) == 4*(k+1))
# In python, range(0, n) = [0, 1, 2, ..., n-1]
for j in range(0, 4*(k+1)):
assert(state_to_index_in_transition_matrix[state_space_at_the_current_level[j]] == j)
# I am using the python map syntax.
# For example, if I say squares = [j**2 for j in [0, 1, 2, 3]], then
# squares = [0, 1, 4, 9]. Similarly, system_of_equations will be a
# list of equations one for each unknown z_i.
# GetLinearEquation(z, state_of_cond_jump_chain)
# could (I am saying 'could' because this is a suggested representation, and the actual
# implementation can change - Ganesh) return an
# equation in the form of a vector of length 4(k+1)+1, where the
# i-th element of the vector is the coefficient of the unknown z_i,
# and the last element is the constant in the equation.
system_of_equations = [GetLinearEquation(z, state_of_cond_jump_chain) for z in state_space_at_the_current_level]
# May be we can use an equation solver from scipy?
# In any case, solution *must* be a vector of length 4(k+1), such that
# solution[j] = Pr(F | z) where z = state_space_at_the_current_level[j]
solution = LinearEquationSolver(system_of_equations)
# ======================================================================
# End Task: Solving the system of equations represented by Equation 25 #
# ======================================================================
# =================================================================
# Begin Task: Calculating the transition matrix using Equation 24 #
# =================================================================
# make a 2-dimensional array of dimensions 4(k+1)+1 x 4(k+1)+1
# Make2DimensionalArray should initialize the array with 0.0
transition_matrix = Make2DimensionalArray(4*(k+1)+1)
# This is to make sure that the array is initialized properly.
# In python, range(0, n) = [0, 1, 2, ..., n-1]
for j in range(0, 4*(k+1)+1):
# assert that each row sums to 0.0. If the assert fails, the
# program will exit at this point
assert(sum(transition_matrix[j]) == 0.0)
# The following loop fills out the transition matrix state by state.
# Each state corresponds to a row in the matrix.
# Thus, each iteration of the following for loop handles one row of the
# transition matrix.
#
# Remember that state_space_at_the_current_level contains the 4(k+1) states at
# the level k. It does not include the one state at level k-1 the chain
# might transition to. But we need not fill the row corresponding to
# that state (the one in level k-1) because no transitions are possible *from* that state,
# and appropriately the probabilities in that row are already initialized to 0.0
#
# Variables z and w have the same meaning that they have in Equation
# 24. z loops over all states in Z_k, and w loops over all events in
# bigbig_H
for z in state_space_at_the_current_level: