forked from rlabbe/Kalman-and-Bayesian-Filters-in-Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
book_format.py
153 lines (117 loc) · 4.36 KB
/
book_format.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# -*- coding: utf-8 -*-
"""Copyright 2015 Roger R Labbe Jr.
Code supporting the book
Kalman and Bayesian Filters in Python
https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python
This is licensed under an MIT license. See the LICENSE.txt file
for more information.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from contextlib import contextmanager
from distutils.version import LooseVersion
from IPython.core.display import HTML
import json
import matplotlib
import matplotlib.pylab as pylab
import matplotlib.pyplot as plt
import numpy as np
import os.path
import sys
import warnings
try:
import seaborn
except:
pass
# version 1.4.3 of matplotlib has a bug that makes
# it issue a spurious warning on every plot that
# clutters the notebook output
if matplotlib.__version__ == '1.4.3':
warnings.simplefilter(action="ignore", category=FutureWarning)
np.set_printoptions(precision=3)
def test_filterpy_version():
import filterpy
from distutils.version import LooseVersion
v = filterpy.__version__
min_version = "0.1.2"
if LooseVersion(v) < LooseVersion(min_version):
raise Exception("Minimum FilterPy version supported is {}.\n"
"Please install a more recent version.\n"
" ex: pip install filterpy --upgrade".format(
min_version))
# ensure that we have the correct filterpy loaded. This is
# called when this module is imported at the top of each book
# chapter so the reader can see that they need to update FilterPy.
test_filterpy_version()
pylab.rcParams['figure.max_open_warning'] = 50
def equal_axis():
pylab.rcParams['figure.figsize'] = 10,10
plt.axis('equal')
def reset_axis():
pylab.rcParams['figure.figsize'] = 9, 3
def set_figsize(x=9, y=4):
pylab.rcParams['figure.figsize'] = x, y
@contextmanager
def figsize(x=9, y=4):
"""Temporarily set the figure size using 'with figsize(a,b):'"""
size = pylab.rcParams['figure.figsize']
set_figsize(x, y)
yield
pylab.rcParams['figure.figsize'] = size
@contextmanager
def numpy_precision(precision):
old = np.get_printoptions()['precision']
np.set_printoptions(precision=precision)
yield
np.set_printoptions(old)
@contextmanager
def printoptions(*args, **kwargs):
original = np.get_printoptions()
np.set_printoptions(*args, **kwargs)
yield
np.set_printoptions(**original)
def _decode_list(data):
rv = []
for item in data:
if isinstance(item, unicode):
item = item.encode('utf-8')
elif isinstance(item, list):
item = _decode_list(item)
elif isinstance(item, dict):
item = _decode_dict(item)
rv.append(item)
return rv
def _decode_dict(data):
rv = {}
for key, value in data.iteritems():
if isinstance(key, unicode):
key = key.encode('utf-8')
if isinstance(value, unicode):
value = value.encode('utf-8')
elif isinstance(value, list):
value = _decode_list(value)
elif isinstance(value, dict):
value = _decode_dict(value)
rv[key] = value
return rv
def load_style(directory = '.', name='code/custom.css'):
if sys.version_info[0] >= 3:
style = json.load(open(os.path.join(directory, "code/538.json")))
else:
style = json.load(open(directory + "/code/538.json"), object_hook=_decode_dict)
# matplotlib has deprecated the use of axes.color_cycle as of version
try:
import seaborn
except:
version = [int(version_no) for version_no in matplotlib.__version__.split('.')]
if version[0] > 1 or (version[0] == 1 and version[1] >= 5):
style["axes.prop_cycle"] = "cycler('color', ['#6d904f','#013afe', '#202020','#fc4f30','#e5ae38','#A60628','#30a2da','#008080','#7A68A6','#CF4457','#188487','#E24A33'])"
style.pop("axes.color_cycle", None)
plt.rcParams.update(style)
set_figsize()
reset_axis ()
np.set_printoptions(suppress=True,precision=3, linewidth=70,
formatter={'float':lambda x:' {:.3}'.format(x)})
styles = open(os.path.join(directory, name), 'r').read()
set_figsize()
return HTML(styles)