-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcjumpchain.py
executable file
·2779 lines (2351 loc) · 117 KB
/
cjumpchain.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/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()b
# 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 numpy import * #sum, zeros, eye, array, allclose
from scipy.misc import * #comb, factorial
from scipy.linalg import solve
import random
import sys
import math
#These strings are supposed to be constants.
SMALLER_S_BT = "smaller_s_bt"
SMALLER_S_TT = "smaller_s_tt"
SMALLER_S_BB = "smaller_s_bb"
KAPPA = "kappa"
M_1 = "m_1"
M_2 = "m_2"
SMALLER_S_B_ARROW_T = "smaller_s_b_arrow_t"
S_BT = "s_bt"
S_BB = "s_bb"
S_TT = "s_tt"
S_B_ARROW_T_GLOBAL = "s_b_arrow_t_global"
#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 Equal(a, b):
"""
For testing purposes only, equal if float a and float b are close
enough they're identically equal
"""
return abs(a-b) < a*1e-7
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)
return -1
def LogFactorialOfNegative(z,terms=20):
"""
Returns an approximation of the log(factorial) any real number that is not a non-positive integer
Input paramters
---------------
z any number that is not a non-positive integer
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. Returns the log(factorial(z))
Details
-------
If z+1 is negative: Make z positive for the calculations. Then if floor(z) is even, the approxiimation
would have been negative if carried out to a number of terms greater than floor(z),
so return 1/approx. Otherwise, if floor(z) is odd, the approximation would have
been positive if carried out to a number of terms greater than floor(z), so return approx.
I.E. log((-a)^even_num)=even_num*log(a); log((-a)^odd_num)=1/(odd_num*log(a))
"""
z=float(z)
z=z+1
if(z>0):
fact=math.log(1/(z),10)
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),10)
return fact
if(z==0):
return 1
if(z<0):
z=-z
#above line * for future reference
fact=math.log(1/(z),10)
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),10)
if(math.fmod(math.floor(z),2)==0):
return 1/fact
#because there is one more negative term in *
else:
return fact
#because * makes the total number of negative #s multiplied even
def CombOfNegative(n,k,terms=20):
"""
An approximation of the Combination function using FactorialOfNegative
Input
-----
n any real number that is not a non-negative integer and such that n-k is not
a non-negative integer
k any real number that is not a non-negative integer and such that n-k is not
a non-negative integer
Output
------
n choose k
"""
log_n_fact=LogFactorialOfNegative(n,terms)
log_k_fact=LogFactorialOfNegative(k,terms)
log_n_fact_over_k_fact=log_n_fact-log_k_fact
log_n_minus_k_fact=LogFactorialOfNegative(n-k,terms)
#print(str(pow(10,log_n_fact_over_k_fact-log_n_minus_k_fact))+" comb of Neg");
return pow(10,log_n_fact_over_k_fact-log_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.
#Notice that I erased 's_tt', 's_bb', 's_bt' b/c
#kappa+smaller_s_tt = s_tt
#kappa+smaller_s_bt = s_bt
#kappa+smaller_s_bb = s_bb
bigbig_K = set([KAPPA, SMALLER_S_TT, SMALLER_S_BT, SMALLER_S_BB])
# 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
#Again, SMALLER_S_B_ARROW_T = m_1+m_2
bigbig_M = set([M_1, M_2, SMALLER_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 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 list of 4-element tuple (q_t, r_t, x_1, x_2)
"""
tuples=range(4*(level_number-1))
j=0
for i in range(level_number+1):
if((i!=0)&(i!=1)):
tuples[i-2]=(i,level_number-i,0,0)
#print(i-2)
for i in range(level_number+1):
if((i!=0)&(i!=level_number)):
j=(i-1)+1*(level_number-1)
#print(j)
tuples[j]=(i,level_number-i,0,1)
for i in range(level_number+1):
if((i!=level_number-1)&(i!=level_number)):
j=i+2*(level_number-1)
#print(j)
tuples[j]=(i,level_number-i,1,1)
for i in range(level_number+1):
if((i!=0)&(i!=level_number)):
j=(i-1)+3*(level_number-1)
#print(j)
tuples[j]=(i,level_number-i,1,0)
return(tuples)
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 tuples representing states of the conditional
jump chain to indices in the transition matrix
"""
tuple_list=MakeTupleList(level_number)
state_to_index_dictionary={}
for i in range(len(tuple_list)):
state_to_index_dictionary[tuple_list[i]]=i
return(state_to_index_dictionary)
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 tuples representing states of
the conditional jump chain
"""
tuple_list=MakeTupleList(level_number)
index_to_state_dictionary={}
for i in range(len(tuple_list)):
index_to_state_dictionary[i] = tuple_list[i]
return(index_to_state_dictionary)
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
to the four-element tuple (called "state", i.e. (q_t,r_t,x_1,x_2)
in state_to_index_in_transistion_matrix dictionary.
Details
-------
Note in here the "state" means the four-element tuple (q_t,r_t,x_1,x_2) where
q_t and r_t are the species in boreal and neotropical regions, respectively. And
x_1 and x_2 are the "transition states" of the two next-coalescing species.
Thus "transition states" here refer to boreal (state 0) and neotropical (state 1)
regions. Going FORWARD in time, only transition from state 0 to state 1 is
possible. Going BACKWARD in time, only transition from state 1 to state 0 is
possible.
From now on we will call such state the "four-element tuple" to avoid confusion
with "transition states."
"""
state_space=range(4*(level_number-1))
index_to_state_map=ReverseMap(level_number)
for i in range(len(state_space)):
state_space[i]=index_to_state_map[i]
return(state_space)
def IsValidState(z,level):
"""
Tests whether the four-element tuple is a state in the jump chain.
Input Parameters
----------------
z A state in the jump chain in the current_level,
or the four-element tuple, (q_t, r_t, x_1, x_2). See ApplyEvent()
for more details.
level The current level
Details
--------
Some sample states that are NOT valid include:
(5,0,1,0), (4,1,1,1), (0,2,0,1), (5,1,1,1)
Note we assume x_1 and x_2 are correctly from (0,1). This "validity"
refers more to states that not possible due to configuration, not
due to misspelling or typos. For instance, (5,0,1,0) is an invalid state
b/c next-coalescing lineage1's state is 1 and there is no state 1 overall.
Return Value
------------
True if the state is a valid state, false otherwise.
"""
q_t = z[0]
r_t = z[1]
x_1 = z[2]
x_2 = z[3]
if (x_1==1 and x_2==1 and r_t<2):
return False
if (x_1==0 and x_2==0 and q_t<2):
return False
if (x_1==1 and r_t<1):
return False
if (x_2==1 and r_t<1):
return False
if (x_1==0 and q_t<1):
return False
if (x_2==0 and q_t<1):
return False
if (x_1>1 or x_1<0 or x_2>1 or x_2<0):
return False
if(q_t<0 or r_t<0):
return False
if(q_t+r_t>level):
return False
return True;
def ApplyEvent(z,w,level):
"""
Returns the state that results when event w is applied to state z, i.e.,
w(z) in eqn (24). The result is also a four-element tuple.
Input Parameters
----------------
level The current level
z A state in the jump chain in the current_level,
or the four-element tuple, (q_t, r_t, x_1, x_2) where
q_t is the number of current lineages in boreal region (state 0)
r_t is the number of current lineages in neotropics region (state 1)
x_1 is the state transition (0 or 1) of the first of the
next-coalescing lineages pair
x_2 is the state transition (0 or 1) of the second of the
next-coalescenct lineages pair
w w is an event that acts on the state in the jump chain. As discussed in
page 20 eqn (24), we could view an event as an operator on the
state. w could be:
Speciation Events (collectively known as bigbig_K):
KAPPA The coalescence (convergence going backwards in time,
or speciation going forward in time) of next-coalescing
lineages
SMALLER_S_TT The coalescence of lineages in (t,t,), (b,b) and (b,t) which aren't the next coalescing lineages.
SMALLER_S_BB Note1: (b,t) is really a pseudo speciation event.
SMALLER_S_BT Note2: these events cannot occur in the current model
Migration Events (collectively known as bigbig_M):
M_1 migration of next-coalescing lineage1, the first lineage
in the next-coalescing lineage pair
M_2 migration of next-coalescing lineage2
"s_b_arrow_t" any other migration
We denote bigbig_H = bigbig_K UNION bigbig_M
So w could be any of the events in bigbig_H.
Details
--------
Note: This is NOT P(F | w(z))!!!. This is simply the state w(z) in the
expression. We calculate probability based on what we know about w(z).
When the method returns (-1, -1, -1, -1) it means it w(z) is not possible -
it is not possible to go from z to w(z).
Return values
-------------
The state that results when an event happens to state z. Also a four-element
tuple, just like z.
Details
-------
IMPORTANT:SMALLER_S_BT, SMALLER_S_BB, and SMALLER_S_TT can never occur in the backwards probability calculation.
Therefore, return (-1,-1,-1,-1) as a signifier of an error. Also, return (-1,-1,-1,-1)
if the input current state, z, is not valid, or if w, the transition, is not a valid event.
"""
q_t = z[0]
r_t = z[1]
x_1 = z[2]
x_2 = z[3]
if (IsValidState(z,level)==False):
return (-1,-1,-1,-1)
if (w==SMALLER_S_BT or w==SMALLER_S_BB or w==SMALLER_S_TT):
#Since these events while going backwards have probability zero in the current model, return (-1,-1,-1,-1)
return (-1,-1,-1,-1)
if (w==KAPPA):
if (x_1==1 and x_2==1):
new_state= (q_t, r_t-1, -1, -1)
#(q_t, r_t, x_1, x_2) --> (q_t, r_t-1, UNDEFINED, UNDEFINED)
if(q_t>-1 and r_t-1 >-1):
return new_state
else:
return (-1,-1,-1,-1)
if ((x_1==1 and x_2==0) or (x_1==0 and x_2==1)):
new_state=(q_t,r_t-1, -1, -1)
if(q_t>-1 and r_t-1 >-1):
return new_state
else:
return (-1,-1,-1,-1)
if (x_1==0 and x_2==0):
new_state= (q_t-1, r_t, -1, -1)
if(q_t-1 >-1 and r_t >-1):
return new_state
else:
return (-1,-1,-1,-1)
if(w==M_1):
if(x_1==1):
#(q_t,r_t,x_1,x_2) --> (q_t,r_t,0,x_2)
tuple = (q_t+1, r_t-1, 0, x_2)
if (IsValidState(tuple,level)==False):
return (-1,-1,-1,-1)
else:
return tuple
else:
#x_1 must have state 1
return (-1,-1,-1,-1)
if(w==M_2):
if(x_2==1):
tuple = (q_t+1,r_t-1,x_1,0)
if (IsValidState(tuple,level)==False):
return (-1,-1,-1,-1)
else:
return tuple
else:
#x_2 must have state 1
return (-1,-1,-1,-1)
if(w==SMALLER_S_B_ARROW_T):
#IMPORTANT!!!!
#Here I take SMALLER_S_B_ARROW_T to mean NOT M_1 NOR M_2, that is:
#M_1, M_2 and "smaller_s_b_arrow_t" form an disjoint set!
#Only true for conditional probability. For uncondtional ones,
#M_1 and M_2 ARE s_b_arrow_t events. But for
#conditional cases, "s_b_arrow_t" really means those "s_b_arrow_t"
#events EXCLUDING M_1 and M_2.
tuple = (q_t+1,r_t-1,x_1,x_2)
if (IsValidState(tuple,level)==False):
return (-1,-1,-1,-1)
return tuple
return (-1,-1,-1,-1)
# w was not a valid event
def Make2DimensionalArray(dimension):
"""
Make a 2-dimensional square array of dimensions with all
slots initialized to 0.0. Number of rows should equal to
the number of columns in the array.
Input Parameters
----------------
dimension An integer, indicating the "width" of the square array
Details
--------
This is used to initialize the transition_matrix used in
MakeTransitionMAtrixForLevel method.
An two-dimension array is really a list of a list.
Return Value
----------------
A two-dimensional square array with all slots initialized to 0.0.
"""
#Old implementation, now obsolete but still want to keep the refernece:
#Taken from http://mail.python.org/pipermail/python-list/2000-December/063456.html
#matrix= [([0.0] * dimension)[:] for i in range(dimension)]
#New implementation, using zeros method in Numpy
matrix = zeros( (dimension,dimension) )
#Explanation: [([2] * 5)[:] for i in range(3)] creates an the matrix
#[[2, 2, 2, 2, 2], [2, 2, 2, 2, 2], [2, 2, 2, 2, 2]]
#that is, a 3-element list, each of whose element is a list [2]*5.
#Note that this creation ensures that each [2,2,2,2,2] is independent of
#each other.
return matrix
def GetLinearEquations(state_space_at_current_level,sigma, level):
"""
Output a constant vector (made up of kappa_ij 's), and
a dimension*dimension matrix each row of which
composes of coefficients of the unknown (which in this case is
P(F|z)
Input Parameters
-----------------
state_space_at_current_level
A list containing
all the states (4-tuples)
at the current level (e.g. level 5),
really generated by the
GetCondJumpChainState(level) method
See comments in MakeTransitionMatrixForLevel
for more details.
level the current level
Output value
-------------
Return (A,b) where A is a level_number*level_number matrix, and b is a constant vector
(i,j) of A represents a transition from state with index i to state with index j
Details
--------
Get the necessary ingredients about the systems
of equations to plug into the LinearEquationSolver
The systems of equations are:
for all z in Z_k,
P(F|z) = sum_{w in M} P(w|z)*P(F|w(z)) + P(k_ij | z)
where P(F|z) and P(F|w(z) are unknowns (could be different or same),
and P(k_ij | z) and P(w|z) are knowns
Now, by our CONSTRUCTION (more like assumption),
(M_1, M_2, "s_b_arrow_t") are DISJOINT SETS in
conditional probability cases, we have, after rearranging terms:
P(k_ij | z) = P(F|z) - sum_{w in M} P(w|z) * P(F|w(z)) for all z in Z_k
= P(F|z) - P(M_1|z)*P(F|M_1(z)) - P(M_2|z)*P(F|M_2(z))
- P("s_b_arrow_t"|z)*P(F|"s_b_arrow_t"(z))
There are 4(k-1) such z's, because w(z) WILL be inside
M by our construction, and if it's not, we simply ignore it in our
computation (b/c we would get (-1,-1,-1,-1) if it's not
in the current state or an invalid state from ApplyEvent()). And
when m(z) is undefined, we would treat P(w|z) as 0
So we can create a 4(k-1) by 4(k-1) matrix called A,
filled with coefficients of various P(F|z)'s in each row.
How do we fill out matrix A?
For instance, suppose there are 5 equations of the following format
x_0 = 4 + 3x_0 + 11x_3 + 8x_4
x_1 = 8 + 2x_1 + 10x_3
x_2 = 17
x_3 = 25 + 3x_1 + 12x_3 + 22x_2
x_4 = 0 + 3x_3
Rearranging, we get:
4 = x_0 - 3x_0 - 11x_3 - 8x_4
8 = x_1 - 2x_1 - 10x_3
17 = x_2
25 = x_3 - 3x_1 - 12x_3- 22x_2
0 = x_4 - 3x_3
We want to eventually turn it into the form that:
[4,8,17,25,0].transpose() = [[-1, 0, 0, -11, -8], * [x_0,x_1,x_2,x_3,x_4].transpose
[0, -1, 0, -10, 0],
[0, 0, 1, 0, 0],
[0, -3, -22, -11, 0],
[0, 0, 0, -3, 1]]
We call the LHS b, and the 5x5 matrix A, we would output (A, b)
"""
length = len(state_space_at_current_level)
constant_vector = [UnconditionalTransitionProbability(KAPPA,z,sigma) for z in state_space_at_current_level]
#when level_number=2,
#we have state_space_at_current_level = [(2, 0, 0, 0), (1, 1, 0, 1), (0, 2, 1, 1), (1, 1, 1, 0)]
#and constant_vector = [1.0, 0.00049975012493753122, 0.058823846204939162, 0.00049975012493753122]
#First create a level by level matrix with diagonal
#initialized to 1's and rest 0's Fill in the diagonals with 1's
#We really want the coefficients to be ints.
matrix = eye(length,length, dtype=float)
#Fill in the coefficient P(M_1|z) into cell matrix[index of z][index of w(z)]
#First, create a Probability of w given Z vector
prob_m1_vector = [-UnconditionalTransitionProbability(M_1, z, sigma) for z in state_space_at_current_level]
prob_m2_vector = [-UnconditionalTransitionProbability(M_2, z, sigma) for z in state_space_at_current_level]
prob_s_b_arrow_t_vector = [-UnconditionalTransitionProbability(SMALLER_S_B_ARROW_T, z, sigma) for z in state_space_at_current_level]
#print "prob_m1_vector is: " + str(prob_m1_vector)
#print "prob_m2_vector is: " + str(prob_m2_vector)
#print "prob_s_b_arrow_t_vector is: " + str(prob_s_b_arrow_t_vector)
#For instance, when level=2, prob_s_b_arrow_t is
#[0.0, 0.99950024987506236, 0.94117615379506092, 0.99950024987506236]
#Remember prob_w_given_z_vector does not depend on (x_1,x_2)
#This way, prob_w_given_z[3] refers to the probability of
#w_given_z_vector for the third element in state_space_at_current_level,
#or really state_space_at_current_level[2]
m1_vector = [ApplyEvent(z,M_1,level) for z in state_space_at_current_level]
m2_vector = [ApplyEvent(z,M_2,level) for z in state_space_at_current_level]
s_b_arrow_t_vector = [ApplyEvent(z,SMALLER_S_B_ARROW_T,level) for z in state_space_at_current_level]
#print m1_vector
#print m2_vector
#print s_b_arrow_t_vector
#For instance, the following code
#state_space_at_current_level = GetCondJumpChainStateSpace(2)
#print state_space_at_current_level
#s_b_arrow_t_vector = [ApplyEvent(z,"s_b_arrow_t") for z in state_space_at_current_level]
#generates:
#state_space_at_current_level = [(2, 0, 0, 0), (1, 1, 0, 1), (0, 2, 1, 1), (1, 1, 1, 0)]
#s_b_arrow_t_vector = [(-1, -1, -1, -1), (2, 0, 0, 1), (1, 1, -1, -1), (2, 0, 1, 0)]
#So s_b_arrow_t_vector is an "ordered" list of the w(z)'s.
level_number = length/4 + 1
state_to_index_map = MakeState2IndexDictionary(level_number)
#print "state_to_index_map[(1,2,0,1)] is: " + str(state_to_index_map[x])
assert(length == len(state_space_at_current_level) == len(prob_m1_vector) == len(m1_vector))
for row in range(length):
#for each row in the matrix, only fill in 3 numbers
#So this implementation is faster than going through the
#entire matrix
if (m1_vector[row]!=(-1,-1,-1,-1)):
#Otherwise, keep it 0
index_of_m1 = state_to_index_map[m1_vector[row]]
matrix[row,index_of_m1] = prob_m1_vector[row]
if (m2_vector[row]!=(-1,-1,-1,-1)):
#Otherwise, keep it 0
index_of_m2 = state_to_index_map[m2_vector[row]]
matrix[row,index_of_m2] = prob_m2_vector[row]
if (s_b_arrow_t_vector[row]!=(-1,-1,-1,-1)):
#Otherwise, keep it 0
index_of_s_b_arrow_t = state_to_index_map[s_b_arrow_t_vector[row]]
matrix[row,index_of_s_b_arrow_t] = prob_s_b_arrow_t_vector[row]
return (matrix, constant_vector)
def LinearEquationSolver(A, b):
"""
Solve system of linear equations given A*x = b, outputs x in vector
form.
Input parameters
----------------
A A square matrix
b A column vector
Output Value
------------
Solution to the system of equations A*x = b. Outputs x which is a
vector.
"""
return solve(A,b)
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 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).
Return Value
----------
p_j, or the probability that the equilibrium number of species equals j given
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
if log_pi=-1, then pi=0 (since the log of 0 is undefined).
"""
log_pi=CalculateLogPi(j_species,sigma)
alpha = sigma[3]
mu = sigma[4]
if (log_pi == -1):
return 0;
return(pow(alpha/mu,log_pi))
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).
Return value
-------------
The log base alpha/mu of p_j, where p_j is defined as
p_j = C(b/alpha + j - 1,j)*(alpha/mu)^j*(1-alpha/mu)^(-b/alpha)
if alpha=mu, -1, a flag is returned (since log of zero, and log base 1 is undefined)
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
if alpha=mu, pi will be always zero, and CalculateLogPi returns -1, a flag that alpha=mu
We want to calculate pi_j = C(b/a+j-1,j)*(a/u)^j*(1-a/u)^(-b/a)
so we take log_a/u of pi_j, which prevents (a/u)^j from becoming
0 when j is large (i.e. when j=1500).
Thus x = log_{a/u} pi_j = log_{a/u} C(b/a+j-1,j) + j + log_{a/u} (1-a/u)^(-b/a)
This functions returns x.
CalculatePi returns pi_j = (a/u)^x, by simply calling
this helper class.
"""
alpha = sigma[3]
b = sigma[1]
mu = sigma[4]
coefficient=1;
if(alpha>mu):
#print("Error, alpha is greater than mu")
return -2
if (alpha== mu):
return -1
if(b<alpha):
combination= float(CombOfNegative(b/alpha+j_species-1,j_species))
else:
combination = float(comb(b/alpha+j_species-1,j_species))
#print(combination);
#print(alpha/mu);
try:
coefficient = math.log(combination,alpha/mu)
except OverflowError:
print("beta "+str(b));
print("j_species "+str(j_species));
print("alpha "+str(alpha));
print("mu "+str(mu));
print("combination "+str(combination)+" base "+str(alpha/mu));
ratio = float(j_species)
ratio2 = -b/alpha*math.log(pow(float(1-alpha/mu),1),alpha/mu)
return coefficient+ratio+ratio2
#I got this function from R documentation
def LogSum(logX,logY,base):
"""
Input Parameters
----------------
logY the log of x with base=base, i.e., log_base X
logY the log of y with base=base, i.e., log_base Y
base the base of the logs of x and y
Return Value
------------
log_base (X+Y)
Details
-------
Note: log_x and log_y must share a common base.
For instance, if logX = 3 = log_2 8
logY = 4 = log_2 16
then LogSum(3,4,2) = log_2 (24) = 4.585
This equality and function were obtained from the R function logSum in the package TileHMM
"""
temp = 1 + pow(base,logY-logX)
return logX + math.log(temp,base)
def CalculateLogPiStar(n_t, current_state_for_uncond_probs, sigma, num_sum=20):
"""
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 num_sum the number of summations to be done, the upper limit of summation is r_t+num_sum
@param sigma set of all parameters for the model
sigma = (lambda, b, B, alpha, mu)
See CalculateLogPi 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)
See CalculateLogPi for theoretical details.
Here we are calculating
LogPiStar = log_{a/u} pi_j - log_{a/u} (sum of a bunch of pi's)
= log_{a/u} pi_j / (sum of a bunch of pi's)
Return value
-------------
The log of piStar, where piStar is defined as:
p(n_t | q_t, r_t)= pi_n_t / sum_{k>=r_t}(pi_k);
Note that piStar 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]
alpha = sigma[3]
mu = sigma[4]
log_numerator = CalculateLogPi(n_t,sigma)
log_denominator = CalculateLogPi(r_t,sigma)
for i in range(r_t+1, r_t+num_sum):
log_denominator=LogSum(log_denominator,CalculateLogPi(i,sigma),alpha/mu)
return log_numerator-log_denominator
def CalculatePiStar(n_t, current_state_for_uncond_probs, sigma, num_sum=20):
"""
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
current_state_for_uncond_probs[1] = r_t
Note: only [1]=r_t is needed.
@param num_sum the number of summations to be done, the upper limit of summation is r_t+num_sum
@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)
This returns the piStar value using the helper method
CalculateLogPiStar
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.
"""
alpha = sigma[3]
mu = sigma[4]
logPiStar = CalculateLogPiStar(n_t, current_state_for_uncond_probs, sigma, num_sum=20)
return pow(alpha/mu,logPiStar)
"""
The old way of calculating PiStar
Note that CalculatePiStar is the "new", logarithmic way of testing
For testing purposes only.
Details
------------
current_state_for_uncond_probs = [1500,1500]
num_sum=20
#sigma = (lambda, b, B, alpha, mu)
sigma=(.1, .1, 1000, .05, .1)
print CalculateLogPi(1500,sigma)
numerator = CalculatePi(1500,sigma)
print numerator==0 //True! That's why we use logs instead of
adding up all the Pi's, b/c numerator
and denominators are all 0s.
"""
r_t = current_state_for_uncond_probs[1]
numerator = CalculatePi(n_t,sigma)
denominator=0.0
for i in range(r_t, r_t+num_sum):
denominator=denominator+CalculatePi(i,sigma)