├── .gitignore
├── setup.py
├── README.md
├── LICENSE
└── pykov.py
/.gitignore:
--------------------------------------------------------------------------------
1 | __pycache__
2 | *.pyc
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | from distutils.core import setup
4 |
5 | setup(
6 | name='pykov',
7 | version='1.1',
8 | description='Pykov is a tiny Python module on finite regular Markov chains.',
9 | author='Riccardo Scalco',
10 | author_email='riccardo.scalco@gmail.com',
11 | url='https://github.com/riccardoscalco/Pykov',
12 | py_modules=['pykov'],
13 | install_requires=['scipy', 'numpy', 'six'],
14 | )
15 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | Welcome to Pykov docs
3 | ====================
4 |
5 | Pykov is a tiny Python module on *finite regular Markov chains*.
6 |
7 | You can define a Markov chain from scratch or read it from a text file according specific format. Pykov is versatile, being it able to manipulate the chain, inserting and removing nodes, and to calculate various kind of quantities, like the steady state distribution, mean first passage times, random walks, absorbing times, and so on.
8 |
9 | Pykov is licensed under the terms of the **GNU General Public License** as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
10 |
11 | ---------------
12 |
13 | Installation
14 | -------------
15 | Pykov can be installed/upgraded via [`pip`](http://pip.readthedocs.org/en/latest/#)
16 | ```sh
17 | $ pip install git+git://github.com/riccardoscalco/Pykov@master #both Python2 and Python3
18 | $ pip install --upgrade git+git://github.com/riccardoscalco/Pykov@master
19 | ```
20 | Note that Pykov depends on **numpy** and **scipy**.
21 |
22 | -----------------
23 |
24 | Getting started
25 | ------------------
26 |
27 | Open your favourite Python shell and import pykov:
28 | ```python
29 | >>> import pykov
30 | >>> pykov.__version__
31 | ```
32 |
33 | ###Vector class
34 | The **Vector class** inherits from python `collections.OrderedDict`, which means it has the same behaviors and features of python ordered dictionaries, with few exceptions. The states and the corresponding probabilities are the keys and the values of the dictionary, respectively.
35 |
36 | collections.OrderedDict is used instead of the default dict because from Python 3.3 onwards, dict is non-deterministic for security reasons (see this [stackoverflow question](http://stackoverflow.com/questions/14956313/dictionary-ordering-non-deterministic-in-python3)). For programs that needs determinism (such as simulations), an OrderedDict should be passed. But for programs where determinism is not an issue, dict can be used.
37 |
38 | Definition of a `pykov.Vector()`:
39 | ```python
40 | >>> p = pykov.Vector()
41 | ```
42 | You can *get* and *set* states in many ways:
43 | ```python
44 | >>> p['A'] = .2
45 | >>> p
46 | {'A': 0.2}
47 |
48 | >>> # Non-deterministic example
49 | >>> p = pykov.Vector({'A':.3, 'B':.7})
50 | >>> p
51 | {'A':0.3, 'B':0.7}
52 |
53 | >>> # Deterministic example
54 | >>> data = collections.OrderedDict((('A', .3), ('B', .7)))
55 | >>> p = pykov.Vector(data)
56 | >>> p
57 | {'A':0.3, 'B':0.7}
58 |
59 | >>> pykov.Vector(A=.3, B=.6, C=.1)
60 | {'A':0.3, 'B':0.6, 'C':0.1}
61 | ```
62 | States not belonging to the vector have zero probability, moreover states with zero probability are not shown:
63 | ```python
64 | >>> q = pykov.Vector(C=.4, B=.6)
65 | >>> q['C']
66 | 0.4
67 | >>> q['Z']
68 | 0.0
69 | >>> 'Z' in q
70 | False
71 |
72 | >>> q['Z']=.2
73 | >>> q
74 | {'C': 0.4, 'B': 0.6, 'Z': 0.2}
75 | >>> 'Z' in q
76 | True
77 | >>> q['Z']=0
78 | >>> q
79 | {'C': 0.4, 'B': 0.6}
80 | >>> 'Z' in q
81 | False
82 | ```
83 |
84 | #### Vector operations
85 | ##### **Sum**
86 | A `pykov.Vector()` instance can be added or substracted to another `pykov.Vector()` instance:
87 | ```python
88 | >>> p = pykov.Vector(A=.3, B=.7)
89 | >>> q = pykov.Vector(C=.5, B=.5)
90 | >>> p + q
91 | {'A': 0.3, 'C': 0.5, 'B': 1.2}
92 | >>> p - q
93 | {'A': 0.3, 'C': -0.5, 'B': 0.2}
94 | >>> q - p
95 | {'A': -0.3, 'C': 0.5, 'B': -0.2}
96 | ```
97 |
98 | ##### **Product**
99 | A `pykov.Vector()` instance can be multiplied by a scalar. The *dot product* with another `pykov.Vector()` or `pykov.Matrix()` instance is also supported.
100 | ```python
101 | >>> p = pykov.Vector(A=.3, B=.7)
102 | >>> p * 3
103 | {'A': 0.9, 'B': 2.1}
104 | >>> 3 * p
105 | {'A': 0.9, 'B': 2.1}
106 | >>> q = pykov.Vector(C=.5, B=.5)
107 | >>> p * q
108 | 0.35
109 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
110 | >>> p * T
111 | {'A': 0.91, 'B': 0.09}
112 | >>> T * p
113 | {'A': 0.42, 'B': 0.3}
114 | ```
115 |
116 | #### Vector methods
117 |
118 | ##### **sum()**
119 | Sum the probability values.
120 | ```python
121 | >>> p = pykov.Vector(A=.3, B=.7)
122 | >>> p.sum()
123 | 1.0
124 | ```
125 |
126 | ##### **sort(reverse=False)**
127 | Return a list of tuples `(state, probability)` sorted according the probability values.
128 | ```python
129 | >>> p = pykov.Vector({'A':.3, 'B':.1, 'C':.6})
130 | >>> p.sort()
131 | [('B', 0.1), ('A', 0.3), ('C', 0.6)]
132 | >>> p.sort(reverse=True)
133 | [('C', 0.6), ('A', 0.3), ('B', 0.1)]
134 | ```
135 | ##### **choose(random_func=None)**
136 | Choose a state at random, according to its probability.
137 | ```python
138 | >>> p = pykov.Vector(A=.3, B=.7)
139 | >>> p.choose()
140 | 'B'
141 | >>> p.choose()
142 | 'B'
143 | >>> p.choose()
144 | 'A'
145 | ```
146 |
147 | Optionally, if you need to supply your own random number generator, you can pass a function that takes two inputs (the min and max) and Pykov will use that function.
148 | ```python
149 | >>> def FakeRandom(min, max): return 0.01
150 | >>> p = pykov.Vector(A=.05, B=.4, C=.4, D=.15)
151 | >>> p.choose(FakeRandom)
152 | 'A'
153 | ```
154 |
155 |
156 | ##### **normalize()**
157 | Normalize the `pykov.Vector`, after normalization the probabilities sum to 1.
158 | ```python
159 | >>> p = pykov.Vector({'A':3, 'B':1, 'C':6})
160 | >>> p.sum()
161 | 10.0
162 | >>> p.normalize()
163 | >>> p
164 | {'A': 0.3, 'C': 0.6, 'B': 0.1}
165 | >>> p.sum()
166 | 1.0
167 | ```
168 |
169 | ##### **copy()**
170 | Return a shallow copy.
171 | ```python
172 | >>> p = pykov.Vector(A=.3, B=.7)
173 | >>> q = p.copy()
174 | >>> p['C'] = 1.
175 | >>> q
176 | {'A': 0.3, 'B': 0.7}
177 | ```
178 |
179 | ##### **entropy()**
180 | Return the Shannon entropy, defined as $H(p) = \sum_i p_i \ln p_i$.
181 | ```python
182 | >>> p = pykov.Vector(A=.3, B=.7)
183 | >>> p.entropy()
184 | 0.6108643020548935
185 | ```
186 | For further details, have a look at *Khinchin A. I., Mathematical Foundations of Information Theory Dover, 1957*.
187 |
188 | ##### **dist(q)**
189 | Return the distance to another `pykov.Vector`, defined as $d(p,q) = \sum_i | p_i - q_i |$.
190 | ```python
191 | >>> p = pykov.Vector(A=.3, B=.7)
192 | >>> q = pykov.Vector(C=.5, B=.5)
193 | >>> p.dist(q)
194 | 1.0
195 | ```
196 |
197 | ##### **relative_entropy(q)**
198 | Return the *Kullback-Leibler* distance, defined as $d(p,q) = \sum_i p_i \ln (p_i/q_i)$.
199 | ```python
200 | >>> p = pykov.Vector(A=.3, B=.7)
201 | >>> q = pykov.Vector(A=.4, B=.6)
202 | >>> p.relative_entropy(q) #d(p,q)
203 | 0.02160085414354654
204 | >>> q.relative_entropy(p) #d(q,p)
205 | 0.022582421084357485
206 | ```
207 | Note that the Kullback-Leibler distance is not symmetric.
208 |
209 | ------------
210 |
211 | ### Matrix class
212 | The `pykov.Matrix()` class inherits from python collections.OrderedDict. Similar to the default dict, OrderedDict `keys` are `tuple` of states, OrderedDict `values` are the matrix entries. Indexes do not need to be `int`, they can be `string`, as the states of a `pykov.Vector()`.
213 |
214 | Definition of `pykov.Matrix()`:
215 | ```python
216 | >>> T = pykov.Matrix()
217 | ```
218 | You can *get* and *set* items in many ways:
219 | ```python
220 | >>> T = pykov.Matrix()
221 | >>> T[('A','B')] = .3
222 | >>> T
223 | {('A', 'B'): 0.3}
224 | >>> T['A','A'] = .7
225 | >>> T
226 | {('A', 'B'): 0.3, ('A', 'A'): 0.7}
227 |
228 | >>> # Non-deterministic example
229 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
230 | >>> T[('A','B')]
231 | 0.3
232 | >>> T['A','B']
233 | 0.3
234 |
235 | >>> # deterministic example
236 | >>> data = collections.OrderedDict((
237 | (('A','B'), .3),
238 | (('A','A'), .7),
239 | (('B','A'), 1.)))
240 | >>> T = pykov.Matrix(data)
241 | >>> T[('A','B')]
242 | 0.3
243 | >>> T['A','B']
244 | 0.3
245 | ```
246 |
247 | Items not belonging to the matrix have value equal to zero, moreover items with value equal to zero are not shown:
248 | ```python
249 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
250 | >>> T['B','B']
251 | 0.0
252 |
253 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
254 | >>> T
255 | {('A', 'B'): 0.3, ('A', 'A'): 0.7, ('B', 'A'): 1.0}
256 | >>> T['A','A'] = 0
257 | >>> T
258 | {('A', 'B'): 0.3, ('B', 'A'): 1.0}
259 | ```
260 |
261 | #### Matrix operations
262 |
263 | ##### **Sum**
264 | A `pykov.Matrix()` instance can be added or substracted to another `pykov.Matrix()` instance.
265 | ```python
266 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
267 | >>> I = pykov.Matrix({('A','A'):1, ('B','B'):1})
268 | >>> T + I
269 | {('B', 'A'): 1.0, ('A', 'B'): 0.3, ('A', 'A'): 1.7, ('B', 'B'): 1.0}
270 | >>> T - I
271 | {('B', 'A'): 1.0, ('A', 'B'): 0.3, ('A', 'A'): -0.3, ('B', 'B'): -1}
272 | ```
273 |
274 | ##### **Product**
275 | A `pykov.Matrix()` instance can be multiplied by a scalar, the dot product with a `pykov.Vector()` or another `pykov.Matrix()` instance is also supported.
276 | ```python
277 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
278 | >>> T * 3
279 | {('B', 'A'): 3.0, ('A', 'B'): 0.9, ('A', 'A'): 2.1}
280 |
281 | >>> p = pykov.Vector(A=.3, B=.7)
282 | >>> T * p
283 | {'A': 0.42, 'B': 0.3}
284 |
285 | >>> W = pykov.Matrix({('N', 'M'): 0.5, ('M', 'N'): 0.7,
286 | ('M', 'M'): 0.3, ('O', 'N'): 0.5,
287 | ('O', 'O'): 0.5, ('N', 'O'): 0.5})
288 | >>> W * W
289 | {('N', 'M'): 0.15, ('M', 'N'): 0.21, ('M', 'O'): 0.35,
290 | ('M', 'M'): 0.44, ('O', 'M'): 0.25, ('O', 'N'): 0.25,
291 | ('O', 'O'): 0.5, ('N', 'O'): 0.25, ('N', 'N'): 0.6}
292 | ```
293 |
294 | #### Matrix methods
295 |
296 | ##### **states()**
297 | Return the `set` of states.
298 | ```python
299 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
300 | >>> T.states()
301 | {'B', 'A'}
302 | ```
303 | States without ingoing or outgoing transitions are removed from the set of states.
304 | ```python
305 | >>> T['A','C']=1
306 | >>> T.states()
307 | {'A', 'C', 'B'}
308 | >>> T['A','C']=0
309 | >>> T.states()
310 | {'A', 'B'}
311 | ```
312 |
313 | ##### **pred(key=None)**
314 | Return the precedessors of a state (if not indicated, of all states). In matrix notation, return the column of the indicated state.
315 | ```python
316 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
317 | >>> T.pred()
318 | {'A': {'A': 0.7, 'B': 1.0}, 'B': {'A': 0.3}}
319 | >>> T.pred('A')
320 | {'A': 0.7, 'B': 1.0}
321 | ```
322 |
323 | ##### **succ(key=None)**
324 | Return the successors of a state (if not indicated, of all states). In matrix notation, return the row of the indicated state.
325 | ```python
326 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
327 | >>> T.succ()
328 | {'A': {'A': 0.7, 'B': 0.3}, 'B': {'A': 1.0}}
329 | >>> T.succ('A')
330 | {'A': 0.7, 'B': 0.3}
331 | ```
332 |
333 | ##### **copy()**
334 | Return a shallow copy.
335 | ```python
336 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
337 | >>> W = T.copy()
338 | >>> T[('B','B')] = 1.
339 | >>> W
340 | {('B', 'A'): 1.0, ('A', 'B'): 0.3, ('A', 'A'): 0.7}
341 | ```
342 |
343 | ##### **remove(states)**
344 | Return a shallow copy of the matrix without the indicated states.
345 | All the links where the states appear are deleted, so that the result will not be in general a stochastic matrix.
346 | ```python
347 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
348 | >>> T.remove(['B'])
349 | {('A', 'A'): 0.7}
350 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.,
351 | ('C','D'): .5, ('D','C'): 1., ('C','B'): .5})
352 | >>> T.remove(['A','B'])
353 | {('C', 'D'): 0.5, ('D', 'C'): 1.0}
354 | ```
355 |
356 | ##### **stochastic()**
357 | Change the `pykov.Matrix()` instance in a right [stochastic matrix](http://en.wikipedia.org/wiki/Stochastic_matrix).
358 | Set the sum of every row equal to one, raise `PykovError` if not possible.
359 | ```python
360 | >>> T = pykov.Matrix({('A','B'): 3, ('A','A'): 7, ('B','A'): .2})
361 | >>> T.stochastic()
362 | >>> T
363 | {('B', 'A'): 1.0, ('A', 'B'): 0.3, ('A', 'A'): 0.7}
364 |
365 | >>> T[('A','C')]=1
366 | >>> T.stochastic()
367 | pykov.PykovError: 'Zero links from node C'
368 | ```
369 |
370 | ##### **transpose()**
371 | Return the transpose of the `pykov.Matrix()` instance.
372 | ```python
373 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
374 | >>> T.transpose()
375 | {('B', 'A'): 0.3, ('A', 'B'): 1.0, ('A', 'A'): 0.7}
376 | >>> T
377 | {('A', 'B'): 0.3, ('A', 'A'): 0.7, ('B', 'A'): 1.0}
378 | ```
379 |
380 | ##### **eye()**
381 | Return the [Identity matrix](http://en.wikipedia.org/wiki/Identity_matrix).
382 | ```python
383 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
384 | >>> T.eye()
385 | {('A', 'A'): 1., ('B', 'B'): 1.}
386 | >>> type(T.eye())
387 |
388 | ```
389 |
390 | ##### **ones()**
391 | Return a `pykov.Vector()` instance with entries equal to 1.
392 | ```python
393 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
394 | >>> T.ones()
395 | {'A': 1.0, 'B': 1.0}
396 | >>> type(T.ones())
397 |
398 | ```
399 |
400 | ##### **trace()**
401 | Return the matrix [trace](http://en.wikipedia.org/wiki/Trace_%28linear_algebra%29).
402 | ```python
403 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
404 | >>> T.trace()
405 | 0.7
406 | ```
407 |
408 | ---------------
409 |
410 | ### Chain class
411 |
412 | The `pykov.Chain` class inherits from `pykov.Matrix` class.
413 | The OrderedDict `key` is a tuple of states, the OrderedDict `value` is the transition
414 | probability to go from the first state to the second state, in other words
415 | pykov describes the transitions of a Markov chain with a *right* stochastic matrix.
416 |
417 | #### Chain methods
418 |
419 | ##### **adjacency()**
420 | Return the [adjacency matrix](http://en.wikipedia.org/wiki/Adjacency_matrix).
421 | ```python
422 | >>> T = pykov.Chain({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
423 | >>> T.adjacency()
424 | {('B', 'A'): 1, ('A', 'B'): 1, ('A', 'A'): 1}
425 | >>> type(T.adjacency())
426 |
427 | ```
428 |
429 | ##### **pow(p, n)**
430 | Find the probability distribution after `n` steps, starting from an initial `pykov.Vector()` `p`.
431 | ```python
432 | >>> T = pykov.Chain({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
433 | >>> p = pykov.Vector(A=1)
434 | >>> T.pow(p,3)
435 | {'A': 0.7629999999999999, 'B': 0.23699999999999996}
436 | >>> p * T * T * T #not efficient
437 | {'A': 0.7629999999999999, 'B': 0.23699999999999996}
438 | ```
439 |
440 | ##### **move(state)**
441 | Do one step from the indicated `state` to one of its successors, chosen at random according to the transition probability. Return the new state.
442 | ```python
443 | >>> T = pykov.Chain({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
444 | >>> T.move('A')
445 | 'B'
446 | ```
447 |
448 | Optionally, if you need to supply your own random number generator, you can pass a function that takes two inputs (the min and max) and Pykov will use that function.
449 | ```python
450 | >>> def FakeRandom(min, max): return 0.01
451 | >>> T.move('A', FakeRandom)
452 | 'B'
453 | ```
454 |
455 | ##### **walk(steps, start=None, stop=None)**
456 | Return a random walk of n `steps`, starting and stopping at the indicated states. If not indicated, then the starting state is chosen according to the steady state probability. If the stopping state is reached before to do n steps, then the walker stops.
457 | ```python
458 | >>> T = pykov.Chain({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
459 | >>> T.walk(10)
460 | ['B', 'A', 'B', 'A', 'A', 'B', 'A', 'A', 'A', 'B', 'A']
461 | >>> T.walk(10,'B','B')
462 | ['B', 'A', 'A', 'A', 'A', 'A', 'B']
463 | ```
464 |
465 | ##### **walk_probability(walk)**
466 | Return the *logarithm* of the **walk** probability (see `walk()` method). Impossible walks have probability equal to zero.
467 | ```python
468 | >>> T = pykov.Chain({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
469 | >>> T.walk_probability(['A','A','B','A','A'])
470 | -1.917322692203401
471 | >>> probability = math.exp(-1.917322692203401)
472 | >>> probability
473 | 0.147
474 |
475 | >>> p = T.walk_probability(['A','B','B','B','A'])
476 | >>> math.exp(p)
477 | 0.0
478 | ```
479 |
480 |
481 | ##### **steady()**
482 | Return the steady state, i.e. the equilibrium distribution of the chain.
483 | ```python
484 | >>> T = pykov.Chain({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
485 | >>> T.steady()
486 | {'A': 0.7692307692307676, 'B': 0.23076923076923028}
487 | ```
488 | Since Pykov describes the chain with a right stochatic matrix,
489 | the steady state $x$ satisfies at the condition $p=pT$
490 | and it is calculated with the *inverse iteration method*
491 | $Q^t x = e$, where $Q = I - T$ and $e = (0,0,...,1)$.
492 | Moreover, the Markov chain is assumed to be ergodic, i.e. the transition matrix
493 | must be irreducible and acyclic.
494 | You can easily test such properties by means of
495 | [NetworkX](http://networkx.github.io/), let's see how:
496 | ```python
497 | >>> import networkx as nx
498 |
499 | >>> T = pykov.Chain({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
500 | >>> G = nx.DiGraph(list(T.keys()))
501 | >>> nx.is_strongly_connected(G) # is irreducible
502 | True
503 | >>> nx.is_aperiodic(G)
504 | True
505 |
506 | >>> T = pykov.Chain({('A','B'): .3, ('A','A'): .7, ('B','B'): 1.})
507 | >>> G = nx.DiGraph(list(T.keys()))
508 | >>> nx.is_strongly_connected(G) # is irreducible
509 | False
510 | >>> nx.is_aperiodic(G)
511 | True
512 |
513 | >>> T = pykov.Chain({('A','B'): 1, ('B','C'): 1., ('C','A'): 1.})
514 | >>> G = nx.DiGraph(list(T.keys()))
515 | >>> nx.is_strongly_connected(G)
516 | True
517 | >>> nx.is_aperiodic(G)
518 | False
519 | ```
520 |
521 | Often, Markov chains created from raw data are not irreducibles.
522 | In such cases, the Markov chain may be defined by means of the
523 | largest strongly connected component of the associated graph.
524 | Strongly connected components can be found with NetworkX:
525 | ```python
526 | >>> nx.strongly_connected_components(G)
527 | ```
528 |
529 | For further details on the inverse iteration method,
530 | have a look at *W. Stewart, Introduction to the Numerical Solution of
531 | Markov Chains, Princeton University Press, Chichester, West Sussex, 1994*.
532 |
533 | ##### **mixing_time(cutoff=0.25, jump=1, p=None)**
534 | Return the [mixing time](http://en.wikipedia.org/wiki/Markov_chain_mixing_time), defined as the number of steps needed to have $|pT^n - \pi| \lt 0.25$, where $\pi$ is the steady state $\pi = \pi T$.
535 |
536 | If the initial distribution `p` is not indicated, then the iteration starts from the less probable state of the steady distribution. The parameter `jump` controls the iteration step, for example with `jump=2` n has values 2,4,6,8,..
537 | ```python
538 | >>> d = {('R','R'):1./2, ('R','N'):1./4, ('R','S'):1./4,
539 | ('N','R'):1./2, ('N','N'):0., ('N','S'):1./2,
540 | ('S','R'):1./4, ('S','N'):1./4, ('S','S'):1./2}
541 | >>> T = pykov.Chain(d)
542 | >>> T.mixing_time()
543 | 2
544 | ```
545 |
546 | ##### **entropy(p=None, norm=False)**
547 | Return the Chain entropy, defined as $H = \sum_i \pi_i H_i$, where $H_i=\sum_j T_{ij}\ln T_{ij}$.
548 | If `p` is not `None`, then the entropy is calculated with the indicated probability `pykov.Vector()`.
549 | ```python
550 | >>> T = pykov.Chain({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
551 | >>> T.entropy()
552 | 0.46989561696530169
553 | ```
554 | With **norm=True** entropy belongs to [0,1].
555 | ```python
556 | >>> T.entropy(norm=True)
557 | 0.33895603665233132
558 | ```
559 | For further details, have a look at *Khinchin A. I., Mathematical Foundations of Information Theory, Dover, 1957*.
560 |
561 | ##### **mfpt_to(state)**
562 | Return the Mean First Passage Times of every state *to* the indicated `state`.
563 | ```python
564 | >>> d = {('R', 'N'): 0.25, ('R', 'S'): 0.25, ('S', 'R'): 0.25,
565 | ('R', 'R'): 0.5, ('N', 'S'): 0.5, ('S', 'S'): 0.5,
566 | ('S', 'N'): 0.25, ('N', 'R'): 0.5, ('N', 'N'): 0.0}
567 | >>> T = pykov.Chain(d)
568 | >>> T.mfpt_to('R')
569 | {'S': 3.333333333333333, 'N': 2.666666666666667} #mfpt from 'S' to 'R' is 3.33
570 | ```
571 | See also *Kemeny J. G. and Snell, J. L., Finite Markov Chains. Springer-Verlag: New York, 1976*.
572 |
573 | ##### **absorbing_time(transient_set)**
574 | Mean number of steps needed to leave the `transient_set`, return the `pykov.Vector()` `tau` where `tau[i]` is the mean number of steps needed to leave the transient set starting from state `i`. The parameter `transient_set` is a subset of states (iterable).
575 | ```python
576 | >>> d = {('R','R'):1./2, ('R','N'):1./4, ('R','S'):1./4,
577 | ('N','R'):1./2, ('N','N'):0., ('N','S'):1./2,
578 | ('S','R'):1./4, ('S','N'):1./4, ('S','S'):1./2}
579 | >>> T = pykov.Chain(d)
580 | >>> p = pykov.Vector({'N':.3, 'S':.7})
581 | >>> tau = T.absorbing_time(p.keys())
582 | >>> tau
583 | {'S': 3.333333333333333, 'N': 2.6666666666666665}
584 | ```
585 | In other words, the mean number of steps in order to leave states `'S'` and `'N'` starting from `'S'` is 3.33.
586 | It is sufficient to calculate `p * tau` in order to weight the mean times according an initial distribution `p`.
587 | ```python
588 | >>> p * tau
589 | 3.1333333333333329
590 | ```
591 | In order to better understand the meaning of the method, the calculation of the previous example can be approximated by means of many random walkers:
592 | ```python
593 | >>> numpy.mean([len(T.walk(10000000,"S","R"))-1 for i in range(1000000)])
594 | 3.3326020000000001
595 | >>> numpy.mean([len(T.walk(10000000,"N","R"))-1 for i in range(1000000)])
596 | 2.6665549999999998
597 | ```
598 |
599 | ##### **absorbing_tour(p, transient_set=None)**
600 | Return a `pykov.Vector()` `v`, where `v[i]` is the mean time the process is in the transient state `i` before leaving the transient set.
601 |
602 | Note that `v.sum()` is equal to `p * tau` (see `absorbing_time()` method).
603 | If not specified, the transient set is defined as the set of states in vector `p`.
604 | ```python
605 | >>> d = {('R','R'):1./2, ('R','N'):1./4, ('R','S'):1./4,
606 | ('N','R'):1./2, ('N','N'):0., ('N','S'):1./2,
607 | ('S','R'):1./4, ('S','N'):1./4, ('S','S'):1./2}
608 | >>> T = pykov.Chain(d)
609 | >>> p = pykov.Vector({'N':.3, 'S':.7})
610 | >>> T.absorbing_tour(p)
611 | {'S': 2.2666666666666666, 'N': 0.8666666666666669}
612 | ```
613 |
614 | ##### **fundamental_matrix()**
615 | Return the fundamental matrix, have a look at *Kemeny J. G. and Snell J. L., Finite Markov Chains. Springer-Verlag: New York, 1976* for further details.
616 | ```python
617 | >>> T = pykov.Chain({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
618 | >>> T.fundamental_matrix()
619 | {('B', 'A'): 0.17751479289940991, ('A', 'B'): 0.053254437869822958,
620 | ('A', 'A'): 0.94674556213017902, ('B', 'B'): 0.82248520710059214}
621 | ```
622 | Note that the fundamental matrix is not sparse.
623 |
624 | ##### **kemeny_constant()**
625 | Return the Kemeny constant of the transition matrix.
626 | ```python
627 | >>> T = pykov.Chain({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
628 | >>> T.kemeny_constant()
629 | 1.7692307692307712
630 | ```
631 |
632 | ----------------------------
633 |
634 | Utilities
635 | ----------
636 | Pykov comes with an utility useful to create a `pykov.Chain()` from a text file, let say file `/mypath/mat`, which contains the transition matrix defined with the following format:
637 | ```python
638 | A A .7
639 | A B .3
640 | B A 1
641 | ```
642 | The `pykov.Chain()` instance is created with the command:
643 | ```python
644 | >>> P = pykov.readmat('/mypath/mat')
645 | >>> P
646 | {('B', 'A'): 1.0, ('A', 'B'): 0.3, ('A', 'A'): 0.7}
647 | ```
648 | -----------------------------------
649 | > Docs written with [StackEdit](https://stackedit.io/).
650 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/pykov.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # PyKov is Python package for the creation, manipulation and study of Markov
4 | # Chains.
5 | # Copyright (C) 2014 Riccardo Scalco
6 | #
7 | # This program is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # This program is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with this program. If not, see .
19 |
20 | # Email: riccardo.scalco@gmail.com
21 |
22 | """Pykov documentation.
23 |
24 | .. module:: A Python module for finite Markov chains.
25 | :platform: Unix, Windows, Mac
26 |
27 | .. moduleauthor::
28 | Riccardo Scalco
29 |
30 | """
31 | import random
32 | import math
33 | import six
34 | import numpy
35 | import sys
36 |
37 | from collections import OrderedDict
38 |
39 | import scipy.sparse as ss
40 | import scipy.sparse.linalg as ssl
41 |
42 | if sys.version_info < (2, 6):
43 | from sets import Set
44 | else:
45 | Set = set
46 |
47 | __date__ = 'March 2015'
48 |
49 | __version__ = 1.1
50 |
51 | __license__ = 'GNU General Public License Version 3'
52 |
53 | __authors__ = 'Riccardo Scalco'
54 |
55 | __many_thanks_to__ = 'Sandra Steiner, Nicky Van Foreest, Adel Qalieh'
56 |
57 |
58 | def _del_cache(fn):
59 | """
60 | Delete cache.
61 | """
62 | def wrapper(*args, **kwargs):
63 | self = args[0]
64 | try:
65 | del(self._states)
66 | except AttributeError:
67 | pass
68 | try:
69 | del(self._succ)
70 | except AttributeError:
71 | pass
72 | try:
73 | del(self._pred)
74 | except AttributeError:
75 | pass
76 | try:
77 | del(self._steady)
78 | except AttributeError:
79 | pass
80 | try:
81 | del(self._guess)
82 | except AttributeError:
83 | pass
84 | try:
85 | del(self._fundamental_matrix)
86 | except AttributeError:
87 | pass
88 | return fn(*args, **kwargs)
89 | return wrapper
90 |
91 |
92 | class PykovError(Exception):
93 |
94 | """
95 | Exception definition form Pykov Errors.
96 | """
97 |
98 | def __init__(self, value):
99 | self.value = value
100 |
101 | def __str__(self):
102 | return repr(self.value)
103 |
104 |
105 | class Vector(OrderedDict):
106 |
107 | """
108 | """
109 |
110 | def __init__(self, data=None, **kwargs):
111 | """
112 | >>> pykov.Vector({'A':.3, 'B':.7})
113 | {'A':.3, 'B':.7}
114 | >>> pykov.Vector(A=.3, B=.7)
115 | {'A':.3, 'B':.7}
116 | """
117 | OrderedDict.__init__(self)
118 |
119 | if data:
120 | self.update([item for item in six.iteritems(data)
121 | if abs(item[1]) > numpy.finfo(numpy.float).eps])
122 | if len(kwargs):
123 | self.update([item for item in six.iteritems(kwargs)
124 | if abs(item[1]) > numpy.finfo(numpy.float).eps])
125 |
126 | def __getitem__(self, key):
127 | """
128 | >>> q = pykov.Vector(C=.4, B=.6)
129 | >>> q['C']
130 | 0.4
131 | >>> q['Z']
132 | 0.0
133 | """
134 | try:
135 | return OrderedDict.__getitem__(self, key)
136 | except KeyError:
137 | return 0.0
138 |
139 | def __setitem__(self, key, value):
140 | """
141 | >>> q = pykov.Vector(C=.4, B=.6)
142 | >>> q['Z']=.2
143 | >>> q
144 | {'C': 0.4, 'B': 0.6, 'Z': 0.2}
145 | >>> q['Z']=0
146 | >>> q
147 | {'C': 0.4, 'B': 0.6}
148 | """
149 | if abs(value) > numpy.finfo(numpy.float).eps:
150 | OrderedDict.__setitem__(self, key, value)
151 | elif key in self:
152 | del(self[key])
153 |
154 | def __mul__(self, M):
155 | """
156 | >>> p = pykov.Vector(A=.3, B=.7)
157 | >>> p * 3
158 | {'A': 0.9, 'B': 2.1}
159 | >>> q = pykov.Vector(C=.5, B=.5)
160 | >>> p * q
161 | 0.35
162 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
163 | >>> p * T
164 | {'A': 0.91, 'B': 0.09}
165 | >>> T * p
166 | {'A': 0.42, 'B': 0.3}
167 | """
168 | if isinstance(M, int) or isinstance(M, float):
169 | return self.__rmul__(M)
170 | if isinstance(M, Matrix):
171 | e2p, p2e = M._el2pos_()
172 | x = self._toarray(e2p)
173 | A = M._dok_(e2p).tocsr().transpose()
174 | y = A.dot(x)
175 | result = Vector()
176 | result._fromarray(y, e2p)
177 | return result
178 | elif isinstance(M, Vector):
179 | result = 0
180 | for state, value in six.iteritems(self):
181 | result += value * M[state]
182 | return result
183 | else:
184 | raise TypeError('unsupported operand type(s) for *:' +
185 | ' \'Vector\' and ' + repr(type(M))[7:-1])
186 |
187 | def __rmul__(self, M):
188 | """
189 | >>> p = pykov.Vector(A=.3, B=.7)
190 | >>> 3 * p
191 | {'A': 0.9, 'B': 2.1}
192 | """
193 | if isinstance(M, int) or isinstance(M, float):
194 | result = Vector()
195 | for state, value in six.iteritems(self):
196 | result[state] = value * M
197 | return result
198 | else:
199 | raise TypeError('unsupported operand type(s) for *: ' +
200 | repr(type(M))[7:-1] + ' and \'Vector\'')
201 |
202 | def __add__(self, v):
203 | """
204 | >>> p = pykov.Vector(A=.3, B=.7)
205 | >>> q = pykov.Vector(C=.5, B=.5)
206 | >>> p + q
207 | {'A': 0.3, 'C': 0.5, 'B': 1.2}
208 | """
209 | if isinstance(v, Vector):
210 | result = Vector()
211 | for state in set(six.iterkeys(self)) | set(v.keys()):
212 | result[state] = self[state] + v[state]
213 | return result
214 | else:
215 | raise TypeError('unsupported operand type(s) for +:' +
216 | ' \'Vector\' and ' + repr(type(v))[7:-1])
217 |
218 | def __sub__(self, v):
219 | """
220 | >>> p = pykov.Vector(A=.3, B=.7)
221 | >>> q = pykov.Vector(C=.5, B=.5)
222 | >>> p - q
223 | {'A': 0.3, 'C': -0.5, 'B': 0.2}
224 | >>> q - p
225 | {'A': -0.3, 'C': 0.5, 'B': -0.2}
226 | """
227 | if isinstance(v, Vector):
228 | result = Vector()
229 | for state in set(six.iterkeys(self)) | set(v.keys()):
230 | result[state] = self[state] - v[state]
231 | return result
232 | else:
233 | raise TypeError('unsupported operand type(s) for -:' +
234 | ' \'Vector\' and ' + repr(type(v))[7:-1])
235 |
236 | def _toarray(self, el2pos):
237 | """
238 | >>> p = pykov.Vector(A=.3, B=.7)
239 | >>> el2pos = {'A': 1, 'B': 0}
240 | >>> v = p._toarray(el2pos)
241 | >>> v
242 | array([ 0.7, 0.3])
243 | """
244 | p = numpy.zeros(len(el2pos))
245 | for key, value in six.iteritems(self):
246 | p[el2pos[key]] = value
247 | return p
248 |
249 | def _fromarray(self, arr, el2pos):
250 | """
251 | >>> p = pykov.Vector()
252 | >>> el2pos = {'A': 1, 'B': 0}
253 | >>> v = numpy.array([ 0.7, 0.3])
254 | >>> p._fromarray(v,el2pos)
255 | >>> p
256 | {'A': 0.3, 'B': 0.7}
257 | """
258 | for elem, pos in el2pos.items():
259 | self[elem] = arr[pos]
260 | return None
261 |
262 | def sort(self, reverse=False):
263 | """
264 | List of (state,probability) sorted according the probability.
265 |
266 | >>> p = pykov.Vector({'A':.3, 'B':.1, 'C':.6})
267 | >>> p.sort()
268 | [('B', 0.1), ('A', 0.3), ('C', 0.6)]
269 | >>> p.sort(reverse=True)
270 | [('C', 0.6), ('A', 0.3), ('B', 0.1)]
271 | """
272 | res = list(six.iteritems(self))
273 | res.sort(key=lambda lst: lst[1], reverse=reverse)
274 | return res
275 |
276 | def normalize(self):
277 | """
278 | Normalize the vector so that the entries sum is 1.
279 |
280 | >>> p = pykov.Vector({'A':3, 'B':1, 'C':6})
281 | >>> p.normalize()
282 | >>> p
283 | {'A': 0.3, 'C': 0.6, 'B': 0.1}
284 | """
285 | s = self.sum()
286 | for k in six.iterkeys(self):
287 | self[k] = self[k] / s
288 |
289 | def choose(self, random_func = None):
290 | """
291 | Choose a state according to its probability.
292 |
293 | >>> p = pykov.Vector(A=.3, B=.7)
294 | >>> p.choose()
295 | 'B'
296 |
297 | Optionally, a function that generates a random number can be supplied.
298 | >>> def FakeRandom(min, max): return 0.01
299 | >>> p = pykov.Vector(A=.05, B=.4, C=.4, D=.15)
300 | >>> p.choose(FakeRandom)
301 | 'A'
302 |
303 | .. seealso::
304 |
305 | `Kevin Parks recipe `_
306 | """
307 | if random_func is None:
308 | random_func = random.uniform
309 | n = random_func(0, 1)
310 | for state, prob in six.iteritems(self):
311 | if n < prob:
312 | break
313 | n = n - prob
314 | return state
315 |
316 | def entropy(self):
317 | """
318 | Return the entropy.
319 |
320 | .. math::
321 |
322 | H(p) = \sum_i p_i \ln p_i
323 |
324 | .. seealso::
325 |
326 | Khinchin, A. I.
327 | Mathematical Foundations of Information Theory
328 | Dover, 1957.
329 |
330 | >>> p = pykov.Vector(A=.3, B=.7)
331 | >>> p.entropy()
332 | 0.6108643020548935
333 | """
334 | return -sum([v * math.log(v) for v in self.values()])
335 |
336 | def relative_entropy(self, p):
337 | """
338 | Return the Kullback-Leibler distance.
339 |
340 | .. math::
341 |
342 | d(q,p) = \sum_i q_i \ln (q_i/p_i)
343 |
344 | .. note::
345 |
346 | The Kullback-Leibler distance is not symmetric.
347 |
348 | >>> p = pykov.Vector(A=.3, B=.7)
349 | >>> q = pykov.Vector(A=.4, B=.6)
350 | >>> p.relative_entropy(q)
351 | 0.02160085414354654
352 | >>> q.relative_entropy(p)
353 | 0.022582421084357485
354 | """
355 | states = set(six.iterkeys(self)) & set(p.keys())
356 | return sum([self[s] * math.log(self[s] / p[s]) for s in states])
357 |
358 | def copy(self):
359 | """
360 | Return a shallow copy.
361 |
362 | >>> p = pykov.Vector(A=.3, B=.7)
363 | >>> q = p.copy()
364 | >>> p['C'] = 1.
365 | >>> q
366 | {'A': 0.3, 'B': 0.7}
367 | """
368 | return Vector(self)
369 |
370 | def sum(self):
371 | """
372 | Sum the values.
373 |
374 | >>> p = pykov.Vector(A=.3, B=.7)
375 | >>> p.sum()
376 | 1.0
377 | """
378 | return float(sum(self.values()))
379 |
380 | def dist(self, v):
381 | """
382 | Return the distance between the two probability vectors.
383 |
384 | .. math::
385 |
386 | d(q,p) = \sum_i |q_i - p_i|
387 |
388 | >>> p = pykov.Vector(A=.3, B=.7)
389 | >>> q = pykov.Vector(C=.5, B=.5)
390 | >>> q.dist(p)
391 | 1.0
392 | """
393 | if isinstance(v, Vector):
394 | result = 0
395 | for state in set(six.iterkeys(self)) | set(v.keys()):
396 | result += abs(v[state] - self[state])
397 | return result
398 |
399 |
400 | class Matrix(OrderedDict):
401 |
402 | """
403 | """
404 |
405 | def __init__(self, data=None):
406 | """
407 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
408 | """
409 | OrderedDict.__init__(self)
410 |
411 | if data:
412 | self.update([item for item in six.iteritems(data)
413 | if abs(item[1]) > numpy.finfo(numpy.float).eps])
414 |
415 | def __getitem__(self, *args):
416 | """
417 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
418 | >>> T[('A','B')]
419 | 0.3
420 | >>> T['A','B']
421 | 0.3
422 | >>>
423 | 0.0
424 | """
425 | try:
426 | return OrderedDict.__getitem__(self, args[0])
427 | except KeyError:
428 | return 0.0
429 |
430 | @_del_cache
431 | def __setitem__(self, key, value):
432 | """
433 | >>> T = pykov.Matrix()
434 | >>> T[('A','B')] = .3
435 | >>> T
436 | {('A', 'B'): 0.3}
437 | >>> T['A','A'] = .7
438 | >>> T
439 | {('A', 'B'): 0.3, ('A', 'A'): 0.7}
440 | >>> T['B','B'] = 0
441 | >>> T
442 | {('A', 'B'): 0.3, ('A', 'A'): 0.7}
443 | >>> T['A','A'] = 0
444 | >>> T
445 | {('A', 'B'): 0.3}
446 |
447 | >>> T = pykov.Matrix({('A','B'): 3, ('A','A'): 7, ('B','A'): .1})
448 | >>> T.states()
449 | {'A', 'B'}
450 | >>> T['A','C']=1
451 | >>> T.states()
452 | {'A', 'B', 'C'}
453 | >>> T['A','C']=0
454 | >>> T.states()
455 | {'A', 'B'}
456 | """
457 | if abs(value) > numpy.finfo(numpy.float).eps:
458 | OrderedDict.__setitem__(self, key, value)
459 | elif key in self:
460 | del(self[key])
461 |
462 | @_del_cache
463 | def __delitem__(self, key):
464 | """
465 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
466 | >>> del(T['B', 'A'])
467 | >>> T
468 | {('A', 'B'): 0.3, ('A', 'A'): 0.7}
469 | """
470 | OrderedDict.__delitem__(self, key)
471 |
472 | @_del_cache
473 | def pop(self, key):
474 | """
475 | Remove specified key and return the corresponding value.
476 | See: help(OrderedDict.pop)
477 |
478 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
479 | >>> T.pop(('A','B'))
480 | 0.3
481 | >>> T
482 | {('B', 'A'): 1.0, ('A', 'A'): 0.7}
483 | """
484 | return OrderedDict.pop(self, key)
485 |
486 | @_del_cache
487 | def popitem(self):
488 | """
489 | Remove and return some (key, value) pair as a 2-tuple.
490 | See: help(OrderedDict.popitem)
491 |
492 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
493 | >>> T.popitem()
494 | (('B', 'A'), 1.0)
495 | >>> T
496 | {('A', 'B'): 0.3, ('A', 'A'): 0.7}
497 | """
498 | return OrderedDict.popitem(self)
499 |
500 | @_del_cache
501 | def clear(self):
502 | """
503 | Remove all keys.
504 | See: help(OrderedDict.clear)
505 |
506 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
507 | >>> T.clear()
508 | >>> T
509 | {}
510 | """
511 | OrderedDict.clear(self)
512 |
513 | @_del_cache
514 | def update(self, other):
515 | """
516 | Update with keys and their values present in other.
517 | See: help(OrderedDict.update)
518 |
519 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
520 | >>> d = {('B', 'C'):2}
521 | >>> T.update(d)
522 | >>> T
523 | {('B', 'A'): 1.0, ('B', 'C'): 2, ('A', 'B'): 0.3, ('A', 'A'): 0.7}
524 | """
525 | OrderedDict.update(self, other)
526 |
527 | @_del_cache
528 | def setdefault(self, k, *args):
529 | """
530 | See: help(OrderedDict.setdefault)
531 |
532 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
533 | >>> T.setdefault(('A','A'),1)
534 | 0.7
535 | >>> T
536 | {('B', 'A'): 1.0, ('A', 'B'): 0.3, ('A', 'A'): 0.7}
537 | >>> T.setdefault(('A','C'),1)
538 | 1
539 | >>> T
540 | {('B', 'A'): 1.0, ('A', 'B'): 0.3, ('A', 'A'): 0.7, ('A', 'C'): 1}
541 | """
542 | return OrderedDict.setdefault(self, k, *args)
543 |
544 | def copy(self):
545 | """
546 | Return a shallow copy.
547 |
548 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
549 | >>> W = T.copy()
550 | >>> T[('B','B')] = 1.
551 | >>> W
552 | {('B', 'A'): 1.0, ('A', 'B'): 0.3, ('A', 'A'): 0.7}
553 | """
554 | return Matrix(self)
555 |
556 | def __reduce__(self):
557 | """Return state information for pickling"""
558 | # Required because we changed the OrderedDict.__init__ signature
559 | return (self.__class__, (), None, None, six.iteritems(self))
560 |
561 | def _dok_(self, el2pos, method=''):
562 | """
563 | """
564 | m = len(el2pos)
565 | S = ss.dok_matrix((m, m))
566 | if method == '':
567 | for k, v in six.iteritems(self):
568 | i = el2pos[k[0]]
569 | j = el2pos[k[1]]
570 | S[i, j] = float(v)
571 | elif method == 'transpose':
572 | for k, v in six.iteritems(self):
573 | i = el2pos[k[0]]
574 | j = el2pos[k[1]]
575 | S[j, i] = float(v)
576 | return S
577 |
578 | def _from_dok_(self, mat, pos2el):
579 | """
580 | """
581 | for ii, val in mat.items():
582 | self[pos2el[ii[0]], pos2el[ii[1]]] = val
583 | return None
584 |
585 | def _numpy_mat(self, el2pos):
586 | """
587 | Return a numpy.matrix object from a dictionary.
588 |
589 | -- Parameters --
590 | t_ij : the OrderedDict, values must be real numbers, keys should be tuples of
591 | two strings.
592 | el2pos : see _map()
593 | """
594 | m = len(el2pos)
595 | T = numpy.matrix(numpy.zeros((m, m)))
596 | for k, v in six.iteritems(self):
597 | T[el2pos[k[0]], el2pos[k[1]]] = v
598 | return T
599 |
600 | def _from_numpy_mat(self, T, pos2el):
601 | """
602 | Return a dictionary from a numpy.matrix object.
603 |
604 | -- Parameters --
605 | T : the numpy.matrix.
606 | pos2el : see _map()
607 | """
608 | for i in range(len(T)):
609 | for j in range(len(T)):
610 | if T[i, j]:
611 | self[(pos2el[i], pos2el[j])] = T[i, j]
612 | return None
613 |
614 | def _el2pos_(self):
615 | """
616 | """
617 | el2pos = {}
618 | pos2el = {}
619 | for pos, element in enumerate(list(self.states())):
620 | el2pos[element] = pos
621 | pos2el[pos] = element
622 | return el2pos, pos2el
623 |
624 | def stochastic(self):
625 | """
626 | Make a right stochastic matrix.
627 |
628 | Set the sum of every row equal to one,
629 | raise ``PykovError`` if it is not possible.
630 |
631 | >>> T = pykov.Matrix({('A','B'): 3, ('A','A'): 7, ('B','A'): .2})
632 | >>> T.stochastic()
633 | >>> T
634 | {('B', 'A'): 1.0, ('A', 'B'): 0.3, ('A', 'A'): 0.7}
635 | >>> T[('A','C')]=1
636 | >>> T.stochastic()
637 | pykov.PykovError: 'Zero links from node C'
638 | """
639 | s = {}
640 | for k, v in self.succ().items():
641 | summ = float(sum(v.values()))
642 | if summ:
643 | s[k] = summ
644 | else:
645 | raise PykovError('Zero links from state ' + k)
646 | for k in six.iterkeys(self):
647 | self[k] = self[k] / s[k[0]]
648 |
649 | def pred(self, key=None):
650 | """
651 | Return the precedessors of a state (if not indicated, of all states).
652 | In Matrix notation: return the coloum of the indicated state.
653 |
654 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
655 | >>> T.pred()
656 | {'A': {'A': 0.7, 'B': 1.0}, 'B': {'A': 0.3}}
657 | >>> T.pred('A')
658 | {'A': 0.7, 'B': 1.0}
659 | """
660 | try:
661 | if key is not None:
662 | return self._pred[key]
663 | else:
664 | return self._pred
665 | except AttributeError:
666 | self._pred = OrderedDict([(state, Vector()) for state in self.states()])
667 | for link, probability in six.iteritems(self):
668 | self._pred[link[1]][link[0]] = probability
669 | if key is not None:
670 | return self._pred[key]
671 | else:
672 | return self._pred
673 |
674 | def succ(self, key=None):
675 | """
676 | Return the successors of a state (if not indicated, of all states).
677 | In Matrix notation: return the row of the indicated state.
678 |
679 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
680 | >>> T.succ()
681 | {'A': {'A': 0.7, 'B': 0.3}, 'B': {'A': 1.0}}
682 | >>> T.succ('A')
683 | {'A': 0.7, 'B': 0.3}
684 | """
685 | try:
686 | if key is not None:
687 | return self._succ[key]
688 | else:
689 | return self._succ
690 | except AttributeError:
691 | self._succ = OrderedDict([(state, Vector()) for state in self.states()])
692 | for link, probability in six.iteritems(self):
693 | self._succ[link[0]][link[1]] = probability
694 | if key is not None:
695 | return self._succ[key]
696 | else:
697 | return self._succ
698 |
699 | def remove(self, states):
700 | """
701 | Return a copy of the Chain, without the indicated states.
702 |
703 | .. warning::
704 |
705 | All the links where the states appear are deleted, so that the result
706 | will not be in general a stochastic matrix.
707 | ..
708 |
709 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
710 | >>> T.remove(['B'])
711 | {('A', 'A'): 0.7}
712 | >>> T = pykov.Chain({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.,
713 | ('C','D'): .5, ('D','C'): 1., ('C','B'): .5})
714 | >>> T.remove(['A','B'])
715 | {('C', 'D'): 0.5, ('D', 'C'): 1.0}
716 | """
717 | return Matrix(OrderedDict([(key, value) for key, value in six.iteritems(self) if
718 | key[0] not in states and key[1] not in states]))
719 |
720 | def states(self):
721 | """
722 | Return the set of states.
723 |
724 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
725 | >>> T.states()
726 | {'A', 'B'}
727 | """
728 | try:
729 | return self._states
730 | except AttributeError:
731 | self._states = set()
732 | for link in six.iterkeys(self):
733 | self._states.add(link[0])
734 | self._states.add(link[1])
735 | return self._states
736 |
737 | def __pow__(self, n):
738 | """
739 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
740 | >>> T**2
741 | {('A', 'B'): 0.21, ('B', 'A'): 0.70, ('A', 'A'): 0.79, ('B', 'B'): 0.30}
742 | >>> T**0
743 | {('A', 'A'): 1.0, ('B', 'B'): 1.0}
744 | """
745 | el2pos, pos2el = self._el2pos_()
746 | P = self._numpy_mat(el2pos)
747 | P = P**n
748 | res = Matrix()
749 | res._from_numpy_mat(P, pos2el)
750 | return res
751 |
752 | def pow(self, n):
753 | return self.__pow__(n)
754 |
755 | def __mul__(self, v):
756 | """
757 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
758 | >>> T * 3
759 | {('B', 'A'): 3.0, ('A', 'B'): 0.9, ('A', 'A'): 2.1}
760 | >>> p = pykov.Vector(A=.3, B=.7)
761 | >>> T * p
762 | {'A': 0.42, 'B': 0.3}
763 | >>> W = pykov.Matrix({('N', 'M'): 0.5, ('M', 'N'): 0.7,
764 | ('M', 'M'): 0.3, ('O', 'N'): 0.5,
765 | ('O', 'O'): 0.5, ('N', 'O'): 0.5})
766 | >>> W * W
767 | {('N', 'M'): 0.15, ('M', 'N'): 0.21, ('M', 'O'): 0.35,
768 | ('M', 'M'): 0.44, ('O', 'M'): 0.25, ('O', 'N'): 0.25,
769 | ('O', 'O'): 0.5, ('N', 'O'): 0.25, ('N', 'N'): 0.6}
770 | """
771 | if isinstance(v, Vector):
772 | e2p, p2e = self._el2pos_()
773 | x = v._toarray(e2p)
774 | M = self._dok_(e2p).tocsr()
775 | y = M.dot(x)
776 | result = Vector()
777 | result._fromarray(y, e2p)
778 | return result
779 | elif isinstance(v, Matrix):
780 | e2p, p2e = self._el2pos_()
781 | M = self._dok_(e2p).tocsr()
782 | N = v._dok_(e2p).tocsr()
783 | C = M.dot(N).todok()
784 | if 'Chain' in repr(self.__class__):
785 | res = Chain()
786 | elif 'Matrix' in repr(self.__class__):
787 | res = Matrix()
788 | res._from_dok_(C, p2e)
789 | return res
790 | elif isinstance(v, int) or isinstance(v, float):
791 | return Matrix(OrderedDict([(key, value * v) for key, value in
792 | six.iteritems(self)]))
793 | else:
794 | raise TypeError('unsupported operand type(s) for *:' +
795 | ' \'Matrix\' and ' + repr(type(v))[7:-1])
796 |
797 | def __rmul__(self, v):
798 | """
799 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
800 | >>> 3 * T
801 | {('B', 'A'): 3.0, ('A', 'B'): 0.9, ('A', 'A'): 2.1}
802 | """
803 | if isinstance(v, int) or isinstance(v, float):
804 | return Matrix(OrderedDict([(key, value * v) for key, value in
805 | six.iteritems(self)]))
806 | else:
807 | raise TypeError('unsupported operand type(s) for *:' +
808 | ' \'Matrix\' and ' + repr(type(v))[7:-1])
809 |
810 | def __add__(self, M):
811 | """
812 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
813 | >>> I = pykov.Matrix({('A','A'):1, ('B','B'):1})
814 | >>> T + I
815 | {('B', 'A'): 1.0, ('A', 'B'): 0.3, ('A', 'A'): 1.7, ('B', 'B'): 1.0}
816 | """
817 | if isinstance(M, Matrix):
818 | result = Matrix()
819 | for link in set(six.iterkeys(self)) | set(M.keys()):
820 | result[link] = self[link] + M[link]
821 | return result
822 | else:
823 | raise TypeError('unsupported operand type(s) for +:' +
824 | ' \'Matrix\' and ' + repr(type(M))[7:-1])
825 |
826 | def __sub__(self, M):
827 | """
828 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
829 | >>> I = pykov.Matrix({('A','A'):1, ('B','B'):1})
830 | >>> T - I
831 | {('B', 'A'): 1.0, ('A', 'B'): 0.3, ('A', 'A'): -0.3, ('B', 'B'): -1}
832 | """
833 | if isinstance(M, Matrix):
834 | result = Matrix()
835 | for link in set(six.iterkeys(self)) | set(M.keys()):
836 | result[link] = self[link] - M[link]
837 | return result
838 | else:
839 | raise TypeError('unsupported operand type(s) for -:' +
840 | ' \'Matrix\' and ' + repr(type(M))[7:-1])
841 |
842 | def trace(self):
843 | """
844 | Return the Matrix trace.
845 |
846 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
847 | >>> T.trace()
848 | 0.7
849 | """
850 | return sum([self[k, k] for k in self.states()])
851 |
852 | def eye(self):
853 | """
854 | Return the Identity Matrix.
855 |
856 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
857 | >>> T.eye()
858 | {('A', 'A'): 1., ('B', 'B'): 1.}
859 | """
860 | return Matrix(OrderedDict([((state, state), 1.) for state in self.states()]))
861 |
862 | def ones(self):
863 | """
864 | Return a ``Vector`` instance with entries equal to one.
865 |
866 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
867 | >>> T.ones()
868 | {'A': 1.0, 'B': 1.0}
869 | """
870 | return Vector(OrderedDict([(state, 1.) for state in self.states()]))
871 |
872 | def transpose(self):
873 | """
874 | Return the transpose Matrix.
875 |
876 | >>> T = pykov.Matrix({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
877 | >>> T.transpose()
878 | {('B', 'A'): 0.3, ('A', 'B'): 1.0, ('A', 'A'): 0.7}
879 | """
880 | return Matrix(OrderedDict([((key[1], key[0]), value) for key, value in
881 | six.iteritems(self)]))
882 |
883 | def _UMPFPACKSolve(self, b, x=None, method='UMFPACK_A'):
884 | """
885 | UMFPACK ( U nsymmetric M ulti F Rontal PACK age)
886 |
887 | Parameters
888 | ----------
889 | method:
890 | "UMFPACK_A" : \mathbf{A} x = b (default)
891 | "UMFPACK_At" : \mathbf{A}^T x = b
892 |
893 | References
894 | ----------
895 | A column pre-ordering strategy for the unsymmetric-pattern multifrontal
896 | method, T. A. Davis, ACM Transactions on Mathematical Software, vol 30,
897 | no. 2, June 2004, pp. 165-195.
898 | """
899 | e2p, p2e = self._el2pos_()
900 | if method == "UMFPACK_At":
901 | A = self._dok_(e2p).tocsr().transpose()
902 | else:
903 | A = self._dok_(e2p).tocsr()
904 | bb = b._toarray(e2p)
905 | x = ssl.spsolve(A, bb, use_umfpack=True)
906 | res = Vector()
907 | res._fromarray(x, e2p)
908 | return res
909 |
910 |
911 | class Chain(Matrix):
912 |
913 | """
914 | """
915 |
916 | def move(self, state, random_func = None):
917 | """
918 | Do one step from the indicated state, and return the final state.
919 |
920 | >>> T = pykov.Chain({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
921 | >>> T.move('A')
922 | 'B'
923 |
924 | Optionally, a function that generates a random number can be supplied.
925 | >>> def FakeRandom(min, max): return 0.01
926 | >>> T.move('A', FakeRandom)
927 | 'B'
928 |
929 | """
930 | return self.succ(state).choose(random_func)
931 |
932 | def pow(self, p, n):
933 | """
934 | Find the probability distribution after n steps, starting from an
935 | initial ``Vector``.
936 |
937 | >>> T = pykov.Chain({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
938 | >>> p = pykov.Vector(A=1)
939 | >>> T.pow(p,3)
940 | {'A': 0.7629999999999999, 'B': 0.23699999999999996}
941 | >>> p * T * T * T
942 | {'A': 0.7629999999999999, 'B': 0.23699999999999996}
943 | """
944 | return p * self**n
945 |
946 | def steady(self):
947 | """
948 | With the assumption of ergodicity, return the steady state.
949 |
950 | .. note::
951 |
952 | Inverse iteration method (P is the Markov chain)
953 |
954 | .. math::
955 |
956 | Q = \mathbf{I} - P
957 |
958 | Q^T x = e
959 |
960 | e = (0,0,\dots,0,1)
961 | ..
962 | ..
963 |
964 |
965 | .. seealso::
966 |
967 | W. Stewart: Introduction to the Numerical Solution of Markov Chains,
968 | Princeton University Press, Chichester, West Sussex, 1994.
969 |
970 | >>> T = pykov.Chain({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
971 | >>> T.steady()
972 | {'A': 0.7692307692307676, 'B': 0.23076923076923028}
973 | """
974 | try:
975 | return self._steady
976 | except AttributeError:
977 | e2p, p2e = self._el2pos_()
978 | m = len(e2p)
979 | P = self._dok_(e2p).tocsr()
980 | Q = ss.eye(m, format='csr') - P
981 | e = numpy.zeros(m)
982 | e[-1] = 1.
983 | Q = Q.transpose()
984 | # not elegant singular matrix error
985 | Q[0, 0] = Q[0, 0] + _machineEpsilon()
986 | x = ssl.spsolve(Q, e, use_umfpack=True)
987 | x = x/sum(x)
988 | res = Vector()
989 | res._fromarray(x, e2p)
990 | self._steady = res
991 | return res
992 |
993 | def entropy(self, p=None, norm=False):
994 | """
995 | Return the ``Chain`` entropy, calculated with the indicated probability
996 | Vector (the steady state by default).
997 |
998 | .. math::
999 |
1000 | H_i = \sum_j P_{ij} \ln P_{ij}
1001 |
1002 | H = \sum \pi_i H_i
1003 |
1004 | .. seealso::
1005 |
1006 | Khinchin, A. I.
1007 | Mathematical Foundations of Information Theory
1008 | Dover, 1957.
1009 |
1010 | >>> T = pykov.Chain({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
1011 | >>> T.entropy()
1012 | 0.46989561696530169
1013 |
1014 | With normalization entropy belongs to [0,1]
1015 |
1016 | >>> T.entropy(norm=True)
1017 | 0.33895603665233132
1018 |
1019 | """
1020 | if not p:
1021 | p = self.steady()
1022 | H = 0.
1023 | for state in self.states():
1024 | H += p[state] * sum([v * math.log(v) for v in
1025 | self.succ(state).values()])
1026 | if norm:
1027 | n = len(self.states())
1028 | return -H / (n * math.log(n))
1029 | return -H
1030 |
1031 | def mfpt_to(self, state):
1032 | """
1033 | Return the Mean First Passage Times of every state to the indicated
1034 | state.
1035 |
1036 | .. seealso::
1037 |
1038 | Kemeny J. G.; Snell, J. L.
1039 | Finite Markov Chains.
1040 | Springer-Verlag: New York, 1976.
1041 |
1042 | >>> d = {('R', 'N'): 0.25, ('R', 'S'): 0.25, ('S', 'R'): 0.25,
1043 | ('R', 'R'): 0.5, ('N', 'S'): 0.5, ('S', 'S'): 0.5,
1044 | ('S', 'N'): 0.25, ('N', 'R'): 0.5, ('N', 'N'): 0.0}
1045 | >>> T = pykov.Chain(d)
1046 | >>> T.mfpt_to('R')
1047 | {'S': 3.333333333333333, 'N': 2.666666666666667}
1048 | """
1049 | if len(self.states()) == 2:
1050 | self.states().remove(state)
1051 | other = self.states().pop()
1052 | self.states().add(state)
1053 | self.states().add(other)
1054 | return Vector({other: 1. / self[other, state]})
1055 | T = self.remove([state])
1056 | T = T.eye() - T
1057 | return T._UMPFPACKSolve(T.ones())
1058 |
1059 | def adjacency(self):
1060 | """
1061 | Return the adjacency matrix.
1062 |
1063 | >>> T = pykov.Chain({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
1064 | >>> T.adjacency()
1065 | {('B', 'A'): 1, ('A', 'B'): 1, ('A', 'A'): 1}
1066 | """
1067 | return Matrix(OrderedDict.fromkeys(self, 1))
1068 |
1069 | def walk(self, steps, start=None, stop=None):
1070 | """
1071 | Return a random walk of n steps, starting and stopping at the
1072 | indicated states.
1073 |
1074 | .. note::
1075 |
1076 | If not indicated or is `None`, then the starting state is chosen
1077 | according to its steady probability.
1078 | If the stopping state is not `None`, the random walk stops early if
1079 | the stopping state is reached.
1080 |
1081 | >>> T = pykov.Chain({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
1082 | >>> T.walk(10)
1083 | ['B', 'A', 'B', 'A', 'A', 'B', 'A', 'A', 'A', 'B', 'A']
1084 | >>> T.walk(10,'B','B')
1085 | ['B', 'A', 'A', 'A', 'A', 'A', 'B']
1086 | """
1087 | if start is None:
1088 | steady = self.steady()
1089 | if len(steady) != 0:
1090 | start = steady.choose()
1091 | else:
1092 | # There is no steady state, so choose a state uniformly at
1093 | # random.
1094 | start = random.sample(self.states(), 1)[0]
1095 | if stop is None:
1096 | result = [start]
1097 | for i in range(steps):
1098 | result.append(self.move(result[-1]))
1099 | return result
1100 | else:
1101 | result = [start]
1102 | for i in range(steps):
1103 | result.append(self.move(result[-1]))
1104 | if result[-1] == stop:
1105 | return result
1106 | return result
1107 |
1108 | def walk_probability(self, walk):
1109 | """
1110 | Given a walk, return the log of its probability.
1111 |
1112 | >>> T = pykov.Chain({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
1113 | >>> T.walk_probability(['A','A','B','A','A'])
1114 | -1.917322692203401
1115 | >>> probability = math.exp(-1.917322692203401)
1116 | 0.147
1117 | >>> p = T.walk_probability(['A','B','B','B','A'])
1118 | >>> math.exp(p)
1119 | 0.0
1120 | """
1121 | res = 0
1122 | for step in zip(walk[:-1], walk[1:]):
1123 | if not self[step]:
1124 | return -float('Inf')
1125 | res += math.log(self[step])
1126 | return res
1127 |
1128 | def mixing_time(self, cutoff=.25, jump=1, p=None):
1129 | """
1130 | Return the mixing time.
1131 |
1132 | If the initial distribution (p) is not indicated,
1133 | then it is set to p={'less probable state':1}.
1134 |
1135 | .. note::
1136 |
1137 | The mixing time is calculated here as the number of steps (n) needed to
1138 | have
1139 |
1140 | .. math::
1141 |
1142 | |p(n)-\pi| < 0.25
1143 |
1144 | p(n)=p P^n
1145 |
1146 | \pi=\pi P
1147 | ..
1148 |
1149 | The parameter ``jump`` controls the iteration step, for example with
1150 | ``jump=2`` n has values 2,4,6,8,..
1151 | ..
1152 |
1153 | >>> d = {('R','R'):1./2, ('R','N'):1./4, ('R','S'):1./4,
1154 | ('N','R'):1./2, ('N','N'):0., ('N','S'):1./2,
1155 | ('S','R'):1./4, ('S','N'):1./4, ('S','S'):1./2}
1156 | >>> T = pykov.Chain(d)
1157 | >>> T.mixing_time()
1158 | 2
1159 | """
1160 | res = []
1161 | d = 1
1162 | n = 0
1163 | if not p:
1164 | p = Vector({self.steady().sort()[0][0]: 1})
1165 | res.append(p.dist(self.steady()))
1166 | while d > cutoff:
1167 | n = n + jump
1168 | p = self.pow(p, jump)
1169 | d = p.dist(self.steady())
1170 | res.append(d)
1171 | return n
1172 |
1173 | def absorbing_time(self, transient_set):
1174 | """
1175 | Mean number of steps needed to leave the transient set.
1176 |
1177 | Return the ``Vector tau``, the ``tau[i]`` is the mean number of steps needed
1178 | to leave the transient set starting from state ``i``. The parameter
1179 | ``transient_set`` is a subset of nodes.
1180 |
1181 | .. note::
1182 |
1183 | If the starting point is a ``Vector p``, then it is sufficient to
1184 | calculate ``p * tau`` in order to weigh the mean times according the
1185 | initial conditions.
1186 |
1187 |
1188 | .. seealso:
1189 |
1190 | Kemeny J. G.; Snell, J. L.
1191 | Finite Markov Chains.
1192 | Springer-Verlag: New York, 1976.
1193 |
1194 | >>> d = {('R','R'):1./2, ('R','N'):1./4, ('R','S'):1./4,
1195 | ('N','R'):1./2, ('N','N'):0., ('N','S'):1./2,
1196 | ('S','R'):1./4, ('S','N'):1./4, ('S','S'):1./2}
1197 | >>> T = pykov.Chain(d)
1198 | >>> p = pykov.Vector({'N':.3, 'S':.7})
1199 | >>> tau = T.absorbing_time(p.keys())
1200 | >>> p * tau
1201 | 3.1333333333333329
1202 | """
1203 | Q = self.remove(self.states() - set(transient_set))
1204 | K = Q.eye() - Q
1205 | # means
1206 | tau = K._UMPFPACKSolve(K.ones())
1207 | return tau
1208 |
1209 | def absorbing_tour(self, p, transient_set=None):
1210 | """
1211 | Return a ``Vector v``, ``v[i]`` is the mean of the total number of times
1212 | the process is in a given transient state ``i`` before to leave the
1213 | transient set.
1214 |
1215 | .. note::
1216 | ``v.sum()`` is equal to ``p * tau`` (see :meth:`absorbing_time` method).
1217 |
1218 | In not specified, the ``transient set`` is defined
1219 | by means of the ``Vector p``.
1220 |
1221 | .. seealso::
1222 |
1223 | Kemeny J. G.; Snell, J. L.
1224 | Finite Markov Chains.
1225 | Springer-Verlag: New York, 1976.
1226 |
1227 | >>> d = {('R','R'):1./2, ('R','N'):1./4, ('R','S'):1./4,
1228 | ('N','R'):1./2, ('N','N'):0., ('N','S'):1./2,
1229 | ('S','R'):1./4, ('S','N'):1./4, ('S','S'):1./2}
1230 | >>> T = pykov.Chain(d)
1231 | >>> p = pykov.Vector({'N':.3, 'S':.7})
1232 | >>> T.absorbing_tour(p)
1233 | {'S': 2.2666666666666666, 'N': 0.8666666666666669}
1234 | """
1235 | if transient_set:
1236 | Q = self.remove(self.states() - transient_set)
1237 | else:
1238 | Q = self.remove(self.states() - set(p.keys()))
1239 | K = Q.eye() - Q
1240 | return K._UMPFPACKSolve(p, method='UMFPACK_At')
1241 |
1242 | def fundamental_matrix(self):
1243 | """
1244 | Return the fundamental matrix.
1245 |
1246 | .. seealso::
1247 |
1248 | Kemeny J. G.; Snell, J. L.
1249 | Finite Markov Chains.
1250 | Springer-Verlag: New York, 1976.
1251 |
1252 | >>> T = pykov.Chain({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
1253 | >>> T.fundamental_matrix()
1254 | {('B', 'A'): 0.17751479289940991, ('A', 'B'): 0.053254437869822958,
1255 | ('A', 'A'): 0.94674556213017902, ('B', 'B'): 0.82248520710059214}
1256 | """
1257 | try:
1258 | return self._fundamental_matrix
1259 | except AttributeError:
1260 | el2pos, pos2el = self._el2pos_()
1261 | p = self.steady()._toarray(el2pos)
1262 | P = self._numpy_mat(el2pos)
1263 | d = len(p)
1264 | A = numpy.matrix([p for i in range(d)])
1265 | I = numpy.matrix(numpy.identity(d))
1266 | E = numpy.matrix(numpy.ones((d, d)))
1267 | D = numpy.zeros((d, d))
1268 | diag = 1. / p
1269 | for pos, val in enumerate(diag):
1270 | D[pos, pos] = val
1271 | Z = numpy.linalg.inv(I - P + A)
1272 | res = Matrix()
1273 | res._from_numpy_mat(Z, pos2el)
1274 | self._fundamental_matrix = res
1275 | return res
1276 |
1277 | def kemeny_constant(self):
1278 | """
1279 | Return the Kemeny constant of the transition matrix.
1280 |
1281 | >>> T = pykov.Chain({('A','B'): .3, ('A','A'): .7, ('B','A'): 1.})
1282 | >>> T.kemeny_constant()
1283 | 1.7692307692307712
1284 | """
1285 | Z = self.fundamental_matrix()
1286 | return Z.trace()
1287 |
1288 |
1289 | def accessibility_matrix(self):
1290 | """
1291 | Return the accessibility matrix of the Markov chain.
1292 |
1293 | ..see also: http://www.ssc.wisc.edu/~jmontgom/commclasses.pdf
1294 | """
1295 | el2pos, pos2el = self._el2pos_()
1296 | Z = self.adjacency()
1297 | I = self.eye()
1298 | n = len(self.states())
1299 |
1300 | A = (I + Z)**(n-1)
1301 | numpy_A = A._numpy_mat(el2pos)
1302 | numpy_A = numpy_A > 0
1303 | numpy_A = numpy_A.astype(int)
1304 | res = Matrix()
1305 | res._from_numpy_mat(numpy_A, pos2el)
1306 | return res
1307 |
1308 | def is_accessible(self, i, j):
1309 | """
1310 | Return whether state j is accessible from state i.
1311 | """
1312 |
1313 | A = self.accessibility_matrix()
1314 | return A.get((i, j)) > 0
1315 |
1316 | def communicates(self, i, j):
1317 | """
1318 | Return whether states i and j communicate.
1319 | """
1320 | return self.is_accessible(i, j) and self.is_accessible(j, i)
1321 |
1322 | def communication_classes(self):
1323 | """
1324 | Return a Set of all communication classes of the Markov chain.
1325 |
1326 | ..see also: http://www.ssc.wisc.edu/~jmontgom/commclasses.pdf
1327 |
1328 | >>> T = pykov.Chain({('A','A'): 1.0, ('B','B'): 1.0})
1329 | >>> T.communication_classes()
1330 | """
1331 | el2pos, pos2el = self._el2pos_()
1332 | A = self.accessibility_matrix()
1333 |
1334 | numpy_A = A._numpy_mat(el2pos)
1335 | numpy_A_trans = numpy.transpose(numpy_A)
1336 | numpy_res = numpy.logical_and(numpy_A, numpy_A_trans)
1337 | numpy_res = numpy_res.astype(int)
1338 |
1339 | #remove duplicate rows
1340 | #remaining rows will give communication
1341 | #ref: http://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array
1342 | a = numpy_res
1343 | b = numpy.ascontiguousarray(a).view(
1344 | numpy.dtype(
1345 | (numpy.void, a.dtype.itemsize * a.shape[1])
1346 | )
1347 | )
1348 | _, idx = numpy.unique(b, return_index=True)
1349 |
1350 | unique_a = a[idx]
1351 |
1352 | res = Set()
1353 | for row in unique_a:
1354 | #each iteration here is a comm. class
1355 | comm_class = Set()
1356 | number_of_elements = len(A.states())
1357 | for el in range(number_of_elements):
1358 | if row[0, el] == 1:
1359 | comm_class.add(pos2el[el])
1360 | res.add(comm_class)
1361 | return res
1362 |
1363 | def readmat(filename):
1364 | """
1365 | Read an external file and return a Chain.
1366 |
1367 | The file must be of the form:
1368 |
1369 | A A .7
1370 | A B .3
1371 | B A 1
1372 |
1373 | Example
1374 | -------
1375 | >>> P = pykov.readmat('/mypath/mat')
1376 | >>> P
1377 | {('B', 'A'): 1.0, ('A', 'B'): 0.3, ('A', 'A'): 0.7}
1378 | """
1379 | with open(filename) as f:
1380 | P = Chain()
1381 | for line in f:
1382 | tmp = line.split()
1383 | P[(tmp[0], tmp[1])] = float(tmp[2])
1384 | return P
1385 |
1386 |
1387 | def readtrj(filename):
1388 | """
1389 | In the case the :class:`Chain` instance must be created from a finite chain
1390 | of states, the transition matrix is not fully defined.
1391 | The function defines the transition probabilities as the maximum likelihood
1392 | probabilities calculated along the chain. Having the file ``/mypath/trj``
1393 | with the following format::
1394 |
1395 | 1
1396 | 1
1397 | 1
1398 | 2
1399 | 1
1400 | 3
1401 |
1402 | the :class:`Chain` instance defined from that chain is:
1403 |
1404 | >>> t = pykov.readtrj('/mypath/trj')
1405 | >>> t
1406 | (1, 1, 1, 2, 1, 3)
1407 | >>> p, P = maximum_likelihood_probabilities(t,lag_time=1, separator='0')
1408 | >>> p
1409 | {1: 0.6666666666666666, 2: 0.16666666666666666, 3: 0.16666666666666666}
1410 | >>> P
1411 | {(1, 2): 0.25, (1, 3): 0.25, (1, 1): 0.5, (2, 1): 1.0, (3, 3): 1.0}
1412 | >>> type(P)
1413 |
1414 | >>> type(p)
1415 |
1416 | """
1417 | with open(filename) as f:
1418 | return tuple(line.strip() for line in f)
1419 |
1420 |
1421 | def _writefile(mylist, filename):
1422 | """
1423 | Export in a file the list.
1424 |
1425 | mylist could be a list of list.
1426 |
1427 | Example
1428 | -------
1429 | >>> L = [[2,3],[4,5]]
1430 | >>> pykov.writefile(L,'tmp')
1431 | >>> l = [1,2]
1432 | >>> pykov.writefile(l,'tmp')
1433 | """
1434 | try:
1435 | L = [[str(i) for i in line] for line in mylist]
1436 | except TypeError:
1437 | L = [str(i) for i in mylist]
1438 | with open(filename, mode='w') as f:
1439 | tmp = '\n'.join('\t'.join(x) for x in L)
1440 | f.write(tmp)
1441 | return None
1442 |
1443 |
1444 | def transitions(trj, nsteps=1, lag_time=1, separator='0'):
1445 | """
1446 | Return the temporal list of transitions observed.
1447 |
1448 | Parameters
1449 | ----------
1450 | trj : the symbolic trajectory.
1451 | nsteps : number of steps.
1452 | lag_time : step length.
1453 | separator: the special symbol indicating the presence of sub-trajectories.
1454 |
1455 | Example
1456 | -------
1457 | >>> trj = [1,2,1,0,2,3,1,0,2,3,2,3,1,2,3]
1458 | >>> pykov.transitions(trj,1,1,0)
1459 | [(1, 2), (2, 1), (2, 3), (3, 1), (2, 3), (3, 2), (2, 3), (3, 1), (1, 2),
1460 | (2, 3)]
1461 | >>> pykov.transitions(trj,1,2,0)
1462 | [(1, 1), (2, 1), (2, 2), (3, 3), (2, 1), (3, 2), (1, 3)]
1463 | >>> pykov.transitions(trj,2,2,0)
1464 | [(2, 2, 1), (3, 3, 2), (2, 1, 3)]
1465 | """
1466 | result = []
1467 | for pos in range(len(trj) - nsteps * lag_time):
1468 | if separator not in trj[pos:(pos + nsteps * lag_time + 1)]:
1469 | tmp = trj[pos:(pos + nsteps * lag_time + 1):lag_time]
1470 | result.append(tuple(tmp))
1471 | return result
1472 |
1473 |
1474 | def maximum_likelihood_probabilities(trj, lag_time=1, separator='0'):
1475 | """
1476 | Return a Chain calculated by means of maximum likelihood probabilities.
1477 |
1478 | Return two objects:
1479 | p : a Vector object, the probability distribution over the nodes.
1480 | T : a Chain object, the Markov chain.
1481 |
1482 | Parameters
1483 | ----------
1484 | trj : the symbolic trajectory.
1485 | lag_time : number of steps defining a transition.
1486 | separator: the special symbol indicating the presence of sub-trajectories.
1487 |
1488 | Example
1489 | -------
1490 | >>> t = [1,2,3,2,3,2,1,2,2,3,3,2]
1491 | >>> p, T = pykov.maximum_likelihood_probabilities(t)
1492 | >>> p
1493 | {1: 0.18181818181818182, 2: 0.4545454545454546, 3: 0.36363636363636365}
1494 | >>> T
1495 | {(1, 2): 1.0, (3, 2): 0.7499999999999999, (2, 3): 0.5999999999999999, (3,
1496 | 3): 0.25, (2, 2): 0.19999999999999998, (2, 1): 0.19999999999999998}
1497 | """
1498 | q_ij = {}
1499 | tr = transitions(trj, nsteps=1, lag_time=lag_time, separator=separator)
1500 | _remove_dead_branch(tr)
1501 | tot = len(tr)
1502 | for step in tr:
1503 | q_ij[step] = q_ij.get(step, 0.) + 1
1504 | for key in q_ij.keys():
1505 | q_ij[key] = q_ij[key] / tot
1506 | p_i = {}
1507 | for k, v in q_ij.items():
1508 | p_i[k[0]] = p_i.get(k[0], 0) + v
1509 | t_ij = {}
1510 | for k, v in q_ij.items():
1511 | t_ij[k] = v / p_i[k[0]]
1512 | T = Chain(t_ij)
1513 | p = Vector(p_i)
1514 | T._guess = Vector(p_i)
1515 | return p, T
1516 |
1517 |
1518 | def _remove_dead_branch(transitions_list):
1519 | """
1520 | Remove dead branchs inserting a selfloop in every node that has not
1521 | outgoing links.
1522 |
1523 | Example
1524 | -------
1525 | >>> trj = [1,2,3,1,2,3,2,2,4,3,5]
1526 | >>> tr = pykov.transitions(trj, nsteps=1)
1527 | >>> tr
1528 | [(1, 2), (2, 3), (3, 1), (1, 2), (2, 3), (3, 2), (2, 2), (2, 4), (4, 3),
1529 | (3, 5)]
1530 | >>> pykov._remove_dead_branch(tr)
1531 | >>> tr
1532 | [(1, 2), (2, 3), (3, 1), (1, 2), (2, 3), (3, 2), (2, 2), (2, 4), (4, 3),
1533 | (3, 5), (5, 5)]
1534 | """
1535 | head_set = set()
1536 | tail_set = set()
1537 | for step in transitions_list:
1538 | head_set.add(step[1])
1539 | tail_set.add(step[0])
1540 | for head in head_set:
1541 | if head not in tail_set:
1542 | transitions_list.append((head, head))
1543 | return None
1544 |
1545 |
1546 | def _machineEpsilon(func=float):
1547 | """
1548 | should be the same result of: numpy.finfo(numpy.float).eps
1549 | """
1550 | machine_epsilon = func(1)
1551 | while func(1) + func(machine_epsilon) != func(1):
1552 | machine_epsilon_last = machine_epsilon
1553 | machine_epsilon = func(machine_epsilon) / func(2)
1554 | return machine_epsilon_last
1555 |
--------------------------------------------------------------------------------