File: MarkovModel.py

package info (click to toggle)
python-biopython 1.42-2
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 17,584 kB
  • ctags: 12,272
  • sloc: python: 80,461; xml: 13,834; ansic: 7,902; cpp: 1,855; sql: 1,144; makefile: 203
file content (484 lines) | stat: -rw-r--r-- 19,399 bytes parent folder | download
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
"""Deal with representations of Markov Models.
"""
# standard modules
import copy
import math
import random

# biopython
from Bio.Seq import MutableSeq

class MarkovModelBuilder:
    """Interface to build up a Markov Model.

    This class is designed to try to separate the task of specifying the
    Markov Model from the actual model itself. This is in hopes of making
    the actual Markov Model classes smaller.

    So, this builder class should be used to create Markov models instead
    of trying to initiate a Markov Model directly.
    """
    # the default pseudo counts to use
    DEFAULT_PSEUDO = 1
    
    def __init__(self, state_alphabet, emission_alphabet):
        """Initialize a builder to create Markov Models.

        Arguments:

        o state_alphabet -- An alphabet containing all of the letters that
        can appear in the states
       
        o emission_alphabet -- An alphabet containing all of the letters for
        states that can be emitted by the HMM.
        """
        self._state_alphabet = state_alphabet
        self._emission_alphabet = emission_alphabet
        
        # the probabilities for transitions and emissions
        # by default we have no transitions and all possible emissions
        self.transition_prob = {}
        self.emission_prob = self._all_blank(state_alphabet,
                                             emission_alphabet)

        # the default pseudocounts for transition and emission counting
        self.transition_pseudo = {}
        self.emission_pseudo = self._all_pseudo(state_alphabet,
                                                emission_alphabet)

    def _all_blank(self, first_alphabet, second_alphabet):
        """Return a dictionary with all counts set to zero.

        This uses the letters in the first and second alphabet to create
        a dictionary with keys of two tuples organized as
        (letter of first alphabet, letter of second alphabet). The values
        are all set to 0.
        """
        all_blank = {}
        for first_state in first_alphabet.letters:
            for second_state in second_alphabet.letters:
                all_blank[(first_state, second_state)] = 0

        return all_blank

    def _all_pseudo(self, first_alphabet, second_alphabet):
        """Return a dictionary with all counts set to a default value.

        This takes the letters in first alphabet and second alphabet and
        creates a dictionary with keys of two tuples organized as:
        (letter of first alphabet, letter of second alphabet). The values
        are all set to the value of the class attribute DEFAULT_PSEUDO.
        """
        all_counts = {}
        for first_state in first_alphabet.letters:
            for second_state in second_alphabet.letters:
                all_counts[(first_state, second_state)] = self.DEFAULT_PSEUDO

        return all_counts
                
    def get_markov_model(self):
        """Return the markov model corresponding with the current parameters.

        Each markov model returned by a call to this function is unique
        (ie. they don't influence each other).
        """
        transition_prob = copy.deepcopy(self.transition_prob)
        emission_prob = copy.deepcopy(self.emission_prob)
        transition_pseudo = copy.deepcopy(self.transition_pseudo)
        emission_pseudo = copy.deepcopy(self.emission_pseudo)
        
        return HiddenMarkovModel(transition_prob, emission_prob,
                                 transition_pseudo, emission_pseudo)

    def set_equal_probabilities(self):
        """Reset all probabilities to be an average value.

        This resets the values of all allowed transitions and all allowed
        emissions to be equal to 1 divided by the number of possible elements.

        This is useful if you just want to initialize a Markov Model to
        starting values (ie. if you have no prior notions of what the
        probabilities should be -- or if you are just feeling too lazy
        to calculate them :-).

        Warning 1 -- this will reset all currently set probabilities.

        Warning 2 -- This just sets all probabilities for transitions and
        emissions to total up to 1, so it doesn't ensure that the sum of
        each set of transitions adds up to 1.
        """
        # first set the transitions
        new_trans_prob = float(1) / float(len(self.transition_prob.keys()))
        for key in self.transition_prob.keys():
            self.transition_prob[key] = new_trans_prob

        # now set the emissions
        new_emission_prob = float(1) / float(len(self.emission_prob.keys()))
        for key in self.emission_prob.keys():
            self.emission_prob[key] = new_emission_prob
            

    def set_random_probabilities(self):
        """Set all probabilities to randomly generated numbers.

        This will reset the value of all allowed transitions and emissions
        to random values.

        Warning 1 -- This will reset any currently set probabibilities.

        Warning 2 -- This does not check to ensure that the sum of
        all of the probabilities is less then 1. It just randomly assigns
        a probability to each
        """
        for key in self.transition_prob.keys():
            self.transition_prob[key] = random.random()

        for key in self.emission_prob.keys():
            self.emission_prob[key] = random.random()

    # --- functions to deal with the transitions in the sequence

    def allow_all_transitions(self):
        """A convenience function to create transitions between all states.

        By default all transitions within the alphabet are disallowed; this
        is a way to change this to allow all possible transitions.
        """
        # first get all probabilities and pseudo counts set
        # to the default values
        all_probs = self._all_blank(self._state_alphabet,
                                    self._state_alphabet)

        all_pseudo = self._all_pseudo(self._state_alphabet,
                                      self._state_alphabet)

        # now set any probabilities and pseudo counts that
        # were previously set
        for set_key in self.transition_prob.keys():
            all_probs[set_key] = self.transition_prob[set_key]

        for set_key in self.transition_pseudo.keys():
            all_pseudo[set_key] = self.transition_pseudo[set_key]

        # finally reinitialize the transition probs and pseudo counts
        self.transition_prob = all_probs
        self.transition_pseudo = all_pseudo

    def allow_transition(self, from_state, to_state, probability = None,
                         pseudocount = None):
        """Set a transition as being possible between the two states.

        probability and pseudocount are optional arguments
        specifying the probabilities and pseudo counts for the transition.
        If these are not supplied, then the values are set to the
        default values.

        Raises:
        KeyError -- if the two states already have an allowed transition.
        """
        # check the sanity of adding these states
        for state in [from_state, to_state]:
            assert state in self._state_alphabet, \
                   "State %s was not found in the sequence alphabet" % state

        # ensure that the states are not already set
        if ((from_state, to_state) not in self.transition_prob.keys() and 
            (from_state, to_state) not in self.transition_pseudo.keys()):
            # set the initial probability
            if probability is None:
                probability = 0
            self.transition_prob[(from_state, to_state)] = probability

            # set the initial pseudocounts
            if pseudocount is None:
                pseudcount = DEFAULT_PSEUDO
            self.transition_pseudo[(from_state, to_state)] = pseudocount 
        else:
            raise KeyError("Transtion from %s to %s is already allowed."
                           % (from_state, to_state))

    def destroy_transition(self, from_state, to_state):
        """Restrict transitions between the two states.

        Raises:
        KeyError if the transition is not currently allowed.
        """
        try:
            del self.transition_prob[(from_state, to_state)]
            del self.transition_pseudo[(from_state, to_state)]
        except KeyError:
            raise KeyError("Transition from %s to %s is already disallowed."
                           % (from_state, to_state))

    def set_transition_score(self, from_state, to_state, probability):
        """Set the probability of a transition between two states.

        Raises:
        KeyError if the transition is not allowed.
        """
        if self.transition_prob.has_key((from_state, to_state)):
            self.transition_prob[(from_state, to_state)] = probability
        else:
            raise KeyError("Transition from %s to %s is not allowed."
                           % (from_state, to_state))

    def set_transition_pseudocount(self, from_state, to_state, count):
        """Set the default pseudocount for a transition.

        To avoid computational problems, it is helpful to be able to
        set a 'default' pseudocount to start with for estimating
        transition and emission probabilities (see p62 in Durbin et al
        for more discussion on this. By default, all transitions have
        a pseudocount of 1.

        Raises:
        KeyError if the transition is not allowed.
        """
        if self.transition_pseudo.has_key((from_state, to_state)):
            self.transition_pseudo[(from_state, to_state)] = count
        else:
            raise KeyError("Transition from %s to %s is not allowed."
                           % (from_state, to_state))

    # --- functions to deal with emissions from the sequence

    def set_emission_score(self, seq_state, emission_state, probability):
        """Set the probability of a emission from a particular state.

        Raises:
        KeyError if the emission from the given state is not allowed.
        """
        if self.emission_prob.has_key((seq_state, emission_state)):
            self.emission_prob[(seq_state, emission_state)] = probability
        else:
            raise KeyError("Emission of %s from %s is not allowed."
                           % (emission_state, seq_state))

    def set_emission_pseudocount(self, seq_state, emission_state, count):
        """Set the default pseudocount for an emission.

        To avoid computational problems, it is helpful to be able to
        set a 'default' pseudocount to start with for estimating
        transition and emission probabilities (see p62 in Durbin et al
        for more discussion on this. By default, all emissions have
        a pseudocount of 1.

        Raises:
        KeyError if the emission from the given state is not allowed.
        """
        if self.emission_pseudo.has_key((seq_state, emission_state)):
            self.emission_pseudo[(seq_state, emission_state)] = count
        else:
            raise KeyError("Emission of %s from %s is not allowed."
                           % (emission_state, seq_state))

class HiddenMarkovModel:
    """Represent a hidden markov model that can be used for state estimation.
    """
    def __init__(self, transition_prob, emission_prob, transition_pseudo,
                 emission_pseudo):
        """Initialize a Markov Model.

        Note: You should use the MarkovModelBuilder class instead of
        initiating this class directly.

        Arguments:

        o transition_prob -- A dictionary of transition probabilities for all
        possible transitions in the sequence.

        o emission_prob -- A dictionary of emissions probabilities for all
        possible emissions from the sequence states.

        o transition_pseudo -- Pseudo-counts to be used for the transitions,
        when counting for purposes of estimating transition probabilities.

        o emission_pseduo -- Pseudo-counts fo tbe used for the emissions,
        when counting for purposes of estimating emission probabilities.
        """
        self._transition_pseudo = transition_pseudo
        self._emission_pseudo = emission_pseudo
        
        self.transition_prob = transition_prob
        self.emission_prob = emission_prob

        # a dictionary of the possible transitions from one letter to the next
        # the keys are the letter, and the values are lists of letters that
        # can be transitioned to
        self._transitions_from = \
           self._calculate_from_transitions(self.transition_prob)

    def _calculate_from_transitions(self, trans_probs):
        """Calculate which 'from transitions' are allowed for each letter.

        This looks through all of the trans_probs, and uses this dictionary
        to determine allowed transitions. It converts this information into
        a dictionary, whose keys are the transition letters and whose
        values are a list of allowed letters to transition to.
        """
        from_transitions = {}

        # loop over all of the different transitions
        for trans_key in trans_probs.keys():
            # if the letter to 'transition from' already exists, add the
            # new letter which can be 'transitioned to' to the list
            try:
                from_transitions[trans_key[0]].append(trans_key[1])
            # otherwise create the list and add the letter
            except KeyError:
                from_transitions[trans_key[0]] = []
                from_transitions[trans_key[0]].append(trans_key[1])

        return from_transitions

    def get_blank_transitions(self):
        """Get the default transitions for the model.

        Returns a dictionary of all of the default transitions between any
        two letters in the sequence alphabet. The dictionary is structured
        with keys as (letter1, letter2) and values as the starting number
        of transitions.
        """
        return self._transition_pseudo

    def get_blank_emissions(self):
        """Get the starting default emmissions for each sequence.
        
        This returns a dictionary of the default emmissions for each
        letter. The dictionary is structured with keys as
        (seq_letter, emmission_letter) and values as the starting number
        of emmissions.
        """
        return self._emission_pseudo

    def transitions_from(self, state_letter):
        """Get all transitions which can happen from the given state.

        This returns all letters which the given state_letter is allowed
        to transition to. An empty list is returned if no letters are possible.
        """
        try:
            return self._transitions_from[state_letter]
        except KeyError:
            return []
        
    def viterbi(self, sequence, state_alphabet):
        """Calculate the most probable state path using the Viterbi algorithm.

        This implements the Viterbi algorithm (see pgs 55-57 in Durbin et
        al for a full explanation -- this is where I took my implementation
        ideas from), to allow decoding of the state path, given a sequence
        of emissions.

        Arguments:

        o sequence -- A Seq object with the emission sequence that we
        want to decode.

        o state_alphabet -- The alphabet of the possible state sequences
        that can be generated.
        """
        # calculate logarithms of the transition and emission probs
        log_trans = self._log_transform(self.transition_prob)
        log_emission = self._log_transform(self.emission_prob)

        viterbi_probs = {}
        pred_state_seq = {}
        state_letters = state_alphabet.letters
        # --- initialization
        #
        # NOTE: My index numbers are one less than what is given in Durbin
        # et al, since we are indexing the sequence going from 0 to
        # (Length - 1) not 1 to Length, like in Durbin et al.
        #
        # v_{0}(0) = 1
        viterbi_probs[(state_letters[0], -1)] = 1
        # v_{k}(0) = 0 for k > 0
        for state_letter in state_letters[1:]:
            viterbi_probs[(state_letter, -1)] = 0

        # --- recursion
        # loop over the training squence (i = 1 .. L)
        for i in range(0, len(sequence)):
            # now loop over all of the letters in the state path
            for main_state in state_letters:
                # e_{l}(x_{i})
                emission_part = log_emission[(main_state, sequence[i])]

                # loop over all possible states
                possible_state_probs = {}
                for cur_state in self.transitions_from(main_state):
                    # a_{kl}
                    trans_part = log_trans[(cur_state, main_state)]

                    # v_{k}(i - 1)
                    viterbi_part = viterbi_probs[(cur_state, i - 1)]
                    cur_prob = viterbi_part + trans_part

                    possible_state_probs[cur_state] = cur_prob

                # finally calculate the viterbi probability using the max
                max_prob = max(possible_state_probs.values())
                viterbi_probs[(main_state, i)] = (emission_part + max_prob)

                # now get the most likely state
                for state in possible_state_probs.keys():
                    if possible_state_probs[state] == max_prob:
                        pred_state_seq[(i - 1, main_state)] = state
                        break
                    
        # --- termination
        # calculate the probability of the state path
        # loop over all letters
        all_probs = {}
        for state in state_letters:
            # v_{k}(L)
            viterbi_part = viterbi_probs[(state, len(sequence) - 1)]
            # a_{k0}
            transition_part = log_trans[(state, state_letters[0])]

            all_probs[state] = viterbi_part * transition_part

        state_path_prob = max(all_probs.values())

        # find the last pointer we need to trace back from
        last_state = ''
        for state in all_probs.keys():
            if all_probs[state] == state_path_prob:
                last_state = state

        assert last_state != '', "Didn't find the last state to trace from!"
                
        # --- traceback
        traceback_seq = MutableSeq('', state_alphabet)
        
        loop_seq = range(0, len(sequence))
        loop_seq.reverse()

        cur_state = last_state
        for i in loop_seq:
            traceback_seq.append(cur_state)
            
            cur_state = pred_state_seq[(i - 1, cur_state)]

        # put the traceback sequence in the proper orientation
        traceback_seq.reverse()

        return traceback_seq.toseq(), state_path_prob

    def _log_transform(self, probability):
        """Return log transform of the given probability dictionary.

        When calculating the Viterbi equation, we need to deal with things
        as sums of logs instead of products of probabilities, so that we
        don't get underflow errors.. This copies the given probability
        dictionary and returns the same dictionary with everything
        transformed with a log.
        """
        log_prob = copy.copy(probability)

        for key in log_prob.keys():
            log_prob[key] = math.log(log_prob[key])

        return log_prob