Path: blob/master/book_format.py
686 views
# -*- coding: utf-8 -*-12"""Copyright 2015 Roger R Labbe Jr.345Code supporting the book67Kalman and Bayesian Filters in Python8https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python91011This is licensed under an MIT license. See the LICENSE.txt file12for more information.13"""1415from contextlib import contextmanager16from IPython.core.display import HTML17import json18import os.path19import sys20import warnings21from kf_book.book_plots import set_figsize, reset_figsize2223def test_installation():24try:25import filterpy26except:27print("Please install FilterPy from the command line by running the command\n\t$ pip install filterpy\n\nSee chapter 0 for instructions.")2829try:30import numpy31except:32print("Please install NumPy before continuing. See chapter 0 for instructions.")3334try:35import scipy36except:37print("Please install SciPy before continuing. See chapter 0 for instructions.")3839try:40import sympy41except:42print("Please install SymPy before continuing. See chapter 0 for instructions.")4344try:45import matplotlib46except:47print("Please install matplotlib before continuing. See chapter 0 for instructions.")4849from distutils.version import LooseVersion5051v = filterpy.__version__52min_version = "1.4.4"53if LooseVersion(v) < LooseVersion(min_version):54print("Minimum FilterPy version supported is {}. "55"Please install a more recent version.\n"56" ex: pip install filterpy --upgrade".format(57min_version))585960v = matplotlib.__version__61min_version = "3.0" # this is really old!!!62if LooseVersion(v) < LooseVersion(min_version):63print("Minimum Matplotlib version supported is {}. "64"Please install a more recent version.".format(min_version))6566# require Python 3.6+67import sys68v = sys.version_info69if v.major < 3 or (v.major == 3 and v.minor < 6):70print('You must use Python version 3.6 or later for the notebooks to work correctly')717273# need to add test for IPython. I think I want to be at 6, which also implies74# Python 3, matplotlib 2+, etc.7576# ensure that we have the correct packages loaded. This is77# called when this module is imported at the top of each book78# chapter so the reader can see that they need to update their environment.79test_installation()808182# now that we've tested the existence of all packages go ahead and import8384import matplotlib85import matplotlib.pylab as pylab86import matplotlib.pyplot as plt87import numpy as np888990try:91matplotlib.style.use('default')92except:93pass949596with warnings.catch_warnings():97warnings.simplefilter("ignore", matplotlib.MatplotlibDeprecationWarning)98pylab.rcParams['figure.max_open_warning'] = 5099100101@contextmanager102def numpy_precision(precision):103old = np.get_printoptions()['precision']104np.set_printoptions(precision=precision)105yield106np.set_printoptions(old)107108@contextmanager109def printoptions(*args, **kwargs):110original = np.get_printoptions()111np.set_printoptions(*args, **kwargs)112yield113np.set_printoptions(**original)114115def _decode_list(data):116rv = []117for item in data:118if isinstance(item, unicode):119item = item.encode('utf-8')120elif isinstance(item, list):121item = _decode_list(item)122elif isinstance(item, dict):123item = _decode_dict(item)124rv.append(item)125return rv126127def _decode_dict(data):128rv = {}129for key, value in data.iteritems():130if isinstance(key, unicode):131key = key.encode('utf-8')132if isinstance(value, unicode):133value = value.encode('utf-8')134elif isinstance(value, list):135value = _decode_list(value)136elif isinstance(value, dict):137value = _decode_dict(value)138rv[key] = value139return rv140141142def set_style():143version = [int(version_no) for version_no in matplotlib.__version__.split('.')]144145try:146if sys.version_info[0] >= 3:147style = json.load(open("./kf_book/538.json"))148else:149style = json.load(open(".//kf_book/538.json"), object_hook=_decode_dict)150151with warnings.catch_warnings():152warnings.simplefilter("ignore", matplotlib.MatplotlibDeprecationWarning)153plt.rcParams.update(style)154except:155pass156np.set_printoptions(suppress=True, precision=3,157threshold=10000., linewidth=70,158formatter={'float':lambda x:' {:.3}'.format(x)})159160# I don't know why I have to do this, but I have to call161# with suppress a second time or the notebook doesn't suppress162# exponents163np.set_printoptions(suppress=True)164reset_figsize()165166style = '''167<style>168.output_wrapper, .output {169height:auto !important;170max-height:100000px;171}172.output_scroll {173box-shadow:none !important;174webkit-box-shadow:none !important;175}176</style>177'''178jscript = '''179%%javascript180IPython.OutputArea.auto_scroll_threshold = 9999;181'''182return HTML(style)183184185