Skip to content

Commit 0d41bf6

Browse files
authored
Merge pull request #95 from ENCCS/update-optimization
Update optimization episode
2 parents 7d239c7 + 2ac3d80 commit 0d41bf6

12 files changed

+614
-51
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
/venv*
44
.jupyter_cache
55
jupyter_execute
6+
__pycache__
67

78
# pixi environments
89
.pixi
910
*.egg-info
11+
_ipython-input*-profile

Makefile

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,12 @@ help:
2222
# Live reload site documents for local development
2323
livehtml:
2424
sphinx-autobuild "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
25+
26+
INTERSPHINX_TARGETS := \
27+
intersphinx-python \
28+
intersphinx-numpy \
29+
intersphinx-ipython
30+
31+
.PHONY: $(INTERSPHINX_TARGETS)
32+
$(INTERSPHINX_TARGETS): intersphinx-%:
33+
cd content && python3 ls_intersphinx_targets.py $(subst intersphinx-,,$@) | less

content/conf.py

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
# remove once sphinx_rtd_theme updated for contrast and accessibility:
3838
"sphinx_rtd_theme_ext_color_contrast",
3939
"sphinx.ext.todo",
40+
"IPython.sphinxext.ipython_console_highlighting",
4041
]
4142

4243
# Settings for myst_nb:
@@ -101,16 +102,31 @@
101102
# :py:mod:`multiprocessing` to link straight to the Python docs of that module.
102103
# List all available references:
103104
# python -msphinx.ext.intersphinx https://docs.python.org/3/objects.inv
104-
# extensions.append('sphinx.ext.intersphinx')
105-
# intersphinx_mapping = {
106-
# #'python': ('https://docs.python.org/3', None),
105+
extensions.append('sphinx.ext.intersphinx')
106+
intersphinx_mapping = {
107+
'python': ('https://docs.python.org/3', None),
107108
# #'sphinx': ('https://www.sphinx-doc.org/', None),
108-
# #'numpy': ('https://numpy.org/doc/stable/', None),
109+
'numpy': ('https://numpy.org/doc/stable/', None),
109110
# #'scipy': ('https://docs.scipy.org/doc/scipy/reference/', None),
110111
# #'pandas': ('https://pandas.pydata.org/docs/', None),
111112
# #'matplotlib': ('https://matplotlib.org/', None),
112113
# 'seaborn': ('https://seaborn.pydata.org/', None),
113-
# }
114+
'ipython': ('https://ipython.readthedocs.io/en/stable/', None),
115+
}
116+
117+
# sphinx-hoverxref
118+
extensions.append("hoverxref.extension")
119+
hoverxref_auto_ref = True
120+
hoverxref_domains = ["py"]
121+
hoverxref_role_types = {
122+
'hoverxref': 'modal',
123+
'ref': 'modal', # for hoverxref_auto_ref config
124+
'func': 'modal',
125+
'meth': 'modal',
126+
'mod': 'tooltip', # for Python Sphinx Domain
127+
'class': 'tooltip', # for Python Sphinx Domain
128+
}
129+
114130

115131
# add few new directives
116132
from sphinx_lesson.directives import _BaseCRDirective

content/example/scalene_web.png

173 KB
Loading

content/example/walk.py

Lines changed: 48 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,56 @@
1+
"""A 1-D random walk.
2+
3+
See also:
4+
- https://lectures.scientific-python.org/intro/numpy/auto_examples/plot_randomwalk.html
5+
6+
"""
17
import numpy as np
28

9+
310
def step():
411
import random
5-
return 1. if random.random() > .5 else -1.
12+
return 1.0 if random.random() > 0.5 else -1.0
13+
14+
15+
def walk(n: int, dx: float = 1.0):
16+
"""The for-loop version.
17+
18+
Parameters
19+
----------
20+
n: int
21+
Number of time steps
22+
23+
dx: float
24+
Step size. Default step size is unity.
25+
26+
"""
27+
xs = np.zeros(n)
628

7-
def walk(n):
8-
x = np.zeros(n)
9-
dx = 1. / n
1029
for i in range(n - 1):
11-
x_new = x[i] + dx * step()
12-
if x_new > 5e-3:
13-
x[i + 1] = 0.
14-
else:
15-
x[i + 1] = x_new
16-
return x
30+
x_new = xs[i] + dx * step()
31+
xs[i + 1] = x_new
32+
33+
return xs
34+
35+
36+
def walk_vec(n: int, dx: float = 1.0):
37+
"""The vectorized version of :func:`walk` using numpy functions."""
38+
import random
39+
steps = np.array(random.sample([1, -1], k=n, counts=[10 * n, 10 * n]))
40+
41+
# steps = np.random.choice([1, -1], size=n)
42+
43+
dx_steps = dx * steps
44+
45+
# set initial condition to zero
46+
dx_steps[0] = 0
47+
# use cumulative sum to replicate time evolution of position x
48+
xs = np.cumsum(dx_steps)
49+
50+
return xs
51+
1752

1853
if __name__ == "__main__":
19-
n = 100000
20-
x = walk(n)
54+
n = 1_000_000
55+
_ = walk(n)
56+
_ = walk_vec(n)

content/example/walk_ensemble_plot.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import numpy as np
2+
import matplotlib.pyplot as plt
3+
# See walk.py for the implementation
4+
import walk
5+
6+
7+
n_stories = 1000
8+
t_max = 200
9+
positions = np.empty((n_stories, t_max))
10+
11+
for i_story in range(n_stories):
12+
positions[i_story, :] = walk.walk(t_max, 1)
13+
14+
# Determine the time evolution of the root-mean-square distance.
15+
sq_distance = positions**2
16+
# Root mean square distance
17+
rms_distance = np.sqrt(np.mean(sq_distance, axis=0))
18+
19+
t = np.arange(t_max)
20+
21+
fig, ax = plt.subplots()
22+
ax.plot(t, rms_distance, "g", label="ensemble RMS distance")
23+
ax.plot(t, np.sqrt(t), "k--", label=r"theoretical $\sqrt{\langle (\delta x)^2 \rangle}$")
24+
ax.set(xlabel="time", ylabel="x")
25+
ax.legend()
26+
27+
plt.tight_layout()
28+
plt.show()

content/index.rst

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ and distributed computing.
6868
pandas-extra
6969
GPU-computing
7070
parallel-computing_opt
71+
optimization_opt
7172

7273

7374
.. toctree::
@@ -136,11 +137,11 @@ Several examples and formulations are inspired by other open source educational
136137
- `Python for Data Analysis <https://github.com/wesm/pydata-book/>`__
137138
- `GTC2017-numba <https://github.com/ContinuumIO/gtc2017-numba/>`__
138139
- `IPython Cookbook <https://ipython-books.github.io/>`__
139-
- `Scipy Lecture Notes <https://scipy-lectures.org/>`__
140+
- `Scientific Python Lectures <https://lectures.scientific-python.org/>`__ (*previously known as, Scipy Lecture Notes*)
140141
- `Machine Learning and Data Science Notebooks <https://sebastianraschka.com/notebooks/ml-notebooks/>`__
141142
- `Elegant SciPy <https://github.com/elegant-scipy/notebooks/>`__
142-
- `A Comprehensive Guide to NumPy Data Types <https://axil.github.io/a-comprehensive-guide-to-numpy-data-types.html>`__
143-
143+
- `A Comprehensive Guide to NumPy Data Types <https://axil.github.io/a-comprehensive-guide-to-numpy-data-types.html/>`__
144+
- `Python performance workshop <https://enccs.github.io/python-perf/>`__
144145

145146
Instructional Material
146147
^^^^^^^^^^^^^^^^^^^^^^

content/ls_intersphinx_targets.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import sys
2+
from sphinx.ext.intersphinx import inspect_main
3+
4+
from conf import intersphinx_mapping
5+
6+
7+
library = sys.argv[1]
8+
url = intersphinx_mapping[library][0] + "/objects.inv"
9+
inspect_main([url])

0 commit comments

Comments
 (0)