table 4.3 K80ΒΆ

For a K80 model of molecular evolution along a fixed evolutionary tree shape, use EM for maximum likelihood estimation of branch lengths and of the K80 kappa parameter given an observed alignment with IUPAC nucleotide ambiguity.

The output includes the results of 8 iterations of EM, enough to converge to the maximum log likelihood -6,113.86 and the maximum likelihood kappa parameter estimate 3.561 given in Table 4.3 of Ziheng Yang’s 2014 textbook.

  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
from __future__ import print_function, division, absolute_import

import copy
import json

import pyparsing

import numpy as np
from numpy.testing import assert_equal

import jsonctmctree.interface

s_tree = """(kiwi_fruit, ((((agave, garlic), rice), black_pepper),
((cabbage, cotton), (cucumber, walnut))), (sunflower, (tomato, tobacco)))"""

def _help_build_tree(parent, root, node, name_to_node, edges):
    if parent is not None:
        edges.append((parent, node))
    neo = node + 1
    if isinstance(root, basestring):
        name_to_node[root] = node
    else:
        for element in root:
            neo = _help_build_tree(node, element, neo, name_to_node, edges)
    return neo

def get_tree_info():
    # Return a dictionary mapping name to node index,
    # and return a list of edges as ordered pairs of node indices.
    tree = s_tree.replace(',', ' ')
    nestedItems = pyparsing.nestedExpr(opener='(', closer=')')
    tree = (nestedItems + pyparsing.stringEnd).parseString(tree).asList()[0]
    name_to_node = {}
    edges = []
    _help_build_tree(None, tree, 0, name_to_node, edges)
    return name_to_node, edges

def get_nucleotide_alignment_info(name_to_node):
    # Return an ordered list of observable node indices,
    # and return the array of iid observations.
    # An observed state of -1 means completely missing data.
    nt_to_state = {
            'A' : [1, 0, 0, 0],
            'C' : [0, 1, 0, 0],
            'G' : [0, 0, 1, 0],
            'T' : [0, 0, 0, 1],
            '?' : [-1, -1, -1, -1],
            '-' : [-1, -1, -1, -1],
            'N' : [-1, -1, -1, -1],
            'M' : [-1, -1, 0, 0],
            'R' : [-1, 0, -1, 0],
            'W' : [-1, 0, 0, -1],
            'S' : [0, -1, -1, 0],
            'Y' : [0, -1, 0, -1],
            'K' : [0, 0, -1, -1],
            }
    sequences = []
    nodes = []
    variables = []
    with open('vegetables.rbcL.txt') as fin:
        lines = fin.readlines()
        header = lines[0]
        for line in lines[1:]:
            name, sequence = line.strip().split()
            node = name_to_node[name]
            nodes.extend([node]*4)
            sequences.append([nt_to_state[c] for c in sequence])
            variables.extend([0, 1, 2, 3])
    # arr[node, site, variable]
    arr = np.array(sequences, dtype=int)
    arr = np.transpose(arr, (1, 0, 2))
    iid_observations = np.reshape(arr, (arr.shape[0], -1))
    iid_observations = iid_observations.tolist()
    return nodes, variables, iid_observations


def get_process_definition(kappa):
    # Get the structure of the rate matrix.
    info = get_transition_components()
    ts_row_states, ts_column_states, tv_row_states, tv_column_states = info

    # Put together the rate matrix.
    rate = 2 + kappa
    row_states = ts_row_states + tv_row_states
    column_states = ts_column_states + tv_column_states
    rates = [kappa/rate]*len(ts_row_states) + [1/rate]*len(tv_row_states)

    # Assemble and return the process definition.
    process_definition = dict(
            row_states = row_states,
            column_states = column_states,
            transition_rates = rates)
    return process_definition


def get_transition_components():
    # Return ts_row_states, ts_col_states, tv_row_states, tv_col_states
    ts_row_states = []
    ts_column_states = []
    tv_row_states = []
    tv_column_states = []
    ident = np.identity(4, dtype=int).tolist()
    # ts: A<->G, C<->T
    ts = ((0, 2), (2, 0), (1, 3), (3, 1))
    for i in range(4):
        for j in range(4):
            if i != j:
                rs = ident[i]
                cs = ident[j]
                if (i, j) in ts:
                    ts_row_states.append(rs)
                    ts_column_states.append(cs)
                else:
                    tv_row_states.append(rs)
                    tv_column_states.append(cs)
    return ts_row_states, ts_column_states, tv_row_states, tv_column_states


def main():

    # Read the tree.
    name_to_node, edges = get_tree_info()
    edge_count = len(edges)
    node_count = edge_count + 1

    # Read the alignment.
    info = get_nucleotide_alignment_info(name_to_node)
    nodes, variables, iid_observations = info
    nsites = len(iid_observations)

    # Define the tree component of the scene
    row_nodes, column_nodes = zip(*edges)
    tree = dict(
            row_nodes = list(row_nodes),
            column_nodes = list(column_nodes),
            edge_rate_scaling_factors = [0.01] * edge_count,
            edge_processes = [0] * edge_count)

    # Get the structure of the rate matrix.
    info = get_transition_components()
    ts_row_states, ts_column_states, tv_row_states, tv_column_states = info
    row_states = ts_row_states + tv_row_states
    column_states = ts_column_states + tv_column_states

    # Define the root distribution.
    ident = np.identity(4, dtype=int).tolist()
    root_prior = dict(
            states = ident,
            probabilities = [0.25, 0.25, 0.25, 0.25])

    # Define the observed data.
    observed_data = dict(
            nodes = nodes,
            variables = variables,
            iid_observations = iid_observations)

    # Assemble the scene.
    scene = dict(
            node_count = node_count,
            process_count = 1,
            state_space_shape = [2, 2, 2, 2],
            tree = tree,
            root_prior = root_prior,
            observed_data = observed_data)

    # Define some requests.
    # These include the log likelihood
    # and the sum of transition count expectations.
    requests = [
            {"property" : "SNNLOGL"},
            {
                "property" : "SDNTRAN",
                "transition_reduction" : {
                    "row_states" : row_states,
                    "column_states" : column_states,
                    "weights" : [1 / nsites] * len(row_states)
                }
            },
            {
                "property" : "SSNTRAN",
                "transition_reduction" : {
                    "row_states" : ts_row_states,
                    "column_states" : ts_column_states,
                    "weights" : [1] * len(ts_row_states)
                }
            },
            {
                "property" : "SSNTRAN",
                "transition_reduction" : {
                    "row_states" : tv_row_states,
                    "column_states" : tv_column_states,
                    "weights" : [1] * len(tv_row_states)
                }
            }]

    # Request some stuff.
    j_in = {
            "scene" : scene,
            "requests" : requests
            }

    arr = []
    j_out = None
    kappa = 2.0
    for i in range(8):

        # if j_out is available, recompute kappa and edge rates
        if j_out is not None:
            ll, edge_rates, ts, tv = j_out['responses']
            kappa = 2 * (ts / tv)
            j_in['scene']['tree']['edge_rate_scaling_factors'] = edge_rates

        j_in['scene']['process_definitions'] = [get_process_definition(kappa)]
        j_out = jsonctmctree.interface.process_json_in(j_in)
        arr.append(copy.deepcopy(j_out))

    print(json.dumps(arr, indent=4))
    print('kappa estimate:', kappa)


main()
  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
[
    {
        "status": "feasible", 
        "responses": [
            -6633.390411239604, 
            [
                0.02719012112490459, 
                0.008398887521202816, 
                0.028265692691131203, 
                0.027349065034800713, 
                0.021535649988126754, 
                0.02658286179807283, 
                0.01894294386385, 
                0.06948726922341159, 
                0.050503382566655784, 
                0.007669802808878244, 
                0.013702687204809457, 
                0.052823591157116725, 
                0.032211210320352075, 
                0.012908733700532662, 
                0.0356021852225603, 
                0.02463372313312453, 
                0.013443604061119134, 
                0.04504060524016177, 
                0.04002232612048246, 
                0.008605881382287808, 
                0.004422842357465284
            ], 
            508.79055800074894, 
            304.23134098972497
        ]
    }, 
    {
        "status": "feasible", 
        "responses": [
            -6122.218275621923, 
            [
                0.029837320396093756, 
                0.005668673512536809, 
                0.028306390874859977, 
                0.024393849659626994, 
                0.017776896215555275, 
                0.028946322289096025, 
                0.01914852173131031, 
                0.08274427129586515, 
                0.058086462498535656, 
                0.00588911388944186, 
                0.013309713817634567, 
                0.05686640353980301, 
                0.032667803646128146, 
                0.011814042313743122, 
                0.03892895331551931, 
                0.02442222861757802, 
                0.011069736322653347, 
                0.04846336852033599, 
                0.04204953711718416, 
                0.008900966014391767, 
                0.0038078087485124163
            ], 
            540.254557849052, 
            306.6899349826408
        ]
    }, 
    {
        "status": "feasible", 
        "responses": [
            -6114.599320168605, 
            [
                0.03044667253918762, 
                0.004881312258455888, 
                0.028141470264532495, 
                0.023015362257333763, 
                0.016096694873876764, 
                0.02937339852160442, 
                0.019089605705006674, 
                0.08629616735645934, 
                0.06001036897134035, 
                0.005543550822591852, 
                0.013420209638508672, 
                0.05747946994620668, 
                0.032646621104238195, 
                0.011604082375655873, 
                0.03966698739204027, 
                0.02417912291576317, 
                0.010495437654172563, 
                0.04913565895142506, 
                0.04242208389008055, 
                0.009000135361460236, 
                0.0037054020089966454
            ], 
            545.14704146323, 
            306.86889408381154
        ]
    }, 
    {
        "status": "feasible", 
        "responses": [
            -6113.944053646576, 
            [
                0.030572724880736667, 
                0.00461306260068012, 
                0.02812950458274665, 
                0.02254807944385944, 
                0.015453071019594247, 
                0.02945753859424341, 
                0.019084414101865198, 
                0.0873761387827672, 
                0.06056204854833944, 
                0.005501905453791952, 
                0.013508338559552727, 
                0.05759337794875128, 
                0.03260049158204631, 
                0.011568853882751676, 
                0.03986424482225878, 
                0.02407650738681122, 
                0.010388197272434712, 
                0.04930088478513986, 
                0.042524629222983036, 
                0.009018490724092882, 
                0.0036873270138649923
            ], 
            546.1822652908345, 
            306.9475336756768
        ]
    }, 
    {
        "status": "feasible", 
        "responses": [
            -6113.8716889810785, 
            [
                0.030594265598912047, 
                0.004505821042372385, 
                0.02814730074985251, 
                0.0224043330881085, 
                0.015205228931620608, 
                0.029473494432226306, 
                0.019092249362020905, 
                0.08772720210100421, 
                0.06072690741776285, 
                0.005516386835325577, 
                0.01354642907028233, 
                0.05762122703150128, 
                0.032573690237946804, 
                0.011559926630786713, 
                0.03992232168636156, 
                0.02403814287448857, 
                0.010381220995947205, 
                0.04934241471522694, 
                0.04255162578092503, 
                0.009021651102548359, 
                0.003684227174606217
            ], 
            546.4485331554899, 
            306.9757703211402
        ]
    }, 
    {
        "status": "feasible", 
        "responses": [
            -6113.86204432763, 
            [
                0.03059683977731909, 
                0.0044573150700444805, 
                0.02816086419654426, 
                0.02236509267472435, 
                0.015107363656168224, 
                0.02947581264911239, 
                0.019098377439874956, 
                0.08784605073083679, 
                0.060776297979880586, 
                0.00553465655366759, 
                0.013560090642857334, 
                0.057630559315267615, 
                0.03256127524810115, 
                0.011555130252883159, 
                0.03994013491897455, 
                0.0240252839578094, 
                0.01038936156849631, 
                0.04935275064174427, 
                0.042557467676028096, 
                0.00902235408758141, 
                0.003683534830138814
            ], 
            546.5269309424081, 
            306.9838336612457
        ]
    }, 
    {
        "status": "feasible", 
        "responses": [
            -6113.860468234672, 
            [
                0.030597047993654723, 
                0.0044334056551510685, 
                0.02816798024669873, 
                0.022357262679840298, 
                0.01506761550341356, 
                0.029475764577415214, 
                0.019101625482465693, 
                0.08788734177544771, 
                0.06079067492083292, 
                0.005547851224839299, 
                0.013564395058977306, 
                0.057634521185341625, 
                0.03255585066044149, 
                0.011551904043577487, 
                0.0399454482696991, 
                0.024021643969835582, 
                0.010396157643717466, 
                0.04935541827977021, 
                0.04255802923981348, 
                0.009022654198749251, 
                0.0036832373588069627
            ], 
            546.5526765642804, 
            306.9855286319781
        ]
    }, 
    {
        "status": "feasible", 
        "responses": [
            -6113.860149878038, 
            [
                0.03059729596119569, 
                0.004420954900595925, 
                0.028171286175917503, 
                0.022357692110290397, 
                0.015050995846481669, 
                0.029475510075349577, 
                0.019103134354132932, 
                0.08790191764342595, 
                0.06079451666329945, 
                0.005556182553229025, 
                0.013565510083649583, 
                0.05763644209699932, 
                0.032553460500772353, 
                0.011549818207406314, 
                0.03994681287576467, 
                0.02402100267653052, 
                0.01040013348081679, 
                0.04935624036837421, 
                0.04255757158275262, 
                0.009022832718253535, 
                0.003683060066415156
            ], 
            546.5620072547885, 
            306.9855384487731
        ]
    }
]