Skip to content

Update optimization episode #95

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jan 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
/venv*
.jupyter_cache
jupyter_execute
__pycache__

# pixi environments
.pixi
*.egg-info
_ipython-input*-profile
9 changes: 9 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,12 @@ help:
# Live reload site documents for local development
livehtml:
sphinx-autobuild "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

INTERSPHINX_TARGETS := \
intersphinx-python \
intersphinx-numpy \
intersphinx-ipython

.PHONY: $(INTERSPHINX_TARGETS)
$(INTERSPHINX_TARGETS): intersphinx-%:
cd content && python3 ls_intersphinx_targets.py $(subst intersphinx-,,$@) | less
26 changes: 21 additions & 5 deletions content/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
# remove once sphinx_rtd_theme updated for contrast and accessibility:
"sphinx_rtd_theme_ext_color_contrast",
"sphinx.ext.todo",
"IPython.sphinxext.ipython_console_highlighting",
]

# Settings for myst_nb:
Expand Down Expand Up @@ -101,16 +102,31 @@
# :py:mod:`multiprocessing` to link straight to the Python docs of that module.
# List all available references:
# python -msphinx.ext.intersphinx https://docs.python.org/3/objects.inv
# extensions.append('sphinx.ext.intersphinx')
# intersphinx_mapping = {
# #'python': ('https://docs.python.org/3', None),
extensions.append('sphinx.ext.intersphinx')
intersphinx_mapping = {
'python': ('https://docs.python.org/3', None),
# #'sphinx': ('https://www.sphinx-doc.org/', None),
# #'numpy': ('https://numpy.org/doc/stable/', None),
'numpy': ('https://numpy.org/doc/stable/', None),
# #'scipy': ('https://docs.scipy.org/doc/scipy/reference/', None),
# #'pandas': ('https://pandas.pydata.org/docs/', None),
# #'matplotlib': ('https://matplotlib.org/', None),
# 'seaborn': ('https://seaborn.pydata.org/', None),
# }
'ipython': ('https://ipython.readthedocs.io/en/stable/', None),
}

# sphinx-hoverxref
extensions.append("hoverxref.extension")
hoverxref_auto_ref = True
hoverxref_domains = ["py"]
hoverxref_role_types = {
'hoverxref': 'modal',
'ref': 'modal', # for hoverxref_auto_ref config
'func': 'modal',
'meth': 'modal',
'mod': 'tooltip', # for Python Sphinx Domain
'class': 'tooltip', # for Python Sphinx Domain
}


# add few new directives
from sphinx_lesson.directives import _BaseCRDirective
Expand Down
Binary file added content/example/scalene_web.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
60 changes: 48 additions & 12 deletions content/example/walk.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,56 @@
"""A 1-D random walk.

See also:
- https://lectures.scientific-python.org/intro/numpy/auto_examples/plot_randomwalk.html

"""
import numpy as np


def step():
import random
return 1. if random.random() > .5 else -1.
return 1.0 if random.random() > 0.5 else -1.0


def walk(n: int, dx: float = 1.0):
"""The for-loop version.

Parameters
----------
n: int
Number of time steps

dx: float
Step size. Default step size is unity.

"""
xs = np.zeros(n)

def walk(n):
x = np.zeros(n)
dx = 1. / n
for i in range(n - 1):
x_new = x[i] + dx * step()
if x_new > 5e-3:
x[i + 1] = 0.
else:
x[i + 1] = x_new
return x
x_new = xs[i] + dx * step()
xs[i + 1] = x_new

return xs


def walk_vec(n: int, dx: float = 1.0):
"""The vectorized version of :func:`walk` using numpy functions."""
import random
steps = np.array(random.sample([1, -1], k=n, counts=[10 * n, 10 * n]))

# steps = np.random.choice([1, -1], size=n)

dx_steps = dx * steps

# set initial condition to zero
dx_steps[0] = 0
# use cumulative sum to replicate time evolution of position x
xs = np.cumsum(dx_steps)

return xs


if __name__ == "__main__":
n = 100000
x = walk(n)
n = 1_000_000
_ = walk(n)
_ = walk_vec(n)
28 changes: 28 additions & 0 deletions content/example/walk_ensemble_plot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import numpy as np
import matplotlib.pyplot as plt
# See walk.py for the implementation
import walk


n_stories = 1000
t_max = 200
positions = np.empty((n_stories, t_max))

for i_story in range(n_stories):
positions[i_story, :] = walk.walk(t_max, 1)

# Determine the time evolution of the root-mean-square distance.
sq_distance = positions**2
# Root mean square distance
rms_distance = np.sqrt(np.mean(sq_distance, axis=0))

t = np.arange(t_max)

fig, ax = plt.subplots()
ax.plot(t, rms_distance, "g", label="ensemble RMS distance")
ax.plot(t, np.sqrt(t), "k--", label=r"theoretical $\sqrt{\langle (\delta x)^2 \rangle}$")
ax.set(xlabel="time", ylabel="x")
ax.legend()

plt.tight_layout()
plt.show()
7 changes: 4 additions & 3 deletions content/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ and distributed computing.
pandas-extra
GPU-computing
parallel-computing_opt
optimization_opt


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

- `A Comprehensive Guide to NumPy Data Types <https://axil.github.io/a-comprehensive-guide-to-numpy-data-types.html/>`__
- `Python performance workshop <https://enccs.github.io/python-perf/>`__

Instructional Material
^^^^^^^^^^^^^^^^^^^^^^
Expand Down
9 changes: 9 additions & 0 deletions content/ls_intersphinx_targets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import sys
from sphinx.ext.intersphinx import inspect_main

from conf import intersphinx_mapping


library = sys.argv[1]
url = intersphinx_mapping[library][0] + "/objects.inv"
inspect_main([url])
Loading
Loading