Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
rlabbe
GitHub Repository: rlabbe/Kalman-and-Bayesian-Filters-in-Python
Path: blob/master/book_format.py
686 views
1
# -*- coding: utf-8 -*-
2
3
"""Copyright 2015 Roger R Labbe Jr.
4
5
6
Code supporting the book
7
8
Kalman and Bayesian Filters in Python
9
https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python
10
11
12
This is licensed under an MIT license. See the LICENSE.txt file
13
for more information.
14
"""
15
16
from contextlib import contextmanager
17
from IPython.core.display import HTML
18
import json
19
import os.path
20
import sys
21
import warnings
22
from kf_book.book_plots import set_figsize, reset_figsize
23
24
def test_installation():
25
try:
26
import filterpy
27
except:
28
print("Please install FilterPy from the command line by running the command\n\t$ pip install filterpy\n\nSee chapter 0 for instructions.")
29
30
try:
31
import numpy
32
except:
33
print("Please install NumPy before continuing. See chapter 0 for instructions.")
34
35
try:
36
import scipy
37
except:
38
print("Please install SciPy before continuing. See chapter 0 for instructions.")
39
40
try:
41
import sympy
42
except:
43
print("Please install SymPy before continuing. See chapter 0 for instructions.")
44
45
try:
46
import matplotlib
47
except:
48
print("Please install matplotlib before continuing. See chapter 0 for instructions.")
49
50
from distutils.version import LooseVersion
51
52
v = filterpy.__version__
53
min_version = "1.4.4"
54
if LooseVersion(v) < LooseVersion(min_version):
55
print("Minimum FilterPy version supported is {}. "
56
"Please install a more recent version.\n"
57
" ex: pip install filterpy --upgrade".format(
58
min_version))
59
60
61
v = matplotlib.__version__
62
min_version = "3.0" # this is really old!!!
63
if LooseVersion(v) < LooseVersion(min_version):
64
print("Minimum Matplotlib version supported is {}. "
65
"Please install a more recent version.".format(min_version))
66
67
# require Python 3.6+
68
import sys
69
v = sys.version_info
70
if v.major < 3 or (v.major == 3 and v.minor < 6):
71
print('You must use Python version 3.6 or later for the notebooks to work correctly')
72
73
74
# need to add test for IPython. I think I want to be at 6, which also implies
75
# Python 3, matplotlib 2+, etc.
76
77
# ensure that we have the correct packages loaded. This is
78
# called when this module is imported at the top of each book
79
# chapter so the reader can see that they need to update their environment.
80
test_installation()
81
82
83
# now that we've tested the existence of all packages go ahead and import
84
85
import matplotlib
86
import matplotlib.pylab as pylab
87
import matplotlib.pyplot as plt
88
import numpy as np
89
90
91
try:
92
matplotlib.style.use('default')
93
except:
94
pass
95
96
97
with warnings.catch_warnings():
98
warnings.simplefilter("ignore", matplotlib.MatplotlibDeprecationWarning)
99
pylab.rcParams['figure.max_open_warning'] = 50
100
101
102
@contextmanager
103
def numpy_precision(precision):
104
old = np.get_printoptions()['precision']
105
np.set_printoptions(precision=precision)
106
yield
107
np.set_printoptions(old)
108
109
@contextmanager
110
def printoptions(*args, **kwargs):
111
original = np.get_printoptions()
112
np.set_printoptions(*args, **kwargs)
113
yield
114
np.set_printoptions(**original)
115
116
def _decode_list(data):
117
rv = []
118
for item in data:
119
if isinstance(item, unicode):
120
item = item.encode('utf-8')
121
elif isinstance(item, list):
122
item = _decode_list(item)
123
elif isinstance(item, dict):
124
item = _decode_dict(item)
125
rv.append(item)
126
return rv
127
128
def _decode_dict(data):
129
rv = {}
130
for key, value in data.iteritems():
131
if isinstance(key, unicode):
132
key = key.encode('utf-8')
133
if isinstance(value, unicode):
134
value = value.encode('utf-8')
135
elif isinstance(value, list):
136
value = _decode_list(value)
137
elif isinstance(value, dict):
138
value = _decode_dict(value)
139
rv[key] = value
140
return rv
141
142
143
def set_style():
144
version = [int(version_no) for version_no in matplotlib.__version__.split('.')]
145
146
try:
147
if sys.version_info[0] >= 3:
148
style = json.load(open("./kf_book/538.json"))
149
else:
150
style = json.load(open(".//kf_book/538.json"), object_hook=_decode_dict)
151
152
with warnings.catch_warnings():
153
warnings.simplefilter("ignore", matplotlib.MatplotlibDeprecationWarning)
154
plt.rcParams.update(style)
155
except:
156
pass
157
np.set_printoptions(suppress=True, precision=3,
158
threshold=10000., linewidth=70,
159
formatter={'float':lambda x:' {:.3}'.format(x)})
160
161
# I don't know why I have to do this, but I have to call
162
# with suppress a second time or the notebook doesn't suppress
163
# exponents
164
np.set_printoptions(suppress=True)
165
reset_figsize()
166
167
style = '''
168
<style>
169
.output_wrapper, .output {
170
height:auto !important;
171
max-height:100000px;
172
}
173
.output_scroll {
174
box-shadow:none !important;
175
webkit-box-shadow:none !important;
176
}
177
</style>
178
'''
179
jscript = '''
180
%%javascript
181
IPython.OutputArea.auto_scroll_threshold = 9999;
182
'''
183
return HTML(style)
184
185