Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Project: topocm
Views: 385
1
import sys
2
import os
3
import re
4
import types
5
import warnings
6
7
import numpy as np
8
import matplotlib
9
import holoviews
10
from holoviews import Options, Store
11
from matplotlib import pyplot as plt
12
from IPython import display
13
from ipywidgets import interact
14
from IPython.display import display_html
15
import kwant
16
17
import pfaffian as pf
18
# A bunch of edx components to pass on, we never use them here
19
import edx_components
20
from edx_components import *
21
import functions
22
from functions import *
23
24
init_mooc_nb = ['np', 'matplotlib', 'kwant', 'holoviews', 'init_notebook',
25
'interact', 'display_html', 'plt', 'pf',
26
'SimpleNamespace', 'pprint_matrix', 'scientific_number',
27
'pretty_fmt_complex']
28
29
__all__ = init_mooc_nb + edx_components.__all__ + functions.__all__
30
31
class SimpleNamespace(types.SimpleNamespace):
32
def update(self, **kwargs):
33
self.__dict__.update(kwargs)
34
return self
35
36
# Adjust printing of matrices, and numpy printing of numbers.
37
def pprint_matrix(data, digits=3):
38
"""Print a numpy array as a latex matrix."""
39
header = (r"\begin{{pmatrix}}"
40
r"{d}\end{{pmatrix}}")
41
d = data.__str__()[1:-1]
42
d = d.replace(']', '')
43
d = d.replace('\n', r'\\')
44
d = re.sub(r' *\[ *', '', d)
45
d = re.sub(r' +', ' & ', d)
46
display.display_latex(display.Latex(header.format(d=d)))
47
48
49
def scientific_number(x):
50
if not x:
51
return '$0$'
52
pot = int(np.log(abs(x)) / np.log(10.0)) - 1
53
fac = x*10**(-pot)
54
return '$%1.1f \cdot 10^{%1.0f}$' % (fac, pot)
55
56
57
def pretty_fmt_complex(num, digits=2):
58
"""Return a human-readable string representation of a number."""
59
def strip_trailing(num_str):
60
return num_str.rstrip('0').rstrip('.')
61
62
if np.round(num, digits) == 0:
63
return '0'
64
65
if np.round(num.imag, digits) == 0:
66
return strip_trailing(str(round(num.real, digits)))
67
68
if np.round(num.real, digits) == 0:
69
return strip_trailing(str(round(num.imag, digits))) + 'i'
70
71
return (pretty_fmt_complex(num.real) + ('+' * (num.imag > 0)) +
72
pretty_fmt_complex(num.imag) + 'i')
73
74
75
nb_html_header = """
76
<script type=text/javascript>
77
/* Add a button for showing or hiding input */
78
on = "Show input";
79
off = "Hide input";
80
function onoff(){
81
currentvalue = document.getElementById('onoff').value;
82
if(currentvalue == off){
83
document.getElementById("onoff").value=on;
84
$('div.input').hide();
85
}else{
86
document.getElementById("onoff").value=off;
87
$('div.input').show();
88
}
89
}
90
91
/* Launch first notebook cell on start */
92
function launch_first_cell (evt) {
93
if (!launch_first_cell.executed
94
&& Jupyter.notebook.kernel
95
) {
96
Jupyter.notebook.get_cells()[0].execute();
97
launch_first_cell.executed = true;
98
}
99
}
100
101
$([Jupyter.events]).on('status_started.Kernel notebook_loaded.Notebook', launch_first_cell);
102
</script>
103
104
<p>Press this button to show/hide the code used in the notebook:
105
<input type="button" class="ui-button ui-widget ui-state-default \
106
ui-corner-all ui-button-text-only" value="Hide input" id="onoff" \
107
onclick="onoff();"></p>
108
"""
109
110
hide_outside_ipython = """<script type=text/javascript>
111
$(document).ready(function (){if(!("IPython" in window)){onoff();}})
112
</script>"""
113
114
115
def init_notebook(mpl=True):
116
# Enable inline plotting in the notebook
117
if mpl:
118
try:
119
get_ipython().enable_matplotlib(gui='inline')
120
except NameError:
121
pass
122
123
print('Populated the namespace with:\n' +
124
', '.join(init_mooc_nb) +
125
'\nfrom code/edx_components:\n' +
126
', '.join(edx_components.__all__) +
127
'\nfrom code/functions:\n' +
128
', '.join(functions.__all__))
129
130
holoviews.notebook_extension('matplotlib')
131
holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.usetex'] = True
132
133
latex_packs = [r'\usepackage{amsmath}',
134
r'\usepackage{amssymb}'
135
r'\usepackage{bm}']
136
137
holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.latex.preamble'] = latex_packs
138
139
# Set plot style.
140
options = Store.options(backend='matplotlib')
141
options.Contours = Options('style', linewidth=2, color='k')
142
options.Contours = Options('plot', aspect='square')
143
options.HLine = Options('style', linestyle='--', color='b', linewidth=2)
144
options.VLine = Options('style', linestyle='--', color='r', linewidth=2)
145
options.Image = Options('style', cmap='RdBu_r')
146
options.Image = Options('plot', title_format='{label}')
147
options.Path = Options('style', linewidth=1.2, color='k')
148
options.Path = Options('plot', aspect='square', title_format='{label}')
149
options.Curve = Options('style', linewidth=2, color='k')
150
options.Curve = Options('plot', aspect='square', title_format='{label}')
151
options.Overlay = Options('plot', show_legend=False, title_format='{label}')
152
options.Layout = Options('plot', title_format='{label}')
153
options.Surface = Options('style', cmap='RdBu_r', rstride=1, cstride=1, lw=0.2)
154
options.Surface = Options('plot', azimuth=20, elevation=8)
155
156
# Turn off a bogus holoviews warning.
157
# Temporary solution to ignore the warnings
158
warnings.filterwarnings('ignore', r'All-NaN (slice|axis) encountered')
159
160
module_dir = os.path.dirname(__file__)
161
matplotlib.rc_file(os.path.join(module_dir, "matplotlibrc"))
162
163
np.set_printoptions(precision=2, suppress=True,
164
formatter={'complexfloat': pretty_fmt_complex})
165
166
# In order to make the notebooks readable through nbviewer we want to hide
167
# the code by default. However the same code is executed by the students,
168
# and in that case we don't want to hide the code. So we check if the code
169
# is executed by one of the mooc developers. Here we do by simply checking
170
# for some files that belong to the internal mooc repository, but are not
171
# published. This is a temporary solution, and should be improved in the
172
# long run.
173
174
developer = os.path.exists(os.path.join(module_dir, os.path.pardir,
175
'scripts'))
176
177
display_html(display.HTML(nb_html_header +
178
(hide_outside_ipython if developer else '')))
179
180
# Patch a bug in holoviews
181
from patch_holoviews import patch_all
182
patch_all()
183
184