diff --git a/.buildinfo b/.buildinfo new file mode 100644 index 000000000..076d9a08f --- /dev/null +++ b/.buildinfo @@ -0,0 +1,4 @@ +# Sphinx build info version 1 +# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. +config: 696e7c40fb06906a6976851a402773b9 +tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 000000000..e69de29bb diff --git a/AUTHORS.html b/AUTHORS.html new file mode 100644 index 000000000..18036ab50 --- /dev/null +++ b/AUTHORS.html @@ -0,0 +1,346 @@ + + + + + + + + 4.1.1. Authors — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

4.1.1. Authors

+
+

4.1.1.1. Editors

+
    +
  • Gaël Varoquaux

  • +
  • Emmanuelle Gouillart

  • +
  • Olav Vahtras

  • +
  • Pierre de Buyl

  • +
  • K. Jarrod Millman

  • +
  • Stéfan van der Walt

  • +
+
+
+

4.1.1.2. Chapter authors

+

Listed by alphabetical order.

+
    +
  • Christopher Burns

  • +
  • Adrian Chauve

  • +
  • Robert Cimrman

  • +
  • Christophe Combelles

  • +
  • André Espaze

  • +
  • Emmanuelle Gouillart

  • +
  • Mike Müller

  • +
  • Fabian Pedregosa

  • +
  • Didrik Pinte

  • +
  • Nicolas Rougier

  • +
  • Gaël Varoquaux

  • +
  • Pauli Virtanen

  • +
  • Zbigniew Jędrzejewski-Szmek

  • +
  • Valentin Haenel (editor from 2011 to 2015)

  • +
+
+
+

4.1.1.3. Additional Contributions

+

Listed by alphabetical order

+
    +
  • Osayd Abdu

  • +
  • arunpersaud

  • +
  • Ross Barnowski

  • +
  • Sebastian Berg

  • +
  • Lilian Besson

  • +
  • Matthieu Boileau

  • +
  • Joris Van den Bossche

  • +
  • Michael Boyle

  • +
  • Matthew Brett

  • +
  • BSGalvan

  • +
  • Lars Buitinck

  • +
  • Pierre de Buyl

  • +
  • Ozan Çağlayan

  • +
  • Lawrence Chan

  • +
  • Adrien Chauve

  • +
  • Robert Cimrman

  • +
  • Christophe Combelles

  • +
  • David Cournapeau

  • +
  • Dave

  • +
  • dogacan dugmeci

  • +
  • Török Edwin

  • +
  • egens

  • +
  • Andre Espaze

  • +
  • André Espaze

  • +
  • Loïc Estève

  • +
  • Corey Farwell

  • +
  • Tim Gates

  • +
  • Stuart Geiger

  • +
  • Olivier Georg

  • +
  • Daniel Gerigk

  • +
  • Robert Gieseke

  • +
  • Philip Gillißen

  • +
  • Ralf Gommers

  • +
  • Emmanuelle Gouillart

  • +
  • Julia Gustavsen

  • +
  • Omar Gutiérrez

  • +
  • Matt Haberland

  • +
  • Valentin Haenel

  • +
  • Pierre Haessig

  • +
  • Bruno Hanzen

  • +
  • Michael Hartmann

  • +
  • Jonathan Helmus

  • +
  • Andreas Hilboll

  • +
  • Himanshu

  • +
  • Julian Hofer

  • +
  • Tim Hoffmann

  • +
  • B. Hohl

  • +
  • Tarek Hoteit

  • +
  • Gert-Ludwig Ingold

  • +
  • Zbigniew Jędrzejewski-Szmek

  • +
  • Thouis (Ray) Jones

  • +
  • jorgeprietoarranz

  • +
  • josephsalmon

  • +
  • Greg Kiar

  • +
  • kikocorreoso

  • +
  • Vince Knight

  • +
  • LFP6

  • +
  • Manuel López-Ibáñez

  • +
  • Marco Mangan

  • +
  • Nicola Masarone

  • +
  • John McLaughlin

  • +
  • mhemantha

  • +
  • michelemaroni89

  • +
  • K. Jarrod Millman

  • +
  • Mohammad

  • +
  • Zachary Moon

  • +
  • Mike Mueller

  • +
  • negm

  • +
  • John B Nelson

  • +
  • nicoguaro

  • +
  • Sergio Oller

  • +
  • Theofilos Papapanagiotou

  • +
  • patniharshit

  • +
  • Fabian Pedregosa

  • +
  • Philippe Pepiot

  • +
  • Tiago M. D. Pereira

  • +
  • Nicolas Pettiaux

  • +
  • Didrik Pinte

  • +
  • Evgeny Pogrebnyak

  • +
  • reverland

  • +
  • Maximilien Riehl

  • +
  • Kristian Rother

  • +
  • Nicolas P. Rougier

  • +
  • Pamphile Roy

  • +
  • Rutzmoser

  • +
  • Sander

  • +
  • João Felipe Santos

  • +
  • Mark Setchell

  • +
  • Helen Sherwood-Taylor

  • +
  • Shoeboxam

  • +
  • Simon

  • +
  • solarjoe

  • +
  • ssmiller

  • +
  • Scott Staniewicz

  • +
  • strpeter

  • +
  • surfer190

  • +
  • Bartosz Telenczuk

  • +
  • tommyod

  • +
  • Wes Turner

  • +
  • Akihiro Uchida

  • +
  • Utkarsh Upadhyay

  • +
  • Olav Vahtras

  • +
  • Stéfan van der Walt

  • +
  • Gaël Varoquaux

  • +
  • Nelle Varoquaux

  • +
  • Olivier Verdier

  • +
  • VirgileFritsch

  • +
  • Pauli Virtanen

  • +
  • Yosh Wakeham

  • +
  • yasutomo57jp

  • +
+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/CHANGES.html b/CHANGES.html new file mode 100644 index 000000000..bfa6010c3 --- /dev/null +++ b/CHANGES.html @@ -0,0 +1,398 @@ + + + + + + + + What’s new — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

What’s new

+
+

Release 2024.1 (April 2024)

+
    +
  • Python 3.10, 3.11, 3.12

  • +
  • Renamed Scientific Python Lectures

  • +
  • Removed old content

  • +
  • Major updates to support recent packages

  • +
  • Updates to the SciPy and scikit-image chapters

  • +
+
+
+

Release 2022.1 (August 2022)

+
    +
  • Replace scikit-learn housing example with California data (Marco Mangan)

  • +
  • Fix links and typos (Zachary Moon, Tim Gates, Marco Mangan, Gert-Ludwig Ingold)

  • +
  • Fix fftpack figure (Osayd Abdu)

  • +
  • Update software version (Pierre de Buyl)

  • +
+
+
+

Release 2020.2 (September 2020)

+
    +
  • Replace image i/o from scipy.misc by imageio (Pierre de Buyl)

  • +
  • Update information on dict ordering (Bharath Saiguhan)

  • +
  • Suppress warnings for mandelbrot example (Pierre de Buyl)

  • +
  • Update NumPy introduction and advanced usage for changes to NumPy: wording, bytes +representation, floating point argument to np.zeros (Ross Barnowski)

  • +
  • Fix links to NumPy documentation to use numpy.org (Ross Barnowski)

  • +
  • Update note on transposed arrays (Ross Barnowski with Eric Wieser)

  • +
  • Use generated figure file for lidar data processing (Lawrence Chan)

  • +
  • Update link from PyMC2 to PyMC3 (B. Hohl)

  • +
  • Fix transparent popup menu to have a background (Pierre de Buyl)

  • +
+
+
+

Release 2020.1 (March 2020)

+
    +
  • Fix outdated URLs (Gert-Ludwig Ingold)

  • +
  • Update packages (Pierre de Buyl)

  • +
  • Remove Python 2 continuous integration (Olav Vahtras - EuroSciPy 2019 sprint)

  • +
  • Fix chessboard size (Mark Setchell)

  • +
  • Add objectives and design choices (Gert-Ludwig Ingold and Pierre de Buyl)

  • +
  • Make the numpy advanced iterator example more elaborate (Sebastian Berg)

  • +
  • Use empty list instead of empty tuple to deactivate ticks (Tim Hoffmann)

  • +
  • Fix typos (Sander van Rijn, cydave, Michel Corne) and off by 2 errors +(Andreas Hilboll)

  • +
  • Improve readability of Polynomials example code (Michel Corne)

  • +
  • Replace suggestions for debugging environments (Gert-Ludwig Ingold)

  • +
  • Add section on Python 2 vs Python 3 (Pierre de Buyl)

  • +
+
+
+

Release 2019.1 (May 2019)

+
    +
  • Update matplotlib compatibility to version 2.2 (Mike Mueller, Joris Van den +Bossche, Pierre de Buyl)

  • +
  • Make C-API example cos_module_np Python 2/3 compatible (Michael Boyle)

  • +
  • Fix typos and outdated URLs (Dogacan Dugmeci, Matthieu Boileau, Stuart Geiger, Omar +Gutiérrez, Himanshu, Julian Hofer, Joseph Salmon, Manuel López-Ibáñez, +Nicola Masarone, michelemaroni89, Evgeny Pogrebnyak, tommyod)

  • +
+
+
+

Release 2018.1 (September 2018)

+
    +
  • Fix wordings, typos, colours (Pierre de Buyl, Greg Kiar, Olav Vahtras +Kristian Rother)

  • +
  • Fix interpolation example code (Scott Staniewicz)

  • +
  • Fix CSS for high density displays (Gaël Varoquaux)

  • +
  • Generate indexing figures with PyX (Gert Ingold)

  • +
  • Warn clearly against the use of Python 2 (Bruno Hanzen)

  • +
  • Update external links (Bruno Hanzen)

  • +
  • Update versions of dependencies: sphinx-gallery, pandas, statsmodels +(Gaël Varoquaux)

  • +
+
+
+

Release 2017.1 (October 2017)

+
    +
  • Update optimization chapter (Michael Hartmann, Gaël Varoquaux)

  • +
  • Update SymPy chapter (Vince Knight)

  • +
  • Update advanced NumPy (Bartosz Teleńczuk)

  • +
  • Update scikit-learn chapter (Gaël Varoquaux)

  • +
  • Update SciPy chapter (Gaël Varoquaux)

  • +
  • Make ‘>>>’ in the prompts unselectable (Pierre de Buyl)

  • +
  • Use common package requirements for pip and conda and improve the build +instructions (Gert-Ludwig Ingold, Vince Knight, Pierre de Buyl)

  • +
  • Set up Circle CI (Loïc Estève)

  • +
  • Improved support for Python 3 integer divisions and calls to print (Loïc +Estève, Gert-Ludwig Ingold, Pierre de Buyl, Gaël Varoquaux)

  • +
  • Change test runner to pytest (Pierre de Buyl)

  • +
  • Replace the plot directive by sphinx-gallery (Gert-Ludwig Ingold)

  • +
+
+
+

Release 2016.1 (September 2016)

+
    +
  • Rework of intro chapter (Gaël Varoquaux)

  • +
  • Integrate sphinx-gallery: examples are now Jupyter notebooks (Gaël +Varoquaux, Gert-Ludwig Ingold, Óscar Nájera)

  • +
  • Better Python 3 tests and support (Gert-Ludwig Ingold)

  • +
  • Adapt examples to Matplotlib 1.5 (Gaël Varoquaux)

  • +
  • Modernize numpy chapter (Bartosz Telenczuk)

  • +
+
+
+

Release 2015.3 (November 2015)

+
    +
  • Collapsed sidebar can now pop up for mid-sized display (Gaël Varoquaux)

  • +
  • Replaced pictures of Lena by raccoon face (Thouis Jones)

  • +
+
+
+

Release 2015.2 (October 2015)

+
    +
  • Authors on cover ordered as in bibtex entry (Nicolas Rougier)

  • +
  • Better rendering on mobile (Gaël Varoquaux)

  • +
  • Fix restructured text markup errors (Olav Vahtras)

  • +
+
+
+

Release 2015.1 (September 2015)

+
    +
  • New chapter on statistics with Python (Gaël Varoquaux)

  • +
  • Better layout in PDF (Gaël Varoquaux)

  • +
  • New HTML layout, simplified formatting, mobile-friendly and sidebar +(Gaël Varoquaux, Nelle Varoquaux)

  • +
  • Logos on the HTML front page and on the PDF cover (Nicolas Rougier)

  • +
  • Python 3 compatible code (Gaël Varoquaux, Olav Vahtras)

  • +
  • Code put up to date for more recent versions of project (Pierre de +Buyl, Emmanuelle Gouillart, Gert-Ludwig Ingold, Nicolas Pettiaux, Olav +Vahtras, Gaël Varoquaux, Nelle Varoquaux)

  • +
  • Matplotlib updated with removal of deprecated pylab interface (Nicolas +Rougier)

  • +
+
+
+

Release 2013.2 (21 August 2013)

+
    +
  • NumPy chapter simplified (Valentin Haenel)

  • +
  • New layout for the HTML rendering (Gaël Varoquaux)

  • +
+
+
+

Release 2013.1 (10 Feb 2013)

+
    +
  • Improvements to the advanced image manipulation chapter (Emmanuelle Gouillart)

  • +
  • Upgrade of the introductory language chapter (Valentin Haenel)

  • +
  • Upgrade of the introductory numpy chapter (Valentin Haenel)

  • +
  • New advanced chapter on interfacing with C (Valentin Haenel)

  • +
  • Minor fixes and improvements in various places (Robert Gieseke, Ozan Çağlayan, +Sergio Oller, kikocorreo, Valentin Haenel)

  • +
+
+
+

Release 2012.3 (26 Nov 2012)

+

This release integrates the changes written for the Euroscipy conference:

+
    +
  • Matplotlib chapter completely redone (Nicolas Rougier, Gaël Varoquaux)

  • +
  • New advanced chapter on mathematical optimization (Gaël Varoquaux)

  • +
  • Mayavi chapter redone (Gaël Varoquaux)

  • +
  • Front page layout slightly improved: folding TOC (Gaël Varoquaux)

  • +
+
+
+

Release 2012.2 (22 Jun 2012)

+

Minor release with a few clean ups (Gael Varoquaux).

+
+
+

Release 2012.1 (20 Jun 2012)

+

This is a minor release with many clean ups. In particular, clean up of +the layout (Gael Varoquaux), shortening of the numpy chapters and +deduplications across the intro and advanced chapters (Gael Varoquaux) +and doctesting of all the code (Gael Varoquaux).

+
+
+

Release 2012.0 (22 Apr 2012)

+

This is a minor release with a few clean ups. In particular, clean up the +scikit-learn chapter (Lars Buitinck), more informative section titles +(Gael Varoquaux), and misc fixes (Valentin Haenel, Virgile Fritsch).

+
+
+

Release 2011.1 (16 Oct 2011)

+

This release is a reworked version of the Euroscipy 2011 tutorial. Layout +has been cleaned and optimized (Valentin Haenel and many others), the Traits +chapter has been merged in (Didrik Pinte)

+
+
+

Release 2011 (1 Sept 2011)

+

This release is used for the Euroscipy 2011 tutorial. The numpy +introductory chapter has been rewamped (Pauli Virtanen). The outline of +the introductory chapters has been simplified (Gaël Varoquaux). Advanced +chapters have been added: advanced Python constructs (Zbigniew +Jędrzejewski-Szmek), debugging code (Gaël Varoquaux), optimizing code +(Gaël Varoquaux), image processing (Emmanuelle Gouillart), scikit-learn +(Fabian Pedregosa).

+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/CNAME b/CNAME new file mode 100644 index 000000000..cde4c3c04 --- /dev/null +++ b/CNAME @@ -0,0 +1 @@ +lectures.scientific-python.org \ No newline at end of file diff --git a/CONTRIBUTING.html b/CONTRIBUTING.html new file mode 100644 index 000000000..969424dc0 --- /dev/null +++ b/CONTRIBUTING.html @@ -0,0 +1,318 @@ + + + + + + + + Contributing — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Contributing

+

The Scientific Python Lectures are a community-based effort and require +constant maintenance and improvements. New contributions such as wording +improvements or inclusion of new topics are welcome.

+

To propose bugfixes or straightforward improvements to the lectures, see the +contribution guide below.

+

For new topics, read the objectives first and open an issue on the GitHub +project to +discuss it with the editors.

+
+

Objectives and design choices for the lectures

+

Contributors should keep the following objectives and design choices of +the Scientific Python Lectures in mind.

+

Objectives:

+
    +
  • Provide a self-contained introduction to Python and its primary computational +packages, the ”Scientific Python stack“.

  • +
  • Provide tutorials for a selection of widely-used and stable computational +libraries. +Currently, we cover pandas, statmodels, seaborn, scikit-image, +scikit-learn, and sympy.

  • +
  • Automated testing is applied to the code examples as much as possible.

  • +
+

Design choices:

+
    +
  • Each chapter should provide a useful basis for a 1‒2 h tutorial.

  • +
  • The code should be readable.

  • +
  • An idomatic style should be followed, e.g. import numpy as np, +preference for array operations, PEP8 coding conventions.

  • +
+
+
+

Contributing guide

+

The directory guide contains instructions on how to contribute:

+ +
+
+

Building instructions

+

To generate the html output for on-screen display, Type:

+
make html
+
+
+

the generated html files can be found in build/html

+

The first build takes a long time, but information is cached and +subsequent builds will be faster.

+

To generate the pdf file for printing:

+
make pdf
+
+
+

The pdf builder is a bit difficult and you might have some TeX errors. +Tweaking the layout in the *.rst files is usually enough to work +around these problems.

+
+

Requirements

+

Build requirements are listed in the +requirements file:

+
numpy==2.1.1
+
scipy==1.14.1 +
matplotlib==3.9.2 +
pandas==2.2.3 +
patsy==0.5.6 +
pyarrow==17.0.0 +
scikit-learn==1.5.2 +
scikit-image==0.24.0 +
sympy==1.13.3 +
statsmodels==0.14.3 +
seaborn==0.13.2 +
pytest>=8.2 +
sphinx>=8.0 +
sphinx-gallery>=0.17 +
sphinx-copybutton +
coverage>=7.5 +
Pillow +
pooch +
ipython +
pickleshare +
pre-commit==4.0 +
requests +
sphinxcontrib-jquery +
+
+

Ensure that you have a virtual environment or conda environment +set up, then install requirements with:

+
pip install -r requirements.txt
+
+
+

Note that you will also need the following system packages:

+
+
    +
  • Python C development headers (the python3-dev package on Debian, e.g.),

  • +
  • a C compiler like gcc,

  • +
  • GNU Make,

  • +
  • a full LaTeX distribution such as TeX Live (texlive-latex-base, +texlive-latex-extra, texlive-fonts-extra, and latexmk +on Debian/Ubuntu),

  • +
  • dvipng,

  • +
  • latexmk,

  • +
  • git.

  • +
+
+
+
+

Updating the cover

+

Use inkscape to modify the cover in images/, then export to PDF:

+
inkscape --export-filename=cover-2024.pdf cover-2024.svg
+
+
+

Ensure that the images/cover.pdf symlink points to the correct +file.

+

+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/LICENSE.html b/LICENSE.html new file mode 100644 index 000000000..eba8d138f --- /dev/null +++ b/LICENSE.html @@ -0,0 +1,177 @@ + + + + + + + + License — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

License

+

All code and material is licensed under a

+

Creative Commons Attribution 4.0 International License (CC-by)

+

https://creativecommons.org/licenses/by/4.0/

+

See the AUTHORS.rst file for a list of contributors.

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/_downloads/004fb5d0b74bb27a4a6578f9ac85a724/plot_mec.ipynb b/_downloads/004fb5d0b74bb27a4a6578f9ac85a724/plot_mec.ipynb new file mode 100644 index 000000000..56111572a --- /dev/null +++ b/_downloads/004fb5d0b74bb27a4a6578f9ac85a724/plot_mec.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Marker edge color\n\nDemo the marker edge color of matplotlib's markers.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nsize = 256, 16\ndpi = 72.0\nfigsize = size[0] / float(dpi), size[1] / float(dpi)\nfig = plt.figure(figsize=figsize, dpi=dpi)\nfig.patch.set_alpha(0)\nplt.axes((0, 0, 1, 1), frameon=False)\n\nrng = np.random.default_rng()\n\nfor i in range(1, 11):\n r, g, b = np.random.uniform(0, 1, 3)\n plt.plot(\n [\n i,\n ],\n [\n 1,\n ],\n \"s\",\n markersize=5,\n markerfacecolor=\"w\",\n markeredgewidth=1.5,\n markeredgecolor=(r, g, b, 1),\n )\n\nplt.xlim(0, 11)\nplt.xticks([])\nplt.yticks([])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/0082b8d8c0ae74f6d7d129dae225bcf5/plot_exercise_10.py b/_downloads/0082b8d8c0ae74f6d7d129dae225bcf5/plot_exercise_10.py new file mode 100644 index 000000000..94aa03cec --- /dev/null +++ b/_downloads/0082b8d8c0ae74f6d7d129dae225bcf5/plot_exercise_10.py @@ -0,0 +1,86 @@ +""" +Exercise +========= + +Exercises with matplotlib. +""" + +import numpy as np +import matplotlib.pyplot as plt + +plt.figure(figsize=(8, 5), dpi=80) +plt.subplot(111) + +X = np.linspace(-np.pi, np.pi, 256) +C, S = np.cos(X), np.sin(X) + +plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine") +plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine") + +ax = plt.gca() +ax.spines["right"].set_color("none") +ax.spines["top"].set_color("none") +ax.xaxis.set_ticks_position("bottom") +ax.spines["bottom"].set_position(("data", 0)) +ax.yaxis.set_ticks_position("left") +ax.spines["left"].set_position(("data", 0)) + +plt.xlim(X.min() * 1.1, X.max() * 1.1) +plt.xticks( + [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], + [r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"], +) + +plt.ylim(C.min() * 1.1, C.max() * 1.1) +plt.yticks([-1, 1], [r"$-1$", r"$+1$"]) + +plt.legend(loc="upper left") + +t = 2 * np.pi / 3 +plt.plot([t, t], [0, np.cos(t)], color="blue", linewidth=1.5, linestyle="--") +plt.scatter( + [ + t, + ], + [ + np.cos(t), + ], + 50, + color="blue", +) +plt.annotate( + r"$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$", + xy=(t, np.sin(t)), + xycoords="data", + xytext=(10, 30), + textcoords="offset points", + fontsize=16, + arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=.2"}, +) + +plt.plot([t, t], [0, np.sin(t)], color="red", linewidth=1.5, linestyle="--") +plt.scatter( + [ + t, + ], + [ + np.sin(t), + ], + 50, + color="red", +) +plt.annotate( + r"$cos(\frac{2\pi}{3})=-\frac{1}{2}$", + xy=(t, np.cos(t)), + xycoords="data", + xytext=(-90, -50), + textcoords="offset points", + fontsize=16, + arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=.2"}, +) + +for label in ax.get_xticklabels() + ax.get_yticklabels(): + label.set_fontsize(16) + label.set_bbox({"facecolor": "white", "edgecolor": "None", "alpha": 0.65}) + +plt.show() diff --git a/_downloads/013d4351bc8285d6f79f280b60e7c4c2/plot_separator.zip b/_downloads/013d4351bc8285d6f79f280b60e7c4c2/plot_separator.zip new file mode 100644 index 000000000..99627261b Binary files /dev/null and b/_downloads/013d4351bc8285d6f79f280b60e7c4c2/plot_separator.zip differ diff --git a/_downloads/01448719cb14a60cb46177ae1696b443/plot_basic2dplot.py b/_downloads/01448719cb14a60cb46177ae1696b443/plot_basic2dplot.py new file mode 100644 index 000000000..1cb4465ab --- /dev/null +++ b/_downloads/01448719cb14a60cb46177ae1696b443/plot_basic2dplot.py @@ -0,0 +1,16 @@ +""" +2D plotting +=========== + +Plot a basic 2D figure + +""" + +import numpy as np +import matplotlib.pyplot as plt + +rng = np.random.default_rng() +image = rng.random((30, 30)) +plt.imshow(image, cmap="hot") +plt.colorbar() +plt.show() diff --git a/_downloads/01acaf28c89d2e60d9a9711f1451e9ab/plot_sharpen.zip b/_downloads/01acaf28c89d2e60d9a9711f1451e9ab/plot_sharpen.zip new file mode 100644 index 000000000..9439bc935 Binary files /dev/null and b/_downloads/01acaf28c89d2e60d9a9711f1451e9ab/plot_sharpen.zip differ diff --git a/_downloads/01bf943c07ee17c694927fc9306ea087/plot_solid_capstyle.py b/_downloads/01bf943c07ee17c694927fc9306ea087/plot_solid_capstyle.py new file mode 100644 index 000000000..4f17e0a12 --- /dev/null +++ b/_downloads/01bf943c07ee17c694927fc9306ea087/plot_solid_capstyle.py @@ -0,0 +1,36 @@ +""" +Solid cap style +================ + +An example demoing the solide cap style in matplotlib. +""" + +import numpy as np +import matplotlib.pyplot as plt + +size = 256, 16 +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = plt.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +plt.axes((0, 0, 1, 1), frameon=False) + +plt.plot(np.arange(4), np.ones(4), color="blue", linewidth=8, solid_capstyle="butt") + +plt.plot( + 5 + np.arange(4), np.ones(4), color="blue", linewidth=8, solid_capstyle="round" +) + +plt.plot( + 10 + np.arange(4), + np.ones(4), + color="blue", + linewidth=8, + solid_capstyle="projecting", +) + +plt.xlim(0, 14) +plt.xticks([]) +plt.yticks([]) + +plt.show() diff --git a/_downloads/03d88a15717fbf3ff09a3f2008d4a67e/plot_boxplot_ext.zip b/_downloads/03d88a15717fbf3ff09a3f2008d4a67e/plot_boxplot_ext.zip new file mode 100644 index 000000000..f194b6ebb Binary files /dev/null and b/_downloads/03d88a15717fbf3ff09a3f2008d4a67e/plot_boxplot_ext.zip differ diff --git a/_downloads/046697e9accd06867ffbb3c1b3cc6c89/plot_exercise_6.ipynb b/_downloads/046697e9accd06867ffbb3c1b3cc6c89/plot_exercise_6.ipynb new file mode 100644 index 000000000..30f52922e --- /dev/null +++ b/_downloads/046697e9accd06867ffbb3c1b3cc6c89/plot_exercise_6.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Exercise 6\n\nExercise 6 with matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(8, 5), dpi=80)\nplt.subplot(111)\n\nX = np.linspace(-np.pi, np.pi, 256)\nC = np.cos(X)\nS = np.sin(X)\n\nplt.plot(X, C, color=\"blue\", linewidth=2.5, linestyle=\"-\")\nplt.plot(X, S, color=\"red\", linewidth=2.5, linestyle=\"-\")\n\nplt.xlim(X.min() * 1.1, X.max() * 1.1)\nplt.xticks(\n [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],\n [r\"$-\\pi$\", r\"$-\\pi/2$\", r\"$0$\", r\"$+\\pi/2$\", r\"$+\\pi$\"],\n)\n\nplt.ylim(C.min() * 1.1, C.max() * 1.1)\nplt.yticks([-1, 0, +1], [r\"$-1$\", r\"$0$\", r\"$+1$\"])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/04753ea12423b96a96756c7b57848399/plot_subplot-horizontal.py b/_downloads/04753ea12423b96a96756c7b57848399/plot_subplot-horizontal.py new file mode 100644 index 000000000..2d731c1cb --- /dev/null +++ b/_downloads/04753ea12423b96a96756c7b57848399/plot_subplot-horizontal.py @@ -0,0 +1,22 @@ +""" +Horizontal arrangement of subplots +================================== + +An example showing horizontal arrangement of subplots with matplotlib. +""" + +import matplotlib.pyplot as plt + +plt.figure(figsize=(6, 4)) +plt.subplot(2, 1, 1) +plt.xticks([]) +plt.yticks([]) +plt.text(0.5, 0.5, "subplot(2,1,1)", ha="center", va="center", size=24, alpha=0.5) + +plt.subplot(2, 1, 2) +plt.xticks([]) +plt.yticks([]) +plt.text(0.5, 0.5, "subplot(2,1,2)", ha="center", va="center", size=24, alpha=0.5) + +plt.tight_layout() +plt.show() diff --git a/_downloads/04d4ef96ac4101131f3f44977213b40d/plot_find_object.zip b/_downloads/04d4ef96ac4101131f3f44977213b40d/plot_find_object.zip new file mode 100644 index 000000000..63d982451 Binary files /dev/null and b/_downloads/04d4ef96ac4101131f3f44977213b40d/plot_find_object.zip differ diff --git a/_downloads/05de9c57e7b2d82868ba98d8c8686b99/plot_mfc.zip b/_downloads/05de9c57e7b2d82868ba98d8c8686b99/plot_mfc.zip new file mode 100644 index 000000000..6b31c4514 Binary files /dev/null and b/_downloads/05de9c57e7b2d82868ba98d8c8686b99/plot_mfc.zip differ diff --git a/_downloads/064f8b8f7deca81f279ad560f5d14f99/plot_resample.ipynb b/_downloads/064f8b8f7deca81f279ad560f5d14f99/plot_resample.ipynb new file mode 100644 index 000000000..b091ac1db --- /dev/null +++ b/_downloads/064f8b8f7deca81f279ad560f5d14f99/plot_resample.ipynb @@ -0,0 +1,86 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Resample a signal with scipy.signal.resample\n\n:func:`scipy.signal.resample` uses FFT to resample a 1D signal.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Generate a signal with 100 data point\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n\nt = np.linspace(0, 5, 100)\nx = np.sin(t)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Downsample it by a factor of 4\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import scipy as sp\n\nx_resampled = sp.signal.resample(x, 25)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Plot\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nplt.figure(figsize=(5, 4))\nplt.plot(t, x, label=\"Original signal\")\nplt.plot(t[::4], x_resampled, \"ko\", label=\"Resampled signal\")\n\nplt.legend(loc=\"best\")\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/06b415bbf4601eeb631a56aade169599/plot_face.ipynb b/_downloads/06b415bbf4601eeb631a56aade169599/plot_face.ipynb new file mode 100644 index 000000000..d6c589ea1 --- /dev/null +++ b/_downloads/06b415bbf4601eeb631a56aade169599/plot_face.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Displaying a Raccoon Face\n\nSmall example to plot a raccoon face.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import scipy as sp\nimport imageio.v3 as iio\n\nf = sp.datasets.face()\niio.imwrite(\"face.png\", f) # uses the Image module (PIL)\n\nimport matplotlib.pyplot as plt\n\nplt.imshow(f)\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/071202cda0a7803d826bb94a712b9c0f/plot_face_denoise.ipynb b/_downloads/071202cda0a7803d826bb94a712b9c0f/plot_face_denoise.ipynb new file mode 100644 index 000000000..b6f99d9fa --- /dev/null +++ b/_downloads/071202cda0a7803d826bb94a712b9c0f/plot_face_denoise.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Image denoising\n\nThis example demoes image denoising on a Raccoon face.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nrng = np.random.default_rng(27446968)\n\nf = sp.datasets.face(gray=True)\nf = f[230:290, 220:320]\n\nnoisy = f + 0.4 * f.std() * rng.random(f.shape)\n\ngauss_denoised = sp.ndimage.gaussian_filter(noisy, 2)\nmed_denoised = sp.ndimage.median_filter(noisy, 3)\n\n\nplt.figure(figsize=(12, 2.8))\n\nplt.subplot(131)\nplt.imshow(noisy, cmap=\"gray\", vmin=40, vmax=220)\nplt.axis(\"off\")\nplt.title(\"noisy\", fontsize=20)\nplt.subplot(132)\nplt.imshow(gauss_denoised, cmap=\"gray\", vmin=40, vmax=220)\nplt.axis(\"off\")\nplt.title(\"Gaussian filter\", fontsize=20)\nplt.subplot(133)\nplt.imshow(med_denoised, cmap=\"gray\", vmin=40, vmax=220)\nplt.axis(\"off\")\nplt.title(\"Median filter\", fontsize=20)\n\nplt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1)\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/0753145f26223423b0e9b7306b06637a/plot_scatter_ext.ipynb b/_downloads/0753145f26223423b0e9b7306b06637a/plot_scatter_ext.ipynb new file mode 100644 index 000000000..605bd5ecb --- /dev/null +++ b/_downloads/0753145f26223423b0e9b7306b06637a/plot_scatter_ext.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot scatter decorated\n\nAn example showing the scatter function, with decorations.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nn = 1024\nrng = np.random.default_rng()\nX = rng.normal(0, 1, n)\nY = rng.normal(0, 1, n)\n\nT = np.arctan2(Y, X)\n\nplt.scatter(X, Y, s=75, c=T, alpha=0.5)\nplt.xlim(-1.5, 1.5)\nplt.xticks([])\nplt.ylim(-1.5, 1.5)\nplt.yticks([])\n\n\n# Add a title and a box around it\nfrom matplotlib.patches import FancyBboxPatch\n\nax = plt.gca()\nax.add_patch(\n FancyBboxPatch(\n (-0.05, 0.87),\n width=0.66,\n height=0.165,\n clip_on=False,\n boxstyle=\"square,pad=0\",\n zorder=3,\n facecolor=\"white\",\n alpha=1.0,\n transform=plt.gca().transAxes,\n )\n)\n\nplt.text(\n -0.05,\n 1.02,\n \" Scatter Plot: plt.scatter(...)\\n\",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"xx-large\",\n transform=plt.gca().transAxes,\n)\n\nplt.text(\n -0.05,\n 1.01,\n \"\\n\\n Make a scatter plot of x versus y \",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"large\",\n transform=plt.gca().transAxes,\n)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/07762975987fa440a90ac3f0b694e8dd/plot_exercise_8.ipynb b/_downloads/07762975987fa440a90ac3f0b694e8dd/plot_exercise_8.ipynb new file mode 100644 index 000000000..4a2166443 --- /dev/null +++ b/_downloads/07762975987fa440a90ac3f0b694e8dd/plot_exercise_8.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Exercise 8\n\nExercise 8 with matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(8, 5), dpi=80)\nplt.subplot(111)\n\nX = np.linspace(-np.pi, np.pi, 256, endpoint=True)\nC = np.cos(X)\nS = np.sin(X)\n\nplt.plot(X, C, color=\"blue\", linewidth=2.5, linestyle=\"-\", label=\"cosine\")\nplt.plot(X, S, color=\"red\", linewidth=2.5, linestyle=\"-\", label=\"sine\")\n\nax = plt.gca()\nax.spines[\"right\"].set_color(\"none\")\nax.spines[\"top\"].set_color(\"none\")\nax.xaxis.set_ticks_position(\"bottom\")\nax.spines[\"bottom\"].set_position((\"data\", 0))\nax.yaxis.set_ticks_position(\"left\")\nax.spines[\"left\"].set_position((\"data\", 0))\n\nplt.xlim(X.min() * 1.1, X.max() * 1.1)\nplt.xticks(\n [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],\n [r\"$-\\pi$\", r\"$-\\pi/2$\", r\"$0$\", r\"$+\\pi/2$\", r\"$+\\pi$\"],\n)\n\nplt.ylim(C.min() * 1.1, C.max() * 1.1)\nplt.yticks([-1, +1], [r\"$-1$\", r\"$+1$\"])\n\nplt.legend(loc=\"upper left\")\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/080b09bb20fcd2d6702a5125f01ded6d/plot_face.py b/_downloads/080b09bb20fcd2d6702a5125f01ded6d/plot_face.py new file mode 100644 index 000000000..560da8eeb --- /dev/null +++ b/_downloads/080b09bb20fcd2d6702a5125f01ded6d/plot_face.py @@ -0,0 +1,17 @@ +""" +Displaying a Raccoon Face +========================= + +Small example to plot a raccoon face. +""" + +import scipy as sp +import imageio.v3 as iio + +f = sp.datasets.face() +iio.imwrite("face.png", f) # uses the Image module (PIL) + +import matplotlib.pyplot as plt + +plt.imshow(f) +plt.show() diff --git a/_downloads/08765114470721dcb78446b2c03154e2/plot_axes.zip b/_downloads/08765114470721dcb78446b2c03154e2/plot_axes.zip new file mode 100644 index 000000000..c5c69cab7 Binary files /dev/null and b/_downloads/08765114470721dcb78446b2c03154e2/plot_axes.zip differ diff --git a/_downloads/087d8fe936fcb7a4762b9850b932cf9e/populations.txt b/_downloads/087d8fe936fcb7a4762b9850b932cf9e/populations.txt new file mode 100644 index 000000000..6de710c3b --- /dev/null +++ b/_downloads/087d8fe936fcb7a4762b9850b932cf9e/populations.txt @@ -0,0 +1,22 @@ +# year hare lynx carrot +1900 30e3 4e3 48300 +1901 47.2e3 6.1e3 48200 +1902 70.2e3 9.8e3 41500 +1903 77.4e3 35.2e3 38200 +1904 36.3e3 59.4e3 40600 +1905 20.6e3 41.7e3 39800 +1906 18.1e3 19e3 38600 +1907 21.4e3 13e3 42300 +1908 22e3 8.3e3 44500 +1909 25.4e3 9.1e3 42100 +1910 27.1e3 7.4e3 46000 +1911 40.3e3 8e3 46800 +1912 57e3 12.3e3 43800 +1913 76.6e3 19.5e3 40900 +1914 52.3e3 45.7e3 39400 +1915 19.5e3 51.1e3 39000 +1916 11.2e3 29.7e3 36700 +1917 7.6e3 15.8e3 41800 +1918 14.6e3 9.7e3 43300 +1919 16.2e3 10.1e3 41300 +1920 24.7e3 8.6e3 47300 diff --git a/_downloads/099178092be7b2bf2dc1326fe229d915/plot_face_tv_denoise.py b/_downloads/099178092be7b2bf2dc1326fe229d915/plot_face_tv_denoise.py new file mode 100644 index 000000000..e1522f00c --- /dev/null +++ b/_downloads/099178092be7b2bf2dc1326fe229d915/plot_face_tv_denoise.py @@ -0,0 +1,42 @@ +""" +Total Variation denoising +=========================== + +This example demoes Total-Variation (TV) denoising on a Raccoon face. +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +from skimage.restoration import denoise_tv_chambolle + +rng = np.random.default_rng(27446968) + +f = sp.datasets.face(gray=True) +f = f[230:290, 220:320] + +noisy = f + 0.4 * f.std() * rng.random(f.shape) + +tv_denoised = denoise_tv_chambolle(noisy, weight=10) + + +plt.figure(figsize=(12, 2.8)) + +plt.subplot(131) +plt.imshow(noisy, cmap="gray", vmin=40, vmax=220) +plt.axis("off") +plt.title("noisy", fontsize=20) +plt.subplot(132) +plt.imshow(tv_denoised, cmap="gray", vmin=40, vmax=220) +plt.axis("off") +plt.title("TV denoising", fontsize=20) + +tv_denoised = denoise_tv_chambolle(noisy, weight=50) +plt.subplot(133) +plt.imshow(tv_denoised, cmap="gray", vmin=40, vmax=220) +plt.axis("off") +plt.title("(more) TV denoising", fontsize=20) + +plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1) +plt.show() diff --git a/_downloads/0a188804c05ac07dc03e455dff045129/plot_ticks.ipynb b/_downloads/0a188804c05ac07dc03e455dff045129/plot_ticks.ipynb new file mode 100644 index 000000000..08ecb1c54 --- /dev/null +++ b/_downloads/0a188804c05ac07dc03e455dff045129/plot_ticks.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Locators for tick on axis\n\nAn example demoing different locators to position ticks on axis for\nmatplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n\nfrom matplotlib import ticker\nimport matplotlib.pyplot as plt\n\n\ndef tickline():\n plt.xlim(0, 10), plt.ylim(-1, 1), plt.yticks([])\n ax = plt.gca()\n ax.spines[\"right\"].set_color(\"none\")\n ax.spines[\"left\"].set_color(\"none\")\n ax.spines[\"top\"].set_color(\"none\")\n ax.xaxis.set_ticks_position(\"bottom\")\n ax.spines[\"bottom\"].set_position((\"data\", 0))\n ax.yaxis.set_ticks_position(\"none\")\n ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.1))\n ax.plot(np.arange(11), np.zeros(11))\n return ax\n\n\nlocators = [\n \"ticker.NullLocator()\",\n \"ticker.MultipleLocator(1.0)\",\n \"ticker.FixedLocator([0, 2, 8, 9, 10])\",\n \"ticker.IndexLocator(3, 1)\",\n \"ticker.LinearLocator(5)\",\n \"ticker.LogLocator(2, [1.0])\",\n \"ticker.AutoLocator()\",\n]\n\nn_locators = len(locators)\n\nsize = 512, 40 * n_locators\ndpi = 72.0\nfigsize = size[0] / float(dpi), size[1] / float(dpi)\nfig = plt.figure(figsize=figsize, dpi=dpi)\nfig.patch.set_alpha(0)\n\n\nfor i, locator in enumerate(locators):\n plt.subplot(n_locators, 1, i + 1)\n ax = tickline()\n ax.xaxis.set_major_locator(eval(locator))\n plt.text(5, 0.3, locator[7:], ha=\"center\")\n\nplt.subplots_adjust(bottom=0.01, top=0.99, left=0.01, right=0.99)\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/0a33ab444bb8375b1acee3709e57b9fe/auto_examples_python.zip b/_downloads/0a33ab444bb8375b1acee3709e57b9fe/auto_examples_python.zip new file mode 100644 index 000000000..76380c28c Binary files /dev/null and b/_downloads/0a33ab444bb8375b1acee3709e57b9fe/auto_examples_python.zip differ diff --git a/_downloads/0a6f0ef4dc153c657557cdbe476b3eb1/plot_constraints.zip b/_downloads/0a6f0ef4dc153c657557cdbe476b3eb1/plot_constraints.zip new file mode 100644 index 000000000..af236be82 Binary files /dev/null and b/_downloads/0a6f0ef4dc153c657557cdbe476b3eb1/plot_constraints.zip differ diff --git a/_downloads/0b1ff32a6c3cf0d70545941b71ce3f48/plot_optimize_lidar_complex_data_fit.ipynb b/_downloads/0b1ff32a6c3cf0d70545941b71ce3f48/plot_optimize_lidar_complex_data_fit.ipynb new file mode 100644 index 000000000..920dbcbdf --- /dev/null +++ b/_downloads/0b1ff32a6c3cf0d70545941b71ce3f48/plot_optimize_lidar_complex_data_fit.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# The lidar system, data and fit (2 of 2 datasets)\n\nGenerate a chart of the data fitted by Gaussian curve\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy as sp\n\n\ndef model(t, coeffs):\n return (\n coeffs[0]\n + coeffs[1] * np.exp(-(((t - coeffs[2]) / coeffs[3]) ** 2))\n + coeffs[4] * np.exp(-(((t - coeffs[5]) / coeffs[6]) ** 2))\n + coeffs[7] * np.exp(-(((t - coeffs[8]) / coeffs[9]) ** 2))\n )\n\n\ndef residuals(coeffs, y, t):\n return y - model(t, coeffs)\n\n\nwaveform_2 = np.load(\"waveform_2.npy\")\nt = np.arange(len(waveform_2))\n\nx0 = np.array([3, 30, 20, 1, 12, 25, 1, 8, 28, 1], dtype=float)\nx, flag = sp.optimize.leastsq(residuals, x0, args=(waveform_2, t))\n\nfig, ax = plt.subplots(figsize=(8, 6))\nplt.plot(t, waveform_2, t, model(t, x))\nplt.xlabel(\"Time [ns]\")\nplt.ylabel(\"Amplitude [bins]\")\nplt.legend([\"Waveform\", \"Model\"])\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/0b72bf1202f0083f93846408b28a8e97/auto_examples_python.zip b/_downloads/0b72bf1202f0083f93846408b28a8e97/auto_examples_python.zip new file mode 100644 index 000000000..f73ac25de Binary files /dev/null and b/_downloads/0b72bf1202f0083f93846408b28a8e97/auto_examples_python.zip differ diff --git a/_downloads/0b8b8c0523d2d07745b047e3760fd3b8/plot_contour.ipynb b/_downloads/0b8b8c0523d2d07745b047e3760fd3b8/plot_contour.ipynb new file mode 100644 index 000000000..53840f515 --- /dev/null +++ b/_downloads/0b8b8c0523d2d07745b047e3760fd3b8/plot_contour.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Displaying the contours of a function\n\nAn example showing how to display the contours of a function with\nmatplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef f(x, y):\n return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2)\n\n\nn = 256\nx = np.linspace(-3, 3, n)\ny = np.linspace(-3, 3, n)\nX, Y = np.meshgrid(x, y)\n\nplt.axes((0.025, 0.025, 0.95, 0.95))\n\nplt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=\"hot\")\nC = plt.contour(X, Y, f(X, Y), 8, colors=\"black\", linewidths=0.5)\nplt.clabel(C, inline=1, fontsize=10)\n\nplt.xticks([])\nplt.yticks([])\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/0bd386160632a3a64fc5d30e56c42819/plot_dash_joinstyle.zip b/_downloads/0bd386160632a3a64fc5d30e56c42819/plot_dash_joinstyle.zip new file mode 100644 index 000000000..0970b1fb4 Binary files /dev/null and b/_downloads/0bd386160632a3a64fc5d30e56c42819/plot_dash_joinstyle.zip differ diff --git a/_downloads/0be0ecd27821722da71c029c4a6b8afa/plot_watershed_segmentation.zip b/_downloads/0be0ecd27821722da71c029c4a6b8afa/plot_watershed_segmentation.zip new file mode 100644 index 000000000..d2ff316a3 Binary files /dev/null and b/_downloads/0be0ecd27821722da71c029c4a6b8afa/plot_watershed_segmentation.zip differ diff --git a/_downloads/0c83938933874ec7a449d472f7caac11/plot_detrend.ipynb b/_downloads/0c83938933874ec7a449d472f7caac11/plot_detrend.ipynb new file mode 100644 index 000000000..27d87260c --- /dev/null +++ b/_downloads/0c83938933874ec7a449d472f7caac11/plot_detrend.ipynb @@ -0,0 +1,86 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Detrending a signal\n\n:func:`scipy.signal.detrend` removes a linear trend.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Generate a random signal with a trend\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n\nt = np.linspace(0, 5, 100)\nrng = np.random.default_rng()\nx = t + rng.normal(size=100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Detrend\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import scipy as sp\n\nx_detrended = sp.signal.detrend(x)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Plot\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nplt.figure(figsize=(5, 4))\nplt.plot(t, x, label=\"x\")\nplt.plot(t, x_detrended, label=\"x_detrended\")\nplt.legend(loc=\"best\")\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/0cefadfd64638d2903c81ba417a275ca/plot_boundaries.zip b/_downloads/0cefadfd64638d2903c81ba417a275ca/plot_boundaries.zip new file mode 100644 index 000000000..ac5a3cf97 Binary files /dev/null and b/_downloads/0cefadfd64638d2903c81ba417a275ca/plot_boundaries.zip differ diff --git a/_downloads/0dca98e912a44b724a28d353be95c883/plot_distances.ipynb b/_downloads/0dca98e912a44b724a28d353be95c883/plot_distances.ipynb new file mode 100644 index 000000000..7e7ac10f5 --- /dev/null +++ b/_downloads/0dca98e912a44b724a28d353be95c883/plot_distances.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Distances exercise\n\nPlot distances in a grid\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nx, y = np.arange(5), np.arange(5)[:, np.newaxis]\ndistance = np.sqrt(x**2 + y**2)\nplt.pcolor(distance)\nplt.colorbar()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/0ddcbe2836331bb026e04cf9f41053a8/plot_polar.py b/_downloads/0ddcbe2836331bb026e04cf9f41053a8/plot_polar.py new file mode 100644 index 000000000..91cc4236b --- /dev/null +++ b/_downloads/0ddcbe2836331bb026e04cf9f41053a8/plot_polar.py @@ -0,0 +1,32 @@ +""" +Plotting in polar coordinates +============================= + +A simple example showing how to plot in polar coordinates with +matplotlib. +""" + +import numpy as np + +import matplotlib +import matplotlib.pyplot as plt + + +jet = matplotlib.colormaps["jet"] + +ax = plt.axes((0.025, 0.025, 0.95, 0.95), polar=True) + +N = 20 +theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N) +rng = np.random.default_rng() +radii = 10 * rng.random(N) +width = np.pi / 4 * rng.random(N) +bars = plt.bar(theta, radii, width=width, bottom=0.0) + +for r, bar in zip(radii, bars, strict=True): + bar.set_facecolor(jet(r / 10.0)) + bar.set_alpha(0.5) + +ax.set_xticklabels([]) +ax.set_yticklabels([]) +plt.show() diff --git a/_downloads/0e26fdc80e9a77a973f4c77e7c333789/plot_dash_capstyle.py b/_downloads/0e26fdc80e9a77a973f4c77e7c333789/plot_dash_capstyle.py new file mode 100644 index 000000000..b12b5b84b --- /dev/null +++ b/_downloads/0e26fdc80e9a77a973f4c77e7c333789/plot_dash_capstyle.py @@ -0,0 +1,49 @@ +""" +Dash capstyle +============= + +An example demoing the dash capstyle. +""" + +import numpy as np +import matplotlib.pyplot as plt + +size = 256, 16 +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = plt.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +plt.axes((0, 0, 1, 1), frameon=False) + +plt.plot( + np.arange(4), + np.ones(4), + color="blue", + dashes=[15, 15], + linewidth=8, + dash_capstyle="butt", +) + +plt.plot( + 5 + np.arange(4), + np.ones(4), + color="blue", + dashes=[15, 15], + linewidth=8, + dash_capstyle="round", +) + +plt.plot( + 10 + np.arange(4), + np.ones(4), + color="blue", + dashes=[15, 15], + linewidth=8, + dash_capstyle="projecting", +) + +plt.xlim(0, 14) +plt.xticks([]) +plt.yticks([]) + +plt.show() diff --git a/_downloads/0e4dc3aa10924cbc3a1bdae2cd82afcf/plot_exercise_3.zip b/_downloads/0e4dc3aa10924cbc3a1bdae2cd82afcf/plot_exercise_3.zip new file mode 100644 index 000000000..0fbc7597c Binary files /dev/null and b/_downloads/0e4dc3aa10924cbc3a1bdae2cd82afcf/plot_exercise_3.zip differ diff --git a/_downloads/0e9b2832686655f2f9da9554871561b4/plot_histo_segmentation.ipynb b/_downloads/0e9b2832686655f2f9da9554871561b4/plot_histo_segmentation.ipynb new file mode 100644 index 000000000..4792f3dd8 --- /dev/null +++ b/_downloads/0e9b2832686655f2f9da9554871561b4/plot_histo_segmentation.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Histogram segmentation\n\nThis example does simple histogram analysis to perform segmentation.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nrng = np.random.default_rng(27446968)\nn = 10\nl = 256\nim = np.zeros((l, l))\npoints = l * rng.random((2, n**2))\nim[(points[0]).astype(int), (points[1]).astype(int)] = 1\nim = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n))\n\nmask = (im > im.mean()).astype(float)\n\nmask += 0.1 * im\n\nimg = mask + 0.2 * rng.normal(size=mask.shape)\n\nhist, bin_edges = np.histogram(img, bins=60)\nbin_centers = 0.5 * (bin_edges[:-1] + bin_edges[1:])\n\nbinary_img = img > 0.5\n\nplt.figure(figsize=(11, 4))\n\nplt.subplot(131)\nplt.imshow(img)\nplt.axis(\"off\")\nplt.subplot(132)\nplt.plot(bin_centers, hist, lw=2)\nplt.axvline(0.5, color=\"r\", ls=\"--\", lw=2)\nplt.text(0.57, 0.8, \"histogram\", fontsize=20, transform=plt.gca().transAxes)\nplt.yticks([])\nplt.subplot(133)\nplt.imshow(binary_img, cmap=\"gray\", interpolation=\"nearest\")\nplt.axis(\"off\")\n\nplt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1)\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/0f171b529bccacaf8ca6f162a94ad61b/ScientificPythonLectures-simple.pdf b/_downloads/0f171b529bccacaf8ca6f162a94ad61b/ScientificPythonLectures-simple.pdf new file mode 100644 index 000000000..ceda064cc Binary files /dev/null and b/_downloads/0f171b529bccacaf8ca6f162a94ad61b/ScientificPythonLectures-simple.pdf differ diff --git a/_downloads/0f1ed4a3840a4b37e9d15bb4dd3fb55d/plot_noisy.py b/_downloads/0f1ed4a3840a4b37e9d15bb4dd3fb55d/plot_noisy.py new file mode 100644 index 000000000..9e39aa02f --- /dev/null +++ b/_downloads/0f1ed4a3840a4b37e9d15bb4dd3fb55d/plot_noisy.py @@ -0,0 +1,31 @@ +""" +Noisy optimization problem +=========================== + +Draws a figure explaining noisy vs non-noisy optimization +""" + +import numpy as np +import matplotlib.pyplot as plt + +rng = np.random.default_rng(27446968) + +x = np.linspace(-5, 5, 101) +x_ = np.linspace(-5, 5, 31) + + +def f(x): + return -np.exp(-(x**2)) + + +# A smooth function +plt.figure(1, figsize=(3, 2.5)) +plt.clf() + +plt.plot(x_, f(x_) + 0.2 * np.random.normal(size=31), linewidth=2) +plt.plot(x, f(x), linewidth=2) + +plt.ylim(ymin=-1.3) +plt.axis("off") +plt.tight_layout() +plt.show() diff --git a/_downloads/0f4b7cf58daefad1c7311ab73144dc41/plot_periodicity_finder.zip b/_downloads/0f4b7cf58daefad1c7311ab73144dc41/plot_periodicity_finder.zip new file mode 100644 index 000000000..3264edcf3 Binary files /dev/null and b/_downloads/0f4b7cf58daefad1c7311ab73144dc41/plot_periodicity_finder.zip differ diff --git a/_downloads/0f6c4bed2e96c559da2e21bed3a3ad6a/plot_curvefit_temperature_data.py b/_downloads/0f6c4bed2e96c559da2e21bed3a3ad6a/plot_curvefit_temperature_data.py new file mode 100644 index 000000000..46b77f1c8 --- /dev/null +++ b/_downloads/0f6c4bed2e96c559da2e21bed3a3ad6a/plot_curvefit_temperature_data.py @@ -0,0 +1,56 @@ +""" +============================================================== +Curve fitting: temperature as a function of month of the year +============================================================== + +We have the min and max temperatures in Alaska for each months of the +year. We would like to find a function to describe this yearly evolution. + +For this, we will fit a periodic function. +""" + +############################################################ +# The data +############################################################ +import numpy as np + +temp_max = np.array([17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18]) +temp_min = np.array([-62, -59, -56, -46, -32, -18, -9, -13, -25, -46, -52, -58]) + +import matplotlib.pyplot as plt + +months = np.arange(12) +plt.plot(months, temp_max, "ro") +plt.plot(months, temp_min, "bo") +plt.xlabel("Month") +plt.ylabel("Min and max temperature") + +############################################################ +# Fitting it to a periodic function +############################################################ + +import scipy as sp + + +def yearly_temps(times, avg, ampl, time_offset): + return avg + ampl * np.cos((times + time_offset) * 2 * np.pi / times.max()) + + +res_max, cov_max = sp.optimize.curve_fit(yearly_temps, months, temp_max, [20, 10, 0]) +res_min, cov_min = sp.optimize.curve_fit(yearly_temps, months, temp_min, [-40, 20, 0]) + +############################################################ +# Plotting the fit +############################################################ + +days = np.linspace(0, 12, num=365) + +plt.figure() +plt.plot(months, temp_max, "ro") +plt.plot(days, yearly_temps(days, *res_max), "r-") +plt.plot(months, temp_min, "bo") +plt.plot(days, yearly_temps(days, *res_min), "b-") +plt.xlabel("Month") +plt.ylabel(r"Temperature ($^\circ$C)") + +plt.show() diff --git a/_downloads/0f7a3cacf11ec37fcbe522bb150f459a/auto_examples_jupyter.zip b/_downloads/0f7a3cacf11ec37fcbe522bb150f459a/auto_examples_jupyter.zip new file mode 100644 index 000000000..ccf1a6bdc Binary files /dev/null and b/_downloads/0f7a3cacf11ec37fcbe522bb150f459a/auto_examples_jupyter.zip differ diff --git a/_downloads/0ffba524ee4345383f6e63b387be12e8/plot_ML_flow_chart.zip b/_downloads/0ffba524ee4345383f6e63b387be12e8/plot_ML_flow_chart.zip new file mode 100644 index 000000000..3bd9342c1 Binary files /dev/null and b/_downloads/0ffba524ee4345383f6e63b387be12e8/plot_ML_flow_chart.zip differ diff --git a/_downloads/10b7d9df1c7e589b34311e6c2d234dbc/plot_contour.zip b/_downloads/10b7d9df1c7e589b34311e6c2d234dbc/plot_contour.zip new file mode 100644 index 000000000..27e08730e Binary files /dev/null and b/_downloads/10b7d9df1c7e589b34311e6c2d234dbc/plot_contour.zip differ diff --git a/_downloads/112596f433ff95bdd91b27d9e8946059/plot_basic1dplot.py b/_downloads/112596f433ff95bdd91b27d9e8946059/plot_basic1dplot.py new file mode 100644 index 000000000..49b2f1764 --- /dev/null +++ b/_downloads/112596f433ff95bdd91b27d9e8946059/plot_basic1dplot.py @@ -0,0 +1,16 @@ +""" +1D plotting +=========== + +Plot a basic 1D figure + +""" + +import numpy as np +import matplotlib.pyplot as plt + +x = np.linspace(0, 3, 20) +y = np.linspace(0, 9, 20) +plt.plot(x, y) +plt.plot(x, y, "o") +plt.show() diff --git a/_downloads/112c5504b4c3482eb4beb76aaaa9aacd/plot_face_tv_denoise.ipynb b/_downloads/112c5504b4c3482eb4beb76aaaa9aacd/plot_face_tv_denoise.ipynb new file mode 100644 index 000000000..86bfa03a7 --- /dev/null +++ b/_downloads/112c5504b4c3482eb4beb76aaaa9aacd/plot_face_tv_denoise.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Total Variation denoising\n\nThis example demoes Total-Variation (TV) denoising on a Raccoon face.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nfrom skimage.restoration import denoise_tv_chambolle\n\nrng = np.random.default_rng(27446968)\n\nf = sp.datasets.face(gray=True)\nf = f[230:290, 220:320]\n\nnoisy = f + 0.4 * f.std() * rng.random(f.shape)\n\ntv_denoised = denoise_tv_chambolle(noisy, weight=10)\n\n\nplt.figure(figsize=(12, 2.8))\n\nplt.subplot(131)\nplt.imshow(noisy, cmap=\"gray\", vmin=40, vmax=220)\nplt.axis(\"off\")\nplt.title(\"noisy\", fontsize=20)\nplt.subplot(132)\nplt.imshow(tv_denoised, cmap=\"gray\", vmin=40, vmax=220)\nplt.axis(\"off\")\nplt.title(\"TV denoising\", fontsize=20)\n\ntv_denoised = denoise_tv_chambolle(noisy, weight=50)\nplt.subplot(133)\nplt.imshow(tv_denoised, cmap=\"gray\", vmin=40, vmax=220)\nplt.axis(\"off\")\nplt.title(\"(more) TV denoising\", fontsize=20)\n\nplt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1)\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/114d2fe096733f8b0b93757b39465f80/plot_check.py b/_downloads/114d2fe096733f8b0b93757b39465f80/plot_check.py new file mode 100644 index 000000000..79e7a5b47 --- /dev/null +++ b/_downloads/114d2fe096733f8b0b93757b39465f80/plot_check.py @@ -0,0 +1,17 @@ +""" +Creating an image +================== + +How to create an image with basic NumPy commands : ``np.zeros``, slicing... + +This examples show how to create a simple checkerboard. +""" + +import numpy as np +import matplotlib.pyplot as plt + +check = np.zeros((8, 8)) +check[::2, 1::2] = 1 +check[1::2, ::2] = 1 +plt.matshow(check, cmap="gray") +plt.show() diff --git a/_downloads/118f253ffa096d670fd43b8044006486/plot_good.ipynb b/_downloads/118f253ffa096d670fd43b8044006486/plot_good.ipynb new file mode 100644 index 000000000..6a2ac1809 --- /dev/null +++ b/_downloads/118f253ffa096d670fd43b8044006486/plot_good.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# A simple, good-looking plot\n\nDemoing some simple features of matplotlib\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib\n\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\n\nfig = plt.figure(figsize=(5, 4), dpi=72)\naxes = fig.add_axes((0.01, 0.01, 0.98, 0.98))\nX = np.linspace(0, 2, 200)\nY = np.sin(2 * np.pi * X)\nplt.plot(X, Y, lw=2)\nplt.ylim(-1.1, 1.1)\nplt.grid()\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/126a7e57c73fe537efa22e2be1887084/plot_elephant.ipynb b/_downloads/126a7e57c73fe537efa22e2be1887084/plot_elephant.ipynb new file mode 100644 index 000000000..d4ffbb0e3 --- /dev/null +++ b/_downloads/126a7e57c73fe537efa22e2be1887084/plot_elephant.ipynb @@ -0,0 +1,97 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Reading and writing an elephant\n\nRead and write images\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## original figure\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "plt.figure()\nimg = plt.imread(\"../../../data/elephant.png\")\nplt.imshow(img)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## red channel displayed in grey\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "plt.figure()\nimg_red = img[:, :, 0]\nplt.imshow(img_red, cmap=\"gray\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## lower resolution\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "plt.figure()\nimg_tiny = img[::6, ::6]\nplt.imshow(img_tiny, interpolation=\"nearest\")\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/12f1dad9afbfc10a7b6e779135f754d5/plot_compare_optimizers.zip b/_downloads/12f1dad9afbfc10a7b6e779135f754d5/plot_compare_optimizers.zip new file mode 100644 index 000000000..95220d3f2 Binary files /dev/null and b/_downloads/12f1dad9afbfc10a7b6e779135f754d5/plot_compare_optimizers.zip differ diff --git a/_downloads/12f6f480e8eb81e99193e20d721778b2/plot_curve_fit.ipynb b/_downloads/12f6f480e8eb81e99193e20d721778b2/plot_curve_fit.ipynb new file mode 100644 index 000000000..3a2b684db --- /dev/null +++ b/_downloads/12f6f480e8eb81e99193e20d721778b2/plot_curve_fit.ipynb @@ -0,0 +1,86 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Curve fitting\n\nDemos a simple curve fitting\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "First generate some data\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n\n# Seed the random number generator for reproducibility\nrng = np.random.default_rng(27446968)\n\nx_data = np.linspace(-5, 5, num=50)\nnoise = 0.01 * np.cos(100 * x_data)\na, b = 2.9, 1.5\ny_data = a * np.cos(b * x_data) + noise\n\n# And plot it\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(6, 4))\nplt.scatter(x_data, y_data)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now fit a simple sine function to the data\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import scipy as sp\n\n\ndef test_func(x, a, b, c):\n return a * np.sin(b * x + c)\n\n\nparams, params_covariance = sp.optimize.curve_fit(\n test_func, x_data, y_data, p0=[2, 1, 3]\n)\n\nprint(params)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "And plot the resulting curve on the data\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "plt.figure(figsize=(6, 4))\nplt.scatter(x_data, y_data, label=\"Data\")\nplt.plot(x_data, test_func(x_data, *params), label=\"Fitted function\")\n\nplt.legend(loc=\"best\")\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/138eaf5870265a2e789724763edc3038/plot_exercise_4.zip b/_downloads/138eaf5870265a2e789724763edc3038/plot_exercise_4.zip new file mode 100644 index 000000000..5a3a000c2 Binary files /dev/null and b/_downloads/138eaf5870265a2e789724763edc3038/plot_exercise_4.zip differ diff --git a/_downloads/13a3c500d7944742d7b6519723a77078/plot_ms.zip b/_downloads/13a3c500d7944742d7b6519723a77078/plot_ms.zip new file mode 100644 index 000000000..f1fbeac06 Binary files /dev/null and b/_downloads/13a3c500d7944742d7b6519723a77078/plot_ms.zip differ diff --git a/_downloads/1477cc10abec44ecdbca60a82fdc05b8/plot_markers.py b/_downloads/1477cc10abec44ecdbca60a82fdc05b8/plot_markers.py new file mode 100644 index 000000000..77da9cb96 --- /dev/null +++ b/_downloads/1477cc10abec44ecdbca60a82fdc05b8/plot_markers.py @@ -0,0 +1,70 @@ +""" +Markers +======= + +Show the different markers of matplotlib. +""" + +import numpy as np +import matplotlib.pyplot as plt + + +def marker(m, i): + X = i * 0.5 * np.ones(11) + Y = np.arange(11) + + plt.plot(X, Y, lw=1, marker=m, ms=10, mfc=(0.75, 0.75, 1, 1), mec=(0, 0, 1, 1)) + plt.text(0.5 * i, 10.25, repr(m), rotation=90, fontsize=15, va="bottom") + + +markers = [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + "o", + "h", + "_", + "1", + "2", + "3", + "4", + "8", + "p", + "^", + "v", + "<", + ">", + "|", + "d", + ",", + "+", + "s", + "*", + "|", + "x", + "D", + "H", + ".", +] + +n_markers = len(markers) + +size = 20 * n_markers, 300 +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = plt.figure(figsize=figsize, dpi=dpi) +plt.axes((0, 0.01, 1, 0.9), frameon=False) + +for i, m in enumerate(markers): + marker(m, i) + +plt.xlim(-0.2, 0.2 + 0.5 * n_markers) +plt.xticks([]) +plt.yticks([]) + +plt.show() diff --git a/_downloads/14802eea7e74fb1f419e21314c008986/plot_smooth.ipynb b/_downloads/14802eea7e74fb1f419e21314c008986/plot_smooth.ipynb new file mode 100644 index 000000000..ce17d8e0f --- /dev/null +++ b/_downloads/14802eea7e74fb1f419e21314c008986/plot_smooth.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Smooth vs non-smooth\n\nDraws a figure to explain smooth versus non smooth optimization.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.linspace(-1.5, 1.5, 101)\n\n# A smooth function\nplt.figure(1, figsize=(3, 2.5))\nplt.clf()\n\nplt.plot(x, np.sqrt(0.2 + x**2), linewidth=2)\nplt.text(-1, 0, \"$f$\", size=20)\n\nplt.ylim(ymin=-0.2)\nplt.axis(\"off\")\nplt.tight_layout()\n\n# A non-smooth function\nplt.figure(2, figsize=(3, 2.5))\nplt.clf()\nplt.plot(x, np.abs(x), linewidth=2)\nplt.text(-1, 0, \"$f$\", size=20)\n\nplt.ylim(ymin=-0.2)\nplt.axis(\"off\")\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/14f31a0b80f0a915eeeeea8c4ae75ff1/plot_interpolation_face.zip b/_downloads/14f31a0b80f0a915eeeeea8c4ae75ff1/plot_interpolation_face.zip new file mode 100644 index 000000000..28da8d450 Binary files /dev/null and b/_downloads/14f31a0b80f0a915eeeeea8c4ae75ff1/plot_interpolation_face.zip differ diff --git a/_downloads/151bac32ba61370a605777d164489579/plot_variance_linear_regr.zip b/_downloads/151bac32ba61370a605777d164489579/plot_variance_linear_regr.zip new file mode 100644 index 000000000..f09bb61a4 Binary files /dev/null and b/_downloads/151bac32ba61370a605777d164489579/plot_variance_linear_regr.zip differ diff --git a/_downloads/1600785c2fb708acded25c8c68a79ff2/auto_examples_python.zip b/_downloads/1600785c2fb708acded25c8c68a79ff2/auto_examples_python.zip new file mode 100644 index 000000000..d4f00b6e8 Binary files /dev/null and b/_downloads/1600785c2fb708acded25c8c68a79ff2/auto_examples_python.zip differ diff --git a/_downloads/166411124cb7aa50d41b7810f8608d70/plot_plot3d_ext.zip b/_downloads/166411124cb7aa50d41b7810f8608d70/plot_plot3d_ext.zip new file mode 100644 index 000000000..bdfcaa173 Binary files /dev/null and b/_downloads/166411124cb7aa50d41b7810f8608d70/plot_plot3d_ext.zip differ diff --git a/_downloads/16cf44ebfa88732cb5d75a6c3b8713e7/plot_find_edges.zip b/_downloads/16cf44ebfa88732cb5d75a6c3b8713e7/plot_find_edges.zip new file mode 100644 index 000000000..b23e24c8f Binary files /dev/null and b/_downloads/16cf44ebfa88732cb5d75a6c3b8713e7/plot_find_edges.zip differ diff --git a/_downloads/172530873850b3fdc1f43a5b8e223621/plot_airfare.ipynb b/_downloads/172530873850b3fdc1f43a5b8e223621/plot_airfare.ipynb new file mode 100644 index 000000000..e9704b49c --- /dev/null +++ b/_downloads/172530873850b3fdc1f43a5b8e223621/plot_airfare.ipynb @@ -0,0 +1,151 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Air fares before and after 9/11\n\nThis is a business-intelligence (BI) like application.\n\nWhat is interesting here is that we may want to study fares as a function\nof the year, paired accordingly to the trips, or forgetting the year,\nonly as a function of the trip endpoints.\n\nUsing statsmodels' linear models, we find that both with an OLS (ordinary\nleast square) and a robust fit, the intercept and the slope are\nsignificantly non-zero: the air fares have decreased between 2000 and\n2001, and their dependence on distance travelled has also decreased\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Standard library imports\nimport os" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Load the data\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import pandas\nimport requests\n\nif not os.path.exists(\"airfares.txt\"):\n # Download the file if it is not present\n r = requests.get(\n \"https://users.stat.ufl.edu/~winner/data/airq4.dat\",\n verify=False, # Wouldn't normally do this, but this site's certificate\n # is not yet distributed\n )\n with open(\"airfares.txt\", \"wb\") as f:\n f.write(r.content)\n\n# As a separator, ' +' is a regular expression that means 'one of more\n# space'\ndata = pandas.read_csv(\n \"airfares.txt\",\n delim_whitespace=True,\n header=0,\n names=[\n \"city1\",\n \"city2\",\n \"pop1\",\n \"pop2\",\n \"dist\",\n \"fare_2000\",\n \"nb_passengers_2000\",\n \"fare_2001\",\n \"nb_passengers_2001\",\n ],\n)\n\n# we log-transform the number of passengers\nimport numpy as np\n\ndata[\"nb_passengers_2000\"] = np.log10(data[\"nb_passengers_2000\"])\ndata[\"nb_passengers_2001\"] = np.log10(data[\"nb_passengers_2001\"])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Make a dataframe with the year as an attribute, instead of separate columns\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# This involves a small danse in which we separate the dataframes in 2,\n# one for year 2000, and one for 2001, before concatenating again.\n\n# Make an index of each flight\ndata_flat = data.reset_index()\n\ndata_2000 = data_flat[\n [\"city1\", \"city2\", \"pop1\", \"pop2\", \"dist\", \"fare_2000\", \"nb_passengers_2000\"]\n]\n# Rename the columns\ndata_2000.columns = pandas.Index(\n [\"city1\", \"city2\", \"pop1\", \"pop2\", \"dist\", \"fare\", \"nb_passengers\"]\n)\n# Add a column with the year\ndata_2000.insert(0, \"year\", 2000)\n\ndata_2001 = data_flat[\n [\"city1\", \"city2\", \"pop1\", \"pop2\", \"dist\", \"fare_2001\", \"nb_passengers_2001\"]\n]\n# Rename the columns\ndata_2001.columns = pandas.Index(\n [\"city1\", \"city2\", \"pop1\", \"pop2\", \"dist\", \"fare\", \"nb_passengers\"]\n)\n# Add a column with the year\ndata_2001.insert(0, \"year\", 2001)\n\ndata_flat = pandas.concat([data_2000, data_2001])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Plot scatter matrices highlighting different aspects\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import seaborn\n\nseaborn.pairplot(\n data_flat, vars=[\"fare\", \"dist\", \"nb_passengers\"], kind=\"reg\", markers=\".\"\n)\n\n# A second plot, to show the effect of the year (ie the 9/11 effect)\nseaborn.pairplot(\n data_flat,\n vars=[\"fare\", \"dist\", \"nb_passengers\"],\n kind=\"reg\",\n hue=\"year\",\n markers=\".\",\n)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Plot the difference in fare\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nplt.figure(figsize=(5, 2))\nseaborn.boxplot(data.fare_2001 - data.fare_2000)\nplt.title(\"Fare: 2001 - 2000\")\nplt.subplots_adjust()\n\nplt.figure(figsize=(5, 2))\nseaborn.boxplot(data.nb_passengers_2001 - data.nb_passengers_2000)\nplt.title(\"NB passengers: 2001 - 2000\")\nplt.subplots_adjust()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Statistical testing: dependence of fare on distance and number of\npassengers\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import statsmodels.formula.api as sm\n\nresult = sm.ols(formula=\"fare ~ 1 + dist + nb_passengers\", data=data_flat).fit()\nprint(result.summary())\n\n# Using a robust fit\nresult = sm.rlm(formula=\"fare ~ 1 + dist + nb_passengers\", data=data_flat).fit()\nprint(result.summary())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Statistical testing: regression of fare on distance: 2001/2000 difference\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "result = sm.ols(formula=\"fare_2001 - fare_2000 ~ 1 + dist\", data=data).fit()\nprint(result.summary())\n\n# Plot the corresponding regression\ndata[\"fare_difference\"] = data[\"fare_2001\"] - data[\"fare_2000\"]\nseaborn.lmplot(x=\"dist\", y=\"fare_difference\", data=data)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/17b24fa3bf34531cd916bcef4b894614/plot_optimize_lidar_data.py b/_downloads/17b24fa3bf34531cd916bcef4b894614/plot_optimize_lidar_data.py new file mode 100644 index 000000000..b7bde0fb4 --- /dev/null +++ b/_downloads/17b24fa3bf34531cd916bcef4b894614/plot_optimize_lidar_data.py @@ -0,0 +1,19 @@ +""" +The lidar system, data (1 of 2 datasets) +======================================== + +Generate a chart of the data recorded by the lidar system +""" + +import numpy as np +import matplotlib.pyplot as plt + +waveform_1 = np.load("waveform_1.npy") + +t = np.arange(len(waveform_1)) + +fig, ax = plt.subplots(figsize=(8, 6)) +plt.plot(t, waveform_1) +plt.xlabel("Time [ns]") +plt.ylabel("Amplitude [bins]") +plt.show() diff --git a/_downloads/18d557409fdfb3d9633ddd820689f51f/plot_sprog_annual_maxima.py b/_downloads/18d557409fdfb3d9633ddd820689f51f/plot_sprog_annual_maxima.py new file mode 100644 index 000000000..c2f7fc1d0 --- /dev/null +++ b/_downloads/18d557409fdfb3d9633ddd820689f51f/plot_sprog_annual_maxima.py @@ -0,0 +1,19 @@ +""" +The Gumbell distribution, results +================================= + +Generate the exercise results on the Gumbell distribution +""" + +import numpy as np +import matplotlib.pyplot as plt + +years_nb = 21 +wspeeds = np.load("sprog-windspeeds.npy") +max_speeds = np.array([arr.max() for arr in np.array_split(wspeeds, years_nb)]) + +plt.figure() +plt.bar(np.arange(years_nb) + 1, max_speeds) +plt.axis("tight") +plt.xlabel("Year") +plt.ylabel("Annual wind speed maxima [$m/s$]") diff --git a/_downloads/18f8c501c9dc5f0290a6dd46c5887386/plot_optimize_example1.zip b/_downloads/18f8c501c9dc5f0290a6dd46c5887386/plot_optimize_example1.zip new file mode 100644 index 000000000..8b03b408a Binary files /dev/null and b/_downloads/18f8c501c9dc5f0290a6dd46c5887386/plot_optimize_example1.zip differ diff --git a/_downloads/19f32cf6c03f9c5d687862ca1e503928/plot_pie_ext.ipynb b/_downloads/19f32cf6c03f9c5d687862ca1e503928/plot_pie_ext.ipynb new file mode 100644 index 000000000..99e93f8fb --- /dev/null +++ b/_downloads/19f32cf6c03f9c5d687862ca1e503928/plot_pie_ext.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Pie chart vignette\n\nDemo pie chart with matplotlib and style the figure.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nn = 20\nX = np.ones(n)\nX[-1] *= 2\nplt.pie(X, explode=X * 0.05, colors=[f\"{i / float(n):f}\" for i in range(n)])\n\nfig = plt.gcf()\nw, h = fig.get_figwidth(), fig.get_figheight()\nr = h / float(w)\n\nplt.xlim(-1.5, 1.5)\nplt.ylim(-1.5 * r, 1.5 * r)\nplt.xticks([])\nplt.yticks([])\n\n\n# Add a title and a box around it\nfrom matplotlib.patches import FancyBboxPatch\n\nax = plt.gca()\nax.add_patch(\n FancyBboxPatch(\n (-0.05, 0.87),\n width=0.66,\n height=0.165,\n clip_on=False,\n boxstyle=\"square,pad=0\",\n zorder=3,\n facecolor=\"white\",\n alpha=1.0,\n transform=plt.gca().transAxes,\n )\n)\n\nplt.text(\n -0.05,\n 1.02,\n \" Pie Chart: plt.pie(...)\\n\",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"xx-large\",\n transform=plt.gca().transAxes,\n)\n\nplt.text(\n -0.05,\n 1.01,\n \"\\n\\n Make a pie chart of an array \",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"large\",\n transform=plt.gca().transAxes,\n)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/19f4ad99ff1853c5df8b14bf5dcca3b0/plot_polyfit.zip b/_downloads/19f4ad99ff1853c5df8b14bf5dcca3b0/plot_polyfit.zip new file mode 100644 index 000000000..89cb7d117 Binary files /dev/null and b/_downloads/19f4ad99ff1853c5df8b14bf5dcca3b0/plot_polyfit.zip differ diff --git a/_downloads/1a1177aeca6040158a5edbbf7debfea4/plot_threshold.ipynb b/_downloads/1a1177aeca6040158a5edbbf7debfea4/plot_threshold.ipynb new file mode 100644 index 000000000..0252cdf38 --- /dev/null +++ b/_downloads/1a1177aeca6040158a5edbbf7debfea4/plot_threshold.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Otsu thresholding\n\nThis example illustrates automatic Otsu thresholding.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\nfrom skimage import data\nfrom skimage import filters\nfrom skimage import exposure\n\ncamera = data.camera()\nval = filters.threshold_otsu(camera)\n\nhist, bins_center = exposure.histogram(camera)\n\nplt.figure(figsize=(9, 4))\nplt.subplot(131)\nplt.imshow(camera, cmap=\"gray\", interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.subplot(132)\nplt.imshow(camera < val, cmap=\"gray\", interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.subplot(133)\nplt.plot(bins_center, hist, lw=2)\nplt.axvline(val, color=\"k\", ls=\"--\")\n\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/1a41b43673f07ac748eec7d364db242f/plot_exercise_2.py b/_downloads/1a41b43673f07ac748eec7d364db242f/plot_exercise_2.py new file mode 100644 index 000000000..bd934ccf4 --- /dev/null +++ b/_downloads/1a41b43673f07ac748eec7d364db242f/plot_exercise_2.py @@ -0,0 +1,39 @@ +""" +Exercise 2 +=========== + +Exercise 2 with matplotlib. +""" + +import numpy as np +import matplotlib.pyplot as plt + +# Create a new figure of size 8x6 points, using 100 dots per inch +plt.figure(figsize=(8, 6), dpi=80) + +# Create a new subplot from a grid of 1x1 +plt.subplot(111) + +X = np.linspace(-np.pi, np.pi, 256) +C, S = np.cos(X), np.sin(X) + +# Plot cosine using blue color with a continuous line of width 1 (pixels) +plt.plot(X, C, color="blue", linewidth=1.0, linestyle="-") + +# Plot sine using green color with a continuous line of width 1 (pixels) +plt.plot(X, S, color="green", linewidth=1.0, linestyle="-") + +# Set x limits +plt.xlim(-4.0, 4.0) + +# Set x ticks +plt.xticks(np.linspace(-4, 4, 9)) + +# Set y limits +plt.ylim(-1.0, 1.0) + +# Set y ticks +plt.yticks(np.linspace(-1, 1, 5)) + +# Show result on screen +plt.show() diff --git a/_downloads/1a454db4c0ce957f8f0d82235f08cd6b/auto_examples_jupyter.zip b/_downloads/1a454db4c0ce957f8f0d82235f08cd6b/auto_examples_jupyter.zip new file mode 100644 index 000000000..91f42d36b Binary files /dev/null and b/_downloads/1a454db4c0ce957f8f0d82235f08cd6b/auto_examples_jupyter.zip differ diff --git a/_downloads/1aa074ddcfe8c04507f99235341abfa7/plot_exercise_ill_conditioned.zip b/_downloads/1aa074ddcfe8c04507f99235341abfa7/plot_exercise_ill_conditioned.zip new file mode 100644 index 000000000..560fe5803 Binary files /dev/null and b/_downloads/1aa074ddcfe8c04507f99235341abfa7/plot_exercise_ill_conditioned.zip differ diff --git a/_downloads/1afc993252ae1472377f6be57c897c66/plot_optimize_lidar_complex_data.zip b/_downloads/1afc993252ae1472377f6be57c897c66/plot_optimize_lidar_complex_data.zip new file mode 100644 index 000000000..1bf10bb69 Binary files /dev/null and b/_downloads/1afc993252ae1472377f6be57c897c66/plot_optimize_lidar_complex_data.zip differ diff --git a/_downloads/1b214f8a9cc77a552d8d8af35dd57c8d/plot_constraints.py b/_downloads/1b214f8a9cc77a552d8d8af35dd57c8d/plot_constraints.py new file mode 100644 index 000000000..05d55e079 --- /dev/null +++ b/_downloads/1b214f8a9cc77a552d8d8af35dd57c8d/plot_constraints.py @@ -0,0 +1,65 @@ +""" +Constraint optimization: visualizing the geometry +================================================== + +A small figure explaining optimization with constraints +""" + +import numpy as np +import matplotlib.pyplot as plt +import scipy as sp + +x, y = np.mgrid[-2.9:5.8:0.05, -2.5:5:0.05] # type: ignore[misc] +x = x.T +y = y.T + +for i in (1, 2): + # Create 2 figure: only the second one will have the optimization + # path + plt.figure(i, figsize=(3, 2.5)) + plt.clf() + plt.axes((0, 0, 1, 1)) + + contours = plt.contour( + np.sqrt((x - 3) ** 2 + (y - 2) ** 2), + extent=[-3, 6, -2.5, 5], + cmap="gnuplot", + ) + plt.clabel(contours, inline=1, fmt="%1.1f", fontsize=14) + plt.plot( + [-1.5, -1.5, 1.5, 1.5, -1.5], [-1.5, 1.5, 1.5, -1.5, -1.5], "k", linewidth=2 + ) + plt.fill_between([-1.5, 1.5], [-1.5, -1.5], [1.5, 1.5], color=".8") + plt.axvline(0, color="k") + plt.axhline(0, color="k") + + plt.text(-0.9, 4.4, "$x_2$", size=20) + plt.text(5.6, -0.6, "$x_1$", size=20) + plt.axis("equal") + plt.axis("off") + +# And now plot the optimization path +accumulator = [] + + +def f(x): + # Store the list of function calls + accumulator.append(x) + return np.sqrt((x[0] - 3) ** 2 + (x[1] - 2) ** 2) + + +# We don't use the gradient, as with the gradient, L-BFGS is too fast, +# and finds the optimum without showing us a pretty path +def f_prime(x): + r = np.sqrt((x[0] - 3) ** 2 + (x[0] - 2) ** 2) + return np.array(((x[0] - 3) / r, (x[0] - 2) / r)) + + +sp.optimize.minimize( + f, np.array([0, 0]), method="L-BFGS-B", bounds=((-1.5, 1.5), (-1.5, 1.5)) +) + +accumulated = np.array(accumulator) +plt.plot(accumulated[:, 0], accumulated[:, 1]) + +plt.show() diff --git a/_downloads/1b9ca3c48567ac6a258ea9a99b43bea0/auto_examples_python.zip b/_downloads/1b9ca3c48567ac6a258ea9a99b43bea0/auto_examples_python.zip new file mode 100644 index 000000000..f599b2305 Binary files /dev/null and b/_downloads/1b9ca3c48567ac6a258ea9a99b43bea0/auto_examples_python.zip differ diff --git a/_downloads/1bb7a80f4aaab4db8c1ec30c543d7dfb/plot_convex.zip b/_downloads/1bb7a80f4aaab4db8c1ec30c543d7dfb/plot_convex.zip new file mode 100644 index 000000000..76d8f52e5 Binary files /dev/null and b/_downloads/1bb7a80f4aaab4db8c1ec30c543d7dfb/plot_convex.zip differ diff --git a/_downloads/1d77b828fba479aebabc7c28fcc5bd75/plot_quiver.ipynb b/_downloads/1d77b828fba479aebabc7c28fcc5bd75/plot_quiver.ipynb new file mode 100644 index 000000000..e9ec33a7d --- /dev/null +++ b/_downloads/1d77b828fba479aebabc7c28fcc5bd75/plot_quiver.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plotting a vector field: quiver\n\nA simple example showing how to plot a vector field (quiver) with\nmatplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nn = 8\nX, Y = np.mgrid[0:n, 0:n]\nT = np.arctan2(Y - n / 2.0, X - n / 2.0)\nR = 10 + np.sqrt((Y - n / 2.0) ** 2 + (X - n / 2.0) ** 2)\nU, V = R * np.cos(T), R * np.sin(T)\n\nplt.axes((0.025, 0.025, 0.95, 0.95))\nplt.quiver(X, Y, U, V, R, alpha=0.5)\nplt.quiver(X, Y, U, V, edgecolor=\"k\", facecolor=\"None\", linewidth=0.5)\n\nplt.xlim(-1, n)\nplt.xticks([])\nplt.ylim(-1, n)\nplt.yticks([])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/1d89e4f6cedb92caa5757ad43c58573d/plot_blur.zip b/_downloads/1d89e4f6cedb92caa5757ad43c58573d/plot_blur.zip new file mode 100644 index 000000000..10658f687 Binary files /dev/null and b/_downloads/1d89e4f6cedb92caa5757ad43c58573d/plot_blur.zip differ diff --git a/_downloads/1db51a25a023c3c90db4156a85fa8964/plot_denoising.zip b/_downloads/1db51a25a023c3c90db4156a85fa8964/plot_denoising.zip new file mode 100644 index 000000000..1b96211dd Binary files /dev/null and b/_downloads/1db51a25a023c3c90db4156a85fa8964/plot_denoising.zip differ diff --git a/_downloads/1dbd874c7a27aa4544b27d33e2c37da9/plot_image_filters.ipynb b/_downloads/1dbd874c7a27aa4544b27d33e2c37da9/plot_image_filters.ipynb new file mode 100644 index 000000000..db80e77af --- /dev/null +++ b/_downloads/1dbd874c7a27aa4544b27d33e2c37da9/plot_image_filters.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot filtering on images\n\nDemo filtering for denoising of images.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Load some data\nimport scipy as sp\n\nface = sp.datasets.face(gray=True)\nface = face[:512, -512:] # crop out square on right\n\n# Apply a variety of filters\nimport matplotlib.pyplot as plt\n\nimport numpy as np\n\nnoisy_face = np.copy(face).astype(float)\nrng = np.random.default_rng()\nnoisy_face += face.std() * 0.5 * rng.standard_normal(face.shape)\nblurred_face = sp.ndimage.gaussian_filter(noisy_face, sigma=3)\nmedian_face = sp.ndimage.median_filter(noisy_face, size=5)\nwiener_face = sp.signal.wiener(noisy_face, (5, 5))\n\nplt.figure(figsize=(12, 3.5))\nplt.subplot(141)\nplt.imshow(noisy_face, cmap=\"gray\")\nplt.axis(\"off\")\nplt.title(\"noisy\")\n\nplt.subplot(142)\nplt.imshow(blurred_face, cmap=\"gray\")\nplt.axis(\"off\")\nplt.title(\"Gaussian filter\")\n\nplt.subplot(143)\nplt.imshow(median_face, cmap=\"gray\")\nplt.axis(\"off\")\nplt.title(\"median filter\")\n\nplt.subplot(144)\nplt.imshow(wiener_face, cmap=\"gray\")\nplt.title(\"Wiener filter\")\nplt.axis(\"off\")\n\nplt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/1e0ac375adddb20afba1a59881719a78/plot_solid_capstyle.zip b/_downloads/1e0ac375adddb20afba1a59881719a78/plot_solid_capstyle.zip new file mode 100644 index 000000000..f9dda5b47 Binary files /dev/null and b/_downloads/1e0ac375adddb20afba1a59881719a78/plot_solid_capstyle.zip differ diff --git a/_downloads/1e39775e76973bfb299c272a0c173be4/plot_pie_ext.py b/_downloads/1e39775e76973bfb299c272a0c173be4/plot_pie_ext.py new file mode 100644 index 000000000..0d781ab8b --- /dev/null +++ b/_downloads/1e39775e76973bfb299c272a0c173be4/plot_pie_ext.py @@ -0,0 +1,64 @@ +""" +Pie chart vignette +=================== + +Demo pie chart with matplotlib and style the figure. +""" + +import numpy as np +import matplotlib.pyplot as plt + +n = 20 +X = np.ones(n) +X[-1] *= 2 +plt.pie(X, explode=X * 0.05, colors=[f"{i / float(n):f}" for i in range(n)]) + +fig = plt.gcf() +w, h = fig.get_figwidth(), fig.get_figheight() +r = h / float(w) + +plt.xlim(-1.5, 1.5) +plt.ylim(-1.5 * r, 1.5 * r) +plt.xticks([]) +plt.yticks([]) + + +# Add a title and a box around it +from matplotlib.patches import FancyBboxPatch + +ax = plt.gca() +ax.add_patch( + FancyBboxPatch( + (-0.05, 0.87), + width=0.66, + height=0.165, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) +) + +plt.text( + -0.05, + 1.02, + " Pie Chart: plt.pie(...)\n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=plt.gca().transAxes, +) + +plt.text( + -0.05, + 1.01, + "\n\n Make a pie chart of an array ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=plt.gca().transAxes, +) + +plt.show() diff --git a/_downloads/1e9a6cd8cd3ac6d49a142bc79a45d91b/plot_randomwalk.ipynb b/_downloads/1e9a6cd8cd3ac6d49a142bc79a45d91b/plot_randomwalk.ipynb new file mode 100644 index 000000000..0f1d77ff4 --- /dev/null +++ b/_downloads/1e9a6cd8cd3ac6d49a142bc79a45d91b/plot_randomwalk.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Random walk exercise\n\nPlot distance as a function of time for a random walk\ntogether with the theoretical result\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\n# We create 1000 realizations with 200 steps each\nn_stories = 1000\nt_max = 200\n\nt = np.arange(t_max)\n# Steps can be -1 or 1 (note that randint excludes the upper limit)\nrng = np.random.default_rng()\nsteps = 2 * rng.integers(0, 1 + 1, (n_stories, t_max)) - 1\n\n# The time evolution of the position is obtained by successively\n# summing up individual steps. This is done for each of the\n# realizations, i.e. along axis 1.\npositions = np.cumsum(steps, axis=1)\n\n# Determine the time evolution of the mean square distance.\nsq_distance = positions**2\nmean_sq_distance = np.mean(sq_distance, axis=0)\n\n# Plot the distance d from the origin as a function of time and\n# compare with the theoretically expected result where d(t)\n# grows as a square root of time t.\nplt.figure(figsize=(4, 3))\nplt.plot(t, np.sqrt(mean_sq_distance), \"g.\", t, np.sqrt(t), \"y-\")\nplt.xlabel(r\"$t$\")\nplt.ylabel(r\"$\\sqrt{\\langle (\\delta x)^2 \\rangle}$\")\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/1ecfa46b247218b67a3ecba48ddb76b3/plot_face.zip b/_downloads/1ecfa46b247218b67a3ecba48ddb76b3/plot_face.zip new file mode 100644 index 000000000..5f7992f50 Binary files /dev/null and b/_downloads/1ecfa46b247218b67a3ecba48ddb76b3/plot_face.zip differ diff --git a/_downloads/1efa35b4eb52d226ce075e7e4886a233/plot_filter_coins.py b/_downloads/1efa35b4eb52d226ce075e7e4886a233/plot_filter_coins.py new file mode 100644 index 000000000..f44d8324d --- /dev/null +++ b/_downloads/1efa35b4eb52d226ce075e7e4886a233/plot_filter_coins.py @@ -0,0 +1,37 @@ +""" +Various denoising filters +========================= + +This example compares several denoising filters available in scikit-image: +a Gaussian filter, a median filter, and total variation denoising. +""" + +import numpy as np +import matplotlib.pyplot as plt +from skimage import data +from skimage import filters +from skimage import restoration + +coins = data.coins() +gaussian_filter_coins = filters.gaussian(coins, sigma=2) +med_filter_coins = filters.median(coins, np.ones((3, 3))) +tv_filter_coins = restoration.denoise_tv_chambolle(coins, weight=0.1) + +plt.figure(figsize=(16, 4)) +plt.subplot(141) +plt.imshow(coins[10:80, 300:370], cmap="gray", interpolation="nearest") +plt.axis("off") +plt.title("Image") +plt.subplot(142) +plt.imshow(gaussian_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest") +plt.axis("off") +plt.title("Gaussian filter") +plt.subplot(143) +plt.imshow(med_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest") +plt.axis("off") +plt.title("Median filter") +plt.subplot(144) +plt.imshow(tv_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest") +plt.axis("off") +plt.title("TV filter") +plt.show() diff --git a/_downloads/1f014b3692d6ded8c965e3167006f244/plot_ms.ipynb b/_downloads/1f014b3692d6ded8c965e3167006f244/plot_ms.ipynb new file mode 100644 index 000000000..dd9933095 --- /dev/null +++ b/_downloads/1f014b3692d6ded8c965e3167006f244/plot_ms.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Marker size\n\nDemo the marker size control in matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nsize = 256, 16\ndpi = 72.0\nfigsize = size[0] / float(dpi), size[1] / float(dpi)\nfig = plt.figure(figsize=figsize, dpi=dpi)\nfig.patch.set_alpha(0)\nplt.axes((0, 0, 1, 1), frameon=False)\n\nfor i in range(1, 11):\n plt.plot(\n [\n i,\n ],\n [\n 1,\n ],\n \"s\",\n markersize=i,\n markerfacecolor=\"w\",\n markeredgewidth=0.5,\n markeredgecolor=\"k\",\n )\n\nplt.xlim(0, 11)\nplt.xticks([])\nplt.yticks([])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/1fb7bb15cc2b23321299f7ea3ef2fd35/plot_bad.py b/_downloads/1fb7bb15cc2b23321299f7ea3ef2fd35/plot_bad.py new file mode 100644 index 000000000..a59fef36a --- /dev/null +++ b/_downloads/1fb7bb15cc2b23321299f7ea3ef2fd35/plot_bad.py @@ -0,0 +1,22 @@ +""" +A simple plotting example +========================== + +A plotting example with a few simple tweaks +""" + +import numpy as np +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt + +fig = plt.figure(figsize=(5, 4), dpi=72) +axes = fig.add_axes((0.01, 0.01, 0.98, 0.98)) +x = np.linspace(0, 2, 200) +y = np.sin(2 * np.pi * x) +plt.plot(x, y, lw=0.25, c="k") +plt.xticks(np.arange(0.0, 2.0, 0.1)) +plt.yticks(np.arange(-1.0, 1.0, 0.1)) +plt.grid() +plt.show() diff --git a/_downloads/2017598365461f3c4b0a71d03ff45443/plot_aliased.zip b/_downloads/2017598365461f3c4b0a71d03ff45443/plot_aliased.zip new file mode 100644 index 000000000..f4fc61a02 Binary files /dev/null and b/_downloads/2017598365461f3c4b0a71d03ff45443/plot_aliased.zip differ diff --git a/_downloads/203508b87fdf5e4c5d7d7110ba3963fc/plot_sharpen.py b/_downloads/203508b87fdf5e4c5d7d7110ba3963fc/plot_sharpen.py new file mode 100644 index 000000000..8f8e65a5a --- /dev/null +++ b/_downloads/203508b87fdf5e4c5d7d7110ba3963fc/plot_sharpen.py @@ -0,0 +1,33 @@ +""" +Image sharpening +================= + +This example shows how to sharpen an image in noiseless situation by +applying the filter inverse to the blur. +""" + +import scipy as sp +import matplotlib.pyplot as plt + +f = sp.datasets.face(gray=True).astype(float) +blurred_f = sp.ndimage.gaussian_filter(f, 3) + +filter_blurred_f = sp.ndimage.gaussian_filter(blurred_f, 1) + +alpha = 30 +sharpened = blurred_f + alpha * (blurred_f - filter_blurred_f) + +plt.figure(figsize=(12, 4)) + +plt.subplot(131) +plt.imshow(f, cmap="gray") +plt.axis("off") +plt.subplot(132) +plt.imshow(blurred_f, cmap="gray") +plt.axis("off") +plt.subplot(133) +plt.imshow(sharpened, cmap="gray") +plt.axis("off") + +plt.tight_layout() +plt.show() diff --git a/_downloads/204ad76afc9af042786c2501de995a98/plot_dash_capstyle.ipynb b/_downloads/204ad76afc9af042786c2501de995a98/plot_dash_capstyle.ipynb new file mode 100644 index 000000000..0534691d0 --- /dev/null +++ b/_downloads/204ad76afc9af042786c2501de995a98/plot_dash_capstyle.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Dash capstyle\n\nAn example demoing the dash capstyle.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nsize = 256, 16\ndpi = 72.0\nfigsize = size[0] / float(dpi), size[1] / float(dpi)\nfig = plt.figure(figsize=figsize, dpi=dpi)\nfig.patch.set_alpha(0)\nplt.axes((0, 0, 1, 1), frameon=False)\n\nplt.plot(\n np.arange(4),\n np.ones(4),\n color=\"blue\",\n dashes=[15, 15],\n linewidth=8,\n dash_capstyle=\"butt\",\n)\n\nplt.plot(\n 5 + np.arange(4),\n np.ones(4),\n color=\"blue\",\n dashes=[15, 15],\n linewidth=8,\n dash_capstyle=\"round\",\n)\n\nplt.plot(\n 10 + np.arange(4),\n np.ones(4),\n color=\"blue\",\n dashes=[15, 15],\n linewidth=8,\n dash_capstyle=\"projecting\",\n)\n\nplt.xlim(0, 14)\nplt.xticks([])\nplt.yticks([])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/20fdfb1503bedc0c8d5e8f9db9c9a98d/plot_exercise_5.py b/_downloads/20fdfb1503bedc0c8d5e8f9db9c9a98d/plot_exercise_5.py new file mode 100644 index 000000000..ed9906da8 --- /dev/null +++ b/_downloads/20fdfb1503bedc0c8d5e8f9db9c9a98d/plot_exercise_5.py @@ -0,0 +1,27 @@ +""" +Exercise 5 +=========== + +Exercise 5 with matplotlib. +""" + +import numpy as np +import matplotlib.pyplot as plt + +plt.figure(figsize=(8, 5), dpi=80) +plt.subplot(111) + +X = np.linspace(-np.pi, np.pi, 256) +S = np.sin(X) +C = np.cos(X) + +plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") +plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") + +plt.xlim(X.min() * 1.1, X.max() * 1.1) +plt.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi]) + +plt.ylim(C.min() * 1.1, C.max() * 1.1) +plt.yticks([-1, 0, +1]) + +plt.show() diff --git a/_downloads/2159eefe66b25292446f3b8c21f133a7/plot_brain_size.py b/_downloads/2159eefe66b25292446f3b8c21f133a7/plot_brain_size.py new file mode 100644 index 000000000..5bb9eb710 --- /dev/null +++ b/_downloads/2159eefe66b25292446f3b8c21f133a7/plot_brain_size.py @@ -0,0 +1,56 @@ +""" +Relating Gender and IQ +======================= + +Going back to the brain size + IQ data, test if the VIQ of male and +female are different after removing the effect of brain size, height and +weight. + +Notice that here 'Gender' is a categorical value. As it is a non-float +data type, statsmodels is able to automatically infer this. + +""" + +import pandas +from statsmodels.formula.api import ols + +data = pandas.read_csv("../brain_size.csv", sep=";", na_values=".") + +model = ols("VIQ ~ Gender + MRI_Count + Height", data).fit() +print(model.summary()) + +# Here, we don't need to define a contrast, as we are testing a single +# coefficient of our model, and not a combination of coefficients. +# However, defining a contrast, which would then be a 'unit contrast', +# will give us the same results +print(model.f_test([0, 1, 0, 0])) + +############################################################################### +# Here we plot a scatter matrix to get intuitions on our results. +# This goes beyond what was asked in the exercise + +# This plotting is useful to get an intuitions on the relationships between +# our different variables + +from pandas import plotting +import matplotlib.pyplot as plt + +# Fill in the missing values for Height for plotting +data["Height"] = data["Height"].ffill() + +# The parameter 'c' is passed to plt.scatter and will control the color +# The same holds for parameters 'marker', 'alpha' and 'cmap', that +# control respectively the type of marker used, their transparency and +# the colormap +plotting.scatter_matrix( + data[["VIQ", "MRI_Count", "Height"]], + c=(data["Gender"] == "Female"), + marker="o", + alpha=1, + cmap="winter", +) + +fig = plt.gcf() +fig.suptitle("blue: male, green: female", size=13) + +plt.show() diff --git a/_downloads/2250da8939d81b5cc457b85593005b83/auto_examples_python.zip b/_downloads/2250da8939d81b5cc457b85593005b83/auto_examples_python.zip new file mode 100644 index 000000000..1133cf3d9 Binary files /dev/null and b/_downloads/2250da8939d81b5cc457b85593005b83/auto_examples_python.zip differ diff --git a/_downloads/22b16052ad6a5682fa38ad35a31b64ac/plot_2d_minimization.zip b/_downloads/22b16052ad6a5682fa38ad35a31b64ac/plot_2d_minimization.zip new file mode 100644 index 000000000..e88ac9b2b Binary files /dev/null and b/_downloads/22b16052ad6a5682fa38ad35a31b64ac/plot_2d_minimization.zip differ diff --git a/_downloads/230bcec9c527480dd85dd9593760f41c/plot_geom_face.py b/_downloads/230bcec9c527480dd85dd9593760f41c/plot_geom_face.py new file mode 100644 index 000000000..e824c4f99 --- /dev/null +++ b/_downloads/230bcec9c527480dd85dd9593760f41c/plot_geom_face.py @@ -0,0 +1,43 @@ +""" +Geometrical transformations +============================== + +This examples demos some simple geometrical transformations on a Raccoon face. +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +face = sp.datasets.face(gray=True) +lx, ly = face.shape +# Cropping +crop_face = face[lx // 4 : -lx // 4, ly // 4 : -ly // 4] +# up <-> down flip +flip_ud_face = np.flipud(face) +# rotation +rotate_face = sp.ndimage.rotate(face, 45) +rotate_face_noreshape = sp.ndimage.rotate(face, 45, reshape=False) + +plt.figure(figsize=(12.5, 2.5)) + + +plt.subplot(151) +plt.imshow(face, cmap="gray") +plt.axis("off") +plt.subplot(152) +plt.imshow(crop_face, cmap="gray") +plt.axis("off") +plt.subplot(153) +plt.imshow(flip_ud_face, cmap="gray") +plt.axis("off") +plt.subplot(154) +plt.imshow(rotate_face, cmap="gray") +plt.axis("off") +plt.subplot(155) +plt.imshow(rotate_face_noreshape, cmap="gray") +plt.axis("off") + +plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) + +plt.show() diff --git a/_downloads/234905c913508d8b5b5850e9937637e3/plot_pie.py b/_downloads/234905c913508d8b5b5850e9937637e3/plot_pie.py new file mode 100644 index 000000000..0eaf8e855 --- /dev/null +++ b/_downloads/234905c913508d8b5b5850e9937637e3/plot_pie.py @@ -0,0 +1,22 @@ +""" +Pie chart +========= + +A simple pie chart example with matplotlib. +""" + +import numpy as np +import matplotlib.pyplot as plt + +n = 20 +Z = np.ones(n) +Z[-1] *= 2 + +plt.axes((0.025, 0.025, 0.95, 0.95)) + +plt.pie(Z, explode=Z * 0.05, colors=[f"{i / float(n):f}" for i in range(n)]) +plt.axis("equal") +plt.xticks([]) +plt.yticks() + +plt.show() diff --git a/_downloads/2369522dd52a62e67e192e1bc840c3d5/plot_alpha.py b/_downloads/2369522dd52a62e67e192e1bc840c3d5/plot_alpha.py new file mode 100644 index 000000000..9b036555a --- /dev/null +++ b/_downloads/2369522dd52a62e67e192e1bc840c3d5/plot_alpha.py @@ -0,0 +1,23 @@ +""" +Alpha: transparency +=================== + +This example demonstrates using alpha for transparency. +""" + +import matplotlib.pyplot as plt + +size = 256, 16 +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = plt.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +plt.axes((0, 0.1, 1, 0.8), frameon=False) + +for i in range(1, 11): + plt.axvline(i, linewidth=1, color="blue", alpha=0.25 + 0.75 * i / 10.0) + +plt.xlim(0, 11) +plt.xticks([]) +plt.yticks([]) +plt.show() diff --git a/_downloads/237272041bcf59588c48337f0a890a47/plot_pie.ipynb b/_downloads/237272041bcf59588c48337f0a890a47/plot_pie.ipynb new file mode 100644 index 000000000..8eb2310c9 --- /dev/null +++ b/_downloads/237272041bcf59588c48337f0a890a47/plot_pie.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Pie chart\n\nA simple pie chart example with matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nn = 20\nZ = np.ones(n)\nZ[-1] *= 2\n\nplt.axes((0.025, 0.025, 0.95, 0.95))\n\nplt.pie(Z, explode=Z * 0.05, colors=[f\"{i / float(n):f}\" for i in range(n)])\nplt.axis(\"equal\")\nplt.xticks([])\nplt.yticks()\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/2424166ecb3a1dfffafbdb71dd0bc9d3/plot_radial_mean.ipynb b/_downloads/2424166ecb3a1dfffafbdb71dd0bc9d3/plot_radial_mean.ipynb new file mode 100644 index 000000000..8e0bade33 --- /dev/null +++ b/_downloads/2424166ecb3a1dfffafbdb71dd0bc9d3/plot_radial_mean.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Radial mean\n\nThis example shows how to do a radial mean with scikit-image.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nf = sp.datasets.face(gray=True)\nsx, sy = f.shape\nX, Y = np.ogrid[0:sx, 0:sy]\n\n\nr = np.hypot(X - sx / 2, Y - sy / 2)\n\nrbin = (20 * r / r.max()).astype(int)\nradial_mean = sp.ndimage.mean(f, labels=rbin, index=np.arange(1, rbin.max() + 1))\n\nplt.figure(figsize=(5, 5))\nplt.axes((0, 0, 1, 1))\nplt.imshow(rbin, cmap=\"nipy_spectral\")\nplt.axis(\"off\")\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/2424cfdf3787c4e1d0b741e4629c9511/plot_gumbell_wind_speed_prediction.zip b/_downloads/2424cfdf3787c4e1d0b741e4629c9511/plot_gumbell_wind_speed_prediction.zip new file mode 100644 index 000000000..800801806 Binary files /dev/null and b/_downloads/2424cfdf3787c4e1d0b741e4629c9511/plot_gumbell_wind_speed_prediction.zip differ diff --git a/_downloads/245498e08d81567a68e7e806b1ea1efe/plot_polynomial_regression.py b/_downloads/245498e08d81567a68e7e806b1ea1efe/plot_polynomial_regression.py new file mode 100644 index 000000000..a2037771d --- /dev/null +++ b/_downloads/245498e08d81567a68e7e806b1ea1efe/plot_polynomial_regression.py @@ -0,0 +1,65 @@ +""" +Plot fitting a 9th order polynomial +==================================== + +Fits data generated from a 9th order polynomial with model of 4th order +and 9th order polynomials, to demonstrate that often simpler models are +to be preferred +""" + +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.colors import ListedColormap + +from sklearn import linear_model + +# Create color maps for 3-class classification problem, as with iris +cmap_light = ListedColormap(["#FFAAAA", "#AAFFAA", "#AAAAFF"]) +cmap_bold = ListedColormap(["#FF0000", "#00FF00", "#0000FF"]) + + +rng = np.random.default_rng(27446968) +x = 2 * rng.random(100) - 1 + +f = lambda t: 1.2 * t**2 + 0.1 * t**3 - 0.4 * t**5 - 0.5 * t**9 +y = f(x) + 0.4 * rng.normal(size=100) + +x_test = np.linspace(-1, 1, 100) + +########################################################################### +# The data +plt.figure(figsize=(6, 4)) +plt.scatter(x, y, s=4) + +########################################################################### +# Fitting 4th and 9th order polynomials +# +# For this we need to engineer features: the n_th powers of x: +plt.figure(figsize=(6, 4)) +plt.scatter(x, y, s=4) + +X = np.array([x**i for i in range(5)]).T +X_test = np.array([x_test**i for i in range(5)]).T +regr = linear_model.LinearRegression() +regr.fit(X, y) +plt.plot(x_test, regr.predict(X_test), label="4th order") + +X = np.array([x**i for i in range(10)]).T +X_test = np.array([x_test**i for i in range(10)]).T +regr = linear_model.LinearRegression() +regr.fit(X, y) +plt.plot(x_test, regr.predict(X_test), label="9th order") + +plt.legend(loc="best") +plt.axis("tight") +plt.title("Fitting a 4th and a 9th order polynomial") + +########################################################################### +# Ground truth +plt.figure(figsize=(6, 4)) +plt.scatter(x, y, s=4) +plt.plot(x_test, f(x_test), label="truth") +plt.axis("tight") +plt.title("Ground truth (9th order polynomial)") + +plt.show() diff --git a/_downloads/24ac082e6648dacb671a084d19553182/plot_watershed_segmentation.py b/_downloads/24ac082e6648dacb671a084d19553182/plot_watershed_segmentation.py new file mode 100644 index 000000000..a08e111d6 --- /dev/null +++ b/_downloads/24ac082e6648dacb671a084d19553182/plot_watershed_segmentation.py @@ -0,0 +1,43 @@ +""" +Watershed segmentation +======================= + +This example shows how to do segmentation with watershed. +""" + +import numpy as np +from skimage.segmentation import watershed +from skimage.feature import peak_local_max +import matplotlib.pyplot as plt +import scipy as sp + +# Generate an initial image with two overlapping circles +x, y = np.indices((80, 80)) +x1, y1, x2, y2 = 28, 28, 44, 52 +r1, r2 = 16, 20 +mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1**2 +mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2**2 +image = np.logical_or(mask_circle1, mask_circle2) +# Now we want to separate the two objects in image +# Generate the markers as local maxima of the distance +# to the background +distance = sp.ndimage.distance_transform_edt(image) +peak_idx = peak_local_max(distance, footprint=np.ones((3, 3)), labels=image) +peak_mask = np.zeros_like(distance, dtype=bool) +peak_mask[tuple(peak_idx.T)] = True +markers = sp.ndimage.label(peak_mask)[0] +labels = watershed(-distance, markers, mask=image) + +plt.figure(figsize=(9, 3.5)) +plt.subplot(131) +plt.imshow(image, cmap="gray", interpolation="nearest") +plt.axis("off") +plt.subplot(132) +plt.imshow(-distance, interpolation="nearest") +plt.axis("off") +plt.subplot(133) +plt.imshow(labels, cmap="nipy_spectral", interpolation="nearest") +plt.axis("off") + +plt.subplots_adjust(hspace=0.01, wspace=0.01, top=1, bottom=0, left=0, right=1) +plt.show() diff --git a/_downloads/25065e200671e40d5a9c49ef6d525092/plot_bad.ipynb b/_downloads/25065e200671e40d5a9c49ef6d525092/plot_bad.ipynb new file mode 100644 index 000000000..7fa72b4ae --- /dev/null +++ b/_downloads/25065e200671e40d5a9c49ef6d525092/plot_bad.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# A simple plotting example\n\nA plotting example with a few simple tweaks\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib\n\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\n\nfig = plt.figure(figsize=(5, 4), dpi=72)\naxes = fig.add_axes((0.01, 0.01, 0.98, 0.98))\nx = np.linspace(0, 2, 200)\ny = np.sin(2 * np.pi * x)\nplt.plot(x, y, lw=0.25, c=\"k\")\nplt.xticks(np.arange(0.0, 2.0, 0.1))\nplt.yticks(np.arange(-1.0, 1.0, 0.1))\nplt.grid()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/25120676740232afe1b432a2a75acfed/plot_image_filters.zip b/_downloads/25120676740232afe1b432a2a75acfed/plot_image_filters.zip new file mode 100644 index 000000000..c4bf5e730 Binary files /dev/null and b/_downloads/25120676740232afe1b432a2a75acfed/plot_image_filters.zip differ diff --git a/_downloads/252760027ef2109cf9ab434889ad53aa/plot_variance_linear_regr.py b/_downloads/252760027ef2109cf9ab434889ad53aa/plot_variance_linear_regr.py new file mode 100644 index 000000000..4fdf0fc0e --- /dev/null +++ b/_downloads/252760027ef2109cf9ab434889ad53aa/plot_variance_linear_regr.py @@ -0,0 +1,58 @@ +""" +================================================== +Plot variance and regularization in linear models +================================================== + + +""" + +import numpy as np + +# Smaller figures +import matplotlib.pyplot as plt + +plt.rcParams["figure.figsize"] = (3, 2) + +############################################################ +# We consider the situation where we have only 2 data point +X = np.c_[0.5, 1].T +y = [0.5, 1] +X_test = np.c_[0, 2].T + +############################################################ +# Without noise, as linear regression fits the data perfectly +from sklearn import linear_model + +regr = linear_model.LinearRegression() +regr.fit(X, y) +plt.plot(X, y, "o") +plt.plot(X_test, regr.predict(X_test)) + +############################################################ +# In real life situation, we have noise (e.g. measurement noise) in our data: +rng = np.random.default_rng(27446968) +for _ in range(6): + noisy_X = X + np.random.normal(loc=0, scale=0.1, size=X.shape) + plt.plot(noisy_X, y, "o") + regr.fit(noisy_X, y) + plt.plot(X_test, regr.predict(X_test)) + +############################################################ +# As we can see, our linear model captures and amplifies the noise in the +# data. It displays a lot of variance. +# +# We can use another linear estimator that uses regularization, the +# :class:`~sklearn.linear_model.Ridge` estimator. This estimator +# regularizes the coefficients by shrinking them to zero, under the +# assumption that very high correlations are often spurious. The alpha +# parameter controls the amount of shrinkage used. + +regr = linear_model.Ridge(alpha=0.1) +np.random.seed(0) +for _ in range(6): + noisy_X = X + np.random.normal(loc=0, scale=0.1, size=X.shape) + plt.plot(noisy_X, y, "o") + regr.fit(noisy_X, y) + plt.plot(X_test, regr.predict(X_test)) + +plt.show() diff --git a/_downloads/2565d072d7006382203c4173427134cb/plot_fft_image_denoise.ipynb b/_downloads/2565d072d7006382203c4173427134cb/plot_fft_image_denoise.ipynb new file mode 100644 index 000000000..9d9e2d642 --- /dev/null +++ b/_downloads/2565d072d7006382203c4173427134cb/plot_fft_image_denoise.ipynb @@ -0,0 +1,122 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Image denoising by FFT\n\nDenoise an image (:download:`../../../../data/moonlanding.png`) by\nimplementing a blur with an FFT.\n\nImplements, via FFT, the following convolution:\n\n\\begin{align}f_1(t) = \\int dt'\\, K(t-t') f_0(t')\\end{align}\n\n\\begin{align}\\tilde{f}_1(\\omega) = \\tilde{K}(\\omega) \\tilde{f}_0(\\omega)\\end{align}\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Read and plot the image\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nim = plt.imread(\"../../../../data/moonlanding.png\").astype(float)\n\nplt.figure()\nplt.imshow(im, \"gray\")\nplt.title(\"Original image\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Compute the 2d FFT of the input image\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import scipy as sp\n\nim_fft = sp.fft.fft2(im)\n\n# Show the results\n\n\ndef plot_spectrum(im_fft):\n from matplotlib.colors import LogNorm\n\n # A logarithmic colormap\n plt.imshow(np.abs(im_fft), norm=LogNorm(vmin=5))\n plt.colorbar()\n\n\nplt.figure()\nplot_spectrum(im_fft)\nplt.title(\"Fourier transform\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Filter in FFT\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# In the lines following, we'll make a copy of the original spectrum and\n# truncate coefficients.\n\n# Define the fraction of coefficients (in each direction) we keep\nkeep_fraction = 0.1\n\n# Call ff a copy of the original transform. NumPy arrays have a copy\n# method for this purpose.\nim_fft2 = im_fft.copy()\n\n# Set r and c to be the number of rows and columns of the array.\nr, c = im_fft2.shape\n\n# Set to zero all rows with indices between r*keep_fraction and\n# r*(1-keep_fraction):\nim_fft2[int(r * keep_fraction) : int(r * (1 - keep_fraction))] = 0\n\n# Similarly with the columns:\nim_fft2[:, int(c * keep_fraction) : int(c * (1 - keep_fraction))] = 0\n\nplt.figure()\nplot_spectrum(im_fft2)\nplt.title(\"Filtered Spectrum\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Reconstruct the final image\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Reconstruct the denoised image from the filtered spectrum, keep only the\n# real part for display.\nim_new = sp.fft.ifft2(im_fft2).real\n\nplt.figure()\nplt.imshow(im_new, \"gray\")\nplt.title(\"Reconstructed Image\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Easier and better: :func:`scipy.ndimage.gaussian_filter`\n\n Implementing filtering directly with FFTs is tricky and time consuming.\n We can use the Gaussian filter from :mod:`scipy.ndimage`\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "im_blur = sp.ndimage.gaussian_filter(im, 4)\n\nplt.figure()\nplt.imshow(im_blur, \"gray\")\nplt.title(\"Blurred image\")\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/25925c75fbd50ddc998e0e56a8ddef4e/plot_subplot-vertical.py b/_downloads/25925c75fbd50ddc998e0e56a8ddef4e/plot_subplot-vertical.py new file mode 100644 index 000000000..4f93f4e97 --- /dev/null +++ b/_downloads/25925c75fbd50ddc998e0e56a8ddef4e/plot_subplot-vertical.py @@ -0,0 +1,23 @@ +""" +Subplot plot arrangement vertical +================================== + +An example showing vertical arrangement of subplots with matplotlib. +""" + +import matplotlib.pyplot as plt + + +plt.figure(figsize=(6, 4)) +plt.subplot(1, 2, 1) +plt.xticks([]) +plt.yticks([]) +plt.text(0.5, 0.5, "subplot(1,2,1)", ha="center", va="center", size=24, alpha=0.5) + +plt.subplot(1, 2, 2) +plt.xticks([]) +plt.yticks([]) +plt.text(0.5, 0.5, "subplot(1,2,2)", ha="center", va="center", size=24, alpha=0.5) + +plt.tight_layout() +plt.show() diff --git a/_downloads/25b4ba8d2913f444a091b98df1be7f4c/plot_iris_knn.py b/_downloads/25b4ba8d2913f444a091b98df1be7f4c/plot_iris_knn.py new file mode 100644 index 000000000..ea52c92ac --- /dev/null +++ b/_downloads/25b4ba8d2913f444a091b98df1be7f4c/plot_iris_knn.py @@ -0,0 +1,63 @@ +""" +Nearest-neighbor prediction on iris +==================================== + +Plot the decision boundary of nearest neighbor decision on iris, first +with a single nearest neighbor, and then using 3 nearest neighbors. +""" + +import numpy as np +import matplotlib.pyplot as plt +from sklearn import neighbors, datasets +from matplotlib.colors import ListedColormap + +# Create color maps for 3-class classification problem, as with iris +cmap_light = ListedColormap(["#FFAAAA", "#AAFFAA", "#AAAAFF"]) +cmap_bold = ListedColormap(["#FF0000", "#00FF00", "#0000FF"]) + +iris = datasets.load_iris() +X = iris.data[:, :2] # we only take the first two features. We could +# avoid this ugly slicing by using a two-dim dataset +y = iris.target + +knn = neighbors.KNeighborsClassifier(n_neighbors=1) +knn.fit(X, y) + +x_min, x_max = X[:, 0].min() - 0.1, X[:, 0].max() + 0.1 +y_min, y_max = X[:, 1].min() - 0.1, X[:, 1].max() + 0.1 +xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100), np.linspace(y_min, y_max, 100)) +Z = knn.predict(np.c_[xx.ravel(), yy.ravel()]) + + +############################################################################### +# Put the result into a color plot +Z = Z.reshape(xx.shape) +plt.figure() +plt.pcolormesh(xx, yy, Z, cmap=cmap_light) + +# Plot also the training points +plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold) +plt.xlabel("sepal length (cm)") +plt.ylabel("sepal width (cm)") +plt.axis("tight") + + +############################################################################### +# And now, redo the analysis with 3 neighbors +knn = neighbors.KNeighborsClassifier(n_neighbors=3) +knn.fit(X, y) + +Z = knn.predict(np.c_[xx.ravel(), yy.ravel()]) + +# Put the result into a color plot +Z = Z.reshape(xx.shape) +plt.figure() +plt.pcolormesh(xx, yy, Z, cmap=cmap_light) + +# Plot also the training points +plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold) +plt.xlabel("sepal length (cm)") +plt.ylabel("sepal width (cm)") +plt.axis("tight") + +plt.show() diff --git a/_downloads/2637bda9fcacd5431901db16441851ef/plot_image_blur.py b/_downloads/2637bda9fcacd5431901db16441851ef/plot_image_blur.py new file mode 100644 index 000000000..19b1d594a --- /dev/null +++ b/_downloads/2637bda9fcacd5431901db16441851ef/plot_image_blur.py @@ -0,0 +1,89 @@ +""" +======================================================= +Simple image blur by convolution with a Gaussian kernel +======================================================= + +Blur an an image (:download:`../../../../data/elephant.png`) using a +Gaussian kernel. + +Convolution is easy to perform with FFT: convolving two signals boils +down to multiplying their FFTs (and performing an inverse FFT). + +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +##################################################################### +# The original image +##################################################################### + +# read image +img = plt.imread("../../../../data/elephant.png") +plt.figure() +plt.imshow(img) + +##################################################################### +# Prepare an Gaussian convolution kernel +##################################################################### + +# First a 1-D Gaussian +t = np.linspace(-10, 10, 30) +bump = np.exp(-0.1 * t**2) +bump /= np.trapezoid(bump) # normalize the integral to 1 + +# make a 2-D kernel out of it +kernel = bump[:, np.newaxis] * bump[np.newaxis, :] + +##################################################################### +# Implement convolution via FFT +##################################################################### + +# Padded fourier transform, with the same shape as the image +# We use :func:`scipy.fft.fft2` to have a 2D FFT +kernel_ft = sp.fft.fft2(kernel, s=img.shape[:2], axes=(0, 1)) + +# convolve +img_ft = sp.fft.fft2(img, axes=(0, 1)) +# the 'newaxis' is to match to color direction +img2_ft = kernel_ft[:, :, np.newaxis] * img_ft +img2 = sp.fft.ifft2(img2_ft, axes=(0, 1)).real + +# clip values to range +img2 = np.clip(img2, 0, 1) + +# plot output +plt.figure() +plt.imshow(img2) + +##################################################################### +# Further exercise (only if you are familiar with this stuff): +# +# A "wrapped border" appears in the upper left and top edges of the +# image. This is because the padding is not done correctly, and does +# not take the kernel size into account (so the convolution "flows out +# of bounds of the image"). Try to remove this artifact. + + +##################################################################### +# A function to do it: :func:`scipy.signal.fftconvolve` +##################################################################### +# +# The above exercise was only for didactic reasons: there exists a +# function in scipy that will do this for us, and probably do a better +# job: :func:`scipy.signal.fftconvolve` + +# mode='same' is there to enforce the same output shape as input arrays +# (ie avoid border effects) +img3 = sp.signal.fftconvolve(img, kernel[:, :, np.newaxis], mode="same") +plt.figure() +plt.imshow(img3) + +##################################################################### +# Note that we still have a decay to zero at the border of the image. +# Using :func:`scipy.ndimage.gaussian_filter` would get rid of this +# artifact + + +plt.show() diff --git a/_downloads/26670769d8d2d4d38b24a5a66e5db9e9/plot_randomwalk.zip b/_downloads/26670769d8d2d4d38b24a5a66e5db9e9/plot_randomwalk.zip new file mode 100644 index 000000000..f2a71ff4e Binary files /dev/null and b/_downloads/26670769d8d2d4d38b24a5a66e5db9e9/plot_randomwalk.zip differ diff --git a/_downloads/26b03df0c9978e44a2d50b3bd93f0a80/plot_bar_ext.zip b/_downloads/26b03df0c9978e44a2d50b3bd93f0a80/plot_bar_ext.zip new file mode 100644 index 000000000..b09940095 Binary files /dev/null and b/_downloads/26b03df0c9978e44a2d50b3bd93f0a80/plot_bar_ext.zip differ diff --git a/_downloads/2701a819a85e01fb665602c51c9a4622/plot_image_blur.ipynb b/_downloads/2701a819a85e01fb665602c51c9a4622/plot_image_blur.ipynb new file mode 100644 index 000000000..00de044c8 --- /dev/null +++ b/_downloads/2701a819a85e01fb665602c51c9a4622/plot_image_blur.ipynb @@ -0,0 +1,140 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Simple image blur by convolution with a Gaussian kernel\n\nBlur an an image (:download:`../../../../data/elephant.png`) using a\nGaussian kernel.\n\nConvolution is easy to perform with FFT: convolving two signals boils\ndown to multiplying their FFTs (and performing an inverse FFT).\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The original image\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# read image\nimg = plt.imread(\"../../../../data/elephant.png\")\nplt.figure()\nplt.imshow(img)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Prepare an Gaussian convolution kernel\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# First a 1-D Gaussian\nt = np.linspace(-10, 10, 30)\nbump = np.exp(-0.1 * t**2)\nbump /= np.trapezoid(bump) # normalize the integral to 1\n\n# make a 2-D kernel out of it\nkernel = bump[:, np.newaxis] * bump[np.newaxis, :]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Implement convolution via FFT\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Padded fourier transform, with the same shape as the image\n# We use :func:`scipy.fft.fft2` to have a 2D FFT\nkernel_ft = sp.fft.fft2(kernel, s=img.shape[:2], axes=(0, 1))\n\n# convolve\nimg_ft = sp.fft.fft2(img, axes=(0, 1))\n# the 'newaxis' is to match to color direction\nimg2_ft = kernel_ft[:, :, np.newaxis] * img_ft\nimg2 = sp.fft.ifft2(img2_ft, axes=(0, 1)).real\n\n# clip values to range\nimg2 = np.clip(img2, 0, 1)\n\n# plot output\nplt.figure()\nplt.imshow(img2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Further exercise (only if you are familiar with this stuff):\n\nA \"wrapped border\" appears in the upper left and top edges of the\nimage. This is because the padding is not done correctly, and does\nnot take the kernel size into account (so the convolution \"flows out\nof bounds of the image\"). Try to remove this artifact.\n\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## A function to do it: :func:`scipy.signal.fftconvolve`\n\n The above exercise was only for didactic reasons: there exists a\n function in scipy that will do this for us, and probably do a better\n job: :func:`scipy.signal.fftconvolve`\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# mode='same' is there to enforce the same output shape as input arrays\n# (ie avoid border effects)\nimg3 = sp.signal.fftconvolve(img, kernel[:, :, np.newaxis], mode=\"same\")\nplt.figure()\nplt.imshow(img3)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that we still have a decay to zero at the border of the image.\nUsing :func:`scipy.ndimage.gaussian_filter` would get rid of this\nartifact\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "plt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/2745a082d699b168200b233e6bc7df1d/plot_contour_ext.zip b/_downloads/2745a082d699b168200b233e6bc7df1d/plot_contour_ext.zip new file mode 100644 index 000000000..8261eaa80 Binary files /dev/null and b/_downloads/2745a082d699b168200b233e6bc7df1d/plot_contour_ext.zip differ diff --git a/_downloads/2762b9f4287d3ad7bd71c18bc397ed65/plot_solve_ivp_damped_spring_mass.py b/_downloads/2762b9f4287d3ad7bd71c18bc397ed65/plot_solve_ivp_damped_spring_mass.py new file mode 100644 index 000000000..b3bb0af8a --- /dev/null +++ b/_downloads/2762b9f4287d3ad7bd71c18bc397ed65/plot_solve_ivp_damped_spring_mass.py @@ -0,0 +1,36 @@ +""" +============================================ +Integrate the Damped spring-mass oscillator +============================================ + + +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +m = 0.5 # kg +k = 4 # N/m +c = 0.4 # N s/m + +zeta = c / (2 * m * np.sqrt(k / m)) +omega = np.sqrt(k / m) + + +def f(t, z, zeta, omega): + return (z[1], -zeta * omega * z[1] - omega**2 * z[0]) + + +t_span = (0, 10) +t_eval = np.linspace(*t_span, 100) +z0 = [1, 0] +res = sp.integrate.solve_ivp( + f, t_span, z0, t_eval=t_eval, args=(zeta, omega), method="LSODA" +) + +plt.figure(figsize=(4, 3)) +plt.plot(res.t, res.y[0], label="y") +plt.plot(res.t, res.y[1], label="dy/dt") +plt.legend(loc="best") +plt.show() diff --git a/_downloads/276a006f6b4865035c913a53521bf965/plot_digits_simple_classif.ipynb b/_downloads/276a006f6b4865035c913a53521bf965/plot_digits_simple_classif.ipynb new file mode 100644 index 000000000..1133ab5d1 --- /dev/null +++ b/_downloads/276a006f6b4865035c913a53521bf965/plot_digits_simple_classif.ipynb @@ -0,0 +1,187 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Simple visualization and classification of the digits dataset\n\nPlot the first few samples of the digits dataset and a 2D representation\nbuilt using PCA, then do a simple classification\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.datasets import load_digits\n\ndigits = load_digits()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Plot the data: images of digits\n\nEach data in a 8x8 image\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nfig = plt.figure(figsize=(6, 6)) # figure size in inches\nfig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)\n\nfor i in range(64):\n ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[])\n ax.imshow(digits.images[i], cmap=\"binary\", interpolation=\"nearest\")\n # label the image with the target value\n ax.text(0, 7, str(digits.target[i]))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Plot a projection on the 2 first principal axis\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "plt.figure()\n\nfrom sklearn.decomposition import PCA\n\npca = PCA(n_components=2)\nproj = pca.fit_transform(digits.data)\nplt.scatter(proj[:, 0], proj[:, 1], c=digits.target, cmap=\"Paired\")\nplt.colorbar()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Classify with Gaussian naive Bayes\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.naive_bayes import GaussianNB\nfrom sklearn.model_selection import train_test_split\n\n# split the data into training and validation sets\nX_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target)\n\n# train the model\nclf = GaussianNB()\nclf.fit(X_train, y_train)\n\n# use the model to predict the labels of the test data\npredicted = clf.predict(X_test)\nexpected = y_test\n\n# Plot the prediction\nfig = plt.figure(figsize=(6, 6)) # figure size in inches\nfig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)\n\n# plot the digits: each image is 8x8 pixels\nfor i in range(64):\n ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[])\n ax.imshow(X_test.reshape(-1, 8, 8)[i], cmap=\"binary\", interpolation=\"nearest\")\n\n # label the image with the target value\n if predicted[i] == expected[i]:\n ax.text(0, 7, str(predicted[i]), color=\"green\")\n else:\n ax.text(0, 7, str(predicted[i]), color=\"red\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Quantify the performance\n\nFirst print the number of correct matches\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "matches = predicted == expected\nprint(matches.sum())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The total number of data points\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "print(len(matches))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "And now, the ration of correct predictions\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "matches.sum() / float(len(matches))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Print the classification report\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn import metrics\n\nprint(metrics.classification_report(expected, predicted))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Print the confusion matrix\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "print(metrics.confusion_matrix(expected, predicted))\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/2892c871cc184099ee9d08189870b79a/auto_examples_python.zip b/_downloads/2892c871cc184099ee9d08189870b79a/auto_examples_python.zip new file mode 100644 index 000000000..6c5129fd9 Binary files /dev/null and b/_downloads/2892c871cc184099ee9d08189870b79a/auto_examples_python.zip differ diff --git a/_downloads/28dfd37c551ccc0dc82d08c51d193f85/plot_radial_mean.py b/_downloads/28dfd37c551ccc0dc82d08c51d193f85/plot_radial_mean.py new file mode 100644 index 000000000..6f8373d44 --- /dev/null +++ b/_downloads/28dfd37c551ccc0dc82d08c51d193f85/plot_radial_mean.py @@ -0,0 +1,27 @@ +""" +Radial mean +============ + +This example shows how to do a radial mean with scikit-image. +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +f = sp.datasets.face(gray=True) +sx, sy = f.shape +X, Y = np.ogrid[0:sx, 0:sy] + + +r = np.hypot(X - sx / 2, Y - sy / 2) + +rbin = (20 * r / r.max()).astype(int) +radial_mean = sp.ndimage.mean(f, labels=rbin, index=np.arange(1, rbin.max() + 1)) + +plt.figure(figsize=(5, 5)) +plt.axes((0, 0, 1, 1)) +plt.imshow(rbin, cmap="nipy_spectral") +plt.axis("off") + +plt.show() diff --git a/_downloads/29870544214783178e96d2ed922c8a68/plot_boxplot_ext.ipynb b/_downloads/29870544214783178e96d2ed922c8a68/plot_boxplot_ext.ipynb new file mode 100644 index 000000000..5c43e24b4 --- /dev/null +++ b/_downloads/29870544214783178e96d2ed922c8a68/plot_boxplot_ext.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Boxplot with matplotlib\n\nAn example of doing box plots with matplotlib\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\n\nfig = plt.figure(figsize=(8, 5))\naxes = plt.subplot(111)\n\nn = 5\nZ = np.zeros((n, 4))\nX = np.linspace(0, 2, n)\nrng = np.random.default_rng()\nY = rng.random((n, 4))\nplt.boxplot(Y)\n\nplt.xticks([])\nplt.yticks([])\n\n\n# Add a title and a box around it\nfrom matplotlib.patches import FancyBboxPatch\n\nax = plt.gca()\nax.add_patch(\n FancyBboxPatch(\n (-0.05, 0.87),\n width=0.66,\n height=0.165,\n clip_on=False,\n boxstyle=\"square,pad=0\",\n zorder=3,\n facecolor=\"white\",\n alpha=1.0,\n transform=plt.gca().transAxes,\n )\n)\n\nplt.text(\n -0.05,\n 1.02,\n \" Box Plot: plt.boxplot(...)\\n \",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"xx-large\",\n transform=axes.transAxes,\n)\n\nplt.text(\n -0.04,\n 0.98,\n \"\\n Make a box and whisker plot \",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"large\",\n transform=axes.transAxes,\n)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/29c9985120914140e08bf6709a482327/plot_linear_model_cv.ipynb b/_downloads/29c9985120914140e08bf6709a482327/plot_linear_model_cv.ipynb new file mode 100644 index 000000000..35cbf014d --- /dev/null +++ b/_downloads/29c9985120914140e08bf6709a482327/plot_linear_model_cv.ipynb @@ -0,0 +1,86 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Use the RidgeCV and LassoCV to set the regularization parameter\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Load the diabetes dataset\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.datasets import load_diabetes\n\ndata = load_diabetes()\nX, y = data.data, data.target\nprint(X.shape)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Compute the cross-validation score with the default hyper-parameters\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.model_selection import cross_val_score\nfrom sklearn.linear_model import Ridge, Lasso\n\nfor Model in [Ridge, Lasso]:\n model = Model()\n print(f\"{Model.__name__}: {cross_val_score(model, X, y).mean()}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We compute the cross-validation score as a function of alpha, the\nstrength of the regularization for Lasso and Ridge\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nalphas = np.logspace(-3, -1, 30)\n\nplt.figure(figsize=(5, 3))\n\nfor Model in [Lasso, Ridge]:\n scores = [cross_val_score(Model(alpha), X, y, cv=3).mean() for alpha in alphas]\n plt.plot(alphas, scores, label=Model.__name__)\n\nplt.legend(loc=\"lower left\")\nplt.xlabel(\"alpha\")\nplt.ylabel(\"cross validation score\")\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/2a1848a2ee8d216becf324545d8f3f43/plot_solve_ivp_simple.py b/_downloads/2a1848a2ee8d216becf324545d8f3f43/plot_solve_ivp_simple.py new file mode 100644 index 000000000..b30f17cd2 --- /dev/null +++ b/_downloads/2a1848a2ee8d216becf324545d8f3f43/plot_solve_ivp_simple.py @@ -0,0 +1,32 @@ +""" +========================= +Integrating a simple ODE +========================= + +Solve the ODE dy/dt = -2y between t = 0..4, with the initial condition +y(t=0) = 1. +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + + +def f(t, y): + return -2 * y + + +t_span = (0, 4) # time interval +t_eval = np.linspace(*t_span) # times at which to evaluate `y` +y0 = [ + 1, +] # initial state +res = sp.integrate.solve_ivp(f, t_span=t_span, y0=y0, t_eval=t_eval) + +plt.figure(figsize=(4, 3)) +plt.plot(res.t, res.y[0]) +plt.xlabel("t") +plt.ylabel("y") +plt.title("Solution of Initial Value Problem") +plt.tight_layout() +plt.show() diff --git a/_downloads/2a35f9c2415a49b277e5e5aeda5f65fe/plot_linear_regression.ipynb b/_downloads/2a35f9c2415a49b277e5e5aeda5f65fe/plot_linear_regression.ipynb new file mode 100644 index 000000000..f58430c5c --- /dev/null +++ b/_downloads/2a35f9c2415a49b277e5e5aeda5f65fe/plot_linear_regression.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# A simple linear regression\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\n\n# x from 0 to 30\nrng = np.random.default_rng()\nx = 30 * rng.random((20, 1))\n\n# y = a*x + b with noise\ny = 0.5 * x + 1.0 + rng.normal(size=x.shape)\n\n# create a linear regression model\nmodel = LinearRegression()\nmodel.fit(x, y)\n\n# predict y from the data\nx_new = np.linspace(0, 30, 100)\ny_new = model.predict(x_new[:, np.newaxis])\n\n# plot the results\nplt.figure(figsize=(4, 3))\nax = plt.axes()\nax.scatter(x, y)\nax.plot(x_new, y_new)\n\nax.set_xlabel(\"x\")\nax.set_ylabel(\"y\")\n\nax.axis(\"tight\")\n\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/2b65282c2aaaed0906526174da54de98/plot_axes-2.ipynb b/_downloads/2b65282c2aaaed0906526174da54de98/plot_axes-2.ipynb new file mode 100644 index 000000000..3e35994f3 --- /dev/null +++ b/_downloads/2b65282c2aaaed0906526174da54de98/plot_axes-2.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Axes\n\nThis example shows various axes command to position matplotlib axes.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nplt.axes((0.1, 0.1, 0.5, 0.5))\nplt.xticks([])\nplt.yticks([])\nplt.text(\n 0.1, 0.1, \"axes((0.1, 0.1, 0.5, 0.5))\", ha=\"left\", va=\"center\", size=16, alpha=0.5\n)\n\nplt.axes((0.2, 0.2, 0.5, 0.5))\nplt.xticks([])\nplt.yticks([])\nplt.text(\n 0.1, 0.1, \"axes((0.2, 0.2, 0.5, 0.5))\", ha=\"left\", va=\"center\", size=16, alpha=0.5\n)\n\nplt.axes((0.3, 0.3, 0.5, 0.5))\nplt.xticks([])\nplt.yticks([])\nplt.text(\n 0.1, 0.1, \"axes((0.3, 0.3, 0.5, 0.5))\", ha=\"left\", va=\"center\", size=16, alpha=0.5\n)\n\nplt.axes((0.4, 0.4, 0.5, 0.5))\nplt.xticks([])\nplt.yticks([])\nplt.text(\n 0.1, 0.1, \"axes((0.4, 0.4, 0.5, 0.5))\", ha=\"left\", va=\"center\", size=16, alpha=0.5\n)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/2bb68d77c9a8208eb2f4f185069b9e11/plot_numpy_array.zip b/_downloads/2bb68d77c9a8208eb2f4f185069b9e11/plot_numpy_array.zip new file mode 100644 index 000000000..f5f0ee7a4 Binary files /dev/null and b/_downloads/2bb68d77c9a8208eb2f4f185069b9e11/plot_numpy_array.zip differ diff --git a/_downloads/2c11f7b267b85632fa7e7b5ef8244712/plot_curvefit_temperature_data.ipynb b/_downloads/2c11f7b267b85632fa7e7b5ef8244712/plot_curvefit_temperature_data.ipynb new file mode 100644 index 000000000..a6270977d --- /dev/null +++ b/_downloads/2c11f7b267b85632fa7e7b5ef8244712/plot_curvefit_temperature_data.ipynb @@ -0,0 +1,86 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Curve fitting: temperature as a function of month of the year\n\nWe have the min and max temperatures in Alaska for each months of the\nyear. We would like to find a function to describe this yearly evolution.\n\nFor this, we will fit a periodic function.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The data\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n\ntemp_max = np.array([17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18])\ntemp_min = np.array([-62, -59, -56, -46, -32, -18, -9, -13, -25, -46, -52, -58])\n\nimport matplotlib.pyplot as plt\n\nmonths = np.arange(12)\nplt.plot(months, temp_max, \"ro\")\nplt.plot(months, temp_min, \"bo\")\nplt.xlabel(\"Month\")\nplt.ylabel(\"Min and max temperature\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Fitting it to a periodic function\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import scipy as sp\n\n\ndef yearly_temps(times, avg, ampl, time_offset):\n return avg + ampl * np.cos((times + time_offset) * 2 * np.pi / times.max())\n\n\nres_max, cov_max = sp.optimize.curve_fit(yearly_temps, months, temp_max, [20, 10, 0])\nres_min, cov_min = sp.optimize.curve_fit(yearly_temps, months, temp_min, [-40, 20, 0])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Plotting the fit\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "days = np.linspace(0, 12, num=365)\n\nplt.figure()\nplt.plot(months, temp_max, \"ro\")\nplt.plot(days, yearly_temps(days, *res_max), \"r-\")\nplt.plot(months, temp_min, \"bo\")\nplt.plot(days, yearly_temps(days, *res_min), \"b-\")\nplt.xlabel(\"Month\")\nplt.ylabel(r\"Temperature ($^\\circ$C)\")\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/2c2b06d20037624c33617b599309f3af/plot_1d_optim.py b/_downloads/2c2b06d20037624c33617b599309f3af/plot_1d_optim.py new file mode 100644 index 000000000..6b0ad89c9 --- /dev/null +++ b/_downloads/2c2b06d20037624c33617b599309f3af/plot_1d_optim.py @@ -0,0 +1,66 @@ +""" +Brent's method +================ + +Illustration of 1D optimization: Brent's method +""" + +import numpy as np +import matplotlib.pyplot as plt +import scipy as sp + +x = np.linspace(-1, 3, 100) +x_0 = np.exp(-1) + + +def f(x): + return (x - x_0) ** 2 + epsilon * np.exp(-5 * (x - 0.5 - x_0) ** 2) + + +for epsilon in (0, 1): + plt.figure(figsize=(3, 2.5)) + plt.axes((0, 0, 1, 1)) + + # A convex function + plt.plot(x, f(x), linewidth=2) + + # Apply brent method. To have access to the iteration, do this in an + # artificial way: allow the algorithm to iter only once + all_x = [] + all_y = [] + for iter in range(30): + result = sp.optimize.minimize_scalar( + f, + bracket=(-5, 2.9, 4.5), + method="Brent", + options={"maxiter": iter}, + tol=np.finfo(1.0).eps, + ) + if result.success: + print("Converged at ", iter) + break + + this_x = result.x + all_x.append(this_x) + all_y.append(f(this_x)) + if iter < 6: + plt.text( + this_x - 0.05 * np.sign(this_x) - 0.05, + f(this_x) + 1.2 * (0.3 - iter % 2), + str(iter + 1), + size=12, + ) + + plt.plot(all_x[:10], all_y[:10], "k+", markersize=12, markeredgewidth=2) + + plt.plot(all_x[-1], all_y[-1], "rx", markersize=12) + plt.axis("off") + plt.ylim(ymin=-1, ymax=8) + + plt.figure(figsize=(4, 3)) + plt.semilogy(np.abs(all_y - all_y[-1]), linewidth=2) + plt.ylabel("Error on f(x)") + plt.xlabel("Iteration") + plt.tight_layout() + +plt.show() diff --git a/_downloads/2cac79be53bd576411aafab4fd60ac6b/plot_denoising.py b/_downloads/2cac79be53bd576411aafab4fd60ac6b/plot_denoising.py new file mode 100644 index 000000000..c460290a4 --- /dev/null +++ b/_downloads/2cac79be53bd576411aafab4fd60ac6b/plot_denoising.py @@ -0,0 +1,44 @@ +""" +Denoising an image with the median filter +========================================== + +This example shows the original image, the noisy image, the denoised +one (with the median filter) and the difference between the two. +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +rng = np.random.default_rng(27446968) + +im = np.zeros((20, 20)) +im[5:-5, 5:-5] = 1 +im = sp.ndimage.distance_transform_bf(im) +im_noise = im + 0.2 * rng.normal(size=im.shape) + +im_med = sp.ndimage.median_filter(im_noise, 3) + +plt.figure(figsize=(16, 5)) + +plt.subplot(141) +plt.imshow(im, interpolation="nearest") +plt.axis("off") +plt.title("Original image", fontsize=20) +plt.subplot(142) +plt.imshow(im_noise, interpolation="nearest", vmin=0, vmax=5) +plt.axis("off") +plt.title("Noisy image", fontsize=20) +plt.subplot(143) +plt.imshow(im_med, interpolation="nearest", vmin=0, vmax=5) +plt.axis("off") +plt.title("Median filter", fontsize=20) +plt.subplot(144) +plt.imshow(np.abs(im - im_med), cmap="hot", interpolation="nearest") +plt.axis("off") +plt.title("Error", fontsize=20) + + +plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1) + +plt.show() diff --git a/_downloads/2d1ade53602de9209594d2c443c729ba/plot_antialiased.py b/_downloads/2d1ade53602de9209594d2c443c729ba/plot_antialiased.py new file mode 100644 index 000000000..e7ae8d2e8 --- /dev/null +++ b/_downloads/2d1ade53602de9209594d2c443c729ba/plot_antialiased.py @@ -0,0 +1,25 @@ +""" +Aliased versus anti-aliased +============================= + +The example shows aliased versus anti-aliased text. +""" + +import matplotlib.pyplot as plt + +size = 128, 16 +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = plt.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +plt.axes((0, 0, 1, 1), frameon=False) + +plt.rcParams["text.antialiased"] = True +plt.text(0.5, 0.5, "Anti-aliased", ha="center", va="center") + +plt.xlim(0, 1) +plt.ylim(0, 1) +plt.xticks([]) +plt.yticks([]) + +plt.show() diff --git a/_downloads/2e14a23e0698434001f4f21ea8a37b42/plot_image_transform.zip b/_downloads/2e14a23e0698434001f4f21ea8a37b42/plot_image_transform.zip new file mode 100644 index 000000000..85c19c62c Binary files /dev/null and b/_downloads/2e14a23e0698434001f4f21ea8a37b42/plot_image_transform.zip differ diff --git a/_downloads/2e413415c9ccb5cee9a8b3f1ff88ec74/plot_iris_knn.ipynb b/_downloads/2e413415c9ccb5cee9a8b3f1ff88ec74/plot_iris_knn.ipynb new file mode 100644 index 000000000..f05e37706 --- /dev/null +++ b/_downloads/2e413415c9ccb5cee9a8b3f1ff88ec74/plot_iris_knn.ipynb @@ -0,0 +1,79 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Nearest-neighbor prediction on iris\n\nPlot the decision boundary of nearest neighbor decision on iris, first\nwith a single nearest neighbor, and then using 3 nearest neighbors.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import neighbors, datasets\nfrom matplotlib.colors import ListedColormap\n\n# Create color maps for 3-class classification problem, as with iris\ncmap_light = ListedColormap([\"#FFAAAA\", \"#AAFFAA\", \"#AAAAFF\"])\ncmap_bold = ListedColormap([\"#FF0000\", \"#00FF00\", \"#0000FF\"])\n\niris = datasets.load_iris()\nX = iris.data[:, :2] # we only take the first two features. We could\n# avoid this ugly slicing by using a two-dim dataset\ny = iris.target\n\nknn = neighbors.KNeighborsClassifier(n_neighbors=1)\nknn.fit(X, y)\n\nx_min, x_max = X[:, 0].min() - 0.1, X[:, 0].max() + 0.1\ny_min, y_max = X[:, 1].min() - 0.1, X[:, 1].max() + 0.1\nxx, yy = np.meshgrid(np.linspace(x_min, x_max, 100), np.linspace(y_min, y_max, 100))\nZ = knn.predict(np.c_[xx.ravel(), yy.ravel()])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Put the result into a color plot\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "Z = Z.reshape(xx.shape)\nplt.figure()\nplt.pcolormesh(xx, yy, Z, cmap=cmap_light)\n\n# Plot also the training points\nplt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)\nplt.xlabel(\"sepal length (cm)\")\nplt.ylabel(\"sepal width (cm)\")\nplt.axis(\"tight\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "And now, redo the analysis with 3 neighbors\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "knn = neighbors.KNeighborsClassifier(n_neighbors=3)\nknn.fit(X, y)\n\nZ = knn.predict(np.c_[xx.ravel(), yy.ravel()])\n\n# Put the result into a color plot\nZ = Z.reshape(xx.shape)\nplt.figure()\nplt.pcolormesh(xx, yy, Z, cmap=cmap_light)\n\n# Plot also the training points\nplt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)\nplt.xlabel(\"sepal length (cm)\")\nplt.ylabel(\"sepal width (cm)\")\nplt.axis(\"tight\")\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/2f24290533b6a2feeb68b48f5f30907d/plot_axes.ipynb b/_downloads/2f24290533b6a2feeb68b48f5f30907d/plot_axes.ipynb new file mode 100644 index 000000000..092d4b958 --- /dev/null +++ b/_downloads/2f24290533b6a2feeb68b48f5f30907d/plot_axes.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Simple axes example\n\nThis example shows a couple of simple usage of axes.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nplt.axes((0.1, 0.1, 0.8, 0.8))\nplt.xticks([])\nplt.yticks([])\nplt.text(\n 0.6, 0.6, \"axes([0.1, 0.1, 0.8, 0.8])\", ha=\"center\", va=\"center\", size=20, alpha=0.5\n)\n\nplt.axes((0.2, 0.2, 0.3, 0.3))\nplt.xticks([])\nplt.yticks([])\nplt.text(\n 0.5, 0.5, \"axes([0.2, 0.2, 0.3, 0.3])\", ha=\"center\", va=\"center\", size=16, alpha=0.5\n)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/2f4712f7579338ffd7cbc84eb5377a97/plot_simple.py b/_downloads/2f4712f7579338ffd7cbc84eb5377a97/plot_simple.py new file mode 100644 index 000000000..a10e9e38d --- /dev/null +++ b/_downloads/2f4712f7579338ffd7cbc84eb5377a97/plot_simple.py @@ -0,0 +1,14 @@ +""" +A simple example +================= + +""" + +import numpy as np +import matplotlib.pyplot as plt + +X = np.linspace(-np.pi, np.pi, 100) +Y = np.sin(X) + +plt.plot(X, Y, linewidth=2) +plt.show() diff --git a/_downloads/2fc36b8873618e8e3726827b8635669b/auto_examples_python.zip b/_downloads/2fc36b8873618e8e3726827b8635669b/auto_examples_python.zip new file mode 100644 index 000000000..37ee90394 Binary files /dev/null and b/_downloads/2fc36b8873618e8e3726827b8635669b/auto_examples_python.zip differ diff --git a/_downloads/302fab588d35d682c61bdb3bac6defce/plot_text_ext.ipynb b/_downloads/302fab588d35d682c61bdb3bac6defce/plot_text_ext.ipynb new file mode 100644 index 000000000..f5cb5e76c --- /dev/null +++ b/_downloads/302fab588d35d682c61bdb3bac6defce/plot_text_ext.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Text printing decorated\n\nAn example showing text printing and decorating the resulting figure.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nfig = plt.figure()\nplt.xticks([])\nplt.yticks([])\n\neqs = []\neqs.append(\n r\"$W^{3\\beta}_{\\delta_1 \\rho_1 \\sigma_2} = U^{3\\beta}_{\\delta_1 \\rho_1} + \\frac{1}{8 \\pi 2} \\int^{\\alpha_2}_{\\alpha_2} d \\alpha^\\prime_2 \\left[\\frac{ U^{2\\beta}_{\\delta_1 \\rho_1} - \\alpha^\\prime_2U^{1\\beta}_{\\rho_1 \\sigma_2} }{U^{0\\beta}_{\\rho_1 \\sigma_2}}\\right]$\"\n)\neqs.append(\n r\"$\\frac{d\\rho}{d t} + \\rho \\vec{v}\\cdot\\nabla\\vec{v} = -\\nabla p + \\mu\\nabla^2 \\vec{v} + \\rho \\vec{g}$\"\n)\neqs.append(r\"$\\int_{-\\infty}^\\infty e^{-x^2}dx=\\sqrt{\\pi}$\")\neqs.append(r\"$E = mc^2 = \\sqrt{{m_0}^2c^4 + p^2c^2}$\")\neqs.append(r\"$F_G = G\\frac{m_1m_2}{r^2}$\")\n\nrng = np.random.default_rng()\n\nfor i in range(24):\n index = rng.integers(0, len(eqs))\n eq = eqs[index]\n size = rng.uniform(12, 32)\n x, y = rng.uniform(0, 1, 2)\n alpha = rng.uniform(0.25, 0.75)\n plt.text(\n x,\n y,\n eq,\n ha=\"center\",\n va=\"center\",\n color=\"#11557c\",\n alpha=alpha,\n transform=plt.gca().transAxes,\n fontsize=size,\n clip_on=True,\n )\n\n\n# Add a title and a box around it\nfrom matplotlib.patches import FancyBboxPatch\n\nax = plt.gca()\nax.add_patch(\n FancyBboxPatch(\n (-0.05, 0.87),\n width=0.66,\n height=0.165,\n clip_on=False,\n boxstyle=\"square,pad=0\",\n zorder=3,\n facecolor=\"white\",\n alpha=1.0,\n transform=plt.gca().transAxes,\n )\n)\n\nplt.text(\n -0.05,\n 1.02,\n \" Text: plt.text(...)\\n\",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"xx-large\",\n transform=plt.gca().transAxes,\n)\n\nplt.text(\n -0.05,\n 1.01,\n \"\\n\\n Draw any kind of text \",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"large\",\n transform=plt.gca().transAxes,\n)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/30b4ad07063f94c61b074cffcfe28380/plot_mfc.ipynb b/_downloads/30b4ad07063f94c61b074cffcfe28380/plot_mfc.ipynb new file mode 100644 index 000000000..8628684b6 --- /dev/null +++ b/_downloads/30b4ad07063f94c61b074cffcfe28380/plot_mfc.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Marker face color\n\nDemo the marker face color of matplotlib's markers.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nsize = 256, 16\ndpi = 72.0\nfigsize = size[0] / float(dpi), size[1] / float(dpi)\nfig = plt.figure(figsize=figsize, dpi=dpi)\nfig.patch.set_alpha(0)\nplt.axes((0, 0, 1, 1), frameon=False)\n\nrng = np.random.default_rng()\n\nfor i in range(1, 11):\n r, g, b = np.random.uniform(0, 1, 3)\n plt.plot(\n [\n i,\n ],\n [\n 1,\n ],\n \"s\",\n markersize=8,\n markerfacecolor=(r, g, b, 1),\n markeredgewidth=0.1,\n markeredgecolor=(0, 0, 0, 0.5),\n )\nplt.xlim(0, 11)\nplt.xticks([])\nplt.yticks([])\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/30c317481ebf471bf6b1470057bd3786/moonlanding.png b/_downloads/30c317481ebf471bf6b1470057bd3786/moonlanding.png new file mode 100644 index 000000000..15e27b1e2 Binary files /dev/null and b/_downloads/30c317481ebf471bf6b1470057bd3786/moonlanding.png differ diff --git a/_downloads/30f02b47364de2a82f69dec2d3804fbd/plot_sobel.ipynb b/_downloads/30f02b47364de2a82f69dec2d3804fbd/plot_sobel.ipynb new file mode 100644 index 000000000..593a59244 --- /dev/null +++ b/_downloads/30f02b47364de2a82f69dec2d3804fbd/plot_sobel.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Computing horizontal gradients with the Sobel filter\n\nThis example illustrates the use of the horizontal Sobel filter, to compute\nhorizontal gradients.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from skimage import data\nfrom skimage import filters\nimport matplotlib.pyplot as plt\n\ntext = data.text()\nhsobel_text = filters.sobel_h(text)\n\nplt.figure(figsize=(12, 3))\n\nplt.subplot(121)\nplt.imshow(text, cmap=\"gray\", interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.subplot(122)\nplt.imshow(hsobel_text, cmap=\"nipy_spectral\", interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/3200b4c873529badd406017e7e28ed90/plot_blur.py b/_downloads/3200b4c873529badd406017e7e28ed90/plot_blur.py new file mode 100644 index 000000000..cfb6f5759 --- /dev/null +++ b/_downloads/3200b4c873529badd406017e7e28ed90/plot_blur.py @@ -0,0 +1,29 @@ +""" +Blurring of images +=================== + +An example showing various processes that blur an image. +""" + +import scipy as sp +import matplotlib.pyplot as plt + +face = sp.datasets.face(gray=True) +blurred_face = sp.ndimage.gaussian_filter(face, sigma=3) +very_blurred = sp.ndimage.gaussian_filter(face, sigma=5) +local_mean = sp.ndimage.uniform_filter(face, size=11) + +plt.figure(figsize=(9, 3)) +plt.subplot(131) +plt.imshow(blurred_face, cmap="gray") +plt.axis("off") +plt.subplot(132) +plt.imshow(very_blurred, cmap="gray") +plt.axis("off") +plt.subplot(133) +plt.imshow(local_mean, cmap="gray") +plt.axis("off") + +plt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.01, right=0.99) + +plt.show() diff --git a/_downloads/32c95a770d97419dbfff1822a2616d87/plot_axes.py b/_downloads/32c95a770d97419dbfff1822a2616d87/plot_axes.py new file mode 100644 index 000000000..422c4c0e4 --- /dev/null +++ b/_downloads/32c95a770d97419dbfff1822a2616d87/plot_axes.py @@ -0,0 +1,25 @@ +""" +Simple axes example +==================== + +This example shows a couple of simple usage of axes. + +""" + +import matplotlib.pyplot as plt + +plt.axes((0.1, 0.1, 0.8, 0.8)) +plt.xticks([]) +plt.yticks([]) +plt.text( + 0.6, 0.6, "axes([0.1, 0.1, 0.8, 0.8])", ha="center", va="center", size=20, alpha=0.5 +) + +plt.axes((0.2, 0.2, 0.3, 0.3)) +plt.xticks([]) +plt.yticks([]) +plt.text( + 0.5, 0.5, "axes([0.2, 0.2, 0.3, 0.3])", ha="center", va="center", size=16, alpha=0.5 +) + +plt.show() diff --git a/_downloads/32fc4a8005c2aad0e2142ca82466ee10/plot_ugly.ipynb b/_downloads/32fc4a8005c2aad0e2142ca82466ee10/plot_ugly.ipynb new file mode 100644 index 000000000..cd0b953de --- /dev/null +++ b/_downloads/32fc4a8005c2aad0e2142ca82466ee10/plot_ugly.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# A example of plotting not quite right\n\nAn \"ugly\" example of plotting.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib\n\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\n\nmatplotlib.rc(\"grid\", color=\"black\", linestyle=\"-\", linewidth=1)\n\nfig = plt.figure(figsize=(5, 4), dpi=72)\naxes = fig.add_axes((0.01, 0.01, 0.98, 0.98), facecolor=\".75\")\nX = np.linspace(0, 2, 40)\nY = np.sin(2 * np.pi * X)\nplt.plot(X, Y, lw=0.05, c=\"b\", antialiased=False)\n\nplt.xticks([])\nplt.yticks(np.arange(-1.0, 1.0, 0.2))\nplt.grid()\nax = plt.gca()\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/3355cf653e094eb1c21d98e2f0f1a440/plot_plot_ext.zip b/_downloads/3355cf653e094eb1c21d98e2f0f1a440/plot_plot_ext.zip new file mode 100644 index 000000000..59fb8b04e Binary files /dev/null and b/_downloads/3355cf653e094eb1c21d98e2f0f1a440/plot_plot_ext.zip differ diff --git a/_downloads/3365b67d13573d54b31be665ef368d40/plot_numpy_array.ipynb b/_downloads/3365b67d13573d54b31be665ef368d40/plot_numpy_array.ipynb new file mode 100644 index 000000000..8a01f75ba --- /dev/null +++ b/_downloads/3365b67d13573d54b31be665ef368d40/plot_numpy_array.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Image manipulation and NumPy arrays\n\nThis example shows how to do image manipulation using common NumPy arrays\ntricks.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nface = sp.datasets.face(gray=True)\nface[10:13, 20:23]\nface[100:120] = 255\n\nlx, ly = face.shape\nX, Y = np.ogrid[0:lx, 0:ly]\nmask = (X - lx / 2) ** 2 + (Y - ly / 2) ** 2 > lx * ly / 4\nface[mask] = 0\nface[range(400), range(400)] = 255\n\nplt.figure(figsize=(3, 3))\nplt.axes((0, 0, 1, 1))\nplt.imshow(face, cmap=\"gray\")\nplt.axis(\"off\")\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/342af837d47b3eb9832ed5bef493428e/plot_wage_data.ipynb b/_downloads/342af837d47b3eb9832ed5bef493428e/plot_wage_data.ipynb new file mode 100644 index 000000000..569e092a7 --- /dev/null +++ b/_downloads/342af837d47b3eb9832ed5bef493428e/plot_wage_data.ipynb @@ -0,0 +1,97 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Visualizing factors influencing wages\n\nThis example uses seaborn to quickly plot various factors relating wages,\nexperience, and education.\n\nSeaborn (https://seaborn.pydata.org) is a library that combines\nvisualization and statistical fits to show trends in data.\n\nNote that importing seaborn changes the matplotlib style to have an\n\"excel-like\" feeling. This changes affect other matplotlib figures. To\nrestore defaults once this example is run, we would need to call\nplt.rcdefaults().\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Standard library imports\nimport os\n\nimport matplotlib.pyplot as plt" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Load the data\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import pandas\nimport requests\n\nif not os.path.exists(\"wages.txt\"):\n # Download the file if it is not present\n r = requests.get(\"http://lib.stat.cmu.edu/datasets/CPS_85_Wages\")\n with open(\"wages.txt\", \"wb\") as f:\n f.write(r.content)\n\n# Give names to the columns\nnames = [\n \"EDUCATION: Number of years of education\",\n \"SOUTH: 1=Person lives in South, 0=Person lives elsewhere\",\n \"SEX: 1=Female, 0=Male\",\n \"EXPERIENCE: Number of years of work experience\",\n \"UNION: 1=Union member, 0=Not union member\",\n \"WAGE: Wage (dollars per hour)\",\n \"AGE: years\",\n \"RACE: 1=Other, 2=Hispanic, 3=White\",\n \"OCCUPATION: 1=Management, 2=Sales, 3=Clerical, 4=Service, 5=Professional, 6=Other\",\n \"SECTOR: 0=Other, 1=Manufacturing, 2=Construction\",\n \"MARR: 0=Unmarried, 1=Married\",\n]\n\nshort_names = [n.split(\":\")[0] for n in names]\n\ndata = pandas.read_csv(\n \"wages.txt\", skiprows=27, skipfooter=6, sep=None, header=None, engine=\"python\"\n)\ndata.columns = pandas.Index(short_names)\n\n# Log-transform the wages, because they typically are increased with\n# multiplicative factors\nimport numpy as np\n\ndata[\"WAGE\"] = np.log10(data[\"WAGE\"])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Plot scatter matrices highlighting different aspects\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import seaborn\n\nseaborn.pairplot(data, vars=[\"WAGE\", \"AGE\", \"EDUCATION\"], kind=\"reg\")\n\nseaborn.pairplot(data, vars=[\"WAGE\", \"AGE\", \"EDUCATION\"], kind=\"reg\", hue=\"SEX\")\nplt.suptitle(\"Effect of gender: 1=Female, 0=Male\")\n\nseaborn.pairplot(data, vars=[\"WAGE\", \"AGE\", \"EDUCATION\"], kind=\"reg\", hue=\"RACE\")\nplt.suptitle(\"Effect of race: 1=Other, 2=Hispanic, 3=White\")\n\nseaborn.pairplot(data, vars=[\"WAGE\", \"AGE\", \"EDUCATION\"], kind=\"reg\", hue=\"UNION\")\nplt.suptitle(\"Effect of union: 1=Union member, 0=Not union member\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Plot a simple regression\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "seaborn.lmplot(y=\"WAGE\", x=\"EDUCATION\", data=data)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/3581db56ea8e85fcf58c3a213e12354c/plot_scatter_ext.py b/_downloads/3581db56ea8e85fcf58c3a213e12354c/plot_scatter_ext.py new file mode 100644 index 000000000..3420c0f50 --- /dev/null +++ b/_downloads/3581db56ea8e85fcf58c3a213e12354c/plot_scatter_ext.py @@ -0,0 +1,63 @@ +""" +Plot scatter decorated +======================= + +An example showing the scatter function, with decorations. +""" + +import numpy as np +import matplotlib.pyplot as plt + +n = 1024 +rng = np.random.default_rng() +X = rng.normal(0, 1, n) +Y = rng.normal(0, 1, n) + +T = np.arctan2(Y, X) + +plt.scatter(X, Y, s=75, c=T, alpha=0.5) +plt.xlim(-1.5, 1.5) +plt.xticks([]) +plt.ylim(-1.5, 1.5) +plt.yticks([]) + + +# Add a title and a box around it +from matplotlib.patches import FancyBboxPatch + +ax = plt.gca() +ax.add_patch( + FancyBboxPatch( + (-0.05, 0.87), + width=0.66, + height=0.165, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) +) + +plt.text( + -0.05, + 1.02, + " Scatter Plot: plt.scatter(...)\n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=plt.gca().transAxes, +) + +plt.text( + -0.05, + 1.01, + "\n\n Make a scatter plot of x versus y ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=plt.gca().transAxes, +) + +plt.show() diff --git a/_downloads/35ca147a0318e90d8236325da2d3f276/plot_optimize_example1.py b/_downloads/35ca147a0318e90d8236325da2d3f276/plot_optimize_example1.py new file mode 100644 index 000000000..41b7cc780 --- /dev/null +++ b/_downloads/35ca147a0318e90d8236325da2d3f276/plot_optimize_example1.py @@ -0,0 +1,29 @@ +""" +========================================= +Finding the minimum of a smooth function +========================================= + +Demos various methods to find the minimum of a function. +""" + +import numpy as np +import matplotlib.pyplot as plt + + +def f(x): + return x**2 + 10 * np.sin(x) + + +x = np.arange(-5, 5, 0.1) +plt.plot(x, f(x)) + +############################################################ +# Now find the minimum with a few methods +import scipy as sp + +# The default (Nelder Mead) +print(sp.optimize.minimize(f, x0=0)) + +############################################################ + +plt.show() diff --git a/_downloads/367fe7dac0a806f734ff452c0da30fd4/plot_linewidth.py b/_downloads/367fe7dac0a806f734ff452c0da30fd4/plot_linewidth.py new file mode 100644 index 000000000..819aff36c --- /dev/null +++ b/_downloads/367fe7dac0a806f734ff452c0da30fd4/plot_linewidth.py @@ -0,0 +1,25 @@ +""" +Linewidth +========= + +Plot various linewidth with matplotlib. +""" + +import matplotlib.pyplot as plt + +size = 256, 16 +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = plt.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +plt.axes((0, 0.1, 1, 0.8), frameon=False) + +for i in range(1, 11): + plt.plot([i, i], [0, 1], color="b", lw=i / 2.0) + +plt.xlim(0, 11) +plt.ylim(0, 1) +plt.xticks([]) +plt.yticks([]) + +plt.show() diff --git a/_downloads/36fee0b7aa78875657bd88b6f91b0959/plot_ugly.zip b/_downloads/36fee0b7aa78875657bd88b6f91b0959/plot_ugly.zip new file mode 100644 index 000000000..d756bf432 Binary files /dev/null and b/_downloads/36fee0b7aa78875657bd88b6f91b0959/plot_ugly.zip differ diff --git a/_downloads/375007856312d11187cb98df5ab8a531/plot_subplot-grid.zip b/_downloads/375007856312d11187cb98df5ab8a531/plot_subplot-grid.zip new file mode 100644 index 000000000..73f4e60b4 Binary files /dev/null and b/_downloads/375007856312d11187cb98df5ab8a531/plot_subplot-grid.zip differ diff --git a/_downloads/3800cc291e0024d966cd6ee966028f8e/demo.py b/_downloads/3800cc291e0024d966cd6ee966028f8e/demo.py new file mode 100644 index 000000000..e5eb025b8 --- /dev/null +++ b/_downloads/3800cc291e0024d966cd6ee966028f8e/demo.py @@ -0,0 +1,19 @@ +# For this example to run, you also need the 'ica.py' file + +import numpy as np +import scipy as sp + +from ica import fastica + + +# @profile # uncomment this line to run with line_profiler +def test(): + rng = np.random.default_rng() + data = rng.random((5000, 100)) + u, s, v = sp.linalg.svd(data) + pca = u[:, :10].T @ data + results = fastica(pca.T, whiten=False) + + +if __name__ == "__main__": + test() diff --git a/_downloads/3900d495dbe09c1891913aa3c5d99cb3/plot_non_bounds_constraints.zip b/_downloads/3900d495dbe09c1891913aa3c5d99cb3/plot_non_bounds_constraints.zip new file mode 100644 index 000000000..471045e6f Binary files /dev/null and b/_downloads/3900d495dbe09c1891913aa3c5d99cb3/plot_non_bounds_constraints.zip differ diff --git a/_downloads/39696cb3a566d70740ec07ac19106c22/plot_scatter.ipynb b/_downloads/39696cb3a566d70740ec07ac19106c22/plot_scatter.ipynb new file mode 100644 index 000000000..198b6000b --- /dev/null +++ b/_downloads/39696cb3a566d70740ec07ac19106c22/plot_scatter.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plotting a scatter of points\n\nA simple example showing how to plot a scatter of points with matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nn = 1024\nrng = np.random.default_rng()\nX = rng.normal(0, 1, n)\nY = rng.normal(0, 1, n)\nT = np.arctan2(Y, X)\n\nplt.axes((0.025, 0.025, 0.95, 0.95))\nplt.scatter(X, Y, s=75, c=T, alpha=0.5)\n\nplt.xlim(-1.5, 1.5)\nplt.xticks([])\nplt.ylim(-1.5, 1.5)\nplt.yticks([])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/39af8fcb4eccf46cf3c097e677d381aa/plot_gradient_descent.ipynb b/_downloads/39af8fcb4eccf46cf3c097e677d381aa/plot_gradient_descent.ipynb new file mode 100644 index 000000000..3ec5b31b4 --- /dev/null +++ b/_downloads/39af8fcb4eccf46cf3c097e677d381aa/plot_gradient_descent.ipynb @@ -0,0 +1,97 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Gradient descent\n\nAn example demoing gradient descent by creating figures that trace the\nevolution of the optimizer.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy as sp\n\nimport collections\nimport sys\nimport os\n\nsys.path.append(os.path.abspath(\"helper\"))\nfrom cost_functions import (\n mk_quad,\n mk_gauss,\n rosenbrock,\n rosenbrock_prime,\n rosenbrock_hessian,\n LoggingFunction,\n CountingFunction,\n)\n\nx_min, x_max = -1, 2\ny_min, y_max = 2.25 / 3 * x_min - 0.2, 2.25 / 3 * x_max - 0.2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A formatter to print values on contours\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "def super_fmt(value):\n if value > 1:\n if np.abs(int(value) - value) < 0.1:\n out = f\"$10^{{{int(value):d}}}$\"\n else:\n out = f\"$10^{{{value:.1f}}}$\"\n else:\n value = np.exp(value - 0.01)\n if value > 0.1:\n out = f\"{value:1.1f}\"\n elif value > 0.01:\n out = f\"{value:.2f}\"\n else:\n out = f\"{value:.2e}\"\n return out" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A gradient descent algorithm\ndo not use: its a toy, use scipy's optimize.fmin_cg\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "def gradient_descent(x0, f, f_prime, hessian=None, adaptative=False):\n x_i, y_i = x0\n all_x_i = []\n all_y_i = []\n all_f_i = []\n\n for i in range(1, 100):\n all_x_i.append(x_i)\n all_y_i.append(y_i)\n all_f_i.append(f([x_i, y_i]))\n dx_i, dy_i = f_prime(np.asarray([x_i, y_i]))\n if adaptative:\n # Compute a step size using a line_search to satisfy the Wolf\n # conditions\n step = sp.optimize.line_search(\n f,\n f_prime,\n np.r_[x_i, y_i],\n -np.r_[dx_i, dy_i],\n np.r_[dx_i, dy_i],\n c2=0.05,\n )\n step = step[0]\n if step is None:\n step = 0\n else:\n step = 1\n x_i += -step * dx_i\n y_i += -step * dy_i\n if np.abs(all_f_i[-1]) < 1e-16:\n break\n return all_x_i, all_y_i, all_f_i\n\n\ndef gradient_descent_adaptative(x0, f, f_prime, hessian=None):\n return gradient_descent(x0, f, f_prime, adaptative=True)\n\n\ndef conjugate_gradient(x0, f, f_prime, hessian=None):\n all_x_i = [x0[0]]\n all_y_i = [x0[1]]\n all_f_i = [f(x0)]\n\n def store(X):\n x, y = X\n all_x_i.append(x)\n all_y_i.append(y)\n all_f_i.append(f(X))\n\n sp.optimize.minimize(\n f, x0, jac=f_prime, method=\"CG\", callback=store, options={\"gtol\": 1e-12}\n )\n return all_x_i, all_y_i, all_f_i\n\n\ndef newton_cg(x0, f, f_prime, hessian):\n all_x_i = [x0[0]]\n all_y_i = [x0[1]]\n all_f_i = [f(x0)]\n\n def store(X):\n x, y = X\n all_x_i.append(x)\n all_y_i.append(y)\n all_f_i.append(f(X))\n\n sp.optimize.minimize(\n f,\n x0,\n method=\"Newton-CG\",\n jac=f_prime,\n hess=hessian,\n callback=store,\n options={\"xtol\": 1e-12},\n )\n return all_x_i, all_y_i, all_f_i\n\n\ndef bfgs(x0, f, f_prime, hessian=None):\n all_x_i = [x0[0]]\n all_y_i = [x0[1]]\n all_f_i = [f(x0)]\n\n def store(X):\n x, y = X\n all_x_i.append(x)\n all_y_i.append(y)\n all_f_i.append(f(X))\n\n sp.optimize.minimize(\n f, x0, method=\"BFGS\", jac=f_prime, callback=store, options={\"gtol\": 1e-12}\n )\n return all_x_i, all_y_i, all_f_i\n\n\ndef powell(x0, f, f_prime, hessian=None):\n all_x_i = [x0[0]]\n all_y_i = [x0[1]]\n all_f_i = [f(x0)]\n\n def store(X):\n x, y = X\n all_x_i.append(x)\n all_y_i.append(y)\n all_f_i.append(f(X))\n\n sp.optimize.minimize(\n f, x0, method=\"Powell\", callback=store, options={\"ftol\": 1e-12}\n )\n return all_x_i, all_y_i, all_f_i\n\n\ndef nelder_mead(x0, f, f_prime, hessian=None):\n all_x_i = [x0[0]]\n all_y_i = [x0[1]]\n all_f_i = [f(x0)]\n\n def store(X):\n x, y = X\n all_x_i.append(x)\n all_y_i.append(y)\n all_f_i.append(f(X))\n\n sp.optimize.minimize(\n f, x0, method=\"Nelder-Mead\", callback=store, options={\"ftol\": 1e-12}\n )\n return all_x_i, all_y_i, all_f_i" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Run different optimizers on these problems\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "levels = {}\n\nfor index, ((f, f_prime, hessian), optimizer) in enumerate(\n (\n (mk_quad(0.7), gradient_descent),\n (mk_quad(0.7), gradient_descent_adaptative),\n (mk_quad(0.02), gradient_descent),\n (mk_quad(0.02), gradient_descent_adaptative),\n (mk_gauss(0.02), gradient_descent_adaptative),\n (\n (rosenbrock, rosenbrock_prime, rosenbrock_hessian),\n gradient_descent_adaptative,\n ),\n (mk_gauss(0.02), conjugate_gradient),\n ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), conjugate_gradient),\n (mk_quad(0.02), newton_cg),\n (mk_gauss(0.02), newton_cg),\n ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), newton_cg),\n (mk_quad(0.02), bfgs),\n (mk_gauss(0.02), bfgs),\n ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), bfgs),\n (mk_quad(0.02), powell),\n (mk_gauss(0.02), powell),\n ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), powell),\n (mk_gauss(0.02), nelder_mead),\n ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), nelder_mead),\n )\n):\n # Compute a gradient-descent\n x_i, y_i = 1.6, 1.1\n counting_f_prime = CountingFunction(f_prime)\n counting_hessian = CountingFunction(hessian)\n logging_f = LoggingFunction(f, counter=counting_f_prime.counter)\n all_x_i, all_y_i, all_f_i = optimizer(\n np.array([x_i, y_i]), logging_f, counting_f_prime, hessian=counting_hessian\n )\n\n # Plot the contour plot\n if not max(all_y_i) < y_max:\n x_min *= 1.2\n x_max *= 1.2\n y_min *= 1.2\n y_max *= 1.2\n x, y = np.mgrid[x_min:x_max:100j, y_min:y_max:100j]\n x = x.T\n y = y.T\n\n plt.figure(index, figsize=(3, 2.5))\n plt.clf()\n plt.axes([0, 0, 1, 1])\n\n X = np.concatenate((x[np.newaxis, ...], y[np.newaxis, ...]), axis=0)\n z = np.apply_along_axis(f, 0, X)\n log_z = np.log(z + 0.01)\n plt.imshow(\n log_z,\n extent=[x_min, x_max, y_min, y_max],\n cmap=plt.cm.gray_r,\n origin=\"lower\",\n vmax=log_z.min() + 1.5 * np.ptp(log_z),\n )\n contours = plt.contour(\n log_z,\n levels=levels.get(f),\n extent=[x_min, x_max, y_min, y_max],\n cmap=plt.cm.gnuplot,\n origin=\"lower\",\n )\n levels[f] = contours.levels\n plt.clabel(contours, inline=1, fmt=super_fmt, fontsize=14)\n\n plt.plot(all_x_i, all_y_i, \"b-\", linewidth=2)\n plt.plot(all_x_i, all_y_i, \"k+\")\n\n plt.plot(logging_f.all_x_i, logging_f.all_y_i, \"k.\", markersize=2)\n\n plt.plot([0], [0], \"rx\", markersize=12)\n\n plt.xticks(())\n plt.yticks(())\n plt.xlim(x_min, x_max)\n plt.ylim(y_min, y_max)\n plt.draw()\n\n plt.figure(index + 100, figsize=(4, 3))\n plt.clf()\n plt.semilogy(np.maximum(np.abs(all_f_i), 1e-30), linewidth=2, label=\"# iterations\")\n plt.ylabel(\"Error on f(x)\")\n plt.semilogy(\n logging_f.counts,\n np.maximum(np.abs(logging_f.all_f_i), 1e-30),\n linewidth=2,\n color=\"g\",\n label=\"# function calls\",\n )\n plt.legend(\n loc=\"upper right\",\n frameon=True,\n prop={\"size\": 11},\n borderaxespad=0,\n handlelength=1.5,\n handletextpad=0.5,\n )\n plt.tight_layout()\n plt.draw()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/3c1d76cc81341d41a4f3fd63a4d05bab/plot_optimize_lidar_data.zip b/_downloads/3c1d76cc81341d41a4f3fd63a4d05bab/plot_optimize_lidar_data.zip new file mode 100644 index 000000000..b23445877 Binary files /dev/null and b/_downloads/3c1d76cc81341d41a4f3fd63a4d05bab/plot_optimize_lidar_data.zip differ diff --git a/_downloads/3c55a7b16349df29dce17d78a9e5e585/plot_constraints.ipynb b/_downloads/3c55a7b16349df29dce17d78a9e5e585/plot_constraints.ipynb new file mode 100644 index 000000000..71e5584f4 --- /dev/null +++ b/_downloads/3c55a7b16349df29dce17d78a9e5e585/plot_constraints.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Constraint optimization: visualizing the geometry\n\nA small figure explaining optimization with constraints\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy as sp\n\nx, y = np.mgrid[-2.9:5.8:0.05, -2.5:5:0.05] # type: ignore[misc]\nx = x.T\ny = y.T\n\nfor i in (1, 2):\n # Create 2 figure: only the second one will have the optimization\n # path\n plt.figure(i, figsize=(3, 2.5))\n plt.clf()\n plt.axes((0, 0, 1, 1))\n\n contours = plt.contour(\n np.sqrt((x - 3) ** 2 + (y - 2) ** 2),\n extent=[-3, 6, -2.5, 5],\n cmap=\"gnuplot\",\n )\n plt.clabel(contours, inline=1, fmt=\"%1.1f\", fontsize=14)\n plt.plot(\n [-1.5, -1.5, 1.5, 1.5, -1.5], [-1.5, 1.5, 1.5, -1.5, -1.5], \"k\", linewidth=2\n )\n plt.fill_between([-1.5, 1.5], [-1.5, -1.5], [1.5, 1.5], color=\".8\")\n plt.axvline(0, color=\"k\")\n plt.axhline(0, color=\"k\")\n\n plt.text(-0.9, 4.4, \"$x_2$\", size=20)\n plt.text(5.6, -0.6, \"$x_1$\", size=20)\n plt.axis(\"equal\")\n plt.axis(\"off\")\n\n# And now plot the optimization path\naccumulator = []\n\n\ndef f(x):\n # Store the list of function calls\n accumulator.append(x)\n return np.sqrt((x[0] - 3) ** 2 + (x[1] - 2) ** 2)\n\n\n# We don't use the gradient, as with the gradient, L-BFGS is too fast,\n# and finds the optimum without showing us a pretty path\ndef f_prime(x):\n r = np.sqrt((x[0] - 3) ** 2 + (x[0] - 2) ** 2)\n return np.array(((x[0] - 3) / r, (x[0] - 2) / r))\n\n\nsp.optimize.minimize(\n f, np.array([0, 0]), method=\"L-BFGS-B\", bounds=((-1.5, 1.5), (-1.5, 1.5))\n)\n\naccumulated = np.array(accumulator)\nplt.plot(accumulated[:, 0], accumulated[:, 1])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/3d68b5f8e4617e8c1b829212e3045467/plot_bar.ipynb b/_downloads/3d68b5f8e4617e8c1b829212e3045467/plot_bar.ipynb new file mode 100644 index 000000000..9799e47c1 --- /dev/null +++ b/_downloads/3d68b5f8e4617e8c1b829212e3045467/plot_bar.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Bar plots\n\nAn example of bar plots with matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nn = 12\nX = np.arange(n)\nrng = np.random.default_rng()\nY1 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n)\nY2 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n)\n\nplt.axes((0.025, 0.025, 0.95, 0.95))\nplt.bar(X, +Y1, facecolor=\"#9999ff\", edgecolor=\"white\")\nplt.bar(X, -Y2, facecolor=\"#ff9999\", edgecolor=\"white\")\n\nfor x, y in zip(X, Y1, strict=True):\n plt.text(x + 0.4, y + 0.05, f\"{y:.2f}\", ha=\"center\", va=\"bottom\")\n\nfor x, y in zip(X, Y2, strict=True):\n plt.text(x + 0.4, -y - 0.05, f\"{y:.2f}\", ha=\"center\", va=\"top\")\n\nplt.xlim(-0.5, n)\nplt.xticks([])\nplt.ylim(-1.25, 1.25)\nplt.yticks([])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/3e3a2258da3217f2e7902b8c4b8a4992/plot_boxplot_ext.py b/_downloads/3e3a2258da3217f2e7902b8c4b8a4992/plot_boxplot_ext.py new file mode 100644 index 000000000..ff844eba2 --- /dev/null +++ b/_downloads/3e3a2258da3217f2e7902b8c4b8a4992/plot_boxplot_ext.py @@ -0,0 +1,65 @@ +""" +Boxplot with matplotlib +======================= + +An example of doing box plots with matplotlib + +""" + +import numpy as np +import matplotlib.pyplot as plt + + +fig = plt.figure(figsize=(8, 5)) +axes = plt.subplot(111) + +n = 5 +Z = np.zeros((n, 4)) +X = np.linspace(0, 2, n) +rng = np.random.default_rng() +Y = rng.random((n, 4)) +plt.boxplot(Y) + +plt.xticks([]) +plt.yticks([]) + + +# Add a title and a box around it +from matplotlib.patches import FancyBboxPatch + +ax = plt.gca() +ax.add_patch( + FancyBboxPatch( + (-0.05, 0.87), + width=0.66, + height=0.165, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) +) + +plt.text( + -0.05, + 1.02, + " Box Plot: plt.boxplot(...)\n ", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=axes.transAxes, +) + +plt.text( + -0.04, + 0.98, + "\n Make a box and whisker plot ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=axes.transAxes, +) + +plt.show() diff --git a/_downloads/3f8900f714330891401c670b01fcb4eb/plot_exercise_2.ipynb b/_downloads/3f8900f714330891401c670b01fcb4eb/plot_exercise_2.ipynb new file mode 100644 index 000000000..47ce18d01 --- /dev/null +++ b/_downloads/3f8900f714330891401c670b01fcb4eb/plot_exercise_2.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Exercise 2\n\nExercise 2 with matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\n# Create a new figure of size 8x6 points, using 100 dots per inch\nplt.figure(figsize=(8, 6), dpi=80)\n\n# Create a new subplot from a grid of 1x1\nplt.subplot(111)\n\nX = np.linspace(-np.pi, np.pi, 256)\nC, S = np.cos(X), np.sin(X)\n\n# Plot cosine using blue color with a continuous line of width 1 (pixels)\nplt.plot(X, C, color=\"blue\", linewidth=1.0, linestyle=\"-\")\n\n# Plot sine using green color with a continuous line of width 1 (pixels)\nplt.plot(X, S, color=\"green\", linewidth=1.0, linestyle=\"-\")\n\n# Set x limits\nplt.xlim(-4.0, 4.0)\n\n# Set x ticks\nplt.xticks(np.linspace(-4, 4, 9))\n\n# Set y limits\nplt.ylim(-1.0, 1.0)\n\n# Set y ticks\nplt.yticks(np.linspace(-1, 1, 5))\n\n# Show result on screen\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/3f8c867062d7d263e36005fcd6792095/plot_measuring_performance.zip b/_downloads/3f8c867062d7d263e36005fcd6792095/plot_measuring_performance.zip new file mode 100644 index 000000000..3ba3a5dfa Binary files /dev/null and b/_downloads/3f8c867062d7d263e36005fcd6792095/plot_measuring_performance.zip differ diff --git a/_downloads/3fd1065703d180fde688d0b784deb9f7/plot_GMM.zip b/_downloads/3fd1065703d180fde688d0b784deb9f7/plot_GMM.zip new file mode 100644 index 000000000..ff97f0413 Binary files /dev/null and b/_downloads/3fd1065703d180fde688d0b784deb9f7/plot_GMM.zip differ diff --git a/_downloads/4085a054baad414c3de7aa284551d858/plot_subplot-grid.py b/_downloads/4085a054baad414c3de7aa284551d858/plot_subplot-grid.py new file mode 100644 index 000000000..87a44d41f --- /dev/null +++ b/_downloads/4085a054baad414c3de7aa284551d858/plot_subplot-grid.py @@ -0,0 +1,33 @@ +""" +Subplot grid +============= + +An example showing the subplot grid in matplotlib. +""" + +import matplotlib.pyplot as plt + +plt.figure(figsize=(6, 4)) +plt.subplot(2, 2, 1) +plt.xticks([]) +plt.yticks([]) +plt.text(0.5, 0.5, "subplot(2,2,1)", ha="center", va="center", size=20, alpha=0.5) + +plt.subplot(2, 2, 2) +plt.xticks([]) +plt.yticks([]) +plt.text(0.5, 0.5, "subplot(2,2,2)", ha="center", va="center", size=20, alpha=0.5) + +plt.subplot(2, 2, 3) +plt.xticks([]) +plt.yticks([]) + +plt.text(0.5, 0.5, "subplot(2,2,3)", ha="center", va="center", size=20, alpha=0.5) + +plt.subplot(2, 2, 4) +plt.xticks([]) +plt.yticks([]) +plt.text(0.5, 0.5, "subplot(2,2,4)", ha="center", va="center", size=20, alpha=0.5) + +plt.tight_layout() +plt.show() diff --git a/_downloads/4120cb801c1ce9a84962b5b98b0ff926/plot_sprog_annual_maxima.ipynb b/_downloads/4120cb801c1ce9a84962b5b98b0ff926/plot_sprog_annual_maxima.ipynb new file mode 100644 index 000000000..e40d0618a --- /dev/null +++ b/_downloads/4120cb801c1ce9a84962b5b98b0ff926/plot_sprog_annual_maxima.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# The Gumbell distribution, results\n\nGenerate the exercise results on the Gumbell distribution\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nyears_nb = 21\nwspeeds = np.load(\"sprog-windspeeds.npy\")\nmax_speeds = np.array([arr.max() for arr in np.array_split(wspeeds, years_nb)])\n\nplt.figure()\nplt.bar(np.arange(years_nb) + 1, max_speeds)\nplt.axis(\"tight\")\nplt.xlabel(\"Year\")\nplt.ylabel(\"Annual wind speed maxima [$m/s$]\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/416ec0e3564864be96c860de3ec031f3/plot_solve_ivp_simple.ipynb b/_downloads/416ec0e3564864be96c860de3ec031f3/plot_solve_ivp_simple.ipynb new file mode 100644 index 000000000..4ce7fbe60 --- /dev/null +++ b/_downloads/416ec0e3564864be96c860de3ec031f3/plot_solve_ivp_simple.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Integrating a simple ODE\n\nSolve the ODE dy/dt = -2y between t = 0..4, with the initial condition\ny(t=0) = 1.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\n\ndef f(t, y):\n return -2 * y\n\n\nt_span = (0, 4) # time interval\nt_eval = np.linspace(*t_span) # times at which to evaluate `y`\ny0 = [\n 1,\n] # initial state\nres = sp.integrate.solve_ivp(f, t_span=t_span, y0=y0, t_eval=t_eval)\n\nplt.figure(figsize=(4, 3))\nplt.plot(res.t, res.y[0])\nplt.xlabel(\"t\")\nplt.ylabel(\"y\")\nplt.title(\"Solution of Initial Value Problem\")\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/424d6f7f0119ce9d124659d4ab7feb78/plot_polar_ext.py b/_downloads/424d6f7f0119ce9d124659d4ab7feb78/plot_polar_ext.py new file mode 100644 index 000000000..bceb0595f --- /dev/null +++ b/_downloads/424d6f7f0119ce9d124659d4ab7feb78/plot_polar_ext.py @@ -0,0 +1,53 @@ +""" +Plotting in polar, decorated +============================= + +An example showing how to plot in polar coordinate, and some +decorations. +""" + +import numpy as np + +import matplotlib +import matplotlib.pyplot as plt + + +plt.subplot(1, 1, 1, polar=True) + +N = 20 +theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N) +rng = np.random.default_rng() +radii = 10 * rng.random(N) +width = np.pi / 4 * rng.random(N) +bars = plt.bar(theta, radii, width=width, bottom=0.0) +jet = matplotlib.colormaps["jet"] + +for r, bar in zip(radii, bars, strict=True): + bar.set_facecolor(jet(r / 10.0)) + bar.set_alpha(0.5) +plt.gca().set_xticklabels([]) +plt.gca().set_yticklabels([]) + + +plt.text( + -0.2, + 1.02, + " Polar Axis \n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + bbox={"facecolor": "white", "alpha": 1.0}, + transform=plt.gca().transAxes, +) + +plt.text( + -0.2, + 1.01, + "\n\n Plot anything using polar axis ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=plt.gca().transAxes, +) + +plt.show() diff --git a/_downloads/4297992c516447c4b3225739a19b7b02/plot_find_object.py b/_downloads/4297992c516447c4b3225739a19b7b02/plot_find_object.py new file mode 100644 index 000000000..9531bd253 --- /dev/null +++ b/_downloads/4297992c516447c4b3225739a19b7b02/plot_find_object.py @@ -0,0 +1,42 @@ +""" +Find the bounding box of an object +=================================== + +This example shows how to extract the bounding box of the largest object + +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +rng = np.random.default_rng(27446968) +n = 10 +l = 256 +im = np.zeros((l, l)) +points = l * rng.random((2, n**2)) +im[(points[0]).astype(int), (points[1]).astype(int)] = 1 +im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) + +mask = im > im.mean() + +label_im, nb_labels = sp.ndimage.label(mask) + +# Find the largest connected component +sizes = sp.ndimage.sum(mask, label_im, range(nb_labels + 1)) +mask_size = sizes < 1000 +remove_pixel = mask_size[label_im] +label_im[remove_pixel] = 0 +labels = np.unique(label_im) +label_im = np.searchsorted(labels, label_im) + +# Now that we have only one connected component, extract it's bounding box +slice_x, slice_y = sp.ndimage.find_objects(label_im == 4)[0] +roi = im[slice_x, slice_y] + +plt.figure(figsize=(4, 2)) +plt.axes((0, 0, 1, 1)) +plt.imshow(roi) +plt.axis("off") + +plt.show() diff --git a/_downloads/42d5e063064417cbfe53d710043f4b0a/plot_granulo.zip b/_downloads/42d5e063064417cbfe53d710043f4b0a/plot_granulo.zip new file mode 100644 index 000000000..57dca0071 Binary files /dev/null and b/_downloads/42d5e063064417cbfe53d710043f4b0a/plot_granulo.zip differ diff --git a/_downloads/42fe33bc43e2eec49653f7398405e731/plot_optimize_lidar_complex_data_fit.py b/_downloads/42fe33bc43e2eec49653f7398405e731/plot_optimize_lidar_complex_data_fit.py new file mode 100644 index 000000000..89a596dcd --- /dev/null +++ b/_downloads/42fe33bc43e2eec49653f7398405e731/plot_optimize_lidar_complex_data_fit.py @@ -0,0 +1,37 @@ +""" +The lidar system, data and fit (2 of 2 datasets) +================================================ + +Generate a chart of the data fitted by Gaussian curve +""" + +import numpy as np +import matplotlib.pyplot as plt +import scipy as sp + + +def model(t, coeffs): + return ( + coeffs[0] + + coeffs[1] * np.exp(-(((t - coeffs[2]) / coeffs[3]) ** 2)) + + coeffs[4] * np.exp(-(((t - coeffs[5]) / coeffs[6]) ** 2)) + + coeffs[7] * np.exp(-(((t - coeffs[8]) / coeffs[9]) ** 2)) + ) + + +def residuals(coeffs, y, t): + return y - model(t, coeffs) + + +waveform_2 = np.load("waveform_2.npy") +t = np.arange(len(waveform_2)) + +x0 = np.array([3, 30, 20, 1, 12, 25, 1, 8, 28, 1], dtype=float) +x, flag = sp.optimize.leastsq(residuals, x0, args=(waveform_2, t)) + +fig, ax = plt.subplots(figsize=(8, 6)) +plt.plot(t, waveform_2, t, model(t, x)) +plt.xlabel("Time [ns]") +plt.ylabel("Amplitude [bins]") +plt.legend(["Waveform", "Model"]) +plt.show() diff --git a/_downloads/43929eb894967ed5df90caed809418b1/plot_grid_ext.ipynb b/_downloads/43929eb894967ed5df90caed809418b1/plot_grid_ext.ipynb new file mode 100644 index 000000000..e32239195 --- /dev/null +++ b/_downloads/43929eb894967ed5df90caed809418b1/plot_grid_ext.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Grid elaborate\n\nAn example displaying a grid on the axes and tweaking the layout.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\nfrom matplotlib.ticker import MultipleLocator\n\nfig = plt.figure(figsize=(8, 6), dpi=72, facecolor=\"white\")\naxes = plt.subplot(111)\naxes.set_xlim(0, 4)\naxes.set_ylim(0, 3)\n\naxes.xaxis.set_major_locator(MultipleLocator(1.0))\naxes.xaxis.set_minor_locator(MultipleLocator(0.1))\naxes.yaxis.set_major_locator(MultipleLocator(1.0))\naxes.yaxis.set_minor_locator(MultipleLocator(0.1))\naxes.grid(which=\"major\", axis=\"x\", linewidth=0.75, linestyle=\"-\", color=\"0.75\")\naxes.grid(which=\"minor\", axis=\"x\", linewidth=0.25, linestyle=\"-\", color=\"0.75\")\naxes.grid(which=\"major\", axis=\"y\", linewidth=0.75, linestyle=\"-\", color=\"0.75\")\naxes.grid(which=\"minor\", axis=\"y\", linewidth=0.25, linestyle=\"-\", color=\"0.75\")\naxes.set_xticklabels([])\naxes.set_yticklabels([])\n\n\n# Add a title and a box around it\nfrom matplotlib.patches import FancyBboxPatch\n\nax = plt.gca()\nax.add_patch(\n FancyBboxPatch(\n (-0.05, 0.87),\n width=0.66,\n height=0.165,\n clip_on=False,\n boxstyle=\"square,pad=0\",\n zorder=3,\n facecolor=\"white\",\n alpha=1.0,\n transform=plt.gca().transAxes,\n )\n)\n\nplt.text(\n -0.05,\n 1.02,\n \" Grid: plt.grid(...)\\n\",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"xx-large\",\n transform=axes.transAxes,\n)\n\nplt.text(\n -0.05,\n 1.01,\n \"\\n\\n Draw ticks and grid \",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"large\",\n transform=axes.transAxes,\n)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/43e89c0f3ced26e755d048decee19e52/plot_separator.py b/_downloads/43e89c0f3ced26e755d048decee19e52/plot_separator.py new file mode 100644 index 000000000..c44d6bcba --- /dev/null +++ b/_downloads/43e89c0f3ced26e755d048decee19e52/plot_separator.py @@ -0,0 +1,43 @@ +""" +Simple picture of the formal problem of machine learning +========================================================= + +This example generates simple synthetic data ploints and shows a +separating hyperplane on them. +""" + +import numpy as np +import matplotlib.pyplot as plt +from sklearn.linear_model import SGDClassifier +from sklearn.datasets import make_blobs + +# we create 50 separable synthetic points +X, Y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.60) + +# fit the model +clf = SGDClassifier(loss="hinge", alpha=0.01, fit_intercept=True) +clf.fit(X, Y) + +# plot the line, the points, and the nearest vectors to the plane +xx = np.linspace(-1, 5, 10) +yy = np.linspace(-1, 5, 10) + +X1, X2 = np.meshgrid(xx, yy) +Z = np.empty(X1.shape) +for (i, j), val in np.ndenumerate(X1): + x1 = val + x2 = X2[i, j] + p = clf.decision_function([[x1, x2]]) + Z[i, j] = p[0] + +plt.figure(figsize=(4, 3)) +ax = plt.axes() +ax.contour( + X1, X2, Z, [-1.0, 0.0, 1.0], colors="k", linestyles=["dashed", "solid", "dashed"] +) +ax.scatter(X[:, 0], X[:, 1], c=Y, cmap="Paired") + +ax.axis("tight") + + +plt.show() diff --git a/_downloads/451c1c5b2ae289d91495af4fe116c29f/plot_plot_ext.ipynb b/_downloads/451c1c5b2ae289d91495af4fe116c29f/plot_plot_ext.ipynb new file mode 100644 index 000000000..8d08756f2 --- /dev/null +++ b/_downloads/451c1c5b2ae289d91495af4fe116c29f/plot_plot_ext.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot example vignette\n\nAn example of plots with matplotlib, and added annotations.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nn = 256\nX = np.linspace(0, 2, n)\nY = np.sin(2 * np.pi * X)\n\nplt.plot(X, Y, lw=2, color=\"violet\")\nplt.xlim(-0.2, 2.2)\nplt.xticks([])\nplt.ylim(-1.2, 1.2)\nplt.yticks([])\n\n\n# Add a title and a box around it\nfrom matplotlib.patches import FancyBboxPatch\n\nax = plt.gca()\nax.add_patch(\n FancyBboxPatch(\n (-0.05, 0.87),\n width=0.66,\n height=0.165,\n clip_on=False,\n boxstyle=\"square,pad=0\",\n zorder=3,\n facecolor=\"white\",\n alpha=1.0,\n transform=plt.gca().transAxes,\n )\n)\n\nplt.text(\n -0.05,\n 1.02,\n \" Regular Plot: plt.plot(...)\\n\",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"xx-large\",\n transform=plt.gca().transAxes,\n)\n\nplt.text(\n -0.05,\n 1.01,\n \"\\n\\n Plot lines and/or markers \",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"large\",\n transform=plt.gca().transAxes,\n)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/454b150a8e93ae641da180ff8e6ffc8e/plot_gridspec.py b/_downloads/454b150a8e93ae641da180ff8e6ffc8e/plot_gridspec.py new file mode 100644 index 000000000..c01e36af1 --- /dev/null +++ b/_downloads/454b150a8e93ae641da180ff8e6ffc8e/plot_gridspec.py @@ -0,0 +1,40 @@ +""" +GridSpec +========= + +An example demoing gridspec +""" + +import matplotlib.pyplot as plt +from matplotlib import gridspec + +plt.figure(figsize=(6, 4)) +G = gridspec.GridSpec(3, 3) + +axes_1 = plt.subplot(G[0, :]) +plt.xticks([]) +plt.yticks([]) +plt.text(0.5, 0.5, "Axes 1", ha="center", va="center", size=24, alpha=0.5) + +axes_2 = plt.subplot(G[1, :-1]) +plt.xticks([]) +plt.yticks([]) +plt.text(0.5, 0.5, "Axes 2", ha="center", va="center", size=24, alpha=0.5) + +axes_3 = plt.subplot(G[1:, -1]) +plt.xticks([]) +plt.yticks([]) +plt.text(0.5, 0.5, "Axes 3", ha="center", va="center", size=24, alpha=0.5) + +axes_4 = plt.subplot(G[-1, 0]) +plt.xticks([]) +plt.yticks([]) +plt.text(0.5, 0.5, "Axes 4", ha="center", va="center", size=24, alpha=0.5) + +axes_5 = plt.subplot(G[-1, -2]) +plt.xticks([]) +plt.yticks([]) +plt.text(0.5, 0.5, "Axes 5", ha="center", va="center", size=24, alpha=0.5) + +plt.tight_layout() +plt.show() diff --git a/_downloads/45b41d9cb7387d3614f3d43ce35efc8e/plot_linewidth.ipynb b/_downloads/45b41d9cb7387d3614f3d43ce35efc8e/plot_linewidth.ipynb new file mode 100644 index 000000000..31cbee501 --- /dev/null +++ b/_downloads/45b41d9cb7387d3614f3d43ce35efc8e/plot_linewidth.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Linewidth\n\nPlot various linewidth with matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nsize = 256, 16\ndpi = 72.0\nfigsize = size[0] / float(dpi), size[1] / float(dpi)\nfig = plt.figure(figsize=figsize, dpi=dpi)\nfig.patch.set_alpha(0)\nplt.axes((0, 0.1, 1, 0.8), frameon=False)\n\nfor i in range(1, 11):\n plt.plot([i, i], [0, 1], color=\"b\", lw=i / 2.0)\n\nplt.xlim(0, 11)\nplt.ylim(0, 1)\nplt.xticks([])\nplt.yticks([])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/45f2b2cb5f7266be0973a01be655609e/plot_find_object.ipynb b/_downloads/45f2b2cb5f7266be0973a01be655609e/plot_find_object.ipynb new file mode 100644 index 000000000..4698b70da --- /dev/null +++ b/_downloads/45f2b2cb5f7266be0973a01be655609e/plot_find_object.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Find the bounding box of an object\n\nThis example shows how to extract the bounding box of the largest object\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nrng = np.random.default_rng(27446968)\nn = 10\nl = 256\nim = np.zeros((l, l))\npoints = l * rng.random((2, n**2))\nim[(points[0]).astype(int), (points[1]).astype(int)] = 1\nim = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n))\n\nmask = im > im.mean()\n\nlabel_im, nb_labels = sp.ndimage.label(mask)\n\n# Find the largest connected component\nsizes = sp.ndimage.sum(mask, label_im, range(nb_labels + 1))\nmask_size = sizes < 1000\nremove_pixel = mask_size[label_im]\nlabel_im[remove_pixel] = 0\nlabels = np.unique(label_im)\nlabel_im = np.searchsorted(labels, label_im)\n\n# Now that we have only one connected component, extract it's bounding box\nslice_x, slice_y = sp.ndimage.find_objects(label_im == 4)[0]\nroi = im[slice_x, slice_y]\n\nplt.figure(figsize=(4, 2))\nplt.axes((0, 0, 1, 1))\nplt.imshow(roi)\nplt.axis(\"off\")\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/465405450f0a521572c03b5f7f73f3eb/plot_camera_uint.zip b/_downloads/465405450f0a521572c03b5f7f73f3eb/plot_camera_uint.zip new file mode 100644 index 000000000..05508bb50 Binary files /dev/null and b/_downloads/465405450f0a521572c03b5f7f73f3eb/plot_camera_uint.zip differ diff --git a/_downloads/4680b2134a3806f49add0bd6b2da88ae/plot_quiver.py b/_downloads/4680b2134a3806f49add0bd6b2da88ae/plot_quiver.py new file mode 100644 index 000000000..694be2506 --- /dev/null +++ b/_downloads/4680b2134a3806f49add0bd6b2da88ae/plot_quiver.py @@ -0,0 +1,27 @@ +""" +Plotting a vector field: quiver +================================ + +A simple example showing how to plot a vector field (quiver) with +matplotlib. +""" + +import numpy as np +import matplotlib.pyplot as plt + +n = 8 +X, Y = np.mgrid[0:n, 0:n] +T = np.arctan2(Y - n / 2.0, X - n / 2.0) +R = 10 + np.sqrt((Y - n / 2.0) ** 2 + (X - n / 2.0) ** 2) +U, V = R * np.cos(T), R * np.sin(T) + +plt.axes((0.025, 0.025, 0.95, 0.95)) +plt.quiver(X, Y, U, V, R, alpha=0.5) +plt.quiver(X, Y, U, V, edgecolor="k", facecolor="None", linewidth=0.5) + +plt.xlim(-1, n) +plt.xticks([]) +plt.ylim(-1, n) +plt.yticks([]) + +plt.show() diff --git a/_downloads/46c77e1812ada32c099b266b64707647/plot_variance_linear_regr.ipynb b/_downloads/46c77e1812ada32c099b266b64707647/plot_variance_linear_regr.ipynb new file mode 100644 index 000000000..a26ac1b3c --- /dev/null +++ b/_downloads/46c77e1812ada32c099b266b64707647/plot_variance_linear_regr.ipynb @@ -0,0 +1,115 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot variance and regularization in linear models\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n\n# Smaller figures\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = (3, 2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We consider the situation where we have only 2 data point\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "X = np.c_[0.5, 1].T\ny = [0.5, 1]\nX_test = np.c_[0, 2].T" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Without noise, as linear regression fits the data perfectly\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn import linear_model\n\nregr = linear_model.LinearRegression()\nregr.fit(X, y)\nplt.plot(X, y, \"o\")\nplt.plot(X_test, regr.predict(X_test))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In real life situation, we have noise (e.g. measurement noise) in our data:\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "rng = np.random.default_rng(27446968)\nfor _ in range(6):\n noisy_X = X + np.random.normal(loc=0, scale=0.1, size=X.shape)\n plt.plot(noisy_X, y, \"o\")\n regr.fit(noisy_X, y)\n plt.plot(X_test, regr.predict(X_test))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "As we can see, our linear model captures and amplifies the noise in the\ndata. It displays a lot of variance.\n\nWe can use another linear estimator that uses regularization, the\n:class:`~sklearn.linear_model.Ridge` estimator. This estimator\nregularizes the coefficients by shrinking them to zero, under the\nassumption that very high correlations are often spurious. The alpha\nparameter controls the amount of shrinkage used.\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "regr = linear_model.Ridge(alpha=0.1)\nnp.random.seed(0)\nfor _ in range(6):\n noisy_X = X + np.random.normal(loc=0, scale=0.1, size=X.shape)\n plt.plot(noisy_X, y, \"o\")\n regr.fit(noisy_X, y)\n plt.plot(X_test, regr.predict(X_test))\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/46d89cb209d4d5e36d1c93b42114c040/plot_numpy_array.py b/_downloads/46d89cb209d4d5e36d1c93b42114c040/plot_numpy_array.py new file mode 100644 index 000000000..4a8a32417 --- /dev/null +++ b/_downloads/46d89cb209d4d5e36d1c93b42114c040/plot_numpy_array.py @@ -0,0 +1,29 @@ +""" +Image manipulation and NumPy arrays +==================================== + +This example shows how to do image manipulation using common NumPy arrays +tricks. + +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +face = sp.datasets.face(gray=True) +face[10:13, 20:23] +face[100:120] = 255 + +lx, ly = face.shape +X, Y = np.ogrid[0:lx, 0:ly] +mask = (X - lx / 2) ** 2 + (Y - ly / 2) ** 2 > lx * ly / 4 +face[mask] = 0 +face[range(400), range(400)] = 255 + +plt.figure(figsize=(3, 3)) +plt.axes((0, 0, 1, 1)) +plt.imshow(face, cmap="gray") +plt.axis("off") + +plt.show() diff --git a/_downloads/48e917272ddf79f61a813480b16c5e08/plot_normal_distribution.py b/_downloads/48e917272ddf79f61a813480b16c5e08/plot_normal_distribution.py new file mode 100644 index 000000000..0ee0f2d76 --- /dev/null +++ b/_downloads/48e917272ddf79f61a813480b16c5e08/plot_normal_distribution.py @@ -0,0 +1,26 @@ +""" +======================================= +Normal distribution: histogram and PDF +======================================= + +Explore the normal distribution: a histogram built from samples and the +PDF (probability density function). +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +dist = sp.stats.norm(loc=0, scale=1) # standard normal distribution +sample = dist.rvs(size=100000) # "random variate sample" +plt.hist( + sample, + bins=51, # group the observations into 50 bins + density=True, # normalize the frequencies + label="normalized histogram", +) + +x = np.linspace(-5, 5) # possible values of the random variable +plt.plot(x, dist.pdf(x), label="PDF") +plt.legend() +plt.show() diff --git a/_downloads/492deb27eee8af1c4534d84382edbb4c/plot_exercise_5.zip b/_downloads/492deb27eee8af1c4534d84382edbb4c/plot_exercise_5.zip new file mode 100644 index 000000000..1e36b13cc Binary files /dev/null and b/_downloads/492deb27eee8af1c4534d84382edbb4c/plot_exercise_5.zip differ diff --git a/_downloads/497e72158c0c5fa166e16abf97cb4eab/plot_color.ipynb b/_downloads/497e72158c0c5fa166e16abf97cb4eab/plot_color.ipynb new file mode 100644 index 000000000..3acac892c --- /dev/null +++ b/_downloads/497e72158c0c5fa166e16abf97cb4eab/plot_color.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# The colors matplotlib line plots\n\nAn example demoing the various colors taken by matplotlib's plot.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nsize = 256, 16\ndpi = 72.0\nfigsize = size[0] / float(dpi), size[1] / float(dpi)\nfig = plt.figure(figsize=figsize, dpi=dpi)\nfig.patch.set_alpha(0)\nplt.axes((0, 0.1, 1, 0.8), frameon=False)\n\nfor i in range(1, 11):\n plt.plot([i, i], [0, 1], lw=1.5)\n\nplt.xlim(0, 11)\nplt.xticks([])\nplt.yticks([])\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/4b1bc57c0666a27490966a93b27b56b1/plot_digits_simple_classif.zip b/_downloads/4b1bc57c0666a27490966a93b27b56b1/plot_digits_simple_classif.zip new file mode 100644 index 000000000..f3d3f4e11 Binary files /dev/null and b/_downloads/4b1bc57c0666a27490966a93b27b56b1/plot_digits_simple_classif.zip differ diff --git a/_downloads/4b3e9dd17996ec9d8268ced6b0e2529f/plot_tsne.zip b/_downloads/4b3e9dd17996ec9d8268ced6b0e2529f/plot_tsne.zip new file mode 100644 index 000000000..dcc13a3c1 Binary files /dev/null and b/_downloads/4b3e9dd17996ec9d8268ced6b0e2529f/plot_tsne.zip differ diff --git a/_downloads/4b964de78726fcda97b79aec972de984/plot_bias_variance.py b/_downloads/4b964de78726fcda97b79aec972de984/plot_bias_variance.py new file mode 100644 index 000000000..b3cb2822c --- /dev/null +++ b/_downloads/4b964de78726fcda97b79aec972de984/plot_bias_variance.py @@ -0,0 +1,146 @@ +""" +==================================== +Bias and variance of polynomial fit +==================================== + +Demo overfitting, underfitting, and validation and learning curves with +polynomial regression. + +Fit polynomes of different degrees to a dataset: for too small a degree, +the model *underfits*, while for too large a degree, it overfits. + +""" + +import numpy as np +import matplotlib.pyplot as plt + + +def generating_func(x, rng=None, error=0.5): + rng = np.random.default_rng(rng) + return rng.normal(10 - 1.0 / (x + 0.1), error) + + +############################################################ +# A polynomial regression +from sklearn.pipeline import make_pipeline +from sklearn.linear_model import LinearRegression +from sklearn.preprocessing import PolynomialFeatures + +############################################################ +# A simple figure to illustrate the problem + +n_samples = 8 + +rng = np.random.default_rng(27446968) +x = 10 ** np.linspace(-2, 0, n_samples) +y = generating_func(x, rng=rng) + +x_test = np.linspace(-0.2, 1.2, 1000) + +titles = ["d = 1 (under-fit; high bias)", "d = 2", "d = 6 (over-fit; high variance)"] +degrees = [1, 2, 6] + +fig = plt.figure(figsize=(9, 3.5)) +fig.subplots_adjust(left=0.06, right=0.98, bottom=0.15, top=0.85, wspace=0.05) + +for i, d in enumerate(degrees): + ax = fig.add_subplot(131 + i, xticks=[], yticks=[]) + ax.scatter(x, y, marker="x", c="k", s=50) + + model = make_pipeline(PolynomialFeatures(d), LinearRegression()) + model.fit(x[:, np.newaxis], y) + ax.plot(x_test, model.predict(x_test[:, np.newaxis]), "-b") + + ax.set_xlim(-0.2, 1.2) + ax.set_ylim(0, 12) + ax.set_xlabel("house size") + if i == 0: + ax.set_ylabel("price") + + ax.set_title(titles[i]) + + +############################################################ +# Generate a larger dataset +from sklearn.model_selection import train_test_split + +n_samples = 200 +test_size = 0.4 +error = 1.0 + +# randomly sample the data +x = rng.random(n_samples) +y = generating_func(x, rng=rng, error=error) + +# split into training, validation, and testing sets. +x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=test_size) + +# show the training and validation sets +plt.figure(figsize=(6, 4)) +plt.scatter(x_train, y_train, color="red", label="Training set") +plt.scatter(x_test, y_test, color="blue", label="Test set") +plt.title("The data") +plt.legend(loc="best") + +############################################################ +# Plot a validation curve +from sklearn.model_selection import validation_curve + +degrees = list(range(1, 21)) + +model = make_pipeline(PolynomialFeatures(), LinearRegression()) + +# The parameter to vary is the "degrees" on the pipeline step +# "polynomialfeatures" +train_scores, validation_scores = validation_curve( + model, + x[:, np.newaxis], + y, + param_name="polynomialfeatures__degree", + param_range=degrees, +) + +# Plot the mean train error and validation error across folds +plt.figure(figsize=(6, 4)) +plt.plot(degrees, validation_scores.mean(axis=1), lw=2, label="cross-validation") +plt.plot(degrees, train_scores.mean(axis=1), lw=2, label="training") + +plt.legend(loc="best") +plt.xlabel("degree of fit") +plt.ylabel("explained variance") +plt.title("Validation curve") +plt.tight_layout() + + +############################################################ +# Learning curves +############################################################ +# +# Plot train and test error with an increasing number of samples + +# A learning curve for d=1, 5, 15 +for d in [1, 5, 15]: + model = make_pipeline(PolynomialFeatures(degree=d), LinearRegression()) + + from sklearn.model_selection import learning_curve + + train_sizes, train_scores, validation_scores = learning_curve( + model, x[:, np.newaxis], y, train_sizes=np.logspace(-1, 0, 20) + ) + + # Plot the mean train error and validation error across folds + plt.figure(figsize=(6, 4)) + plt.plot( + train_sizes, validation_scores.mean(axis=1), lw=2, label="cross-validation" + ) + plt.plot(train_sizes, train_scores.mean(axis=1), lw=2, label="training") + plt.ylim(ymin=-0.1, ymax=1) + + plt.legend(loc="best") + plt.xlabel("number of train samples") + plt.ylabel("explained variance") + plt.title("Learning curve (degree=%i)" % d) + plt.tight_layout() + + +plt.show() diff --git a/_downloads/4bb6211a9bc4842f9f48c9dad33b5464/2_4_mandelbrot.py b/_downloads/4bb6211a9bc4842f9f48c9dad33b5464/2_4_mandelbrot.py new file mode 100644 index 000000000..c7b942ada --- /dev/null +++ b/_downloads/4bb6211a9bc4842f9f48c9dad33b5464/2_4_mandelbrot.py @@ -0,0 +1,34 @@ +""" +Compute the Mandelbrot fractal +""" + +import numpy as np +import matplotlib.pyplot as plt +from numpy import newaxis + + +def compute_mandelbrot(N_max, some_threshold, nx, ny): + # A grid of c-values + x = np.linspace(-2, 1, nx) + y = np.linspace(-1.5, 1.5, ny) + + c = x[:, newaxis] + 1j * y[newaxis, :] + + # Mandelbrot iteration + + z = c + for j in range(N_max): + z = z**2 + c + + mandelbrot_set = abs(z) < some_threshold + + return mandelbrot_set + + +# Save + +mandelbrot_set = compute_mandelbrot(50, 50.0, 601, 401) + +plt.imshow(mandelbrot_set.T, extent=[-2, 1, -1.5, 1.5]) # type: ignore[arg-type] +plt.gray() +plt.savefig("mandelbrot.png") diff --git a/_downloads/4c07decd125a49910282d878149a5872/plot_fftpack.zip b/_downloads/4c07decd125a49910282d878149a5872/plot_fftpack.zip new file mode 100644 index 000000000..644f4143b Binary files /dev/null and b/_downloads/4c07decd125a49910282d878149a5872/plot_fftpack.zip differ diff --git a/_downloads/4c12a3bf44dfa1d29ce0a7c95ed3def3/plot_svm_non_linear.py b/_downloads/4c12a3bf44dfa1d29ce0a7c95ed3def3/plot_svm_non_linear.py new file mode 100644 index 000000000..f5c246b42 --- /dev/null +++ b/_downloads/4c12a3bf44dfa1d29ce0a7c95ed3def3/plot_svm_non_linear.py @@ -0,0 +1,124 @@ +""" +Example of linear and non-linear models +======================================== + +This is an example plot from the tutorial which accompanies an explanation +of the support vector machine GUI. +""" + +import numpy as np +import matplotlib.pyplot as plt + +from sklearn import svm + + +rng = np.random.default_rng(27446968) + +############################################################################## +# data that is linearly separable + + +def linear_model(rseed=42, n_samples=30): + "Generate data according to a linear model" + np.random.seed(rseed) + + data = np.random.normal(0, 10, (n_samples, 2)) + data[: n_samples // 2] -= 15 + data[n_samples // 2 :] += 15 + + labels = np.ones(n_samples) + labels[: n_samples // 2] = -1 + + return data, labels + + +X, y = linear_model() +clf = svm.SVC(kernel="linear") +clf.fit(X, y) + +plt.figure(figsize=(6, 4)) +ax = plt.subplot(111, xticks=[], yticks=[]) +ax.scatter(X[:, 0], X[:, 1], c=y, cmap="bone") + +ax.scatter( + clf.support_vectors_[:, 0], + clf.support_vectors_[:, 1], + s=80, + edgecolors="k", + facecolors="none", +) + +delta = 1 +y_min, y_max = -50, 50 +x_min, x_max = -50, 50 +x = np.arange(x_min, x_max + delta, delta) +y = np.arange(y_min, y_max + delta, delta) +X1, X2 = np.meshgrid(x, y) +Z = clf.decision_function(np.c_[X1.ravel(), X2.ravel()]) +Z = Z.reshape(X1.shape) + +ax.contour( + X1, X2, Z, [-1.0, 0.0, 1.0], colors="k", linestyles=["dashed", "solid", "dashed"] +) + + +############################################################################## +# data with a non-linear separation + + +def nonlinear_model(rseed=27446968, n_samples=30): + rng = np.random.default_rng(rseed) + + radius = 40 * rng.random(n_samples) + far_pts = radius > 20 + radius[far_pts] *= 1.2 + radius[~far_pts] *= 1.1 + + theta = rng.random(n_samples) * np.pi * 2 + + data = np.empty((n_samples, 2)) + data[:, 0] = radius * np.cos(theta) + data[:, 1] = radius * np.sin(theta) + + labels = np.ones(n_samples) + labels[far_pts] = -1 + + return data, labels + + +X, y = nonlinear_model() +clf = svm.SVC(kernel="rbf", gamma=0.001, coef0=0, degree=3) +clf.fit(X, y) + +plt.figure(figsize=(6, 4)) +ax = plt.subplot(1, 1, 1, xticks=[], yticks=[]) +ax.scatter(X[:, 0], X[:, 1], c=y, cmap="bone", zorder=2) + +ax.scatter( + clf.support_vectors_[:, 0], + clf.support_vectors_[:, 1], + s=80, + edgecolors="k", + facecolors="none", +) + +delta = 1 +y_min, y_max = -50, 50 +x_min, x_max = -50, 50 +x = np.arange(x_min, x_max + delta, delta) +y = np.arange(y_min, y_max + delta, delta) +X1, X2 = np.meshgrid(x, y) +Z = clf.decision_function(np.c_[X1.ravel(), X2.ravel()]) +Z = Z.reshape(X1.shape) + +ax.contour( + X1, + X2, + Z, + [-1.0, 0.0, 1.0], + colors="k", + linestyles=["dashed", "solid", "dashed"], + zorder=1, +) + +plt.show() diff --git a/_downloads/4d4764abd24c8089a081acb3901425c6/plot_filter_coins.ipynb b/_downloads/4d4764abd24c8089a081acb3901425c6/plot_filter_coins.ipynb new file mode 100644 index 000000000..561c6d88f --- /dev/null +++ b/_downloads/4d4764abd24c8089a081acb3901425c6/plot_filter_coins.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Various denoising filters\n\nThis example compares several denoising filters available in scikit-image:\na Gaussian filter, a median filter, and total variation denoising.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\nfrom skimage import data\nfrom skimage import filters\nfrom skimage import restoration\n\ncoins = data.coins()\ngaussian_filter_coins = filters.gaussian(coins, sigma=2)\nmed_filter_coins = filters.median(coins, np.ones((3, 3)))\ntv_filter_coins = restoration.denoise_tv_chambolle(coins, weight=0.1)\n\nplt.figure(figsize=(16, 4))\nplt.subplot(141)\nplt.imshow(coins[10:80, 300:370], cmap=\"gray\", interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.title(\"Image\")\nplt.subplot(142)\nplt.imshow(gaussian_filter_coins[10:80, 300:370], cmap=\"gray\", interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.title(\"Gaussian filter\")\nplt.subplot(143)\nplt.imshow(med_filter_coins[10:80, 300:370], cmap=\"gray\", interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.title(\"Median filter\")\nplt.subplot(144)\nplt.imshow(tv_filter_coins[10:80, 300:370], cmap=\"gray\", interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.title(\"TV filter\")\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/4da30e3eda4e9e783805cf750fed9e68/plot_camera_uint.ipynb b/_downloads/4da30e3eda4e9e783805cf750fed9e68/plot_camera_uint.ipynb new file mode 100644 index 000000000..bc4f6fb33 --- /dev/null +++ b/_downloads/4da30e3eda4e9e783805cf750fed9e68/plot_camera_uint.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Integers can overflow\n\nAn illustration of overflow problem arising when working with integers\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\nfrom skimage import data\n\ncamera = data.camera()\ncamera_multiply = 3 * camera\n\nplt.figure(figsize=(8, 4))\nplt.subplot(121)\nplt.imshow(camera, cmap=\"gray\", interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.subplot(122)\nplt.imshow(camera_multiply, cmap=\"gray\", interpolation=\"nearest\")\nplt.axis(\"off\")\n\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/4f1450472e9d811b9dc59f37e0801af2/plot_compare_classifiers.ipynb b/_downloads/4f1450472e9d811b9dc59f37e0801af2/plot_compare_classifiers.ipynb new file mode 100644 index 000000000..432d18b23 --- /dev/null +++ b/_downloads/4f1450472e9d811b9dc59f37e0801af2/plot_compare_classifiers.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Compare classifiers on the digits data\n\nCompare the performance of a variety of classifiers on a test set for the\ndigits data.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn import model_selection, datasets, metrics\nfrom sklearn.svm import LinearSVC\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.neighbors import KNeighborsClassifier\n\ndigits = datasets.load_digits()\nX = digits.data\ny = digits.target\nX_train, X_test, y_train, y_test = model_selection.train_test_split(\n X, y, test_size=0.25, random_state=0\n)\n\nfor Model in [LinearSVC, GaussianNB, KNeighborsClassifier]:\n clf = Model().fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n print(f\"{Model.__name__}: {metrics.f1_score(y_test, y_pred, average='macro')}\")\n\nprint(\"------------------\")\n\n# test SVC loss\nfor loss in [\"hinge\", \"squared_hinge\"]:\n clf = LinearSVC(loss=loss).fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n print(\n f\"LinearSVC(loss='{loss}'): {metrics.f1_score(y_test, y_pred, average='macro')}\"\n )\n\nprint(\"-------------------\")\n\n# test the number of neighbors\nfor n_neighbors in range(1, 11):\n clf = KNeighborsClassifier(n_neighbors=n_neighbors).fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n print(\n f\"KNeighbors(n_neighbors={n_neighbors}): {metrics.f1_score(y_test, y_pred, average='macro')}\"\n )" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/4f3d68627814bf98dd4d720de992fbb8/plot_curve_fit.zip b/_downloads/4f3d68627814bf98dd4d720de992fbb8/plot_curve_fit.zip new file mode 100644 index 000000000..0bef29bae Binary files /dev/null and b/_downloads/4f3d68627814bf98dd4d720de992fbb8/plot_curve_fit.zip differ diff --git a/_downloads/4fb373e037de48b6a3f962765cbb09e0/plot_compare_optimizers.ipynb b/_downloads/4fb373e037de48b6a3f962765cbb09e0/plot_compare_optimizers.ipynb new file mode 100644 index 000000000..226a3251f --- /dev/null +++ b/_downloads/4fb373e037de48b6a3f962765cbb09e0/plot_compare_optimizers.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plotting the comparison of optimizers\n\nPlots the results from the comparison of optimizers.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import pickle\nimport sys\n\nimport numpy as np\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nresults = pickle.load(\n open(f\"helper/compare_optimizers_py{sys.version_info[0]}.pkl\", \"rb\")\n)\nn_methods = len(list(results.values())[0][\"Rosenbrock \"])\nn_dims = len(results)\n\nsymbols = \"o>*Ds\"\n\nplt.figure(1, figsize=(10, 4))\nplt.clf()\n\nnipy_spectral = matplotlib.colormaps[\"nipy_spectral\"]\ncolors = nipy_spectral(np.linspace(0, 1, n_dims))[:, :3]\n\nmethod_names = list(list(results.values())[0][\"Rosenbrock \"].keys())\nmethod_names.sort(key=lambda x: x[::-1], reverse=True)\n\nfor n_dim_index, ((n_dim, n_dim_bench), color) in enumerate(\n zip(sorted(results.items()), colors, strict=True)\n):\n for (cost_name, cost_bench), symbol in zip(\n sorted(n_dim_bench.items()), symbols, strict=True\n ):\n for (\n method_index,\n method_name,\n ) in enumerate(method_names):\n this_bench = cost_bench[method_name]\n bench = np.mean(this_bench)\n plt.semilogy(\n [\n method_index + 0.1 * n_dim_index,\n ],\n [\n bench,\n ],\n marker=symbol,\n color=color,\n )\n\n# Create a legend for the problem type\nfor cost_name, symbol in zip(sorted(n_dim_bench.keys()), symbols, strict=True):\n plt.semilogy(\n [\n -10,\n ],\n [\n 0,\n ],\n symbol,\n color=\".5\",\n label=cost_name,\n )\n\nplt.xticks(np.arange(n_methods), method_names, size=11)\nplt.xlim(-0.2, n_methods - 0.5)\nplt.legend(loc=\"best\", numpoints=1, handletextpad=0, prop={\"size\": 12}, frameon=False)\nplt.ylabel(\"# function calls (a.u.)\")\n\n# Create a second legend for the problem dimensionality\nplt.twinx()\n\nfor n_dim, color in zip(sorted(results.keys()), colors, strict=True):\n plt.plot(\n [\n -10,\n ],\n [\n 0,\n ],\n \"o\",\n color=color,\n label=\"# dim: %i\" % n_dim,\n )\nplt.legend(\n loc=(0.47, 0.07),\n numpoints=1,\n handletextpad=0,\n prop={\"size\": 12},\n frameon=False,\n ncol=2,\n)\nplt.xlim(-0.2, n_methods - 0.5)\n\nplt.xticks(np.arange(n_methods), method_names)\nplt.yticks(())\n\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/4fff26f4b1f5d352d0711217e8db0fa9/auto_examples_jupyter.zip b/_downloads/4fff26f4b1f5d352d0711217e8db0fa9/auto_examples_jupyter.zip new file mode 100644 index 000000000..e871e721b Binary files /dev/null and b/_downloads/4fff26f4b1f5d352d0711217e8db0fa9/auto_examples_jupyter.zip differ diff --git a/_downloads/5001b0ec7d8a21b03661b571fb5452b1/plot_smooth.py b/_downloads/5001b0ec7d8a21b03661b571fb5452b1/plot_smooth.py new file mode 100644 index 000000000..073810d8c --- /dev/null +++ b/_downloads/5001b0ec7d8a21b03661b571fb5452b1/plot_smooth.py @@ -0,0 +1,33 @@ +""" +Smooth vs non-smooth +===================== + +Draws a figure to explain smooth versus non smooth optimization. +""" + +import numpy as np +import matplotlib.pyplot as plt + +x = np.linspace(-1.5, 1.5, 101) + +# A smooth function +plt.figure(1, figsize=(3, 2.5)) +plt.clf() + +plt.plot(x, np.sqrt(0.2 + x**2), linewidth=2) +plt.text(-1, 0, "$f$", size=20) + +plt.ylim(ymin=-0.2) +plt.axis("off") +plt.tight_layout() + +# A non-smooth function +plt.figure(2, figsize=(3, 2.5)) +plt.clf() +plt.plot(x, np.abs(x), linewidth=2) +plt.text(-1, 0, "$f$", size=20) + +plt.ylim(ymin=-0.2) +plt.axis("off") +plt.tight_layout() +plt.show() diff --git a/_downloads/5113d594da334330b9f6cb3bb9c47323/plot_mew.zip b/_downloads/5113d594da334330b9f6cb3bb9c47323/plot_mew.zip new file mode 100644 index 000000000..a79b31f78 Binary files /dev/null and b/_downloads/5113d594da334330b9f6cb3bb9c47323/plot_mew.zip differ diff --git a/_downloads/5126d55e56bcf5d6d166c6d8959bc2e1/plot_gumbell_wind_speed_prediction.py b/_downloads/5126d55e56bcf5d6d166c6d8959bc2e1/plot_gumbell_wind_speed_prediction.py new file mode 100644 index 000000000..a632610b0 --- /dev/null +++ b/_downloads/5126d55e56bcf5d6d166c6d8959bc2e1/plot_gumbell_wind_speed_prediction.py @@ -0,0 +1,39 @@ +""" +The Gumbell distribution +========================= + +Generate the exercise results on the Gumbell distribution +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + + +def gumbell_dist(arr): + return -np.log(-np.log(arr)) + + +years_nb = 21 +wspeeds = np.load("sprog-windspeeds.npy") +max_speeds = np.array([arr.max() for arr in np.array_split(wspeeds, years_nb)]) +sorted_max_speeds = np.sort(max_speeds) + +cprob = (np.arange(years_nb, dtype=np.float32) + 1) / (years_nb + 1) +gprob = gumbell_dist(cprob) +speed_spline = sp.interpolate.UnivariateSpline(gprob, sorted_max_speeds, k=1) +nprob = gumbell_dist(np.linspace(1e-3, 1 - 1e-3, 100)) +fitted_max_speeds = speed_spline(nprob) + +fifty_prob = gumbell_dist(49.0 / 50.0) +fifty_wind = speed_spline(fifty_prob) + +plt.figure() +plt.plot(sorted_max_speeds, gprob, "o") +plt.plot(fitted_max_speeds, nprob, "g--") +plt.plot([fifty_wind], [fifty_prob], "o", ms=8.0, mfc="y", mec="y") +plt.plot([fifty_wind, fifty_wind], [plt.axis()[2], fifty_prob], "k--") +plt.text(35, -1, rf"$V_{{50}} = {fifty_wind:.2f} \, m/s$") +plt.xlabel("Annual wind speed maxima [$m/s$]") +plt.ylabel("Gumbell cumulative probability") +plt.show() diff --git a/_downloads/5169ddefd7709854c60e0462350ae47e/plot_normal_distribution.ipynb b/_downloads/5169ddefd7709854c60e0462350ae47e/plot_normal_distribution.ipynb new file mode 100644 index 000000000..b7a0189ea --- /dev/null +++ b/_downloads/5169ddefd7709854c60e0462350ae47e/plot_normal_distribution.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Normal distribution: histogram and PDF\n\nExplore the normal distribution: a histogram built from samples and the\nPDF (probability density function).\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\ndist = sp.stats.norm(loc=0, scale=1) # standard normal distribution\nsample = dist.rvs(size=100000) # \"random variate sample\"\nplt.hist(\n sample,\n bins=51, # group the observations into 50 bins\n density=True, # normalize the frequencies\n label=\"normalized histogram\",\n)\n\nx = np.linspace(-5, 5) # possible values of the random variable\nplt.plot(x, dist.pdf(x), label=\"PDF\")\nplt.legend()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/51b003312c250820df2a9666ad752b93/plot_plot3d-2.zip b/_downloads/51b003312c250820df2a9666ad752b93/plot_plot3d-2.zip new file mode 100644 index 000000000..ea7c21ab6 Binary files /dev/null and b/_downloads/51b003312c250820df2a9666ad752b93/plot_plot3d-2.zip differ diff --git a/_downloads/520b4ca957d03d3bc6d207e0b1e41abd/plot_exercise_7.zip b/_downloads/520b4ca957d03d3bc6d207e0b1e41abd/plot_exercise_7.zip new file mode 100644 index 000000000..df00058ec Binary files /dev/null and b/_downloads/520b4ca957d03d3bc6d207e0b1e41abd/plot_exercise_7.zip differ diff --git a/_downloads/5263d8d059888a36ff0d575899d24165/plot_contour_ext.ipynb b/_downloads/5263d8d059888a36ff0d575899d24165/plot_contour_ext.ipynb new file mode 100644 index 000000000..fec20eadf --- /dev/null +++ b/_downloads/5263d8d059888a36ff0d575899d24165/plot_contour_ext.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Display the contours of a function\n\nAn example demoing how to plot the contours of a function, with\nadditional layout tweaks.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef f(x, y):\n return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2)\n\n\nn = 256\nx = np.linspace(-3, 3, n)\ny = np.linspace(-3, 3, n)\nX, Y = np.meshgrid(x, y)\n\nplt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=\"hot\")\nC = plt.contour(X, Y, f(X, Y), 8, colors=\"black\", linewidth=0.5)\nplt.clabel(C, inline=1, fontsize=10)\nplt.xticks([])\nplt.yticks([])\n\n\n# Add a title and a box around it\nfrom matplotlib.patches import FancyBboxPatch\n\nax = plt.gca()\nax.add_patch(\n FancyBboxPatch(\n (-0.05, 0.87),\n width=0.66,\n height=0.165,\n clip_on=False,\n boxstyle=\"square,pad=0\",\n zorder=3,\n facecolor=\"white\",\n alpha=1.0,\n transform=plt.gca().transAxes,\n )\n)\n\nplt.text(\n -0.05,\n 1.02,\n \" Contour Plot: plt.contour(..)\\n\",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"xx-large\",\n transform=plt.gca().transAxes,\n)\n\nplt.text(\n -0.05,\n 1.01,\n \"\\n\\n Draw contour lines and filled contours \",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"large\",\n transform=plt.gca().transAxes,\n)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/52a4590525b8afc778856cbf04b1a2d0/plot_GMM.py b/_downloads/52a4590525b8afc778856cbf04b1a2d0/plot_GMM.py new file mode 100644 index 000000000..afc85be62 --- /dev/null +++ b/_downloads/52a4590525b8afc778856cbf04b1a2d0/plot_GMM.py @@ -0,0 +1,54 @@ +""" +Segmentation with Gaussian mixture models +========================================= + +This example performs a Gaussian mixture model analysis of the image +histogram to find the right thresholds for separating foreground from +background. + +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt +from sklearn.mixture import GaussianMixture + +rng = np.random.default_rng(27446968) +n = 10 +l = 256 +im = np.zeros((l, l)) +points = l * rng.random((2, n**2)) +im[(points[0]).astype(int), (points[1]).astype(int)] = 1 +im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) + +mask = (im > im.mean()).astype(float) + + +img = mask + 0.3 * rng.normal(size=mask.shape) + +hist, bin_edges = np.histogram(img, bins=60) +bin_centers = 0.5 * (bin_edges[:-1] + bin_edges[1:]) + +classif = GaussianMixture(n_components=2) +classif.fit(img.reshape((img.size, 1))) + +threshold = np.mean(classif.means_) +binary_img = img > threshold + + +plt.figure(figsize=(11, 4)) + +plt.subplot(131) +plt.imshow(img) +plt.axis("off") +plt.subplot(132) +plt.plot(bin_centers, hist, lw=2) +plt.axvline(0.5, color="r", ls="--", lw=2) +plt.text(0.57, 0.8, "histogram", fontsize=20, transform=plt.gca().transAxes) +plt.yticks([]) +plt.subplot(133) +plt.imshow(binary_img, cmap="gray", interpolation="nearest") +plt.axis("off") + +plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) +plt.show() diff --git a/_downloads/52ce146440fee9a2f72d2905a4de2a10/plot_non_bounds_constraints.ipynb b/_downloads/52ce146440fee9a2f72d2905a4de2a10/plot_non_bounds_constraints.ipynb new file mode 100644 index 000000000..65a92f6a0 --- /dev/null +++ b/_downloads/52ce146440fee9a2f72d2905a4de2a10/plot_non_bounds_constraints.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Optimization with constraints\n\nAn example showing how to do optimization with general constraints using\nSLSQP and cobyla.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy as sp\n\nx, y = np.mgrid[-2.03:4.2:0.04, -1.6:3.2:0.04] # type: ignore[misc]\nx = x.T\ny = y.T\n\nplt.figure(1, figsize=(3, 2.5))\nplt.clf()\nplt.axes((0, 0, 1, 1))\n\ncontours = plt.contour(\n np.sqrt((x - 3) ** 2 + (y - 2) ** 2),\n extent=[-2.03, 4.2, -1.6, 3.2],\n cmap=\"gnuplot\",\n)\nplt.clabel(contours, inline=1, fmt=\"%1.1f\", fontsize=14)\nplt.plot([-1.5, 0, 1.5, 0, -1.5], [0, 1.5, 0, -1.5, 0], \"k\", linewidth=2)\nplt.fill_between([-1.5, 0, 1.5], [0, -1.5, 0], [0, 1.5, 0], color=\".8\")\nplt.axvline(0, color=\"k\")\nplt.axhline(0, color=\"k\")\n\nplt.text(-0.9, 2.8, \"$x_2$\", size=20)\nplt.text(3.6, -0.6, \"$x_1$\", size=20)\nplt.axis(\"tight\")\nplt.axis(\"off\")\n\n# And now plot the optimization path\naccumulator = []\n\n\ndef f(x):\n # Store the list of function calls\n accumulator.append(x)\n return np.sqrt((x[0] - 3) ** 2 + (x[1] - 2) ** 2)\n\n\ndef constraint(x):\n return np.atleast_1d(1.5 - np.sum(np.abs(x)))\n\n\nsp.optimize.minimize(\n f, np.array([0, 0]), method=\"SLSQP\", constraints={\"fun\": constraint, \"type\": \"ineq\"}\n)\n\naccumulated = np.array(accumulator)\nplt.plot(accumulated[:, 0], accumulated[:, 1])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/53773cf0c55149a4f54eca8effc54bc9/plot_axes-2.py b/_downloads/53773cf0c55149a4f54eca8effc54bc9/plot_axes-2.py new file mode 100644 index 000000000..97a33dc02 --- /dev/null +++ b/_downloads/53773cf0c55149a4f54eca8effc54bc9/plot_axes-2.py @@ -0,0 +1,39 @@ +""" +Axes +==== + +This example shows various axes command to position matplotlib axes. + +""" + +import matplotlib.pyplot as plt + +plt.axes((0.1, 0.1, 0.5, 0.5)) +plt.xticks([]) +plt.yticks([]) +plt.text( + 0.1, 0.1, "axes((0.1, 0.1, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5 +) + +plt.axes((0.2, 0.2, 0.5, 0.5)) +plt.xticks([]) +plt.yticks([]) +plt.text( + 0.1, 0.1, "axes((0.2, 0.2, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5 +) + +plt.axes((0.3, 0.3, 0.5, 0.5)) +plt.xticks([]) +plt.yticks([]) +plt.text( + 0.1, 0.1, "axes((0.3, 0.3, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5 +) + +plt.axes((0.4, 0.4, 0.5, 0.5)) +plt.xticks([]) +plt.yticks([]) +plt.text( + 0.1, 0.1, "axes((0.4, 0.4, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5 +) + +plt.show() diff --git a/_downloads/53d861872f5ac3e2fae5c7bcd492df2c/plot_imshow_ext.zip b/_downloads/53d861872f5ac3e2fae5c7bcd492df2c/plot_imshow_ext.zip new file mode 100644 index 000000000..2011a8539 Binary files /dev/null and b/_downloads/53d861872f5ac3e2fae5c7bcd492df2c/plot_imshow_ext.zip differ diff --git a/_downloads/53f29d480c529c2231e1eaba4a90fb2a/plot_dash_joinstyle.py b/_downloads/53f29d480c529c2231e1eaba4a90fb2a/plot_dash_joinstyle.py new file mode 100644 index 000000000..ec488f989 --- /dev/null +++ b/_downloads/53f29d480c529c2231e1eaba4a90fb2a/plot_dash_joinstyle.py @@ -0,0 +1,48 @@ +""" +Dash join style +================ + +Example demoing the dash join style. +""" + +import numpy as np +import matplotlib.pyplot as plt + +size = 256, 16 +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = plt.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +plt.axes((0, 0, 1, 1), frameon=False) + +plt.plot( + np.arange(3), + [0, 1, 0], + color="blue", + dashes=[12, 5], + linewidth=8, + dash_joinstyle="miter", +) +plt.plot( + 4 + np.arange(3), + [0, 1, 0], + color="blue", + dashes=[12, 5], + linewidth=8, + dash_joinstyle="bevel", +) +plt.plot( + 8 + np.arange(3), + [0, 1, 0], + color="blue", + dashes=[12, 5], + linewidth=8, + dash_joinstyle="round", +) + +plt.xlim(0, 12) +plt.ylim(-1, 2) +plt.xticks([]) +plt.yticks([]) + +plt.show() diff --git a/_downloads/54bcaaf868b390d8ed3b91b6b9ae526c/plot_watershed_segmentation.ipynb b/_downloads/54bcaaf868b390d8ed3b91b6b9ae526c/plot_watershed_segmentation.ipynb new file mode 100644 index 000000000..da8efd673 --- /dev/null +++ b/_downloads/54bcaaf868b390d8ed3b91b6b9ae526c/plot_watershed_segmentation.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Watershed segmentation\n\nThis example shows how to do segmentation with watershed.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nfrom skimage.segmentation import watershed\nfrom skimage.feature import peak_local_max\nimport matplotlib.pyplot as plt\nimport scipy as sp\n\n# Generate an initial image with two overlapping circles\nx, y = np.indices((80, 80))\nx1, y1, x2, y2 = 28, 28, 44, 52\nr1, r2 = 16, 20\nmask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1**2\nmask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2**2\nimage = np.logical_or(mask_circle1, mask_circle2)\n# Now we want to separate the two objects in image\n# Generate the markers as local maxima of the distance\n# to the background\ndistance = sp.ndimage.distance_transform_edt(image)\npeak_idx = peak_local_max(distance, footprint=np.ones((3, 3)), labels=image)\npeak_mask = np.zeros_like(distance, dtype=bool)\npeak_mask[tuple(peak_idx.T)] = True\nmarkers = sp.ndimage.label(peak_mask)[0]\nlabels = watershed(-distance, markers, mask=image)\n\nplt.figure(figsize=(9, 3.5))\nplt.subplot(131)\nplt.imshow(image, cmap=\"gray\", interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.subplot(132)\nplt.imshow(-distance, interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.subplot(133)\nplt.imshow(labels, cmap=\"nipy_spectral\", interpolation=\"nearest\")\nplt.axis(\"off\")\n\nplt.subplots_adjust(hspace=0.01, wspace=0.01, top=1, bottom=0, left=0, right=1)\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/5524df9d0609739d2e1739dc3c6654a1/plot_segmentations.zip b/_downloads/5524df9d0609739d2e1739dc3c6654a1/plot_segmentations.zip new file mode 100644 index 000000000..b687b7ccf Binary files /dev/null and b/_downloads/5524df9d0609739d2e1739dc3c6654a1/plot_segmentations.zip differ diff --git a/_downloads/557ec3c6e69977eba8bd0862fed720a7/plot_solve_ivp_simple.zip b/_downloads/557ec3c6e69977eba8bd0862fed720a7/plot_solve_ivp_simple.zip new file mode 100644 index 000000000..b8e205d38 Binary files /dev/null and b/_downloads/557ec3c6e69977eba8bd0862fed720a7/plot_solve_ivp_simple.zip differ diff --git a/_downloads/5649b4dd9a420d1d970ff266e5863a13/plot_separator.ipynb b/_downloads/5649b4dd9a420d1d970ff266e5863a13/plot_separator.ipynb new file mode 100644 index 000000000..381a6dd26 --- /dev/null +++ b/_downloads/5649b4dd9a420d1d970ff266e5863a13/plot_separator.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Simple picture of the formal problem of machine learning\n\nThis example generates simple synthetic data ploints and shows a\nseparating hyperplane on them.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.datasets import make_blobs\n\n# we create 50 separable synthetic points\nX, Y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.60)\n\n# fit the model\nclf = SGDClassifier(loss=\"hinge\", alpha=0.01, fit_intercept=True)\nclf.fit(X, Y)\n\n# plot the line, the points, and the nearest vectors to the plane\nxx = np.linspace(-1, 5, 10)\nyy = np.linspace(-1, 5, 10)\n\nX1, X2 = np.meshgrid(xx, yy)\nZ = np.empty(X1.shape)\nfor (i, j), val in np.ndenumerate(X1):\n x1 = val\n x2 = X2[i, j]\n p = clf.decision_function([[x1, x2]])\n Z[i, j] = p[0]\n\nplt.figure(figsize=(4, 3))\nax = plt.axes()\nax.contour(\n X1, X2, Z, [-1.0, 0.0, 1.0], colors=\"k\", linestyles=[\"dashed\", \"solid\", \"dashed\"]\n)\nax.scatter(X[:, 0], X[:, 1], c=Y, cmap=\"Paired\")\n\nax.axis(\"tight\")\n\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/564e4b22f13ad57fb726424eeb91fd87/plot_iris_analysis.zip b/_downloads/564e4b22f13ad57fb726424eeb91fd87/plot_iris_analysis.zip new file mode 100644 index 000000000..1e4047081 Binary files /dev/null and b/_downloads/564e4b22f13ad57fb726424eeb91fd87/plot_iris_analysis.zip differ diff --git a/_downloads/5695b63b6b5f05e364a24c4d056c1c02/plot_image_transform.py b/_downloads/5695b63b6b5f05e364a24c4d056c1c02/plot_image_transform.py new file mode 100644 index 000000000..c2978faed --- /dev/null +++ b/_downloads/5695b63b6b5f05e364a24c4d056c1c02/plot_image_transform.py @@ -0,0 +1,47 @@ +""" +============================================ +Plot geometrical transformations on images +============================================ + +Demo geometrical transformations of images. +""" + +# Load some data +import scipy as sp + +face = sp.datasets.face(gray=True) + +# Apply a variety of transformations +import matplotlib.pyplot as plt + +shifted_face = sp.ndimage.shift(face, (50, 50)) +shifted_face2 = sp.ndimage.shift(face, (50, 50), mode="nearest") +rotated_face = sp.ndimage.rotate(face, 30) +cropped_face = face[50:-50, 50:-50] +zoomed_face = sp.ndimage.zoom(face, 2) +zoomed_face.shape + +plt.figure(figsize=(15, 3)) +plt.subplot(151) +plt.imshow(shifted_face, cmap="gray") +plt.axis("off") + +plt.subplot(152) +plt.imshow(shifted_face2, cmap="gray") +plt.axis("off") + +plt.subplot(153) +plt.imshow(rotated_face, cmap="gray") +plt.axis("off") + +plt.subplot(154) +plt.imshow(cropped_face, cmap="gray") +plt.axis("off") + +plt.subplot(155) +plt.imshow(zoomed_face, cmap="gray") +plt.axis("off") + +plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99) + +plt.show() diff --git a/_downloads/56b7a0ac184553d0e2a8e898f2685420/plot_find_edges.py b/_downloads/56b7a0ac184553d0e2a8e898f2685420/plot_find_edges.py new file mode 100644 index 000000000..02816698d --- /dev/null +++ b/_downloads/56b7a0ac184553d0e2a8e898f2685420/plot_find_edges.py @@ -0,0 +1,52 @@ +""" +Finding edges with Sobel filters +================================== + +The Sobel filter is one of the simplest way of finding edges. +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +rng = np.random.default_rng(27446968) + +im = np.zeros((256, 256)) +im[64:-64, 64:-64] = 1 + +im = sp.ndimage.rotate(im, 15, mode="constant") +im = sp.ndimage.gaussian_filter(im, 8) + +sx = sp.ndimage.sobel(im, axis=0, mode="constant") +sy = sp.ndimage.sobel(im, axis=1, mode="constant") +sob = np.hypot(sx, sy) + +plt.figure(figsize=(16, 5)) +plt.subplot(141) +plt.imshow(im, cmap="gray") +plt.axis("off") +plt.title("square", fontsize=20) +plt.subplot(142) +plt.imshow(sx) +plt.axis("off") +plt.title("Sobel (x direction)", fontsize=20) +plt.subplot(143) +plt.imshow(sob) +plt.axis("off") +plt.title("Sobel filter", fontsize=20) + +im += 0.07 * rng.random(im.shape) + +sx = sp.ndimage.sobel(im, axis=0, mode="constant") +sy = sp.ndimage.sobel(im, axis=1, mode="constant") +sob = np.hypot(sx, sy) + +plt.subplot(144) +plt.imshow(sob) +plt.axis("off") +plt.title("Sobel for noisy image", fontsize=20) + + +plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=0.9) + +plt.show() diff --git a/_downloads/5785e8fe0271fadf4db4da9b5e62e4c7/plot_pandas.ipynb b/_downloads/5785e8fe0271fadf4db4da9b5e62e4c7/plot_pandas.ipynb new file mode 100644 index 000000000..58da24288 --- /dev/null +++ b/_downloads/5785e8fe0271fadf4db4da9b5e62e4c7/plot_pandas.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plotting simple quantities of a pandas dataframe\n\nThis example loads from a CSV file data with mixed numerical and\ncategorical entries, and plots a few quantities, separately for females\nand males, thanks to the pandas integrated plotting tool (that uses\nmatplotlib behind the scene).\n\nSee http://pandas.pydata.org/pandas-docs/stable/visualization.html\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import pandas\n\ndata = pandas.read_csv(\"brain_size.csv\", sep=\";\", na_values=\".\")\n\n# Box plots of different columns for each gender\ngroupby_gender = data.groupby(\"Gender\")\ngroupby_gender.boxplot(column=[\"FSIQ\", \"VIQ\", \"PIQ\"])\n\nfrom pandas import plotting\n\n# Scatter matrices for different columns\nplotting.scatter_matrix(data[[\"Weight\", \"Height\", \"MRI_Count\"]])\nplotting.scatter_matrix(data[[\"PIQ\", \"VIQ\", \"FSIQ\"]])\n\nimport matplotlib.pyplot as plt\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/57e2fdfa6dc847f08b04a9f311671894/ScientificPythonLectures.pdf b/_downloads/57e2fdfa6dc847f08b04a9f311671894/ScientificPythonLectures.pdf new file mode 100644 index 000000000..84d39b067 Binary files /dev/null and b/_downloads/57e2fdfa6dc847f08b04a9f311671894/ScientificPythonLectures.pdf differ diff --git a/_downloads/595e57d413cc007302206f7483b15e69/plot_sobel.zip b/_downloads/595e57d413cc007302206f7483b15e69/plot_sobel.zip new file mode 100644 index 000000000..4cec2a2e1 Binary files /dev/null and b/_downloads/595e57d413cc007302206f7483b15e69/plot_sobel.zip differ diff --git a/_downloads/5a4d1f404ac03526e4c4059781b1d638/plot_blur.ipynb b/_downloads/5a4d1f404ac03526e4c4059781b1d638/plot_blur.ipynb new file mode 100644 index 000000000..b9a7de77d --- /dev/null +++ b/_downloads/5a4d1f404ac03526e4c4059781b1d638/plot_blur.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Blurring of images\n\nAn example showing various processes that blur an image.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import scipy as sp\nimport matplotlib.pyplot as plt\n\nface = sp.datasets.face(gray=True)\nblurred_face = sp.ndimage.gaussian_filter(face, sigma=3)\nvery_blurred = sp.ndimage.gaussian_filter(face, sigma=5)\nlocal_mean = sp.ndimage.uniform_filter(face, size=11)\n\nplt.figure(figsize=(9, 3))\nplt.subplot(131)\nplt.imshow(blurred_face, cmap=\"gray\")\nplt.axis(\"off\")\nplt.subplot(132)\nplt.imshow(very_blurred, cmap=\"gray\")\nplt.axis(\"off\")\nplt.subplot(133)\nplt.imshow(local_mean, cmap=\"gray\")\nplt.axis(\"off\")\n\nplt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.01, right=0.99)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/5a9cb398d5c77b9dc1ffa679a8056369/plot_clean_morpho.py b/_downloads/5a9cb398d5c77b9dc1ffa679a8056369/plot_clean_morpho.py new file mode 100644 index 000000000..cdcd1dc49 --- /dev/null +++ b/_downloads/5a9cb398d5c77b9dc1ffa679a8056369/plot_clean_morpho.py @@ -0,0 +1,54 @@ +""" +Cleaning segmentation with mathematical morphology +=================================================== + +An example showing how to clean segmentation with mathematical +morphology: removing small regions and holes. + +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +rng = np.random.default_rng(27446968) +n = 10 +l = 256 +im = np.zeros((l, l)) +points = l * rng.random((2, n**2)) +im[(points[0]).astype(int), (points[1]).astype(int)] = 1 +im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) + +mask = (im > im.mean()).astype(float) + + +img = mask + 0.3 * rng.normal(size=mask.shape) + +binary_img = img > 0.5 + +# Remove small white regions +open_img = sp.ndimage.binary_opening(binary_img) +# Remove small black hole +close_img = sp.ndimage.binary_closing(open_img) + +plt.figure(figsize=(12, 3)) + +l = 128 + +plt.subplot(141) +plt.imshow(binary_img[:l, :l], cmap="gray") +plt.axis("off") +plt.subplot(142) +plt.imshow(open_img[:l, :l], cmap="gray") +plt.axis("off") +plt.subplot(143) +plt.imshow(close_img[:l, :l], cmap="gray") +plt.axis("off") +plt.subplot(144) +plt.imshow(mask[:l, :l], cmap="gray") +plt.contour(close_img[:l, :l], [0.5], linewidths=2, colors="r") +plt.axis("off") + +plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) + +plt.show() diff --git a/_downloads/5c9b6c91d363172b2dce61e28d5879dd/plot_regression.zip b/_downloads/5c9b6c91d363172b2dce61e28d5879dd/plot_regression.zip new file mode 100644 index 000000000..8f92166b4 Binary files /dev/null and b/_downloads/5c9b6c91d363172b2dce61e28d5879dd/plot_regression.zip differ diff --git a/_downloads/5d7da85c6aafec5f729274e641021c8b/plot_maskedstats.ipynb b/_downloads/5d7da85c6aafec5f729274e641021c8b/plot_maskedstats.ipynb new file mode 100644 index 000000000..e36313784 --- /dev/null +++ b/_downloads/5d7da85c6aafec5f729274e641021c8b/plot_maskedstats.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Example: Masked statistics\n\nPlot a masked statistics\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\ndata = np.loadtxt(\"../../../../data/populations.txt\")\npopulations = np.ma.masked_array(data[:, 1:]) # type: ignore[var-annotated]\nyear = data[:, 0]\n\nbad_years = ((year >= 1903) & (year <= 1910)) | ((year >= 1917) & (year <= 1918))\npopulations[bad_years, 0] = np.ma.masked\npopulations[bad_years, 1] = np.ma.masked\n\nplt.plot(year, populations, \"o-\")\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/5e5f820328df6aafbaf0c667db5d3af0/elephant.png b/_downloads/5e5f820328df6aafbaf0c667db5d3af0/elephant.png new file mode 100644 index 000000000..bc9ab4352 Binary files /dev/null and b/_downloads/5e5f820328df6aafbaf0c667db5d3af0/elephant.png differ diff --git a/_downloads/5ecf93c2bfe0bad28d5ac1df487a73ee/plot_spectral_clustering.ipynb b/_downloads/5ecf93c2bfe0bad28d5ac1df487a73ee/plot_spectral_clustering.ipynb new file mode 100644 index 000000000..ca6d657e8 --- /dev/null +++ b/_downloads/5ecf93c2bfe0bad28d5ac1df487a73ee/plot_spectral_clustering.ipynb @@ -0,0 +1,72 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Segmentation with spectral clustering\n\nThis example uses spectral clustering to do segmentation.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.feature_extraction import image\nfrom sklearn.cluster import spectral_clustering" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "l = 100\nx, y = np.indices((l, l))\n\ncenter1 = (28, 24)\ncenter2 = (40, 50)\ncenter3 = (67, 58)\ncenter4 = (24, 70)\n\nradius1, radius2, radius3, radius4 = 16, 14, 15, 14\n\ncircle1 = (x - center1[0]) ** 2 + (y - center1[1]) ** 2 < radius1**2\ncircle2 = (x - center2[0]) ** 2 + (y - center2[1]) ** 2 < radius2**2\ncircle3 = (x - center3[0]) ** 2 + (y - center3[1]) ** 2 < radius3**2\ncircle4 = (x - center4[0]) ** 2 + (y - center4[1]) ** 2 < radius4**2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "4 circles\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "img = circle1 + circle2 + circle3 + circle4\nmask = img.astype(bool)\nimg = img.astype(float)\n\nrng = np.random.default_rng(27446968)\nimg += 1 + 0.2 * rng.normal(size=img.shape)\n\n# Convert the image into a graph with the value of the gradient on the\n# edges.\ngraph = image.img_to_graph(img, mask=mask)\n\n# Take a decreasing function of the gradient: we take it weakly\n# dependent from the gradient the segmentation is close to a voronoi\ngraph.data = np.exp(-graph.data / graph.data.std())\n\n# Force the solver to be arpack, since amg is numerically\n# unstable on this example\nlabels = spectral_clustering(graph, n_clusters=4)\nlabel_im = -np.ones(mask.shape)\nlabel_im[mask] = labels\n\nplt.figure(figsize=(6, 3))\nplt.subplot(121)\nplt.imshow(img, cmap=\"nipy_spectral\", interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.subplot(122)\nplt.imshow(label_im, cmap=\"nipy_spectral\", interpolation=\"nearest\")\nplt.axis(\"off\")\n\nplt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.01, right=0.99)\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/5f5388bc3ac394d2433dd5ed63b144a8/plot_mandelbrot.ipynb b/_downloads/5f5388bc3ac394d2433dd5ed63b144a8/plot_mandelbrot.ipynb new file mode 100644 index 000000000..ed81f744e --- /dev/null +++ b/_downloads/5f5388bc3ac394d2433dd5ed63b144a8/plot_mandelbrot.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Mandelbrot set\n\nCompute the Mandelbrot fractal and plot it\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy import newaxis\nimport warnings\n\n\ndef compute_mandelbrot(N_max, some_threshold, nx, ny):\n # A grid of c-values\n x = np.linspace(-2, 1, nx)\n y = np.linspace(-1.5, 1.5, ny)\n\n c = x[:, newaxis] + 1j * y[newaxis, :]\n\n # Mandelbrot iteration\n\n z = c\n\n # The code below overflows in many regions of the x-y grid, suppress\n # warnings temporarily\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n for j in range(N_max):\n z = z**2 + c\n mandelbrot_set = abs(z) < some_threshold\n\n return mandelbrot_set\n\n\nmandelbrot_set = compute_mandelbrot(50, 50.0, 601, 401)\n\nplt.imshow(mandelbrot_set.T, extent=(-2, 1, -1.5, 1.5))\nplt.gray()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/5f7ceb076c39ab46f3fc2acbb5f45609/plot_exercise_5.ipynb b/_downloads/5f7ceb076c39ab46f3fc2acbb5f45609/plot_exercise_5.ipynb new file mode 100644 index 000000000..8ae4b0ab3 --- /dev/null +++ b/_downloads/5f7ceb076c39ab46f3fc2acbb5f45609/plot_exercise_5.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Exercise 5\n\nExercise 5 with matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(8, 5), dpi=80)\nplt.subplot(111)\n\nX = np.linspace(-np.pi, np.pi, 256)\nS = np.sin(X)\nC = np.cos(X)\n\nplt.plot(X, C, color=\"blue\", linewidth=2.5, linestyle=\"-\")\nplt.plot(X, S, color=\"red\", linewidth=2.5, linestyle=\"-\")\n\nplt.xlim(X.min() * 1.1, X.max() * 1.1)\nplt.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi])\n\nplt.ylim(C.min() * 1.1, C.max() * 1.1)\nplt.yticks([-1, 0, +1])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/5f7dee6ae0ab518da904e101b0cd966f/plot_gradient_descent.zip b/_downloads/5f7dee6ae0ab518da904e101b0cd966f/plot_gradient_descent.zip new file mode 100644 index 000000000..21228ff7a Binary files /dev/null and b/_downloads/5f7dee6ae0ab518da904e101b0cd966f/plot_gradient_descent.zip differ diff --git a/_downloads/5fb7d5a26865b522cf480c08aef31139/plot_solid_capstyle.ipynb b/_downloads/5fb7d5a26865b522cf480c08aef31139/plot_solid_capstyle.ipynb new file mode 100644 index 000000000..0b73b7ead --- /dev/null +++ b/_downloads/5fb7d5a26865b522cf480c08aef31139/plot_solid_capstyle.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Solid cap style\n\nAn example demoing the solide cap style in matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nsize = 256, 16\ndpi = 72.0\nfigsize = size[0] / float(dpi), size[1] / float(dpi)\nfig = plt.figure(figsize=figsize, dpi=dpi)\nfig.patch.set_alpha(0)\nplt.axes((0, 0, 1, 1), frameon=False)\n\nplt.plot(np.arange(4), np.ones(4), color=\"blue\", linewidth=8, solid_capstyle=\"butt\")\n\nplt.plot(\n 5 + np.arange(4), np.ones(4), color=\"blue\", linewidth=8, solid_capstyle=\"round\"\n)\n\nplt.plot(\n 10 + np.arange(4),\n np.ones(4),\n color=\"blue\",\n linewidth=8,\n solid_capstyle=\"projecting\",\n)\n\nplt.xlim(0, 14)\nplt.xticks([])\nplt.yticks([])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/613ac3bf0ee500a06e4e98fc37c69f01/plot_synthetic_data.py b/_downloads/613ac3bf0ee500a06e4e98fc37c69f01/plot_synthetic_data.py new file mode 100644 index 000000000..1c5e47ce0 --- /dev/null +++ b/_downloads/613ac3bf0ee500a06e4e98fc37c69f01/plot_synthetic_data.py @@ -0,0 +1,37 @@ +""" +Synthetic data +=============== + +The example generates and displays simple synthetic data. +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +rng = np.random.default_rng(27446968) +n = 10 +l = 256 +im = np.zeros((l, l)) +points = l * rng.random((2, n**2)) +im[(points[0]).astype(int), (points[1]).astype(int)] = 1 +im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) + +mask = im > im.mean() + +label_im, nb_labels = sp.ndimage.label(mask) + +plt.figure(figsize=(9, 3)) + +plt.subplot(131) +plt.imshow(im) +plt.axis("off") +plt.subplot(132) +plt.imshow(mask, cmap="gray") +plt.axis("off") +plt.subplot(133) +plt.imshow(label_im, cmap="nipy_spectral") +plt.axis("off") + +plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1) +plt.show() diff --git a/_downloads/626ac1bee11135cc834c11c9a8cd74af/plot_fftpack.py b/_downloads/626ac1bee11135cc834c11c9a8cd74af/plot_fftpack.py new file mode 100644 index 000000000..476a373ff --- /dev/null +++ b/_downloads/626ac1bee11135cc834c11c9a8cd74af/plot_fftpack.py @@ -0,0 +1,98 @@ +""" +============================================= +Plotting and manipulating FFTs for filtering +============================================= + +Plot the power of the FFT of a signal and inverse FFT back to reconstruct +a signal. + +This example demonstrate :func:`scipy.fft.fft`, +:func:`scipy.fft.fftfreq` and :func:`scipy.fft.ifft`. It +implements a basic filter that is very suboptimal, and should not be +used. + +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +############################################################ +# Generate the signal +############################################################ + +# Seed the random number generator +rng = np.random.default_rng(27446968) + +time_step = 0.02 +period = 5.0 + +time_vec = np.arange(0, 20, time_step) +sig = np.sin(2 * np.pi / period * time_vec) + 0.5 * rng.normal(size=time_vec.size) + +plt.figure(figsize=(6, 5)) +plt.plot(time_vec, sig, label="Original signal") + +############################################################ +# Compute and plot the power +############################################################ + +# The FFT of the signal +sig_fft = sp.fft.fft(sig) + +# And the power (sig_fft is of complex dtype) +power = np.abs(sig_fft) ** 2 + +# The corresponding frequencies +sample_freq = sp.fft.fftfreq(sig.size, d=time_step) + +# Plot the FFT power +plt.figure(figsize=(6, 5)) +plt.plot(sample_freq, power) +plt.xlabel("Frequency [Hz]") +plt.ylabel("plower") + +# Find the peak frequency: we can focus on only the positive frequencies +pos_mask = np.where(sample_freq > 0) +freqs = sample_freq[pos_mask] +peak_freq = freqs[power[pos_mask].argmax()] + +# Check that it does indeed correspond to the frequency that we generate +# the signal with +np.allclose(peak_freq, 1.0 / period) + +# An inner plot to show the peak frequency +axes = plt.axes((0.55, 0.3, 0.3, 0.5)) +plt.title("Peak frequency") +plt.plot(freqs[:8], power[pos_mask][:8]) +plt.setp(axes, yticks=[]) + +# scipy.signal.find_peaks_cwt can also be used for more advanced +# peak detection + +############################################################ +# Remove all the high frequencies +############################################################ +# +# We now remove all the high frequencies and transform back from +# frequencies to signal. + +high_freq_fft = sig_fft.copy() +high_freq_fft[np.abs(sample_freq) > peak_freq] = 0 +filtered_sig = sp.fft.ifft(high_freq_fft) + +plt.figure(figsize=(6, 5)) +plt.plot(time_vec, sig, label="Original signal") +plt.plot(time_vec, filtered_sig, linewidth=3, label="Filtered signal") +plt.xlabel("Time [s]") +plt.ylabel("Amplitude") + +plt.legend(loc="best") + +############################################################ +# +# **Note** This is actually a bad way of creating a filter: such brutal +# cut-off in frequency space does not control distortion on the signal. +# +# Filters should be created using the SciPy filter design code +plt.show() diff --git a/_downloads/62a0b2972561cb7da02b2da7e03e46b7/max-speeds.npy b/_downloads/62a0b2972561cb7da02b2da7e03e46b7/max-speeds.npy new file mode 100644 index 000000000..176d285cb Binary files /dev/null and b/_downloads/62a0b2972561cb7da02b2da7e03e46b7/max-speeds.npy differ diff --git a/_downloads/62ea0e3c02dc58bd8c7f4b91fe30ffd7/plot_pca.py b/_downloads/62ea0e3c02dc58bd8c7f4b91fe30ffd7/plot_pca.py new file mode 100644 index 000000000..e09f420e4 --- /dev/null +++ b/_downloads/62ea0e3c02dc58bd8c7f4b91fe30ffd7/plot_pca.py @@ -0,0 +1,37 @@ +""" +=============== +Demo PCA in 2D +=============== + +""" + +############################################################ +# Load the iris data +from sklearn import datasets + +iris = datasets.load_iris() +X = iris.data +y = iris.target + +############################################################ +# Fit a PCA +from sklearn.decomposition import PCA + +pca = PCA(n_components=2, whiten=True) +pca.fit(X) + +############################################################ +# Project the data in 2D +X_pca = pca.transform(X) + +############################################################ +# Visualize the data +target_ids = range(len(iris.target_names)) + +import matplotlib.pyplot as plt + +plt.figure(figsize=(6, 5)) +for i, c, label in zip(target_ids, "rgbcmykw", iris.target_names, strict=False): + plt.scatter(X_pca[y == i, 0], X_pca[y == i, 1], c=c, label=label) +plt.legend() +plt.show() diff --git a/_downloads/62edd5b69bad35322a403fadba3b3924/lobpcg_sakurai.py b/_downloads/62edd5b69bad35322a403fadba3b3924/lobpcg_sakurai.py new file mode 100644 index 000000000..33445ade1 --- /dev/null +++ b/_downloads/62edd5b69bad35322a403fadba3b3924/lobpcg_sakurai.py @@ -0,0 +1,70 @@ +""" +LOBPCG: block-preconditioned solver +=================================== + +This example demos the LOBPCG block-preconditioned solver. +""" + +import time +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +np.set_printoptions(precision=8, linewidth=90) + + +def sakurai(n): + """Example taken from + T. Sakurai, H. Tadano, Y. Inadomi and U. Nagashima + A moment-based method for large-scale generalized eigenvalue problems + Appl. Num. Anal. Comp. Math. Vol. 1 No. 2 (2004) + """ + + A = sp.sparse.eye(n, n) + d0 = np.hstack([5, 6 * np.ones(n - 2), 5]) + d1 = -4 * np.ones(n) + d2 = np.ones(n) + B = sp.sparse.spdiags([d2, d1, d0, d1, d2], [-2, -1, 0, 1, 2], n, n) + + k = np.arange(1, n + 1) + w_ex = np.sort( + 1.0 / (16.0 * pow(np.cos(0.5 * k * np.pi / (n + 1)), 4)) + ) # exact eigenvalues + + return A, B, w_ex + + +m = 3 # Blocksize + +# +# Large scale +# +n = 2500 +A, B, w_ex = sakurai(n) # Mikota pair +X = np.random.random((n, m)) +data = [] +tt = time.perf_counter() +eigs, vecs, resnh = sp.sparse.linalg.lobpcg( + A, + X, + B, + tol=1e-6, + largest=False, + maxiter=2000, + retResidualNormsHistory=1, +) +data.append(time.perf_counter() - tt) +print("Results by LOBPCG for n=" + str(n)) +print() +print(eigs) +print() +print("Exact eigenvalues") +print() +print(w_ex[:m]) +print() +print("Elapsed time", data[0]) +plt.loglog(np.arange(1, n + 1), w_ex, "b.") +plt.xlabel(r"Number $i$") +plt.ylabel(r"$\lambda_i$") +plt.title("Eigenvalue distribution") +plt.show() diff --git a/_downloads/630cb5bb8a67f74cbae271e95bcc4dd1/plot_quiver.zip b/_downloads/630cb5bb8a67f74cbae271e95bcc4dd1/plot_quiver.zip new file mode 100644 index 000000000..c9b926d80 Binary files /dev/null and b/_downloads/630cb5bb8a67f74cbae271e95bcc4dd1/plot_quiver.zip differ diff --git a/_downloads/63670dd69e21223b8057b106b9b1ae06/plot_gridspec.ipynb b/_downloads/63670dd69e21223b8057b106b9b1ae06/plot_gridspec.ipynb new file mode 100644 index 000000000..ae4e436cb --- /dev/null +++ b/_downloads/63670dd69e21223b8057b106b9b1ae06/plot_gridspec.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# GridSpec\n\nAn example demoing gridspec\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\nfrom matplotlib import gridspec\n\nplt.figure(figsize=(6, 4))\nG = gridspec.GridSpec(3, 3)\n\naxes_1 = plt.subplot(G[0, :])\nplt.xticks([])\nplt.yticks([])\nplt.text(0.5, 0.5, \"Axes 1\", ha=\"center\", va=\"center\", size=24, alpha=0.5)\n\naxes_2 = plt.subplot(G[1, :-1])\nplt.xticks([])\nplt.yticks([])\nplt.text(0.5, 0.5, \"Axes 2\", ha=\"center\", va=\"center\", size=24, alpha=0.5)\n\naxes_3 = plt.subplot(G[1:, -1])\nplt.xticks([])\nplt.yticks([])\nplt.text(0.5, 0.5, \"Axes 3\", ha=\"center\", va=\"center\", size=24, alpha=0.5)\n\naxes_4 = plt.subplot(G[-1, 0])\nplt.xticks([])\nplt.yticks([])\nplt.text(0.5, 0.5, \"Axes 4\", ha=\"center\", va=\"center\", size=24, alpha=0.5)\n\naxes_5 = plt.subplot(G[-1, -2])\nplt.xticks([])\nplt.yticks([])\nplt.text(0.5, 0.5, \"Axes 5\", ha=\"center\", va=\"center\", size=24, alpha=0.5)\n\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/6419cedca82ae36cfc1609953be351dc/plot_fft_image_denoise.py b/_downloads/6419cedca82ae36cfc1609953be351dc/plot_fft_image_denoise.py new file mode 100644 index 000000000..a0c4890a2 --- /dev/null +++ b/_downloads/6419cedca82ae36cfc1609953be351dc/plot_fft_image_denoise.py @@ -0,0 +1,111 @@ +r""" +====================== +Image denoising by FFT +====================== + +Denoise an image (:download:`../../../../data/moonlanding.png`) by +implementing a blur with an FFT. + +Implements, via FFT, the following convolution: + +.. math:: + + f_1(t) = \int dt'\, K(t-t') f_0(t') + +.. math:: + + \tilde{f}_1(\omega) = \tilde{K}(\omega) \tilde{f}_0(\omega) + +""" + +############################################################ +# Read and plot the image +############################################################ +import numpy as np +import matplotlib.pyplot as plt + +im = plt.imread("../../../../data/moonlanding.png").astype(float) + +plt.figure() +plt.imshow(im, "gray") +plt.title("Original image") + + +############################################################ +# Compute the 2d FFT of the input image +############################################################ +import scipy as sp + +im_fft = sp.fft.fft2(im) + +# Show the results + + +def plot_spectrum(im_fft): + from matplotlib.colors import LogNorm + + # A logarithmic colormap + plt.imshow(np.abs(im_fft), norm=LogNorm(vmin=5)) + plt.colorbar() + + +plt.figure() +plot_spectrum(im_fft) +plt.title("Fourier transform") + +############################################################ +# Filter in FFT +############################################################ + +# In the lines following, we'll make a copy of the original spectrum and +# truncate coefficients. + +# Define the fraction of coefficients (in each direction) we keep +keep_fraction = 0.1 + +# Call ff a copy of the original transform. NumPy arrays have a copy +# method for this purpose. +im_fft2 = im_fft.copy() + +# Set r and c to be the number of rows and columns of the array. +r, c = im_fft2.shape + +# Set to zero all rows with indices between r*keep_fraction and +# r*(1-keep_fraction): +im_fft2[int(r * keep_fraction) : int(r * (1 - keep_fraction))] = 0 + +# Similarly with the columns: +im_fft2[:, int(c * keep_fraction) : int(c * (1 - keep_fraction))] = 0 + +plt.figure() +plot_spectrum(im_fft2) +plt.title("Filtered Spectrum") + + +############################################################ +# Reconstruct the final image +############################################################ + +# Reconstruct the denoised image from the filtered spectrum, keep only the +# real part for display. +im_new = sp.fft.ifft2(im_fft2).real + +plt.figure() +plt.imshow(im_new, "gray") +plt.title("Reconstructed Image") + + +############################################################ +# Easier and better: :func:`scipy.ndimage.gaussian_filter` +############################################################ +# +# Implementing filtering directly with FFTs is tricky and time consuming. +# We can use the Gaussian filter from :mod:`scipy.ndimage` + +im_blur = sp.ndimage.gaussian_filter(im, 4) + +plt.figure() +plt.imshow(im_blur, "gray") +plt.title("Blurred image") + +plt.show() diff --git a/_downloads/647962c1ccd68b0dd2e3097843b992c0/plot_polynomial_regression.zip b/_downloads/647962c1ccd68b0dd2e3097843b992c0/plot_polynomial_regression.zip new file mode 100644 index 000000000..e351b53f2 Binary files /dev/null and b/_downloads/647962c1ccd68b0dd2e3097843b992c0/plot_polynomial_regression.zip differ diff --git a/_downloads/6494c0af9327da6f966eb92a97a6839a/plot_exercise_1.py b/_downloads/6494c0af9327da6f966eb92a97a6839a/plot_exercise_1.py new file mode 100644 index 000000000..d4a05e17f --- /dev/null +++ b/_downloads/6494c0af9327da6f966eb92a97a6839a/plot_exercise_1.py @@ -0,0 +1,17 @@ +""" +Exercise 1 +=========== + +Solution of the exercise 1 with matplotlib. +""" + +import numpy as np +import matplotlib.pyplot as plt + +n = 256 +X = np.linspace(-np.pi, np.pi, 256) +C, S = np.cos(X), np.sin(X) +plt.plot(X, C) +plt.plot(X, S) + +plt.show() diff --git a/_downloads/64f2f3126e2e454a2df8870b2c3e01b5/plot_imshow.ipynb b/_downloads/64f2f3126e2e454a2df8870b2c3e01b5/plot_imshow.ipynb new file mode 100644 index 000000000..0ed7ddcfb --- /dev/null +++ b/_downloads/64f2f3126e2e454a2df8870b2c3e01b5/plot_imshow.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Imshow elaborate\n\nAn example demoing imshow and styling the figure.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef f(x, y):\n return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2)\n\n\nn = 10\nx = np.linspace(-3, 3, int(3.5 * n))\ny = np.linspace(-3, 3, int(3.0 * n))\nX, Y = np.meshgrid(x, y)\nZ = f(X, Y)\n\nplt.axes((0.025, 0.025, 0.95, 0.95))\nplt.imshow(Z, interpolation=\"nearest\", cmap=\"bone\", origin=\"lower\")\nplt.colorbar(shrink=0.92)\n\nplt.xticks([])\nplt.yticks([])\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/659af44a336cadf9645ba1624e216c57/plot_bias_variance.ipynb b/_downloads/659af44a336cadf9645ba1624e216c57/plot_bias_variance.ipynb new file mode 100644 index 000000000..9709ba62c --- /dev/null +++ b/_downloads/659af44a336cadf9645ba1624e216c57/plot_bias_variance.ipynb @@ -0,0 +1,133 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Bias and variance of polynomial fit\n\nDemo overfitting, underfitting, and validation and learning curves with\npolynomial regression.\n\nFit polynomes of different degrees to a dataset: for too small a degree,\nthe model *underfits*, while for too large a degree, it overfits.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef generating_func(x, rng=None, error=0.5):\n rng = np.random.default_rng(rng)\n return rng.normal(10 - 1.0 / (x + 0.1), error)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A polynomial regression\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.pipeline import make_pipeline\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import PolynomialFeatures" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A simple figure to illustrate the problem\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "n_samples = 8\n\nrng = np.random.default_rng(27446968)\nx = 10 ** np.linspace(-2, 0, n_samples)\ny = generating_func(x, rng=rng)\n\nx_test = np.linspace(-0.2, 1.2, 1000)\n\ntitles = [\"d = 1 (under-fit; high bias)\", \"d = 2\", \"d = 6 (over-fit; high variance)\"]\ndegrees = [1, 2, 6]\n\nfig = plt.figure(figsize=(9, 3.5))\nfig.subplots_adjust(left=0.06, right=0.98, bottom=0.15, top=0.85, wspace=0.05)\n\nfor i, d in enumerate(degrees):\n ax = fig.add_subplot(131 + i, xticks=[], yticks=[])\n ax.scatter(x, y, marker=\"x\", c=\"k\", s=50)\n\n model = make_pipeline(PolynomialFeatures(d), LinearRegression())\n model.fit(x[:, np.newaxis], y)\n ax.plot(x_test, model.predict(x_test[:, np.newaxis]), \"-b\")\n\n ax.set_xlim(-0.2, 1.2)\n ax.set_ylim(0, 12)\n ax.set_xlabel(\"house size\")\n if i == 0:\n ax.set_ylabel(\"price\")\n\n ax.set_title(titles[i])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Generate a larger dataset\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.model_selection import train_test_split\n\nn_samples = 200\ntest_size = 0.4\nerror = 1.0\n\n# randomly sample the data\nx = rng.random(n_samples)\ny = generating_func(x, rng=rng, error=error)\n\n# split into training, validation, and testing sets.\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=test_size)\n\n# show the training and validation sets\nplt.figure(figsize=(6, 4))\nplt.scatter(x_train, y_train, color=\"red\", label=\"Training set\")\nplt.scatter(x_test, y_test, color=\"blue\", label=\"Test set\")\nplt.title(\"The data\")\nplt.legend(loc=\"best\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Plot a validation curve\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.model_selection import validation_curve\n\ndegrees = list(range(1, 21))\n\nmodel = make_pipeline(PolynomialFeatures(), LinearRegression())\n\n# The parameter to vary is the \"degrees\" on the pipeline step\n# \"polynomialfeatures\"\ntrain_scores, validation_scores = validation_curve(\n model,\n x[:, np.newaxis],\n y,\n param_name=\"polynomialfeatures__degree\",\n param_range=degrees,\n)\n\n# Plot the mean train error and validation error across folds\nplt.figure(figsize=(6, 4))\nplt.plot(degrees, validation_scores.mean(axis=1), lw=2, label=\"cross-validation\")\nplt.plot(degrees, train_scores.mean(axis=1), lw=2, label=\"training\")\n\nplt.legend(loc=\"best\")\nplt.xlabel(\"degree of fit\")\nplt.ylabel(\"explained variance\")\nplt.title(\"Validation curve\")\nplt.tight_layout()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Learning curves\n\n Plot train and test error with an increasing number of samples\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# A learning curve for d=1, 5, 15\nfor d in [1, 5, 15]:\n model = make_pipeline(PolynomialFeatures(degree=d), LinearRegression())\n\n from sklearn.model_selection import learning_curve\n\n train_sizes, train_scores, validation_scores = learning_curve(\n model, x[:, np.newaxis], y, train_sizes=np.logspace(-1, 0, 20)\n )\n\n # Plot the mean train error and validation error across folds\n plt.figure(figsize=(6, 4))\n plt.plot(\n train_sizes, validation_scores.mean(axis=1), lw=2, label=\"cross-validation\"\n )\n plt.plot(train_sizes, train_scores.mean(axis=1), lw=2, label=\"training\")\n plt.ylim(ymin=-0.1, ymax=1)\n\n plt.legend(loc=\"best\")\n plt.xlabel(\"number of train samples\")\n plt.ylabel(\"explained variance\")\n plt.title(\"Learning curve (degree=%i)\" % d)\n plt.tight_layout()\n\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/66ba730fed168f2a44f551578587f9ea/plot_granulo.ipynb b/_downloads/66ba730fed168f2a44f551578587f9ea/plot_granulo.ipynb new file mode 100644 index 000000000..653e90189 --- /dev/null +++ b/_downloads/66ba730fed168f2a44f551578587f9ea/plot_granulo.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Granulometry\n\nThis example performs a simple granulometry analysis.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\n\ndef disk_structure(n):\n struct = np.zeros((2 * n + 1, 2 * n + 1))\n x, y = np.indices((2 * n + 1, 2 * n + 1))\n mask = (x - n) ** 2 + (y - n) ** 2 <= n**2\n struct[mask] = 1\n return struct.astype(bool)\n\n\ndef granulometry(data, sizes=None):\n s = max(data.shape)\n if sizes is None:\n sizes = range(1, s / 2, 2)\n granulo = [\n sp.ndimage.binary_opening(data, structure=disk_structure(n)).sum()\n for n in sizes\n ]\n return granulo\n\n\nrng = np.random.default_rng(27446968)\nn = 10\nl = 256\nim = np.zeros((l, l))\npoints = l * rng.random((2, n**2))\nim[(points[0]).astype(int), (points[1]).astype(int)] = 1\nim = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n))\n\nmask = im > im.mean()\n\ngranulo = granulometry(mask, sizes=np.arange(2, 19, 4))\n\nplt.figure(figsize=(6, 2.2))\n\nplt.subplot(121)\nplt.imshow(mask, cmap=\"gray\")\nopened = sp.ndimage.binary_opening(mask, structure=disk_structure(10))\nopened_more = sp.ndimage.binary_opening(mask, structure=disk_structure(14))\nplt.contour(opened, [0.5], colors=\"b\", linewidths=2)\nplt.contour(opened_more, [0.5], colors=\"r\", linewidths=2)\nplt.axis(\"off\")\nplt.subplot(122)\nplt.plot(np.arange(2, 19, 4), granulo, \"ok\", ms=8)\n\n\nplt.subplots_adjust(wspace=0.02, hspace=0.15, top=0.95, bottom=0.15, left=0, right=0.95)\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/66edd5a812d651c507abbf497a5c0af1/to_debug.py b/_downloads/66edd5a812d651c507abbf497a5c0af1/to_debug.py new file mode 100644 index 000000000..fd2e3a1de --- /dev/null +++ b/_downloads/66edd5a812d651c507abbf497a5c0af1/to_debug.py @@ -0,0 +1,70 @@ +""" +A script to compare different root-finding algorithms. + +This version of the script is buggy and does not execute. It is your task +to find an fix these bugs. + +The output of the script should look like: + + Benching 1D root-finder optimizers from scipy.optimize: + brenth: 604678 total function calls + brentq: 594454 total function calls + ridder: 778394 total function calls + bisect: 2148380 total function calls +""" + +from itertools import product + +import numpy as np +import scipy as sp + +rng = np.random.default_rng(27446968) + +FUNCTIONS = ( + np.tan, # Dilating map + np.tanh, # Contracting map + lambda x: x**3 + 1e-4 * x, # Almost null gradient at the root + lambda x: x + np.sin(2 * x), # Non monotonous function + lambda x: 1.1 * x + np.sin(4 * x), # Function with several local maxima +) + +OPTIMIZERS = ( + sp.optimize.brenth, + sp.optimize.brentq, + sp.optimize.ridder, + sp.optimize.bisect, +) + + +def apply_optimizer(optimizer, func, a, b): + """Return the number of function calls given an root-finding optimizer, + a function and upper and lower bounds. + """ + return (optimizer(func, a, b, full_output=True)[1].function_calls,) + + +def bench_optimizer(optimizer, param_grid): + """Find roots for all the functions, and upper and lower bounds + given and return the total number of function calls. + """ + return sum(apply_optimizer(optimizer, func, a, b) for func, a, b in param_grid) + + +def compare_optimizers(optimizers): + """Compare all the optimizers given on a grid of a few different + functions all admitting a single root in zero and a upper and + lower bounds. + """ + random_a = -1.3 + rng.random(size=100) + random_b = 0.3 + rng.random(size=100) + param_grid = product(FUNCTIONS, random_a, random_b) + print("Benching 1D root-finder optimizers from scipy.optimize:") + for optimizer in OPTIMIZERS: + print( + "% 20s: % 8i total function calls" + % (optimizer.__name__, bench_optimizer(optimizer, param_grid)) + ) + + +if __name__ == "__main__": + compare_optimizers(OPTIMIZERS) diff --git a/_downloads/6729e3c0d4be619d7873c2dc2350daba/plot_optimize_lidar_data.ipynb b/_downloads/6729e3c0d4be619d7873c2dc2350daba/plot_optimize_lidar_data.ipynb new file mode 100644 index 000000000..c92fd177e --- /dev/null +++ b/_downloads/6729e3c0d4be619d7873c2dc2350daba/plot_optimize_lidar_data.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# The lidar system, data (1 of 2 datasets)\n\nGenerate a chart of the data recorded by the lidar system\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nwaveform_1 = np.load(\"waveform_1.npy\")\n\nt = np.arange(len(waveform_1))\n\nfig, ax = plt.subplots(figsize=(8, 6))\nplt.plot(t, waveform_1)\nplt.xlabel(\"Time [ns]\")\nplt.ylabel(\"Amplitude [bins]\")\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/677ee7ef9ac9281e526ba11c6370a5b8/plot_geom_face.zip b/_downloads/677ee7ef9ac9281e526ba11c6370a5b8/plot_geom_face.zip new file mode 100644 index 000000000..cb2513000 Binary files /dev/null and b/_downloads/677ee7ef9ac9281e526ba11c6370a5b8/plot_geom_face.zip differ diff --git a/_downloads/67abe56861ac8a377af26857cda03cdc/plot_optimize_example1.ipynb b/_downloads/67abe56861ac8a377af26857cda03cdc/plot_optimize_example1.ipynb new file mode 100644 index 000000000..07b60278e --- /dev/null +++ b/_downloads/67abe56861ac8a377af26857cda03cdc/plot_optimize_example1.ipynb @@ -0,0 +1,72 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Finding the minimum of a smooth function\n\nDemos various methods to find the minimum of a function.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef f(x):\n return x**2 + 10 * np.sin(x)\n\n\nx = np.arange(-5, 5, 0.1)\nplt.plot(x, f(x))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now find the minimum with a few methods\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import scipy as sp\n\n# The default (Nelder Mead)\nprint(sp.optimize.minimize(f, x0=0))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "plt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/68905f39147a619d9769bc933d0f9f59/plot_aliased.py b/_downloads/68905f39147a619d9769bc933d0f9f59/plot_aliased.py new file mode 100644 index 000000000..5804307c8 --- /dev/null +++ b/_downloads/68905f39147a619d9769bc933d0f9f59/plot_aliased.py @@ -0,0 +1,26 @@ +""" +Aliased versus anti-aliased +============================= + +This example demonstrates aliased versus anti-aliased text. +""" + +import matplotlib.pyplot as plt + +size = 128, 16 +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = plt.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) + +plt.axes((0, 0, 1, 1), frameon=False) + +plt.rcParams["text.antialiased"] = False +plt.text(0.5, 0.5, "Aliased", ha="center", va="center") + +plt.xlim(0, 1) +plt.ylim(0, 1) +plt.xticks([]) +plt.yticks([]) + +plt.show() diff --git a/_downloads/68de56713b1c45308ccaa1c05a4617c7/plot_multiplot_ext.ipynb b/_downloads/68de56713b1c45308ccaa1c05a4617c7/plot_multiplot_ext.ipynb new file mode 100644 index 000000000..f3af1c24f --- /dev/null +++ b/_downloads/68de56713b1c45308ccaa1c05a4617c7/plot_multiplot_ext.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Multiple plots vignette\n\nDemo multiple plots and style the figure.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nax = plt.subplot(2, 1, 1)\nax.set_xticklabels([])\nax.set_yticklabels([])\n\n\n# Add a title and a box around it\nfrom matplotlib.patches import FancyBboxPatch\n\nax = plt.gca()\nax.add_patch(\n FancyBboxPatch(\n (-0.05, 0.72),\n width=0.66,\n height=0.34,\n clip_on=False,\n boxstyle=\"square,pad=0\",\n zorder=3,\n facecolor=\"white\",\n alpha=1.0,\n transform=plt.gca().transAxes,\n )\n)\n\nplt.text(\n -0.05,\n 1.02,\n \" Multiplot: plt.subplot(...)\\n\",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"xx-large\",\n transform=ax.transAxes,\n)\nplt.text(\n -0.05,\n 1.01,\n \"\\n\\n Plot several plots at once \",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"large\",\n transform=ax.transAxes,\n)\n\nax = plt.subplot(2, 2, 3)\nax.set_xticklabels([])\nax.set_yticklabels([])\n\nax = plt.subplot(2, 2, 4)\nax.set_xticklabels([])\nax.set_yticklabels([])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/699574c2cbd548225fcff45f27d8ff4b/plot_block_mean.ipynb b/_downloads/699574c2cbd548225fcff45f27d8ff4b/plot_block_mean.ipynb new file mode 100644 index 000000000..ec19e539d --- /dev/null +++ b/_downloads/699574c2cbd548225fcff45f27d8ff4b/plot_block_mean.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot the block mean of an image\n\nAn example showing how to use broad-casting to plot the mean of\nblocks of an image.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nf = sp.datasets.face(gray=True)\nsx, sy = f.shape\nX, Y = np.ogrid[0:sx, 0:sy]\n\nregions = sy // 6 * (X // 4) + Y // 6\nblock_mean = sp.ndimage.mean(f, labels=regions, index=np.arange(1, regions.max() + 1))\nblock_mean.shape = (sx // 4, sy // 6)\n\nplt.figure(figsize=(5, 5))\nplt.imshow(block_mean, cmap=\"gray\")\nplt.axis(\"off\")\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/69bd605f3cc5747ec35588a81de5dc2a/plot_t_test.ipynb b/_downloads/69bd605f3cc5747ec35588a81de5dc2a/plot_t_test.ipynb new file mode 100644 index 000000000..d65e47ee0 --- /dev/null +++ b/_downloads/69bd605f3cc5747ec35588a81de5dc2a/plot_t_test.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Comparing 2 sets of samples from Gaussians\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\n# Generates 2 sets of observations\nrng = np.random.default_rng(27446968)\nsamples1 = rng.normal(0, size=1000)\nsamples2 = rng.normal(1, size=1000)\n\n# Compute a histogram of the sample\nbins = np.linspace(-4, 4, 30)\nhistogram1, bins = np.histogram(samples1, bins=bins, density=True)\nhistogram2, bins = np.histogram(samples2, bins=bins, density=True)\n\nplt.figure(figsize=(6, 4))\nplt.hist(samples1, bins=bins, density=True, label=\"Samples 1\") # type: ignore[arg-type]\nplt.hist(samples2, bins=bins, density=True, label=\"Samples 2\") # type: ignore[arg-type]\nplt.legend(loc=\"best\")\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/69df5372de74262a5d82c482785750d8/plot_display_face.zip b/_downloads/69df5372de74262a5d82c482785750d8/plot_display_face.zip new file mode 100644 index 000000000..bdcaa14fc Binary files /dev/null and b/_downloads/69df5372de74262a5d82c482785750d8/plot_display_face.zip differ diff --git a/_downloads/6a2976a5409edbfb414e890c11760a67/plot_geom_face.ipynb b/_downloads/6a2976a5409edbfb414e890c11760a67/plot_geom_face.ipynb new file mode 100644 index 000000000..45a93c7f2 --- /dev/null +++ b/_downloads/6a2976a5409edbfb414e890c11760a67/plot_geom_face.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Geometrical transformations\n\nThis examples demos some simple geometrical transformations on a Raccoon face.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nface = sp.datasets.face(gray=True)\nlx, ly = face.shape\n# Cropping\ncrop_face = face[lx // 4 : -lx // 4, ly // 4 : -ly // 4]\n# up <-> down flip\nflip_ud_face = np.flipud(face)\n# rotation\nrotate_face = sp.ndimage.rotate(face, 45)\nrotate_face_noreshape = sp.ndimage.rotate(face, 45, reshape=False)\n\nplt.figure(figsize=(12.5, 2.5))\n\n\nplt.subplot(151)\nplt.imshow(face, cmap=\"gray\")\nplt.axis(\"off\")\nplt.subplot(152)\nplt.imshow(crop_face, cmap=\"gray\")\nplt.axis(\"off\")\nplt.subplot(153)\nplt.imshow(flip_ud_face, cmap=\"gray\")\nplt.axis(\"off\")\nplt.subplot(154)\nplt.imshow(rotate_face, cmap=\"gray\")\nplt.axis(\"off\")\nplt.subplot(155)\nplt.imshow(rotate_face_noreshape, cmap=\"gray\")\nplt.axis(\"off\")\n\nplt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/6a6a218ec312c425a4d08c5e8c4e2347/plot_chebyfit.ipynb b/_downloads/6a6a218ec312c425a4d08c5e8c4e2347/plot_chebyfit.ipynb new file mode 100644 index 000000000..5a23c2a4d --- /dev/null +++ b/_downloads/6a6a218ec312c425a4d08c5e8c4e2347/plot_chebyfit.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Fitting in Chebyshev basis\n\nPlot noisy data and their polynomial fit in a Chebyshev basis\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nrng = np.random.default_rng(27446968)\n\nx = np.linspace(-1, 1, 2000)\ny = np.cos(x) + 0.3 * rng.random(2000)\np = np.polynomial.Chebyshev.fit(x, y, 90)\n\nplt.plot(x, y, \"r.\")\nplt.plot(x, p(x), \"k-\", lw=3)\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/6a82c9359d06ed7ce9f78272514d7958/plot_cumulative_wind_speed_prediction.ipynb b/_downloads/6a82c9359d06ed7ce9f78272514d7958/plot_cumulative_wind_speed_prediction.ipynb new file mode 100644 index 000000000..8f2a57960 --- /dev/null +++ b/_downloads/6a82c9359d06ed7ce9f78272514d7958/plot_cumulative_wind_speed_prediction.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Cumulative wind speed prediction\n\nGenerate the image cumulative-wind-speed-prediction.png\nfor the interpolate section of scipy.rst.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nmax_speeds = np.load(\"max-speeds.npy\")\nyears_nb = max_speeds.shape[0]\n\ncprob = (np.arange(years_nb, dtype=np.float32) + 1) / (years_nb + 1)\nsorted_max_speeds = np.sort(max_speeds)\nspeed_spline = sp.interpolate.UnivariateSpline(cprob, sorted_max_speeds)\nnprob = np.linspace(0, 1, 100)\nfitted_max_speeds = speed_spline(nprob)\n\nfifty_prob = 1.0 - 0.02\nfifty_wind = speed_spline(fifty_prob)\n\nplt.figure()\nplt.plot(sorted_max_speeds, cprob, \"o\")\nplt.plot(fitted_max_speeds, nprob, \"g--\")\nplt.plot([fifty_wind], [fifty_prob], \"o\", ms=8.0, mfc=\"y\", mec=\"y\")\nplt.text(30, 0.05, rf\"$V_{{50}} = {fifty_wind:.2f} \\, m/s$\")\nplt.plot([fifty_wind, fifty_wind], [plt.axis()[2], fifty_prob], \"k--\")\nplt.xlabel(\"Annual wind speed maxima [$m/s$]\")\nplt.ylabel(\"Cumulative probability\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/6aa7f4a037bb438549771d54e885725d/plot_exercise_ill_conditioned.ipynb b/_downloads/6aa7f4a037bb438549771d54e885725d/plot_exercise_ill_conditioned.ipynb new file mode 100644 index 000000000..b9ef8338d --- /dev/null +++ b/_downloads/6aa7f4a037bb438549771d54e885725d/plot_exercise_ill_conditioned.ipynb @@ -0,0 +1,61 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Alternating optimization\n\nThe challenge here is that Hessian of the problem is a very\nill-conditioned matrix. This can easily be seen, as the Hessian of the\nfirst term in simply 2 * K.T @ K. Thus the conditioning of the\nproblem can be judged from looking at the conditioning of K.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import time\n\nimport numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nrng = np.random.default_rng(27446968)\n\nK = rng.normal(size=(100, 100))\n\n\ndef f(x):\n return np.sum((K @ (x - 1)) ** 2) + np.sum(x**2) ** 2\n\n\ndef f_prime(x):\n return 2 * K.T @ K @ (x - 1) + 4 * np.sum(x**2) * x\n\n\ndef hessian(x):\n H = 2 * K.T @ K + 4 * 2 * x * x[:, np.newaxis]\n return H + 4 * np.eye(H.shape[0]) * np.sum(x**2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Some pretty plotting\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "plt.figure(1)\nplt.clf()\nZ = X, Y = np.mgrid[-1.5:1.5:100j, -1.1:1.1:100j] # type: ignore[misc]\n# Complete in the additional dimensions with zeros\nZ = np.reshape(Z, (2, -1)).copy()\nZ.resize((100, Z.shape[-1]))\nZ = np.apply_along_axis(f, 0, Z)\nZ = np.reshape(Z, X.shape)\nplt.imshow(Z.T, cmap=\"gray_r\", extent=(-1.5, 1.5, -1.1, 1.1), origin=\"lower\")\nplt.contour(X, Y, Z, cmap=\"gnuplot\")\n\n# A reference but slow solution:\nt0 = time.time()\nx_ref = sp.optimize.minimize(f, K[0], method=\"Powell\").x\nprint(f\" Powell: time {time.time() - t0:.2f}s\")\nf_ref = f(x_ref)\n\n# Compare different approaches\nt0 = time.time()\nx_bfgs = sp.optimize.minimize(f, K[0], method=\"BFGS\").x\nprint(\n f\" BFGS: time {time.time() - t0:.2f}s, x error {np.sqrt(np.sum((x_bfgs - x_ref) ** 2)):.2f}, f error {f(x_bfgs) - f_ref:.2f}\"\n)\n\nt0 = time.time()\nx_l_bfgs = sp.optimize.minimize(f, K[0], method=\"L-BFGS-B\").x\nprint(\n f\" L-BFGS: time {time.time() - t0:.2f}s, x error {np.sqrt(np.sum((x_l_bfgs - x_ref) ** 2)):.2f}, f error {f(x_l_bfgs) - f_ref:.2f}\"\n)\n\n\nt0 = time.time()\nx_bfgs = sp.optimize.minimize(f, K[0], jac=f_prime, method=\"BFGS\").x\nprint(\n f\" BFGS w f': time {time.time() - t0:.2f}s, x error {np.sqrt(np.sum((x_bfgs - x_ref) ** 2)):.2f}, f error {f(x_bfgs) - f_ref:.2f}\"\n)\n\nt0 = time.time()\nx_l_bfgs = sp.optimize.minimize(f, K[0], jac=f_prime, method=\"L-BFGS-B\").x\nprint(\n f\"L-BFGS w f': time {time.time() - t0:.2f}s, x error {np.sqrt(np.sum((x_l_bfgs - x_ref) ** 2)):.2f}, f error {f(x_l_bfgs) - f_ref:.2f}\"\n)\n\nt0 = time.time()\nx_newton = sp.optimize.minimize(\n f, K[0], jac=f_prime, hess=hessian, method=\"Newton-CG\"\n).x\nprint(\n f\" Newton: time {time.time() - t0:.2f}s, x error {np.sqrt(np.sum((x_newton - x_ref) ** 2)):.2f}, f error {f(x_newton) - f_ref:.2f}\"\n)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/6abc07a6a1c63c2a9596dcd63dd89275/plot_populations.py b/_downloads/6abc07a6a1c63c2a9596dcd63dd89275/plot_populations.py new file mode 100644 index 000000000..22d25a0e7 --- /dev/null +++ b/_downloads/6abc07a6a1c63c2a9596dcd63dd89275/plot_populations.py @@ -0,0 +1,18 @@ +""" +Population exercise +=================== + +Plot populations of hares, lynxes, and carrots + +""" + +import numpy as np +import matplotlib.pyplot as plt + +data = np.loadtxt("../../../data/populations.txt") +year, hares, lynxes, carrots = data.T + +plt.axes((0.2, 0.1, 0.5, 0.8)) +plt.plot(year, hares, year, lynxes, year, carrots) +plt.legend(("Hare", "Lynx", "Carrot"), loc=(1.05, 0.5)) +plt.show() diff --git a/_downloads/6ad44d048dee6fbe12f8e12039977ee7/plot_axes-2.zip b/_downloads/6ad44d048dee6fbe12f8e12039977ee7/plot_axes-2.zip new file mode 100644 index 000000000..818d0aecd Binary files /dev/null and b/_downloads/6ad44d048dee6fbe12f8e12039977ee7/plot_axes-2.zip differ diff --git a/_downloads/6b243c53bc90ebf98f1fa35cdc37528b/plot_exercise_3.ipynb b/_downloads/6b243c53bc90ebf98f1fa35cdc37528b/plot_exercise_3.ipynb new file mode 100644 index 000000000..012190806 --- /dev/null +++ b/_downloads/6b243c53bc90ebf98f1fa35cdc37528b/plot_exercise_3.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Exercise 3\n\nExercise 3 with matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(8, 5), dpi=80)\nplt.subplot(111)\n\nX = np.linspace(-np.pi, np.pi, 256)\nC, S = np.cos(X), np.sin(X)\n\nplt.plot(X, C, color=\"blue\", linewidth=2.5, linestyle=\"-\")\nplt.plot(X, S, color=\"red\", linewidth=2.5, linestyle=\"-\")\n\nplt.xlim(-4.0, 4.0)\nplt.xticks(np.linspace(-4, 4, 9))\n\nplt.ylim(-1.0, 1.0)\nplt.yticks(np.linspace(-1, 1, 5))\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/6b3c521e21b0cbc4a5eb0a951581ee27/plot_clean_morpho.ipynb b/_downloads/6b3c521e21b0cbc4a5eb0a951581ee27/plot_clean_morpho.ipynb new file mode 100644 index 000000000..b398713b1 --- /dev/null +++ b/_downloads/6b3c521e21b0cbc4a5eb0a951581ee27/plot_clean_morpho.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Cleaning segmentation with mathematical morphology\n\nAn example showing how to clean segmentation with mathematical\nmorphology: removing small regions and holes.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nrng = np.random.default_rng(27446968)\nn = 10\nl = 256\nim = np.zeros((l, l))\npoints = l * rng.random((2, n**2))\nim[(points[0]).astype(int), (points[1]).astype(int)] = 1\nim = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n))\n\nmask = (im > im.mean()).astype(float)\n\n\nimg = mask + 0.3 * rng.normal(size=mask.shape)\n\nbinary_img = img > 0.5\n\n# Remove small white regions\nopen_img = sp.ndimage.binary_opening(binary_img)\n# Remove small black hole\nclose_img = sp.ndimage.binary_closing(open_img)\n\nplt.figure(figsize=(12, 3))\n\nl = 128\n\nplt.subplot(141)\nplt.imshow(binary_img[:l, :l], cmap=\"gray\")\nplt.axis(\"off\")\nplt.subplot(142)\nplt.imshow(open_img[:l, :l], cmap=\"gray\")\nplt.axis(\"off\")\nplt.subplot(143)\nplt.imshow(close_img[:l, :l], cmap=\"gray\")\nplt.axis(\"off\")\nplt.subplot(144)\nplt.imshow(mask[:l, :l], cmap=\"gray\")\nplt.contour(close_img[:l, :l], [0.5], linewidths=2, colors=\"r\")\nplt.axis(\"off\")\n\nplt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/6c4b367d8ba9371e9254c70abb7496c5/iris.csv b/_downloads/6c4b367d8ba9371e9254c70abb7496c5/iris.csv new file mode 100644 index 000000000..050993a69 --- /dev/null +++ b/_downloads/6c4b367d8ba9371e9254c70abb7496c5/iris.csv @@ -0,0 +1,151 @@ +sepal_length,sepal_width,petal_length,petal_width,name +5.1,3.5,1.4,0.2,setosa +4.9,3.0,1.4,0.2,setosa +4.7,3.2,1.3,0.2,setosa +4.6,3.1,1.5,0.2,setosa +5.0,3.6,1.4,0.2,setosa +5.4,3.9,1.7,0.4,setosa +4.6,3.4,1.4,0.3,setosa +5.0,3.4,1.5,0.2,setosa +4.4,2.9,1.4,0.2,setosa +4.9,3.1,1.5,0.1,setosa +5.4,3.7,1.5,0.2,setosa +4.8,3.4,1.6,0.2,setosa +4.8,3.0,1.4,0.1,setosa +4.3,3.0,1.1,0.1,setosa +5.8,4.0,1.2,0.2,setosa +5.7,4.4,1.5,0.4,setosa +5.4,3.9,1.3,0.4,setosa +5.1,3.5,1.4,0.3,setosa +5.7,3.8,1.7,0.3,setosa +5.1,3.8,1.5,0.3,setosa +5.4,3.4,1.7,0.2,setosa +5.1,3.7,1.5,0.4,setosa +4.6,3.6,1.0,0.2,setosa +5.1,3.3,1.7,0.5,setosa +4.8,3.4,1.9,0.2,setosa +5.0,3.0,1.6,0.2,setosa +5.0,3.4,1.6,0.4,setosa +5.2,3.5,1.5,0.2,setosa +5.2,3.4,1.4,0.2,setosa +4.7,3.2,1.6,0.2,setosa +4.8,3.1,1.6,0.2,setosa +5.4,3.4,1.5,0.4,setosa +5.2,4.1,1.5,0.1,setosa +5.5,4.2,1.4,0.2,setosa +4.9,3.1,1.5,0.1,setosa +5.0,3.2,1.2,0.2,setosa +5.5,3.5,1.3,0.2,setosa +4.9,3.1,1.5,0.1,setosa +4.4,3.0,1.3,0.2,setosa +5.1,3.4,1.5,0.2,setosa +5.0,3.5,1.3,0.3,setosa +4.5,2.3,1.3,0.3,setosa +4.4,3.2,1.3,0.2,setosa +5.0,3.5,1.6,0.6,setosa +5.1,3.8,1.9,0.4,setosa +4.8,3.0,1.4,0.3,setosa +5.1,3.8,1.6,0.2,setosa +4.6,3.2,1.4,0.2,setosa +5.3,3.7,1.5,0.2,setosa +5.0,3.3,1.4,0.2,setosa +7.0,3.2,4.7,1.4,versicolor +6.4,3.2,4.5,1.5,versicolor +6.9,3.1,4.9,1.5,versicolor +5.5,2.3,4.0,1.3,versicolor +6.5,2.8,4.6,1.5,versicolor +5.7,2.8,4.5,1.3,versicolor +6.3,3.3,4.7,1.6,versicolor +4.9,2.4,3.3,1.0,versicolor +6.6,2.9,4.6,1.3,versicolor +5.2,2.7,3.9,1.4,versicolor +5.0,2.0,3.5,1.0,versicolor +5.9,3.0,4.2,1.5,versicolor +6.0,2.2,4.0,1.0,versicolor +6.1,2.9,4.7,1.4,versicolor +5.6,2.9,3.6,1.3,versicolor +6.7,3.1,4.4,1.4,versicolor +5.6,3.0,4.5,1.5,versicolor +5.8,2.7,4.1,1.0,versicolor +6.2,2.2,4.5,1.5,versicolor +5.6,2.5,3.9,1.1,versicolor +5.9,3.2,4.8,1.8,versicolor +6.1,2.8,4.0,1.3,versicolor +6.3,2.5,4.9,1.5,versicolor +6.1,2.8,4.7,1.2,versicolor +6.4,2.9,4.3,1.3,versicolor +6.6,3.0,4.4,1.4,versicolor +6.8,2.8,4.8,1.4,versicolor +6.7,3.0,5.0,1.7,versicolor +6.0,2.9,4.5,1.5,versicolor +5.7,2.6,3.5,1.0,versicolor +5.5,2.4,3.8,1.1,versicolor +5.5,2.4,3.7,1.0,versicolor +5.8,2.7,3.9,1.2,versicolor +6.0,2.7,5.1,1.6,versicolor +5.4,3.0,4.5,1.5,versicolor +6.0,3.4,4.5,1.6,versicolor +6.7,3.1,4.7,1.5,versicolor +6.3,2.3,4.4,1.3,versicolor +5.6,3.0,4.1,1.3,versicolor +5.5,2.5,4.0,1.3,versicolor +5.5,2.6,4.4,1.2,versicolor +6.1,3.0,4.6,1.4,versicolor +5.8,2.6,4.0,1.2,versicolor +5.0,2.3,3.3,1.0,versicolor +5.6,2.7,4.2,1.3,versicolor +5.7,3.0,4.2,1.2,versicolor +5.7,2.9,4.2,1.3,versicolor +6.2,2.9,4.3,1.3,versicolor +5.1,2.5,3.0,1.1,versicolor +5.7,2.8,4.1,1.3,versicolor +6.3,3.3,6.0,2.5,virginica +5.8,2.7,5.1,1.9,virginica +7.1,3.0,5.9,2.1,virginica +6.3,2.9,5.6,1.8,virginica +6.5,3.0,5.8,2.2,virginica +7.6,3.0,6.6,2.1,virginica +4.9,2.5,4.5,1.7,virginica +7.3,2.9,6.3,1.8,virginica +6.7,2.5,5.8,1.8,virginica +7.2,3.6,6.1,2.5,virginica +6.5,3.2,5.1,2.0,virginica +6.4,2.7,5.3,1.9,virginica +6.8,3.0,5.5,2.1,virginica +5.7,2.5,5.0,2.0,virginica +5.8,2.8,5.1,2.4,virginica +6.4,3.2,5.3,2.3,virginica +6.5,3.0,5.5,1.8,virginica +7.7,3.8,6.7,2.2,virginica +7.7,2.6,6.9,2.3,virginica +6.0,2.2,5.0,1.5,virginica +6.9,3.2,5.7,2.3,virginica +5.6,2.8,4.9,2.0,virginica +7.7,2.8,6.7,2.0,virginica +6.3,2.7,4.9,1.8,virginica +6.7,3.3,5.7,2.1,virginica +7.2,3.2,6.0,1.8,virginica +6.2,2.8,4.8,1.8,virginica +6.1,3.0,4.9,1.8,virginica +6.4,2.8,5.6,2.1,virginica +7.2,3.0,5.8,1.6,virginica +7.4,2.8,6.1,1.9,virginica +7.9,3.8,6.4,2.0,virginica +6.4,2.8,5.6,2.2,virginica +6.3,2.8,5.1,1.5,virginica +6.1,2.6,5.6,1.4,virginica +7.7,3.0,6.1,2.3,virginica +6.3,3.4,5.6,2.4,virginica +6.4,3.1,5.5,1.8,virginica +6.0,3.0,4.8,1.8,virginica +6.9,3.1,5.4,2.1,virginica +6.7,3.1,5.6,2.4,virginica +6.9,3.1,5.1,2.3,virginica +5.8,2.7,5.1,1.9,virginica +6.8,3.2,5.9,2.3,virginica +6.7,3.3,5.7,2.5,virginica +6.7,3.0,5.2,2.3,virginica +6.3,2.5,5.0,1.9,virginica +6.5,3.0,5.2,2.0,virginica +6.2,3.4,5.4,2.3,virginica +5.9,3.0,5.1,1.8,virginica diff --git a/_downloads/6db0bb911897ac73e48f2e61eccb9f04/auto_examples_jupyter.zip b/_downloads/6db0bb911897ac73e48f2e61eccb9f04/auto_examples_jupyter.zip new file mode 100644 index 000000000..fadce9863 Binary files /dev/null and b/_downloads/6db0bb911897ac73e48f2e61eccb9f04/auto_examples_jupyter.zip differ diff --git a/_downloads/6dcd0c481a31f8a8692b0138ebd870dd/plot_alpha.zip b/_downloads/6dcd0c481a31f8a8692b0138ebd870dd/plot_alpha.zip new file mode 100644 index 000000000..cae55b571 Binary files /dev/null and b/_downloads/6dcd0c481a31f8a8692b0138ebd870dd/plot_alpha.zip differ diff --git a/_downloads/6dfc37c3fe3c19871bbb8c8ab6249cf0/plot_pca.zip b/_downloads/6dfc37c3fe3c19871bbb8c8ab6249cf0/plot_pca.zip new file mode 100644 index 000000000..09f81253d Binary files /dev/null and b/_downloads/6dfc37c3fe3c19871bbb8c8ab6249cf0/plot_pca.zip differ diff --git a/_downloads/6e1b8bd6fa52e61c095fe0e84e20d14b/plot_solid_joinstyle.py b/_downloads/6e1b8bd6fa52e61c095fe0e84e20d14b/plot_solid_joinstyle.py new file mode 100644 index 000000000..c254acfba --- /dev/null +++ b/_downloads/6e1b8bd6fa52e61c095fe0e84e20d14b/plot_solid_joinstyle.py @@ -0,0 +1,31 @@ +""" +Solid joint style +================== + +An example showing the different solid joint styles in matplotlib. +""" + +import numpy as np +import matplotlib.pyplot as plt + +size = 256, 16 +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = plt.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +plt.axes((0, 0, 1, 1), frameon=False) + +plt.plot(np.arange(3), [0, 1, 0], color="blue", linewidth=8, solid_joinstyle="miter") +plt.plot( + 4 + np.arange(3), [0, 1, 0], color="blue", linewidth=8, solid_joinstyle="bevel" +) +plt.plot( + 8 + np.arange(3), [0, 1, 0], color="blue", linewidth=8, solid_joinstyle="round" +) + +plt.xlim(0, 12) +plt.ylim(-1, 2) +plt.xticks([]) +plt.yticks([]) + +plt.show() diff --git a/_downloads/6e405f96efafba03aaa39899aa5aea3e/plot_equalize_hist.ipynb b/_downloads/6e405f96efafba03aaa39899aa5aea3e/plot_equalize_hist.ipynb new file mode 100644 index 000000000..939b39a14 --- /dev/null +++ b/_downloads/6e405f96efafba03aaa39899aa5aea3e/plot_equalize_hist.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Equalizing the histogram of an image\n\nHistogram equalizing makes images have a uniform histogram.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from skimage import data, exposure\nimport matplotlib.pyplot as plt\n\ncamera = data.camera()\ncamera_equalized = exposure.equalize_hist(camera)\n\nplt.figure(figsize=(7, 3))\n\nplt.subplot(121)\nplt.imshow(camera, cmap=\"gray\", interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.subplot(122)\nplt.imshow(camera_equalized, cmap=\"gray\", interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/6f21614a3d7e794584d745d80156a8c4/plot_imshow.zip b/_downloads/6f21614a3d7e794584d745d80156a8c4/plot_imshow.zip new file mode 100644 index 000000000..051a75d58 Binary files /dev/null and b/_downloads/6f21614a3d7e794584d745d80156a8c4/plot_imshow.zip differ diff --git a/_downloads/6f300d02279951acf1df9f1d9009d88e/auto_examples_jupyter.zip b/_downloads/6f300d02279951acf1df9f1d9009d88e/auto_examples_jupyter.zip new file mode 100644 index 000000000..94a4a9282 Binary files /dev/null and b/_downloads/6f300d02279951acf1df9f1d9009d88e/auto_examples_jupyter.zip differ diff --git a/_downloads/6f7f160aa8f60e10fd054aa7736aa00a/plot_digits_simple_classif.py b/_downloads/6f7f160aa8f60e10fd054aa7736aa00a/plot_digits_simple_classif.py new file mode 100644 index 000000000..75ea9e7b3 --- /dev/null +++ b/_downloads/6f7f160aa8f60e10fd054aa7736aa00a/plot_digits_simple_classif.py @@ -0,0 +1,102 @@ +""" +Simple visualization and classification of the digits dataset +============================================================= + +Plot the first few samples of the digits dataset and a 2D representation +built using PCA, then do a simple classification +""" + +from sklearn.datasets import load_digits + +digits = load_digits() + +############################################################################### +# Plot the data: images of digits +# ------------------------------- +# +# Each data in a 8x8 image +import matplotlib.pyplot as plt + +fig = plt.figure(figsize=(6, 6)) # figure size in inches +fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05) + +for i in range(64): + ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[]) + ax.imshow(digits.images[i], cmap="binary", interpolation="nearest") + # label the image with the target value + ax.text(0, 7, str(digits.target[i])) + + +############################################################################### +# Plot a projection on the 2 first principal axis +# ------------------------------------------------ + +plt.figure() + +from sklearn.decomposition import PCA + +pca = PCA(n_components=2) +proj = pca.fit_transform(digits.data) +plt.scatter(proj[:, 0], proj[:, 1], c=digits.target, cmap="Paired") +plt.colorbar() + + +############################################################################### +# Classify with Gaussian naive Bayes +# ---------------------------------- + +from sklearn.naive_bayes import GaussianNB +from sklearn.model_selection import train_test_split + +# split the data into training and validation sets +X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target) + +# train the model +clf = GaussianNB() +clf.fit(X_train, y_train) + +# use the model to predict the labels of the test data +predicted = clf.predict(X_test) +expected = y_test + +# Plot the prediction +fig = plt.figure(figsize=(6, 6)) # figure size in inches +fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05) + +# plot the digits: each image is 8x8 pixels +for i in range(64): + ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[]) + ax.imshow(X_test.reshape(-1, 8, 8)[i], cmap="binary", interpolation="nearest") + + # label the image with the target value + if predicted[i] == expected[i]: + ax.text(0, 7, str(predicted[i]), color="green") + else: + ax.text(0, 7, str(predicted[i]), color="red") + + +############################################################################### +# Quantify the performance +# ------------------------ +# +# First print the number of correct matches +matches = predicted == expected +print(matches.sum()) +############################################################################### +# The total number of data points +print(len(matches)) +############################################################################### +# And now, the ration of correct predictions +matches.sum() / float(len(matches)) + +############################################################################### +# Print the classification report +from sklearn import metrics + +print(metrics.classification_report(expected, predicted)) + +############################################################################### +# Print the confusion matrix +print(metrics.confusion_matrix(expected, predicted)) + +plt.show() diff --git a/_downloads/6fbee82c2c17e13da383632fd082c04b/plot_mew.ipynb b/_downloads/6fbee82c2c17e13da383632fd082c04b/plot_mew.ipynb new file mode 100644 index 000000000..3137b909b --- /dev/null +++ b/_downloads/6fbee82c2c17e13da383632fd082c04b/plot_mew.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Marker edge width\n\nDemo the marker edge widths of matplotlib's markers.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nsize = 256, 16\ndpi = 72.0\nfigsize = size[0] / float(dpi), size[1] / float(dpi)\nfig = plt.figure(figsize=figsize, dpi=dpi)\nfig.patch.set_alpha(0)\nplt.axes((0, 0, 1, 1), frameon=False)\n\nfor i in range(1, 11):\n plt.plot(\n [\n i,\n ],\n [\n 1,\n ],\n \"s\",\n markersize=5,\n markeredgewidth=1 + i / 10.0,\n markeredgecolor=\"k\",\n markerfacecolor=\"w\",\n )\nplt.xlim(0, 11)\nplt.xticks([])\nplt.yticks([])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/7024a7ec7d6b403ea334ebd923ce4f1e/plot_propagation.zip b/_downloads/7024a7ec7d6b403ea334ebd923ce4f1e/plot_propagation.zip new file mode 100644 index 000000000..2c311e77a Binary files /dev/null and b/_downloads/7024a7ec7d6b403ea334ebd923ce4f1e/plot_propagation.zip differ diff --git a/_downloads/71dcc269d32746cb691de09489dff8c4/plot_iris_scatter.ipynb b/_downloads/71dcc269d32746cb691de09489dff8c4/plot_iris_scatter.ipynb new file mode 100644 index 000000000..5e2e366c4 --- /dev/null +++ b/_downloads/71dcc269d32746cb691de09489dff8c4/plot_iris_scatter.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot 2D views of the iris dataset\n\nPlot a simple scatter plot of 2 features of the iris dataset.\n\nNote that more elaborate visualization of this dataset is detailed\nin the `statistics` chapter.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Load the data\nfrom sklearn.datasets import load_iris\n\niris = load_iris()\n\nfrom matplotlib import ticker\nimport matplotlib.pyplot as plt\n\n# The indices of the features that we are plotting\nx_index = 0\ny_index = 1\n\n# this formatter will label the colorbar with the correct target names\nformatter = ticker.FuncFormatter(lambda i, *args: iris.target_names[int(i)])\n\nplt.figure(figsize=(5, 4))\nplt.scatter(iris.data[:, x_index], iris.data[:, y_index], c=iris.target)\nplt.colorbar(ticks=[0, 1, 2], format=formatter)\nplt.xlabel(iris.feature_names[x_index])\nplt.ylabel(iris.feature_names[y_index])\n\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/72a27b877a48b6033defa0485f366b3e/plot_elephant.py b/_downloads/72a27b877a48b6033defa0485f366b3e/plot_elephant.py new file mode 100644 index 000000000..ad3f7b827 --- /dev/null +++ b/_downloads/72a27b877a48b6033defa0485f366b3e/plot_elephant.py @@ -0,0 +1,36 @@ +""" +Reading and writing an elephant +=============================== + +Read and write images + +""" + +import numpy as np +import matplotlib.pyplot as plt + +################################# +# original figure +################################# + +plt.figure() +img = plt.imread("../../../data/elephant.png") +plt.imshow(img) + +################################# +# red channel displayed in grey +################################# + +plt.figure() +img_red = img[:, :, 0] +plt.imshow(img_red, cmap="gray") + +################################# +# lower resolution +################################# + +plt.figure() +img_tiny = img[::6, ::6] +plt.imshow(img_tiny, interpolation="nearest") + +plt.show() diff --git a/_downloads/72b36244e963fe3a6328733219f50baa/plot_contour.py b/_downloads/72b36244e963fe3a6328733219f50baa/plot_contour.py new file mode 100644 index 000000000..ce3081038 --- /dev/null +++ b/_downloads/72b36244e963fe3a6328733219f50baa/plot_contour.py @@ -0,0 +1,30 @@ +""" +Displaying the contours of a function +====================================== + +An example showing how to display the contours of a function with +matplotlib. +""" + +import numpy as np +import matplotlib.pyplot as plt + + +def f(x, y): + return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2) + + +n = 256 +x = np.linspace(-3, 3, n) +y = np.linspace(-3, 3, n) +X, Y = np.meshgrid(x, y) + +plt.axes((0.025, 0.025, 0.95, 0.95)) + +plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap="hot") +C = plt.contour(X, Y, f(X, Y), 8, colors="black", linewidths=0.5) +plt.clabel(C, inline=1, fontsize=10) + +plt.xticks([]) +plt.yticks([]) +plt.show() diff --git a/_downloads/72bbb96c98d897f6a8a56d95351b53b0/plot_quiver_ext.zip b/_downloads/72bbb96c98d897f6a8a56d95351b53b0/plot_quiver_ext.zip new file mode 100644 index 000000000..724703ea9 Binary files /dev/null and b/_downloads/72bbb96c98d897f6a8a56d95351b53b0/plot_quiver_ext.zip differ diff --git a/_downloads/72d4c3452820930ebd8da0c70f996b0e/plot_histo_segmentation.zip b/_downloads/72d4c3452820930ebd8da0c70f996b0e/plot_histo_segmentation.zip new file mode 100644 index 000000000..f12e0dc7c Binary files /dev/null and b/_downloads/72d4c3452820930ebd8da0c70f996b0e/plot_histo_segmentation.zip differ diff --git a/_downloads/73064326fccc2239a0bef117d7bb60c3/direct_solve.py b/_downloads/73064326fccc2239a0bef117d7bb60c3/direct_solve.py new file mode 100644 index 000000000..38de7cf7e --- /dev/null +++ b/_downloads/73064326fccc2239a0bef117d7bb60c3/direct_solve.py @@ -0,0 +1,30 @@ +""" +Solve a linear system +======================= + +Construct a 1000x1000 lil_array and add some values to it, convert it +to CSR format and solve A x = b for x:and solve a linear system with a +direct solver. +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +rng = np.random.default_rng(27446968) + +mtx = sp.sparse.lil_array((1000, 1000), dtype=np.float64) +mtx[0, :100] = rng.random(100) +mtx[1, 100:200] = mtx[[0], :100] +mtx.setdiag(rng.random(1000)) + +plt.clf() +plt.spy(mtx, marker=".", markersize=2) +plt.show() + +mtx = mtx.tocsr() +rhs = rng.random(1000) + +x = sp.sparse.linalg.spsolve(mtx, rhs) + +print(f"residual: {np.linalg.norm(mtx @ x - rhs)!r}") diff --git a/_downloads/73700c7889780001ae8a55032b2c9c7d/plot_connect_measurements.py b/_downloads/73700c7889780001ae8a55032b2c9c7d/plot_connect_measurements.py new file mode 100644 index 000000000..1a3223c42 --- /dev/null +++ b/_downloads/73700c7889780001ae8a55032b2c9c7d/plot_connect_measurements.py @@ -0,0 +1,59 @@ +""" +============================= +Demo connected components +============================= + +Extracting and labeling connected components in a 2D array +""" + +import numpy as np +import matplotlib.pyplot as plt + +############################################################ +# Generate some binary data +x, y = np.indices((100, 100)) +sig = ( + np.sin(2 * np.pi * x / 50.0) + * np.sin(2 * np.pi * y / 50.0) + * (1 + x * y / 50.0**2) ** 2 +) +mask = sig > 1 + +plt.figure(figsize=(7, 3.5)) +plt.subplot(1, 2, 1) +plt.imshow(sig) +plt.axis("off") +plt.title("sig") + +plt.subplot(1, 2, 2) +plt.imshow(mask, cmap="gray") +plt.axis("off") +plt.title("mask") +plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9) + + +############################################################ +# Label connected components +import scipy as sp + +labels, nb = sp.ndimage.label(mask) + +plt.figure(figsize=(3.5, 3.5)) +plt.imshow(labels) +plt.title("label") +plt.axis("off") + +plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9) + + +############################################################ +# Extract the 4th connected component, and crop the array around it +sl = sp.ndimage.find_objects(labels == 4) +plt.figure(figsize=(3.5, 3.5)) +plt.imshow(sig[sl[0]]) +plt.title("Cropped connected component") +plt.axis("off") + +plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9) + +plt.show() diff --git a/_downloads/7393e8f344af5455e0b6f365d30e4e42/plot_plot3d-2.py b/_downloads/7393e8f344af5455e0b6f365d30e4e42/plot_plot3d-2.py new file mode 100644 index 000000000..e2c17c2c4 --- /dev/null +++ b/_downloads/7393e8f344af5455e0b6f365d30e4e42/plot_plot3d-2.py @@ -0,0 +1,44 @@ +""" +3D plotting +============ + +Demo 3D plotting with matplotlib and style the figure. +""" + +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d.axes3d import Axes3D, get_test_data + +ax: Axes3D = plt.figure().add_subplot(projection="3d") +X, Y, Z = get_test_data(0.05) +cset = ax.contourf(X, Y, Z) +ax.clabel(cset, fontsize=9, inline=1) + +plt.xticks([]) +plt.yticks([]) +ax.set_zticks([]) + + +ax.text2D( + -0.05, + 1.05, + " 3D plots \n", + horizontalalignment="left", + verticalalignment="top", + bbox={"facecolor": "white", "alpha": 1.0}, + family="DejaVu Sans", + size="x-large", + transform=plt.gca().transAxes, +) + +ax.text2D( + -0.05, + 0.975, + " Plot 2D or 3D data", + horizontalalignment="left", + verticalalignment="top", + family="DejaVu Sans", + size="medium", + transform=plt.gca().transAxes, +) + +plt.show() diff --git a/_downloads/73f1ed3c5aea893e65e7b1211fe8d781/plot_maskedstats.py b/_downloads/73f1ed3c5aea893e65e7b1211fe8d781/plot_maskedstats.py new file mode 100644 index 000000000..8b015217d --- /dev/null +++ b/_downloads/73f1ed3c5aea893e65e7b1211fe8d781/plot_maskedstats.py @@ -0,0 +1,21 @@ +""" +Example: Masked statistics +========================== + +Plot a masked statistics + +""" + +import numpy as np +import matplotlib.pyplot as plt + +data = np.loadtxt("../../../../data/populations.txt") +populations = np.ma.masked_array(data[:, 1:]) # type: ignore[var-annotated] +year = data[:, 0] + +bad_years = ((year >= 1903) & (year <= 1910)) | ((year >= 1917) & (year <= 1918)) +populations[bad_years, 0] = np.ma.masked +populations[bad_years, 1] = np.ma.masked + +plt.plot(year, populations, "o-") +plt.show() diff --git a/_downloads/740da254f21226b4e953b87580fa5ebf/plot_image_filters.py b/_downloads/740da254f21226b4e953b87580fa5ebf/plot_image_filters.py new file mode 100644 index 000000000..a2d33d22c --- /dev/null +++ b/_downloads/740da254f21226b4e953b87580fa5ebf/plot_image_filters.py @@ -0,0 +1,50 @@ +""" +========================= +Plot filtering on images +========================= + +Demo filtering for denoising of images. +""" + +# Load some data +import scipy as sp + +face = sp.datasets.face(gray=True) +face = face[:512, -512:] # crop out square on right + +# Apply a variety of filters +import matplotlib.pyplot as plt + +import numpy as np + +noisy_face = np.copy(face).astype(float) +rng = np.random.default_rng() +noisy_face += face.std() * 0.5 * rng.standard_normal(face.shape) +blurred_face = sp.ndimage.gaussian_filter(noisy_face, sigma=3) +median_face = sp.ndimage.median_filter(noisy_face, size=5) +wiener_face = sp.signal.wiener(noisy_face, (5, 5)) + +plt.figure(figsize=(12, 3.5)) +plt.subplot(141) +plt.imshow(noisy_face, cmap="gray") +plt.axis("off") +plt.title("noisy") + +plt.subplot(142) +plt.imshow(blurred_face, cmap="gray") +plt.axis("off") +plt.title("Gaussian filter") + +plt.subplot(143) +plt.imshow(median_face, cmap="gray") +plt.axis("off") +plt.title("median filter") + +plt.subplot(144) +plt.imshow(wiener_face, cmap="gray") +plt.title("Wiener filter") +plt.axis("off") + +plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99) + +plt.show() diff --git a/_downloads/741be962793dd52196d55f37023e6432/plot_t_test.zip b/_downloads/741be962793dd52196d55f37023e6432/plot_t_test.zip new file mode 100644 index 000000000..ba0567d65 Binary files /dev/null and b/_downloads/741be962793dd52196d55f37023e6432/plot_t_test.zip differ diff --git a/_downloads/7428acf3aecde61db686e3dd8d7befc8/plot_histo_segmentation.py b/_downloads/7428acf3aecde61db686e3dd8d7befc8/plot_histo_segmentation.py new file mode 100644 index 000000000..81d225f2d --- /dev/null +++ b/_downloads/7428acf3aecde61db686e3dd8d7befc8/plot_histo_segmentation.py @@ -0,0 +1,46 @@ +""" +Histogram segmentation +====================== + +This example does simple histogram analysis to perform segmentation. +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +rng = np.random.default_rng(27446968) +n = 10 +l = 256 +im = np.zeros((l, l)) +points = l * rng.random((2, n**2)) +im[(points[0]).astype(int), (points[1]).astype(int)] = 1 +im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) + +mask = (im > im.mean()).astype(float) + +mask += 0.1 * im + +img = mask + 0.2 * rng.normal(size=mask.shape) + +hist, bin_edges = np.histogram(img, bins=60) +bin_centers = 0.5 * (bin_edges[:-1] + bin_edges[1:]) + +binary_img = img > 0.5 + +plt.figure(figsize=(11, 4)) + +plt.subplot(131) +plt.imshow(img) +plt.axis("off") +plt.subplot(132) +plt.plot(bin_centers, hist, lw=2) +plt.axvline(0.5, color="r", ls="--", lw=2) +plt.text(0.57, 0.8, "histogram", fontsize=20, transform=plt.gca().transAxes) +plt.yticks([]) +plt.subplot(133) +plt.imshow(binary_img, cmap="gray", interpolation="nearest") +plt.axis("off") + +plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) +plt.show() diff --git a/_downloads/744acd2eaeaddc216e296cc290db74b0/plot_exercise_4.py b/_downloads/744acd2eaeaddc216e296cc290db74b0/plot_exercise_4.py new file mode 100644 index 000000000..2ea03614f --- /dev/null +++ b/_downloads/744acd2eaeaddc216e296cc290db74b0/plot_exercise_4.py @@ -0,0 +1,24 @@ +""" +Exercise 4 +=========== + +Exercise 4 with matplotlib. +""" + +import numpy as np +import matplotlib.pyplot as plt + +plt.figure(figsize=(8, 5), dpi=80) +plt.subplot(111) + +X = np.linspace(-np.pi, np.pi, 256) +S = np.sin(X) +C = np.cos(X) + +plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") +plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") + +plt.xlim(X.min() * 1.1, X.max() * 1.1) +plt.ylim(C.min() * 1.1, C.max() * 1.1) + +plt.show() diff --git a/_downloads/754b39f073a8b9961b2110f23cb15e1e/plot_ticks.zip b/_downloads/754b39f073a8b9961b2110f23cb15e1e/plot_ticks.zip new file mode 100644 index 000000000..c46b89ffe Binary files /dev/null and b/_downloads/754b39f073a8b9961b2110f23cb15e1e/plot_ticks.zip differ diff --git a/_downloads/7652d267b9fb81f033f52fbc98fc3bbf/plot_grid.zip b/_downloads/7652d267b9fb81f033f52fbc98fc3bbf/plot_grid.zip new file mode 100644 index 000000000..ca15204ff Binary files /dev/null and b/_downloads/7652d267b9fb81f033f52fbc98fc3bbf/plot_grid.zip differ diff --git a/_downloads/76fdd1eb6ef9c7f8c58f0c5ed2d50e4e/plot_linestyles.ipynb b/_downloads/76fdd1eb6ef9c7f8c58f0c5ed2d50e4e/plot_linestyles.ipynb new file mode 100644 index 000000000..fe6a9d2a5 --- /dev/null +++ b/_downloads/76fdd1eb6ef9c7f8c58f0c5ed2d50e4e/plot_linestyles.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Linestyles\n\nPlot the different line styles.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef linestyle(ls, i):\n X = i * 0.5 * np.ones(11)\n Y = np.arange(11)\n plt.plot(\n X,\n Y,\n ls,\n color=(0.0, 0.0, 1, 1),\n lw=3,\n ms=8,\n mfc=(0.75, 0.75, 1, 1),\n mec=(0, 0, 1, 1),\n )\n plt.text(0.5 * i, 10.25, ls, rotation=90, fontsize=15, va=\"bottom\")\n\n\nlinestyles = [\n \"-\",\n \"--\",\n \":\",\n \"-.\",\n \".\",\n \",\",\n \"o\",\n \"^\",\n \"v\",\n \"<\",\n \">\",\n \"s\",\n \"+\",\n \"x\",\n \"d\",\n \"1\",\n \"2\",\n \"3\",\n \"4\",\n \"h\",\n \"p\",\n \"|\",\n \"_\",\n \"D\",\n \"H\",\n]\nn_lines = len(linestyles)\n\nsize = 20 * n_lines, 300\ndpi = 72.0\nfigsize = size[0] / float(dpi), size[1] / float(dpi)\nfig = plt.figure(figsize=figsize, dpi=dpi)\nplt.axes((0, 0.01, 1, 0.9), frameon=False)\n\nfor i, ls in enumerate(linestyles):\n linestyle(ls, i)\n\nplt.xlim(-0.2, 0.2 + 0.5 * n_lines)\nplt.xticks([])\nplt.yticks([])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/771b051163d7a6d27c28c4bc30cfbcd9/plot_interpolation_face.ipynb b/_downloads/771b051163d7a6d27c28c4bc30cfbcd9/plot_interpolation_face.ipynb new file mode 100644 index 000000000..cca19965e --- /dev/null +++ b/_downloads/771b051163d7a6d27c28c4bc30cfbcd9/plot_interpolation_face.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Image interpolation\n\nThe example demonstrates image interpolation on a Raccoon face.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import scipy as sp\nimport matplotlib.pyplot as plt\n\nf = sp.datasets.face(gray=True)\n\nplt.figure(figsize=(8, 4))\n\nplt.subplot(1, 2, 1)\nplt.imshow(f[320:340, 510:530], cmap=\"gray\")\nplt.axis(\"off\")\n\nplt.subplot(1, 2, 2)\nplt.imshow(f[320:340, 510:530], cmap=\"gray\", interpolation=\"nearest\")\nplt.axis(\"off\")\n\nplt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1)\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/773dc99bdbb7f8745dde3665b6afd346/plot_convex.ipynb b/_downloads/773dc99bdbb7f8745dde3665b6afd346/plot_convex.ipynb new file mode 100644 index 000000000..d556718eb --- /dev/null +++ b/_downloads/773dc99bdbb7f8745dde3665b6afd346/plot_convex.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Convex function\n\nA figure showing the definition of a convex function\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.linspace(-1, 2)\n\nplt.figure(1, figsize=(3, 2.5))\nplt.clf()\n\n# A convex function\nplt.plot(x, x**2, linewidth=2)\nplt.text(-0.7, -(0.6**2), \"$f$\", size=20)\n\n# The tangent in one point\nplt.plot(x, 2 * x - 1)\nplt.plot(1, 1, \"k+\")\nplt.text(0.3, -0.75, \"Tangent to $f$\", size=15)\nplt.text(1, 1 - 0.5, \"C\", size=15)\n\n# Convexity as barycenter\nplt.plot([0.35, 1.85], [0.35**2, 1.85**2])\nplt.plot([0.35, 1.85], [0.35**2, 1.85**2], \"k+\")\nplt.text(0.35 - 0.2, 0.35**2 + 0.1, \"A\", size=15)\nplt.text(1.85 - 0.2, 1.85**2, \"B\", size=15)\n\nplt.ylim(ymin=-1)\nplt.axis(\"off\")\nplt.tight_layout()\n\n# Convexity as barycenter\nplt.figure(2, figsize=(3, 2.5))\nplt.clf()\nplt.plot(x, x**2 + np.exp(-5 * (x - 0.5) ** 2), linewidth=2)\nplt.text(-0.7, -(0.6**2), \"$f$\", size=20)\n\nplt.ylim(ymin=-1)\nplt.axis(\"off\")\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/77f34a3a3e9fbc6b013d9a15222035a1/plot_resample.py b/_downloads/77f34a3a3e9fbc6b013d9a15222035a1/plot_resample.py new file mode 100644 index 000000000..11d20e256 --- /dev/null +++ b/_downloads/77f34a3a3e9fbc6b013d9a15222035a1/plot_resample.py @@ -0,0 +1,30 @@ +""" +Resample a signal with scipy.signal.resample +============================================= + +:func:`scipy.signal.resample` uses FFT to resample a 1D signal. +""" + +############################################################ +# Generate a signal with 100 data point +import numpy as np + +t = np.linspace(0, 5, 100) +x = np.sin(t) + +############################################################ +# Downsample it by a factor of 4 +import scipy as sp + +x_resampled = sp.signal.resample(x, 25) + +############################################################ +# Plot +import matplotlib.pyplot as plt + +plt.figure(figsize=(5, 4)) +plt.plot(t, x, label="Original signal") +plt.plot(t[::4], x_resampled, "ko", label="Resampled signal") + +plt.legend(loc="best") +plt.show() diff --git a/_downloads/787232bd98a3c806a60b0975b160a5a4/plot_exercise_7.py b/_downloads/787232bd98a3c806a60b0975b160a5a4/plot_exercise_7.py new file mode 100644 index 000000000..98f7a1ab9 --- /dev/null +++ b/_downloads/787232bd98a3c806a60b0975b160a5a4/plot_exercise_7.py @@ -0,0 +1,38 @@ +""" +Exercise 7 +=========== + +Exercise 7 with matplotlib +""" + +import numpy as np +import matplotlib.pyplot as plt + +plt.figure(figsize=(8, 5), dpi=80) +plt.subplot(111) + +X = np.linspace(-np.pi, np.pi, 256, endpoint=True) +C = np.cos(X) +S = np.sin(X) + +plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") +plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") + +ax = plt.gca() +ax.spines["right"].set_color("none") +ax.spines["top"].set_color("none") +ax.xaxis.set_ticks_position("bottom") +ax.spines["bottom"].set_position(("data", 0)) +ax.yaxis.set_ticks_position("left") +ax.spines["left"].set_position(("data", 0)) + +plt.xlim(X.min() * 1.1, X.max() * 1.1) +plt.xticks( + [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], + [r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"], +) + +plt.ylim(C.min() * 1.1, C.max() * 1.1) +plt.yticks([-1, 0, +1], [r"$-1$", r"$0$", r"$+1$"]) + +plt.show() diff --git a/_downloads/787a9a6a4e2aba394885ef1a8ebdd639/plot_normal_distribution.zip b/_downloads/787a9a6a4e2aba394885ef1a8ebdd639/plot_normal_distribution.zip new file mode 100644 index 000000000..6f0af20e9 Binary files /dev/null and b/_downloads/787a9a6a4e2aba394885ef1a8ebdd639/plot_normal_distribution.zip differ diff --git a/_downloads/78875376bd4dd31db37903698f0fccbe/plot_linewidth.zip b/_downloads/78875376bd4dd31db37903698f0fccbe/plot_linewidth.zip new file mode 100644 index 000000000..4788ac077 Binary files /dev/null and b/_downloads/78875376bd4dd31db37903698f0fccbe/plot_linewidth.zip differ diff --git a/_downloads/78b6f6f2e71bfcf28d5d8718f86e2da7/plot_resample.zip b/_downloads/78b6f6f2e71bfcf28d5d8718f86e2da7/plot_resample.zip new file mode 100644 index 000000000..70541b71d Binary files /dev/null and b/_downloads/78b6f6f2e71bfcf28d5d8718f86e2da7/plot_resample.zip differ diff --git a/_downloads/78e6c2098b358d5ff00ea0f04c2cd0dd/plot_scatter.zip b/_downloads/78e6c2098b358d5ff00ea0f04c2cd0dd/plot_scatter.zip new file mode 100644 index 000000000..7cd2f7c49 Binary files /dev/null and b/_downloads/78e6c2098b358d5ff00ea0f04c2cd0dd/plot_scatter.zip differ diff --git a/_downloads/7905a944d50cd667d081d6a2590587d6/plot_compare_optimizers.py b/_downloads/7905a944d50cd667d081d6a2590587d6/plot_compare_optimizers.py new file mode 100644 index 000000000..034106cbf --- /dev/null +++ b/_downloads/7905a944d50cd667d081d6a2590587d6/plot_compare_optimizers.py @@ -0,0 +1,105 @@ +""" +Plotting the comparison of optimizers +====================================== + +Plots the results from the comparison of optimizers. + +""" + +import pickle +import sys + +import numpy as np + +import matplotlib +import matplotlib.pyplot as plt + +results = pickle.load( + open(f"helper/compare_optimizers_py{sys.version_info[0]}.pkl", "rb") +) +n_methods = len(list(results.values())[0]["Rosenbrock "]) +n_dims = len(results) + +symbols = "o>*Ds" + +plt.figure(1, figsize=(10, 4)) +plt.clf() + +nipy_spectral = matplotlib.colormaps["nipy_spectral"] +colors = nipy_spectral(np.linspace(0, 1, n_dims))[:, :3] + +method_names = list(list(results.values())[0]["Rosenbrock "].keys()) +method_names.sort(key=lambda x: x[::-1], reverse=True) + +for n_dim_index, ((n_dim, n_dim_bench), color) in enumerate( + zip(sorted(results.items()), colors, strict=True) +): + for (cost_name, cost_bench), symbol in zip( + sorted(n_dim_bench.items()), symbols, strict=True + ): + for ( + method_index, + method_name, + ) in enumerate(method_names): + this_bench = cost_bench[method_name] + bench = np.mean(this_bench) + plt.semilogy( + [ + method_index + 0.1 * n_dim_index, + ], + [ + bench, + ], + marker=symbol, + color=color, + ) + +# Create a legend for the problem type +for cost_name, symbol in zip(sorted(n_dim_bench.keys()), symbols, strict=True): + plt.semilogy( + [ + -10, + ], + [ + 0, + ], + symbol, + color=".5", + label=cost_name, + ) + +plt.xticks(np.arange(n_methods), method_names, size=11) +plt.xlim(-0.2, n_methods - 0.5) +plt.legend(loc="best", numpoints=1, handletextpad=0, prop={"size": 12}, frameon=False) +plt.ylabel("# function calls (a.u.)") + +# Create a second legend for the problem dimensionality +plt.twinx() + +for n_dim, color in zip(sorted(results.keys()), colors, strict=True): + plt.plot( + [ + -10, + ], + [ + 0, + ], + "o", + color=color, + label="# dim: %i" % n_dim, + ) +plt.legend( + loc=(0.47, 0.07), + numpoints=1, + handletextpad=0, + prop={"size": 12}, + frameon=False, + ncol=2, +) +plt.xlim(-0.2, n_methods - 0.5) + +plt.xticks(np.arange(n_methods), method_names) +plt.yticks(()) + +plt.tight_layout() +plt.show() diff --git a/_downloads/79d684df11b316e1cb0b39958be9d973/plot_scatter_ext.zip b/_downloads/79d684df11b316e1cb0b39958be9d973/plot_scatter_ext.zip new file mode 100644 index 000000000..3a588c27b Binary files /dev/null and b/_downloads/79d684df11b316e1cb0b39958be9d973/plot_scatter_ext.zip differ diff --git a/_downloads/7a5f733c51db3ecde900f56ffc927e1a/plot_polyfit.py b/_downloads/7a5f733c51db3ecde900f56ffc927e1a/plot_polyfit.py new file mode 100644 index 000000000..b39c57682 --- /dev/null +++ b/_downloads/7a5f733c51db3ecde900f56ffc927e1a/plot_polyfit.py @@ -0,0 +1,20 @@ +""" +Fitting to polynomial +===================== + +Plot noisy data and their polynomial fit + +""" + +import numpy as np +import matplotlib.pyplot as plt + +rng = np.random.default_rng(27446968) + +x = np.linspace(0, 1, 20) +y = np.cos(x) + 0.3 * rng.random(20) +p = np.poly1d(np.polyfit(x, y, 3)) + +t = np.linspace(0, 1, 200) +plt.plot(x, y, "o", t, p(t), "-") +plt.show() diff --git a/_downloads/7a9948d5a99297ffb65c09c5b5050d70/plot_wage_education_gender.py b/_downloads/7a9948d5a99297ffb65c09c5b5050d70/plot_wage_education_gender.py new file mode 100644 index 000000000..6818895a3 --- /dev/null +++ b/_downloads/7a9948d5a99297ffb65c09c5b5050d70/plot_wage_education_gender.py @@ -0,0 +1,91 @@ +""" +Test for an education/gender interaction in wages +================================================== + +Wages depend mostly on education. Here we investigate how this dependence +is related to gender: not only does gender create an offset in wages, it +also seems that wages increase more with education for males than +females. + +Does our data support this last hypothesis? We will test this using +statsmodels' formulas +(http://statsmodels.sourceforge.net/stable/example_formulas.html). + +""" + +############################################################################## +# Load and massage the data +import pandas + +import urllib.request +import os + +if not os.path.exists("wages.txt"): + # Download the file if it is not present + url = "http://lib.stat.cmu.edu/datasets/CPS_85_Wages" + with urllib.request.urlopen(url) as r, open("wages.txt", "wb") as f: + f.write(r.read()) + +# EDUCATION: Number of years of education +# SEX: 1=Female, 0=Male +# WAGE: Wage (dollars per hour) +data = pandas.read_csv( + "wages.txt", + skiprows=27, + skipfooter=6, + sep=None, + header=None, + names=["education", "gender", "wage"], + usecols=[0, 2, 5], +) + +# Convert genders to strings (this is particularly useful so that the +# statsmodels formulas detects that gender is a categorical variable) +import numpy as np + +data["gender"] = np.choose(data.gender, ["male", "female"]) + +# Log-transform the wages, because they typically are increased with +# multiplicative factors +data["wage"] = np.log10(data["wage"]) + + +############################################################################## +# simple plotting +import seaborn + +# Plot 2 linear fits for male and female. +seaborn.lmplot(y="wage", x="education", hue="gender", data=data) + + +############################################################################## +# statistical analysis +import statsmodels.formula.api as sm + +# Note that this model is not the plot displayed above: it is one +# joined model for male and female, not separate models for male and +# female. The reason is that a single model enables statistical testing +result = sm.ols(formula="wage ~ education + gender", data=data).fit() +print(result.summary()) + + +############################################################################## +# The plots above highlight that there is not only a different offset in +# wage but also a different slope +# +# We need to model this using an interaction +result = sm.ols( + formula="wage ~ education + gender + education * gender", data=data +).fit() +print(result.summary()) + + +############################################################################## +# Looking at the p-value of the interaction of gender and education, the +# data does not support the hypothesis that education benefits males +# more than female (p-value > 0.05). + + +import matplotlib.pyplot as plt + +plt.show() diff --git a/_downloads/7ad801cfc01c7834f88f116ee4bd9253/plot_iris_scatter.py b/_downloads/7ad801cfc01c7834f88f116ee4bd9253/plot_iris_scatter.py new file mode 100644 index 000000000..54c738314 --- /dev/null +++ b/_downloads/7ad801cfc01c7834f88f116ee4bd9253/plot_iris_scatter.py @@ -0,0 +1,33 @@ +""" +Plot 2D views of the iris dataset +================================= + +Plot a simple scatter plot of 2 features of the iris dataset. + +Note that more elaborate visualization of this dataset is detailed +in the :ref:`statistics` chapter. +""" + +# Load the data +from sklearn.datasets import load_iris + +iris = load_iris() + +from matplotlib import ticker +import matplotlib.pyplot as plt + +# The indices of the features that we are plotting +x_index = 0 +y_index = 1 + +# this formatter will label the colorbar with the correct target names +formatter = ticker.FuncFormatter(lambda i, *args: iris.target_names[int(i)]) + +plt.figure(figsize=(5, 4)) +plt.scatter(iris.data[:, x_index], iris.data[:, y_index], c=iris.target) +plt.colorbar(ticks=[0, 1, 2], format=formatter) +plt.xlabel(iris.feature_names[x_index]) +plt.ylabel(iris.feature_names[y_index]) + +plt.tight_layout() +plt.show() diff --git a/_downloads/7b6f246877addfb4a9c029a09f7cfb9e/plot_text.zip b/_downloads/7b6f246877addfb4a9c029a09f7cfb9e/plot_text.zip new file mode 100644 index 000000000..8a3d5b3de Binary files /dev/null and b/_downloads/7b6f246877addfb4a9c029a09f7cfb9e/plot_text.zip differ diff --git a/_downloads/7bf71267da8d4813316c9c1e2c4e994b/plot_equalize_hist.zip b/_downloads/7bf71267da8d4813316c9c1e2c4e994b/plot_equalize_hist.zip new file mode 100644 index 000000000..04eeb1674 Binary files /dev/null and b/_downloads/7bf71267da8d4813316c9c1e2c4e994b/plot_equalize_hist.zip differ diff --git a/_downloads/7d8c1bd81d3b9548270815c6091455ac/plot_exercise_1.ipynb b/_downloads/7d8c1bd81d3b9548270815c6091455ac/plot_exercise_1.ipynb new file mode 100644 index 000000000..4e7bfce2c --- /dev/null +++ b/_downloads/7d8c1bd81d3b9548270815c6091455ac/plot_exercise_1.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Exercise 1\n\nSolution of the exercise 1 with matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nn = 256\nX = np.linspace(-np.pi, np.pi, 256)\nC, S = np.cos(X), np.sin(X)\nplt.plot(X, C)\nplt.plot(X, S)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/7db363978ca478abcd6c3427dade3344/plot_plot3d_ext.ipynb b/_downloads/7db363978ca478abcd6c3427dade3344/plot_plot3d_ext.ipynb new file mode 100644 index 000000000..c26cddbd1 --- /dev/null +++ b/_downloads/7db363978ca478abcd6c3427dade3344/plot_plot3d_ext.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# 3D plotting vignette\n\nDemo 3D plotting with matplotlib and decorate the figure.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure()\nax = Axes3D(fig)\nX = np.arange(-4, 4, 0.25)\nY = np.arange(-4, 4, 0.25)\nX, Y = np.meshgrid(X, Y)\nR = np.sqrt(X**2 + Y**2)\nZ = np.sin(R)\n\nax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=\"hot\")\nax.contourf(X, Y, Z, zdir=\"z\", offset=-2, cmap=\"hot\")\nax.set_zlim(-2, 2)\nplt.xticks([])\nplt.yticks([])\nax.set_zticks([])\n\nax.text2D(\n 0.05,\n 0.93,\n \" 3D plots \\n\",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"xx-large\",\n bbox={\"facecolor\": \"white\", \"alpha\": 1.0},\n transform=plt.gca().transAxes,\n)\n\nax.text2D(\n 0.05,\n 0.87,\n \" Plot 2D or 3D data\",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"large\",\n transform=plt.gca().transAxes,\n)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/7f7f8acc9ddab13f92d2fa6038efa3e4/plot_plot.ipynb b/_downloads/7f7f8acc9ddab13f92d2fa6038efa3e4/plot_plot.ipynb new file mode 100644 index 000000000..46a2f4395 --- /dev/null +++ b/_downloads/7f7f8acc9ddab13f92d2fa6038efa3e4/plot_plot.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot and filled plots\n\nSimple example of plots and filling between them with matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nn = 256\nX = np.linspace(-np.pi, np.pi, n)\nY = np.sin(2 * X)\n\nplt.axes((0.025, 0.025, 0.95, 0.95))\n\nplt.plot(X, Y + 1, color=\"blue\", alpha=1.00)\nplt.fill_between(X, 1, Y + 1, color=\"blue\", alpha=0.25)\n\nplt.plot(X, Y - 1, color=\"blue\", alpha=1.00)\nplt.fill_between(X, -1, Y - 1, (Y - 1) > -1, color=\"blue\", alpha=0.25)\nplt.fill_between(X, -1, Y - 1, (Y - 1) < -1, color=\"red\", alpha=0.25)\n\nplt.xlim(-np.pi, np.pi)\nplt.xticks([])\nplt.ylim(-2.5, 2.5)\nplt.yticks([])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/7fc517f348aceffd7980a68c80194844/2_2_data_statistics.py b/_downloads/7fc517f348aceffd7980a68c80194844/2_2_data_statistics.py new file mode 100644 index 000000000..7c26ad387 --- /dev/null +++ b/_downloads/7fc517f348aceffd7980a68c80194844/2_2_data_statistics.py @@ -0,0 +1,33 @@ +import numpy as np + +data = np.loadtxt("../../../data/populations.txt") +year, hares, lynxes, carrots = data.T +populations = data[:, 1:] + +print(" Hares, Lynxes, Carrots") +print("Mean:", populations.mean(axis=0)) +print("Std:", populations.std(axis=0)) + +j_max_years = np.argmax(populations, axis=0) +print("Max. year:", year[j_max_years]) + +max_species = np.argmax(populations, axis=1) +species = np.array(["Hare", "Lynx", "Carrot"]) +print("Max species:") +print(year) +print(species[max_species]) + +above_50000 = np.any(populations > 50000, axis=1) +print("Any above 50000:", year[above_50000]) + +j_top_2 = np.argsort(populations, axis=0)[:2] +print("Top 2 years with lowest populations for each:") +print(year[j_top_2]) + +hare_grad = np.gradient(hares, 1.0) +print("diff(Hares) vs. Lynxes correlation", np.corrcoef(hare_grad, lynxes)[0, 1]) + +import matplotlib.pyplot as plt + +plt.plot(year, hare_grad, year, -lynxes) +plt.savefig("plot.png") diff --git a/_downloads/7fc8763c311f03848fdb4847e36113b0/plot_find_edges.ipynb b/_downloads/7fc8763c311f03848fdb4847e36113b0/plot_find_edges.ipynb new file mode 100644 index 000000000..a431a19bd --- /dev/null +++ b/_downloads/7fc8763c311f03848fdb4847e36113b0/plot_find_edges.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Finding edges with Sobel filters\n\nThe Sobel filter is one of the simplest way of finding edges.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nrng = np.random.default_rng(27446968)\n\nim = np.zeros((256, 256))\nim[64:-64, 64:-64] = 1\n\nim = sp.ndimage.rotate(im, 15, mode=\"constant\")\nim = sp.ndimage.gaussian_filter(im, 8)\n\nsx = sp.ndimage.sobel(im, axis=0, mode=\"constant\")\nsy = sp.ndimage.sobel(im, axis=1, mode=\"constant\")\nsob = np.hypot(sx, sy)\n\nplt.figure(figsize=(16, 5))\nplt.subplot(141)\nplt.imshow(im, cmap=\"gray\")\nplt.axis(\"off\")\nplt.title(\"square\", fontsize=20)\nplt.subplot(142)\nplt.imshow(sx)\nplt.axis(\"off\")\nplt.title(\"Sobel (x direction)\", fontsize=20)\nplt.subplot(143)\nplt.imshow(sob)\nplt.axis(\"off\")\nplt.title(\"Sobel filter\", fontsize=20)\n\nim += 0.07 * rng.random(im.shape)\n\nsx = sp.ndimage.sobel(im, axis=0, mode=\"constant\")\nsy = sp.ndimage.sobel(im, axis=1, mode=\"constant\")\nsob = np.hypot(sx, sy)\n\nplt.subplot(144)\nplt.imshow(sob)\nplt.axis(\"off\")\nplt.title(\"Sobel for noisy image\", fontsize=20)\n\n\nplt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=0.9)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/807a4e47b5dc0dc7a5e796b905361e65/plot_exercise_8.zip b/_downloads/807a4e47b5dc0dc7a5e796b905361e65/plot_exercise_8.zip new file mode 100644 index 000000000..2164ea10d Binary files /dev/null and b/_downloads/807a4e47b5dc0dc7a5e796b905361e65/plot_exercise_8.zip differ diff --git a/_downloads/81b80feef26945201577b75c3061dfb1/auto_examples_jupyter.zip b/_downloads/81b80feef26945201577b75c3061dfb1/auto_examples_jupyter.zip new file mode 100644 index 000000000..0716bf669 Binary files /dev/null and b/_downloads/81b80feef26945201577b75c3061dfb1/auto_examples_jupyter.zip differ diff --git a/_downloads/81cb4dac76c5a445b7e0097a404bb8ab/plot_face_denoise.py b/_downloads/81cb4dac76c5a445b7e0097a404bb8ab/plot_face_denoise.py new file mode 100644 index 000000000..29601d2a4 --- /dev/null +++ b/_downloads/81cb4dac76c5a445b7e0097a404bb8ab/plot_face_denoise.py @@ -0,0 +1,39 @@ +""" +Image denoising +================ + +This example demoes image denoising on a Raccoon face. +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +rng = np.random.default_rng(27446968) + +f = sp.datasets.face(gray=True) +f = f[230:290, 220:320] + +noisy = f + 0.4 * f.std() * rng.random(f.shape) + +gauss_denoised = sp.ndimage.gaussian_filter(noisy, 2) +med_denoised = sp.ndimage.median_filter(noisy, 3) + + +plt.figure(figsize=(12, 2.8)) + +plt.subplot(131) +plt.imshow(noisy, cmap="gray", vmin=40, vmax=220) +plt.axis("off") +plt.title("noisy", fontsize=20) +plt.subplot(132) +plt.imshow(gauss_denoised, cmap="gray", vmin=40, vmax=220) +plt.axis("off") +plt.title("Gaussian filter", fontsize=20) +plt.subplot(133) +plt.imshow(med_denoised, cmap="gray", vmin=40, vmax=220) +plt.axis("off") +plt.title("Median filter", fontsize=20) + +plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1) +plt.show() diff --git a/_downloads/823258ce931aec94c1f5ee708a7e4d92/plot_smooth.zip b/_downloads/823258ce931aec94c1f5ee708a7e4d92/plot_smooth.zip new file mode 100644 index 000000000..bded2e862 Binary files /dev/null and b/_downloads/823258ce931aec94c1f5ee708a7e4d92/plot_smooth.zip differ diff --git a/_downloads/8291f4bbc97f142049719e85c29674b4/plot_pie.zip b/_downloads/8291f4bbc97f142049719e85c29674b4/plot_pie.zip new file mode 100644 index 000000000..8555cc98e Binary files /dev/null and b/_downloads/8291f4bbc97f142049719e85c29674b4/plot_pie.zip differ diff --git a/_downloads/82a5d60cacda7af3740a0633cac3ccb0/plot_threshold.py b/_downloads/82a5d60cacda7af3740a0633cac3ccb0/plot_threshold.py new file mode 100644 index 000000000..b03c75df4 --- /dev/null +++ b/_downloads/82a5d60cacda7af3740a0633cac3ccb0/plot_threshold.py @@ -0,0 +1,30 @@ +""" +Otsu thresholding +================== + +This example illustrates automatic Otsu thresholding. +""" + +import matplotlib.pyplot as plt +from skimage import data +from skimage import filters +from skimage import exposure + +camera = data.camera() +val = filters.threshold_otsu(camera) + +hist, bins_center = exposure.histogram(camera) + +plt.figure(figsize=(9, 4)) +plt.subplot(131) +plt.imshow(camera, cmap="gray", interpolation="nearest") +plt.axis("off") +plt.subplot(132) +plt.imshow(camera < val, cmap="gray", interpolation="nearest") +plt.axis("off") +plt.subplot(133) +plt.plot(bins_center, hist, lw=2) +plt.axvline(val, color="k", ls="--") + +plt.tight_layout() +plt.show() diff --git a/_downloads/82d41d3015024d0ccb97d78fee2a5a89/index_error.py b/_downloads/82d41d3015024d0ccb97d78fee2a5a89/index_error.py new file mode 100644 index 000000000..90f4ec581 --- /dev/null +++ b/_downloads/82d41d3015024d0ccb97d78fee2a5a89/index_error.py @@ -0,0 +1,10 @@ +"""Small snippet to raise an IndexError.""" + + +def index_error(): + lst = list("foobar") + print(lst[len(lst)]) + + +if __name__ == "__main__": + index_error() diff --git a/_downloads/82dd5f438b506c6169568b5a9ad02652/auto_examples_python.zip b/_downloads/82dd5f438b506c6169568b5a9ad02652/auto_examples_python.zip new file mode 100644 index 000000000..c5cbff518 Binary files /dev/null and b/_downloads/82dd5f438b506c6169568b5a9ad02652/auto_examples_python.zip differ diff --git a/_downloads/83508a65265829c4246a6c0e4522d218/plot_bad.zip b/_downloads/83508a65265829c4246a6c0e4522d218/plot_bad.zip new file mode 100644 index 000000000..75063eefc Binary files /dev/null and b/_downloads/83508a65265829c4246a6c0e4522d218/plot_bad.zip differ diff --git a/_downloads/849658b414081c58162c8806dee210de/plot_linear_regression.zip b/_downloads/849658b414081c58162c8806dee210de/plot_linear_regression.zip new file mode 100644 index 000000000..dac85d52a Binary files /dev/null and b/_downloads/849658b414081c58162c8806dee210de/plot_linear_regression.zip differ diff --git a/_downloads/84e210a8e105ce82deb47aaec574b27e/plot_non_bounds_constraints.py b/_downloads/84e210a8e105ce82deb47aaec574b27e/plot_non_bounds_constraints.py new file mode 100644 index 000000000..a694dddfe --- /dev/null +++ b/_downloads/84e210a8e105ce82deb47aaec574b27e/plot_non_bounds_constraints.py @@ -0,0 +1,58 @@ +""" +Optimization with constraints +================================ + +An example showing how to do optimization with general constraints using +SLSQP and cobyla. +""" + +import numpy as np +import matplotlib.pyplot as plt +import scipy as sp + +x, y = np.mgrid[-2.03:4.2:0.04, -1.6:3.2:0.04] # type: ignore[misc] +x = x.T +y = y.T + +plt.figure(1, figsize=(3, 2.5)) +plt.clf() +plt.axes((0, 0, 1, 1)) + +contours = plt.contour( + np.sqrt((x - 3) ** 2 + (y - 2) ** 2), + extent=[-2.03, 4.2, -1.6, 3.2], + cmap="gnuplot", +) +plt.clabel(contours, inline=1, fmt="%1.1f", fontsize=14) +plt.plot([-1.5, 0, 1.5, 0, -1.5], [0, 1.5, 0, -1.5, 0], "k", linewidth=2) +plt.fill_between([-1.5, 0, 1.5], [0, -1.5, 0], [0, 1.5, 0], color=".8") +plt.axvline(0, color="k") +plt.axhline(0, color="k") + +plt.text(-0.9, 2.8, "$x_2$", size=20) +plt.text(3.6, -0.6, "$x_1$", size=20) +plt.axis("tight") +plt.axis("off") + +# And now plot the optimization path +accumulator = [] + + +def f(x): + # Store the list of function calls + accumulator.append(x) + return np.sqrt((x[0] - 3) ** 2 + (x[1] - 2) ** 2) + + +def constraint(x): + return np.atleast_1d(1.5 - np.sum(np.abs(x))) + + +sp.optimize.minimize( + f, np.array([0, 0]), method="SLSQP", constraints={"fun": constraint, "type": "ineq"} +) + +accumulated = np.array(accumulator) +plt.plot(accumulated[:, 0], accumulated[:, 1]) + +plt.show() diff --git a/_downloads/84f42e9bb31f1d50de1e20d740af16cc/plot_greyscale_dilation.zip b/_downloads/84f42e9bb31f1d50de1e20d740af16cc/plot_greyscale_dilation.zip new file mode 100644 index 000000000..13e6d614e Binary files /dev/null and b/_downloads/84f42e9bb31f1d50de1e20d740af16cc/plot_greyscale_dilation.zip differ diff --git a/_downloads/85de001e88853aac9678c7f3fcdb819e/plot_exercise_6.zip b/_downloads/85de001e88853aac9678c7f3fcdb819e/plot_exercise_6.zip new file mode 100644 index 000000000..a1f46976d Binary files /dev/null and b/_downloads/85de001e88853aac9678c7f3fcdb819e/plot_exercise_6.zip differ diff --git a/_downloads/8604fa43f4253cc000c59ee6fd6f9d19/plot_synthetic_data.zip b/_downloads/8604fa43f4253cc000c59ee6fd6f9d19/plot_synthetic_data.zip new file mode 100644 index 000000000..3c0eb440f Binary files /dev/null and b/_downloads/8604fa43f4253cc000c59ee6fd6f9d19/plot_synthetic_data.zip differ diff --git a/_downloads/86250585d7f3cc220720dc012bf75516/plot_optimize_example2.ipynb b/_downloads/86250585d7f3cc220720dc012bf75516/plot_optimize_example2.ipynb new file mode 100644 index 000000000..f2afdab7f --- /dev/null +++ b/_downloads/86250585d7f3cc220720dc012bf75516/plot_optimize_example2.ipynb @@ -0,0 +1,104 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Minima and roots of a function\n\nDemos finding minima and roots of a function.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Define the function\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n\nx = np.arange(-10, 10, 0.1)\n\n\ndef f(x):\n return x**2 + 10 * np.sin(x)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Find minima\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import scipy as sp\n\n# Global optimization\ngrid = (-10, 10, 0.1)\nxmin_global = sp.optimize.brute(f, (grid,))\nprint(f\"Global minima found {xmin_global}\")\n\n# Constrain optimization\nxmin_local = sp.optimize.fminbound(f, 0, 10)\nprint(f\"Local minimum found {xmin_local}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Root finding\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "root = sp.optimize.root(f, 1) # our initial guess is 1\nprint(f\"First root found {root.x}\")\nroot2 = sp.optimize.root(f, -2.5)\nprint(f\"Second root found {root2.x}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Plot function, minima, and roots\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nfig = plt.figure(figsize=(6, 4))\nax = fig.add_subplot(111)\n\n# Plot the function\nax.plot(x, f(x), \"b-\", label=\"f(x)\")\n\n# Plot the minima\nxmins = np.array([xmin_global[0], xmin_local])\nax.plot(xmins, f(xmins), \"go\", label=\"Minima\")\n\n# Plot the roots\nroots = np.array([root.x, root2.x])\nax.plot(roots, f(roots), \"kv\", label=\"Roots\")\n\n# Decorate the figure\nax.legend(loc=\"best\")\nax.set_xlabel(\"x\")\nax.set_ylabel(\"f(x)\")\nax.axhline(0, color=\"gray\")\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/866c79d9270433bca47a31f132ec663b/plot_plot3d-2.ipynb b/_downloads/866c79d9270433bca47a31f132ec663b/plot_plot3d-2.ipynb new file mode 100644 index 000000000..e3cb12bbe --- /dev/null +++ b/_downloads/866c79d9270433bca47a31f132ec663b/plot_plot3d-2.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# 3D plotting\n\nDemo 3D plotting with matplotlib and style the figure.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d.axes3d import Axes3D, get_test_data\n\nax: Axes3D = plt.figure().add_subplot(projection=\"3d\")\nX, Y, Z = get_test_data(0.05)\ncset = ax.contourf(X, Y, Z)\nax.clabel(cset, fontsize=9, inline=1)\n\nplt.xticks([])\nplt.yticks([])\nax.set_zticks([])\n\n\nax.text2D(\n -0.05,\n 1.05,\n \" 3D plots \\n\",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n bbox={\"facecolor\": \"white\", \"alpha\": 1.0},\n family=\"DejaVu Sans\",\n size=\"x-large\",\n transform=plt.gca().transAxes,\n)\n\nax.text2D(\n -0.05,\n 0.975,\n \" Plot 2D or 3D data\",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n family=\"DejaVu Sans\",\n size=\"medium\",\n transform=plt.gca().transAxes,\n)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/86c0bcca22f591312240f58580642c4c/plot_propagation.py b/_downloads/86c0bcca22f591312240f58580642c4c/plot_propagation.py new file mode 100644 index 000000000..9a98c2636 --- /dev/null +++ b/_downloads/86c0bcca22f591312240f58580642c4c/plot_propagation.py @@ -0,0 +1,35 @@ +""" +Opening, erosion, and propagation +================================== + +This example shows simple operations of mathematical morphology. +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +square = np.zeros((32, 32)) +square[10:-10, 10:-10] = 1 +rng = np.random.default_rng(27446968) +x, y = (32 * rng.random((2, 20))).astype(int) +square[x, y] = 1 + +open_square = sp.ndimage.binary_opening(square) + +eroded_square = sp.ndimage.binary_erosion(square) +reconstruction = sp.ndimage.binary_propagation(eroded_square, mask=square) + +plt.figure(figsize=(9.5, 3)) +plt.subplot(131) +plt.imshow(square, cmap="gray", interpolation="nearest") +plt.axis("off") +plt.subplot(132) +plt.imshow(open_square, cmap="gray", interpolation="nearest") +plt.axis("off") +plt.subplot(133) +plt.imshow(reconstruction, cmap="gray", interpolation="nearest") +plt.axis("off") + +plt.subplots_adjust(wspace=0, hspace=0.02, top=0.99, bottom=0.01, left=0.01, right=0.99) +plt.show() diff --git a/_downloads/86ec77d40d7acd6b162e1b12e71de034/plot_radial_mean.zip b/_downloads/86ec77d40d7acd6b162e1b12e71de034/plot_radial_mean.zip new file mode 100644 index 000000000..61296b2e7 Binary files /dev/null and b/_downloads/86ec77d40d7acd6b162e1b12e71de034/plot_radial_mean.zip differ diff --git a/_downloads/86f0aa93444d3ad46192a466c68d0d5a/plot_wage_data.py b/_downloads/86f0aa93444d3ad46192a466c68d0d5a/plot_wage_data.py new file mode 100644 index 000000000..f7b2b0811 --- /dev/null +++ b/_downloads/86f0aa93444d3ad46192a466c68d0d5a/plot_wage_data.py @@ -0,0 +1,83 @@ +""" +Visualizing factors influencing wages +===================================== + +This example uses seaborn to quickly plot various factors relating wages, +experience, and education. + +Seaborn (https://seaborn.pydata.org) is a library that combines +visualization and statistical fits to show trends in data. + +Note that importing seaborn changes the matplotlib style to have an +"excel-like" feeling. This changes affect other matplotlib figures. To +restore defaults once this example is run, we would need to call +plt.rcdefaults(). +""" + +# Standard library imports +import os + +import matplotlib.pyplot as plt + +############################################################################## +# Load the data +import pandas +import requests + +if not os.path.exists("wages.txt"): + # Download the file if it is not present + r = requests.get("http://lib.stat.cmu.edu/datasets/CPS_85_Wages") + with open("wages.txt", "wb") as f: + f.write(r.content) + +# Give names to the columns +names = [ + "EDUCATION: Number of years of education", + "SOUTH: 1=Person lives in South, 0=Person lives elsewhere", + "SEX: 1=Female, 0=Male", + "EXPERIENCE: Number of years of work experience", + "UNION: 1=Union member, 0=Not union member", + "WAGE: Wage (dollars per hour)", + "AGE: years", + "RACE: 1=Other, 2=Hispanic, 3=White", + "OCCUPATION: 1=Management, 2=Sales, 3=Clerical, 4=Service, 5=Professional, 6=Other", + "SECTOR: 0=Other, 1=Manufacturing, 2=Construction", + "MARR: 0=Unmarried, 1=Married", +] + +short_names = [n.split(":")[0] for n in names] + +data = pandas.read_csv( + "wages.txt", skiprows=27, skipfooter=6, sep=None, header=None, engine="python" +) +data.columns = pandas.Index(short_names) + +# Log-transform the wages, because they typically are increased with +# multiplicative factors +import numpy as np + +data["WAGE"] = np.log10(data["WAGE"]) + +############################################################################## +# Plot scatter matrices highlighting different aspects + +import seaborn + +seaborn.pairplot(data, vars=["WAGE", "AGE", "EDUCATION"], kind="reg") + +seaborn.pairplot(data, vars=["WAGE", "AGE", "EDUCATION"], kind="reg", hue="SEX") +plt.suptitle("Effect of gender: 1=Female, 0=Male") + +seaborn.pairplot(data, vars=["WAGE", "AGE", "EDUCATION"], kind="reg", hue="RACE") +plt.suptitle("Effect of race: 1=Other, 2=Hispanic, 3=White") + +seaborn.pairplot(data, vars=["WAGE", "AGE", "EDUCATION"], kind="reg", hue="UNION") +plt.suptitle("Effect of union: 1=Union member, 0=Not union member") + + +############################################################################## +# Plot a simple regression + +seaborn.lmplot(y="WAGE", x="EDUCATION", data=data) + +plt.show() diff --git a/_downloads/86f3df5b69db292971728a23d1b71a95/plot_exercise_7.ipynb b/_downloads/86f3df5b69db292971728a23d1b71a95/plot_exercise_7.ipynb new file mode 100644 index 000000000..262129dd7 --- /dev/null +++ b/_downloads/86f3df5b69db292971728a23d1b71a95/plot_exercise_7.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Exercise 7\n\nExercise 7 with matplotlib\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(8, 5), dpi=80)\nplt.subplot(111)\n\nX = np.linspace(-np.pi, np.pi, 256, endpoint=True)\nC = np.cos(X)\nS = np.sin(X)\n\nplt.plot(X, C, color=\"blue\", linewidth=2.5, linestyle=\"-\")\nplt.plot(X, S, color=\"red\", linewidth=2.5, linestyle=\"-\")\n\nax = plt.gca()\nax.spines[\"right\"].set_color(\"none\")\nax.spines[\"top\"].set_color(\"none\")\nax.xaxis.set_ticks_position(\"bottom\")\nax.spines[\"bottom\"].set_position((\"data\", 0))\nax.yaxis.set_ticks_position(\"left\")\nax.spines[\"left\"].set_position((\"data\", 0))\n\nplt.xlim(X.min() * 1.1, X.max() * 1.1)\nplt.xticks(\n [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],\n [r\"$-\\pi$\", r\"$-\\pi/2$\", r\"$0$\", r\"$+\\pi/2$\", r\"$+\\pi$\"],\n)\n\nplt.ylim(C.min() * 1.1, C.max() * 1.1)\nplt.yticks([-1, 0, +1], [r\"$-1$\", r\"$0$\", r\"$+1$\"])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/871fdb856d4a583b346bf2c795d66dae/plot_denoising.ipynb b/_downloads/871fdb856d4a583b346bf2c795d66dae/plot_denoising.ipynb new file mode 100644 index 000000000..e761a7797 --- /dev/null +++ b/_downloads/871fdb856d4a583b346bf2c795d66dae/plot_denoising.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Denoising an image with the median filter\n\nThis example shows the original image, the noisy image, the denoised\none (with the median filter) and the difference between the two.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nrng = np.random.default_rng(27446968)\n\nim = np.zeros((20, 20))\nim[5:-5, 5:-5] = 1\nim = sp.ndimage.distance_transform_bf(im)\nim_noise = im + 0.2 * rng.normal(size=im.shape)\n\nim_med = sp.ndimage.median_filter(im_noise, 3)\n\nplt.figure(figsize=(16, 5))\n\nplt.subplot(141)\nplt.imshow(im, interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.title(\"Original image\", fontsize=20)\nplt.subplot(142)\nplt.imshow(im_noise, interpolation=\"nearest\", vmin=0, vmax=5)\nplt.axis(\"off\")\nplt.title(\"Noisy image\", fontsize=20)\nplt.subplot(143)\nplt.imshow(im_med, interpolation=\"nearest\", vmin=0, vmax=5)\nplt.axis(\"off\")\nplt.title(\"Median filter\", fontsize=20)\nplt.subplot(144)\nplt.imshow(np.abs(im - im_med), cmap=\"hot\", interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.title(\"Error\", fontsize=20)\n\n\nplt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/878c944c61bf270774367269f80928f2/plot_grid_ext.zip b/_downloads/878c944c61bf270774367269f80928f2/plot_grid_ext.zip new file mode 100644 index 000000000..1dd0c51b8 Binary files /dev/null and b/_downloads/878c944c61bf270774367269f80928f2/plot_grid_ext.zip differ diff --git a/_downloads/8812e165083c54750deb2a9868aff357/plot_bias_variance.zip b/_downloads/8812e165083c54750deb2a9868aff357/plot_bias_variance.zip new file mode 100644 index 000000000..1e1974a48 Binary files /dev/null and b/_downloads/8812e165083c54750deb2a9868aff357/plot_bias_variance.zip differ diff --git a/_downloads/88627d0a729972f1004263ea1fc36304/plot_solid_joinstyle.ipynb b/_downloads/88627d0a729972f1004263ea1fc36304/plot_solid_joinstyle.ipynb new file mode 100644 index 000000000..a66dede6d --- /dev/null +++ b/_downloads/88627d0a729972f1004263ea1fc36304/plot_solid_joinstyle.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Solid joint style\n\nAn example showing the different solid joint styles in matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nsize = 256, 16\ndpi = 72.0\nfigsize = size[0] / float(dpi), size[1] / float(dpi)\nfig = plt.figure(figsize=figsize, dpi=dpi)\nfig.patch.set_alpha(0)\nplt.axes((0, 0, 1, 1), frameon=False)\n\nplt.plot(np.arange(3), [0, 1, 0], color=\"blue\", linewidth=8, solid_joinstyle=\"miter\")\nplt.plot(\n 4 + np.arange(3), [0, 1, 0], color=\"blue\", linewidth=8, solid_joinstyle=\"bevel\"\n)\nplt.plot(\n 8 + np.arange(3), [0, 1, 0], color=\"blue\", linewidth=8, solid_joinstyle=\"round\"\n)\n\nplt.xlim(0, 12)\nplt.ylim(-1, 2)\nplt.xticks([])\nplt.yticks([])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/8865c44d716ae6d0ebb9efd7055bd528/plot_svm_non_linear.ipynb b/_downloads/8865c44d716ae6d0ebb9efd7055bd528/plot_svm_non_linear.ipynb new file mode 100644 index 000000000..c273fe2eb --- /dev/null +++ b/_downloads/8865c44d716ae6d0ebb9efd7055bd528/plot_svm_non_linear.ipynb @@ -0,0 +1,79 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Example of linear and non-linear models\n\nThis is an example plot from the tutorial which accompanies an explanation\nof the support vector machine GUI.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn import svm\n\n\nrng = np.random.default_rng(27446968)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "data that is linearly separable\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "def linear_model(rseed=42, n_samples=30):\n \"Generate data according to a linear model\"\n np.random.seed(rseed)\n\n data = np.random.normal(0, 10, (n_samples, 2))\n data[: n_samples // 2] -= 15\n data[n_samples // 2 :] += 15\n\n labels = np.ones(n_samples)\n labels[: n_samples // 2] = -1\n\n return data, labels\n\n\nX, y = linear_model()\nclf = svm.SVC(kernel=\"linear\")\nclf.fit(X, y)\n\nplt.figure(figsize=(6, 4))\nax = plt.subplot(111, xticks=[], yticks=[])\nax.scatter(X[:, 0], X[:, 1], c=y, cmap=\"bone\")\n\nax.scatter(\n clf.support_vectors_[:, 0],\n clf.support_vectors_[:, 1],\n s=80,\n edgecolors=\"k\",\n facecolors=\"none\",\n)\n\ndelta = 1\ny_min, y_max = -50, 50\nx_min, x_max = -50, 50\nx = np.arange(x_min, x_max + delta, delta)\ny = np.arange(y_min, y_max + delta, delta)\nX1, X2 = np.meshgrid(x, y)\nZ = clf.decision_function(np.c_[X1.ravel(), X2.ravel()])\nZ = Z.reshape(X1.shape)\n\nax.contour(\n X1, X2, Z, [-1.0, 0.0, 1.0], colors=\"k\", linestyles=[\"dashed\", \"solid\", \"dashed\"]\n)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "data with a non-linear separation\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "def nonlinear_model(rseed=27446968, n_samples=30):\n rng = np.random.default_rng(rseed)\n\n radius = 40 * rng.random(n_samples)\n far_pts = radius > 20\n radius[far_pts] *= 1.2\n radius[~far_pts] *= 1.1\n\n theta = rng.random(n_samples) * np.pi * 2\n\n data = np.empty((n_samples, 2))\n data[:, 0] = radius * np.cos(theta)\n data[:, 1] = radius * np.sin(theta)\n\n labels = np.ones(n_samples)\n labels[far_pts] = -1\n\n return data, labels\n\n\nX, y = nonlinear_model()\nclf = svm.SVC(kernel=\"rbf\", gamma=0.001, coef0=0, degree=3)\nclf.fit(X, y)\n\nplt.figure(figsize=(6, 4))\nax = plt.subplot(1, 1, 1, xticks=[], yticks=[])\nax.scatter(X[:, 0], X[:, 1], c=y, cmap=\"bone\", zorder=2)\n\nax.scatter(\n clf.support_vectors_[:, 0],\n clf.support_vectors_[:, 1],\n s=80,\n edgecolors=\"k\",\n facecolors=\"none\",\n)\n\ndelta = 1\ny_min, y_max = -50, 50\nx_min, x_max = -50, 50\nx = np.arange(x_min, x_max + delta, delta)\ny = np.arange(y_min, y_max + delta, delta)\nX1, X2 = np.meshgrid(x, y)\nZ = clf.decision_function(np.c_[X1.ravel(), X2.ravel()])\nZ = Z.reshape(X1.shape)\n\nax.contour(\n X1,\n X2,\n Z,\n [-1.0, 0.0, 1.0],\n colors=\"k\",\n linestyles=[\"dashed\", \"solid\", \"dashed\"],\n zorder=1,\n)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/8912a25b1c5893cbcf67b06b87c1802f/plot_dash_joinstyle.ipynb b/_downloads/8912a25b1c5893cbcf67b06b87c1802f/plot_dash_joinstyle.ipynb new file mode 100644 index 000000000..ae1ee8a98 --- /dev/null +++ b/_downloads/8912a25b1c5893cbcf67b06b87c1802f/plot_dash_joinstyle.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Dash join style\n\nExample demoing the dash join style.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nsize = 256, 16\ndpi = 72.0\nfigsize = size[0] / float(dpi), size[1] / float(dpi)\nfig = plt.figure(figsize=figsize, dpi=dpi)\nfig.patch.set_alpha(0)\nplt.axes((0, 0, 1, 1), frameon=False)\n\nplt.plot(\n np.arange(3),\n [0, 1, 0],\n color=\"blue\",\n dashes=[12, 5],\n linewidth=8,\n dash_joinstyle=\"miter\",\n)\nplt.plot(\n 4 + np.arange(3),\n [0, 1, 0],\n color=\"blue\",\n dashes=[12, 5],\n linewidth=8,\n dash_joinstyle=\"bevel\",\n)\nplt.plot(\n 8 + np.arange(3),\n [0, 1, 0],\n color=\"blue\",\n dashes=[12, 5],\n linewidth=8,\n dash_joinstyle=\"round\",\n)\n\nplt.xlim(0, 12)\nplt.ylim(-1, 2)\nplt.xticks([])\nplt.yticks([])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/89e050515d3da6313decb5b1b0d5787d/auto_examples_python.zip b/_downloads/89e050515d3da6313decb5b1b0d5787d/auto_examples_python.zip new file mode 100644 index 000000000..5d1c42699 Binary files /dev/null and b/_downloads/89e050515d3da6313decb5b1b0d5787d/auto_examples_python.zip differ diff --git a/_downloads/8a364a9c810a3c3d1d7f02537942d5b3/plot_subplot-horizontal.ipynb b/_downloads/8a364a9c810a3c3d1d7f02537942d5b3/plot_subplot-horizontal.ipynb new file mode 100644 index 000000000..fbf08fc1c --- /dev/null +++ b/_downloads/8a364a9c810a3c3d1d7f02537942d5b3/plot_subplot-horizontal.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Horizontal arrangement of subplots\n\nAn example showing horizontal arrangement of subplots with matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nplt.figure(figsize=(6, 4))\nplt.subplot(2, 1, 1)\nplt.xticks([])\nplt.yticks([])\nplt.text(0.5, 0.5, \"subplot(2,1,1)\", ha=\"center\", va=\"center\", size=24, alpha=0.5)\n\nplt.subplot(2, 1, 2)\nplt.xticks([])\nplt.yticks([])\nplt.text(0.5, 0.5, \"subplot(2,1,2)\", ha=\"center\", va=\"center\", size=24, alpha=0.5)\n\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/8a8157730f987068eca9b442de7cc332/plot_distances.zip b/_downloads/8a8157730f987068eca9b442de7cc332/plot_distances.zip new file mode 100644 index 000000000..398b09630 Binary files /dev/null and b/_downloads/8a8157730f987068eca9b442de7cc332/plot_distances.zip differ diff --git a/_downloads/8aefcc66c43f13f0f0231de4b694744c/plot_subplot-vertical.zip b/_downloads/8aefcc66c43f13f0f0231de4b694744c/plot_subplot-vertical.zip new file mode 100644 index 000000000..30c4a5579 Binary files /dev/null and b/_downloads/8aefcc66c43f13f0f0231de4b694744c/plot_subplot-vertical.zip differ diff --git a/_downloads/8b6c2eaa1115f35473af4c8fd702e320/plot_basic2dplot.zip b/_downloads/8b6c2eaa1115f35473af4c8fd702e320/plot_basic2dplot.zip new file mode 100644 index 000000000..c8613ef92 Binary files /dev/null and b/_downloads/8b6c2eaa1115f35473af4c8fd702e320/plot_basic2dplot.zip differ diff --git a/_downloads/8baab3838ba07ad8d4217ea480a5c6e7/auto_examples_python.zip b/_downloads/8baab3838ba07ad8d4217ea480a5c6e7/auto_examples_python.zip new file mode 100644 index 000000000..402df4dfb Binary files /dev/null and b/_downloads/8baab3838ba07ad8d4217ea480a5c6e7/auto_examples_python.zip differ diff --git a/_downloads/8c283a04e8f80d1abeccdd9b0d977c5a/plot_interpolation.ipynb b/_downloads/8c283a04e8f80d1abeccdd9b0d977c5a/plot_interpolation.ipynb new file mode 100644 index 000000000..5712bb843 --- /dev/null +++ b/_downloads/8c283a04e8f80d1abeccdd9b0d977c5a/plot_interpolation.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# A demo of 1D interpolation\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Generate data\nimport numpy as np\n\nrng = np.random.default_rng(27446968)\nmeasured_time = np.linspace(0, 2 * np.pi, 20)\nfunction = np.sin(measured_time)\nnoise = rng.normal(loc=0, scale=0.1, size=20)\nmeasurements = function + noise\n\n# Smooth the curve and interpolate at new times\nimport scipy as sp\n\nsmoothing_spline = sp.interpolate.make_smoothing_spline(measured_time, measurements)\ninterpolation_time = np.linspace(0, 2 * np.pi, 200)\nsmooth_results = smoothing_spline(interpolation_time)\n\n# Plot the data, the interpolant, and the original function\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(6, 4))\nplt.plot(measured_time, measurements, \".\", ms=6, label=\"measurements\")\nplt.plot(interpolation_time, smooth_results, label=\"smoothing spline\")\nplt.plot(interpolation_time, np.sin(interpolation_time), \"--\", label=\"underlying curve\")\nplt.legend()\nplt.show()\n\n# Fit the data exactly\ninterp_spline = sp.interpolate.make_interp_spline(measured_time, function)\ninterp_results = interp_spline(interpolation_time)\n\n# Plot the data, the interpolant, and the original function\nplt.figure(figsize=(6, 4))\nplt.plot(measured_time, function, \".\", ms=6, label=\"measurements\")\nplt.plot(interpolation_time, interp_results, label=\"interpolating spline\")\nplt.plot(interpolation_time, np.sin(interpolation_time), \"--\", label=\"underlying curve\")\nplt.legend()\nplt.show()\n\n# Plot interpolant, its derivative, and its antiderivative\nplt.figure(figsize=(6, 4))\nt = interpolation_time\nplt.plot(t, interp_spline(t), label=\"spline\")\nplt.plot(t, interp_spline.derivative()(t), label=\"derivative\")\nplt.plot(t, interp_spline.antiderivative()(t) - 1, label=\"antiderivative\")\n\nplt.legend()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/8da74510b6533b5cd0d7bcdff74bda7f/auto_examples_jupyter.zip b/_downloads/8da74510b6533b5cd0d7bcdff74bda7f/auto_examples_jupyter.zip new file mode 100644 index 000000000..ddb98db57 Binary files /dev/null and b/_downloads/8da74510b6533b5cd0d7bcdff74bda7f/auto_examples_jupyter.zip differ diff --git a/_downloads/8ddfdcadc216f4bf1323011a953f4846/plot_spectrogram.ipynb b/_downloads/8ddfdcadc216f4bf1323011a953f4846/plot_spectrogram.ipynb new file mode 100644 index 000000000..16d0af31a --- /dev/null +++ b/_downloads/8ddfdcadc216f4bf1323011a953f4846/plot_spectrogram.ipynb @@ -0,0 +1,108 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Spectrogram, power spectral density\n\nDemo spectrogram and power spectral density on a frequency chirp.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Generate a chirp signal\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Seed the random number generator\nnp.random.seed(0)\n\ntime_step = 0.01\ntime_vec = np.arange(0, 70, time_step)\n\n# A signal with a small frequency chirp\nsig = np.sin(0.5 * np.pi * time_vec * (1 + 0.1 * time_vec))\n\nplt.figure(figsize=(8, 5))\nplt.plot(time_vec, sig)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Compute and plot the spectrogram\n\n The spectrum of the signal on consecutive time windows\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import scipy as sp\n\nfreqs, times, spectrogram = sp.signal.spectrogram(sig)\n\nplt.figure(figsize=(5, 4))\nplt.imshow(spectrogram, aspect=\"auto\", cmap=\"hot_r\", origin=\"lower\")\nplt.title(\"Spectrogram\")\nplt.ylabel(\"Frequency band\")\nplt.xlabel(\"Time window\")\nplt.tight_layout()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Compute and plot the power spectral density (PSD)\n\n The power of the signal per frequency band\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "freqs, psd = sp.signal.welch(sig)\n\nplt.figure(figsize=(5, 4))\nplt.semilogx(freqs, psd)\nplt.title(\"PSD: power spectral density\")\nplt.xlabel(\"Frequency\")\nplt.ylabel(\"Power\")\nplt.tight_layout()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "plt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/8e293846e0477b502ceae80a6e61c717/plot_plot.py b/_downloads/8e293846e0477b502ceae80a6e61c717/plot_plot.py new file mode 100644 index 000000000..2932069ac --- /dev/null +++ b/_downloads/8e293846e0477b502ceae80a6e61c717/plot_plot.py @@ -0,0 +1,29 @@ +""" +Plot and filled plots +===================== + +Simple example of plots and filling between them with matplotlib. +""" + +import numpy as np +import matplotlib.pyplot as plt + +n = 256 +X = np.linspace(-np.pi, np.pi, n) +Y = np.sin(2 * X) + +plt.axes((0.025, 0.025, 0.95, 0.95)) + +plt.plot(X, Y + 1, color="blue", alpha=1.00) +plt.fill_between(X, 1, Y + 1, color="blue", alpha=0.25) + +plt.plot(X, Y - 1, color="blue", alpha=1.00) +plt.fill_between(X, -1, Y - 1, (Y - 1) > -1, color="blue", alpha=0.25) +plt.fill_between(X, -1, Y - 1, (Y - 1) < -1, color="red", alpha=0.25) + +plt.xlim(-np.pi, np.pi) +plt.xticks([]) +plt.ylim(-2.5, 2.5) +plt.yticks([]) + +plt.show() diff --git a/_downloads/8eac263f497f0a3124a691828e6e26aa/plot_brain_size.ipynb b/_downloads/8eac263f497f0a3124a691828e6e26aa/plot_brain_size.ipynb new file mode 100644 index 000000000..6f5c31e9e --- /dev/null +++ b/_downloads/8eac263f497f0a3124a691828e6e26aa/plot_brain_size.ipynb @@ -0,0 +1,61 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Relating Gender and IQ\n\nGoing back to the brain size + IQ data, test if the VIQ of male and\nfemale are different after removing the effect of brain size, height and\nweight.\n\nNotice that here 'Gender' is a categorical value. As it is a non-float\ndata type, statsmodels is able to automatically infer this.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import pandas\nfrom statsmodels.formula.api import ols\n\ndata = pandas.read_csv(\"../brain_size.csv\", sep=\";\", na_values=\".\")\n\nmodel = ols(\"VIQ ~ Gender + MRI_Count + Height\", data).fit()\nprint(model.summary())\n\n# Here, we don't need to define a contrast, as we are testing a single\n# coefficient of our model, and not a combination of coefficients.\n# However, defining a contrast, which would then be a 'unit contrast',\n# will give us the same results\nprint(model.f_test([0, 1, 0, 0]))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here we plot a scatter matrix to get intuitions on our results.\nThis goes beyond what was asked in the exercise\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# This plotting is useful to get an intuitions on the relationships between\n# our different variables\n\nfrom pandas import plotting\nimport matplotlib.pyplot as plt\n\n# Fill in the missing values for Height for plotting\ndata[\"Height\"] = data[\"Height\"].ffill()\n\n# The parameter 'c' is passed to plt.scatter and will control the color\n# The same holds for parameters 'marker', 'alpha' and 'cmap', that\n# control respectively the type of marker used, their transparency and\n# the colormap\nplotting.scatter_matrix(\n data[[\"VIQ\", \"MRI_Count\", \"Height\"]],\n c=(data[\"Gender\"] == \"Female\"),\n marker=\"o\",\n alpha=1,\n cmap=\"winter\",\n)\n\nfig = plt.gcf()\nfig.suptitle(\"blue: male, green: female\", size=13)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/8f9d33335cd8da0b5ff10b3b8d31af86/plot_plot3d_ext.py b/_downloads/8f9d33335cd8da0b5ff10b3b8d31af86/plot_plot3d_ext.py new file mode 100644 index 000000000..dab3b16e9 --- /dev/null +++ b/_downloads/8f9d33335cd8da0b5ff10b3b8d31af86/plot_plot3d_ext.py @@ -0,0 +1,48 @@ +""" +3D plotting vignette +===================== + +Demo 3D plotting with matplotlib and decorate the figure. +""" + +import numpy as np +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d import Axes3D + +fig = plt.figure() +ax = Axes3D(fig) +X = np.arange(-4, 4, 0.25) +Y = np.arange(-4, 4, 0.25) +X, Y = np.meshgrid(X, Y) +R = np.sqrt(X**2 + Y**2) +Z = np.sin(R) + +ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap="hot") +ax.contourf(X, Y, Z, zdir="z", offset=-2, cmap="hot") +ax.set_zlim(-2, 2) +plt.xticks([]) +plt.yticks([]) +ax.set_zticks([]) + +ax.text2D( + 0.05, + 0.93, + " 3D plots \n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + bbox={"facecolor": "white", "alpha": 1.0}, + transform=plt.gca().transAxes, +) + +ax.text2D( + 0.05, + 0.87, + " Plot 2D or 3D data", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=plt.gca().transAxes, +) + +plt.show() diff --git a/_downloads/8fa8795781b788196d27822116b68b1c/plot_segmentations.ipynb b/_downloads/8fa8795781b788196d27822116b68b1c/plot_segmentations.ipynb new file mode 100644 index 000000000..e96d9c331 --- /dev/null +++ b/_downloads/8fa8795781b788196d27822116b68b1c/plot_segmentations.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Watershed and random walker for segmentation\n\nThis example compares two segmentation methods in order to separate two\nconnected disks: the watershed algorithm, and the random walker algorithm.\n\nBoth segmentation methods require seeds, that are pixels belonging\nunambigusouly to a reagion. Here, local maxima of the distance map to the\nbackground are used as seeds.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nfrom skimage.segmentation import watershed\nfrom skimage.feature import peak_local_max\nfrom skimage import measure\nfrom skimage.segmentation import random_walker\nimport matplotlib.pyplot as plt\nimport scipy as sp\n\n# Generate an initial image with two overlapping circles\nx, y = np.indices((80, 80))\nx1, y1, x2, y2 = 28, 28, 44, 52\nr1, r2 = 16, 20\nmask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1**2\nmask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2**2\nimage = np.logical_or(mask_circle1, mask_circle2)\n# Now we want to separate the two objects in image\n# Generate the markers as local maxima of the distance\n# to the background\ndistance = sp.ndimage.distance_transform_edt(image)\npeak_idx = peak_local_max(distance, footprint=np.ones((3, 3)), labels=image)\npeak_mask = np.zeros_like(distance, dtype=bool)\npeak_mask[tuple(peak_idx.T)] = True\nmarkers = measure.label(peak_mask)\nlabels_ws = watershed(-distance, markers, mask=image)\n\nmarkers[~image] = -1\nlabels_rw = random_walker(image, markers)\n\nplt.figure(figsize=(12, 3.5))\nplt.subplot(141)\nplt.imshow(image, cmap=\"gray\", interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.title(\"image\")\nplt.subplot(142)\nplt.imshow(-distance, interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.title(\"distance map\")\nplt.subplot(143)\nplt.imshow(labels_ws, cmap=\"nipy_spectral\", interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.title(\"watershed segmentation\")\nplt.subplot(144)\nplt.imshow(labels_rw, cmap=\"nipy_spectral\", interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.title(\"random walker segmentation\")\n\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/8fb5c872de25ea365d31fa99c5ac28fc/plot_plot3d.ipynb b/_downloads/8fb5c872de25ea365d31fa99c5ac28fc/plot_plot3d.ipynb new file mode 100644 index 000000000..a8d8594a8 --- /dev/null +++ b/_downloads/8fb5c872de25ea365d31fa99c5ac28fc/plot_plot3d.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# 3D plotting\n\nA simple example of 3D plotting.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nax: Axes3D = plt.figure().add_subplot(projection=\"3d\")\nX = np.arange(-4, 4, 0.25)\nY = np.arange(-4, 4, 0.25)\nX, Y = np.meshgrid(X, Y)\nR = np.sqrt(X**2 + Y**2)\nZ = np.sin(R)\n\nax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=\"hot\")\nax.contourf(X, Y, Z, zdir=\"z\", offset=-2, cmap=\"hot\")\nax.set_zlim(-2, 2)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/8fea29d223bf87104927e931c3cd6db5/plot_wage_data.zip b/_downloads/8fea29d223bf87104927e931c3cd6db5/plot_wage_data.zip new file mode 100644 index 000000000..e63336974 Binary files /dev/null and b/_downloads/8fea29d223bf87104927e931c3cd6db5/plot_wage_data.zip differ diff --git a/_downloads/902ca00964a73761077571b3273229b4/sprog-windspeeds.npy b/_downloads/902ca00964a73761077571b3273229b4/sprog-windspeeds.npy new file mode 100644 index 000000000..7df0080c4 Binary files /dev/null and b/_downloads/902ca00964a73761077571b3273229b4/sprog-windspeeds.npy differ diff --git a/_downloads/902faf4cd6dda7ff9be9c7c54b42f48a/plot_noisy.ipynb b/_downloads/902faf4cd6dda7ff9be9c7c54b42f48a/plot_noisy.ipynb new file mode 100644 index 000000000..3dee8a090 --- /dev/null +++ b/_downloads/902faf4cd6dda7ff9be9c7c54b42f48a/plot_noisy.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Noisy optimization problem\n\nDraws a figure explaining noisy vs non-noisy optimization\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nrng = np.random.default_rng(27446968)\n\nx = np.linspace(-5, 5, 101)\nx_ = np.linspace(-5, 5, 31)\n\n\ndef f(x):\n return -np.exp(-(x**2))\n\n\n# A smooth function\nplt.figure(1, figsize=(3, 2.5))\nplt.clf()\n\nplt.plot(x_, f(x_) + 0.2 * np.random.normal(size=31), linewidth=2)\nplt.plot(x, f(x), linewidth=2)\n\nplt.ylim(ymin=-1.3)\nplt.axis(\"off\")\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/90bab5a52b3cb2560c649df67368b1b7/plot_text_ext.py b/_downloads/90bab5a52b3cb2560c649df67368b1b7/plot_text_ext.py new file mode 100644 index 000000000..cc54ee166 --- /dev/null +++ b/_downloads/90bab5a52b3cb2560c649df67368b1b7/plot_text_ext.py @@ -0,0 +1,86 @@ +""" +Text printing decorated +======================= + +An example showing text printing and decorating the resulting figure. +""" + +import numpy as np +import matplotlib.pyplot as plt + +fig = plt.figure() +plt.xticks([]) +plt.yticks([]) + +eqs = [] +eqs.append( + r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$" +) +eqs.append( + r"$\frac{d\rho}{d t} + \rho \vec{v}\cdot\nabla\vec{v} = -\nabla p + \mu\nabla^2 \vec{v} + \rho \vec{g}$" +) +eqs.append(r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$") +eqs.append(r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$") +eqs.append(r"$F_G = G\frac{m_1m_2}{r^2}$") + +rng = np.random.default_rng() + +for i in range(24): + index = rng.integers(0, len(eqs)) + eq = eqs[index] + size = rng.uniform(12, 32) + x, y = rng.uniform(0, 1, 2) + alpha = rng.uniform(0.25, 0.75) + plt.text( + x, + y, + eq, + ha="center", + va="center", + color="#11557c", + alpha=alpha, + transform=plt.gca().transAxes, + fontsize=size, + clip_on=True, + ) + + +# Add a title and a box around it +from matplotlib.patches import FancyBboxPatch + +ax = plt.gca() +ax.add_patch( + FancyBboxPatch( + (-0.05, 0.87), + width=0.66, + height=0.165, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) +) + +plt.text( + -0.05, + 1.02, + " Text: plt.text(...)\n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=plt.gca().transAxes, +) + +plt.text( + -0.05, + 1.01, + "\n\n Draw any kind of text ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=plt.gca().transAxes, +) + +plt.show() diff --git a/_downloads/90e6ac022f08c3c6163b9a0a0e3de6f5/plot_color.py b/_downloads/90e6ac022f08c3c6163b9a0a0e3de6f5/plot_color.py new file mode 100644 index 000000000..e85ab03cc --- /dev/null +++ b/_downloads/90e6ac022f08c3c6163b9a0a0e3de6f5/plot_color.py @@ -0,0 +1,23 @@ +""" +The colors matplotlib line plots +================================== + +An example demoing the various colors taken by matplotlib's plot. +""" + +import matplotlib.pyplot as plt + +size = 256, 16 +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = plt.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +plt.axes((0, 0.1, 1, 0.8), frameon=False) + +for i in range(1, 11): + plt.plot([i, i], [0, 1], lw=1.5) + +plt.xlim(0, 11) +plt.xticks([]) +plt.yticks([]) +plt.show() diff --git a/_downloads/91f285e00795c5e1fd970c2bdd8ee1eb/plot_interpolation.zip b/_downloads/91f285e00795c5e1fd970c2bdd8ee1eb/plot_interpolation.zip new file mode 100644 index 000000000..ff6b855f2 Binary files /dev/null and b/_downloads/91f285e00795c5e1fd970c2bdd8ee1eb/plot_interpolation.zip differ diff --git a/_downloads/91fecb654c4be191bb17c00d706f7e03/plot_multiplot_ext.py b/_downloads/91fecb654c4be191bb17c00d706f7e03/plot_multiplot_ext.py new file mode 100644 index 000000000..67cbb8aaa --- /dev/null +++ b/_downloads/91fecb654c4be191bb17c00d706f7e03/plot_multiplot_ext.py @@ -0,0 +1,60 @@ +""" +Multiple plots vignette +======================== + +Demo multiple plots and style the figure. +""" + +import matplotlib.pyplot as plt + +ax = plt.subplot(2, 1, 1) +ax.set_xticklabels([]) +ax.set_yticklabels([]) + + +# Add a title and a box around it +from matplotlib.patches import FancyBboxPatch + +ax = plt.gca() +ax.add_patch( + FancyBboxPatch( + (-0.05, 0.72), + width=0.66, + height=0.34, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) +) + +plt.text( + -0.05, + 1.02, + " Multiplot: plt.subplot(...)\n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=ax.transAxes, +) +plt.text( + -0.05, + 1.01, + "\n\n Plot several plots at once ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=ax.transAxes, +) + +ax = plt.subplot(2, 2, 3) +ax.set_xticklabels([]) +ax.set_yticklabels([]) + +ax = plt.subplot(2, 2, 4) +ax.set_xticklabels([]) +ax.set_yticklabels([]) + +plt.show() diff --git a/_downloads/924612161d0534e3099080ee59104f7d/plot_interpolation.py b/_downloads/924612161d0534e3099080ee59104f7d/plot_interpolation.py new file mode 100644 index 000000000..9b77bead2 --- /dev/null +++ b/_downloads/924612161d0534e3099080ee59104f7d/plot_interpolation.py @@ -0,0 +1,54 @@ +""" +============================ +A demo of 1D interpolation +============================ + +""" + +# Generate data +import numpy as np + +rng = np.random.default_rng(27446968) +measured_time = np.linspace(0, 2 * np.pi, 20) +function = np.sin(measured_time) +noise = rng.normal(loc=0, scale=0.1, size=20) +measurements = function + noise + +# Smooth the curve and interpolate at new times +import scipy as sp + +smoothing_spline = sp.interpolate.make_smoothing_spline(measured_time, measurements) +interpolation_time = np.linspace(0, 2 * np.pi, 200) +smooth_results = smoothing_spline(interpolation_time) + +# Plot the data, the interpolant, and the original function +import matplotlib.pyplot as plt + +plt.figure(figsize=(6, 4)) +plt.plot(measured_time, measurements, ".", ms=6, label="measurements") +plt.plot(interpolation_time, smooth_results, label="smoothing spline") +plt.plot(interpolation_time, np.sin(interpolation_time), "--", label="underlying curve") +plt.legend() +plt.show() + +# Fit the data exactly +interp_spline = sp.interpolate.make_interp_spline(measured_time, function) +interp_results = interp_spline(interpolation_time) + +# Plot the data, the interpolant, and the original function +plt.figure(figsize=(6, 4)) +plt.plot(measured_time, function, ".", ms=6, label="measurements") +plt.plot(interpolation_time, interp_results, label="interpolating spline") +plt.plot(interpolation_time, np.sin(interpolation_time), "--", label="underlying curve") +plt.legend() +plt.show() + +# Plot interpolant, its derivative, and its antiderivative +plt.figure(figsize=(6, 4)) +t = interpolation_time +plt.plot(t, interp_spline(t), label="spline") +plt.plot(t, interp_spline.derivative()(t), label="derivative") +plt.plot(t, interp_spline.antiderivative()(t) - 1, label="antiderivative") + +plt.legend() +plt.show() diff --git a/_downloads/942fd17f06c5e6ff25d56505dab71447/plot_bar.py b/_downloads/942fd17f06c5e6ff25d56505dab71447/plot_bar.py new file mode 100644 index 000000000..eef014d20 --- /dev/null +++ b/_downloads/942fd17f06c5e6ff25d56505dab71447/plot_bar.py @@ -0,0 +1,32 @@ +""" +Bar plots +========== + +An example of bar plots with matplotlib. +""" + +import numpy as np +import matplotlib.pyplot as plt + +n = 12 +X = np.arange(n) +rng = np.random.default_rng() +Y1 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n) +Y2 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n) + +plt.axes((0.025, 0.025, 0.95, 0.95)) +plt.bar(X, +Y1, facecolor="#9999ff", edgecolor="white") +plt.bar(X, -Y2, facecolor="#ff9999", edgecolor="white") + +for x, y in zip(X, Y1, strict=True): + plt.text(x + 0.4, y + 0.05, f"{y:.2f}", ha="center", va="bottom") + +for x, y in zip(X, Y2, strict=True): + plt.text(x + 0.4, -y - 0.05, f"{y:.2f}", ha="center", va="top") + +plt.xlim(-0.5, n) +plt.xticks([]) +plt.ylim(-1.25, 1.25) +plt.yticks([]) + +plt.show() diff --git a/_downloads/949a26781c949af5004abfdd5b6244b1/plot_simple.ipynb b/_downloads/949a26781c949af5004abfdd5b6244b1/plot_simple.ipynb new file mode 100644 index 000000000..ac3ac40bd --- /dev/null +++ b/_downloads/949a26781c949af5004abfdd5b6244b1/plot_simple.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# A simple example\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nX = np.linspace(-np.pi, np.pi, 100)\nY = np.sin(X)\n\nplt.plot(X, Y, linewidth=2)\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/94af1f4f47d59e522228399667d1eb65/plot_interpolation_face.py b/_downloads/94af1f4f47d59e522228399667d1eb65/plot_interpolation_face.py new file mode 100644 index 000000000..e89f25a99 --- /dev/null +++ b/_downloads/94af1f4f47d59e522228399667d1eb65/plot_interpolation_face.py @@ -0,0 +1,24 @@ +""" +Image interpolation +===================== + +The example demonstrates image interpolation on a Raccoon face. +""" + +import scipy as sp +import matplotlib.pyplot as plt + +f = sp.datasets.face(gray=True) + +plt.figure(figsize=(8, 4)) + +plt.subplot(1, 2, 1) +plt.imshow(f[320:340, 510:530], cmap="gray") +plt.axis("off") + +plt.subplot(1, 2, 2) +plt.imshow(f[320:340, 510:530], cmap="gray", interpolation="nearest") +plt.axis("off") + +plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1) +plt.show() diff --git a/_downloads/94b91ef79b924fc3a0f282dbe75dd1e1/plot_camera.zip b/_downloads/94b91ef79b924fc3a0f282dbe75dd1e1/plot_camera.zip new file mode 100644 index 000000000..3c4910f6d Binary files /dev/null and b/_downloads/94b91ef79b924fc3a0f282dbe75dd1e1/plot_camera.zip differ diff --git a/_downloads/94b9aeaa2734fe96d12f48cc9479d7f8/plot_measuring_performance.py b/_downloads/94b9aeaa2734fe96d12f48cc9479d7f8/plot_measuring_performance.py new file mode 100644 index 000000000..68548eebc --- /dev/null +++ b/_downloads/94b9aeaa2734fe96d12f48cc9479d7f8/plot_measuring_performance.py @@ -0,0 +1,43 @@ +""" +Measuring Decision Tree performance +==================================== + +Demonstrates overfit when testing on train set. +""" + +############################################################ +# Get the data + +from sklearn.datasets import fetch_california_housing + +data = fetch_california_housing(as_frame=True) + +############################################################ +# Train and test a model +from sklearn.tree import DecisionTreeRegressor + +clf = DecisionTreeRegressor().fit(data.data, data.target) + +predicted = clf.predict(data.data) +expected = data.target + +############################################################ +# Plot predicted as a function of expected + +import matplotlib.pyplot as plt + +plt.figure(figsize=(4, 3)) +plt.scatter(expected, predicted) +plt.plot([0, 5], [0, 5], "--k") +plt.axis("tight") +plt.xlabel("True price ($100k)") +plt.ylabel("Predicted price ($100k)") +plt.tight_layout() + +############################################################ +# Pretty much no errors! +# +# This is too good to be true: we are testing the model on the train +# data, which is not a measure of generalization. +# +# **The results are not valid** diff --git a/_downloads/95a00addf9f386941386bcbe0b831b68/plot_tsne.py b/_downloads/95a00addf9f386941386bcbe0b831b68/plot_tsne.py new file mode 100644 index 000000000..ea35ed1a1 --- /dev/null +++ b/_downloads/95a00addf9f386941386bcbe0b831b68/plot_tsne.py @@ -0,0 +1,44 @@ +""" +========================== +tSNE to visualize digits +========================== + +Here we use :class:`sklearn.manifold.TSNE` to visualize the digits +datasets. Indeed, the digits are vectors in a 8*8 = 64 dimensional space. +We want to project them in 2D for visualization. tSNE is often a good +solution, as it groups and separates data points based on their local +relationship. + +""" + +############################################################ +# Load the iris data +from sklearn import datasets + +digits = datasets.load_digits() +# Take the first 500 data points: it's hard to see 1500 points +X = digits.data[:500] +y = digits.target[:500] + +############################################################ +# Fit and transform with a TSNE +from sklearn.manifold import TSNE + +tsne = TSNE(n_components=2, random_state=0) + +############################################################ +# Project the data in 2D +X_2d = tsne.fit_transform(X) + +############################################################ +# Visualize the data +target_ids = range(len(digits.target_names)) + +import matplotlib.pyplot as plt + +plt.figure(figsize=(6, 5)) +colors = "r", "g", "b", "c", "m", "y", "k", "w", "orange", "purple" +for i, c, label in zip(target_ids, colors, digits.target_names, strict=True): + plt.scatter(X_2d[y == i, 0], X_2d[y == i, 1], c=c, label=label) +plt.legend() +plt.show() diff --git a/_downloads/95c1cc9ce4e821dd553edde9e228be37/plot_text.ipynb b/_downloads/95c1cc9ce4e821dd553edde9e228be37/plot_text.ipynb new file mode 100644 index 000000000..25ca74e32 --- /dev/null +++ b/_downloads/95c1cc9ce4e821dd553edde9e228be37/plot_text.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Demo text printing\n\nA example showing off elaborate text printing with matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\n\neqs = []\neqs.append(\n r\"$W^{3\\beta}_{\\delta_1 \\rho_1 \\sigma_2} = U^{3\\beta}_{\\delta_1 \\rho_1} + \\frac{1}{8 \\pi 2} \\int^{\\alpha_2}_{\\alpha_2} d \\alpha^\\prime_2 \\left[\\frac{ U^{2\\beta}_{\\delta_1 \\rho_1} - \\alpha^\\prime_2U^{1\\beta}_{\\rho_1 \\sigma_2} }{U^{0\\beta}_{\\rho_1 \\sigma_2}}\\right]$\"\n)\neqs.append(\n r\"$\\frac{d\\rho}{d t} + \\rho \\vec{v}\\cdot\\nabla\\vec{v} = -\\nabla p + \\mu\\nabla^2 \\vec{v} + \\rho \\vec{g}$\"\n)\neqs.append(r\"$\\int_{-\\infty}^\\infty e^{-x^2}dx=\\sqrt{\\pi}$\")\neqs.append(r\"$E = mc^2 = \\sqrt{{m_0}^2c^4 + p^2c^2}$\")\neqs.append(r\"$F_G = G\\frac{m_1m_2}{r^2}$\")\n\nplt.axes((0.025, 0.025, 0.95, 0.95))\n\nrng = np.random.default_rng()\n\nfor i in range(24):\n index = rng.integers(0, len(eqs))\n eq = eqs[index]\n size = np.random.uniform(12, 32)\n x, y = np.random.uniform(0, 1, 2)\n alpha = np.random.uniform(0.25, 0.75)\n plt.text(\n x,\n y,\n eq,\n ha=\"center\",\n va=\"center\",\n color=\"#11557c\",\n alpha=alpha,\n transform=plt.gca().transAxes,\n fontsize=size,\n clip_on=True,\n )\nplt.xticks([])\nplt.yticks([])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/9697d8e56ef0ad799f3fb1bd276625b2/plot_paired_boxplots.zip b/_downloads/9697d8e56ef0ad799f3fb1bd276625b2/plot_paired_boxplots.zip new file mode 100644 index 000000000..ba20d6653 Binary files /dev/null and b/_downloads/9697d8e56ef0ad799f3fb1bd276625b2/plot_paired_boxplots.zip differ diff --git a/_downloads/9702312098be34ce50e4d07ed6ad02a2/plot_mathematical_morpho.ipynb b/_downloads/9702312098be34ce50e4d07ed6ad02a2/plot_mathematical_morpho.ipynb new file mode 100644 index 000000000..81d89b16a --- /dev/null +++ b/_downloads/9702312098be34ce50e4d07ed6ad02a2/plot_mathematical_morpho.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Demo mathematical morphology\n\nA basic demo of binary opening and closing.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Generate some binary data\nimport numpy as np\n\nnp.random.seed(0)\na = np.zeros((50, 50))\na[10:-10, 10:-10] = 1\na += 0.25 * np.random.standard_normal(a.shape)\nmask = a >= 0.5\n\n# Apply mathematical morphology\nimport scipy as sp\n\nopened_mask = sp.ndimage.binary_opening(mask)\nclosed_mask = sp.ndimage.binary_closing(opened_mask)\n\n# Plot\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(12, 3.5))\nplt.subplot(141)\nplt.imshow(a, cmap=\"gray\")\nplt.axis(\"off\")\nplt.title(\"a\")\n\nplt.subplot(142)\nplt.imshow(mask, cmap=\"gray\")\nplt.axis(\"off\")\nplt.title(\"mask\")\n\nplt.subplot(143)\nplt.imshow(opened_mask, cmap=\"gray\")\nplt.axis(\"off\")\nplt.title(\"opened_mask\")\n\nplt.subplot(144)\nplt.imshow(closed_mask, cmap=\"gray\")\nplt.title(\"closed_mask\")\nplt.axis(\"off\")\n\nplt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/97494e872ef19268664b76eba18e3981/plot_fftpack.ipynb b/_downloads/97494e872ef19268664b76eba18e3981/plot_fftpack.ipynb new file mode 100644 index 000000000..899216af7 --- /dev/null +++ b/_downloads/97494e872ef19268664b76eba18e3981/plot_fftpack.ipynb @@ -0,0 +1,115 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plotting and manipulating FFTs for filtering\n\nPlot the power of the FFT of a signal and inverse FFT back to reconstruct\na signal.\n\nThis example demonstrate :func:`scipy.fft.fft`,\n:func:`scipy.fft.fftfreq` and :func:`scipy.fft.ifft`. It\nimplements a basic filter that is very suboptimal, and should not be\nused.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Generate the signal\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Seed the random number generator\nrng = np.random.default_rng(27446968)\n\ntime_step = 0.02\nperiod = 5.0\n\ntime_vec = np.arange(0, 20, time_step)\nsig = np.sin(2 * np.pi / period * time_vec) + 0.5 * rng.normal(size=time_vec.size)\n\nplt.figure(figsize=(6, 5))\nplt.plot(time_vec, sig, label=\"Original signal\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Compute and plot the power\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# The FFT of the signal\nsig_fft = sp.fft.fft(sig)\n\n# And the power (sig_fft is of complex dtype)\npower = np.abs(sig_fft) ** 2\n\n# The corresponding frequencies\nsample_freq = sp.fft.fftfreq(sig.size, d=time_step)\n\n# Plot the FFT power\nplt.figure(figsize=(6, 5))\nplt.plot(sample_freq, power)\nplt.xlabel(\"Frequency [Hz]\")\nplt.ylabel(\"plower\")\n\n# Find the peak frequency: we can focus on only the positive frequencies\npos_mask = np.where(sample_freq > 0)\nfreqs = sample_freq[pos_mask]\npeak_freq = freqs[power[pos_mask].argmax()]\n\n# Check that it does indeed correspond to the frequency that we generate\n# the signal with\nnp.allclose(peak_freq, 1.0 / period)\n\n# An inner plot to show the peak frequency\naxes = plt.axes((0.55, 0.3, 0.3, 0.5))\nplt.title(\"Peak frequency\")\nplt.plot(freqs[:8], power[pos_mask][:8])\nplt.setp(axes, yticks=[])\n\n# scipy.signal.find_peaks_cwt can also be used for more advanced\n# peak detection" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Remove all the high frequencies\n\n We now remove all the high frequencies and transform back from\n frequencies to signal.\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "high_freq_fft = sig_fft.copy()\nhigh_freq_fft[np.abs(sample_freq) > peak_freq] = 0\nfiltered_sig = sp.fft.ifft(high_freq_fft)\n\nplt.figure(figsize=(6, 5))\nplt.plot(time_vec, sig, label=\"Original signal\")\nplt.plot(time_vec, filtered_sig, linewidth=3, label=\"Filtered signal\")\nplt.xlabel(\"Time [s]\")\nplt.ylabel(\"Amplitude\")\n\nplt.legend(loc=\"best\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Note** This is actually a bad way of creating a filter: such brutal\ncut-off in frequency space does not control distortion on the signal.\n\nFilters should be created using the SciPy filter design code\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "plt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/988830c5768bb0895d6f145c58c0a2b0/plot_periodicity_finder.ipynb b/_downloads/988830c5768bb0895d6f145c58c0a2b0/plot_periodicity_finder.ipynb new file mode 100644 index 000000000..4ab9edeb8 --- /dev/null +++ b/_downloads/988830c5768bb0895d6f145c58c0a2b0/plot_periodicity_finder.ipynb @@ -0,0 +1,93 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Crude periodicity finding\n\nDiscover the periods in evolution of animal populations\n(:download:`../../../../data/populations.txt`)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Load the data\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n\ndata = np.loadtxt(\"../../../../data/populations.txt\")\nyears = data[:, 0]\npopulations = data[:, 1:]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Plot the data\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nplt.figure()\nplt.plot(years, populations * 1e-3)\nplt.xlabel(\"Year\")\nplt.ylabel(r\"Population number ($\\cdot10^3$)\")\nplt.legend([\"hare\", \"lynx\", \"carrot\"], loc=1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Plot its periods\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import scipy as sp\n\nft_populations = sp.fft.fft(populations, axis=0)\nfrequencies = sp.fft.fftfreq(populations.shape[0], years[1] - years[0])\nperiods = 1 / frequencies\n\nplt.figure()\nplt.plot(periods, abs(ft_populations) * 1e-3, \"o\")\nplt.xlim(0, 22)\nplt.xlabel(\"Period\")\nplt.ylabel(r\"Power ($\\cdot10^3$)\")\n\nplt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "There's probably a period of around 10 years (obvious from the\nplot), but for this crude a method, there's not enough data to say\nmuch more.\n\n" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/992e59c70b3fde2bca75098fd2535762/plot_multiplot.ipynb b/_downloads/992e59c70b3fde2bca75098fd2535762/plot_multiplot.ipynb new file mode 100644 index 000000000..00ec577c7 --- /dev/null +++ b/_downloads/992e59c70b3fde2bca75098fd2535762/plot_multiplot.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Subplots\n\nShow multiple subplots in matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nfig = plt.figure()\nfig.subplots_adjust(bottom=0.025, left=0.025, top=0.975, right=0.975)\n\nplt.subplot(2, 1, 1)\nplt.xticks([]), plt.yticks([])\n\nplt.subplot(2, 3, 4)\nplt.xticks([])\nplt.yticks([])\n\nplt.subplot(2, 3, 5)\nplt.xticks([])\nplt.yticks([])\n\nplt.subplot(2, 3, 6)\nplt.xticks([])\nplt.yticks([])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/99e9a92e52d793e0a559d75fb89c7745/plot_optimize_lidar_complex_data.ipynb b/_downloads/99e9a92e52d793e0a559d75fb89c7745/plot_optimize_lidar_complex_data.ipynb new file mode 100644 index 000000000..cae840b52 --- /dev/null +++ b/_downloads/99e9a92e52d793e0a559d75fb89c7745/plot_optimize_lidar_complex_data.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# The lidar system, data (2 of 2 datasets)\n\nGenerate a chart of more complex data recorded by the lidar system\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nwaveform_2 = np.load(\"waveform_2.npy\")\n\nt = np.arange(len(waveform_2))\n\nfig, ax = plt.subplots(figsize=(8, 6))\nplt.plot(t, waveform_2)\nplt.xlabel(\"Time [ns]\")\nplt.ylabel(\"Amplitude [bins]\")\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/9a464579a68f30bd35e8a26476c33dd5/plot_regression_3d.py b/_downloads/9a464579a68f30bd35e8a26476c33dd5/plot_regression_3d.py new file mode 100644 index 000000000..21b096cc5 --- /dev/null +++ b/_downloads/9a464579a68f30bd35e8a26476c33dd5/plot_regression_3d.py @@ -0,0 +1,76 @@ +""" +Multiple Regression +==================== + +Calculate using 'statsmodels' just the best fit, or all the corresponding +statistical parameters. + +Also shows how to make 3d plots. +""" + +# Original author: Thomas Haslwanter + +import numpy as np +import matplotlib.pyplot as plt +import pandas + +# For 3d plots. This import is necessary to have 3D plotting below +from mpl_toolkits.mplot3d import Axes3D + +# For statistics. Requires statsmodels 5.0 or more +from statsmodels.formula.api import ols + +# Analysis of Variance (ANOVA) on linear models +from statsmodels.stats.anova import anova_lm + +############################################################################## +# Generate and show the data +x = np.linspace(-5, 5, 21) +# We generate a 2D grid +X, Y = np.meshgrid(x, x) + +# To get reproducible values, provide a seed value +rng = np.random.default_rng(27446968) + +# Z is the elevation of this 2D grid +Z = -5 + 3 * X - 0.5 * Y + 8 * np.random.normal(size=X.shape) + +# Plot the data +ax: Axes3D = plt.figure().add_subplot(projection="3d") +surf = ax.plot_surface(X, Y, Z, cmap="coolwarm", rstride=1, cstride=1) +ax.view_init(20, -120) +ax.set_xlabel("X") +ax.set_ylabel("Y") +ax.set_zlabel("Z") + +############################################################################## +# Multilinear regression model, calculating fit, P-values, confidence +# intervals etc. + +# Convert the data into a Pandas DataFrame to use the formulas framework +# in statsmodels + +# First we need to flatten the data: it's 2D layout is not relevant. +X = X.flatten() +Y = Y.flatten() +Z = Z.flatten() + +data = pandas.DataFrame({"x": X, "y": Y, "z": Z}) + +# Fit the model +model = ols("z ~ x + y", data).fit() + +# Print the summary +print(model.summary()) + +print("\nRetrieving manually the parameter estimates:") +print(model._results.params) +# should be array([-4.99754526, 3.00250049, -0.50514907]) + +# Perform analysis of variance on fitted linear model +anova_results = anova_lm(model) + +print("\nANOVA results") +print(anova_results) + +plt.show() diff --git a/_downloads/9acfadb02f79390a633a9c17efa80dae/plot_grid.py b/_downloads/9acfadb02f79390a633a9c17efa80dae/plot_grid.py new file mode 100644 index 000000000..aa94d0547 --- /dev/null +++ b/_downloads/9acfadb02f79390a633a9c17efa80dae/plot_grid.py @@ -0,0 +1,26 @@ +""" +Grid +==== + +Displaying a grid on the axes in matploblib. +""" + +import matplotlib.pyplot as plt +from matplotlib import ticker + +ax = plt.axes((0.025, 0.025, 0.95, 0.95)) + +ax.set_xlim(0, 4) +ax.set_ylim(0, 3) +ax.xaxis.set_major_locator(ticker.MultipleLocator(1.0)) +ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.1)) +ax.yaxis.set_major_locator(ticker.MultipleLocator(1.0)) +ax.yaxis.set_minor_locator(ticker.MultipleLocator(0.1)) +ax.grid(which="major", axis="x", linewidth=0.75, linestyle="-", color="0.75") +ax.grid(which="minor", axis="x", linewidth=0.25, linestyle="-", color="0.75") +ax.grid(which="major", axis="y", linewidth=0.75, linestyle="-", color="0.75") +ax.grid(which="minor", axis="y", linewidth=0.25, linestyle="-", color="0.75") +ax.set_xticklabels([]) +ax.set_yticklabels([]) + +plt.show() diff --git a/_downloads/9aebea6012b6722b3f0f5bac4c1730f9/plot_display_face.py b/_downloads/9aebea6012b6722b3f0f5bac4c1730f9/plot_display_face.py new file mode 100644 index 000000000..4e4ff948a --- /dev/null +++ b/_downloads/9aebea6012b6722b3f0f5bac4c1730f9/plot_display_face.py @@ -0,0 +1,28 @@ +""" +Display a Raccoon Face +====================== + +An example that displays a raccoon face with matplotlib. +""" + +import scipy as sp +import matplotlib.pyplot as plt + +f = sp.datasets.face(gray=True) + +plt.figure(figsize=(10, 3.6)) + +plt.subplot(131) +plt.imshow(f, cmap="gray") + +plt.subplot(132) +plt.imshow(f, cmap="gray", vmin=30, vmax=200) +plt.axis("off") + +plt.subplot(133) +plt.imshow(f, cmap="gray") +plt.contour(f, [50, 200]) +plt.axis("off") + +plt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.05, right=0.99) +plt.show() diff --git a/_downloads/9b144152ddedf97481370b24250c2113/plot_polynomial_regression.ipynb b/_downloads/9b144152ddedf97481370b24250c2113/plot_polynomial_regression.ipynb new file mode 100644 index 000000000..d4f5ca377 --- /dev/null +++ b/_downloads/9b144152ddedf97481370b24250c2113/plot_polynomial_regression.ipynb @@ -0,0 +1,97 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot fitting a 9th order polynomial\n\nFits data generated from a 9th order polynomial with model of 4th order\nand 9th order polynomials, to demonstrate that often simpler models are\nto be preferred\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\n\nfrom sklearn import linear_model\n\n# Create color maps for 3-class classification problem, as with iris\ncmap_light = ListedColormap([\"#FFAAAA\", \"#AAFFAA\", \"#AAAAFF\"])\ncmap_bold = ListedColormap([\"#FF0000\", \"#00FF00\", \"#0000FF\"])\n\n\nrng = np.random.default_rng(27446968)\nx = 2 * rng.random(100) - 1\n\nf = lambda t: 1.2 * t**2 + 0.1 * t**3 - 0.4 * t**5 - 0.5 * t**9\ny = f(x) + 0.4 * rng.normal(size=100)\n\nx_test = np.linspace(-1, 1, 100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The data\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "plt.figure(figsize=(6, 4))\nplt.scatter(x, y, s=4)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Fitting 4th and 9th order polynomials\n\nFor this we need to engineer features: the n_th powers of x:\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "plt.figure(figsize=(6, 4))\nplt.scatter(x, y, s=4)\n\nX = np.array([x**i for i in range(5)]).T\nX_test = np.array([x_test**i for i in range(5)]).T\nregr = linear_model.LinearRegression()\nregr.fit(X, y)\nplt.plot(x_test, regr.predict(X_test), label=\"4th order\")\n\nX = np.array([x**i for i in range(10)]).T\nX_test = np.array([x_test**i for i in range(10)]).T\nregr = linear_model.LinearRegression()\nregr.fit(X, y)\nplt.plot(x_test, regr.predict(X_test), label=\"9th order\")\n\nplt.legend(loc=\"best\")\nplt.axis(\"tight\")\nplt.title(\"Fitting a 4th and a 9th order polynomial\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Ground truth\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "plt.figure(figsize=(6, 4))\nplt.scatter(x, y, s=4)\nplt.plot(x_test, f(x_test), label=\"truth\")\nplt.axis(\"tight\")\nplt.title(\"Ground truth (9th order polynomial)\")\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/9c1b6587163c7c1c6e0d6e988c158248/plot_image_transform.ipynb b/_downloads/9c1b6587163c7c1c6e0d6e988c158248/plot_image_transform.ipynb new file mode 100644 index 000000000..edd097bbf --- /dev/null +++ b/_downloads/9c1b6587163c7c1c6e0d6e988c158248/plot_image_transform.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot geometrical transformations on images\n\nDemo geometrical transformations of images.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Load some data\nimport scipy as sp\n\nface = sp.datasets.face(gray=True)\n\n# Apply a variety of transformations\nimport matplotlib.pyplot as plt\n\nshifted_face = sp.ndimage.shift(face, (50, 50))\nshifted_face2 = sp.ndimage.shift(face, (50, 50), mode=\"nearest\")\nrotated_face = sp.ndimage.rotate(face, 30)\ncropped_face = face[50:-50, 50:-50]\nzoomed_face = sp.ndimage.zoom(face, 2)\nzoomed_face.shape\n\nplt.figure(figsize=(15, 3))\nplt.subplot(151)\nplt.imshow(shifted_face, cmap=\"gray\")\nplt.axis(\"off\")\n\nplt.subplot(152)\nplt.imshow(shifted_face2, cmap=\"gray\")\nplt.axis(\"off\")\n\nplt.subplot(153)\nplt.imshow(rotated_face, cmap=\"gray\")\nplt.axis(\"off\")\n\nplt.subplot(154)\nplt.imshow(cropped_face, cmap=\"gray\")\nplt.axis(\"off\")\n\nplt.subplot(155)\nplt.imshow(zoomed_face, cmap=\"gray\")\nplt.axis(\"off\")\n\nplt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/9c304be3653ac9170330ad1acc68bbc1/plot_filter_coins.zip b/_downloads/9c304be3653ac9170330ad1acc68bbc1/plot_filter_coins.zip new file mode 100644 index 000000000..2ccd3526c Binary files /dev/null and b/_downloads/9c304be3653ac9170330ad1acc68bbc1/plot_filter_coins.zip differ diff --git a/_downloads/9c67e7165064e14a86404fd10515c5ef/plot_optimize_lidar_data_fit.py b/_downloads/9c67e7165064e14a86404fd10515c5ef/plot_optimize_lidar_data_fit.py new file mode 100644 index 000000000..8eafe5e6f --- /dev/null +++ b/_downloads/9c67e7165064e14a86404fd10515c5ef/plot_optimize_lidar_data_fit.py @@ -0,0 +1,34 @@ +""" +The lidar system, data and fit (1 of 2 datasets) +================================================ + +Generate a chart of the data fitted by Gaussian curve +""" + +import numpy as np +import matplotlib.pyplot as plt +import scipy as sp + + +def model(t, coeffs): + return coeffs[0] + coeffs[1] * np.exp(-(((t - coeffs[2]) / coeffs[3]) ** 2)) + + +def residuals(coeffs, y, t): + return y - model(t, coeffs) + + +waveform_1 = np.load("waveform_1.npy") +t = np.arange(len(waveform_1)) + +x0 = np.array([3, 30, 15, 1], dtype=float) +x, flag = sp.optimize.leastsq(residuals, x0, args=(waveform_1, t)) + +print(x) + +fig, ax = plt.subplots(figsize=(8, 6)) +plt.plot(t, waveform_1, t, model(t, x)) +plt.xlabel("Time [ns]") +plt.ylabel("Amplitude [bins]") +plt.legend(["Waveform", "Model"]) +plt.show() diff --git a/_downloads/9cf1b648269436444582bebf933adccf/demo_opt.py b/_downloads/9cf1b648269436444582bebf933adccf/demo_opt.py new file mode 100644 index 000000000..410e52ddf --- /dev/null +++ b/_downloads/9cf1b648269436444582bebf933adccf/demo_opt.py @@ -0,0 +1,18 @@ +# For this example to run, you also need the 'ica.py' file + +import numpy as np +import scipy as sp + +from ica import fastica + + +def test(): + rng = np.random.default_rng() + data = rng.random((5000, 100)) + u, s, v = sp.linalg.svd(data, full_matrices=False) + pca = u[:, :10].T @ data + results = fastica(pca.T, whiten=False) + + +if __name__ == "__main__": + test() diff --git a/_downloads/9d003f0584e679ff6627ed71dee2a1fc/plot_mandelbrot.py b/_downloads/9d003f0584e679ff6627ed71dee2a1fc/plot_mandelbrot.py new file mode 100644 index 000000000..84382e8ec --- /dev/null +++ b/_downloads/9d003f0584e679ff6627ed71dee2a1fc/plot_mandelbrot.py @@ -0,0 +1,41 @@ +""" +Mandelbrot set +============== + +Compute the Mandelbrot fractal and plot it + +""" + +import numpy as np +import matplotlib.pyplot as plt +from numpy import newaxis +import warnings + + +def compute_mandelbrot(N_max, some_threshold, nx, ny): + # A grid of c-values + x = np.linspace(-2, 1, nx) + y = np.linspace(-1.5, 1.5, ny) + + c = x[:, newaxis] + 1j * y[newaxis, :] + + # Mandelbrot iteration + + z = c + + # The code below overflows in many regions of the x-y grid, suppress + # warnings temporarily + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + for j in range(N_max): + z = z**2 + c + mandelbrot_set = abs(z) < some_threshold + + return mandelbrot_set + + +mandelbrot_set = compute_mandelbrot(50, 50.0, 601, 401) + +plt.imshow(mandelbrot_set.T, extent=(-2, 1, -1.5, 1.5)) +plt.gray() +plt.show() diff --git a/_downloads/9d319f2787b2ee342eb77567224fff09/plot_fft_image_denoise.zip b/_downloads/9d319f2787b2ee342eb77567224fff09/plot_fft_image_denoise.zip new file mode 100644 index 000000000..060ccab8a Binary files /dev/null and b/_downloads/9d319f2787b2ee342eb77567224fff09/plot_fft_image_denoise.zip differ diff --git a/_downloads/9d35ba6bb9435c765ccdf905208656fc/plot_iris_analysis.ipynb b/_downloads/9d35ba6bb9435c765ccdf905208656fc/plot_iris_analysis.ipynb new file mode 100644 index 000000000..d40741970 --- /dev/null +++ b/_downloads/9d35ba6bb9435c765ccdf905208656fc/plot_iris_analysis.ipynb @@ -0,0 +1,79 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Analysis of Iris petal and sepal sizes\n\nIllustrate an analysis on a real dataset:\n\n- Visualizing the data to formulate intuitions\n- Fitting of a linear model\n- Hypothesis test of the effect of a categorical variable in the presence\n of a continuous confound\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nimport pandas\nfrom pandas import plotting\n\nfrom statsmodels.formula.api import ols\n\n# Load the data\ndata = pandas.read_csv(\"iris.csv\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Plot a scatter matrix\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Express the names as categories\ncategories = pandas.Categorical(data[\"name\"])\n\n# The parameter 'c' is passed to plt.scatter and will control the color\nplotting.scatter_matrix(data, c=categories.codes, marker=\"o\")\n\nfig = plt.gcf()\nfig.suptitle(\"blue: setosa, green: versicolor, red: virginica\", size=13)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Statistical analysis\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Let us try to explain the sepal length as a function of the petal\n# width and the category of iris\n\nmodel = ols(\"sepal_width ~ name + petal_length\", data).fit()\nprint(model.summary())\n\n# Now formulate a \"contrast\", to test if the offset for versicolor and\n# virginica are identical\n\nprint(\"Testing the difference between effect of versicolor and virginica\")\nprint(model.f_test([0, 1, -1, 0]))\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/9d6dd5ee0e8e9dbe37b12250922ca2b8/auto_examples_jupyter.zip b/_downloads/9d6dd5ee0e8e9dbe37b12250922ca2b8/auto_examples_jupyter.zip new file mode 100644 index 000000000..bf87b8d1e Binary files /dev/null and b/_downloads/9d6dd5ee0e8e9dbe37b12250922ca2b8/auto_examples_jupyter.zip differ diff --git a/_downloads/9e22f6571297550fc2f98ceb27aa01cd/plot_eigenfaces.ipynb b/_downloads/9e22f6571297550fc2f98ceb27aa01cd/plot_eigenfaces.ipynb new file mode 100644 index 000000000..f82dc5d14 --- /dev/null +++ b/_downloads/9e22f6571297550fc2f98ceb27aa01cd/plot_eigenfaces.ipynb @@ -0,0 +1,277 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# The eigenfaces example: chaining PCA and SVMs\n\nThe goal of this example is to show how an unsupervised method and a\nsupervised one can be chained for better prediction. It starts with a\ndidactic but lengthy way of doing things, and finishes with the\nidiomatic approach to pipelining in scikit-learn.\n\nHere we'll take a look at a simple facial recognition example. Ideally,\nwe would use a dataset consisting of a subset of the [Labeled Faces in\nthe Wild](http://vis-www.cs.umass.edu/lfw/)_ data that is available\nwith :func:`sklearn.datasets.fetch_lfw_people`. However, this is a\nrelatively large download (~200MB) so we will do the tutorial on a\nsimpler, less rich dataset. Feel free to explore the LFW dataset.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn import datasets\n\nfaces = datasets.fetch_olivetti_faces()\nfaces.data.shape" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let's visualize these faces to see what we're working with\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nfig = plt.figure(figsize=(8, 6))\n# plot several images\nfor i in range(15):\n ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[])\n ax.imshow(faces.images[i], cmap=\"bone\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + ".. tip::\n\n Note is that these faces have already been localized and scaled to a\n common size. This is an important preprocessing piece for facial\n recognition, and is a process that can require a large collection of\n training data. This can be done in scikit-learn, but the challenge is\n gathering a sufficient amount of training data for the algorithm to work.\n Fortunately, this piece is common enough that it has been done. One good\n resource is\n [OpenCV](https://docs.opencv.org/2.4/modules/contrib/doc/facerec/facerec_tutorial.html)_,\n the *Open Computer Vision Library*.\n\nWe'll perform a Support Vector classification of the images. We'll do a\ntypical train-test split on the images:\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(\n faces.data, faces.target, random_state=0\n)\n\nprint(X_train.shape, X_test.shape)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Preprocessing: Principal Component Analysis\n\n1850 dimensions is a lot for SVM. We can use PCA to reduce these 1850\nfeatures to a manageable size, while maintaining most of the information\nin the dataset.\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn import decomposition\n\npca = decomposition.PCA(n_components=150, whiten=True)\npca.fit(X_train)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "One interesting part of PCA is that it computes the \"mean\" face, which\ncan be interesting to examine:\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "plt.imshow(pca.mean_.reshape(faces.images[0].shape), cmap=\"bone\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The principal components measure deviations about this mean along\northogonal axes.\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "print(pca.components_.shape)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "It is also interesting to visualize these principal components:\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "fig = plt.figure(figsize=(16, 6))\nfor i in range(30):\n ax = fig.add_subplot(3, 10, i + 1, xticks=[], yticks=[])\n ax.imshow(pca.components_[i].reshape(faces.images[0].shape), cmap=\"bone\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The components (\"eigenfaces\") are ordered by their importance from\ntop-left to bottom-right. We see that the first few components seem to\nprimarily take care of lighting conditions; the remaining components\npull out certain identifying features: the nose, eyes, eyebrows, etc.\n\nWith this projection computed, we can now project our original training\nand test data onto the PCA basis:\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "X_train_pca = pca.transform(X_train)\nX_test_pca = pca.transform(X_test)\nprint(X_train_pca.shape)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "print(X_test_pca.shape)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "These projected components correspond to factors in a linear combination\nof component images such that the combination approaches the original\nface.\n\n## Doing the Learning: Support Vector Machines\n\nNow we'll perform support-vector-machine classification on this reduced\ndataset:\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn import svm\n\nclf = svm.SVC(C=5.0, gamma=0.001)\nclf.fit(X_train_pca, y_train)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Finally, we can evaluate how well this classification did. First, we\nmight plot a few of the test-cases with the labels learned from the\ntraining set:\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n\nfig = plt.figure(figsize=(8, 6))\nfor i in range(15):\n ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[])\n ax.imshow(X_test[i].reshape(faces.images[0].shape), cmap=\"bone\")\n y_pred = clf.predict(X_test_pca[i, np.newaxis])[0]\n color = \"black\" if y_pred == y_test[i] else \"red\"\n ax.set_title(y_pred, fontsize=\"small\", color=color)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The classifier is correct on an impressive number of images given the\nsimplicity of its learning model! Using a linear classifier on 150\nfeatures derived from the pixel-level data, the algorithm correctly\nidentifies a large number of the people in the images.\n\nAgain, we can quantify this effectiveness using one of several measures\nfrom :mod:`sklearn.metrics`. First we can do the classification\nreport, which shows the precision, recall and other measures of the\n\"goodness\" of the classification:\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn import metrics\n\ny_pred = clf.predict(X_test_pca)\nprint(metrics.classification_report(y_test, y_pred))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Another interesting metric is the *confusion matrix*, which indicates\nhow often any two items are mixed-up. The confusion matrix of a perfect\nclassifier would only have nonzero entries on the diagonal, with zeros\non the off-diagonal:\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "print(metrics.confusion_matrix(y_test, y_pred))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Pipelining\n\nAbove we used PCA as a pre-processing step before applying our support\nvector machine classifier. Plugging the output of one estimator directly\ninto the input of a second estimator is a commonly used pattern; for\nthis reason scikit-learn provides a ``Pipeline`` object which automates\nthis process. The above problem can be re-expressed as a pipeline as\nfollows:\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.pipeline import Pipeline\n\nclf = Pipeline(\n [\n (\"pca\", decomposition.PCA(n_components=150, whiten=True)),\n (\"svm\", svm.LinearSVC(C=1.0)),\n ]\n)\n\nclf.fit(X_train, y_train)\n\ny_pred = clf.predict(X_test)\nprint(metrics.confusion_matrix(y_pred, y_test))\nplt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## A Note on Facial Recognition\n\nHere we have used PCA \"eigenfaces\" as a pre-processing step for facial\nrecognition. The reason we chose this is because PCA is a\nbroadly-applicable technique, which can be useful for a wide array of\ndata types. Research in the field of facial recognition in particular,\nhowever, has shown that other more specific feature extraction methods\nare can be much more effective.\n\n" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/9e308838d2e1d42c5fe93c40df441351/plot_regression.py b/_downloads/9e308838d2e1d42c5fe93c40df441351/plot_regression.py new file mode 100644 index 000000000..c0bb5f564 --- /dev/null +++ b/_downloads/9e308838d2e1d42c5fe93c40df441351/plot_regression.py @@ -0,0 +1,63 @@ +""" +Simple Regression +==================== + +Fit a simple linear regression using 'statsmodels', compute corresponding +p-values. +""" + +# Original author: Thomas Haslwanter + +import numpy as np +import matplotlib.pyplot as plt +import pandas + +# For statistics. Requires statsmodels 5.0 or more +from statsmodels.formula.api import ols + +# Analysis of Variance (ANOVA) on linear models +from statsmodels.stats.anova import anova_lm + +############################################################################## +# Generate and show the data +x = np.linspace(-5, 5, 20) + +# To get reproducible values, provide a seed value +rng = np.random.default_rng(27446968) + +y = -5 + 3 * x + 4 * np.random.normal(size=x.shape) + +# Plot the data +plt.figure(figsize=(5, 4)) +plt.plot(x, y, "o") + +############################################################################## +# Multilinear regression model, calculating fit, P-values, confidence +# intervals etc. + +# Convert the data into a Pandas DataFrame to use the formulas framework +# in statsmodels +data = pandas.DataFrame({"x": x, "y": y}) + +# Fit the model +model = ols("y ~ x", data).fit() + +# Print the summary +print(model.summary()) + +# Perform analysis of variance on fitted linear model +anova_results = anova_lm(model) + +print("\nANOVA results") +print(anova_results) + +############################################################################## +# Plot the fitted model + +# Retrieve the parameter estimates +offset, coef = model._results.params +plt.plot(x, x * coef + offset) +plt.xlabel("x") +plt.ylabel("y") + +plt.show() diff --git a/_downloads/9e9950c070c433b994305d82bac8324d/plot_curvefit_temperature_data.zip b/_downloads/9e9950c070c433b994305d82bac8324d/plot_curvefit_temperature_data.zip new file mode 100644 index 000000000..215e74837 Binary files /dev/null and b/_downloads/9e9950c070c433b994305d82bac8324d/plot_curvefit_temperature_data.zip differ diff --git a/_downloads/9ed960f80d4d9fbda51acfc92b6ed2d2/plot_cumulative_wind_speed_prediction.py b/_downloads/9ed960f80d4d9fbda51acfc92b6ed2d2/plot_cumulative_wind_speed_prediction.py new file mode 100644 index 000000000..699268c9f --- /dev/null +++ b/_downloads/9ed960f80d4d9fbda51acfc92b6ed2d2/plot_cumulative_wind_speed_prediction.py @@ -0,0 +1,32 @@ +""" +Cumulative wind speed prediction +================================ + +Generate the image cumulative-wind-speed-prediction.png +for the interpolate section of scipy.rst. +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +max_speeds = np.load("max-speeds.npy") +years_nb = max_speeds.shape[0] + +cprob = (np.arange(years_nb, dtype=np.float32) + 1) / (years_nb + 1) +sorted_max_speeds = np.sort(max_speeds) +speed_spline = sp.interpolate.UnivariateSpline(cprob, sorted_max_speeds) +nprob = np.linspace(0, 1, 100) +fitted_max_speeds = speed_spline(nprob) + +fifty_prob = 1.0 - 0.02 +fifty_wind = speed_spline(fifty_prob) + +plt.figure() +plt.plot(sorted_max_speeds, cprob, "o") +plt.plot(fitted_max_speeds, nprob, "g--") +plt.plot([fifty_wind], [fifty_prob], "o", ms=8.0, mfc="y", mec="y") +plt.text(30, 0.05, rf"$V_{{50}} = {fifty_wind:.2f} \, m/s$") +plt.plot([fifty_wind, fifty_wind], [plt.axis()[2], fifty_prob], "k--") +plt.xlabel("Annual wind speed maxima [$m/s$]") +plt.ylabel("Cumulative probability") diff --git a/_downloads/9effa8131e1f4d62961812583d4d606a/plot_text.py b/_downloads/9effa8131e1f4d62961812583d4d606a/plot_text.py new file mode 100644 index 000000000..8b119b11e --- /dev/null +++ b/_downloads/9effa8131e1f4d62961812583d4d606a/plot_text.py @@ -0,0 +1,48 @@ +""" +Demo text printing +=================== + +A example showing off elaborate text printing with matplotlib. +""" + +import numpy as np +import matplotlib.pyplot as plt + + +eqs = [] +eqs.append( + r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$" +) +eqs.append( + r"$\frac{d\rho}{d t} + \rho \vec{v}\cdot\nabla\vec{v} = -\nabla p + \mu\nabla^2 \vec{v} + \rho \vec{g}$" +) +eqs.append(r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$") +eqs.append(r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$") +eqs.append(r"$F_G = G\frac{m_1m_2}{r^2}$") + +plt.axes((0.025, 0.025, 0.95, 0.95)) + +rng = np.random.default_rng() + +for i in range(24): + index = rng.integers(0, len(eqs)) + eq = eqs[index] + size = np.random.uniform(12, 32) + x, y = np.random.uniform(0, 1, 2) + alpha = np.random.uniform(0.25, 0.75) + plt.text( + x, + y, + eq, + ha="center", + va="center", + color="#11557c", + alpha=alpha, + transform=plt.gca().transAxes, + fontsize=size, + clip_on=True, + ) +plt.xticks([]) +plt.yticks([]) + +plt.show() diff --git a/_downloads/9f3d6a2f66b687ce890ac2989abccb9a/plot_ML_flow_chart.py b/_downloads/9f3d6a2f66b687ce890ac2989abccb9a/plot_ML_flow_chart.py new file mode 100644 index 000000000..b986ab8de --- /dev/null +++ b/_downloads/9f3d6a2f66b687ce890ac2989abccb9a/plot_ML_flow_chart.py @@ -0,0 +1,166 @@ +""" +Tutorial Diagrams +----------------- + +This script plots the flow-charts used in the scikit-learn tutorials. +""" + +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.patches import Circle, Rectangle, Polygon, Arrow, FancyArrow + + +def create_base(box_bg="#CCCCCC", arrow1="#88CCFF", arrow2="#88FF88", supervised=True): + fig = plt.figure(figsize=(9, 6), facecolor="w") + ax = plt.axes((0, 0, 1, 1), xticks=[], yticks=[], frameon=False) + ax.set_xlim(0, 9) + ax.set_ylim(0, 6) + + patches = [ + Rectangle((0.3, 3.6), 1.5, 1.8, zorder=1, fc=box_bg), + Rectangle((0.5, 3.8), 1.5, 1.8, zorder=2, fc=box_bg), + Rectangle((0.7, 4.0), 1.5, 1.8, zorder=3, fc=box_bg), + Rectangle((2.9, 3.6), 0.2, 1.8, fc=box_bg), + Rectangle((3.1, 3.8), 0.2, 1.8, fc=box_bg), + Rectangle((3.3, 4.0), 0.2, 1.8, fc=box_bg), + Rectangle((0.3, 0.2), 1.5, 1.8, fc=box_bg), + Rectangle((2.9, 0.2), 0.2, 1.8, fc=box_bg), + Circle((5.5, 3.5), 1.0, fc=box_bg), + Polygon([[5.5, 1.7], [6.1, 1.1], [5.5, 0.5], [4.9, 1.1]], fc=box_bg), + FancyArrow( + 2.3, 4.6, 0.35, 0, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2 + ), + FancyArrow( + 3.75, 4.2, 0.5, -0.2, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2 + ), + FancyArrow( + 5.5, 2.4, 0, -0.4, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2 + ), + FancyArrow( + 2.0, 1.1, 0.5, 0, fc=arrow2, width=0.25, head_width=0.5, head_length=0.2 + ), + FancyArrow( + 3.3, 1.1, 1.3, 0, fc=arrow2, width=0.25, head_width=0.5, head_length=0.2 + ), + FancyArrow( + 6.2, 1.1, 0.8, 0, fc=arrow2, width=0.25, head_width=0.5, head_length=0.2 + ), + ] + + if supervised: + patches += [ + Rectangle((0.3, 2.4), 1.5, 0.5, zorder=1, fc=box_bg), + Rectangle((0.5, 2.6), 1.5, 0.5, zorder=2, fc=box_bg), + Rectangle((0.7, 2.8), 1.5, 0.5, zorder=3, fc=box_bg), + FancyArrow( + 2.3, 2.9, 2.0, 0, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2 + ), + Rectangle((7.3, 0.85), 1.5, 0.5, fc=box_bg), + ] + else: + patches += [Rectangle((7.3, 0.2), 1.5, 1.8, fc=box_bg)] + + for p in patches: + ax.add_patch(p) + + plt.text( + 1.45, + 4.9, + "Training\nText,\nDocuments,\nImages,\netc.", + ha="center", + va="center", + fontsize=14, + ) + + plt.text(3.6, 4.9, "Feature\nVectors", ha="left", va="center", fontsize=14) + + plt.text( + 5.5, 3.5, "Machine\nLearning\nAlgorithm", ha="center", va="center", fontsize=14 + ) + + plt.text( + 1.05, + 1.1, + "New Text,\nDocument,\nImage,\netc.", + ha="center", + va="center", + fontsize=14, + ) + + plt.text(3.3, 1.7, "Feature\nVector", ha="left", va="center", fontsize=14) + + plt.text(5.5, 1.1, "Predictive\nModel", ha="center", va="center", fontsize=12) + + if supervised: + plt.text(1.45, 3.05, "Labels", ha="center", va="center", fontsize=14) + + plt.text(8.05, 1.1, "Expected\nLabel", ha="center", va="center", fontsize=14) + plt.text( + 8.8, 5.8, "Supervised Learning Model", ha="right", va="top", fontsize=18 + ) + + else: + plt.text( + 8.05, + 1.1, + "Likelihood\nor Cluster ID\nor Better\nRepresentation", + ha="center", + va="center", + fontsize=12, + ) + plt.text( + 8.8, 5.8, "Unsupervised Learning Model", ha="right", va="top", fontsize=18 + ) + + +def plot_supervised_chart(annotate=False): + create_base(supervised=True) + if annotate: + fontdict = {"color": "r", "weight": "bold", "size": 14} + plt.text( + 1.9, + 4.55, + "X = vec.fit_transform(input)", + fontdict=fontdict, + rotation=20, + ha="left", + va="bottom", + ) + plt.text( + 3.7, + 3.2, + "clf.fit(X, y)", + fontdict=fontdict, + rotation=20, + ha="left", + va="bottom", + ) + plt.text( + 1.7, + 1.5, + "X_new = vec.transform(input)", + fontdict=fontdict, + rotation=20, + ha="left", + va="bottom", + ) + plt.text( + 6.1, + 1.5, + "y_new = clf.predict(X_new)", + fontdict=fontdict, + rotation=20, + ha="left", + va="bottom", + ) + + +def plot_unsupervised_chart(): + create_base(supervised=False) + + +if __name__ == "__main__": + plot_supervised_chart(False) + plot_supervised_chart(True) + plot_unsupervised_chart() + plt.show() diff --git a/_downloads/9f97d03cee7ad959e5e8c9433392fd22/plot_spectrogram.zip b/_downloads/9f97d03cee7ad959e5e8c9433392fd22/plot_spectrogram.zip new file mode 100644 index 000000000..2dc29da51 Binary files /dev/null and b/_downloads/9f97d03cee7ad959e5e8c9433392fd22/plot_spectrogram.zip differ diff --git a/_downloads/ScientificPythonLectures-simple.pdf b/_downloads/ScientificPythonLectures-simple.pdf new file mode 100644 index 000000000..ceda064cc Binary files /dev/null and b/_downloads/ScientificPythonLectures-simple.pdf differ diff --git a/_downloads/ScientificPythonLectures.pdf b/_downloads/ScientificPythonLectures.pdf new file mode 100644 index 000000000..84d39b067 Binary files /dev/null and b/_downloads/ScientificPythonLectures.pdf differ diff --git a/_downloads/a0089e3fb9ec86e5880d0264c7475f79/plot_scatter.py b/_downloads/a0089e3fb9ec86e5880d0264c7475f79/plot_scatter.py new file mode 100644 index 000000000..c27f599b5 --- /dev/null +++ b/_downloads/a0089e3fb9ec86e5880d0264c7475f79/plot_scatter.py @@ -0,0 +1,25 @@ +""" +Plotting a scatter of points +============================== + +A simple example showing how to plot a scatter of points with matplotlib. +""" + +import numpy as np +import matplotlib.pyplot as plt + +n = 1024 +rng = np.random.default_rng() +X = rng.normal(0, 1, n) +Y = rng.normal(0, 1, n) +T = np.arctan2(Y, X) + +plt.axes((0.025, 0.025, 0.95, 0.95)) +plt.scatter(X, Y, s=75, c=T, alpha=0.5) + +plt.xlim(-1.5, 1.5) +plt.xticks([]) +plt.ylim(-1.5, 1.5) +plt.yticks([]) + +plt.show() diff --git a/_downloads/a0486ba2c53c77e26e3809bd8c66266b/plot_ugly.py b/_downloads/a0486ba2c53c77e26e3809bd8c66266b/plot_ugly.py new file mode 100644 index 000000000..e3910fab2 --- /dev/null +++ b/_downloads/a0486ba2c53c77e26e3809bd8c66266b/plot_ugly.py @@ -0,0 +1,27 @@ +""" +A example of plotting not quite right +====================================== + +An "ugly" example of plotting. +""" + +import numpy as np +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt + +matplotlib.rc("grid", color="black", linestyle="-", linewidth=1) + +fig = plt.figure(figsize=(5, 4), dpi=72) +axes = fig.add_axes((0.01, 0.01, 0.98, 0.98), facecolor=".75") +X = np.linspace(0, 2, 40) +Y = np.sin(2 * np.pi * X) +plt.plot(X, Y, lw=0.05, c="b", antialiased=False) + +plt.xticks([]) +plt.yticks(np.arange(-1.0, 1.0, 0.2)) +plt.grid() +ax = plt.gca() + +plt.show() diff --git a/_downloads/a060ac0d4ba378dc3d99a072382aa4a8/plot_ms.py b/_downloads/a060ac0d4ba378dc3d99a072382aa4a8/plot_ms.py new file mode 100644 index 000000000..ac55f8e06 --- /dev/null +++ b/_downloads/a060ac0d4ba378dc3d99a072382aa4a8/plot_ms.py @@ -0,0 +1,36 @@ +""" +Marker size +=========== + +Demo the marker size control in matplotlib. +""" + +import matplotlib.pyplot as plt + +size = 256, 16 +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = plt.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +plt.axes((0, 0, 1, 1), frameon=False) + +for i in range(1, 11): + plt.plot( + [ + i, + ], + [ + 1, + ], + "s", + markersize=i, + markerfacecolor="w", + markeredgewidth=0.5, + markeredgecolor="k", + ) + +plt.xlim(0, 11) +plt.xticks([]) +plt.yticks([]) + +plt.show() diff --git a/_downloads/a09c4ec16d60289c0888ca6e67fa3dad/plot_colormaps.py b/_downloads/a09c4ec16d60289c0888ca6e67fa3dad/plot_colormaps.py new file mode 100644 index 000000000..fb4a98800 --- /dev/null +++ b/_downloads/a09c4ec16d60289c0888ca6e67fa3dad/plot_colormaps.py @@ -0,0 +1,29 @@ +""" +Colormaps +========= + +An example plotting the matplotlib colormaps. +""" + +import numpy as np + +import matplotlib +import matplotlib.pyplot as plt + + +plt.rc("text", usetex=False) +a = np.outer(np.arange(0, 1, 0.01), np.ones(10)) + +plt.figure(figsize=(10, 5)) +plt.subplots_adjust(top=0.8, bottom=0.05, left=0.01, right=0.99) +maps = [m for m in matplotlib.colormaps if not m.endswith("_r")] +maps.sort() +l = len(maps) + 1 + +for i, m in enumerate(maps): + plt.subplot(1, l, i + 1) + plt.axis("off") + plt.imshow(a, aspect="auto", cmap=plt.get_cmap(m), origin="lower") + plt.title(m, rotation=90, fontsize=10, va="bottom") + +plt.show() diff --git a/_downloads/a0c5fcd7d59ff915efc8fa7d449eb97b/plot_camera.py b/_downloads/a0c5fcd7d59ff915efc8fa7d449eb97b/plot_camera.py new file mode 100644 index 000000000..030b6d1ef --- /dev/null +++ b/_downloads/a0c5fcd7d59ff915efc8fa7d449eb97b/plot_camera.py @@ -0,0 +1,19 @@ +""" +Displaying a simple image +========================= + +Load and display an image +""" + +import matplotlib.pyplot as plt +from skimage import data + +camera = data.camera() + + +plt.figure(figsize=(4, 4)) +plt.imshow(camera, cmap="gray", interpolation="nearest") +plt.axis("off") + +plt.tight_layout() +plt.show() diff --git a/_downloads/a0ec376e4bfb9e9d199e96fa59b160a7/plot_iris_analysis.py b/_downloads/a0ec376e4bfb9e9d199e96fa59b160a7/plot_iris_analysis.py new file mode 100644 index 000000000..f00ae0259 --- /dev/null +++ b/_downloads/a0ec376e4bfb9e9d199e96fa59b160a7/plot_iris_analysis.py @@ -0,0 +1,50 @@ +""" +Analysis of Iris petal and sepal sizes +======================================= + +Illustrate an analysis on a real dataset: + +- Visualizing the data to formulate intuitions +- Fitting of a linear model +- Hypothesis test of the effect of a categorical variable in the presence + of a continuous confound + +""" + +import matplotlib.pyplot as plt + +import pandas +from pandas import plotting + +from statsmodels.formula.api import ols + +# Load the data +data = pandas.read_csv("iris.csv") + +############################################################################## +# Plot a scatter matrix + +# Express the names as categories +categories = pandas.Categorical(data["name"]) + +# The parameter 'c' is passed to plt.scatter and will control the color +plotting.scatter_matrix(data, c=categories.codes, marker="o") + +fig = plt.gcf() +fig.suptitle("blue: setosa, green: versicolor, red: virginica", size=13) + +############################################################################## +# Statistical analysis + +# Let us try to explain the sepal length as a function of the petal +# width and the category of iris + +model = ols("sepal_width ~ name + petal_length", data).fit() +print(model.summary()) + +# Now formulate a "contrast", to test if the offset for versicolor and +# virginica are identical + +print("Testing the difference between effect of versicolor and virginica") +print(model.f_test([0, 1, -1, 0])) +plt.show() diff --git a/_downloads/a0ff70d70c1a22e67cb888f905cdb5d1/plot_connect_measurements.ipynb b/_downloads/a0ff70d70c1a22e67cb888f905cdb5d1/plot_connect_measurements.ipynb new file mode 100644 index 000000000..52d788cfe --- /dev/null +++ b/_downloads/a0ff70d70c1a22e67cb888f905cdb5d1/plot_connect_measurements.ipynb @@ -0,0 +1,97 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Demo connected components\n\nExtracting and labeling connected components in a 2D array\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Generate some binary data\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "x, y = np.indices((100, 100))\nsig = (\n np.sin(2 * np.pi * x / 50.0)\n * np.sin(2 * np.pi * y / 50.0)\n * (1 + x * y / 50.0**2) ** 2\n)\nmask = sig > 1\n\nplt.figure(figsize=(7, 3.5))\nplt.subplot(1, 2, 1)\nplt.imshow(sig)\nplt.axis(\"off\")\nplt.title(\"sig\")\n\nplt.subplot(1, 2, 2)\nplt.imshow(mask, cmap=\"gray\")\nplt.axis(\"off\")\nplt.title(\"mask\")\nplt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Label connected components\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import scipy as sp\n\nlabels, nb = sp.ndimage.label(mask)\n\nplt.figure(figsize=(3.5, 3.5))\nplt.imshow(labels)\nplt.title(\"label\")\nplt.axis(\"off\")\n\nplt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Extract the 4th connected component, and crop the array around it\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "sl = sp.ndimage.find_objects(labels == 4)\nplt.figure(figsize=(3.5, 3.5))\nplt.imshow(sig[sl[0]])\nplt.title(\"Cropped connected component\")\nplt.axis(\"off\")\n\nplt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/a102f7251697bfda0298d81da99265a8/plot_mec.py b/_downloads/a102f7251697bfda0298d81da99265a8/plot_mec.py new file mode 100644 index 000000000..09c562c1f --- /dev/null +++ b/_downloads/a102f7251697bfda0298d81da99265a8/plot_mec.py @@ -0,0 +1,40 @@ +""" +Marker edge color +================== + +Demo the marker edge color of matplotlib's markers. +""" + +import numpy as np +import matplotlib.pyplot as plt + +size = 256, 16 +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = plt.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +plt.axes((0, 0, 1, 1), frameon=False) + +rng = np.random.default_rng() + +for i in range(1, 11): + r, g, b = np.random.uniform(0, 1, 3) + plt.plot( + [ + i, + ], + [ + 1, + ], + "s", + markersize=5, + markerfacecolor="w", + markeredgewidth=1.5, + markeredgecolor=(r, g, b, 1), + ) + +plt.xlim(0, 11) +plt.xticks([]) +plt.yticks([]) + +plt.show() diff --git a/_downloads/a270b1ff8e5e827628ac7831afe66f78/plot_svm_non_linear.zip b/_downloads/a270b1ff8e5e827628ac7831afe66f78/plot_svm_non_linear.zip new file mode 100644 index 000000000..907d25173 Binary files /dev/null and b/_downloads/a270b1ff8e5e827628ac7831afe66f78/plot_svm_non_linear.zip differ diff --git a/_downloads/a2a07370678339b54fd037b07adf498f/plot_mathematical_morpho.py b/_downloads/a2a07370678339b54fd037b07adf498f/plot_mathematical_morpho.py new file mode 100644 index 000000000..d802a736f --- /dev/null +++ b/_downloads/a2a07370678339b54fd037b07adf498f/plot_mathematical_morpho.py @@ -0,0 +1,50 @@ +""" +============================= +Demo mathematical morphology +============================= + +A basic demo of binary opening and closing. +""" + +# Generate some binary data +import numpy as np + +np.random.seed(0) +a = np.zeros((50, 50)) +a[10:-10, 10:-10] = 1 +a += 0.25 * np.random.standard_normal(a.shape) +mask = a >= 0.5 + +# Apply mathematical morphology +import scipy as sp + +opened_mask = sp.ndimage.binary_opening(mask) +closed_mask = sp.ndimage.binary_closing(opened_mask) + +# Plot +import matplotlib.pyplot as plt + +plt.figure(figsize=(12, 3.5)) +plt.subplot(141) +plt.imshow(a, cmap="gray") +plt.axis("off") +plt.title("a") + +plt.subplot(142) +plt.imshow(mask, cmap="gray") +plt.axis("off") +plt.title("mask") + +plt.subplot(143) +plt.imshow(opened_mask, cmap="gray") +plt.axis("off") +plt.title("opened_mask") + +plt.subplot(144) +plt.imshow(closed_mask, cmap="gray") +plt.title("closed_mask") +plt.axis("off") + +plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99) + +plt.show() diff --git a/_downloads/a3214e6ab64419b419d4601a6d2a99a8/plot_mandelbrot.zip b/_downloads/a3214e6ab64419b419d4601a6d2a99a8/plot_mandelbrot.zip new file mode 100644 index 000000000..8ade3680e Binary files /dev/null and b/_downloads/a3214e6ab64419b419d4601a6d2a99a8/plot_mandelbrot.zip differ diff --git a/_downloads/a418a4cfd48b230cb01cd2400f797ee3/plot_convex.py b/_downloads/a418a4cfd48b230cb01cd2400f797ee3/plot_convex.py new file mode 100644 index 000000000..c835d4047 --- /dev/null +++ b/_downloads/a418a4cfd48b230cb01cd2400f797ee3/plot_convex.py @@ -0,0 +1,45 @@ +""" +Convex function +================ + +A figure showing the definition of a convex function +""" + +import numpy as np +import matplotlib.pyplot as plt + +x = np.linspace(-1, 2) + +plt.figure(1, figsize=(3, 2.5)) +plt.clf() + +# A convex function +plt.plot(x, x**2, linewidth=2) +plt.text(-0.7, -(0.6**2), "$f$", size=20) + +# The tangent in one point +plt.plot(x, 2 * x - 1) +plt.plot(1, 1, "k+") +plt.text(0.3, -0.75, "Tangent to $f$", size=15) +plt.text(1, 1 - 0.5, "C", size=15) + +# Convexity as barycenter +plt.plot([0.35, 1.85], [0.35**2, 1.85**2]) +plt.plot([0.35, 1.85], [0.35**2, 1.85**2], "k+") +plt.text(0.35 - 0.2, 0.35**2 + 0.1, "A", size=15) +plt.text(1.85 - 0.2, 1.85**2, "B", size=15) + +plt.ylim(ymin=-1) +plt.axis("off") +plt.tight_layout() + +# Convexity as barycenter +plt.figure(2, figsize=(3, 2.5)) +plt.clf() +plt.plot(x, x**2 + np.exp(-5 * (x - 0.5) ** 2), linewidth=2) +plt.text(-0.7, -(0.6**2), "$f$", size=20) + +plt.ylim(ymin=-1) +plt.axis("off") +plt.tight_layout() +plt.show() diff --git a/_downloads/a4553a93f54d361176c368c5aed853e8/plot_multiplot.py b/_downloads/a4553a93f54d361176c368c5aed853e8/plot_multiplot.py new file mode 100644 index 000000000..564ad09ac --- /dev/null +++ b/_downloads/a4553a93f54d361176c368c5aed853e8/plot_multiplot.py @@ -0,0 +1,28 @@ +""" +Subplots +========= + +Show multiple subplots in matplotlib. +""" + +import matplotlib.pyplot as plt + +fig = plt.figure() +fig.subplots_adjust(bottom=0.025, left=0.025, top=0.975, right=0.975) + +plt.subplot(2, 1, 1) +plt.xticks([]), plt.yticks([]) + +plt.subplot(2, 3, 4) +plt.xticks([]) +plt.yticks([]) + +plt.subplot(2, 3, 5) +plt.xticks([]) +plt.yticks([]) + +plt.subplot(2, 3, 6) +plt.xticks([]) +plt.yticks([]) + +plt.show() diff --git a/_downloads/a4f5923a3ef0800f35394133174ab90a/plot_brain_size.zip b/_downloads/a4f5923a3ef0800f35394133174ab90a/plot_brain_size.zip new file mode 100644 index 000000000..3ef620306 Binary files /dev/null and b/_downloads/a4f5923a3ef0800f35394133174ab90a/plot_brain_size.zip differ diff --git a/_downloads/a556d904c77fdb21411c127bda4bf2fc/plot_chebyfit.zip b/_downloads/a556d904c77fdb21411c127bda4bf2fc/plot_chebyfit.zip new file mode 100644 index 000000000..a0c3d537c Binary files /dev/null and b/_downloads/a556d904c77fdb21411c127bda4bf2fc/plot_chebyfit.zip differ diff --git a/_downloads/a66e54b3827ba5267cfb3e5e88eab733/plot_synthetic_data.ipynb b/_downloads/a66e54b3827ba5267cfb3e5e88eab733/plot_synthetic_data.ipynb new file mode 100644 index 000000000..f7613d9a5 --- /dev/null +++ b/_downloads/a66e54b3827ba5267cfb3e5e88eab733/plot_synthetic_data.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Synthetic data\n\nThe example generates and displays simple synthetic data.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nrng = np.random.default_rng(27446968)\nn = 10\nl = 256\nim = np.zeros((l, l))\npoints = l * rng.random((2, n**2))\nim[(points[0]).astype(int), (points[1]).astype(int)] = 1\nim = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n))\n\nmask = im > im.mean()\n\nlabel_im, nb_labels = sp.ndimage.label(mask)\n\nplt.figure(figsize=(9, 3))\n\nplt.subplot(131)\nplt.imshow(im)\nplt.axis(\"off\")\nplt.subplot(132)\nplt.imshow(mask, cmap=\"gray\")\nplt.axis(\"off\")\nplt.subplot(133)\nplt.imshow(label_im, cmap=\"nipy_spectral\")\nplt.axis(\"off\")\n\nplt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1)\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/a699756fa9adf5bfdad78fbde59b3acf/plot_periodicity_finder.py b/_downloads/a699756fa9adf5bfdad78fbde59b3acf/plot_periodicity_finder.py new file mode 100644 index 000000000..f2b13c890 --- /dev/null +++ b/_downloads/a699756fa9adf5bfdad78fbde59b3acf/plot_periodicity_finder.py @@ -0,0 +1,52 @@ +""" +========================== +Crude periodicity finding +========================== + +Discover the periods in evolution of animal populations +(:download:`../../../../data/populations.txt`) +""" + +############################################################ +# Load the data +############################################################ + +import numpy as np + +data = np.loadtxt("../../../../data/populations.txt") +years = data[:, 0] +populations = data[:, 1:] + +############################################################ +# Plot the data +############################################################ + +import matplotlib.pyplot as plt + +plt.figure() +plt.plot(years, populations * 1e-3) +plt.xlabel("Year") +plt.ylabel(r"Population number ($\cdot10^3$)") +plt.legend(["hare", "lynx", "carrot"], loc=1) + +############################################################ +# Plot its periods +############################################################ +import scipy as sp + +ft_populations = sp.fft.fft(populations, axis=0) +frequencies = sp.fft.fftfreq(populations.shape[0], years[1] - years[0]) +periods = 1 / frequencies + +plt.figure() +plt.plot(periods, abs(ft_populations) * 1e-3, "o") +plt.xlim(0, 22) +plt.xlabel("Period") +plt.ylabel(r"Power ($\cdot10^3$)") + +plt.show() + +############################################################ +# There's probably a period of around 10 years (obvious from the +# plot), but for this crude a method, there's not enough data to say +# much more. diff --git a/_downloads/a76d0ee0f2c6e4f86b7fd7b2e08b0baf/plot_airfare.py b/_downloads/a76d0ee0f2c6e4f86b7fd7b2e08b0baf/plot_airfare.py new file mode 100644 index 000000000..f4d1cc0f0 --- /dev/null +++ b/_downloads/a76d0ee0f2c6e4f86b7fd7b2e08b0baf/plot_airfare.py @@ -0,0 +1,151 @@ +""" +Air fares before and after 9/11 +===================================== + +This is a business-intelligence (BI) like application. + +What is interesting here is that we may want to study fares as a function +of the year, paired accordingly to the trips, or forgetting the year, +only as a function of the trip endpoints. + +Using statsmodels' linear models, we find that both with an OLS (ordinary +least square) and a robust fit, the intercept and the slope are +significantly non-zero: the air fares have decreased between 2000 and +2001, and their dependence on distance travelled has also decreased + +""" + +# Standard library imports +import os + +############################################################################## +# Load the data +import pandas +import requests + +if not os.path.exists("airfares.txt"): + # Download the file if it is not present + r = requests.get( + "https://users.stat.ufl.edu/~winner/data/airq4.dat", + verify=False, # Wouldn't normally do this, but this site's certificate + # is not yet distributed + ) + with open("airfares.txt", "wb") as f: + f.write(r.content) + +# As a separator, ' +' is a regular expression that means 'one of more +# space' +data = pandas.read_csv( + "airfares.txt", + delim_whitespace=True, + header=0, + names=[ + "city1", + "city2", + "pop1", + "pop2", + "dist", + "fare_2000", + "nb_passengers_2000", + "fare_2001", + "nb_passengers_2001", + ], +) + +# we log-transform the number of passengers +import numpy as np + +data["nb_passengers_2000"] = np.log10(data["nb_passengers_2000"]) +data["nb_passengers_2001"] = np.log10(data["nb_passengers_2001"]) + +############################################################################## +# Make a dataframe with the year as an attribute, instead of separate columns + +# This involves a small danse in which we separate the dataframes in 2, +# one for year 2000, and one for 2001, before concatenating again. + +# Make an index of each flight +data_flat = data.reset_index() + +data_2000 = data_flat[ + ["city1", "city2", "pop1", "pop2", "dist", "fare_2000", "nb_passengers_2000"] +] +# Rename the columns +data_2000.columns = pandas.Index( + ["city1", "city2", "pop1", "pop2", "dist", "fare", "nb_passengers"] +) +# Add a column with the year +data_2000.insert(0, "year", 2000) + +data_2001 = data_flat[ + ["city1", "city2", "pop1", "pop2", "dist", "fare_2001", "nb_passengers_2001"] +] +# Rename the columns +data_2001.columns = pandas.Index( + ["city1", "city2", "pop1", "pop2", "dist", "fare", "nb_passengers"] +) +# Add a column with the year +data_2001.insert(0, "year", 2001) + +data_flat = pandas.concat([data_2000, data_2001]) + + +############################################################################## +# Plot scatter matrices highlighting different aspects + +import seaborn + +seaborn.pairplot( + data_flat, vars=["fare", "dist", "nb_passengers"], kind="reg", markers="." +) + +# A second plot, to show the effect of the year (ie the 9/11 effect) +seaborn.pairplot( + data_flat, + vars=["fare", "dist", "nb_passengers"], + kind="reg", + hue="year", + markers=".", +) + + +############################################################################## +# Plot the difference in fare + +import matplotlib.pyplot as plt + +plt.figure(figsize=(5, 2)) +seaborn.boxplot(data.fare_2001 - data.fare_2000) +plt.title("Fare: 2001 - 2000") +plt.subplots_adjust() + +plt.figure(figsize=(5, 2)) +seaborn.boxplot(data.nb_passengers_2001 - data.nb_passengers_2000) +plt.title("NB passengers: 2001 - 2000") +plt.subplots_adjust() + + +############################################################################## +# Statistical testing: dependence of fare on distance and number of +# passengers +import statsmodels.formula.api as sm + +result = sm.ols(formula="fare ~ 1 + dist + nb_passengers", data=data_flat).fit() +print(result.summary()) + +# Using a robust fit +result = sm.rlm(formula="fare ~ 1 + dist + nb_passengers", data=data_flat).fit() +print(result.summary()) + + +############################################################################## +# Statistical testing: regression of fare on distance: 2001/2000 difference + +result = sm.ols(formula="fare_2001 - fare_2000 ~ 1 + dist", data=data).fit() +print(result.summary()) + +# Plot the corresponding regression +data["fare_difference"] = data["fare_2001"] - data["fare_2000"] +seaborn.lmplot(x="dist", y="fare_difference", data=data) + +plt.show() diff --git a/_downloads/a79bf8cb3c664c3c60e656d9230702cb/auto_examples_jupyter.zip b/_downloads/a79bf8cb3c664c3c60e656d9230702cb/auto_examples_jupyter.zip new file mode 100644 index 000000000..73bfdb5e9 Binary files /dev/null and b/_downloads/a79bf8cb3c664c3c60e656d9230702cb/auto_examples_jupyter.zip differ diff --git a/_downloads/a8003d07ee68e6e69caa7a1a2f3d240a/plot_labels.py b/_downloads/a8003d07ee68e6e69caa7a1a2f3d240a/plot_labels.py new file mode 100644 index 000000000..1b99701fd --- /dev/null +++ b/_downloads/a8003d07ee68e6e69caa7a1a2f3d240a/plot_labels.py @@ -0,0 +1,38 @@ +""" +Labelling connected components of an image +=========================================== + +This example shows how to label connected components of a binary image, using +the dedicated skimage.measure.label function. +""" + +from skimage import measure +from skimage import filters +import matplotlib.pyplot as plt +import numpy as np + +n = 12 +l = 256 +rng = np.random.default_rng(27446968) +im = np.zeros((l, l)) +points = l * rng.random((2, n**2)) +im[(points[0]).astype(int), (points[1]).astype(int)] = 1 +im = filters.gaussian(im, sigma=l / (4.0 * n)) +blobs = im > 0.7 * im.mean() + +all_labels = measure.label(blobs) +blobs_labels = measure.label(blobs, background=0) + +plt.figure(figsize=(9, 3.5)) +plt.subplot(131) +plt.imshow(blobs, cmap="gray") +plt.axis("off") +plt.subplot(132) +plt.imshow(all_labels, cmap="nipy_spectral") +plt.axis("off") +plt.subplot(133) +plt.imshow(blobs_labels, cmap="nipy_spectral") +plt.axis("off") + +plt.tight_layout() +plt.show() diff --git a/_downloads/a804a1eb4b4e0f0bd776f7d1aa1a6833/plot_exercise_10.ipynb b/_downloads/a804a1eb4b4e0f0bd776f7d1aa1a6833/plot_exercise_10.ipynb new file mode 100644 index 000000000..9ceefaf3f --- /dev/null +++ b/_downloads/a804a1eb4b4e0f0bd776f7d1aa1a6833/plot_exercise_10.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Exercise\n\nExercises with matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(8, 5), dpi=80)\nplt.subplot(111)\n\nX = np.linspace(-np.pi, np.pi, 256)\nC, S = np.cos(X), np.sin(X)\n\nplt.plot(X, C, color=\"blue\", linewidth=2.5, linestyle=\"-\", label=\"cosine\")\nplt.plot(X, S, color=\"red\", linewidth=2.5, linestyle=\"-\", label=\"sine\")\n\nax = plt.gca()\nax.spines[\"right\"].set_color(\"none\")\nax.spines[\"top\"].set_color(\"none\")\nax.xaxis.set_ticks_position(\"bottom\")\nax.spines[\"bottom\"].set_position((\"data\", 0))\nax.yaxis.set_ticks_position(\"left\")\nax.spines[\"left\"].set_position((\"data\", 0))\n\nplt.xlim(X.min() * 1.1, X.max() * 1.1)\nplt.xticks(\n [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],\n [r\"$-\\pi$\", r\"$-\\pi/2$\", r\"$0$\", r\"$+\\pi/2$\", r\"$+\\pi$\"],\n)\n\nplt.ylim(C.min() * 1.1, C.max() * 1.1)\nplt.yticks([-1, 1], [r\"$-1$\", r\"$+1$\"])\n\nplt.legend(loc=\"upper left\")\n\nt = 2 * np.pi / 3\nplt.plot([t, t], [0, np.cos(t)], color=\"blue\", linewidth=1.5, linestyle=\"--\")\nplt.scatter(\n [\n t,\n ],\n [\n np.cos(t),\n ],\n 50,\n color=\"blue\",\n)\nplt.annotate(\n r\"$sin(\\frac{2\\pi}{3})=\\frac{\\sqrt{3}}{2}$\",\n xy=(t, np.sin(t)),\n xycoords=\"data\",\n xytext=(10, 30),\n textcoords=\"offset points\",\n fontsize=16,\n arrowprops={\"arrowstyle\": \"->\", \"connectionstyle\": \"arc3,rad=.2\"},\n)\n\nplt.plot([t, t], [0, np.sin(t)], color=\"red\", linewidth=1.5, linestyle=\"--\")\nplt.scatter(\n [\n t,\n ],\n [\n np.sin(t),\n ],\n 50,\n color=\"red\",\n)\nplt.annotate(\n r\"$cos(\\frac{2\\pi}{3})=-\\frac{1}{2}$\",\n xy=(t, np.cos(t)),\n xycoords=\"data\",\n xytext=(-90, -50),\n textcoords=\"offset points\",\n fontsize=16,\n arrowprops={\"arrowstyle\": \"->\", \"connectionstyle\": \"arc3,rad=.2\"},\n)\n\nfor label in ax.get_xticklabels() + ax.get_yticklabels():\n label.set_fontsize(16)\n label.set_bbox({\"facecolor\": \"white\", \"edgecolor\": \"None\", \"alpha\": 0.65})\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/a82b253fb62b0bcaefba288bfc2b2d44/2_5_markov_chain.py b/_downloads/a82b253fb62b0bcaefba288bfc2b2d44/2_5_markov_chain.py new file mode 100644 index 000000000..c6656a3f5 --- /dev/null +++ b/_downloads/a82b253fb62b0bcaefba288bfc2b2d44/2_5_markov_chain.py @@ -0,0 +1,39 @@ +import numpy as np + +rng = np.random.default_rng(27446968) + +n_states = 5 +n_steps = 50 +tolerance = 1e-5 + +# Random transition matrix and state vector +P = rng.random(size=(n_states, n_states)) +p = rng.random(n_states) + +# Normalize rows in P +P /= P.sum(axis=1)[:, np.newaxis] + +# Normalize p +p /= p.sum() + +# Take steps +for k in range(n_steps): + p = P.T @ p + +p_50 = p +print(p_50) + +# Compute stationary state +w, v = np.linalg.eig(P.T) + +j_stationary = np.argmin(abs(w - 1.0)) +p_stationary = v[:, j_stationary].real +p_stationary /= p_stationary.sum() +print(p_stationary) + +# Compare +if all(abs(p_50 - p_stationary) < tolerance): + print("Tolerance satisfied in infty-norm") + +if np.linalg.norm(p_50 - p_stationary) < tolerance: + print("Tolerance satisfied in 2-norm") diff --git a/_downloads/a862480a01bf06b20aff6e9b886e99b7/plot_gradient_descent.py b/_downloads/a862480a01bf06b20aff6e9b886e99b7/plot_gradient_descent.py new file mode 100644 index 000000000..edc08683c --- /dev/null +++ b/_downloads/a862480a01bf06b20aff6e9b886e99b7/plot_gradient_descent.py @@ -0,0 +1,291 @@ +""" +Gradient descent +================== + +An example demoing gradient descent by creating figures that trace the +evolution of the optimizer. +""" + +import numpy as np +import matplotlib.pyplot as plt +import scipy as sp + +import collections +import sys +import os + +sys.path.append(os.path.abspath("helper")) +from cost_functions import ( + mk_quad, + mk_gauss, + rosenbrock, + rosenbrock_prime, + rosenbrock_hessian, + LoggingFunction, + CountingFunction, +) + +x_min, x_max = -1, 2 +y_min, y_max = 2.25 / 3 * x_min - 0.2, 2.25 / 3 * x_max - 0.2 + + +############################################################################### +# A formatter to print values on contours +def super_fmt(value): + if value > 1: + if np.abs(int(value) - value) < 0.1: + out = f"$10^{{{int(value):d}}}$" + else: + out = f"$10^{{{value:.1f}}}$" + else: + value = np.exp(value - 0.01) + if value > 0.1: + out = f"{value:1.1f}" + elif value > 0.01: + out = f"{value:.2f}" + else: + out = f"{value:.2e}" + return out + + +############################################################################### +# A gradient descent algorithm +# do not use: its a toy, use scipy's optimize.fmin_cg + + +def gradient_descent(x0, f, f_prime, hessian=None, adaptative=False): + x_i, y_i = x0 + all_x_i = [] + all_y_i = [] + all_f_i = [] + + for i in range(1, 100): + all_x_i.append(x_i) + all_y_i.append(y_i) + all_f_i.append(f([x_i, y_i])) + dx_i, dy_i = f_prime(np.asarray([x_i, y_i])) + if adaptative: + # Compute a step size using a line_search to satisfy the Wolf + # conditions + step = sp.optimize.line_search( + f, + f_prime, + np.r_[x_i, y_i], + -np.r_[dx_i, dy_i], + np.r_[dx_i, dy_i], + c2=0.05, + ) + step = step[0] + if step is None: + step = 0 + else: + step = 1 + x_i += -step * dx_i + y_i += -step * dy_i + if np.abs(all_f_i[-1]) < 1e-16: + break + return all_x_i, all_y_i, all_f_i + + +def gradient_descent_adaptative(x0, f, f_prime, hessian=None): + return gradient_descent(x0, f, f_prime, adaptative=True) + + +def conjugate_gradient(x0, f, f_prime, hessian=None): + all_x_i = [x0[0]] + all_y_i = [x0[1]] + all_f_i = [f(x0)] + + def store(X): + x, y = X + all_x_i.append(x) + all_y_i.append(y) + all_f_i.append(f(X)) + + sp.optimize.minimize( + f, x0, jac=f_prime, method="CG", callback=store, options={"gtol": 1e-12} + ) + return all_x_i, all_y_i, all_f_i + + +def newton_cg(x0, f, f_prime, hessian): + all_x_i = [x0[0]] + all_y_i = [x0[1]] + all_f_i = [f(x0)] + + def store(X): + x, y = X + all_x_i.append(x) + all_y_i.append(y) + all_f_i.append(f(X)) + + sp.optimize.minimize( + f, + x0, + method="Newton-CG", + jac=f_prime, + hess=hessian, + callback=store, + options={"xtol": 1e-12}, + ) + return all_x_i, all_y_i, all_f_i + + +def bfgs(x0, f, f_prime, hessian=None): + all_x_i = [x0[0]] + all_y_i = [x0[1]] + all_f_i = [f(x0)] + + def store(X): + x, y = X + all_x_i.append(x) + all_y_i.append(y) + all_f_i.append(f(X)) + + sp.optimize.minimize( + f, x0, method="BFGS", jac=f_prime, callback=store, options={"gtol": 1e-12} + ) + return all_x_i, all_y_i, all_f_i + + +def powell(x0, f, f_prime, hessian=None): + all_x_i = [x0[0]] + all_y_i = [x0[1]] + all_f_i = [f(x0)] + + def store(X): + x, y = X + all_x_i.append(x) + all_y_i.append(y) + all_f_i.append(f(X)) + + sp.optimize.minimize( + f, x0, method="Powell", callback=store, options={"ftol": 1e-12} + ) + return all_x_i, all_y_i, all_f_i + + +def nelder_mead(x0, f, f_prime, hessian=None): + all_x_i = [x0[0]] + all_y_i = [x0[1]] + all_f_i = [f(x0)] + + def store(X): + x, y = X + all_x_i.append(x) + all_y_i.append(y) + all_f_i.append(f(X)) + + sp.optimize.minimize( + f, x0, method="Nelder-Mead", callback=store, options={"ftol": 1e-12} + ) + return all_x_i, all_y_i, all_f_i + + +############################################################################### +# Run different optimizers on these problems +levels = {} + +for index, ((f, f_prime, hessian), optimizer) in enumerate( + ( + (mk_quad(0.7), gradient_descent), + (mk_quad(0.7), gradient_descent_adaptative), + (mk_quad(0.02), gradient_descent), + (mk_quad(0.02), gradient_descent_adaptative), + (mk_gauss(0.02), gradient_descent_adaptative), + ( + (rosenbrock, rosenbrock_prime, rosenbrock_hessian), + gradient_descent_adaptative, + ), + (mk_gauss(0.02), conjugate_gradient), + ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), conjugate_gradient), + (mk_quad(0.02), newton_cg), + (mk_gauss(0.02), newton_cg), + ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), newton_cg), + (mk_quad(0.02), bfgs), + (mk_gauss(0.02), bfgs), + ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), bfgs), + (mk_quad(0.02), powell), + (mk_gauss(0.02), powell), + ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), powell), + (mk_gauss(0.02), nelder_mead), + ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), nelder_mead), + ) +): + # Compute a gradient-descent + x_i, y_i = 1.6, 1.1 + counting_f_prime = CountingFunction(f_prime) + counting_hessian = CountingFunction(hessian) + logging_f = LoggingFunction(f, counter=counting_f_prime.counter) + all_x_i, all_y_i, all_f_i = optimizer( + np.array([x_i, y_i]), logging_f, counting_f_prime, hessian=counting_hessian + ) + + # Plot the contour plot + if not max(all_y_i) < y_max: + x_min *= 1.2 + x_max *= 1.2 + y_min *= 1.2 + y_max *= 1.2 + x, y = np.mgrid[x_min:x_max:100j, y_min:y_max:100j] + x = x.T + y = y.T + + plt.figure(index, figsize=(3, 2.5)) + plt.clf() + plt.axes([0, 0, 1, 1]) + + X = np.concatenate((x[np.newaxis, ...], y[np.newaxis, ...]), axis=0) + z = np.apply_along_axis(f, 0, X) + log_z = np.log(z + 0.01) + plt.imshow( + log_z, + extent=[x_min, x_max, y_min, y_max], + cmap=plt.cm.gray_r, + origin="lower", + vmax=log_z.min() + 1.5 * np.ptp(log_z), + ) + contours = plt.contour( + log_z, + levels=levels.get(f), + extent=[x_min, x_max, y_min, y_max], + cmap=plt.cm.gnuplot, + origin="lower", + ) + levels[f] = contours.levels + plt.clabel(contours, inline=1, fmt=super_fmt, fontsize=14) + + plt.plot(all_x_i, all_y_i, "b-", linewidth=2) + plt.plot(all_x_i, all_y_i, "k+") + + plt.plot(logging_f.all_x_i, logging_f.all_y_i, "k.", markersize=2) + + plt.plot([0], [0], "rx", markersize=12) + + plt.xticks(()) + plt.yticks(()) + plt.xlim(x_min, x_max) + plt.ylim(y_min, y_max) + plt.draw() + + plt.figure(index + 100, figsize=(4, 3)) + plt.clf() + plt.semilogy(np.maximum(np.abs(all_f_i), 1e-30), linewidth=2, label="# iterations") + plt.ylabel("Error on f(x)") + plt.semilogy( + logging_f.counts, + np.maximum(np.abs(logging_f.all_f_i), 1e-30), + linewidth=2, + color="g", + label="# function calls", + ) + plt.legend( + loc="upper right", + frameon=True, + prop={"size": 11}, + borderaxespad=0, + handlelength=1.5, + handletextpad=0.5, + ) + plt.tight_layout() + plt.draw() diff --git a/_downloads/a97e244e8249638bd45f20304532dab9/plot_block_mean.zip b/_downloads/a97e244e8249638bd45f20304532dab9/plot_block_mean.zip new file mode 100644 index 000000000..fb2f243c0 Binary files /dev/null and b/_downloads/a97e244e8249638bd45f20304532dab9/plot_block_mean.zip differ diff --git a/_downloads/a9dc152c8859c92637cfeb69a6f88e7e/plot_mathematical_morpho.zip b/_downloads/a9dc152c8859c92637cfeb69a6f88e7e/plot_mathematical_morpho.zip new file mode 100644 index 000000000..beda36bd7 Binary files /dev/null and b/_downloads/a9dc152c8859c92637cfeb69a6f88e7e/plot_mathematical_morpho.zip differ diff --git a/_downloads/aa11703fc147025439eb1f8803f95c4b/auto_examples_jupyter.zip b/_downloads/aa11703fc147025439eb1f8803f95c4b/auto_examples_jupyter.zip new file mode 100644 index 000000000..a041daa42 Binary files /dev/null and b/_downloads/aa11703fc147025439eb1f8803f95c4b/auto_examples_jupyter.zip differ diff --git a/_downloads/aaaea8e5519044332d59a559c3119e9b/plot_measure_data.ipynb b/_downloads/aaaea8e5519044332d59a559c3119e9b/plot_measure_data.ipynb new file mode 100644 index 000000000..df97a6726 --- /dev/null +++ b/_downloads/aaaea8e5519044332d59a559c3119e9b/plot_measure_data.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Measurements from images\n\nThis examples shows how to measure quantities from various images.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nrng = np.random.default_rng(27446968)\nn = 10\nl = 256\nim = np.zeros((l, l))\npoints = l * rng.random((2, n**2))\nim[(points[0]).astype(int), (points[1]).astype(int)] = 1\nim = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n))\n\nmask = im > im.mean()\n\nlabel_im, nb_labels = sp.ndimage.label(mask)\n\nsizes = sp.ndimage.sum(mask, label_im, range(nb_labels + 1))\nmask_size = sizes < 1000\nremove_pixel = mask_size[label_im]\nlabel_im[remove_pixel] = 0\nlabels = np.unique(label_im)\nlabel_clean = np.searchsorted(labels, label_im)\n\n\nplt.figure(figsize=(6, 3))\n\nplt.subplot(121)\nplt.imshow(label_im, cmap=\"nipy_spectral\")\nplt.axis(\"off\")\nplt.subplot(122)\nplt.imshow(label_clean, vmax=nb_labels, cmap=\"nipy_spectral\")\nplt.axis(\"off\")\n\nplt.subplots_adjust(wspace=0.01, hspace=0.01, top=1, bottom=0, left=0, right=1)\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/ab1c6b4de850f7ef8490b052bc77429a/plot_sprog_annual_maxima.py b/_downloads/ab1c6b4de850f7ef8490b052bc77429a/plot_sprog_annual_maxima.py new file mode 100644 index 000000000..c2f7fc1d0 --- /dev/null +++ b/_downloads/ab1c6b4de850f7ef8490b052bc77429a/plot_sprog_annual_maxima.py @@ -0,0 +1,19 @@ +""" +The Gumbell distribution, results +================================= + +Generate the exercise results on the Gumbell distribution +""" + +import numpy as np +import matplotlib.pyplot as plt + +years_nb = 21 +wspeeds = np.load("sprog-windspeeds.npy") +max_speeds = np.array([arr.max() for arr in np.array_split(wspeeds, years_nb)]) + +plt.figure() +plt.bar(np.arange(years_nb) + 1, max_speeds) +plt.axis("tight") +plt.xlabel("Year") +plt.ylabel("Annual wind speed maxima [$m/s$]") diff --git a/_downloads/ab357e1b9c3bba6536900dfd3dbec9b2/plot_exercise_flat_minimum.ipynb b/_downloads/ab357e1b9c3bba6536900dfd3dbec9b2/plot_exercise_flat_minimum.ipynb new file mode 100644 index 000000000..822242201 --- /dev/null +++ b/_downloads/ab357e1b9c3bba6536900dfd3dbec9b2/plot_exercise_flat_minimum.ipynb @@ -0,0 +1,61 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Finding a minimum in a flat neighborhood\n\nAn exercise of finding minimum. This exercise is hard because the\nfunction is very flat around the minimum (all its derivatives are zero).\nThus gradient information is unreliable.\n\nThe function admits a minimum in [0, 0]. The challenge is to get within\n1e-7 of this minimum, starting at x0 = [1, 1].\n\nThe solution that we adopt here is to give up on using gradient or\ninformation based on local differences, and to rely on the Powell\nalgorithm. With 162 function evaluations, we get to 1e-8 of the\nsolution.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\n\ndef f(x):\n return np.exp(-1 / (0.01 * x[0] ** 2 + x[1] ** 2))\n\n\n# A well-conditionned version of f:\ndef g(x):\n return f([10 * x[0], x[1]])\n\n\n# The gradient of g. We won't use it here for the optimization.\ndef g_prime(x):\n r = np.sqrt(x[0] ** 2 + x[1] ** 2)\n return 2 / r**3 * g(x) * x / r\n\n\nresult = sp.optimize.minimize(g, [1, 1], method=\"Powell\", tol=1e-10)\nx_min = result.x" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Some pretty plotting\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "plt.figure(0)\nplt.clf()\nt = np.linspace(-1.1, 1.1, 100)\nplt.plot(t, f([0, t]))\n\nplt.figure(1)\nplt.clf()\nX, Y = np.mgrid[-1.5:1.5:100j, -1.1:1.1:100j] # type: ignore[misc]\nplt.imshow(f([X, Y]).T, cmap=\"gray_r\", extent=(-1.5, 1.5, -1.1, 1.1), origin=\"lower\")\nplt.contour(X, Y, f([X, Y]), cmap=\"gnuplot\")\n\n# Plot the gradient\ndX, dY = g_prime([0.1 * X[::5, ::5], Y[::5, ::5]])\n# Adjust for our preconditioning\ndX *= 0.1\nplt.quiver(X[::5, ::5], Y[::5, ::5], dX, dY, color=\".5\")\n\n# Plot our solution\nplt.plot(x_min[0], x_min[1], \"r+\", markersize=15)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/ab994ac0ae874974d85796bf2b32da71/plot_t_test.py b/_downloads/ab994ac0ae874974d85796bf2b32da71/plot_t_test.py new file mode 100644 index 000000000..b72461326 --- /dev/null +++ b/_downloads/ab994ac0ae874974d85796bf2b32da71/plot_t_test.py @@ -0,0 +1,25 @@ +""" +========================================== +Comparing 2 sets of samples from Gaussians +========================================== + +""" + +import numpy as np +import matplotlib.pyplot as plt + +# Generates 2 sets of observations +rng = np.random.default_rng(27446968) +samples1 = rng.normal(0, size=1000) +samples2 = rng.normal(1, size=1000) + +# Compute a histogram of the sample +bins = np.linspace(-4, 4, 30) +histogram1, bins = np.histogram(samples1, bins=bins, density=True) +histogram2, bins = np.histogram(samples2, bins=bins, density=True) + +plt.figure(figsize=(6, 4)) +plt.hist(samples1, bins=bins, density=True, label="Samples 1") # type: ignore[arg-type] +plt.hist(samples2, bins=bins, density=True, label="Samples 2") # type: ignore[arg-type] +plt.legend(loc="best") +plt.show() diff --git a/_downloads/ad610c155f815ae710a7d3e95165e235/plot_good.py b/_downloads/ad610c155f815ae710a7d3e95165e235/plot_good.py new file mode 100644 index 000000000..3d4c385fd --- /dev/null +++ b/_downloads/ad610c155f815ae710a7d3e95165e235/plot_good.py @@ -0,0 +1,22 @@ +""" +A simple, good-looking plot +=========================== + +Demoing some simple features of matplotlib +""" + +import numpy as np +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt + +fig = plt.figure(figsize=(5, 4), dpi=72) +axes = fig.add_axes((0.01, 0.01, 0.98, 0.98)) +X = np.linspace(0, 2, 200) +Y = np.sin(2 * np.pi * X) +plt.plot(X, Y, lw=2) +plt.ylim(-1.1, 1.1) +plt.grid() + +plt.show() diff --git a/_downloads/ad7492b03b439743a01692e2d9ea33a9/plot_2d_minimization.ipynb b/_downloads/ad7492b03b439743a01692e2d9ea33a9/plot_2d_minimization.ipynb new file mode 100644 index 000000000..ed2e777bf --- /dev/null +++ b/_downloads/ad7492b03b439743a01692e2d9ea33a9/plot_2d_minimization.ipynb @@ -0,0 +1,97 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Optimization of a two-parameter function\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n\n\n# Define the function that we are interested in\ndef sixhump(x):\n return (\n (4 - 2.1 * x[0] ** 2 + x[0] ** 4 / 3) * x[0] ** 2\n + x[0] * x[1]\n + (-4 + 4 * x[1] ** 2) * x[1] ** 2\n )\n\n\n# Make a grid to evaluate the function (for plotting)\nxlim = [-2, 2]\nylim = [-1, 1]\nx = np.linspace(*xlim) # type: ignore[call-overload]\ny = np.linspace(*ylim) # type: ignore[call-overload]\nxg, yg = np.meshgrid(x, y)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## A 2D image plot of the function\n Simple visualization in 2D\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nplt.figure()\nplt.imshow(sixhump([xg, yg]), extent=xlim + ylim, origin=\"lower\") # type: ignore[arg-type]\nplt.colorbar()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## A 3D surface plot of the function\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure()\nax: Axes3D = fig.add_subplot(111, projection=\"3d\")\nsurf = ax.plot_surface(\n xg,\n yg,\n sixhump([xg, yg]),\n rstride=1,\n cstride=1,\n cmap=\"viridis\",\n linewidth=0,\n antialiased=False,\n)\n\nax.set_xlabel(\"x\")\nax.set_ylabel(\"y\")\nax.set_zlabel(\"f(x, y)\")\nax.set_title(\"Six-hump Camelback function\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Find minima\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import scipy as sp\n\n# local minimization\nres_local = sp.optimize.minimize(sixhump, x0=[0, 0])\n\n# global minimization\nres_global = sp.optimize.differential_evolution(sixhump, bounds=[xlim, ylim])\n\nplt.figure()\n# Show the function in 2D\nplt.imshow(sixhump([xg, yg]), extent=xlim + ylim, origin=\"lower\") # type: ignore[arg-type]\nplt.colorbar()\n# Mark the minima\nplt.scatter(res_local.x[0], res_local.x[1], label=\"local minimizer\")\nplt.scatter(res_global.x[0], res_global.x[1], label=\"global minimizer\")\nplt.legend()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/aed1d31a01198451dfb7b554476f0e54/plot_curve_fitting.zip b/_downloads/aed1d31a01198451dfb7b554476f0e54/plot_curve_fitting.zip new file mode 100644 index 000000000..d6497d757 Binary files /dev/null and b/_downloads/aed1d31a01198451dfb7b554476f0e54/plot_curve_fitting.zip differ diff --git a/_downloads/aeeb6a3a1328db54b670eedc61737811/plot_optimize_lidar_complex_data.py b/_downloads/aeeb6a3a1328db54b670eedc61737811/plot_optimize_lidar_complex_data.py new file mode 100644 index 000000000..11caf2b63 --- /dev/null +++ b/_downloads/aeeb6a3a1328db54b670eedc61737811/plot_optimize_lidar_complex_data.py @@ -0,0 +1,19 @@ +""" +The lidar system, data (2 of 2 datasets) +======================================== + +Generate a chart of more complex data recorded by the lidar system +""" + +import numpy as np +import matplotlib.pyplot as plt + +waveform_2 = np.load("waveform_2.npy") + +t = np.arange(len(waveform_2)) + +fig, ax = plt.subplots(figsize=(8, 6)) +plt.plot(t, waveform_2) +plt.xlabel("Time [ns]") +plt.ylabel("Amplitude [bins]") +plt.show() diff --git a/_downloads/b0e2d9e4c38d79297230873223237f96/plot_polar_ext.zip b/_downloads/b0e2d9e4c38d79297230873223237f96/plot_polar_ext.zip new file mode 100644 index 000000000..36b6e352b Binary files /dev/null and b/_downloads/b0e2d9e4c38d79297230873223237f96/plot_polar_ext.zip differ diff --git a/_downloads/b143f5b1d756f4936bdab75c2123d941/plot_antialiased.ipynb b/_downloads/b143f5b1d756f4936bdab75c2123d941/plot_antialiased.ipynb new file mode 100644 index 000000000..0fe7a509e --- /dev/null +++ b/_downloads/b143f5b1d756f4936bdab75c2123d941/plot_antialiased.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Aliased versus anti-aliased\n\nThe example shows aliased versus anti-aliased text.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nsize = 128, 16\ndpi = 72.0\nfigsize = size[0] / float(dpi), size[1] / float(dpi)\nfig = plt.figure(figsize=figsize, dpi=dpi)\nfig.patch.set_alpha(0)\nplt.axes((0, 0, 1, 1), frameon=False)\n\nplt.rcParams[\"text.antialiased\"] = True\nplt.text(0.5, 0.5, \"Anti-aliased\", ha=\"center\", va=\"center\")\n\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xticks([])\nplt.yticks([])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/b1fe17687c77cef6e0615d437d4a21bc/plot_optimize_example2.zip b/_downloads/b1fe17687c77cef6e0615d437d4a21bc/plot_optimize_example2.zip new file mode 100644 index 000000000..f1de4d4cd Binary files /dev/null and b/_downloads/b1fe17687c77cef6e0615d437d4a21bc/plot_optimize_example2.zip differ diff --git a/_downloads/b469ed5749ccc71bba51ed327a390651/plot_bar_ext.py b/_downloads/b469ed5749ccc71bba51ed327a390651/plot_bar_ext.py new file mode 100644 index 000000000..dc5ecba66 --- /dev/null +++ b/_downloads/b469ed5749ccc71bba51ed327a390651/plot_bar_ext.py @@ -0,0 +1,61 @@ +""" +Bar plot advanced +================== + +An more elaborate bar plot example +""" + +import numpy as np +import matplotlib.pyplot as plt + +n = 16 +X = np.arange(n) +Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n) +Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n) +plt.bar(X, Y1, facecolor="#9999ff", edgecolor="white") +plt.bar(X, -Y2, facecolor="#ff9999", edgecolor="white") +plt.xlim(-0.5, n) +plt.xticks([]) +plt.ylim(-1, 1) +plt.yticks([]) + + +# Add a title and a box around it +from matplotlib.patches import FancyBboxPatch + +ax = plt.gca() +ax.add_patch( + FancyBboxPatch( + (-0.05, 0.87), + width=0.66, + height=0.165, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) +) + +plt.text( + -0.05, + 1.02, + " Bar Plot: plt.bar(...)\n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=plt.gca().transAxes, +) + +plt.text( + -0.05, + 1.01, + "\n\n Make a bar plot with rectangles ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=plt.gca().transAxes, +) + +plt.show() diff --git a/_downloads/b475d9ef92341bcb2009225ca6070bc0/plot_solve_ivp_damped_spring_mass.ipynb b/_downloads/b475d9ef92341bcb2009225ca6070bc0/plot_solve_ivp_damped_spring_mass.ipynb new file mode 100644 index 000000000..890db7415 --- /dev/null +++ b/_downloads/b475d9ef92341bcb2009225ca6070bc0/plot_solve_ivp_damped_spring_mass.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Integrate the Damped spring-mass oscillator\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nm = 0.5 # kg\nk = 4 # N/m\nc = 0.4 # N s/m\n\nzeta = c / (2 * m * np.sqrt(k / m))\nomega = np.sqrt(k / m)\n\n\ndef f(t, z, zeta, omega):\n return (z[1], -zeta * omega * z[1] - omega**2 * z[0])\n\n\nt_span = (0, 10)\nt_eval = np.linspace(*t_span, 100)\nz0 = [1, 0]\nres = sp.integrate.solve_ivp(\n f, t_span, z0, t_eval=t_eval, args=(zeta, omega), method=\"LSODA\"\n)\n\nplt.figure(figsize=(4, 3))\nplt.plot(res.t, res.y[0], label=\"y\")\nplt.plot(res.t, res.y[1], label=\"dy/dt\")\nplt.legend(loc=\"best\")\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/b4ed86a1b28592bd634582b947c1abdd/plot_simple.zip b/_downloads/b4ed86a1b28592bd634582b947c1abdd/plot_simple.zip new file mode 100644 index 000000000..b09ea1cb2 Binary files /dev/null and b/_downloads/b4ed86a1b28592bd634582b947c1abdd/plot_simple.zip differ diff --git a/_downloads/b4ef698db8ca845e5845c4618278f29a/requirements.txt b/_downloads/b4ef698db8ca845e5845c4618278f29a/requirements.txt new file mode 100644 index 000000000..d99c3a9b9 --- /dev/null +++ b/_downloads/b4ef698db8ca845e5845c4618278f29a/requirements.txt @@ -0,0 +1,23 @@ +numpy==2.1.1 +scipy==1.14.1 +matplotlib==3.9.2 +pandas==2.2.3 +patsy==0.5.6 +pyarrow==17.0.0 +scikit-learn==1.5.2 +scikit-image==0.24.0 +sympy==1.13.3 +statsmodels==0.14.3 +seaborn==0.13.2 +pytest>=8.2 +sphinx>=8.0 +sphinx-gallery>=0.17 +sphinx-copybutton +coverage>=7.5 +Pillow +pooch +ipython +pickleshare +pre-commit==4.0 +requests +sphinxcontrib-jquery diff --git a/_downloads/b4f7dfe5dea520e69bca7a7b06d7ba42/auto_examples_jupyter.zip b/_downloads/b4f7dfe5dea520e69bca7a7b06d7ba42/auto_examples_jupyter.zip new file mode 100644 index 000000000..5a4ecef2d Binary files /dev/null and b/_downloads/b4f7dfe5dea520e69bca7a7b06d7ba42/auto_examples_jupyter.zip differ diff --git a/_downloads/b586386ca3054ffe32a0c9518b909719/plot_curve_fitting.py b/_downloads/b586386ca3054ffe32a0c9518b909719/plot_curve_fitting.py new file mode 100644 index 000000000..2495f0347 --- /dev/null +++ b/_downloads/b586386ca3054ffe32a0c9518b909719/plot_curve_fitting.py @@ -0,0 +1,35 @@ +""" +Curve fitting +============= + +A curve fitting example +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +rng = np.random.default_rng(27446968) + + +# Our test function +def f(t, omega, phi): + return np.cos(omega * t + phi) + + +# Our x and y data +x = np.linspace(0, 3, 50) +y = f(x, 1.5, 1) + 0.1 * np.random.normal(size=50) + +# Fit the model: the parameters omega and phi can be found in the +# `params` vector +params, params_cov = sp.optimize.curve_fit(f, x, y) + +# plot the data and the fitted curve +t = np.linspace(0, 3, 1000) + +plt.figure(1) +plt.clf() +plt.plot(x, y, "bx") +plt.plot(t, f(t, *params), "r-") +plt.show() diff --git a/_downloads/b647a1b82ee04abbc1e436ea52e3bf30/plot_eigenfaces.zip b/_downloads/b647a1b82ee04abbc1e436ea52e3bf30/plot_eigenfaces.zip new file mode 100644 index 000000000..aeb899520 Binary files /dev/null and b/_downloads/b647a1b82ee04abbc1e436ea52e3bf30/plot_eigenfaces.zip differ diff --git a/_downloads/b70e493cb435626a4f014b9aa902e4e6/plot_markers.ipynb b/_downloads/b70e493cb435626a4f014b9aa902e4e6/plot_markers.ipynb new file mode 100644 index 000000000..c515e7c22 --- /dev/null +++ b/_downloads/b70e493cb435626a4f014b9aa902e4e6/plot_markers.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Markers\n\nShow the different markers of matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef marker(m, i):\n X = i * 0.5 * np.ones(11)\n Y = np.arange(11)\n\n plt.plot(X, Y, lw=1, marker=m, ms=10, mfc=(0.75, 0.75, 1, 1), mec=(0, 0, 1, 1))\n plt.text(0.5 * i, 10.25, repr(m), rotation=90, fontsize=15, va=\"bottom\")\n\n\nmarkers = [\n 0,\n 1,\n 2,\n 3,\n 4,\n 5,\n 6,\n 7,\n \"o\",\n \"h\",\n \"_\",\n \"1\",\n \"2\",\n \"3\",\n \"4\",\n \"8\",\n \"p\",\n \"^\",\n \"v\",\n \"<\",\n \">\",\n \"|\",\n \"d\",\n \",\",\n \"+\",\n \"s\",\n \"*\",\n \"|\",\n \"x\",\n \"D\",\n \"H\",\n \".\",\n]\n\nn_markers = len(markers)\n\nsize = 20 * n_markers, 300\ndpi = 72.0\nfigsize = size[0] / float(dpi), size[1] / float(dpi)\nfig = plt.figure(figsize=figsize, dpi=dpi)\nplt.axes((0, 0.01, 1, 0.9), frameon=False)\n\nfor i, m in enumerate(markers):\n marker(m, i)\n\nplt.xlim(-0.2, 0.2 + 0.5 * n_markers)\nplt.xticks([])\nplt.yticks([])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/b724a541352f54a04e7cdc3fd0ba5b2f/plot_compare_classifiers.zip b/_downloads/b724a541352f54a04e7cdc3fd0ba5b2f/plot_compare_classifiers.zip new file mode 100644 index 000000000..01b42348a Binary files /dev/null and b/_downloads/b724a541352f54a04e7cdc3fd0ba5b2f/plot_compare_classifiers.zip differ diff --git a/_downloads/b8279bc8c121ddab15cef6e7b0b5af99/plot_california_prediction.py b/_downloads/b8279bc8c121ddab15cef6e7b0b5af99/plot_california_prediction.py new file mode 100644 index 000000000..dc049a11e --- /dev/null +++ b/_downloads/b8279bc8c121ddab15cef6e7b0b5af99/plot_california_prediction.py @@ -0,0 +1,83 @@ +""" +A simple regression analysis on the California housing data +=========================================================== + +Here we perform a simple regression analysis on the California housing +data, exploring two types of regressors. + +""" + +from sklearn.datasets import fetch_california_housing + +data = fetch_california_housing(as_frame=True) + +############################################################################## +# Print a histogram of the quantity to predict: price +import matplotlib.pyplot as plt + +plt.figure(figsize=(4, 3)) +plt.hist(data.target) +plt.xlabel("price ($100k)") +plt.ylabel("count") +plt.tight_layout() + +############################################################################## +# Print the join histogram for each feature + +for index, feature_name in enumerate(data.feature_names): + plt.figure(figsize=(4, 3)) + plt.scatter(data.data[feature_name], data.target) + plt.ylabel("Price", size=15) + plt.xlabel(feature_name, size=15) + plt.tight_layout() + + +############################################################################## +# Simple prediction + +from sklearn.model_selection import train_test_split + +X_train, X_test, y_train, y_test = train_test_split(data.data, data.target) + +from sklearn.linear_model import LinearRegression + +clf = LinearRegression() +clf.fit(X_train, y_train) +predicted = clf.predict(X_test) +expected = y_test + +plt.figure(figsize=(4, 3)) +plt.scatter(expected, predicted) +plt.plot([0, 8], [0, 8], "--k") +plt.axis("tight") +plt.xlabel("True price ($100k)") +plt.ylabel("Predicted price ($100k)") +plt.tight_layout() + + +############################################################################## +# Prediction with gradient boosted tree + +from sklearn.ensemble import GradientBoostingRegressor + +clf = GradientBoostingRegressor() +clf.fit(X_train, y_train) + +predicted = clf.predict(X_test) +expected = y_test + +plt.figure(figsize=(4, 3)) +plt.scatter(expected, predicted) +plt.plot([0, 5], [0, 5], "--k") +plt.axis("tight") +plt.xlabel("True price ($100k)") +plt.ylabel("Predicted price ($100k)") +plt.tight_layout() + +############################################################################## +# Print the error rate +import numpy as np + +print(f"RMS: {np.sqrt(np.mean((predicted - expected) ** 2))!r} ") + +plt.show() diff --git a/_downloads/b9460e25f7ac9be6933bc3eb831d7cb7/plot_solid_joinstyle.zip b/_downloads/b9460e25f7ac9be6933bc3eb831d7cb7/plot_solid_joinstyle.zip new file mode 100644 index 000000000..e14d6acbb Binary files /dev/null and b/_downloads/b9460e25f7ac9be6933bc3eb831d7cb7/plot_solid_joinstyle.zip differ diff --git a/_downloads/b9982f04a3b5c3fc72ca38542ef180eb/plot_boundaries.py b/_downloads/b9982f04a3b5c3fc72ca38542ef180eb/plot_boundaries.py new file mode 100644 index 000000000..7c6df30f0 --- /dev/null +++ b/_downloads/b9982f04a3b5c3fc72ca38542ef180eb/plot_boundaries.py @@ -0,0 +1,28 @@ +""" +Segmentation contours +===================== + +Visualize segmentation contours on original grayscale image. +""" + +from skimage import data, segmentation +from skimage import filters +import matplotlib.pyplot as plt +import numpy as np + +coins = data.coins() +mask = coins > filters.threshold_otsu(coins) +clean_border = segmentation.clear_border(mask).astype(int) + +coins_edges = segmentation.mark_boundaries(coins, clean_border) + +plt.figure(figsize=(8, 3.5)) +plt.subplot(121) +plt.imshow(clean_border, cmap="gray") +plt.axis("off") +plt.subplot(122) +plt.imshow(coins_edges) +plt.axis("off") + +plt.tight_layout() +plt.show() diff --git a/_downloads/b99ce800fd40461de3e3d41196cb945c/plot_plot_ext.py b/_downloads/b99ce800fd40461de3e3d41196cb945c/plot_plot_ext.py new file mode 100644 index 000000000..96febc34f --- /dev/null +++ b/_downloads/b99ce800fd40461de3e3d41196cb945c/plot_plot_ext.py @@ -0,0 +1,60 @@ +""" +Plot example vignette +======================= + +An example of plots with matplotlib, and added annotations. +""" + +import numpy as np +import matplotlib.pyplot as plt + +n = 256 +X = np.linspace(0, 2, n) +Y = np.sin(2 * np.pi * X) + +plt.plot(X, Y, lw=2, color="violet") +plt.xlim(-0.2, 2.2) +plt.xticks([]) +plt.ylim(-1.2, 1.2) +plt.yticks([]) + + +# Add a title and a box around it +from matplotlib.patches import FancyBboxPatch + +ax = plt.gca() +ax.add_patch( + FancyBboxPatch( + (-0.05, 0.87), + width=0.66, + height=0.165, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) +) + +plt.text( + -0.05, + 1.02, + " Regular Plot: plt.plot(...)\n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=plt.gca().transAxes, +) + +plt.text( + -0.05, + 1.01, + "\n\n Plot lines and/or markers ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=plt.gca().transAxes, +) + +plt.show() diff --git a/_downloads/b9bd122934bf671c4661a83f5e3deb05/plot_cumulative_wind_speed_prediction.zip b/_downloads/b9bd122934bf671c4661a83f5e3deb05/plot_cumulative_wind_speed_prediction.zip new file mode 100644 index 000000000..c8c27120d Binary files /dev/null and b/_downloads/b9bd122934bf671c4661a83f5e3deb05/plot_cumulative_wind_speed_prediction.zip differ diff --git a/_downloads/ba3f88bc12aff497f404dc8dbb311d17/plot_pie_ext.zip b/_downloads/ba3f88bc12aff497f404dc8dbb311d17/plot_pie_ext.zip new file mode 100644 index 000000000..f7957541f Binary files /dev/null and b/_downloads/ba3f88bc12aff497f404dc8dbb311d17/plot_pie_ext.zip differ diff --git a/_downloads/bb9a3d85bf86c563bd1dfc6d2b43b0b8/plot_block_mean.py b/_downloads/bb9a3d85bf86c563bd1dfc6d2b43b0b8/plot_block_mean.py new file mode 100644 index 000000000..4cc4d6ef3 --- /dev/null +++ b/_downloads/bb9a3d85bf86c563bd1dfc6d2b43b0b8/plot_block_mean.py @@ -0,0 +1,25 @@ +""" +Plot the block mean of an image +================================ + +An example showing how to use broad-casting to plot the mean of +blocks of an image. +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +f = sp.datasets.face(gray=True) +sx, sy = f.shape +X, Y = np.ogrid[0:sx, 0:sy] + +regions = sy // 6 * (X // 4) + Y // 6 +block_mean = sp.ndimage.mean(f, labels=regions, index=np.arange(1, regions.max() + 1)) +block_mean.shape = (sx // 4, sy // 6) + +plt.figure(figsize=(5, 5)) +plt.imshow(block_mean, cmap="gray") +plt.axis("off") + +plt.show() diff --git a/_downloads/bc3dc332f8d9bff152b2aafed094edd1/plot_optimize_example2.py b/_downloads/bc3dc332f8d9bff152b2aafed094edd1/plot_optimize_example2.py new file mode 100644 index 000000000..b78193e30 --- /dev/null +++ b/_downloads/bc3dc332f8d9bff152b2aafed094edd1/plot_optimize_example2.py @@ -0,0 +1,71 @@ +""" +=============================== +Minima and roots of a function +=============================== + +Demos finding minima and roots of a function. +""" + +############################################################ +# Define the function +############################################################ + +import numpy as np + +x = np.arange(-10, 10, 0.1) + + +def f(x): + return x**2 + 10 * np.sin(x) + + +############################################################ +# Find minima +############################################################ + +import scipy as sp + +# Global optimization +grid = (-10, 10, 0.1) +xmin_global = sp.optimize.brute(f, (grid,)) +print(f"Global minima found {xmin_global}") + +# Constrain optimization +xmin_local = sp.optimize.fminbound(f, 0, 10) +print(f"Local minimum found {xmin_local}") + +############################################################ +# Root finding +############################################################ + +root = sp.optimize.root(f, 1) # our initial guess is 1 +print(f"First root found {root.x}") +root2 = sp.optimize.root(f, -2.5) +print(f"Second root found {root2.x}") + +############################################################ +# Plot function, minima, and roots +############################################################ + +import matplotlib.pyplot as plt + +fig = plt.figure(figsize=(6, 4)) +ax = fig.add_subplot(111) + +# Plot the function +ax.plot(x, f(x), "b-", label="f(x)") + +# Plot the minima +xmins = np.array([xmin_global[0], xmin_local]) +ax.plot(xmins, f(xmins), "go", label="Minima") + +# Plot the roots +roots = np.array([root.x, root2.x]) +ax.plot(roots, f(roots), "kv", label="Roots") + +# Decorate the figure +ax.legend(loc="best") +ax.set_xlabel("x") +ax.set_ylabel("f(x)") +ax.axhline(0, color="gray") +plt.show() diff --git a/_downloads/bd1de370277eaf66270a2867c40ff5ca/plot_exercise_flat_minimum.py b/_downloads/bd1de370277eaf66270a2867c40ff5ca/plot_exercise_flat_minimum.py new file mode 100644 index 000000000..a8cc42199 --- /dev/null +++ b/_downloads/bd1de370277eaf66270a2867c40ff5ca/plot_exercise_flat_minimum.py @@ -0,0 +1,64 @@ +""" +Finding a minimum in a flat neighborhood +========================================= + +An exercise of finding minimum. This exercise is hard because the +function is very flat around the minimum (all its derivatives are zero). +Thus gradient information is unreliable. + +The function admits a minimum in [0, 0]. The challenge is to get within +1e-7 of this minimum, starting at x0 = [1, 1]. + +The solution that we adopt here is to give up on using gradient or +information based on local differences, and to rely on the Powell +algorithm. With 162 function evaluations, we get to 1e-8 of the +solution. +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + + +def f(x): + return np.exp(-1 / (0.01 * x[0] ** 2 + x[1] ** 2)) + + +# A well-conditionned version of f: +def g(x): + return f([10 * x[0], x[1]]) + + +# The gradient of g. We won't use it here for the optimization. +def g_prime(x): + r = np.sqrt(x[0] ** 2 + x[1] ** 2) + return 2 / r**3 * g(x) * x / r + + +result = sp.optimize.minimize(g, [1, 1], method="Powell", tol=1e-10) +x_min = result.x + +############################################################################### +# Some pretty plotting + +plt.figure(0) +plt.clf() +t = np.linspace(-1.1, 1.1, 100) +plt.plot(t, f([0, t])) + +plt.figure(1) +plt.clf() +X, Y = np.mgrid[-1.5:1.5:100j, -1.1:1.1:100j] # type: ignore[misc] +plt.imshow(f([X, Y]).T, cmap="gray_r", extent=(-1.5, 1.5, -1.1, 1.1), origin="lower") +plt.contour(X, Y, f([X, Y]), cmap="gnuplot") + +# Plot the gradient +dX, dY = g_prime([0.1 * X[::5, ::5], Y[::5, ::5]]) +# Adjust for our preconditioning +dX *= 0.1 +plt.quiver(X[::5, ::5], Y[::5, ::5], dX, dY, color=".5") + +# Plot our solution +plt.plot(x_min[0], x_min[1], "r+", markersize=15) + +plt.show() diff --git a/_downloads/bd293c2bb0b5380ef69f521523b3b50e/plot_multiplot_ext.zip b/_downloads/bd293c2bb0b5380ef69f521523b3b50e/plot_multiplot_ext.zip new file mode 100644 index 000000000..ece60a789 Binary files /dev/null and b/_downloads/bd293c2bb0b5380ef69f521523b3b50e/plot_multiplot_ext.zip differ diff --git a/_downloads/bdebdac0158aa0aba3528a33b9086eef/plot_curve_fit.py b/_downloads/bdebdac0158aa0aba3528a33b9086eef/plot_curve_fit.py new file mode 100644 index 000000000..88fe899b8 --- /dev/null +++ b/_downloads/bdebdac0158aa0aba3528a33b9086eef/plot_curve_fit.py @@ -0,0 +1,51 @@ +""" +=============== +Curve fitting +=============== + +Demos a simple curve fitting +""" + +############################################################ +# First generate some data +import numpy as np + +# Seed the random number generator for reproducibility +rng = np.random.default_rng(27446968) + +x_data = np.linspace(-5, 5, num=50) +noise = 0.01 * np.cos(100 * x_data) +a, b = 2.9, 1.5 +y_data = a * np.cos(b * x_data) + noise + +# And plot it +import matplotlib.pyplot as plt + +plt.figure(figsize=(6, 4)) +plt.scatter(x_data, y_data) + +############################################################ +# Now fit a simple sine function to the data +import scipy as sp + + +def test_func(x, a, b, c): + return a * np.sin(b * x + c) + + +params, params_covariance = sp.optimize.curve_fit( + test_func, x_data, y_data, p0=[2, 1, 3] +) + +print(params) + +############################################################ +# And plot the resulting curve on the data + +plt.figure(figsize=(6, 4)) +plt.scatter(x_data, y_data, label="Data") +plt.plot(x_data, test_func(x_data, *params), label="Fitted function") + +plt.legend(loc="best") + +plt.show() diff --git a/_downloads/be301ce8229a46c9f901d9021b108e9b/plot_threshold.zip b/_downloads/be301ce8229a46c9f901d9021b108e9b/plot_threshold.zip new file mode 100644 index 000000000..dcf82b8a6 Binary files /dev/null and b/_downloads/be301ce8229a46c9f901d9021b108e9b/plot_threshold.zip differ diff --git a/_downloads/be946a2388d53c54c1fefabc827802a7/plot_imshow_ext.ipynb b/_downloads/be946a2388d53c54c1fefabc827802a7/plot_imshow_ext.ipynb new file mode 100644 index 000000000..af82546cd --- /dev/null +++ b/_downloads/be946a2388d53c54c1fefabc827802a7/plot_imshow_ext.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Imshow demo\n\nDemoing imshow\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef f(x, y):\n return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2)\n\n\nn = 10\nx = np.linspace(-3, 3, 8 * n)\ny = np.linspace(-3, 3, 6 * n)\nX, Y = np.meshgrid(x, y)\nZ = f(X, Y)\nplt.imshow(Z, interpolation=\"nearest\", cmap=\"bone\", origin=\"lower\")\nplt.xticks([])\nplt.yticks([])\n\n\n# Add a title and a box around it\nfrom matplotlib.patches import FancyBboxPatch\n\nax = plt.gca()\nax.add_patch(\n FancyBboxPatch(\n (-0.05, 0.87),\n width=0.66,\n height=0.165,\n clip_on=False,\n boxstyle=\"square,pad=0\",\n zorder=3,\n facecolor=\"white\",\n alpha=1.0,\n transform=plt.gca().transAxes,\n )\n)\n\nplt.text(\n -0.05,\n 1.02,\n \" Imshow: plt.imshow(...)\\n\",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"xx-large\",\n transform=plt.gca().transAxes,\n)\n\nplt.text(\n -0.05,\n 1.01,\n \"\\n\\n Display an image to current axes \",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n family=\"DejaVu Sans\",\n size=\"large\",\n transform=plt.gca().transAxes,\n)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/be980e6a7a1acf6dd47f50d1d5b7c3e6/plot_basic2dplot.ipynb b/_downloads/be980e6a7a1acf6dd47f50d1d5b7c3e6/plot_basic2dplot.ipynb new file mode 100644 index 000000000..a8bc5bb78 --- /dev/null +++ b/_downloads/be980e6a7a1acf6dd47f50d1d5b7c3e6/plot_basic2dplot.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# 2D plotting\n\nPlot a basic 2D figure\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nrng = np.random.default_rng()\nimage = rng.random((30, 30))\nplt.imshow(image, cmap=\"hot\")\nplt.colorbar()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/becde0c834acc783076c4edf69a13460/plot_regression_3d.zip b/_downloads/becde0c834acc783076c4edf69a13460/plot_regression_3d.zip new file mode 100644 index 000000000..e675a73db Binary files /dev/null and b/_downloads/becde0c834acc783076c4edf69a13460/plot_regression_3d.zip differ diff --git a/_downloads/bf19416421472ce89f383cd8462ced6c/plot_grid.ipynb b/_downloads/bf19416421472ce89f383cd8462ced6c/plot_grid.ipynb new file mode 100644 index 000000000..d072521d7 --- /dev/null +++ b/_downloads/bf19416421472ce89f383cd8462ced6c/plot_grid.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Grid\n\nDisplaying a grid on the axes in matploblib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\nfrom matplotlib import ticker\n\nax = plt.axes((0.025, 0.025, 0.95, 0.95))\n\nax.set_xlim(0, 4)\nax.set_ylim(0, 3)\nax.xaxis.set_major_locator(ticker.MultipleLocator(1.0))\nax.xaxis.set_minor_locator(ticker.MultipleLocator(0.1))\nax.yaxis.set_major_locator(ticker.MultipleLocator(1.0))\nax.yaxis.set_minor_locator(ticker.MultipleLocator(0.1))\nax.grid(which=\"major\", axis=\"x\", linewidth=0.75, linestyle=\"-\", color=\"0.75\")\nax.grid(which=\"minor\", axis=\"x\", linewidth=0.25, linestyle=\"-\", color=\"0.75\")\nax.grid(which=\"major\", axis=\"y\", linewidth=0.75, linestyle=\"-\", color=\"0.75\")\nax.grid(which=\"minor\", axis=\"y\", linewidth=0.25, linestyle=\"-\", color=\"0.75\")\nax.set_xticklabels([])\nax.set_yticklabels([])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/c05d5adda7c587d25c84594ddf51a3dc/plot_detrend.zip b/_downloads/c05d5adda7c587d25c84594ddf51a3dc/plot_detrend.zip new file mode 100644 index 000000000..754872ee7 Binary files /dev/null and b/_downloads/c05d5adda7c587d25c84594ddf51a3dc/plot_detrend.zip differ diff --git a/_downloads/c1229bced9384289ec009fa773970c7c/plot_polar.ipynb b/_downloads/c1229bced9384289ec009fa773970c7c/plot_polar.ipynb new file mode 100644 index 000000000..3038544a8 --- /dev/null +++ b/_downloads/c1229bced9384289ec009fa773970c7c/plot_polar.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plotting in polar coordinates\n\nA simple example showing how to plot in polar coordinates with\nmatplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n\njet = matplotlib.colormaps[\"jet\"]\n\nax = plt.axes((0.025, 0.025, 0.95, 0.95), polar=True)\n\nN = 20\ntheta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N)\nrng = np.random.default_rng()\nradii = 10 * rng.random(N)\nwidth = np.pi / 4 * rng.random(N)\nbars = plt.bar(theta, radii, width=width, bottom=0.0)\n\nfor r, bar in zip(radii, bars, strict=True):\n bar.set_facecolor(jet(r / 10.0))\n bar.set_alpha(0.5)\n\nax.set_xticklabels([])\nax.set_yticklabels([])\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/c157e4de30509b9b3f7431287d8625e3/plot_gumbell_wind_speed_prediction.ipynb b/_downloads/c157e4de30509b9b3f7431287d8625e3/plot_gumbell_wind_speed_prediction.ipynb new file mode 100644 index 000000000..0b18cc6d4 --- /dev/null +++ b/_downloads/c157e4de30509b9b3f7431287d8625e3/plot_gumbell_wind_speed_prediction.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# The Gumbell distribution\n\nGenerate the exercise results on the Gumbell distribution\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\n\ndef gumbell_dist(arr):\n return -np.log(-np.log(arr))\n\n\nyears_nb = 21\nwspeeds = np.load(\"sprog-windspeeds.npy\")\nmax_speeds = np.array([arr.max() for arr in np.array_split(wspeeds, years_nb)])\nsorted_max_speeds = np.sort(max_speeds)\n\ncprob = (np.arange(years_nb, dtype=np.float32) + 1) / (years_nb + 1)\ngprob = gumbell_dist(cprob)\nspeed_spline = sp.interpolate.UnivariateSpline(gprob, sorted_max_speeds, k=1)\nnprob = gumbell_dist(np.linspace(1e-3, 1 - 1e-3, 100))\nfitted_max_speeds = speed_spline(nprob)\n\nfifty_prob = gumbell_dist(49.0 / 50.0)\nfifty_wind = speed_spline(fifty_prob)\n\nplt.figure()\nplt.plot(sorted_max_speeds, gprob, \"o\")\nplt.plot(fitted_max_speeds, nprob, \"g--\")\nplt.plot([fifty_wind], [fifty_prob], \"o\", ms=8.0, mfc=\"y\", mec=\"y\")\nplt.plot([fifty_wind, fifty_wind], [plt.axis()[2], fifty_prob], \"k--\")\nplt.text(35, -1, rf\"$V_{{50}} = {fifty_wind:.2f} \\, m/s$\")\nplt.xlabel(\"Annual wind speed maxima [$m/s$]\")\nplt.ylabel(\"Gumbell cumulative probability\")\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/c1b0930df30a2b09b6e986076164b51b/plot_exercise_8.py b/_downloads/c1b0930df30a2b09b6e986076164b51b/plot_exercise_8.py new file mode 100644 index 000000000..aaf15103a --- /dev/null +++ b/_downloads/c1b0930df30a2b09b6e986076164b51b/plot_exercise_8.py @@ -0,0 +1,40 @@ +""" +Exercise 8 +========== + +Exercise 8 with matplotlib. +""" + +import numpy as np +import matplotlib.pyplot as plt + +plt.figure(figsize=(8, 5), dpi=80) +plt.subplot(111) + +X = np.linspace(-np.pi, np.pi, 256, endpoint=True) +C = np.cos(X) +S = np.sin(X) + +plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine") +plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine") + +ax = plt.gca() +ax.spines["right"].set_color("none") +ax.spines["top"].set_color("none") +ax.xaxis.set_ticks_position("bottom") +ax.spines["bottom"].set_position(("data", 0)) +ax.yaxis.set_ticks_position("left") +ax.spines["left"].set_position(("data", 0)) + +plt.xlim(X.min() * 1.1, X.max() * 1.1) +plt.xticks( + [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], + [r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"], +) + +plt.ylim(C.min() * 1.1, C.max() * 1.1) +plt.yticks([-1, +1], [r"$-1$", r"$+1$"]) + +plt.legend(loc="upper left") + +plt.show() diff --git a/_downloads/c1c59f72dcb1ae4d36a5bf0271952e33/plot_basic1dplot.ipynb b/_downloads/c1c59f72dcb1ae4d36a5bf0271952e33/plot_basic1dplot.ipynb new file mode 100644 index 000000000..962c43241 --- /dev/null +++ b/_downloads/c1c59f72dcb1ae4d36a5bf0271952e33/plot_basic1dplot.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# 1D plotting\n\nPlot a basic 1D figure\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.linspace(0, 3, 20)\ny = np.linspace(0, 9, 20)\nplt.plot(x, y)\nplt.plot(x, y, \"o\")\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/c232e43c6d2d47cf551a1a4e75810e62/plot_color.zip b/_downloads/c232e43c6d2d47cf551a1a4e75810e62/plot_color.zip new file mode 100644 index 000000000..90e842202 Binary files /dev/null and b/_downloads/c232e43c6d2d47cf551a1a4e75810e62/plot_color.zip differ diff --git a/_downloads/c2c883f96cfab4c67c430b0caa3e7e82/wiener_filtering.py b/_downloads/c2c883f96cfab4c67c430b0caa3e7e82/wiener_filtering.py new file mode 100644 index 000000000..ae7f247bb --- /dev/null +++ b/_downloads/c2c883f96cfab4c67c430b0caa3e7e82/wiener_filtering.py @@ -0,0 +1,55 @@ +"""Wiener filtering a noisy raccoon face: this module is buggy""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + + +def local_mean(img, size=3): + """Compute a image of the local average""" + structure_element = np.ones((size, size), dtype=img.dtype) + l_mean = sp.signal.correlate(img, structure_element, mode="same") + return np.int64(l_mean / size**2) + + +def local_var(img, size=3): + """Compute a image of the local variance""" + structure_element = np.ones((size, size), dtype=img.dtype) + l_var = sp.signal.correlate(img**2, structure_element, mode="same") + l_var = np.int64(l_var / size**2) + l_var -= local_mean(img, size=size) ** 2 + return l_var + + +def iterated_wiener(noisy_img, size=3): + """Wiener filter with iterative computation of the noise variance. + + Do not use this: this is crappy code to demo bugs! + """ + noisy_img = noisy_img + denoised_img = local_mean(noisy_img, size=size) + l_var = local_var(noisy_img, size=size) + for i in range(3): + res = noisy_img - denoised_img + noise = (res**2).sum() / res.size + noise_level = 1 - noise / l_var + noise_level[noise_level < 0] = 0 + denoised_img = np.int64(noise_level * res) + return denoised_img + + +################################################################################ +cut = (slice(128, -128), slice(128, -128)) + +rng = np.random.default_rng(27446968) + +face = sp.datasets.face(gray=True) +noisy_face = face + 20 * rng.integers(3, size=face.shape) - 30 + +plt.matshow(face[cut], cmap="gray") +plt.matshow(noisy_face[cut], cmap="gray") + +denoised_face = iterated_wiener(noisy_face) +plt.matshow(denoised_face[cut], cmap="gray") + +plt.show() diff --git a/_downloads/c2f32906445807fe8f9622200620ecb7/plot_eigenfaces.py b/_downloads/c2f32906445807fe8f9622200620ecb7/plot_eigenfaces.py new file mode 100644 index 000000000..04d224740 --- /dev/null +++ b/_downloads/c2f32906445807fe8f9622200620ecb7/plot_eigenfaces.py @@ -0,0 +1,196 @@ +""" +The eigenfaces example: chaining PCA and SVMs +============================================= + +The goal of this example is to show how an unsupervised method and a +supervised one can be chained for better prediction. It starts with a +didactic but lengthy way of doing things, and finishes with the +idiomatic approach to pipelining in scikit-learn. + +Here we'll take a look at a simple facial recognition example. Ideally, +we would use a dataset consisting of a subset of the `Labeled Faces in +the Wild `__ data that is available +with :func:`sklearn.datasets.fetch_lfw_people`. However, this is a +relatively large download (~200MB) so we will do the tutorial on a +simpler, less rich dataset. Feel free to explore the LFW dataset. +""" + +from sklearn import datasets + +faces = datasets.fetch_olivetti_faces() +faces.data.shape + +############################################################ +# Let's visualize these faces to see what we're working with + +import matplotlib.pyplot as plt + +fig = plt.figure(figsize=(8, 6)) +# plot several images +for i in range(15): + ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[]) + ax.imshow(faces.images[i], cmap="bone") + +############################################################ +# .. tip:: +# +# Note is that these faces have already been localized and scaled to a +# common size. This is an important preprocessing piece for facial +# recognition, and is a process that can require a large collection of +# training data. This can be done in scikit-learn, but the challenge is +# gathering a sufficient amount of training data for the algorithm to work. +# Fortunately, this piece is common enough that it has been done. One good +# resource is +# `OpenCV `__, +# the *Open Computer Vision Library*. +# +# We'll perform a Support Vector classification of the images. We'll do a +# typical train-test split on the images: + +from sklearn.model_selection import train_test_split + +X_train, X_test, y_train, y_test = train_test_split( + faces.data, faces.target, random_state=0 +) + +print(X_train.shape, X_test.shape) + +############################################################ +# Preprocessing: Principal Component Analysis +# ------------------------------------------- +# +# 1850 dimensions is a lot for SVM. We can use PCA to reduce these 1850 +# features to a manageable size, while maintaining most of the information +# in the dataset. + +from sklearn import decomposition + +pca = decomposition.PCA(n_components=150, whiten=True) +pca.fit(X_train) + +############################################################ +# One interesting part of PCA is that it computes the "mean" face, which +# can be interesting to examine: + +plt.imshow(pca.mean_.reshape(faces.images[0].shape), cmap="bone") + +############################################################ +# The principal components measure deviations about this mean along +# orthogonal axes. + +print(pca.components_.shape) + +############################################################ +# It is also interesting to visualize these principal components: + +fig = plt.figure(figsize=(16, 6)) +for i in range(30): + ax = fig.add_subplot(3, 10, i + 1, xticks=[], yticks=[]) + ax.imshow(pca.components_[i].reshape(faces.images[0].shape), cmap="bone") + +############################################################ +# The components ("eigenfaces") are ordered by their importance from +# top-left to bottom-right. We see that the first few components seem to +# primarily take care of lighting conditions; the remaining components +# pull out certain identifying features: the nose, eyes, eyebrows, etc. +# +# With this projection computed, we can now project our original training +# and test data onto the PCA basis: + +X_train_pca = pca.transform(X_train) +X_test_pca = pca.transform(X_test) +print(X_train_pca.shape) +############################################################ +print(X_test_pca.shape) + +############################################################ +# These projected components correspond to factors in a linear combination +# of component images such that the combination approaches the original +# face. +# +# Doing the Learning: Support Vector Machines +# ------------------------------------------- +# +# Now we'll perform support-vector-machine classification on this reduced +# dataset: + +from sklearn import svm + +clf = svm.SVC(C=5.0, gamma=0.001) +clf.fit(X_train_pca, y_train) + +############################################################ +# Finally, we can evaluate how well this classification did. First, we +# might plot a few of the test-cases with the labels learned from the +# training set: + +import numpy as np + +fig = plt.figure(figsize=(8, 6)) +for i in range(15): + ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[]) + ax.imshow(X_test[i].reshape(faces.images[0].shape), cmap="bone") + y_pred = clf.predict(X_test_pca[i, np.newaxis])[0] + color = "black" if y_pred == y_test[i] else "red" + ax.set_title(y_pred, fontsize="small", color=color) + +############################################################ +# The classifier is correct on an impressive number of images given the +# simplicity of its learning model! Using a linear classifier on 150 +# features derived from the pixel-level data, the algorithm correctly +# identifies a large number of the people in the images. +# +# Again, we can quantify this effectiveness using one of several measures +# from :mod:`sklearn.metrics`. First we can do the classification +# report, which shows the precision, recall and other measures of the +# "goodness" of the classification: + +from sklearn import metrics + +y_pred = clf.predict(X_test_pca) +print(metrics.classification_report(y_test, y_pred)) + +############################################################ +# Another interesting metric is the *confusion matrix*, which indicates +# how often any two items are mixed-up. The confusion matrix of a perfect +# classifier would only have nonzero entries on the diagonal, with zeros +# on the off-diagonal: + +print(metrics.confusion_matrix(y_test, y_pred)) + +############################################################ +# Pipelining +# ---------- +# +# Above we used PCA as a pre-processing step before applying our support +# vector machine classifier. Plugging the output of one estimator directly +# into the input of a second estimator is a commonly used pattern; for +# this reason scikit-learn provides a ``Pipeline`` object which automates +# this process. The above problem can be re-expressed as a pipeline as +# follows: + +from sklearn.pipeline import Pipeline + +clf = Pipeline( + [ + ("pca", decomposition.PCA(n_components=150, whiten=True)), + ("svm", svm.LinearSVC(C=1.0)), + ] +) + +clf.fit(X_train, y_train) + +y_pred = clf.predict(X_test) +print(metrics.confusion_matrix(y_pred, y_test)) +plt.show() + +############################################################ +# A Note on Facial Recognition +# ---------------------------- +# +# Here we have used PCA "eigenfaces" as a pre-processing step for facial +# recognition. The reason we chose this is because PCA is a +# broadly-applicable technique, which can be useful for a wide array of +# data types. Research in the field of facial recognition in particular, +# however, has shown that other more specific feature extraction methods +# are can be much more effective. diff --git a/_downloads/c2fc91e8b4d544f494bcbbb337f395e8/plot_2d_minimization.py b/_downloads/c2fc91e8b4d544f494bcbbb337f395e8/plot_2d_minimization.py new file mode 100644 index 000000000..9fa0b009e --- /dev/null +++ b/_downloads/c2fc91e8b4d544f494bcbbb337f395e8/plot_2d_minimization.py @@ -0,0 +1,79 @@ +""" +========================================= +Optimization of a two-parameter function +========================================= + +""" + +import numpy as np + + +# Define the function that we are interested in +def sixhump(x): + return ( + (4 - 2.1 * x[0] ** 2 + x[0] ** 4 / 3) * x[0] ** 2 + + x[0] * x[1] + + (-4 + 4 * x[1] ** 2) * x[1] ** 2 + ) + + +# Make a grid to evaluate the function (for plotting) +xlim = [-2, 2] +ylim = [-1, 1] +x = np.linspace(*xlim) # type: ignore[call-overload] +y = np.linspace(*ylim) # type: ignore[call-overload] +xg, yg = np.meshgrid(x, y) + +############################################################ +# A 2D image plot of the function +############################################################ +# Simple visualization in 2D +import matplotlib.pyplot as plt + +plt.figure() +plt.imshow(sixhump([xg, yg]), extent=xlim + ylim, origin="lower") # type: ignore[arg-type] +plt.colorbar() + +############################################################ +# A 3D surface plot of the function +############################################################ +from mpl_toolkits.mplot3d import Axes3D + +fig = plt.figure() +ax: Axes3D = fig.add_subplot(111, projection="3d") +surf = ax.plot_surface( + xg, + yg, + sixhump([xg, yg]), + rstride=1, + cstride=1, + cmap="viridis", + linewidth=0, + antialiased=False, +) + +ax.set_xlabel("x") +ax.set_ylabel("y") +ax.set_zlabel("f(x, y)") +ax.set_title("Six-hump Camelback function") + +############################################################ +# Find minima +############################################################ +import scipy as sp + +# local minimization +res_local = sp.optimize.minimize(sixhump, x0=[0, 0]) + +# global minimization +res_global = sp.optimize.differential_evolution(sixhump, bounds=[xlim, ylim]) + +plt.figure() +# Show the function in 2D +plt.imshow(sixhump([xg, yg]), extent=xlim + ylim, origin="lower") # type: ignore[arg-type] +plt.colorbar() +# Mark the minima +plt.scatter(res_local.x[0], res_local.x[1], label="local minimizer") +plt.scatter(res_global.x[0], res_global.x[1], label="global minimizer") +plt.legend() +plt.show() diff --git a/_downloads/c3214327415847f91f1518feb21bdba4/plot_wage_education_gender.ipynb b/_downloads/c3214327415847f91f1518feb21bdba4/plot_wage_education_gender.ipynb new file mode 100644 index 000000000..41e0dd3de --- /dev/null +++ b/_downloads/c3214327415847f91f1518feb21bdba4/plot_wage_education_gender.ipynb @@ -0,0 +1,122 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Test for an education/gender interaction in wages\n\nWages depend mostly on education. Here we investigate how this dependence\nis related to gender: not only does gender create an offset in wages, it\nalso seems that wages increase more with education for males than\nfemales.\n\nDoes our data support this last hypothesis? We will test this using\nstatsmodels' formulas\n(http://statsmodels.sourceforge.net/stable/example_formulas.html).\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Load and massage the data\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import pandas\n\nimport urllib.request\nimport os\n\nif not os.path.exists(\"wages.txt\"):\n # Download the file if it is not present\n url = \"http://lib.stat.cmu.edu/datasets/CPS_85_Wages\"\n with urllib.request.urlopen(url) as r, open(\"wages.txt\", \"wb\") as f:\n f.write(r.read())\n\n# EDUCATION: Number of years of education\n# SEX: 1=Female, 0=Male\n# WAGE: Wage (dollars per hour)\ndata = pandas.read_csv(\n \"wages.txt\",\n skiprows=27,\n skipfooter=6,\n sep=None,\n header=None,\n names=[\"education\", \"gender\", \"wage\"],\n usecols=[0, 2, 5],\n)\n\n# Convert genders to strings (this is particularly useful so that the\n# statsmodels formulas detects that gender is a categorical variable)\nimport numpy as np\n\ndata[\"gender\"] = np.choose(data.gender, [\"male\", \"female\"])\n\n# Log-transform the wages, because they typically are increased with\n# multiplicative factors\ndata[\"wage\"] = np.log10(data[\"wage\"])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "simple plotting\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import seaborn\n\n# Plot 2 linear fits for male and female.\nseaborn.lmplot(y=\"wage\", x=\"education\", hue=\"gender\", data=data)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "statistical analysis\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import statsmodels.formula.api as sm\n\n# Note that this model is not the plot displayed above: it is one\n# joined model for male and female, not separate models for male and\n# female. The reason is that a single model enables statistical testing\nresult = sm.ols(formula=\"wage ~ education + gender\", data=data).fit()\nprint(result.summary())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The plots above highlight that there is not only a different offset in\nwage but also a different slope\n\nWe need to model this using an interaction\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "result = sm.ols(\n formula=\"wage ~ education + gender + education * gender\", data=data\n).fit()\nprint(result.summary())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Looking at the p-value of the interaction of gender and education, the\ndata does not support the hypothesis that education benefits males\nmore than female (p-value > 0.05).\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/c33eeb5b1dd0cf4b3817f7160cb1e16d/plot_sharpen.ipynb b/_downloads/c33eeb5b1dd0cf4b3817f7160cb1e16d/plot_sharpen.ipynb new file mode 100644 index 000000000..e977bf763 --- /dev/null +++ b/_downloads/c33eeb5b1dd0cf4b3817f7160cb1e16d/plot_sharpen.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Image sharpening\n\nThis example shows how to sharpen an image in noiseless situation by\napplying the filter inverse to the blur.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import scipy as sp\nimport matplotlib.pyplot as plt\n\nf = sp.datasets.face(gray=True).astype(float)\nblurred_f = sp.ndimage.gaussian_filter(f, 3)\n\nfilter_blurred_f = sp.ndimage.gaussian_filter(blurred_f, 1)\n\nalpha = 30\nsharpened = blurred_f + alpha * (blurred_f - filter_blurred_f)\n\nplt.figure(figsize=(12, 4))\n\nplt.subplot(131)\nplt.imshow(f, cmap=\"gray\")\nplt.axis(\"off\")\nplt.subplot(132)\nplt.imshow(blurred_f, cmap=\"gray\")\nplt.axis(\"off\")\nplt.subplot(133)\nplt.imshow(sharpened, cmap=\"gray\")\nplt.axis(\"off\")\n\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/c3cdb551bd416e1ea5c2a0f52e934ce8/plot_exercise_flat_minimum.zip b/_downloads/c3cdb551bd416e1ea5c2a0f52e934ce8/plot_exercise_flat_minimum.zip new file mode 100644 index 000000000..523c34e13 Binary files /dev/null and b/_downloads/c3cdb551bd416e1ea5c2a0f52e934ce8/plot_exercise_flat_minimum.zip differ diff --git a/_downloads/c42cea3773633a6c5d61d0f2e388a415/plot_grid_ext.py b/_downloads/c42cea3773633a6c5d61d0f2e388a415/plot_grid_ext.py new file mode 100644 index 000000000..5242c164e --- /dev/null +++ b/_downloads/c42cea3773633a6c5d61d0f2e388a415/plot_grid_ext.py @@ -0,0 +1,64 @@ +""" +Grid elaborate +=============== + +An example displaying a grid on the axes and tweaking the layout. +""" + +import matplotlib.pyplot as plt +from matplotlib.ticker import MultipleLocator + +fig = plt.figure(figsize=(8, 6), dpi=72, facecolor="white") +axes = plt.subplot(111) +axes.set_xlim(0, 4) +axes.set_ylim(0, 3) + +axes.xaxis.set_major_locator(MultipleLocator(1.0)) +axes.xaxis.set_minor_locator(MultipleLocator(0.1)) +axes.yaxis.set_major_locator(MultipleLocator(1.0)) +axes.yaxis.set_minor_locator(MultipleLocator(0.1)) +axes.grid(which="major", axis="x", linewidth=0.75, linestyle="-", color="0.75") +axes.grid(which="minor", axis="x", linewidth=0.25, linestyle="-", color="0.75") +axes.grid(which="major", axis="y", linewidth=0.75, linestyle="-", color="0.75") +axes.grid(which="minor", axis="y", linewidth=0.25, linestyle="-", color="0.75") +axes.set_xticklabels([]) +axes.set_yticklabels([]) + + +# Add a title and a box around it +from matplotlib.patches import FancyBboxPatch + +ax = plt.gca() +ax.add_patch( + FancyBboxPatch( + (-0.05, 0.87), + width=0.66, + height=0.165, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) +) + +plt.text( + -0.05, + 1.02, + " Grid: plt.grid(...)\n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=axes.transAxes, +) + +plt.text( + -0.05, + 1.01, + "\n\n Draw ticks and grid ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=axes.transAxes, +) diff --git a/_downloads/c42da6043134c10a1477255ab2daf2eb/plot_camera.ipynb b/_downloads/c42da6043134c10a1477255ab2daf2eb/plot_camera.ipynb new file mode 100644 index 000000000..b4a3dbdd8 --- /dev/null +++ b/_downloads/c42da6043134c10a1477255ab2daf2eb/plot_camera.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Displaying a simple image\n\nLoad and display an image\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\nfrom skimage import data\n\ncamera = data.camera()\n\n\nplt.figure(figsize=(4, 4))\nplt.imshow(camera, cmap=\"gray\", interpolation=\"nearest\")\nplt.axis(\"off\")\n\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/c445ec1d296a5fa731228e6c4174e769/plot_greyscale_dilation.ipynb b/_downloads/c445ec1d296a5fa731228e6c4174e769/plot_greyscale_dilation.ipynb new file mode 100644 index 000000000..c6fdedca4 --- /dev/null +++ b/_downloads/c445ec1d296a5fa731228e6c4174e769/plot_greyscale_dilation.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Greyscale dilation\n\nThis example illustrates greyscale mathematical morphology.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nim = np.zeros((64, 64))\nrng = np.random.default_rng(27446968)\nx, y = (63 * rng.random((2, 8))).astype(int)\nim[x, y] = np.arange(8)\n\nbigger_points = sp.ndimage.grey_dilation(im, size=(5, 5), structure=np.ones((5, 5)))\n\nsquare = np.zeros((16, 16))\nsquare[4:-4, 4:-4] = 1\ndist = sp.ndimage.distance_transform_bf(square)\ndilate_dist = sp.ndimage.grey_dilation(dist, size=(3, 3), structure=np.ones((3, 3)))\n\nplt.figure(figsize=(12.5, 3))\nplt.subplot(141)\nplt.imshow(im, interpolation=\"nearest\", cmap=\"nipy_spectral\")\nplt.axis(\"off\")\nplt.subplot(142)\nplt.imshow(bigger_points, interpolation=\"nearest\", cmap=\"nipy_spectral\")\nplt.axis(\"off\")\nplt.subplot(143)\nplt.imshow(dist, interpolation=\"nearest\", cmap=\"nipy_spectral\")\nplt.axis(\"off\")\nplt.subplot(144)\nplt.imshow(dilate_dist, interpolation=\"nearest\", cmap=\"nipy_spectral\")\nplt.axis(\"off\")\n\nplt.subplots_adjust(wspace=0, hspace=0.02, top=0.99, bottom=0.01, left=0.01, right=0.99)\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/c48c856d7b4352e3e562792088175e0d/plot_camera_uint.py b/_downloads/c48c856d7b4352e3e562792088175e0d/plot_camera_uint.py new file mode 100644 index 000000000..bb9253e41 --- /dev/null +++ b/_downloads/c48c856d7b4352e3e562792088175e0d/plot_camera_uint.py @@ -0,0 +1,23 @@ +""" +Integers can overflow +====================== + +An illustration of overflow problem arising when working with integers +""" + +import matplotlib.pyplot as plt +from skimage import data + +camera = data.camera() +camera_multiply = 3 * camera + +plt.figure(figsize=(8, 4)) +plt.subplot(121) +plt.imshow(camera, cmap="gray", interpolation="nearest") +plt.axis("off") +plt.subplot(122) +plt.imshow(camera_multiply, cmap="gray", interpolation="nearest") +plt.axis("off") + +plt.tight_layout() +plt.show() diff --git a/_downloads/c495de1e43bcd8688a3ee21fd8c69e18/plot_quiver_ext.ipynb b/_downloads/c495de1e43bcd8688a3ee21fd8c69e18/plot_quiver_ext.ipynb new file mode 100644 index 000000000..f988a46d9 --- /dev/null +++ b/_downloads/c495de1e43bcd8688a3ee21fd8c69e18/plot_quiver_ext.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plotting quiver decorated\n\nAn example showing quiver with decorations.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nn = 8\nX, Y = np.mgrid[0:n, 0:n]\nT = np.arctan2(Y - n / 2.0, X - n / 2.0)\nR = 10 + np.sqrt((Y - n / 2.0) ** 2 + (X - n / 2.0) ** 2)\nU, V = R * np.cos(T), R * np.sin(T)\n\nplt.quiver(X, Y, U, V, R, alpha=0.5)\nplt.quiver(X, Y, U, V, edgecolor=\"k\", facecolor=\"None\", linewidth=0.5)\n\nplt.xlim(-1, n)\nplt.xticks([])\nplt.ylim(-1, n)\nplt.yticks([])\n\n\n# Add a title and a box around it\nfrom matplotlib.patches import FancyBboxPatch\n\nax = plt.gca()\nax.add_patch(\n FancyBboxPatch(\n (-0.05, 0.87),\n width=0.66,\n height=0.165,\n clip_on=False,\n boxstyle=\"square,pad=0\",\n zorder=3,\n facecolor=\"white\",\n alpha=1.0,\n transform=plt.gca().transAxes,\n )\n)\n\nplt.text(\n -0.05,\n 1.02,\n \" Quiver Plot: plt.quiver(...)\\n\",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"xx-large\",\n transform=plt.gca().transAxes,\n)\n\nplt.text(\n -0.05,\n 1.01,\n \"\\n\\n Plot a 2-D field of arrows \",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"large\",\n transform=plt.gca().transAxes,\n)\n\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/c6ba6e16e99b02c448c24d1062d9cc7d/plot_exercise_9.ipynb b/_downloads/c6ba6e16e99b02c448c24d1062d9cc7d/plot_exercise_9.ipynb new file mode 100644 index 000000000..90608f274 --- /dev/null +++ b/_downloads/c6ba6e16e99b02c448c24d1062d9cc7d/plot_exercise_9.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Exercise 9\n\nExercise 9 with matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(8, 5), dpi=80)\nplt.subplot(111)\n\nX = np.linspace(-np.pi, np.pi, 256, endpoint=True)\nC = np.cos(X)\nS = np.sin(X)\n\nplt.plot(X, C, color=\"blue\", linewidth=2.5, linestyle=\"-\", label=\"cosine\")\nplt.plot(X, S, color=\"red\", linewidth=2.5, linestyle=\"-\", label=\"sine\")\n\nax = plt.gca()\nax.spines[\"right\"].set_color(\"none\")\nax.spines[\"top\"].set_color(\"none\")\nax.xaxis.set_ticks_position(\"bottom\")\nax.spines[\"bottom\"].set_position((\"data\", 0))\nax.yaxis.set_ticks_position(\"left\")\nax.spines[\"left\"].set_position((\"data\", 0))\n\nplt.xlim(X.min() * 1.1, X.max() * 1.1)\nplt.xticks(\n [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],\n [r\"$-\\pi$\", r\"$-\\pi/2$\", r\"$0$\", r\"$+\\pi/2$\", r\"$+\\pi$\"],\n)\n\nplt.ylim(C.min() * 1.1, C.max() * 1.1)\nplt.yticks([-1, +1], [r\"$-1$\", r\"$+1$\"])\n\nt = 2 * np.pi / 3\nplt.plot([t, t], [0, np.cos(t)], color=\"blue\", linewidth=1.5, linestyle=\"--\")\nplt.scatter(\n [\n t,\n ],\n [\n np.cos(t),\n ],\n 50,\n color=\"blue\",\n)\nplt.annotate(\n r\"$sin(\\frac{2\\pi}{3})=\\frac{\\sqrt{3}}{2}$\",\n xy=(t, np.sin(t)),\n xycoords=\"data\",\n xytext=(+10, +30),\n textcoords=\"offset points\",\n fontsize=16,\n arrowprops={\"arrowstyle\": \"->\", \"connectionstyle\": \"arc3,rad=.2\"},\n)\n\nplt.plot([t, t], [0, np.sin(t)], color=\"red\", linewidth=1.5, linestyle=\"--\")\nplt.scatter(\n [\n t,\n ],\n [\n np.sin(t),\n ],\n 50,\n color=\"red\",\n)\nplt.annotate(\n r\"$cos(\\frac{2\\pi}{3})=-\\frac{1}{2}$\",\n xy=(t, np.cos(t)),\n xycoords=\"data\",\n xytext=(-90, -50),\n textcoords=\"offset points\",\n fontsize=16,\n arrowprops={\"arrowstyle\": \"->\", \"connectionstyle\": \"arc3,rad=.2\"},\n)\n\nplt.legend(loc=\"upper left\")\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/c6fdb72038a18b6901aeef3179c5d126/plot_face_denoise.zip b/_downloads/c6fdb72038a18b6901aeef3179c5d126/plot_face_denoise.zip new file mode 100644 index 000000000..f6677659c Binary files /dev/null and b/_downloads/c6fdb72038a18b6901aeef3179c5d126/plot_face_denoise.zip differ diff --git a/_downloads/c87147191b8bbffd05c98cac7659d455/plot_spectrogram.py b/_downloads/c87147191b8bbffd05c98cac7659d455/plot_spectrogram.py new file mode 100644 index 000000000..988d618e2 --- /dev/null +++ b/_downloads/c87147191b8bbffd05c98cac7659d455/plot_spectrogram.py @@ -0,0 +1,63 @@ +""" +====================================== +Spectrogram, power spectral density +====================================== + +Demo spectrogram and power spectral density on a frequency chirp. +""" + +import numpy as np +import matplotlib.pyplot as plt + +############################################################ +# Generate a chirp signal +############################################################ + +# Seed the random number generator +np.random.seed(0) + +time_step = 0.01 +time_vec = np.arange(0, 70, time_step) + +# A signal with a small frequency chirp +sig = np.sin(0.5 * np.pi * time_vec * (1 + 0.1 * time_vec)) + +plt.figure(figsize=(8, 5)) +plt.plot(time_vec, sig) + +############################################################ +# Compute and plot the spectrogram +############################################################ +# +# The spectrum of the signal on consecutive time windows + +import scipy as sp + +freqs, times, spectrogram = sp.signal.spectrogram(sig) + +plt.figure(figsize=(5, 4)) +plt.imshow(spectrogram, aspect="auto", cmap="hot_r", origin="lower") +plt.title("Spectrogram") +plt.ylabel("Frequency band") +plt.xlabel("Time window") +plt.tight_layout() + + +############################################################ +# Compute and plot the power spectral density (PSD) +############################################################ +# +# The power of the signal per frequency band + +freqs, psd = sp.signal.welch(sig) + +plt.figure(figsize=(5, 4)) +plt.semilogx(freqs, psd) +plt.title("PSD: power spectral density") +plt.xlabel("Frequency") +plt.ylabel("Power") +plt.tight_layout() + +############################################################ + +plt.show() diff --git a/_downloads/c9023a2700bcc920f3f92277c13fcee0/plot_mec.zip b/_downloads/c9023a2700bcc920f3f92277c13fcee0/plot_mec.zip new file mode 100644 index 000000000..2df60ddd1 Binary files /dev/null and b/_downloads/c9023a2700bcc920f3f92277c13fcee0/plot_mec.zip differ diff --git a/_downloads/c903157069200a991273293a7e34f6fc/plot_spectral_clustering.zip b/_downloads/c903157069200a991273293a7e34f6fc/plot_spectral_clustering.zip new file mode 100644 index 000000000..33cb209ee Binary files /dev/null and b/_downloads/c903157069200a991273293a7e34f6fc/plot_spectral_clustering.zip differ diff --git a/_downloads/c9070dc3a3160cec80a5c9273566e9cd/plot_subplot-horizontal.zip b/_downloads/c9070dc3a3160cec80a5c9273566e9cd/plot_subplot-horizontal.zip new file mode 100644 index 000000000..7e392b98f Binary files /dev/null and b/_downloads/c9070dc3a3160cec80a5c9273566e9cd/plot_subplot-horizontal.zip differ diff --git a/_downloads/c91ad7a55da17a3c6ece5384f65c2646/plot_california_prediction.zip b/_downloads/c91ad7a55da17a3c6ece5384f65c2646/plot_california_prediction.zip new file mode 100644 index 000000000..56a98c61a Binary files /dev/null and b/_downloads/c91ad7a55da17a3c6ece5384f65c2646/plot_california_prediction.zip differ diff --git a/_downloads/c930e767c3c21003ae239d127e81078e/plot_propagation.ipynb b/_downloads/c930e767c3c21003ae239d127e81078e/plot_propagation.ipynb new file mode 100644 index 000000000..7f4175e61 --- /dev/null +++ b/_downloads/c930e767c3c21003ae239d127e81078e/plot_propagation.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Opening, erosion, and propagation\n\nThis example shows simple operations of mathematical morphology.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nsquare = np.zeros((32, 32))\nsquare[10:-10, 10:-10] = 1\nrng = np.random.default_rng(27446968)\nx, y = (32 * rng.random((2, 20))).astype(int)\nsquare[x, y] = 1\n\nopen_square = sp.ndimage.binary_opening(square)\n\neroded_square = sp.ndimage.binary_erosion(square)\nreconstruction = sp.ndimage.binary_propagation(eroded_square, mask=square)\n\nplt.figure(figsize=(9.5, 3))\nplt.subplot(131)\nplt.imshow(square, cmap=\"gray\", interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.subplot(132)\nplt.imshow(open_square, cmap=\"gray\", interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.subplot(133)\nplt.imshow(reconstruction, cmap=\"gray\", interpolation=\"nearest\")\nplt.axis(\"off\")\n\nplt.subplots_adjust(wspace=0, hspace=0.02, top=0.99, bottom=0.01, left=0.01, right=0.99)\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/cad368fa7137d6ffa043dd3d82b4d906/plot_greyscale_dilation.py b/_downloads/cad368fa7137d6ffa043dd3d82b4d906/plot_greyscale_dilation.py new file mode 100644 index 000000000..2ede10a98 --- /dev/null +++ b/_downloads/cad368fa7137d6ffa043dd3d82b4d906/plot_greyscale_dilation.py @@ -0,0 +1,39 @@ +""" +Greyscale dilation +==================== + +This example illustrates greyscale mathematical morphology. +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +im = np.zeros((64, 64)) +rng = np.random.default_rng(27446968) +x, y = (63 * rng.random((2, 8))).astype(int) +im[x, y] = np.arange(8) + +bigger_points = sp.ndimage.grey_dilation(im, size=(5, 5), structure=np.ones((5, 5))) + +square = np.zeros((16, 16)) +square[4:-4, 4:-4] = 1 +dist = sp.ndimage.distance_transform_bf(square) +dilate_dist = sp.ndimage.grey_dilation(dist, size=(3, 3), structure=np.ones((3, 3))) + +plt.figure(figsize=(12.5, 3)) +plt.subplot(141) +plt.imshow(im, interpolation="nearest", cmap="nipy_spectral") +plt.axis("off") +plt.subplot(142) +plt.imshow(bigger_points, interpolation="nearest", cmap="nipy_spectral") +plt.axis("off") +plt.subplot(143) +plt.imshow(dist, interpolation="nearest", cmap="nipy_spectral") +plt.axis("off") +plt.subplot(144) +plt.imshow(dilate_dist, interpolation="nearest", cmap="nipy_spectral") +plt.axis("off") + +plt.subplots_adjust(wspace=0, hspace=0.02, top=0.99, bottom=0.01, left=0.01, right=0.99) +plt.show() diff --git a/_downloads/cbbfb7cd3169a3efdc227a4c4fa0eb45/plot_subplot-vertical.ipynb b/_downloads/cbbfb7cd3169a3efdc227a4c4fa0eb45/plot_subplot-vertical.ipynb new file mode 100644 index 000000000..4ccc12b5e --- /dev/null +++ b/_downloads/cbbfb7cd3169a3efdc227a4c4fa0eb45/plot_subplot-vertical.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Subplot plot arrangement vertical\n\nAn example showing vertical arrangement of subplots with matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\n\nplt.figure(figsize=(6, 4))\nplt.subplot(1, 2, 1)\nplt.xticks([])\nplt.yticks([])\nplt.text(0.5, 0.5, \"subplot(1,2,1)\", ha=\"center\", va=\"center\", size=24, alpha=0.5)\n\nplt.subplot(1, 2, 2)\nplt.xticks([])\nplt.yticks([])\nplt.text(0.5, 0.5, \"subplot(1,2,2)\", ha=\"center\", va=\"center\", size=24, alpha=0.5)\n\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/cc416a88f21a8e1578ef320a9b7da061/plot_basic1dplot.zip b/_downloads/cc416a88f21a8e1578ef320a9b7da061/plot_basic1dplot.zip new file mode 100644 index 000000000..a6af6f48f Binary files /dev/null and b/_downloads/cc416a88f21a8e1578ef320a9b7da061/plot_basic1dplot.zip differ diff --git a/_downloads/cc48b617db83afe66c7e4e955ea3f3bd/brain_size.csv b/_downloads/cc48b617db83afe66c7e4e955ea3f3bd/brain_size.csv new file mode 100644 index 000000000..226980e53 --- /dev/null +++ b/_downloads/cc48b617db83afe66c7e4e955ea3f3bd/brain_size.csv @@ -0,0 +1,41 @@ +"";"Gender";"FSIQ";"VIQ";"PIQ";"Weight";"Height";"MRI_Count" +"1";"Female";133;132;124;"118";"64.5";816932 +"2";"Male";140;150;124;".";"72.5";1001121 +"3";"Male";139;123;150;"143";"73.3";1038437 +"4";"Male";133;129;128;"172";"68.8";965353 +"5";"Female";137;132;134;"147";"65.0";951545 +"6";"Female";99;90;110;"146";"69.0";928799 +"7";"Female";138;136;131;"138";"64.5";991305 +"8";"Female";92;90;98;"175";"66.0";854258 +"9";"Male";89;93;84;"134";"66.3";904858 +"10";"Male";133;114;147;"172";"68.8";955466 +"11";"Female";132;129;124;"118";"64.5";833868 +"12";"Male";141;150;128;"151";"70.0";1079549 +"13";"Male";135;129;124;"155";"69.0";924059 +"14";"Female";140;120;147;"155";"70.5";856472 +"15";"Female";96;100;90;"146";"66.0";878897 +"16";"Female";83;71;96;"135";"68.0";865363 +"17";"Female";132;132;120;"127";"68.5";852244 +"18";"Male";100;96;102;"178";"73.5";945088 +"19";"Female";101;112;84;"136";"66.3";808020 +"20";"Male";80;77;86;"180";"70.0";889083 +"21";"Male";83;83;86;".";".";892420 +"22";"Male";97;107;84;"186";"76.5";905940 +"23";"Female";135;129;134;"122";"62.0";790619 +"24";"Male";139;145;128;"132";"68.0";955003 +"25";"Female";91;86;102;"114";"63.0";831772 +"26";"Male";141;145;131;"171";"72.0";935494 +"27";"Female";85;90;84;"140";"68.0";798612 +"28";"Male";103;96;110;"187";"77.0";1062462 +"29";"Female";77;83;72;"106";"63.0";793549 +"30";"Female";130;126;124;"159";"66.5";866662 +"31";"Female";133;126;132;"127";"62.5";857782 +"32";"Male";144;145;137;"191";"67.0";949589 +"33";"Male";103;96;110;"192";"75.5";997925 +"34";"Male";90;96;86;"181";"69.0";879987 +"35";"Female";83;90;81;"143";"66.5";834344 +"36";"Female";133;129;128;"153";"66.5";948066 +"37";"Male";140;150;124;"144";"70.5";949395 +"38";"Female";88;86;94;"139";"64.5";893983 +"39";"Male";81;90;74;"148";"74.0";930016 +"40";"Male";89;91;89;"179";"75.5";935863 diff --git a/_downloads/ccada9fac6e82573ff43825b66ed8038/plot_gridspec.zip b/_downloads/ccada9fac6e82573ff43825b66ed8038/plot_gridspec.zip new file mode 100644 index 000000000..6a917aee9 Binary files /dev/null and b/_downloads/ccada9fac6e82573ff43825b66ed8038/plot_gridspec.zip differ diff --git a/_downloads/ccf3ecd852a9312e63587410d2521b12/plot_linear_model_cv.zip b/_downloads/ccf3ecd852a9312e63587410d2521b12/plot_linear_model_cv.zip new file mode 100644 index 000000000..f79b2eeee Binary files /dev/null and b/_downloads/ccf3ecd852a9312e63587410d2521b12/plot_linear_model_cv.zip differ diff --git a/_downloads/cd28535ac6b02e69e5303bf386f90e61/plot_features.py b/_downloads/cd28535ac6b02e69e5303bf386f90e61/plot_features.py new file mode 100644 index 000000000..74cda9f2d --- /dev/null +++ b/_downloads/cd28535ac6b02e69e5303bf386f90e61/plot_features.py @@ -0,0 +1,26 @@ +""" +Affine transform +================= + +Warping and affine transforms of images. +""" + +import matplotlib.pyplot as plt + +from skimage import data +from skimage.feature import corner_harris, corner_subpix, corner_peaks +from skimage.transform import warp, AffineTransform + + +tform = AffineTransform(scale=(1.3, 1.1), rotation=1, shear=0.7, translation=(210, 50)) +image = warp(data.checkerboard(), tform.inverse, output_shape=(350, 350)) + +coords = corner_peaks(corner_harris(image), min_distance=5) +coords_subpix = corner_subpix(image, coords, window_size=13) + +plt.gray() +plt.imshow(image, interpolation="nearest") +plt.plot(coords_subpix[:, 1], coords_subpix[:, 0], "+r", markersize=15, mew=5) +plt.plot(coords[:, 1], coords[:, 0], ".b", markersize=7) +plt.axis("off") +plt.show() diff --git a/_downloads/cd8e685eae1fabbadf80cfeed9eaa9f1/plot_compare_classifiers.py b/_downloads/cd8e685eae1fabbadf80cfeed9eaa9f1/plot_compare_classifiers.py new file mode 100644 index 000000000..40aec4156 --- /dev/null +++ b/_downloads/cd8e685eae1fabbadf80cfeed9eaa9f1/plot_compare_classifiers.py @@ -0,0 +1,44 @@ +""" +Compare classifiers on the digits data +======================================= + +Compare the performance of a variety of classifiers on a test set for the +digits data. +""" + +from sklearn import model_selection, datasets, metrics +from sklearn.svm import LinearSVC +from sklearn.naive_bayes import GaussianNB +from sklearn.neighbors import KNeighborsClassifier + +digits = datasets.load_digits() +X = digits.data +y = digits.target +X_train, X_test, y_train, y_test = model_selection.train_test_split( + X, y, test_size=0.25, random_state=0 +) + +for Model in [LinearSVC, GaussianNB, KNeighborsClassifier]: + clf = Model().fit(X_train, y_train) + y_pred = clf.predict(X_test) + print(f"{Model.__name__}: {metrics.f1_score(y_test, y_pred, average='macro')}") + +print("------------------") + +# test SVC loss +for loss in ["hinge", "squared_hinge"]: + clf = LinearSVC(loss=loss).fit(X_train, y_train) + y_pred = clf.predict(X_test) + print( + f"LinearSVC(loss='{loss}'): {metrics.f1_score(y_test, y_pred, average='macro')}" + ) + +print("-------------------") + +# test the number of neighbors +for n_neighbors in range(1, 11): + clf = KNeighborsClassifier(n_neighbors=n_neighbors).fit(X_train, y_train) + y_pred = clf.predict(X_test) + print( + f"KNeighbors(n_neighbors={n_neighbors}): {metrics.f1_score(y_test, y_pred, average='macro')}" + ) diff --git a/_downloads/cd97ee9bb9b448cc1cb086da5ace2107/plot_linear_model_cv.py b/_downloads/cd97ee9bb9b448cc1cb086da5ace2107/plot_linear_model_cv.py new file mode 100644 index 000000000..bc7f3a467 --- /dev/null +++ b/_downloads/cd97ee9bb9b448cc1cb086da5ace2107/plot_linear_model_cv.py @@ -0,0 +1,44 @@ +""" +================================================================ +Use the RidgeCV and LassoCV to set the regularization parameter +================================================================ + + +""" + +############################################################ +# Load the diabetes dataset +from sklearn.datasets import load_diabetes + +data = load_diabetes() +X, y = data.data, data.target +print(X.shape) + +############################################################ +# Compute the cross-validation score with the default hyper-parameters +from sklearn.model_selection import cross_val_score +from sklearn.linear_model import Ridge, Lasso + +for Model in [Ridge, Lasso]: + model = Model() + print(f"{Model.__name__}: {cross_val_score(model, X, y).mean()}") + +############################################################ +# We compute the cross-validation score as a function of alpha, the +# strength of the regularization for Lasso and Ridge +import numpy as np +import matplotlib.pyplot as plt + +alphas = np.logspace(-3, -1, 30) + +plt.figure(figsize=(5, 3)) + +for Model in [Lasso, Ridge]: + scores = [cross_val_score(Model(alpha), X, y, cv=3).mean() for alpha in alphas] + plt.plot(alphas, scores, label=Model.__name__) + +plt.legend(loc="lower left") +plt.xlabel("alpha") +plt.ylabel("cross validation score") +plt.tight_layout() +plt.show() diff --git a/_downloads/ce97e733a6f11546bd60364a41a327a0/plot_mfc.py b/_downloads/ce97e733a6f11546bd60364a41a327a0/plot_mfc.py new file mode 100644 index 000000000..e14cdea2b --- /dev/null +++ b/_downloads/ce97e733a6f11546bd60364a41a327a0/plot_mfc.py @@ -0,0 +1,38 @@ +""" +Marker face color +================== + +Demo the marker face color of matplotlib's markers. +""" + +import numpy as np +import matplotlib.pyplot as plt + +size = 256, 16 +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = plt.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +plt.axes((0, 0, 1, 1), frameon=False) + +rng = np.random.default_rng() + +for i in range(1, 11): + r, g, b = np.random.uniform(0, 1, 3) + plt.plot( + [ + i, + ], + [ + 1, + ], + "s", + markersize=8, + markerfacecolor=(r, g, b, 1), + markeredgewidth=0.1, + markeredgecolor=(0, 0, 0, 0.5), + ) +plt.xlim(0, 11) +plt.xticks([]) +plt.yticks([]) +plt.show() diff --git a/_downloads/cf0764bb707612e100eb22fef00477a4/plot_good.zip b/_downloads/cf0764bb707612e100eb22fef00477a4/plot_good.zip new file mode 100644 index 000000000..4dd6b7d10 Binary files /dev/null and b/_downloads/cf0764bb707612e100eb22fef00477a4/plot_good.zip differ diff --git a/_downloads/cf3ed03c69806e87c9cb45fe8506005c/plot_populations.zip b/_downloads/cf3ed03c69806e87c9cb45fe8506005c/plot_populations.zip new file mode 100644 index 000000000..048383aea Binary files /dev/null and b/_downloads/cf3ed03c69806e87c9cb45fe8506005c/plot_populations.zip differ diff --git a/_downloads/cf5322f1d0f76e6a5a607d6c76ca4eea/plot_iris_knn.zip b/_downloads/cf5322f1d0f76e6a5a607d6c76ca4eea/plot_iris_knn.zip new file mode 100644 index 000000000..4736b5411 Binary files /dev/null and b/_downloads/cf5322f1d0f76e6a5a607d6c76ca4eea/plot_iris_knn.zip differ diff --git a/_downloads/d08178be0c957daeb055b0d4af4f625d/plot_populations.ipynb b/_downloads/d08178be0c957daeb055b0d4af4f625d/plot_populations.ipynb new file mode 100644 index 000000000..e22bfe744 --- /dev/null +++ b/_downloads/d08178be0c957daeb055b0d4af4f625d/plot_populations.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Population exercise\n\nPlot populations of hares, lynxes, and carrots\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\ndata = np.loadtxt(\"../../../data/populations.txt\")\nyear, hares, lynxes, carrots = data.T\n\nplt.axes((0.2, 0.1, 0.5, 0.8))\nplt.plot(year, hares, year, lynxes, year, carrots)\nplt.legend((\"Hare\", \"Lynx\", \"Carrot\"), loc=(1.05, 0.5))\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/d0a957a84bd098de78a28b3efeb4aa1f/plot_plot3d.zip b/_downloads/d0a957a84bd098de78a28b3efeb4aa1f/plot_plot3d.zip new file mode 100644 index 000000000..39a0e965f Binary files /dev/null and b/_downloads/d0a957a84bd098de78a28b3efeb4aa1f/plot_plot3d.zip differ diff --git a/_downloads/d0adc161a3be32ffcdc21c040444aff2/plot_exercise_6.py b/_downloads/d0adc161a3be32ffcdc21c040444aff2/plot_exercise_6.py new file mode 100644 index 000000000..237ddebaf --- /dev/null +++ b/_downloads/d0adc161a3be32ffcdc21c040444aff2/plot_exercise_6.py @@ -0,0 +1,30 @@ +""" +Exercise 6 +=========== + +Exercise 6 with matplotlib. +""" + +import numpy as np +import matplotlib.pyplot as plt + +plt.figure(figsize=(8, 5), dpi=80) +plt.subplot(111) + +X = np.linspace(-np.pi, np.pi, 256) +C = np.cos(X) +S = np.sin(X) + +plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") +plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") + +plt.xlim(X.min() * 1.1, X.max() * 1.1) +plt.xticks( + [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], + [r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"], +) + +plt.ylim(C.min() * 1.1, C.max() * 1.1) +plt.yticks([-1, 0, +1], [r"$-1$", r"$0$", r"$+1$"]) + +plt.show() diff --git a/_downloads/d260dbf6ef31296747d36c522ff4ea29/plot_paired_boxplots.ipynb b/_downloads/d260dbf6ef31296747d36c522ff4ea29/plot_paired_boxplots.ipynb new file mode 100644 index 000000000..700eb7ce7 --- /dev/null +++ b/_downloads/d260dbf6ef31296747d36c522ff4ea29/plot_paired_boxplots.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Boxplots and paired differences\n\nPlot boxplots for FSIQ, PIQ, and the paired difference between the two:\nwhile the spread (error bars) for FSIQ and PIQ are very large, there is a\nsystematic (common) effect due to the subjects. This effect is cancelled\nout in the difference and the spread of the difference (\"paired\" by\nsubject) is much smaller than the spread of the individual measures.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import pandas\n\nimport matplotlib.pyplot as plt\n\ndata = pandas.read_csv(\"brain_size.csv\", sep=\";\", na_values=\".\")\n\n# Box plot of FSIQ and PIQ (different measures od IQ)\nplt.figure(figsize=(4, 3))\ndata.boxplot(column=[\"FSIQ\", \"PIQ\"])\n\n# Boxplot of the difference\nplt.figure(figsize=(4, 3))\nplt.boxplot(data[\"FSIQ\"] - data[\"PIQ\"])\nplt.xticks((1,), (\"FSIQ - PIQ\",))\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/d286abc77dba4234817b32ee50a7ceed/plot_tsne.ipynb b/_downloads/d286abc77dba4234817b32ee50a7ceed/plot_tsne.ipynb new file mode 100644 index 000000000..bebbcc1ca --- /dev/null +++ b/_downloads/d286abc77dba4234817b32ee50a7ceed/plot_tsne.ipynb @@ -0,0 +1,104 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# tSNE to visualize digits\n\nHere we use :class:`sklearn.manifold.TSNE` to visualize the digits\ndatasets. Indeed, the digits are vectors in a 8*8 = 64 dimensional space.\nWe want to project them in 2D for visualization. tSNE is often a good\nsolution, as it groups and separates data points based on their local\nrelationship.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Load the iris data\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn import datasets\n\ndigits = datasets.load_digits()\n# Take the first 500 data points: it's hard to see 1500 points\nX = digits.data[:500]\ny = digits.target[:500]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Fit and transform with a TSNE\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.manifold import TSNE\n\ntsne = TSNE(n_components=2, random_state=0)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Project the data in 2D\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "X_2d = tsne.fit_transform(X)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Visualize the data\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "target_ids = range(len(digits.target_names))\n\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(6, 5))\ncolors = \"r\", \"g\", \"b\", \"c\", \"m\", \"y\", \"k\", \"w\", \"orange\", \"purple\"\nfor i, c, label in zip(target_ids, colors, digits.target_names, strict=True):\n plt.scatter(X_2d[y == i, 0], X_2d[y == i, 1], c=c, label=label)\nplt.legend()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/d2d3170217c08d0235c7e902251fc299/plot_polar.zip b/_downloads/d2d3170217c08d0235c7e902251fc299/plot_polar.zip new file mode 100644 index 000000000..21aa5d019 Binary files /dev/null and b/_downloads/d2d3170217c08d0235c7e902251fc299/plot_polar.zip differ diff --git a/_downloads/d34bf7c9e10ce85c00ea227419e0765d/plot_mew.py b/_downloads/d34bf7c9e10ce85c00ea227419e0765d/plot_mew.py new file mode 100644 index 000000000..5e78b176b --- /dev/null +++ b/_downloads/d34bf7c9e10ce85c00ea227419e0765d/plot_mew.py @@ -0,0 +1,35 @@ +""" +Marker edge width +================= + +Demo the marker edge widths of matplotlib's markers. +""" + +import matplotlib.pyplot as plt + +size = 256, 16 +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = plt.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +plt.axes((0, 0, 1, 1), frameon=False) + +for i in range(1, 11): + plt.plot( + [ + i, + ], + [ + 1, + ], + "s", + markersize=5, + markeredgewidth=1 + i / 10.0, + markeredgecolor="k", + markerfacecolor="w", + ) +plt.xlim(0, 11) +plt.xticks([]) +plt.yticks([]) + +plt.show() diff --git a/_downloads/d3bbee69b681b618f914c2964327ebda/plot_pca.ipynb b/_downloads/d3bbee69b681b618f914c2964327ebda/plot_pca.ipynb new file mode 100644 index 000000000..70a5dbdc3 --- /dev/null +++ b/_downloads/d3bbee69b681b618f914c2964327ebda/plot_pca.ipynb @@ -0,0 +1,104 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Demo PCA in 2D\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Load the iris data\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn import datasets\n\niris = datasets.load_iris()\nX = iris.data\ny = iris.target" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Fit a PCA\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.decomposition import PCA\n\npca = PCA(n_components=2, whiten=True)\npca.fit(X)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Project the data in 2D\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "X_pca = pca.transform(X)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Visualize the data\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "target_ids = range(len(iris.target_names))\n\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(6, 5))\nfor i, c, label in zip(target_ids, \"rgbcmykw\", iris.target_names, strict=False):\n plt.scatter(X_pca[y == i, 0], X_pca[y == i, 1], c=c, label=label)\nplt.legend()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/d5171e3aa6f2c733c6741bd33051b5ba/plot_1d_optim.ipynb b/_downloads/d5171e3aa6f2c733c6741bd33051b5ba/plot_1d_optim.ipynb new file mode 100644 index 000000000..34e503851 --- /dev/null +++ b/_downloads/d5171e3aa6f2c733c6741bd33051b5ba/plot_1d_optim.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Brent's method\n\nIllustration of 1D optimization: Brent's method\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy as sp\n\nx = np.linspace(-1, 3, 100)\nx_0 = np.exp(-1)\n\n\ndef f(x):\n return (x - x_0) ** 2 + epsilon * np.exp(-5 * (x - 0.5 - x_0) ** 2)\n\n\nfor epsilon in (0, 1):\n plt.figure(figsize=(3, 2.5))\n plt.axes((0, 0, 1, 1))\n\n # A convex function\n plt.plot(x, f(x), linewidth=2)\n\n # Apply brent method. To have access to the iteration, do this in an\n # artificial way: allow the algorithm to iter only once\n all_x = []\n all_y = []\n for iter in range(30):\n result = sp.optimize.minimize_scalar(\n f,\n bracket=(-5, 2.9, 4.5),\n method=\"Brent\",\n options={\"maxiter\": iter},\n tol=np.finfo(1.0).eps,\n )\n if result.success:\n print(\"Converged at \", iter)\n break\n\n this_x = result.x\n all_x.append(this_x)\n all_y.append(f(this_x))\n if iter < 6:\n plt.text(\n this_x - 0.05 * np.sign(this_x) - 0.05,\n f(this_x) + 1.2 * (0.3 - iter % 2),\n str(iter + 1),\n size=12,\n )\n\n plt.plot(all_x[:10], all_y[:10], \"k+\", markersize=12, markeredgewidth=2)\n\n plt.plot(all_x[-1], all_y[-1], \"rx\", markersize=12)\n plt.axis(\"off\")\n plt.ylim(ymin=-1, ymax=8)\n\n plt.figure(figsize=(4, 3))\n plt.semilogy(np.abs(all_y - all_y[-1]), linewidth=2)\n plt.ylabel(\"Error on f(x)\")\n plt.xlabel(\"Iteration\")\n plt.tight_layout()\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/d5bf899a3b2e6de0907db36efaf25280/plot_segmentations.py b/_downloads/d5bf899a3b2e6de0907db36efaf25280/plot_segmentations.py new file mode 100644 index 000000000..16896c987 --- /dev/null +++ b/_downloads/d5bf899a3b2e6de0907db36efaf25280/plot_segmentations.py @@ -0,0 +1,60 @@ +""" +Watershed and random walker for segmentation +============================================ + +This example compares two segmentation methods in order to separate two +connected disks: the watershed algorithm, and the random walker algorithm. + +Both segmentation methods require seeds, that are pixels belonging +unambigusouly to a reagion. Here, local maxima of the distance map to the +background are used as seeds. +""" + +import numpy as np +from skimage.segmentation import watershed +from skimage.feature import peak_local_max +from skimage import measure +from skimage.segmentation import random_walker +import matplotlib.pyplot as plt +import scipy as sp + +# Generate an initial image with two overlapping circles +x, y = np.indices((80, 80)) +x1, y1, x2, y2 = 28, 28, 44, 52 +r1, r2 = 16, 20 +mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1**2 +mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2**2 +image = np.logical_or(mask_circle1, mask_circle2) +# Now we want to separate the two objects in image +# Generate the markers as local maxima of the distance +# to the background +distance = sp.ndimage.distance_transform_edt(image) +peak_idx = peak_local_max(distance, footprint=np.ones((3, 3)), labels=image) +peak_mask = np.zeros_like(distance, dtype=bool) +peak_mask[tuple(peak_idx.T)] = True +markers = measure.label(peak_mask) +labels_ws = watershed(-distance, markers, mask=image) + +markers[~image] = -1 +labels_rw = random_walker(image, markers) + +plt.figure(figsize=(12, 3.5)) +plt.subplot(141) +plt.imshow(image, cmap="gray", interpolation="nearest") +plt.axis("off") +plt.title("image") +plt.subplot(142) +plt.imshow(-distance, interpolation="nearest") +plt.axis("off") +plt.title("distance map") +plt.subplot(143) +plt.imshow(labels_ws, cmap="nipy_spectral", interpolation="nearest") +plt.axis("off") +plt.title("watershed segmentation") +plt.subplot(144) +plt.imshow(labels_rw, cmap="nipy_spectral", interpolation="nearest") +plt.axis("off") +plt.title("random walker segmentation") + +plt.tight_layout() +plt.show() diff --git a/_downloads/d6243f64f666f0f79222569ebbce30a1/plot_check.ipynb b/_downloads/d6243f64f666f0f79222569ebbce30a1/plot_check.ipynb new file mode 100644 index 000000000..dad3790f6 --- /dev/null +++ b/_downloads/d6243f64f666f0f79222569ebbce30a1/plot_check.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Creating an image\n\nHow to create an image with basic NumPy commands : ``np.zeros``, slicing...\n\nThis examples show how to create a simple checkerboard.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\ncheck = np.zeros((8, 8))\ncheck[::2, 1::2] = 1\ncheck[1::2, ::2] = 1\nplt.matshow(check, cmap=\"gray\")\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/d74b12f2f530620c92b0f12d5ac5c9c9/plot_features.ipynb b/_downloads/d74b12f2f530620c92b0f12d5ac5c9c9/plot_features.ipynb new file mode 100644 index 000000000..58ff4f9da --- /dev/null +++ b/_downloads/d74b12f2f530620c92b0f12d5ac5c9c9/plot_features.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Affine transform\n\nWarping and affine transforms of images.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nfrom skimage import data\nfrom skimage.feature import corner_harris, corner_subpix, corner_peaks\nfrom skimage.transform import warp, AffineTransform\n\n\ntform = AffineTransform(scale=(1.3, 1.1), rotation=1, shear=0.7, translation=(210, 50))\nimage = warp(data.checkerboard(), tform.inverse, output_shape=(350, 350))\n\ncoords = corner_peaks(corner_harris(image), min_distance=5)\ncoords_subpix = corner_subpix(image, coords, window_size=13)\n\nplt.gray()\nplt.imshow(image, interpolation=\"nearest\")\nplt.plot(coords_subpix[:, 1], coords_subpix[:, 0], \"+r\", markersize=15, mew=5)\nplt.plot(coords[:, 1], coords[:, 0], \".b\", markersize=7)\nplt.axis(\"off\")\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/d8371bb095a3b16f8d07554e484f0035/plot_granulo.py b/_downloads/d8371bb095a3b16f8d07554e484f0035/plot_granulo.py new file mode 100644 index 000000000..215e0344a --- /dev/null +++ b/_downloads/d8371bb095a3b16f8d07554e484f0035/plot_granulo.py @@ -0,0 +1,58 @@ +""" +Granulometry +============ + +This example performs a simple granulometry analysis. +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + + +def disk_structure(n): + struct = np.zeros((2 * n + 1, 2 * n + 1)) + x, y = np.indices((2 * n + 1, 2 * n + 1)) + mask = (x - n) ** 2 + (y - n) ** 2 <= n**2 + struct[mask] = 1 + return struct.astype(bool) + + +def granulometry(data, sizes=None): + s = max(data.shape) + if sizes is None: + sizes = range(1, s / 2, 2) + granulo = [ + sp.ndimage.binary_opening(data, structure=disk_structure(n)).sum() + for n in sizes + ] + return granulo + + +rng = np.random.default_rng(27446968) +n = 10 +l = 256 +im = np.zeros((l, l)) +points = l * rng.random((2, n**2)) +im[(points[0]).astype(int), (points[1]).astype(int)] = 1 +im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) + +mask = im > im.mean() + +granulo = granulometry(mask, sizes=np.arange(2, 19, 4)) + +plt.figure(figsize=(6, 2.2)) + +plt.subplot(121) +plt.imshow(mask, cmap="gray") +opened = sp.ndimage.binary_opening(mask, structure=disk_structure(10)) +opened_more = sp.ndimage.binary_opening(mask, structure=disk_structure(14)) +plt.contour(opened, [0.5], colors="b", linewidths=2) +plt.contour(opened_more, [0.5], colors="r", linewidths=2) +plt.axis("off") +plt.subplot(122) +plt.plot(np.arange(2, 19, 4), granulo, "ok", ms=8) + + +plt.subplots_adjust(wspace=0.02, hspace=0.15, top=0.95, bottom=0.15, left=0, right=0.95) +plt.show() diff --git a/_downloads/d83c4540f14cc4433aca0bb00ab24757/plot_pandas.zip b/_downloads/d83c4540f14cc4433aca0bb00ab24757/plot_pandas.zip new file mode 100644 index 000000000..6ce14b77f Binary files /dev/null and b/_downloads/d83c4540f14cc4433aca0bb00ab24757/plot_pandas.zip differ diff --git a/_downloads/d8cf73dbe1f756474e5728aae9bc0ff5/plot_detrend.py b/_downloads/d8cf73dbe1f756474e5728aae9bc0ff5/plot_detrend.py new file mode 100644 index 000000000..15b241e19 --- /dev/null +++ b/_downloads/d8cf73dbe1f756474e5728aae9bc0ff5/plot_detrend.py @@ -0,0 +1,31 @@ +""" +=================== +Detrending a signal +=================== + +:func:`scipy.signal.detrend` removes a linear trend. +""" + +############################################################ +# Generate a random signal with a trend +import numpy as np + +t = np.linspace(0, 5, 100) +rng = np.random.default_rng() +x = t + rng.normal(size=100) + +############################################################ +# Detrend +import scipy as sp + +x_detrended = sp.signal.detrend(x) + +############################################################ +# Plot +import matplotlib.pyplot as plt + +plt.figure(figsize=(5, 4)) +plt.plot(t, x, label="x") +plt.plot(t, x_detrended, label="x_detrended") +plt.legend(loc="best") +plt.show() diff --git a/_downloads/d94f9d7208f0c490ba8ab6f7b2a9885a/plot_linestyles.zip b/_downloads/d94f9d7208f0c490ba8ab6f7b2a9885a/plot_linestyles.zip new file mode 100644 index 000000000..772272cb1 Binary files /dev/null and b/_downloads/d94f9d7208f0c490ba8ab6f7b2a9885a/plot_linestyles.zip differ diff --git a/_downloads/d953697caacf285105c74ec28ef2fb8b/plot_exercise_9.zip b/_downloads/d953697caacf285105c74ec28ef2fb8b/plot_exercise_9.zip new file mode 100644 index 000000000..6470ca4cb Binary files /dev/null and b/_downloads/d953697caacf285105c74ec28ef2fb8b/plot_exercise_9.zip differ diff --git a/_downloads/d9f2df0226f27834ad64f68808fec0aa/plot_plot3d.py b/_downloads/d9f2df0226f27834ad64f68808fec0aa/plot_plot3d.py new file mode 100644 index 000000000..019f1ada1 --- /dev/null +++ b/_downloads/d9f2df0226f27834ad64f68808fec0aa/plot_plot3d.py @@ -0,0 +1,23 @@ +""" +3D plotting +=========== + +A simple example of 3D plotting. +""" + +import numpy as np +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d import Axes3D + +ax: Axes3D = plt.figure().add_subplot(projection="3d") +X = np.arange(-4, 4, 0.25) +Y = np.arange(-4, 4, 0.25) +X, Y = np.meshgrid(X, Y) +R = np.sqrt(X**2 + Y**2) +Z = np.sin(R) + +ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap="hot") +ax.contourf(X, Y, Z, zdir="z", offset=-2, cmap="hot") +ax.set_zlim(-2, 2) + +plt.show() diff --git a/_downloads/da756e3c91f993fc2ad8ba8999f34dd0/plot_regression_3d.ipynb b/_downloads/da756e3c91f993fc2ad8ba8999f34dd0/plot_regression_3d.ipynb new file mode 100644 index 000000000..68fe27369 --- /dev/null +++ b/_downloads/da756e3c91f993fc2ad8ba8999f34dd0/plot_regression_3d.ipynb @@ -0,0 +1,79 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Multiple Regression\n\nCalculate using 'statsmodels' just the best fit, or all the corresponding\nstatistical parameters.\n\nAlso shows how to make 3d plots.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Original author: Thomas Haslwanter\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas\n\n# For 3d plots. This import is necessary to have 3D plotting below\nfrom mpl_toolkits.mplot3d import Axes3D\n\n# For statistics. Requires statsmodels 5.0 or more\nfrom statsmodels.formula.api import ols\n\n# Analysis of Variance (ANOVA) on linear models\nfrom statsmodels.stats.anova import anova_lm" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Generate and show the data\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "x = np.linspace(-5, 5, 21)\n# We generate a 2D grid\nX, Y = np.meshgrid(x, x)\n\n# To get reproducible values, provide a seed value\nrng = np.random.default_rng(27446968)\n\n# Z is the elevation of this 2D grid\nZ = -5 + 3 * X - 0.5 * Y + 8 * np.random.normal(size=X.shape)\n\n# Plot the data\nax: Axes3D = plt.figure().add_subplot(projection=\"3d\")\nsurf = ax.plot_surface(X, Y, Z, cmap=\"coolwarm\", rstride=1, cstride=1)\nax.view_init(20, -120)\nax.set_xlabel(\"X\")\nax.set_ylabel(\"Y\")\nax.set_zlabel(\"Z\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Multilinear regression model, calculating fit, P-values, confidence\nintervals etc.\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Convert the data into a Pandas DataFrame to use the formulas framework\n# in statsmodels\n\n# First we need to flatten the data: it's 2D layout is not relevant.\nX = X.flatten()\nY = Y.flatten()\nZ = Z.flatten()\n\ndata = pandas.DataFrame({\"x\": X, \"y\": Y, \"z\": Z})\n\n# Fit the model\nmodel = ols(\"z ~ x + y\", data).fit()\n\n# Print the summary\nprint(model.summary())\n\nprint(\"\\nRetrieving manually the parameter estimates:\")\nprint(model._results.params)\n# should be array([-4.99754526, 3.00250049, -0.50514907])\n\n# Perform analysis of variance on fitted linear model\nanova_results = anova_lm(model)\n\nprint(\"\\nANOVA results\")\nprint(anova_results)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/dacfe65583ff8dac5bca5227d08359b0/plot_features.zip b/_downloads/dacfe65583ff8dac5bca5227d08359b0/plot_features.zip new file mode 100644 index 000000000..78854c22f Binary files /dev/null and b/_downloads/dacfe65583ff8dac5bca5227d08359b0/plot_features.zip differ diff --git a/_downloads/db8e02e15565785a5bb5806ca000306c/plot_exercise_4.ipynb b/_downloads/db8e02e15565785a5bb5806ca000306c/plot_exercise_4.ipynb new file mode 100644 index 000000000..fbc160746 --- /dev/null +++ b/_downloads/db8e02e15565785a5bb5806ca000306c/plot_exercise_4.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Exercise 4\n\nExercise 4 with matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(8, 5), dpi=80)\nplt.subplot(111)\n\nX = np.linspace(-np.pi, np.pi, 256)\nS = np.sin(X)\nC = np.cos(X)\n\nplt.plot(X, C, color=\"blue\", linewidth=2.5, linestyle=\"-\")\nplt.plot(X, S, color=\"red\", linewidth=2.5, linestyle=\"-\")\n\nplt.xlim(X.min() * 1.1, X.max() * 1.1)\nplt.ylim(C.min() * 1.1, C.max() * 1.1)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/dc6b17d2f9b1031f1295846cb20dac90/plot_exercise_9.py b/_downloads/dc6b17d2f9b1031f1295846cb20dac90/plot_exercise_9.py new file mode 100644 index 000000000..58fb21725 --- /dev/null +++ b/_downloads/dc6b17d2f9b1031f1295846cb20dac90/plot_exercise_9.py @@ -0,0 +1,83 @@ +""" +Exercise 9 +========== + +Exercise 9 with matplotlib. +""" + +import numpy as np +import matplotlib.pyplot as plt + +plt.figure(figsize=(8, 5), dpi=80) +plt.subplot(111) + +X = np.linspace(-np.pi, np.pi, 256, endpoint=True) +C = np.cos(X) +S = np.sin(X) + +plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine") +plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine") + +ax = plt.gca() +ax.spines["right"].set_color("none") +ax.spines["top"].set_color("none") +ax.xaxis.set_ticks_position("bottom") +ax.spines["bottom"].set_position(("data", 0)) +ax.yaxis.set_ticks_position("left") +ax.spines["left"].set_position(("data", 0)) + +plt.xlim(X.min() * 1.1, X.max() * 1.1) +plt.xticks( + [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], + [r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"], +) + +plt.ylim(C.min() * 1.1, C.max() * 1.1) +plt.yticks([-1, +1], [r"$-1$", r"$+1$"]) + +t = 2 * np.pi / 3 +plt.plot([t, t], [0, np.cos(t)], color="blue", linewidth=1.5, linestyle="--") +plt.scatter( + [ + t, + ], + [ + np.cos(t), + ], + 50, + color="blue", +) +plt.annotate( + r"$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$", + xy=(t, np.sin(t)), + xycoords="data", + xytext=(+10, +30), + textcoords="offset points", + fontsize=16, + arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=.2"}, +) + +plt.plot([t, t], [0, np.sin(t)], color="red", linewidth=1.5, linestyle="--") +plt.scatter( + [ + t, + ], + [ + np.sin(t), + ], + 50, + color="red", +) +plt.annotate( + r"$cos(\frac{2\pi}{3})=-\frac{1}{2}$", + xy=(t, np.cos(t)), + xycoords="data", + xytext=(-90, -50), + textcoords="offset points", + fontsize=16, + arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=.2"}, +) + +plt.legend(loc="upper left") + +plt.show() diff --git a/_downloads/dccc75ba2cb5bab589c12062eb2f8f20/plot_ML_flow_chart.ipynb b/_downloads/dccc75ba2cb5bab589c12062eb2f8f20/plot_ML_flow_chart.ipynb new file mode 100644 index 000000000..6070f0b9c --- /dev/null +++ b/_downloads/dccc75ba2cb5bab589c12062eb2f8f20/plot_ML_flow_chart.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Tutorial Diagrams\n\nThis script plots the flow-charts used in the scikit-learn tutorials.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Circle, Rectangle, Polygon, Arrow, FancyArrow\n\n\ndef create_base(box_bg=\"#CCCCCC\", arrow1=\"#88CCFF\", arrow2=\"#88FF88\", supervised=True):\n fig = plt.figure(figsize=(9, 6), facecolor=\"w\")\n ax = plt.axes((0, 0, 1, 1), xticks=[], yticks=[], frameon=False)\n ax.set_xlim(0, 9)\n ax.set_ylim(0, 6)\n\n patches = [\n Rectangle((0.3, 3.6), 1.5, 1.8, zorder=1, fc=box_bg),\n Rectangle((0.5, 3.8), 1.5, 1.8, zorder=2, fc=box_bg),\n Rectangle((0.7, 4.0), 1.5, 1.8, zorder=3, fc=box_bg),\n Rectangle((2.9, 3.6), 0.2, 1.8, fc=box_bg),\n Rectangle((3.1, 3.8), 0.2, 1.8, fc=box_bg),\n Rectangle((3.3, 4.0), 0.2, 1.8, fc=box_bg),\n Rectangle((0.3, 0.2), 1.5, 1.8, fc=box_bg),\n Rectangle((2.9, 0.2), 0.2, 1.8, fc=box_bg),\n Circle((5.5, 3.5), 1.0, fc=box_bg),\n Polygon([[5.5, 1.7], [6.1, 1.1], [5.5, 0.5], [4.9, 1.1]], fc=box_bg),\n FancyArrow(\n 2.3, 4.6, 0.35, 0, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2\n ),\n FancyArrow(\n 3.75, 4.2, 0.5, -0.2, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2\n ),\n FancyArrow(\n 5.5, 2.4, 0, -0.4, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2\n ),\n FancyArrow(\n 2.0, 1.1, 0.5, 0, fc=arrow2, width=0.25, head_width=0.5, head_length=0.2\n ),\n FancyArrow(\n 3.3, 1.1, 1.3, 0, fc=arrow2, width=0.25, head_width=0.5, head_length=0.2\n ),\n FancyArrow(\n 6.2, 1.1, 0.8, 0, fc=arrow2, width=0.25, head_width=0.5, head_length=0.2\n ),\n ]\n\n if supervised:\n patches += [\n Rectangle((0.3, 2.4), 1.5, 0.5, zorder=1, fc=box_bg),\n Rectangle((0.5, 2.6), 1.5, 0.5, zorder=2, fc=box_bg),\n Rectangle((0.7, 2.8), 1.5, 0.5, zorder=3, fc=box_bg),\n FancyArrow(\n 2.3, 2.9, 2.0, 0, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2\n ),\n Rectangle((7.3, 0.85), 1.5, 0.5, fc=box_bg),\n ]\n else:\n patches += [Rectangle((7.3, 0.2), 1.5, 1.8, fc=box_bg)]\n\n for p in patches:\n ax.add_patch(p)\n\n plt.text(\n 1.45,\n 4.9,\n \"Training\\nText,\\nDocuments,\\nImages,\\netc.\",\n ha=\"center\",\n va=\"center\",\n fontsize=14,\n )\n\n plt.text(3.6, 4.9, \"Feature\\nVectors\", ha=\"left\", va=\"center\", fontsize=14)\n\n plt.text(\n 5.5, 3.5, \"Machine\\nLearning\\nAlgorithm\", ha=\"center\", va=\"center\", fontsize=14\n )\n\n plt.text(\n 1.05,\n 1.1,\n \"New Text,\\nDocument,\\nImage,\\netc.\",\n ha=\"center\",\n va=\"center\",\n fontsize=14,\n )\n\n plt.text(3.3, 1.7, \"Feature\\nVector\", ha=\"left\", va=\"center\", fontsize=14)\n\n plt.text(5.5, 1.1, \"Predictive\\nModel\", ha=\"center\", va=\"center\", fontsize=12)\n\n if supervised:\n plt.text(1.45, 3.05, \"Labels\", ha=\"center\", va=\"center\", fontsize=14)\n\n plt.text(8.05, 1.1, \"Expected\\nLabel\", ha=\"center\", va=\"center\", fontsize=14)\n plt.text(\n 8.8, 5.8, \"Supervised Learning Model\", ha=\"right\", va=\"top\", fontsize=18\n )\n\n else:\n plt.text(\n 8.05,\n 1.1,\n \"Likelihood\\nor Cluster ID\\nor Better\\nRepresentation\",\n ha=\"center\",\n va=\"center\",\n fontsize=12,\n )\n plt.text(\n 8.8, 5.8, \"Unsupervised Learning Model\", ha=\"right\", va=\"top\", fontsize=18\n )\n\n\ndef plot_supervised_chart(annotate=False):\n create_base(supervised=True)\n if annotate:\n fontdict = {\"color\": \"r\", \"weight\": \"bold\", \"size\": 14}\n plt.text(\n 1.9,\n 4.55,\n \"X = vec.fit_transform(input)\",\n fontdict=fontdict,\n rotation=20,\n ha=\"left\",\n va=\"bottom\",\n )\n plt.text(\n 3.7,\n 3.2,\n \"clf.fit(X, y)\",\n fontdict=fontdict,\n rotation=20,\n ha=\"left\",\n va=\"bottom\",\n )\n plt.text(\n 1.7,\n 1.5,\n \"X_new = vec.transform(input)\",\n fontdict=fontdict,\n rotation=20,\n ha=\"left\",\n va=\"bottom\",\n )\n plt.text(\n 6.1,\n 1.5,\n \"y_new = clf.predict(X_new)\",\n fontdict=fontdict,\n rotation=20,\n ha=\"left\",\n va=\"bottom\",\n )\n\n\ndef plot_unsupervised_chart():\n create_base(supervised=False)\n\n\nif __name__ == \"__main__\":\n plot_supervised_chart(False)\n plot_supervised_chart(True)\n plot_unsupervised_chart()\n plt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/dd2d00f22e1036d3c16c8a2471b7804e/plot_airfare.zip b/_downloads/dd2d00f22e1036d3c16c8a2471b7804e/plot_airfare.zip new file mode 100644 index 000000000..75e9537de Binary files /dev/null and b/_downloads/dd2d00f22e1036d3c16c8a2471b7804e/plot_airfare.zip differ diff --git a/_downloads/ddedd798cae54d7ec84a01f9a7b2783e/plot_iris_scatter.zip b/_downloads/ddedd798cae54d7ec84a01f9a7b2783e/plot_iris_scatter.zip new file mode 100644 index 000000000..ee085c1d5 Binary files /dev/null and b/_downloads/ddedd798cae54d7ec84a01f9a7b2783e/plot_iris_scatter.zip differ diff --git a/_downloads/de87f70e68be15b20dbcec53a68d0367/plot_check.zip b/_downloads/de87f70e68be15b20dbcec53a68d0367/plot_check.zip new file mode 100644 index 000000000..174bbe4fc Binary files /dev/null and b/_downloads/de87f70e68be15b20dbcec53a68d0367/plot_check.zip differ diff --git a/_downloads/df455c46ef277671fa87a7c56279fffc/plot_paired_boxplots.py b/_downloads/df455c46ef277671fa87a7c56279fffc/plot_paired_boxplots.py new file mode 100644 index 000000000..cfcd0fc74 --- /dev/null +++ b/_downloads/df455c46ef277671fa87a7c56279fffc/plot_paired_boxplots.py @@ -0,0 +1,28 @@ +""" +Boxplots and paired differences +================================================= + +Plot boxplots for FSIQ, PIQ, and the paired difference between the two: +while the spread (error bars) for FSIQ and PIQ are very large, there is a +systematic (common) effect due to the subjects. This effect is cancelled +out in the difference and the spread of the difference ("paired" by +subject) is much smaller than the spread of the individual measures. + +""" + +import pandas + +import matplotlib.pyplot as plt + +data = pandas.read_csv("brain_size.csv", sep=";", na_values=".") + +# Box plot of FSIQ and PIQ (different measures od IQ) +plt.figure(figsize=(4, 3)) +data.boxplot(column=["FSIQ", "PIQ"]) + +# Boxplot of the difference +plt.figure(figsize=(4, 3)) +plt.boxplot(data["FSIQ"] - data["PIQ"]) +plt.xticks((1,), ("FSIQ - PIQ",)) + +plt.show() diff --git a/_downloads/df6923ee4446add42a246da44204a875/plot_polyfit.ipynb b/_downloads/df6923ee4446add42a246da44204a875/plot_polyfit.ipynb new file mode 100644 index 000000000..c7e1c6149 --- /dev/null +++ b/_downloads/df6923ee4446add42a246da44204a875/plot_polyfit.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Fitting to polynomial\n\nPlot noisy data and their polynomial fit\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nrng = np.random.default_rng(27446968)\n\nx = np.linspace(0, 1, 20)\ny = np.cos(x) + 0.3 * rng.random(20)\np = np.poly1d(np.polyfit(x, y, 3))\n\nt = np.linspace(0, 1, 200)\nplt.plot(x, y, \"o\", t, p(t), \"-\")\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/dfa1e4a8f2c6697083fd7014698b97da/plot_gumbell_wind_speed_prediction.py b/_downloads/dfa1e4a8f2c6697083fd7014698b97da/plot_gumbell_wind_speed_prediction.py new file mode 100644 index 000000000..a632610b0 --- /dev/null +++ b/_downloads/dfa1e4a8f2c6697083fd7014698b97da/plot_gumbell_wind_speed_prediction.py @@ -0,0 +1,39 @@ +""" +The Gumbell distribution +========================= + +Generate the exercise results on the Gumbell distribution +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + + +def gumbell_dist(arr): + return -np.log(-np.log(arr)) + + +years_nb = 21 +wspeeds = np.load("sprog-windspeeds.npy") +max_speeds = np.array([arr.max() for arr in np.array_split(wspeeds, years_nb)]) +sorted_max_speeds = np.sort(max_speeds) + +cprob = (np.arange(years_nb, dtype=np.float32) + 1) / (years_nb + 1) +gprob = gumbell_dist(cprob) +speed_spline = sp.interpolate.UnivariateSpline(gprob, sorted_max_speeds, k=1) +nprob = gumbell_dist(np.linspace(1e-3, 1 - 1e-3, 100)) +fitted_max_speeds = speed_spline(nprob) + +fifty_prob = gumbell_dist(49.0 / 50.0) +fifty_wind = speed_spline(fifty_prob) + +plt.figure() +plt.plot(sorted_max_speeds, gprob, "o") +plt.plot(fitted_max_speeds, nprob, "g--") +plt.plot([fifty_wind], [fifty_prob], "o", ms=8.0, mfc="y", mec="y") +plt.plot([fifty_wind, fifty_wind], [plt.axis()[2], fifty_prob], "k--") +plt.text(35, -1, rf"$V_{{50}} = {fifty_wind:.2f} \, m/s$") +plt.xlabel("Annual wind speed maxima [$m/s$]") +plt.ylabel("Gumbell cumulative probability") +plt.show() diff --git a/_downloads/dfd49df3a3311e8a46692a04ab4a03ec/plot_optimize_lidar_complex_data_fit.zip b/_downloads/dfd49df3a3311e8a46692a04ab4a03ec/plot_optimize_lidar_complex_data_fit.zip new file mode 100644 index 000000000..a8e16ffbd Binary files /dev/null and b/_downloads/dfd49df3a3311e8a46692a04ab4a03ec/plot_optimize_lidar_complex_data_fit.zip differ diff --git a/_downloads/e013bb3ccf7b0cf427e58300b4427207/plot_measure_data.zip b/_downloads/e013bb3ccf7b0cf427e58300b4427207/plot_measure_data.zip new file mode 100644 index 000000000..0c8fe6c61 Binary files /dev/null and b/_downloads/e013bb3ccf7b0cf427e58300b4427207/plot_measure_data.zip differ diff --git a/_downloads/e013bc5e4e44f6d9204ca06bba142047/plot_image_blur.zip b/_downloads/e013bc5e4e44f6d9204ca06bba142047/plot_image_blur.zip new file mode 100644 index 000000000..e0d6f754e Binary files /dev/null and b/_downloads/e013bc5e4e44f6d9204ca06bba142047/plot_image_blur.zip differ diff --git a/_downloads/e0a9f1dee6915fc69085ab3cd15a65c7/plot_dash_capstyle.zip b/_downloads/e0a9f1dee6915fc69085ab3cd15a65c7/plot_dash_capstyle.zip new file mode 100644 index 000000000..88c86a866 Binary files /dev/null and b/_downloads/e0a9f1dee6915fc69085ab3cd15a65c7/plot_dash_capstyle.zip differ diff --git a/_downloads/e2da317e51eaf42911b4c79427e05ed3/plot_equalize_hist.py b/_downloads/e2da317e51eaf42911b4c79427e05ed3/plot_equalize_hist.py new file mode 100644 index 000000000..9696b5e1c --- /dev/null +++ b/_downloads/e2da317e51eaf42911b4c79427e05ed3/plot_equalize_hist.py @@ -0,0 +1,23 @@ +""" +Equalizing the histogram of an image +===================================== + +Histogram equalizing makes images have a uniform histogram. +""" + +from skimage import data, exposure +import matplotlib.pyplot as plt + +camera = data.camera() +camera_equalized = exposure.equalize_hist(camera) + +plt.figure(figsize=(7, 3)) + +plt.subplot(121) +plt.imshow(camera, cmap="gray", interpolation="nearest") +plt.axis("off") +plt.subplot(122) +plt.imshow(camera_equalized, cmap="gray", interpolation="nearest") +plt.axis("off") +plt.tight_layout() +plt.show() diff --git a/_downloads/e383de81be8ade5dfe9875c794dc12b9/plot_wage_education_gender.zip b/_downloads/e383de81be8ade5dfe9875c794dc12b9/plot_wage_education_gender.zip new file mode 100644 index 000000000..4a28236a8 Binary files /dev/null and b/_downloads/e383de81be8ade5dfe9875c794dc12b9/plot_wage_education_gender.zip differ diff --git a/_downloads/e3bea99ef462c0b72c3f077143a3cf77/plot_measuring_performance.ipynb b/_downloads/e3bea99ef462c0b72c3f077143a3cf77/plot_measuring_performance.ipynb new file mode 100644 index 000000000..776a1f69e --- /dev/null +++ b/_downloads/e3bea99ef462c0b72c3f077143a3cf77/plot_measuring_performance.ipynb @@ -0,0 +1,93 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Measuring Decision Tree performance\n\nDemonstrates overfit when testing on train set.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Get the data\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.datasets import fetch_california_housing\n\ndata = fetch_california_housing(as_frame=True)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Train and test a model\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.tree import DecisionTreeRegressor\n\nclf = DecisionTreeRegressor().fit(data.data, data.target)\n\npredicted = clf.predict(data.data)\nexpected = data.target" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Plot predicted as a function of expected\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nplt.figure(figsize=(4, 3))\nplt.scatter(expected, predicted)\nplt.plot([0, 5], [0, 5], \"--k\")\nplt.axis(\"tight\")\nplt.xlabel(\"True price ($100k)\")\nplt.ylabel(\"Predicted price ($100k)\")\nplt.tight_layout()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Pretty much no errors!\n\nThis is too good to be true: we are testing the model on the train\ndata, which is not a measure of generalization.\n\n**The results are not valid**\n\n" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/e463b114494fb7e28688fcd24ca17c63/pyamg_with_lobpcg.py b/_downloads/e463b114494fb7e28688fcd24ca17c63/pyamg_with_lobpcg.py new file mode 100644 index 000000000..5713a4c29 --- /dev/null +++ b/_downloads/e463b114494fb7e28688fcd24ca17c63/pyamg_with_lobpcg.py @@ -0,0 +1,43 @@ +""" +Compute eigenvectors and eigenvalues using a preconditioned eigensolver +======================================================================= + +In this example Smoothed Aggregation (SA) is used to precondition +the LOBPCG eigensolver on a two-dimensional Poisson problem with +Dirichlet boundary conditions. +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +from pyamg import smoothed_aggregation_solver +from pyamg.gallery import poisson + +N = 100 +K = 9 +A = poisson((N, N), format="csr") + +# create the AMG hierarchy +ml = smoothed_aggregation_solver(A) + +# initial approximation to the K eigenvectors +X = np.random.random((A.shape[0], K)) + +# preconditioner based on ml +M = ml.aspreconditioner() + +# compute eigenvalues and eigenvectors with LOBPCG +W, V = sp.sparse.linalg.lobpcg(A, X, M=M, tol=1e-8, largest=False) + + +# plot the eigenvectors +plt.figure(figsize=(9, 9)) + +for i in range(K): + plt.subplot(3, 3, i + 1) + plt.title("Eigenvector %d" % i) + plt.pcolor(V[:, i].reshape(N, N)) + plt.axis("equal") + plt.axis("off") +plt.show() diff --git a/_downloads/e55096112c1bd77de716f744b83a2581/plot_GMM.ipynb b/_downloads/e55096112c1bd77de716f744b83a2581/plot_GMM.ipynb new file mode 100644 index 000000000..2f4962857 --- /dev/null +++ b/_downloads/e55096112c1bd77de716f744b83a2581/plot_GMM.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Segmentation with Gaussian mixture models\n\nThis example performs a Gaussian mixture model analysis of the image\nhistogram to find the right thresholds for separating foreground from\nbackground.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\nfrom sklearn.mixture import GaussianMixture\n\nrng = np.random.default_rng(27446968)\nn = 10\nl = 256\nim = np.zeros((l, l))\npoints = l * rng.random((2, n**2))\nim[(points[0]).astype(int), (points[1]).astype(int)] = 1\nim = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n))\n\nmask = (im > im.mean()).astype(float)\n\n\nimg = mask + 0.3 * rng.normal(size=mask.shape)\n\nhist, bin_edges = np.histogram(img, bins=60)\nbin_centers = 0.5 * (bin_edges[:-1] + bin_edges[1:])\n\nclassif = GaussianMixture(n_components=2)\nclassif.fit(img.reshape((img.size, 1)))\n\nthreshold = np.mean(classif.means_)\nbinary_img = img > threshold\n\n\nplt.figure(figsize=(11, 4))\n\nplt.subplot(131)\nplt.imshow(img)\nplt.axis(\"off\")\nplt.subplot(132)\nplt.plot(bin_centers, hist, lw=2)\nplt.axvline(0.5, color=\"r\", ls=\"--\", lw=2)\nplt.text(0.57, 0.8, \"histogram\", fontsize=20, transform=plt.gca().transAxes)\nplt.yticks([])\nplt.subplot(133)\nplt.imshow(binary_img, cmap=\"gray\", interpolation=\"nearest\")\nplt.axis(\"off\")\n\nplt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1)\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/e5511af4715dd76a98444f7606713950/plot_alpha.ipynb b/_downloads/e5511af4715dd76a98444f7606713950/plot_alpha.ipynb new file mode 100644 index 000000000..cb97a5d76 --- /dev/null +++ b/_downloads/e5511af4715dd76a98444f7606713950/plot_alpha.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Alpha: transparency\n\nThis example demonstrates using alpha for transparency.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nsize = 256, 16\ndpi = 72.0\nfigsize = size[0] / float(dpi), size[1] / float(dpi)\nfig = plt.figure(figsize=figsize, dpi=dpi)\nfig.patch.set_alpha(0)\nplt.axes((0, 0.1, 1, 0.8), frameon=False)\n\nfor i in range(1, 11):\n plt.axvline(i, linewidth=1, color=\"blue\", alpha=0.25 + 0.75 * i / 10.0)\n\nplt.xlim(0, 11)\nplt.xticks([])\nplt.yticks([])\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/e565049c60c3ed3bdbbc365917d4a637/plot_noisy.zip b/_downloads/e565049c60c3ed3bdbbc365917d4a637/plot_noisy.zip new file mode 100644 index 000000000..27af1fbb3 Binary files /dev/null and b/_downloads/e565049c60c3ed3bdbbc365917d4a637/plot_noisy.zip differ diff --git a/_downloads/e56a0928f37c85e2d97b2b710d2d7a8b/plot_optimize_lidar_data_fit.zip b/_downloads/e56a0928f37c85e2d97b2b710d2d7a8b/plot_optimize_lidar_data_fit.zip new file mode 100644 index 000000000..b044dd018 Binary files /dev/null and b/_downloads/e56a0928f37c85e2d97b2b710d2d7a8b/plot_optimize_lidar_data_fit.zip differ diff --git a/_downloads/e6a7581098b9d5b1d1b4b19eff09e05c/plot_face_tv_denoise.zip b/_downloads/e6a7581098b9d5b1d1b4b19eff09e05c/plot_face_tv_denoise.zip new file mode 100644 index 000000000..9f57174dc Binary files /dev/null and b/_downloads/e6a7581098b9d5b1d1b4b19eff09e05c/plot_face_tv_denoise.zip differ diff --git a/_downloads/e72cc8b7f824a5c2263f0fd68584b5ae/plot_plot.zip b/_downloads/e72cc8b7f824a5c2263f0fd68584b5ae/plot_plot.zip new file mode 100644 index 000000000..53eeca447 Binary files /dev/null and b/_downloads/e72cc8b7f824a5c2263f0fd68584b5ae/plot_plot.zip differ diff --git a/_downloads/e78d9d46983461222b331afd9cba8b99/plot_ticks.py b/_downloads/e78d9d46983461222b331afd9cba8b99/plot_ticks.py new file mode 100644 index 000000000..9bb7baae0 --- /dev/null +++ b/_downloads/e78d9d46983461222b331afd9cba8b99/plot_ticks.py @@ -0,0 +1,55 @@ +""" +Locators for tick on axis +========================== + +An example demoing different locators to position ticks on axis for +matplotlib. +""" + +import numpy as np + +from matplotlib import ticker +import matplotlib.pyplot as plt + + +def tickline(): + plt.xlim(0, 10), plt.ylim(-1, 1), plt.yticks([]) + ax = plt.gca() + ax.spines["right"].set_color("none") + ax.spines["left"].set_color("none") + ax.spines["top"].set_color("none") + ax.xaxis.set_ticks_position("bottom") + ax.spines["bottom"].set_position(("data", 0)) + ax.yaxis.set_ticks_position("none") + ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.1)) + ax.plot(np.arange(11), np.zeros(11)) + return ax + + +locators = [ + "ticker.NullLocator()", + "ticker.MultipleLocator(1.0)", + "ticker.FixedLocator([0, 2, 8, 9, 10])", + "ticker.IndexLocator(3, 1)", + "ticker.LinearLocator(5)", + "ticker.LogLocator(2, [1.0])", + "ticker.AutoLocator()", +] + +n_locators = len(locators) + +size = 512, 40 * n_locators +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = plt.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) + + +for i, locator in enumerate(locators): + plt.subplot(n_locators, 1, i + 1) + ax = tickline() + ax.xaxis.set_major_locator(eval(locator)) + plt.text(5, 0.3, locator[7:], ha="center") + +plt.subplots_adjust(bottom=0.01, top=0.99, left=0.01, right=0.99) +plt.show() diff --git a/_downloads/e79a0d11052db69c3ff58eb6381c67da/plot_multiplot.zip b/_downloads/e79a0d11052db69c3ff58eb6381c67da/plot_multiplot.zip new file mode 100644 index 000000000..f623272f4 Binary files /dev/null and b/_downloads/e79a0d11052db69c3ff58eb6381c67da/plot_multiplot.zip differ diff --git a/_downloads/e953fd7529ea41c8c900f677583fcf61/plot_bar_ext.ipynb b/_downloads/e953fd7529ea41c8c900f677583fcf61/plot_bar_ext.ipynb new file mode 100644 index 000000000..dfe259021 --- /dev/null +++ b/_downloads/e953fd7529ea41c8c900f677583fcf61/plot_bar_ext.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Bar plot advanced\n\nAn more elaborate bar plot example\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\n\nn = 16\nX = np.arange(n)\nY1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)\nY2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)\nplt.bar(X, Y1, facecolor=\"#9999ff\", edgecolor=\"white\")\nplt.bar(X, -Y2, facecolor=\"#ff9999\", edgecolor=\"white\")\nplt.xlim(-0.5, n)\nplt.xticks([])\nplt.ylim(-1, 1)\nplt.yticks([])\n\n\n# Add a title and a box around it\nfrom matplotlib.patches import FancyBboxPatch\n\nax = plt.gca()\nax.add_patch(\n FancyBboxPatch(\n (-0.05, 0.87),\n width=0.66,\n height=0.165,\n clip_on=False,\n boxstyle=\"square,pad=0\",\n zorder=3,\n facecolor=\"white\",\n alpha=1.0,\n transform=plt.gca().transAxes,\n )\n)\n\nplt.text(\n -0.05,\n 1.02,\n \" Bar Plot: plt.bar(...)\\n\",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"xx-large\",\n transform=plt.gca().transAxes,\n)\n\nplt.text(\n -0.05,\n 1.01,\n \"\\n\\n Make a bar plot with rectangles \",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"large\",\n transform=plt.gca().transAxes,\n)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/e9a75528b96af5e372f609ca1c41bbe4/plot_subplot-grid.ipynb b/_downloads/e9a75528b96af5e372f609ca1c41bbe4/plot_subplot-grid.ipynb new file mode 100644 index 000000000..ada5e216d --- /dev/null +++ b/_downloads/e9a75528b96af5e372f609ca1c41bbe4/plot_subplot-grid.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Subplot grid\n\nAn example showing the subplot grid in matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nplt.figure(figsize=(6, 4))\nplt.subplot(2, 2, 1)\nplt.xticks([])\nplt.yticks([])\nplt.text(0.5, 0.5, \"subplot(2,2,1)\", ha=\"center\", va=\"center\", size=20, alpha=0.5)\n\nplt.subplot(2, 2, 2)\nplt.xticks([])\nplt.yticks([])\nplt.text(0.5, 0.5, \"subplot(2,2,2)\", ha=\"center\", va=\"center\", size=20, alpha=0.5)\n\nplt.subplot(2, 2, 3)\nplt.xticks([])\nplt.yticks([])\n\nplt.text(0.5, 0.5, \"subplot(2,2,3)\", ha=\"center\", va=\"center\", size=20, alpha=0.5)\n\nplt.subplot(2, 2, 4)\nplt.xticks([])\nplt.yticks([])\nplt.text(0.5, 0.5, \"subplot(2,2,4)\", ha=\"center\", va=\"center\", size=20, alpha=0.5)\n\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/ead7a1f32a1dc4b57d558be16fd34e6a/plot_sobel.py b/_downloads/ead7a1f32a1dc4b57d558be16fd34e6a/plot_sobel.py new file mode 100644 index 000000000..c1d7a3195 --- /dev/null +++ b/_downloads/ead7a1f32a1dc4b57d558be16fd34e6a/plot_sobel.py @@ -0,0 +1,25 @@ +""" +Computing horizontal gradients with the Sobel filter +===================================================== + +This example illustrates the use of the horizontal Sobel filter, to compute +horizontal gradients. +""" + +from skimage import data +from skimage import filters +import matplotlib.pyplot as plt + +text = data.text() +hsobel_text = filters.sobel_h(text) + +plt.figure(figsize=(12, 3)) + +plt.subplot(121) +plt.imshow(text, cmap="gray", interpolation="nearest") +plt.axis("off") +plt.subplot(122) +plt.imshow(hsobel_text, cmap="nipy_spectral", interpolation="nearest") +plt.axis("off") +plt.tight_layout() +plt.show() diff --git a/_downloads/eafa0bdd2c50265bf12a82e8d776a8f2/plot_spectral_clustering.py b/_downloads/eafa0bdd2c50265bf12a82e8d776a8f2/plot_spectral_clustering.py new file mode 100644 index 000000000..69d58341e --- /dev/null +++ b/_downloads/eafa0bdd2c50265bf12a82e8d776a8f2/plot_spectral_clustering.py @@ -0,0 +1,62 @@ +""" +Segmentation with spectral clustering +====================================== + +This example uses spectral clustering to do segmentation. +""" + +import numpy as np +import matplotlib.pyplot as plt + +from sklearn.feature_extraction import image +from sklearn.cluster import spectral_clustering + +################################################################################ +l = 100 +x, y = np.indices((l, l)) + +center1 = (28, 24) +center2 = (40, 50) +center3 = (67, 58) +center4 = (24, 70) + +radius1, radius2, radius3, radius4 = 16, 14, 15, 14 + +circle1 = (x - center1[0]) ** 2 + (y - center1[1]) ** 2 < radius1**2 +circle2 = (x - center2[0]) ** 2 + (y - center2[1]) ** 2 < radius2**2 +circle3 = (x - center3[0]) ** 2 + (y - center3[1]) ** 2 < radius3**2 +circle4 = (x - center4[0]) ** 2 + (y - center4[1]) ** 2 < radius4**2 + +################################################################################ +# 4 circles +img = circle1 + circle2 + circle3 + circle4 +mask = img.astype(bool) +img = img.astype(float) + +rng = np.random.default_rng(27446968) +img += 1 + 0.2 * rng.normal(size=img.shape) + +# Convert the image into a graph with the value of the gradient on the +# edges. +graph = image.img_to_graph(img, mask=mask) + +# Take a decreasing function of the gradient: we take it weakly +# dependent from the gradient the segmentation is close to a voronoi +graph.data = np.exp(-graph.data / graph.data.std()) + +# Force the solver to be arpack, since amg is numerically +# unstable on this example +labels = spectral_clustering(graph, n_clusters=4) +label_im = -np.ones(mask.shape) +label_im[mask] = labels + +plt.figure(figsize=(6, 3)) +plt.subplot(121) +plt.imshow(img, cmap="nipy_spectral", interpolation="nearest") +plt.axis("off") +plt.subplot(122) +plt.imshow(label_im, cmap="nipy_spectral", interpolation="nearest") +plt.axis("off") + +plt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.01, right=0.99) +plt.show() diff --git a/_downloads/eb076796d0dc9974f567d9396ac673fd/plot_california_prediction.ipynb b/_downloads/eb076796d0dc9974f567d9396ac673fd/plot_california_prediction.ipynb new file mode 100644 index 000000000..d247c6ba0 --- /dev/null +++ b/_downloads/eb076796d0dc9974f567d9396ac673fd/plot_california_prediction.ipynb @@ -0,0 +1,133 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# A simple regression analysis on the California housing data\n\nHere we perform a simple regression analysis on the California housing\ndata, exploring two types of regressors.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.datasets import fetch_california_housing\n\ndata = fetch_california_housing(as_frame=True)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Print a histogram of the quantity to predict: price\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nplt.figure(figsize=(4, 3))\nplt.hist(data.target)\nplt.xlabel(\"price ($100k)\")\nplt.ylabel(\"count\")\nplt.tight_layout()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Print the join histogram for each feature\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "for index, feature_name in enumerate(data.feature_names):\n plt.figure(figsize=(4, 3))\n plt.scatter(data.data[feature_name], data.target)\n plt.ylabel(\"Price\", size=15)\n plt.xlabel(feature_name, size=15)\n plt.tight_layout()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Simple prediction\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(data.data, data.target)\n\nfrom sklearn.linear_model import LinearRegression\n\nclf = LinearRegression()\nclf.fit(X_train, y_train)\npredicted = clf.predict(X_test)\nexpected = y_test\n\nplt.figure(figsize=(4, 3))\nplt.scatter(expected, predicted)\nplt.plot([0, 8], [0, 8], \"--k\")\nplt.axis(\"tight\")\nplt.xlabel(\"True price ($100k)\")\nplt.ylabel(\"Predicted price ($100k)\")\nplt.tight_layout()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Prediction with gradient boosted tree\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.ensemble import GradientBoostingRegressor\n\nclf = GradientBoostingRegressor()\nclf.fit(X_train, y_train)\n\npredicted = clf.predict(X_test)\nexpected = y_test\n\nplt.figure(figsize=(4, 3))\nplt.scatter(expected, predicted)\nplt.plot([0, 5], [0, 5], \"--k\")\nplt.axis(\"tight\")\nplt.xlabel(\"True price ($100k)\")\nplt.ylabel(\"Predicted price ($100k)\")\nplt.tight_layout()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Print the error rate\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n\nprint(f\"RMS: {np.sqrt(np.mean((predicted - expected) ** 2))!r} \")\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/eb5ebae5ddd986b54f929ada90b3b83a/2_3_crude_integration.py b/_downloads/eb5ebae5ddd986b54f929ada90b3b83a/2_3_crude_integration.py new file mode 100644 index 000000000..8c548822e --- /dev/null +++ b/_downloads/eb5ebae5ddd986b54f929ada90b3b83a/2_3_crude_integration.py @@ -0,0 +1,23 @@ +import numpy as np +from numpy import newaxis + + +def f(a, b, c): + return a**b - c + + +a = np.linspace(0, 1, 24) +b = np.linspace(0, 1, 12) +c = np.linspace(0, 1, 6) + +samples = f(a[:, newaxis, newaxis], b[newaxis, :, newaxis], c[newaxis, newaxis, :]) + +# or, +# +# a, b, c = np.ogrid[0:1:24j, 0:1:12j, 0:1:6j] +# samples = f(a, b, c) + +integral = samples.mean() + +print("Approximation:", integral) +print("Exact:", np.log(2) - 0.5) diff --git a/_downloads/ec8bb5ee2970e9e4fbcdca5a87cd0c13/plot_polar_ext.ipynb b/_downloads/ec8bb5ee2970e9e4fbcdca5a87cd0c13/plot_polar_ext.ipynb new file mode 100644 index 000000000..39b7812c3 --- /dev/null +++ b/_downloads/ec8bb5ee2970e9e4fbcdca5a87cd0c13/plot_polar_ext.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plotting in polar, decorated\n\nAn example showing how to plot in polar coordinate, and some\ndecorations.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n\nplt.subplot(1, 1, 1, polar=True)\n\nN = 20\ntheta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N)\nrng = np.random.default_rng()\nradii = 10 * rng.random(N)\nwidth = np.pi / 4 * rng.random(N)\nbars = plt.bar(theta, radii, width=width, bottom=0.0)\njet = matplotlib.colormaps[\"jet\"]\n\nfor r, bar in zip(radii, bars, strict=True):\n bar.set_facecolor(jet(r / 10.0))\n bar.set_alpha(0.5)\nplt.gca().set_xticklabels([])\nplt.gca().set_yticklabels([])\n\n\nplt.text(\n -0.2,\n 1.02,\n \" Polar Axis \\n\",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"xx-large\",\n bbox={\"facecolor\": \"white\", \"alpha\": 1.0},\n transform=plt.gca().transAxes,\n)\n\nplt.text(\n -0.2,\n 1.01,\n \"\\n\\n Plot anything using polar axis \",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n size=\"large\",\n transform=plt.gca().transAxes,\n)\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/ecd37296d6746bfc2a95d6da2743de6d/plot_distances.py b/_downloads/ecd37296d6746bfc2a95d6da2743de6d/plot_distances.py new file mode 100644 index 000000000..f461dde31 --- /dev/null +++ b/_downloads/ecd37296d6746bfc2a95d6da2743de6d/plot_distances.py @@ -0,0 +1,16 @@ +""" +Distances exercise +================== + +Plot distances in a grid + +""" + +import numpy as np +import matplotlib.pyplot as plt + +x, y = np.arange(5), np.arange(5)[:, np.newaxis] +distance = np.sqrt(x**2 + y**2) +plt.pcolor(distance) +plt.colorbar() +plt.show() diff --git a/_downloads/ed20045e54294659125d2789f3ee7cd2/plot_colormaps.zip b/_downloads/ed20045e54294659125d2789f3ee7cd2/plot_colormaps.zip new file mode 100644 index 000000000..2371df214 Binary files /dev/null and b/_downloads/ed20045e54294659125d2789f3ee7cd2/plot_colormaps.zip differ diff --git a/_downloads/ed61849ebbec9bf6ba89e36856c8afa1/segfault.py b/_downloads/ed61849ebbec9bf6ba89e36856c8afa1/segfault.py new file mode 100644 index 000000000..675b701f7 --- /dev/null +++ b/_downloads/ed61849ebbec9bf6ba89e36856c8afa1/segfault.py @@ -0,0 +1,25 @@ +"""Simple code that creates a segfault using numpy. Used to learn +debugging segfaults with GDB. +""" + +import numpy as np +from numpy.lib import stride_tricks + + +def make_big_array(small_array): + big_array = stride_tricks.as_strided( + small_array, shape=(int(2e6), int(2e6)), strides=(32, 32) + ) + return big_array + + +def print_big_array(small_array): + big_array = make_big_array(small_array) + print(big_array[-10:]) + return big_array + + +l = [] +for i in range(10): + a = np.arange(8) + l.append(print_big_array(a)) diff --git a/_downloads/ef045a734dcc8ff40b2d0d6bb35a0c37/gdbinit b/_downloads/ef045a734dcc8ff40b2d0d6bb35a0c37/gdbinit new file mode 100644 index 000000000..247daa483 --- /dev/null +++ b/_downloads/ef045a734dcc8ff40b2d0d6bb35a0c37/gdbinit @@ -0,0 +1,71 @@ +# -*- ksh -*- +# +# If you use the GNU debugger gdb to debug the Python C runtime, you +# might find some of the following commands useful. Copy this to your +# ~/.gdbinit file and it'll get loaded into gdb automatically when you +# start it up. Then, at the gdb prompt you can do things like: +# +# (gdb) pyo apyobjectptr +# +# refcounts: 1 +# address : 84a7a2c +# $1 = void +# (gdb) + +# Prints a representation of the object to stderr, along with the +# number of reference counts it current has and the hex address the +# object is allocated at. The argument must be a PyObject* +define pyo +print _PyObject_Dump($arg0) +end + +# Prints a representation of the object to stderr, along with the +# number of reference counts it current has and the hex address the +# object is allocated at. The argument must be a PyGC_Head* +define pyg +print _PyGC_Dump($arg0) +end + +# A rewrite of the Python interpreter's line number calculator in GDB's +# command language +define lineno + set $__continue = 1 + set $__co = f->f_code + set $__lasti = f->f_lasti + set $__sz = ((PyStringObject *)$__co->co_lnotab)->ob_size/2 + set $__p = (unsigned char *)((PyStringObject *)$__co->co_lnotab)->ob_sval + set $__li = $__co->co_firstlineno + set $__ad = 0 + while ($__sz-1 >= 0 && $__continue) + set $__sz = $__sz - 1 + set $__ad = $__ad + *$__p + set $__p = $__p + 1 + if ($__ad > $__lasti) + set $__continue = 0 + end + set $__li = $__li + *$__p + set $__p = $__p + 1 + end + printf "%d", $__li +end + +define pyframe + set $__fn = (char *)((PyStringObject *)co->co_filename)->ob_sval + set $__n = (char *)((PyStringObject *)co->co_name)->ob_sval + printf "%s (", $__fn + lineno + printf "): %s\n", $__n +### Uncomment these lines when using from within Emacs/XEmacs so it will +### automatically track/display the current Python source line +# printf "%c%c%s:", 032, 032, $__fn +# lineno +# printf ":1\n" +end + +define printframe + if $pc > PyEval_EvalFrameEx && $pc < PyEval_EvalCodeEx + pyframe + else + frame + end +end diff --git a/_downloads/ef4a92843f62ba91846707fe85cd068d/plot_quiver_ext.py b/_downloads/ef4a92843f62ba91846707fe85cd068d/plot_quiver_ext.py new file mode 100644 index 000000000..81d20ea14 --- /dev/null +++ b/_downloads/ef4a92843f62ba91846707fe85cd068d/plot_quiver_ext.py @@ -0,0 +1,65 @@ +""" +Plotting quiver decorated +========================== + +An example showing quiver with decorations. +""" + +import numpy as np +import matplotlib.pyplot as plt + +n = 8 +X, Y = np.mgrid[0:n, 0:n] +T = np.arctan2(Y - n / 2.0, X - n / 2.0) +R = 10 + np.sqrt((Y - n / 2.0) ** 2 + (X - n / 2.0) ** 2) +U, V = R * np.cos(T), R * np.sin(T) + +plt.quiver(X, Y, U, V, R, alpha=0.5) +plt.quiver(X, Y, U, V, edgecolor="k", facecolor="None", linewidth=0.5) + +plt.xlim(-1, n) +plt.xticks([]) +plt.ylim(-1, n) +plt.yticks([]) + + +# Add a title and a box around it +from matplotlib.patches import FancyBboxPatch + +ax = plt.gca() +ax.add_patch( + FancyBboxPatch( + (-0.05, 0.87), + width=0.66, + height=0.165, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) +) + +plt.text( + -0.05, + 1.02, + " Quiver Plot: plt.quiver(...)\n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=plt.gca().transAxes, +) + +plt.text( + -0.05, + 1.01, + "\n\n Plot a 2-D field of arrows ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=plt.gca().transAxes, +) + + +plt.show() diff --git a/_downloads/f05275a94b3a56959ba6d7f69fe027c4/plot_labels.ipynb b/_downloads/f05275a94b3a56959ba6d7f69fe027c4/plot_labels.ipynb new file mode 100644 index 000000000..fb86f1578 --- /dev/null +++ b/_downloads/f05275a94b3a56959ba6d7f69fe027c4/plot_labels.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Labelling connected components of an image\n\nThis example shows how to label connected components of a binary image, using\nthe dedicated skimage.measure.label function.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from skimage import measure\nfrom skimage import filters\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nn = 12\nl = 256\nrng = np.random.default_rng(27446968)\nim = np.zeros((l, l))\npoints = l * rng.random((2, n**2))\nim[(points[0]).astype(int), (points[1]).astype(int)] = 1\nim = filters.gaussian(im, sigma=l / (4.0 * n))\nblobs = im > 0.7 * im.mean()\n\nall_labels = measure.label(blobs)\nblobs_labels = measure.label(blobs, background=0)\n\nplt.figure(figsize=(9, 3.5))\nplt.subplot(131)\nplt.imshow(blobs, cmap=\"gray\")\nplt.axis(\"off\")\nplt.subplot(132)\nplt.imshow(all_labels, cmap=\"nipy_spectral\")\nplt.axis(\"off\")\nplt.subplot(133)\nplt.imshow(blobs_labels, cmap=\"nipy_spectral\")\nplt.axis(\"off\")\n\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/f0c2480708e8f088b8cecc1a46350c8f/plot_aliased.ipynb b/_downloads/f0c2480708e8f088b8cecc1a46350c8f/plot_aliased.ipynb new file mode 100644 index 000000000..cd44f558a --- /dev/null +++ b/_downloads/f0c2480708e8f088b8cecc1a46350c8f/plot_aliased.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Aliased versus anti-aliased\n\nThis example demonstrates aliased versus anti-aliased text.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n\nsize = 128, 16\ndpi = 72.0\nfigsize = size[0] / float(dpi), size[1] / float(dpi)\nfig = plt.figure(figsize=figsize, dpi=dpi)\nfig.patch.set_alpha(0)\n\nplt.axes((0, 0, 1, 1), frameon=False)\n\nplt.rcParams[\"text.antialiased\"] = False\nplt.text(0.5, 0.5, \"Aliased\", ha=\"center\", va=\"center\")\n\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xticks([])\nplt.yticks([])\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/f0c6cfac053d9c50c1ad4646455adad3/plot_display_face.ipynb b/_downloads/f0c6cfac053d9c50c1ad4646455adad3/plot_display_face.ipynb new file mode 100644 index 000000000..6da4d5ed0 --- /dev/null +++ b/_downloads/f0c6cfac053d9c50c1ad4646455adad3/plot_display_face.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Display a Raccoon Face\n\nAn example that displays a raccoon face with matplotlib.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import scipy as sp\nimport matplotlib.pyplot as plt\n\nf = sp.datasets.face(gray=True)\n\nplt.figure(figsize=(10, 3.6))\n\nplt.subplot(131)\nplt.imshow(f, cmap=\"gray\")\n\nplt.subplot(132)\nplt.imshow(f, cmap=\"gray\", vmin=30, vmax=200)\nplt.axis(\"off\")\n\nplt.subplot(133)\nplt.imshow(f, cmap=\"gray\")\nplt.contour(f, [50, 200])\nplt.axis(\"off\")\n\nplt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.05, right=0.99)\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/f221749774c0529207e9b06e14cfb784/ica.py b/_downloads/f221749774c0529207e9b06e14cfb784/ica.py new file mode 100644 index 000000000..06ceb0361 --- /dev/null +++ b/_downloads/f221749774c0529207e9b06e14cfb784/ica.py @@ -0,0 +1,293 @@ +# Author: Pierre Lafaye de Micheaux, Stefan van der Walt +# Python FastICA +# License: GPL unless permission obtained otherwise +# Look at algorithms in Tables 8.3 and 8.4 page 196 in the book: Independent Component Analysis, by Aapo et al. + +import numpy as np +import types + + +__all__ = ["fastica"] + + +def _gs_decorrelation(w, W, j): + """Gram-Schmidt-like decorrelation.""" + t = np.zeros_like(w) + for u in range(j): + t = t + (w @ W[u]) * W[u] + w -= t + return w + + +def _ica_def(X, tol, g, gprime, fun_args, maxit, w_init): + """Deflationary FastICA using fun approx to neg-entropy function + + Used internally by FastICA. + """ + + n_comp = w_init.shape[0] + W = np.zeros((n_comp, n_comp), dtype=float) + + # j is the index of the extracted component + for j in range(n_comp): + w = w_init[j, :].copy() + w /= np.sqrt((w**2).sum()) + + n_iterations = 0 + # we set lim to tol+1 to be sure to enter at least once in next while + lim = tol + 1 + while (lim > tol) & (n_iterations < (maxit - 1)): + wtx = w.T @ X + gwtx = g(wtx, fun_args) + g_wtx = gprime(wtx, fun_args) + w1 = (X * gwtx).mean(axis=1) - g_wtx.mean() * w + + _gs_decorrelation(w1, W, j) + + w1 /= np.sqrt((w1**2).sum()) + + lim = np.abs(np.abs((w1 * w).sum()) - 1) + w = w1 + n_iterations = n_iterations + 1 + + W[j, :] = w + + return W + + +def _sym_decorrelation(W): + """Symmetric decorrelation""" + K = W @ W.T + s, u = np.linalg.eigh(K) + # u (resp. s) contains the eigenvectors (resp. square roots of + # the eigenvalues) of W * W.T + u, W = (np.asmatrix(e) for e in (u, W)) + W = (u * np.diag(1.0 / np.sqrt(s)) * u.T) * W # W = (W * W.T) ^{-1/2} * W + return W + + +def _ica_par(X, tol, g, gprime, fun_args, maxit, w_init): + """Parallel FastICA. + + Used internally by FastICA. + + """ + n, p = X.shape + + W = _sym_decorrelation(w_init) + + # we set lim to tol+1 to be sure to enter at least once in next while + lim = tol + 1 + it = 0 + while (lim > tol) and (it < (maxit - 1)): + wtx = (W @ X).A # .A transforms to array type + gwtx = g(wtx, fun_args) + g_wtx = gprime(wtx, fun_args) + W1 = (gwtx @ X.T) / float(p) - np.diag(g_wtx.mean(axis=1)) @ W + + W1 = _sym_decorrelation(W1) + + lim = max(abs(abs(np.diag(W1 @ W.T)) - 1)) + W = W1 + it = it + 1 + + return W + + +def fastica( + X, + n_comp=None, + algorithm="parallel", + whiten=True, + fun="logcosh", + fun_prime="", + fun_args={}, + maxit=200, + tol=1e-04, + w_init=None, +): + """Perform Fast Independent Component Analysis. + + Parameters + ---------- + X : (n,p) array + Array with n observations (statistical units) measured on p variables. + n_comp : int, optional + Number of components to extract. If None no dimension reduction + is performed. + algorithm : {'parallel','deflation'} + Apply an parallel or deflational FASTICA algorithm. + whiten: boolean, optional + If true perform an initial whitening of the data. Do not set to + false unless the data is already white, as you will get incorrect + results. + If whiten is true, the data is assumed to have already been + preprocessed: it should be centered, normed and white. + fun : String or Function + The functional form of the G function used in the + approximation to neg-entropy. Could be either 'logcosh', 'exp', + or 'cube'. + You can also provide your own function but in this case, its + derivative should be provided via argument fun_prime + fun_prime : Empty string ('') or Function + See fun. + fun_args : Optional dictionary + If empty and if fun='logcosh', fun_args will take value + {'alpha' : 1.0} + maxit : int + Maximum number of iterations to perform + tol : float + A positive scalar giving the tolerance at which the + un-mixing matrix is considered to have converged + w_init : (n_comp,n_comp) array + Initial un-mixing array of dimension (n.comp,n.comp). + If None (default) then an array of normal r.v.'s is used + source_only: if True, only the sources matrix is returned + + Results + ------- + K : (p,n_comp) array + pre-whitening matrix that projects data onto th first n.comp + principal components. Returned only if whiten is True + W : (n_comp,n_comp) array + estimated un-mixing matrix + The mixing matrix can be obtained by:: + w = np.asmatrix(W) * K.T + A = w.T * (w * w.T).I + S : (n,n_comp) array + estimated source matrix + + Examples + -------- + + >>> X = np.array( + [[5.,1.4,1.9,0], \ + [2,5.4,8.,1.1], \ + [3,6.4,9,1.2]]) + >>> w_init = np.array([[1,4],[7,2]]) + >>> n_comp = 2 + >>> k, W, S = fastica(X, n_comp, algorithm='parallel', w_init=w_init) + >>> print(S) + [[-0.02387286 -1.41401205] + [ 1.23650679 0.68633152] + [-1.21263393 0.72768053]] + + Notes + ----- + + The data matrix X is considered to be a linear combination of + non-Gaussian (independent) components i.e. X = SA where columns of S + contain the independent components and A is a linear mixing + matrix. In short ICA attempts to `un-mix' the data by estimating an + un-mixing matrix W where XW = S. + + Implemented using FastICA: + + A. Hyvarinen and E. Oja, Independent Component Analysis: + Algorithms and Applications, Neural Networks, 13(4-5), 2000, + pp. 411-430 + + """ + algorithm_funcs = {"parallel": _ica_par, "deflation": _ica_def} + + alpha = fun_args.get("alpha", 1.0) + if (alpha < 1) or (alpha > 2): + raise ValueError("alpha must be in [1,2]") + + if isinstance(fun, str): + # Some standard nonlinear functions + if fun == "logcosh": + + def g(x, fun_args): + alpha = fun_args.get("alpha", 1.0) + return np.tanh(alpha * x) + + def gprime(x, fun_args): + alpha = fun_args.get("alpha", 1.0) + return alpha * (1 - (np.tanh(alpha * x)) ** 2) + + elif fun == "exp": + + def g(x, fun_args): + return x * np.exp(-(x**2) / 2) + + def gprime(x, fun_args): + return (1 - x**2) * np.exp(-(x**2) / 2) + + elif fun == "cube": + + def g(x, fun_args): + return x**3 + + def gprime(x, fun_args): + return 3 * x**2 + + else: + raise ValueError("fun argument should be one of logcosh, exp or cube") + elif type(fun) is not types.FunctionType: + raise ValueError( + "fun argument should be either a string " + "(one of logcosh, exp or cube) or a function" + ) + else: + + def g(x, fun_args): + return fun(x, **fun_args) + + def gprime(x, fun_args): + return fun_prime(x, **fun_args) + + n, p = X.shape + + if n_comp is None: + n_comp = min(n, p) + if n_comp > min(n, p): + n_comp = min(n, p) + print(f"n_comp is too large: it will be set to {n_comp}") + + if whiten: + # Centering the columns (ie the variables) + X = X - X.mean(axis=0) + + # Whitening and preprocessing by PCA + _, d, v = np.linalg.svd(X, full_matrices=False) + del _ + # XXX: Maybe we could provide a mean to estimate n_comp if it has not + # been provided ??? So that we do not have to perform another PCA + # before calling fastica ??? + K = (v * (np.sqrt(n) / d)[:, np.newaxis])[:n_comp] # see (6.33) p.140 + del v, d + X1 = ( + K @ X.T + ) # see (13.6) p.267 Here X1 is white and data in X has been projected onto a subspace by PCA + else: + X1 = X.T + + if w_init is None: + rng = np.random.default_rng() + w_init = rng.normal(size=(n_comp, n_comp)) + else: + w_init = np.asarray(w_init) + if w_init.shape != (n_comp, n_comp): + raise ValueError(f"w_init has invalid shape -- should be {n_comp, n_comp}") + + kwargs = { + "tol": tol, + "g": g, + "gprime": gprime, + "fun_args": fun_args, + "maxit": maxit, + "w_init": w_init, + } + + func = algorithm_funcs[algorithm] + + W = func(X1, **kwargs) + del X1 + + if whiten: + S = (np.asmatrix(W) * K) @ X.T + return [np.asarray(e.T) for e in (K, W, S)] + else: + S = W @ X.T + return [np.asarray(e.T) for e in (W, S)] diff --git a/_downloads/f2b21b92b5a112a28d0894ad041f7b6f/plot_exercise_2.zip b/_downloads/f2b21b92b5a112a28d0894ad041f7b6f/plot_exercise_2.zip new file mode 100644 index 000000000..dd372f9fc Binary files /dev/null and b/_downloads/f2b21b92b5a112a28d0894ad041f7b6f/plot_exercise_2.zip differ diff --git a/_downloads/f2d2bbfa4ec12cb0d2248f8c86208bec/plot_exercise_ill_conditioned.py b/_downloads/f2d2bbfa4ec12cb0d2248f8c86208bec/plot_exercise_ill_conditioned.py new file mode 100644 index 000000000..c2a557ddb --- /dev/null +++ b/_downloads/f2d2bbfa4ec12cb0d2248f8c86208bec/plot_exercise_ill_conditioned.py @@ -0,0 +1,89 @@ +""" +Alternating optimization +========================= + +The challenge here is that Hessian of the problem is a very +ill-conditioned matrix. This can easily be seen, as the Hessian of the +first term in simply 2 * K.T @ K. Thus the conditioning of the +problem can be judged from looking at the conditioning of K. +""" + +import time + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +rng = np.random.default_rng(27446968) + +K = rng.normal(size=(100, 100)) + + +def f(x): + return np.sum((K @ (x - 1)) ** 2) + np.sum(x**2) ** 2 + + +def f_prime(x): + return 2 * K.T @ K @ (x - 1) + 4 * np.sum(x**2) * x + + +def hessian(x): + H = 2 * K.T @ K + 4 * 2 * x * x[:, np.newaxis] + return H + 4 * np.eye(H.shape[0]) * np.sum(x**2) + + +############################################################################### +# Some pretty plotting + +plt.figure(1) +plt.clf() +Z = X, Y = np.mgrid[-1.5:1.5:100j, -1.1:1.1:100j] # type: ignore[misc] +# Complete in the additional dimensions with zeros +Z = np.reshape(Z, (2, -1)).copy() +Z.resize((100, Z.shape[-1])) +Z = np.apply_along_axis(f, 0, Z) +Z = np.reshape(Z, X.shape) +plt.imshow(Z.T, cmap="gray_r", extent=(-1.5, 1.5, -1.1, 1.1), origin="lower") +plt.contour(X, Y, Z, cmap="gnuplot") + +# A reference but slow solution: +t0 = time.time() +x_ref = sp.optimize.minimize(f, K[0], method="Powell").x +print(f" Powell: time {time.time() - t0:.2f}s") +f_ref = f(x_ref) + +# Compare different approaches +t0 = time.time() +x_bfgs = sp.optimize.minimize(f, K[0], method="BFGS").x +print( + f" BFGS: time {time.time() - t0:.2f}s, x error {np.sqrt(np.sum((x_bfgs - x_ref) ** 2)):.2f}, f error {f(x_bfgs) - f_ref:.2f}" +) + +t0 = time.time() +x_l_bfgs = sp.optimize.minimize(f, K[0], method="L-BFGS-B").x +print( + f" L-BFGS: time {time.time() - t0:.2f}s, x error {np.sqrt(np.sum((x_l_bfgs - x_ref) ** 2)):.2f}, f error {f(x_l_bfgs) - f_ref:.2f}" +) + + +t0 = time.time() +x_bfgs = sp.optimize.minimize(f, K[0], jac=f_prime, method="BFGS").x +print( + f" BFGS w f': time {time.time() - t0:.2f}s, x error {np.sqrt(np.sum((x_bfgs - x_ref) ** 2)):.2f}, f error {f(x_bfgs) - f_ref:.2f}" +) + +t0 = time.time() +x_l_bfgs = sp.optimize.minimize(f, K[0], jac=f_prime, method="L-BFGS-B").x +print( + f"L-BFGS w f': time {time.time() - t0:.2f}s, x error {np.sqrt(np.sum((x_l_bfgs - x_ref) ** 2)):.2f}, f error {f(x_l_bfgs) - f_ref:.2f}" +) + +t0 = time.time() +x_newton = sp.optimize.minimize( + f, K[0], jac=f_prime, hess=hessian, method="Newton-CG" +).x +print( + f" Newton: time {time.time() - t0:.2f}s, x error {np.sqrt(np.sum((x_newton - x_ref) ** 2)):.2f}, f error {f(x_newton) - f_ref:.2f}" +) + +plt.show() diff --git a/_downloads/f3804754fa95016254cac570e8c7b19b/plot_solve_ivp_damped_spring_mass.zip b/_downloads/f3804754fa95016254cac570e8c7b19b/plot_solve_ivp_damped_spring_mass.zip new file mode 100644 index 000000000..fb60c1064 Binary files /dev/null and b/_downloads/f3804754fa95016254cac570e8c7b19b/plot_solve_ivp_damped_spring_mass.zip differ diff --git a/_downloads/f3ab9f1d461865860ea6d127c52f266b/plot_measure_data.py b/_downloads/f3ab9f1d461865860ea6d127c52f266b/plot_measure_data.py new file mode 100644 index 000000000..91ef02b87 --- /dev/null +++ b/_downloads/f3ab9f1d461865860ea6d127c52f266b/plot_measure_data.py @@ -0,0 +1,43 @@ +""" +Measurements from images +========================== + +This examples shows how to measure quantities from various images. + +""" + +import numpy as np +import scipy as sp +import matplotlib.pyplot as plt + +rng = np.random.default_rng(27446968) +n = 10 +l = 256 +im = np.zeros((l, l)) +points = l * rng.random((2, n**2)) +im[(points[0]).astype(int), (points[1]).astype(int)] = 1 +im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) + +mask = im > im.mean() + +label_im, nb_labels = sp.ndimage.label(mask) + +sizes = sp.ndimage.sum(mask, label_im, range(nb_labels + 1)) +mask_size = sizes < 1000 +remove_pixel = mask_size[label_im] +label_im[remove_pixel] = 0 +labels = np.unique(label_im) +label_clean = np.searchsorted(labels, label_im) + + +plt.figure(figsize=(6, 3)) + +plt.subplot(121) +plt.imshow(label_im, cmap="nipy_spectral") +plt.axis("off") +plt.subplot(122) +plt.imshow(label_clean, vmax=nb_labels, cmap="nipy_spectral") +plt.axis("off") + +plt.subplots_adjust(wspace=0.01, hspace=0.01, top=1, bottom=0, left=0, right=1) +plt.show() diff --git a/_downloads/f42d83b2c3216148b5b020e41e158f15/plot_maskedstats.zip b/_downloads/f42d83b2c3216148b5b020e41e158f15/plot_maskedstats.zip new file mode 100644 index 000000000..89c2a6265 Binary files /dev/null and b/_downloads/f42d83b2c3216148b5b020e41e158f15/plot_maskedstats.zip differ diff --git a/_downloads/f497c893cfa7b28682fbe34379de1a8b/plot_1d_optim.zip b/_downloads/f497c893cfa7b28682fbe34379de1a8b/plot_1d_optim.zip new file mode 100644 index 000000000..ed8936ec5 Binary files /dev/null and b/_downloads/f497c893cfa7b28682fbe34379de1a8b/plot_1d_optim.zip differ diff --git a/_downloads/f4b9e747d3946e08fbfacd412476e0b6/plot_elephant.zip b/_downloads/f4b9e747d3946e08fbfacd412476e0b6/plot_elephant.zip new file mode 100644 index 000000000..86ac382e0 Binary files /dev/null and b/_downloads/f4b9e747d3946e08fbfacd412476e0b6/plot_elephant.zip differ diff --git a/_downloads/f50cdaf9218e291d14df5a01ee4f2791/plot_imshow_ext.py b/_downloads/f50cdaf9218e291d14df5a01ee4f2791/plot_imshow_ext.py new file mode 100644 index 000000000..ab8545fef --- /dev/null +++ b/_downloads/f50cdaf9218e291d14df5a01ee4f2791/plot_imshow_ext.py @@ -0,0 +1,65 @@ +""" +Imshow demo +============ + +Demoing imshow +""" + +import numpy as np +import matplotlib.pyplot as plt + + +def f(x, y): + return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2) + + +n = 10 +x = np.linspace(-3, 3, 8 * n) +y = np.linspace(-3, 3, 6 * n) +X, Y = np.meshgrid(x, y) +Z = f(X, Y) +plt.imshow(Z, interpolation="nearest", cmap="bone", origin="lower") +plt.xticks([]) +plt.yticks([]) + + +# Add a title and a box around it +from matplotlib.patches import FancyBboxPatch + +ax = plt.gca() +ax.add_patch( + FancyBboxPatch( + (-0.05, 0.87), + width=0.66, + height=0.165, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) +) + +plt.text( + -0.05, + 1.02, + " Imshow: plt.imshow(...)\n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=plt.gca().transAxes, +) + +plt.text( + -0.05, + 1.01, + "\n\n Display an image to current axes ", + horizontalalignment="left", + verticalalignment="top", + family="DejaVu Sans", + size="large", + transform=plt.gca().transAxes, +) + +plt.show() diff --git a/_downloads/f54d1b0cf4942596ef7e8479230abc36/plot_sprog_annual_maxima.zip b/_downloads/f54d1b0cf4942596ef7e8479230abc36/plot_sprog_annual_maxima.zip new file mode 100644 index 000000000..0ff1497a3 Binary files /dev/null and b/_downloads/f54d1b0cf4942596ef7e8479230abc36/plot_sprog_annual_maxima.zip differ diff --git a/_downloads/f5894559a01fb2ff65bd69f8b108d280/plot_linestyles.py b/_downloads/f5894559a01fb2ff65bd69f8b108d280/plot_linestyles.py new file mode 100644 index 000000000..58d691e0c --- /dev/null +++ b/_downloads/f5894559a01fb2ff65bd69f8b108d280/plot_linestyles.py @@ -0,0 +1,70 @@ +""" +Linestyles +========== + +Plot the different line styles. +""" + +import numpy as np +import matplotlib.pyplot as plt + + +def linestyle(ls, i): + X = i * 0.5 * np.ones(11) + Y = np.arange(11) + plt.plot( + X, + Y, + ls, + color=(0.0, 0.0, 1, 1), + lw=3, + ms=8, + mfc=(0.75, 0.75, 1, 1), + mec=(0, 0, 1, 1), + ) + plt.text(0.5 * i, 10.25, ls, rotation=90, fontsize=15, va="bottom") + + +linestyles = [ + "-", + "--", + ":", + "-.", + ".", + ",", + "o", + "^", + "v", + "<", + ">", + "s", + "+", + "x", + "d", + "1", + "2", + "3", + "4", + "h", + "p", + "|", + "_", + "D", + "H", +] +n_lines = len(linestyles) + +size = 20 * n_lines, 300 +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = plt.figure(figsize=figsize, dpi=dpi) +plt.axes((0, 0.01, 1, 0.9), frameon=False) + +for i, ls in enumerate(linestyles): + linestyle(ls, i) + +plt.xlim(-0.2, 0.2 + 0.5 * n_lines) +plt.xticks([]) +plt.yticks([]) + +plt.show() diff --git a/_downloads/f633e7b1593a330f531b6bab05e9c5d3/plot_curve_fitting.ipynb b/_downloads/f633e7b1593a330f531b6bab05e9c5d3/plot_curve_fitting.ipynb new file mode 100644 index 000000000..ac73a939f --- /dev/null +++ b/_downloads/f633e7b1593a330f531b6bab05e9c5d3/plot_curve_fitting.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Curve fitting\n\nA curve fitting example\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nrng = np.random.default_rng(27446968)\n\n\n# Our test function\ndef f(t, omega, phi):\n return np.cos(omega * t + phi)\n\n\n# Our x and y data\nx = np.linspace(0, 3, 50)\ny = f(x, 1.5, 1) + 0.1 * np.random.normal(size=50)\n\n# Fit the model: the parameters omega and phi can be found in the\n# `params` vector\nparams, params_cov = sp.optimize.curve_fit(f, x, y)\n\n# plot the data and the fitted curve\nt = np.linspace(0, 3, 1000)\n\nplt.figure(1)\nplt.clf()\nplt.plot(x, y, \"bx\")\nplt.plot(t, f(t, *params), \"r-\")\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/f6fb815200495c6fca51c423813f800d/plot_imshow.py b/_downloads/f6fb815200495c6fca51c423813f800d/plot_imshow.py new file mode 100644 index 000000000..624428b21 --- /dev/null +++ b/_downloads/f6fb815200495c6fca51c423813f800d/plot_imshow.py @@ -0,0 +1,28 @@ +""" +Imshow elaborate +================= + +An example demoing imshow and styling the figure. +""" + +import numpy as np +import matplotlib.pyplot as plt + + +def f(x, y): + return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2) + + +n = 10 +x = np.linspace(-3, 3, int(3.5 * n)) +y = np.linspace(-3, 3, int(3.0 * n)) +X, Y = np.meshgrid(x, y) +Z = f(X, Y) + +plt.axes((0.025, 0.025, 0.95, 0.95)) +plt.imshow(Z, interpolation="nearest", cmap="bone", origin="lower") +plt.colorbar(shrink=0.92) + +plt.xticks([]) +plt.yticks([]) +plt.show() diff --git a/_downloads/f76035d5531aa2ed7f7103028de83ce7/plot_exercise_3.py b/_downloads/f76035d5531aa2ed7f7103028de83ce7/plot_exercise_3.py new file mode 100644 index 000000000..f2011f03a --- /dev/null +++ b/_downloads/f76035d5531aa2ed7f7103028de83ce7/plot_exercise_3.py @@ -0,0 +1,26 @@ +""" +Exercise 3 +========== + +Exercise 3 with matplotlib. +""" + +import numpy as np +import matplotlib.pyplot as plt + +plt.figure(figsize=(8, 5), dpi=80) +plt.subplot(111) + +X = np.linspace(-np.pi, np.pi, 256) +C, S = np.cos(X), np.sin(X) + +plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") +plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") + +plt.xlim(-4.0, 4.0) +plt.xticks(np.linspace(-4, 4, 9)) + +plt.ylim(-1.0, 1.0) +plt.yticks(np.linspace(-1, 1, 5)) + +plt.show() diff --git a/_downloads/f77b0511d6d0033c991cbeddb293d79b/plot_exercise_10.zip b/_downloads/f77b0511d6d0033c991cbeddb293d79b/plot_exercise_10.zip new file mode 100644 index 000000000..7d4cc0d07 Binary files /dev/null and b/_downloads/f77b0511d6d0033c991cbeddb293d79b/plot_exercise_10.zip differ diff --git a/_downloads/f8e50ae5e9b67b97393fbe04b3e6c4bf/plot_regression.ipynb b/_downloads/f8e50ae5e9b67b97393fbe04b3e6c4bf/plot_regression.ipynb new file mode 100644 index 000000000..87237d277 --- /dev/null +++ b/_downloads/f8e50ae5e9b67b97393fbe04b3e6c4bf/plot_regression.ipynb @@ -0,0 +1,97 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Simple Regression\n\nFit a simple linear regression using 'statsmodels', compute corresponding\np-values.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Original author: Thomas Haslwanter\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas\n\n# For statistics. Requires statsmodels 5.0 or more\nfrom statsmodels.formula.api import ols\n\n# Analysis of Variance (ANOVA) on linear models\nfrom statsmodels.stats.anova import anova_lm" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Generate and show the data\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "x = np.linspace(-5, 5, 20)\n\n# To get reproducible values, provide a seed value\nrng = np.random.default_rng(27446968)\n\ny = -5 + 3 * x + 4 * np.random.normal(size=x.shape)\n\n# Plot the data\nplt.figure(figsize=(5, 4))\nplt.plot(x, y, \"o\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Multilinear regression model, calculating fit, P-values, confidence\nintervals etc.\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Convert the data into a Pandas DataFrame to use the formulas framework\n# in statsmodels\ndata = pandas.DataFrame({\"x\": x, \"y\": y})\n\n# Fit the model\nmodel = ols(\"y ~ x\", data).fit()\n\n# Print the summary\nprint(model.summary())\n\n# Perform analysis of variance on fitted linear model\nanova_results = anova_lm(model)\n\nprint(\"\\nANOVA results\")\nprint(anova_results)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Plot the fitted model\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Retrieve the parameter estimates\noffset, coef = model._results.params\nplt.plot(x, x * coef + offset)\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/f951e65b8afefb7642f17809208bebf7/plot_antialiased.zip b/_downloads/f951e65b8afefb7642f17809208bebf7/plot_antialiased.zip new file mode 100644 index 000000000..2845bc5e4 Binary files /dev/null and b/_downloads/f951e65b8afefb7642f17809208bebf7/plot_antialiased.zip differ diff --git a/_downloads/f95e72c3ad9c3297faca09b1432d2f64/plot_clean_morpho.zip b/_downloads/f95e72c3ad9c3297faca09b1432d2f64/plot_clean_morpho.zip new file mode 100644 index 000000000..25aa6054c Binary files /dev/null and b/_downloads/f95e72c3ad9c3297faca09b1432d2f64/plot_clean_morpho.zip differ diff --git a/_downloads/f964f18be6a1f320bd4623ee20655324/plot_text_ext.zip b/_downloads/f964f18be6a1f320bd4623ee20655324/plot_text_ext.zip new file mode 100644 index 000000000..d00ef7448 Binary files /dev/null and b/_downloads/f964f18be6a1f320bd4623ee20655324/plot_text_ext.zip differ diff --git a/_downloads/f9f9e6203d48c0f13da3d3ed87fe18e2/plot_colormaps.ipynb b/_downloads/f9f9e6203d48c0f13da3d3ed87fe18e2/plot_colormaps.ipynb new file mode 100644 index 000000000..5d9b0f6b2 --- /dev/null +++ b/_downloads/f9f9e6203d48c0f13da3d3ed87fe18e2/plot_colormaps.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Colormaps\n\nAn example plotting the matplotlib colormaps.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n\nplt.rc(\"text\", usetex=False)\na = np.outer(np.arange(0, 1, 0.01), np.ones(10))\n\nplt.figure(figsize=(10, 5))\nplt.subplots_adjust(top=0.8, bottom=0.05, left=0.01, right=0.99)\nmaps = [m for m in matplotlib.colormaps if not m.endswith(\"_r\")]\nmaps.sort()\nl = len(maps) + 1\n\nfor i, m in enumerate(maps):\n plt.subplot(1, l, i + 1)\n plt.axis(\"off\")\n plt.imshow(a, aspect=\"auto\", cmap=plt.get_cmap(m), origin=\"lower\")\n plt.title(m, rotation=90, fontsize=10, va=\"bottom\")\n\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/fa097a8bc165a4abf5f143a9ef254c54/plot_boundaries.ipynb b/_downloads/fa097a8bc165a4abf5f143a9ef254c54/plot_boundaries.ipynb new file mode 100644 index 000000000..0882a00bc --- /dev/null +++ b/_downloads/fa097a8bc165a4abf5f143a9ef254c54/plot_boundaries.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Segmentation contours\n\nVisualize segmentation contours on original grayscale image.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from skimage import data, segmentation\nfrom skimage import filters\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ncoins = data.coins()\nmask = coins > filters.threshold_otsu(coins)\nclean_border = segmentation.clear_border(mask).astype(int)\n\ncoins_edges = segmentation.mark_boundaries(coins, clean_border)\n\nplt.figure(figsize=(8, 3.5))\nplt.subplot(121)\nplt.imshow(clean_border, cmap=\"gray\")\nplt.axis(\"off\")\nplt.subplot(122)\nplt.imshow(coins_edges)\nplt.axis(\"off\")\n\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/fb0f1977eb9deb61e65ec8bc89094418/plot_optimize_lidar_data_fit.ipynb b/_downloads/fb0f1977eb9deb61e65ec8bc89094418/plot_optimize_lidar_data_fit.ipynb new file mode 100644 index 000000000..2b19f73bc --- /dev/null +++ b/_downloads/fb0f1977eb9deb61e65ec8bc89094418/plot_optimize_lidar_data_fit.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# The lidar system, data and fit (1 of 2 datasets)\n\nGenerate a chart of the data fitted by Gaussian curve\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy as sp\n\n\ndef model(t, coeffs):\n return coeffs[0] + coeffs[1] * np.exp(-(((t - coeffs[2]) / coeffs[3]) ** 2))\n\n\ndef residuals(coeffs, y, t):\n return y - model(t, coeffs)\n\n\nwaveform_1 = np.load(\"waveform_1.npy\")\nt = np.arange(len(waveform_1))\n\nx0 = np.array([3, 30, 15, 1], dtype=float)\nx, flag = sp.optimize.leastsq(residuals, x0, args=(waveform_1, t))\n\nprint(x)\n\nfig, ax = plt.subplots(figsize=(8, 6))\nplt.plot(t, waveform_1, t, model(t, x))\nplt.xlabel(\"Time [ns]\")\nplt.ylabel(\"Amplitude [bins]\")\nplt.legend([\"Waveform\", \"Model\"])\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/_downloads/fb209a70dadbbf510a731be13bac3e98/plot_chebyfit.py b/_downloads/fb209a70dadbbf510a731be13bac3e98/plot_chebyfit.py new file mode 100644 index 000000000..aef27f6ce --- /dev/null +++ b/_downloads/fb209a70dadbbf510a731be13bac3e98/plot_chebyfit.py @@ -0,0 +1,20 @@ +""" +Fitting in Chebyshev basis +========================== + +Plot noisy data and their polynomial fit in a Chebyshev basis + +""" + +import numpy as np +import matplotlib.pyplot as plt + +rng = np.random.default_rng(27446968) + +x = np.linspace(-1, 1, 2000) +y = np.cos(x) + 0.3 * rng.random(2000) +p = np.polynomial.Chebyshev.fit(x, y, 90) + +plt.plot(x, y, "r.") +plt.plot(x, p(x), "k-", lw=3) +plt.show() diff --git a/_downloads/fb4815405a17970d5ecf15f8a4d7b09d/plot_markers.zip b/_downloads/fb4815405a17970d5ecf15f8a4d7b09d/plot_markers.zip new file mode 100644 index 000000000..c4aea2c2c Binary files /dev/null and b/_downloads/fb4815405a17970d5ecf15f8a4d7b09d/plot_markers.zip differ diff --git a/_downloads/fb65d7dff3f45cdf51223fb441aef0e6/plot_linear_regression.py b/_downloads/fb65d7dff3f45cdf51223fb441aef0e6/plot_linear_regression.py new file mode 100644 index 000000000..50e414694 --- /dev/null +++ b/_downloads/fb65d7dff3f45cdf51223fb441aef0e6/plot_linear_regression.py @@ -0,0 +1,38 @@ +""" +A simple linear regression +=========================== + +""" + +import numpy as np +import matplotlib.pyplot as plt +from sklearn.linear_model import LinearRegression + +# x from 0 to 30 +rng = np.random.default_rng() +x = 30 * rng.random((20, 1)) + +# y = a*x + b with noise +y = 0.5 * x + 1.0 + rng.normal(size=x.shape) + +# create a linear regression model +model = LinearRegression() +model.fit(x, y) + +# predict y from the data +x_new = np.linspace(0, 30, 100) +y_new = model.predict(x_new[:, np.newaxis]) + +# plot the results +plt.figure(figsize=(4, 3)) +ax = plt.axes() +ax.scatter(x, y) +ax.plot(x_new, y_new) + +ax.set_xlabel("x") +ax.set_ylabel("y") + +ax.axis("tight") + + +plt.show() diff --git a/_downloads/fb9f0c50d3b231e7f0a309f2b56a8740/plot_pandas.py b/_downloads/fb9f0c50d3b231e7f0a309f2b56a8740/plot_pandas.py new file mode 100644 index 000000000..9308a511e --- /dev/null +++ b/_downloads/fb9f0c50d3b231e7f0a309f2b56a8740/plot_pandas.py @@ -0,0 +1,29 @@ +""" +Plotting simple quantities of a pandas dataframe +================================================= + +This example loads from a CSV file data with mixed numerical and +categorical entries, and plots a few quantities, separately for females +and males, thanks to the pandas integrated plotting tool (that uses +matplotlib behind the scene). + +See http://pandas.pydata.org/pandas-docs/stable/visualization.html +""" + +import pandas + +data = pandas.read_csv("brain_size.csv", sep=";", na_values=".") + +# Box plots of different columns for each gender +groupby_gender = data.groupby("Gender") +groupby_gender.boxplot(column=["FSIQ", "VIQ", "PIQ"]) + +from pandas import plotting + +# Scatter matrices for different columns +plotting.scatter_matrix(data[["Weight", "Height", "MRI_Count"]]) +plotting.scatter_matrix(data[["PIQ", "VIQ", "FSIQ"]]) + +import matplotlib.pyplot as plt + +plt.show() diff --git a/_downloads/fd82f9c624491b72038b3d8ec417b26e/plot_contour_ext.py b/_downloads/fd82f9c624491b72038b3d8ec417b26e/plot_contour_ext.py new file mode 100644 index 000000000..70aae462c --- /dev/null +++ b/_downloads/fd82f9c624491b72038b3d8ec417b26e/plot_contour_ext.py @@ -0,0 +1,68 @@ +""" +Display the contours of a function +=================================== + +An example demoing how to plot the contours of a function, with +additional layout tweaks. + +""" + +import numpy as np +import matplotlib.pyplot as plt + + +def f(x, y): + return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2) + + +n = 256 +x = np.linspace(-3, 3, n) +y = np.linspace(-3, 3, n) +X, Y = np.meshgrid(x, y) + +plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap="hot") +C = plt.contour(X, Y, f(X, Y), 8, colors="black", linewidth=0.5) +plt.clabel(C, inline=1, fontsize=10) +plt.xticks([]) +plt.yticks([]) + + +# Add a title and a box around it +from matplotlib.patches import FancyBboxPatch + +ax = plt.gca() +ax.add_patch( + FancyBboxPatch( + (-0.05, 0.87), + width=0.66, + height=0.165, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) +) + +plt.text( + -0.05, + 1.02, + " Contour Plot: plt.contour(..)\n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=plt.gca().transAxes, +) + +plt.text( + -0.05, + 1.01, + "\n\n Draw contour lines and filled contours ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=plt.gca().transAxes, +) + +plt.show() diff --git a/_downloads/fde06fbe82fcd8984cdf2092a32abab0/plot_bar.zip b/_downloads/fde06fbe82fcd8984cdf2092a32abab0/plot_bar.zip new file mode 100644 index 000000000..62f52a6eb Binary files /dev/null and b/_downloads/fde06fbe82fcd8984cdf2092a32abab0/plot_bar.zip differ diff --git a/_downloads/fdefd92f37a69c92db6c9fb8d8756ffe/plot_connect_measurements.zip b/_downloads/fdefd92f37a69c92db6c9fb8d8756ffe/plot_connect_measurements.zip new file mode 100644 index 000000000..63fde4a9b Binary files /dev/null and b/_downloads/fdefd92f37a69c92db6c9fb8d8756ffe/plot_connect_measurements.zip differ diff --git a/_downloads/fe5771c06c8960974b0ce4306b9d6d5b/plot_randomwalk.py b/_downloads/fe5771c06c8960974b0ce4306b9d6d5b/plot_randomwalk.py new file mode 100644 index 000000000..eaa4dccf6 --- /dev/null +++ b/_downloads/fe5771c06c8960974b0ce4306b9d6d5b/plot_randomwalk.py @@ -0,0 +1,39 @@ +""" +Random walk exercise +==================== + +Plot distance as a function of time for a random walk +together with the theoretical result + +""" + +import numpy as np +import matplotlib.pyplot as plt + +# We create 1000 realizations with 200 steps each +n_stories = 1000 +t_max = 200 + +t = np.arange(t_max) +# Steps can be -1 or 1 (note that randint excludes the upper limit) +rng = np.random.default_rng() +steps = 2 * rng.integers(0, 1 + 1, (n_stories, t_max)) - 1 + +# The time evolution of the position is obtained by successively +# summing up individual steps. This is done for each of the +# realizations, i.e. along axis 1. +positions = np.cumsum(steps, axis=1) + +# Determine the time evolution of the mean square distance. +sq_distance = positions**2 +mean_sq_distance = np.mean(sq_distance, axis=0) + +# Plot the distance d from the origin as a function of time and +# compare with the theoretically expected result where d(t) +# grows as a square root of time t. +plt.figure(figsize=(4, 3)) +plt.plot(t, np.sqrt(mean_sq_distance), "g.", t, np.sqrt(t), "y-") +plt.xlabel(r"$t$") +plt.ylabel(r"$\sqrt{\langle (\delta x)^2 \rangle}$") +plt.tight_layout() +plt.show() diff --git a/_downloads/fef51fefbc4306cd767710473a730af7/auto_examples_python.zip b/_downloads/fef51fefbc4306cd767710473a730af7/auto_examples_python.zip new file mode 100644 index 000000000..d344f2a56 Binary files /dev/null and b/_downloads/fef51fefbc4306cd767710473a730af7/auto_examples_python.zip differ diff --git a/_downloads/ff693d5926c40b3cc1b2c279aa1e42a5/plot_exercise_1.zip b/_downloads/ff693d5926c40b3cc1b2c279aa1e42a5/plot_exercise_1.zip new file mode 100644 index 000000000..2995607b9 Binary files /dev/null and b/_downloads/ff693d5926c40b3cc1b2c279aa1e42a5/plot_exercise_1.zip differ diff --git a/_downloads/ffa4afb9f3a84e354cd7ed19a1109038/plot_labels.zip b/_downloads/ffa4afb9f3a84e354cd7ed19a1109038/plot_labels.zip new file mode 100644 index 000000000..252c62a3d Binary files /dev/null and b/_downloads/ffa4afb9f3a84e354cd7ed19a1109038/plot_labels.zip differ diff --git a/_images/MV_HFV_012.jpg b/_images/MV_HFV_012.jpg new file mode 100644 index 000000000..f647a1be9 Binary files /dev/null and b/_images/MV_HFV_012.jpg differ diff --git a/_images/axis_convention.png b/_images/axis_convention.png new file mode 100644 index 000000000..7782d261a Binary files /dev/null and b/_images/axis_convention.png differ diff --git a/_images/cpu-cacheline.png b/_images/cpu-cacheline.png new file mode 100644 index 000000000..f64b3c08f Binary files /dev/null and b/_images/cpu-cacheline.png differ diff --git a/_images/diamond_kernel.png b/_images/diamond_kernel.png new file mode 100644 index 000000000..66e4e6fb1 Binary files /dev/null and b/_images/diamond_kernel.png differ diff --git a/_images/exo_histos.png b/_images/exo_histos.png new file mode 100644 index 000000000..88f42554c Binary files /dev/null and b/_images/exo_histos.png differ diff --git a/_images/face.png b/_images/face.png new file mode 100644 index 000000000..b777c3dec Binary files /dev/null and b/_images/face.png differ diff --git a/_images/faces.png b/_images/faces.png new file mode 100644 index 000000000..aaeca08ba Binary files /dev/null and b/_images/faces.png differ diff --git a/_images/graph.png b/_images/graph.png new file mode 100644 index 000000000..ff99b10fe Binary files /dev/null and b/_images/graph.png differ diff --git a/_images/graph_g.png b/_images/graph_g.png new file mode 100644 index 000000000..b2ca5e602 Binary files /dev/null and b/_images/graph_g.png differ diff --git a/_images/graph_rcm.png b/_images/graph_rcm.png new file mode 100644 index 000000000..30b260409 Binary files /dev/null and b/_images/graph_rcm.png differ diff --git a/_images/icon-archive.svg b/_images/icon-archive.svg new file mode 100644 index 000000000..e5de35252 --- /dev/null +++ b/_images/icon-archive.svg @@ -0,0 +1 @@ + diff --git a/_images/icon-github.svg b/_images/icon-github.svg new file mode 100644 index 000000000..98d74c33f --- /dev/null +++ b/_images/icon-github.svg @@ -0,0 +1 @@ + diff --git a/_images/icon-pdf.svg b/_images/icon-pdf.svg new file mode 100644 index 000000000..2e4829713 --- /dev/null +++ b/_images/icon-pdf.svg @@ -0,0 +1 @@ + diff --git a/_images/image_spectral_clustering.png b/_images/image_spectral_clustering.png new file mode 100644 index 000000000..69f4dd98d Binary files /dev/null and b/_images/image_spectral_clustering.png differ diff --git a/_images/iris_setosa.jpg b/_images/iris_setosa.jpg new file mode 100644 index 000000000..dc3e22919 Binary files /dev/null and b/_images/iris_setosa.jpg differ diff --git a/_images/iris_versicolor.jpg b/_images/iris_versicolor.jpg new file mode 100644 index 000000000..671e7b66e Binary files /dev/null and b/_images/iris_versicolor.jpg differ diff --git a/_images/iris_virginica.jpg b/_images/iris_virginica.jpg new file mode 100644 index 000000000..ebad5dcfc Binary files /dev/null and b/_images/iris_virginica.jpg differ diff --git a/_images/kernels.png b/_images/kernels.png new file mode 100644 index 000000000..5883f6176 Binary files /dev/null and b/_images/kernels.png differ diff --git a/_images/lobpcg_eigenvalues.png b/_images/lobpcg_eigenvalues.png new file mode 100644 index 000000000..8ffd1e31b Binary files /dev/null and b/_images/lobpcg_eigenvalues.png differ diff --git a/_images/logo.svg b/_images/logo.svg new file mode 100644 index 000000000..c42584323 --- /dev/null +++ b/_images/logo.svg @@ -0,0 +1,1167 @@ + + + + + + + + + + + + image/svg+xml + + + + + + +   + +   + + + + + + + + + + + + + + + + + + + Python + + Matplotlib + + + + + + + + + + + + + + + + + scikits + + NumPy + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + SciPy + + + IPython + + + IP[y]: + + + + + Cython + + + + + + + 2015EDITION + + ScientificPythonLectures + + + + + + + + + + + + diff --git a/_images/mandelbrot.png b/_images/mandelbrot.png new file mode 100644 index 000000000..0a8ff9eac Binary files /dev/null and b/_images/mandelbrot.png differ diff --git a/_images/markov-chain.png b/_images/markov-chain.png new file mode 100644 index 000000000..feb937bdf Binary files /dev/null and b/_images/markov-chain.png differ diff --git a/_images/math/0182ba33e258f3deb58c92b008d230ef01fa5e73.png b/_images/math/0182ba33e258f3deb58c92b008d230ef01fa5e73.png new file mode 100644 index 000000000..251a60c2b Binary files /dev/null and b/_images/math/0182ba33e258f3deb58c92b008d230ef01fa5e73.png differ diff --git a/_images/math/027ba8fbd14f093e0c1477e9541dae7c7777c628.png b/_images/math/027ba8fbd14f093e0c1477e9541dae7c7777c628.png new file mode 100644 index 000000000..f9b266134 Binary files /dev/null and b/_images/math/027ba8fbd14f093e0c1477e9541dae7c7777c628.png differ diff --git a/_images/math/062fe3fe01f453ba3243adc7b8c7e6cf3c7fd0d7.png b/_images/math/062fe3fe01f453ba3243adc7b8c7e6cf3c7fd0d7.png new file mode 100644 index 000000000..2e4dc39f6 Binary files /dev/null and b/_images/math/062fe3fe01f453ba3243adc7b8c7e6cf3c7fd0d7.png differ diff --git a/_images/math/096eac87b625c08028577514fde43e27b55f0fb0.png b/_images/math/096eac87b625c08028577514fde43e27b55f0fb0.png new file mode 100644 index 000000000..0eeececdf Binary files /dev/null and b/_images/math/096eac87b625c08028577514fde43e27b55f0fb0.png differ diff --git a/_images/math/162ee3418d0839f4a3b13bb8a40445e062271bb8.png b/_images/math/162ee3418d0839f4a3b13bb8a40445e062271bb8.png new file mode 100644 index 000000000..5ee4bb0db Binary files /dev/null and b/_images/math/162ee3418d0839f4a3b13bb8a40445e062271bb8.png differ diff --git a/_images/math/194913536ec3a8bd61f17ba46b65318395a1e09b.png b/_images/math/194913536ec3a8bd61f17ba46b65318395a1e09b.png new file mode 100644 index 000000000..f23872352 Binary files /dev/null and b/_images/math/194913536ec3a8bd61f17ba46b65318395a1e09b.png differ diff --git a/_images/math/1aa57d85d556a451eb72fc726f16425c9ac05b48.png b/_images/math/1aa57d85d556a451eb72fc726f16425c9ac05b48.png new file mode 100644 index 000000000..6be908c47 Binary files /dev/null and b/_images/math/1aa57d85d556a451eb72fc726f16425c9ac05b48.png differ diff --git a/_images/math/1b37a12d753412cf66c783574d194423b8526eb8.png b/_images/math/1b37a12d753412cf66c783574d194423b8526eb8.png new file mode 100644 index 000000000..76aef212c Binary files /dev/null and b/_images/math/1b37a12d753412cf66c783574d194423b8526eb8.png differ diff --git a/_images/math/1fad4fa47682fc7932bab3cf1b1ba61b3ae4742b.png b/_images/math/1fad4fa47682fc7932bab3cf1b1ba61b3ae4742b.png new file mode 100644 index 000000000..f2e7339ee Binary files /dev/null and b/_images/math/1fad4fa47682fc7932bab3cf1b1ba61b3ae4742b.png differ diff --git a/_images/math/2154574b2533dbc09ab05cc8abddfa6293157251.png b/_images/math/2154574b2533dbc09ab05cc8abddfa6293157251.png new file mode 100644 index 000000000..2d5c21009 Binary files /dev/null and b/_images/math/2154574b2533dbc09ab05cc8abddfa6293157251.png differ diff --git a/_images/math/22176117b9ceea0b5976577272817474b55aeabd.png b/_images/math/22176117b9ceea0b5976577272817474b55aeabd.png new file mode 100644 index 000000000..42cccfa61 Binary files /dev/null and b/_images/math/22176117b9ceea0b5976577272817474b55aeabd.png differ diff --git a/_images/math/2262ae8a4c67b0e5fcc16ec2cd0a0577f7db0233.png b/_images/math/2262ae8a4c67b0e5fcc16ec2cd0a0577f7db0233.png new file mode 100644 index 000000000..5edcad356 Binary files /dev/null and b/_images/math/2262ae8a4c67b0e5fcc16ec2cd0a0577f7db0233.png differ diff --git a/_images/math/236cfa521d84d09194f6bdf365d271aeb9a07ed4.png b/_images/math/236cfa521d84d09194f6bdf365d271aeb9a07ed4.png new file mode 100644 index 000000000..91710b54e Binary files /dev/null and b/_images/math/236cfa521d84d09194f6bdf365d271aeb9a07ed4.png differ diff --git a/_images/math/25e209de39366eccadbc70d6501bfdcadb7bb335.png b/_images/math/25e209de39366eccadbc70d6501bfdcadb7bb335.png new file mode 100644 index 000000000..a58378815 Binary files /dev/null and b/_images/math/25e209de39366eccadbc70d6501bfdcadb7bb335.png differ diff --git a/_images/math/298514b3249adf66ee7a1796d4965404183ba223.png b/_images/math/298514b3249adf66ee7a1796d4965404183ba223.png new file mode 100644 index 000000000..964453554 Binary files /dev/null and b/_images/math/298514b3249adf66ee7a1796d4965404183ba223.png differ diff --git a/_images/math/29a66ecbf396095d467c5ae6c5746174f6437ab2.png b/_images/math/29a66ecbf396095d467c5ae6c5746174f6437ab2.png new file mode 100644 index 000000000..a90727f8a Binary files /dev/null and b/_images/math/29a66ecbf396095d467c5ae6c5746174f6437ab2.png differ diff --git a/_images/math/2bb98b9a2f25d98a0968eba7deb2f46bbcf2db84.png b/_images/math/2bb98b9a2f25d98a0968eba7deb2f46bbcf2db84.png new file mode 100644 index 000000000..c631aad70 Binary files /dev/null and b/_images/math/2bb98b9a2f25d98a0968eba7deb2f46bbcf2db84.png differ diff --git a/_images/math/2c2455aaac8b19ec0f81b93699f65652a7bb2757.png b/_images/math/2c2455aaac8b19ec0f81b93699f65652a7bb2757.png new file mode 100644 index 000000000..4a7801d85 Binary files /dev/null and b/_images/math/2c2455aaac8b19ec0f81b93699f65652a7bb2757.png differ diff --git a/_images/math/2c4a20d6466f0fccf721189621e17984f0b2cf13.png b/_images/math/2c4a20d6466f0fccf721189621e17984f0b2cf13.png new file mode 100644 index 000000000..3eccd06e6 Binary files /dev/null and b/_images/math/2c4a20d6466f0fccf721189621e17984f0b2cf13.png differ diff --git a/_images/math/2d82e6dd524217300976da17f7a988d7f263f47c.png b/_images/math/2d82e6dd524217300976da17f7a988d7f263f47c.png new file mode 100644 index 000000000..ac01830fc Binary files /dev/null and b/_images/math/2d82e6dd524217300976da17f7a988d7f263f47c.png differ diff --git a/_images/math/2edc5eeddc22a27d97b43dd58e8effdc3cdbb50e.png b/_images/math/2edc5eeddc22a27d97b43dd58e8effdc3cdbb50e.png new file mode 100644 index 000000000..a40be6571 Binary files /dev/null and b/_images/math/2edc5eeddc22a27d97b43dd58e8effdc3cdbb50e.png differ diff --git a/_images/math/315113e168ae1975826fc9fd887a0b36de4c4f3b.png b/_images/math/315113e168ae1975826fc9fd887a0b36de4c4f3b.png new file mode 100644 index 000000000..9218fd0e1 Binary files /dev/null and b/_images/math/315113e168ae1975826fc9fd887a0b36de4c4f3b.png differ diff --git a/_images/math/31ab61d088d20d402673a0114576392a6f0dee54.png b/_images/math/31ab61d088d20d402673a0114576392a6f0dee54.png new file mode 100644 index 000000000..e0ee02865 Binary files /dev/null and b/_images/math/31ab61d088d20d402673a0114576392a6f0dee54.png differ diff --git a/_images/math/31c1d5a6d4c546305ffba66da7f558eda91552c1.png b/_images/math/31c1d5a6d4c546305ffba66da7f558eda91552c1.png new file mode 100644 index 000000000..15098465e Binary files /dev/null and b/_images/math/31c1d5a6d4c546305ffba66da7f558eda91552c1.png differ diff --git a/_images/math/33d6733749a5ed01aece354a048f762268da7788.png b/_images/math/33d6733749a5ed01aece354a048f762268da7788.png new file mode 100644 index 000000000..5977c640b Binary files /dev/null and b/_images/math/33d6733749a5ed01aece354a048f762268da7788.png differ diff --git a/_images/math/3e35a1e2b879210a5efd985bacb7534ac67a39e5.png b/_images/math/3e35a1e2b879210a5efd985bacb7534ac67a39e5.png new file mode 100644 index 000000000..a2ef02c09 Binary files /dev/null and b/_images/math/3e35a1e2b879210a5efd985bacb7534ac67a39e5.png differ diff --git a/_images/math/3efddd4f2c121e38b96251d05a121e5ed5f45d48.png b/_images/math/3efddd4f2c121e38b96251d05a121e5ed5f45d48.png new file mode 100644 index 000000000..d9e2fed00 Binary files /dev/null and b/_images/math/3efddd4f2c121e38b96251d05a121e5ed5f45d48.png differ diff --git a/_images/math/42df65e173ad3a068b9ba1df3f04552c3d8891b7.png b/_images/math/42df65e173ad3a068b9ba1df3f04552c3d8891b7.png new file mode 100644 index 000000000..a00efcfda Binary files /dev/null and b/_images/math/42df65e173ad3a068b9ba1df3f04552c3d8891b7.png differ diff --git a/_images/math/49c18f96bb9f34727e1052f384360e52cad28111.png b/_images/math/49c18f96bb9f34727e1052f384360e52cad28111.png new file mode 100644 index 000000000..552a28287 Binary files /dev/null and b/_images/math/49c18f96bb9f34727e1052f384360e52cad28111.png differ diff --git a/_images/math/4acea62c9b4ccecc636c83b6786d4d89b0c185b6.png b/_images/math/4acea62c9b4ccecc636c83b6786d4d89b0c185b6.png new file mode 100644 index 000000000..e8d082396 Binary files /dev/null and b/_images/math/4acea62c9b4ccecc636c83b6786d4d89b0c185b6.png differ diff --git a/_images/math/54882a4fb7e897bef9ddefa43613e96b8f7f030a.png b/_images/math/54882a4fb7e897bef9ddefa43613e96b8f7f030a.png new file mode 100644 index 000000000..52fe9d2a3 Binary files /dev/null and b/_images/math/54882a4fb7e897bef9ddefa43613e96b8f7f030a.png differ diff --git a/_images/math/55c52550f69dbbc219f5cf1b8974f8f21697eb3e.png b/_images/math/55c52550f69dbbc219f5cf1b8974f8f21697eb3e.png new file mode 100644 index 000000000..c38d8a864 Binary files /dev/null and b/_images/math/55c52550f69dbbc219f5cf1b8974f8f21697eb3e.png differ diff --git a/_images/math/5e06117abf4deabc40d40dbf519bef8984aae52b.png b/_images/math/5e06117abf4deabc40d40dbf519bef8984aae52b.png new file mode 100644 index 000000000..bff650f76 Binary files /dev/null and b/_images/math/5e06117abf4deabc40d40dbf519bef8984aae52b.png differ diff --git a/_images/math/5f7c59773b684e323fe2c935297e92cacf7efb56.png b/_images/math/5f7c59773b684e323fe2c935297e92cacf7efb56.png new file mode 100644 index 000000000..dc1c10ed8 Binary files /dev/null and b/_images/math/5f7c59773b684e323fe2c935297e92cacf7efb56.png differ diff --git a/_images/math/5fc132397b70274cd203e1332f7d759e3c2b743c.png b/_images/math/5fc132397b70274cd203e1332f7d759e3c2b743c.png new file mode 100644 index 000000000..ba4c3966a Binary files /dev/null and b/_images/math/5fc132397b70274cd203e1332f7d759e3c2b743c.png differ diff --git a/_images/math/61ca0e4c620b72474cfef49a9578554be687b263.png b/_images/math/61ca0e4c620b72474cfef49a9578554be687b263.png new file mode 100644 index 000000000..e84d15b7f Binary files /dev/null and b/_images/math/61ca0e4c620b72474cfef49a9578554be687b263.png differ diff --git a/_images/math/62e0200c24671deae8cd46724de0c259b2cab1e3.png b/_images/math/62e0200c24671deae8cd46724de0c259b2cab1e3.png new file mode 100644 index 000000000..212ef2294 Binary files /dev/null and b/_images/math/62e0200c24671deae8cd46724de0c259b2cab1e3.png differ diff --git a/_images/math/65babba3ba65bcb0e73bdb5ebee5a7f3b7cf43f3.png b/_images/math/65babba3ba65bcb0e73bdb5ebee5a7f3b7cf43f3.png new file mode 100644 index 000000000..b044d4a70 Binary files /dev/null and b/_images/math/65babba3ba65bcb0e73bdb5ebee5a7f3b7cf43f3.png differ diff --git a/_images/math/66d092be32cdbbdc4ef4697b3f3fdb774a3ab300.png b/_images/math/66d092be32cdbbdc4ef4697b3f3fdb774a3ab300.png new file mode 100644 index 000000000..79f2f3a88 Binary files /dev/null and b/_images/math/66d092be32cdbbdc4ef4697b3f3fdb774a3ab300.png differ diff --git a/_images/math/690144ece687c16c209683f6ede856c7f75d49d5.png b/_images/math/690144ece687c16c209683f6ede856c7f75d49d5.png new file mode 100644 index 000000000..3458f6a22 Binary files /dev/null and b/_images/math/690144ece687c16c209683f6ede856c7f75d49d5.png differ diff --git a/_images/math/6f2f72bcef7c21a9f128fb0ae90f01834a21aaca.png b/_images/math/6f2f72bcef7c21a9f128fb0ae90f01834a21aaca.png new file mode 100644 index 000000000..1f04f3e63 Binary files /dev/null and b/_images/math/6f2f72bcef7c21a9f128fb0ae90f01834a21aaca.png differ diff --git a/_images/math/74eefd41f5d29e6f4ac551857ce003870ded7a34.png b/_images/math/74eefd41f5d29e6f4ac551857ce003870ded7a34.png new file mode 100644 index 000000000..3a2a8c53d Binary files /dev/null and b/_images/math/74eefd41f5d29e6f4ac551857ce003870ded7a34.png differ diff --git a/_images/math/7655245409c863d9d3c9ad7155003ce94ffc8723.png b/_images/math/7655245409c863d9d3c9ad7155003ce94ffc8723.png new file mode 100644 index 000000000..ffec79c45 Binary files /dev/null and b/_images/math/7655245409c863d9d3c9ad7155003ce94ffc8723.png differ diff --git a/_images/math/7829c6c02b1f51745ac93cd243dc9cdd4b713aeb.png b/_images/math/7829c6c02b1f51745ac93cd243dc9cdd4b713aeb.png new file mode 100644 index 000000000..728a86a4d Binary files /dev/null and b/_images/math/7829c6c02b1f51745ac93cd243dc9cdd4b713aeb.png differ diff --git a/_images/math/7d4583719a0951efcdf261a0358000868947ebda.png b/_images/math/7d4583719a0951efcdf261a0358000868947ebda.png new file mode 100644 index 000000000..bf1110ae9 Binary files /dev/null and b/_images/math/7d4583719a0951efcdf261a0358000868947ebda.png differ diff --git a/_images/math/7d5440d2e9acccd4a74906cd88037927faebabbb.png b/_images/math/7d5440d2e9acccd4a74906cd88037927faebabbb.png new file mode 100644 index 000000000..e73b5d44d Binary files /dev/null and b/_images/math/7d5440d2e9acccd4a74906cd88037927faebabbb.png differ diff --git a/_images/math/7dc7273a9277722cdc7a2f665fc345290846f5d3.png b/_images/math/7dc7273a9277722cdc7a2f665fc345290846f5d3.png new file mode 100644 index 000000000..669a2461e Binary files /dev/null and b/_images/math/7dc7273a9277722cdc7a2f665fc345290846f5d3.png differ diff --git a/_images/math/845891ac960ccd9ef061ce40d7067522cc18428e.png b/_images/math/845891ac960ccd9ef061ce40d7067522cc18428e.png new file mode 100644 index 000000000..6b087d0b6 Binary files /dev/null and b/_images/math/845891ac960ccd9ef061ce40d7067522cc18428e.png differ diff --git a/_images/math/852a035872b3556477446bc1c7f681047a27adab.png b/_images/math/852a035872b3556477446bc1c7f681047a27adab.png new file mode 100644 index 000000000..c09e0f707 Binary files /dev/null and b/_images/math/852a035872b3556477446bc1c7f681047a27adab.png differ diff --git a/_images/math/86c7fdea249af54b2c4b55bb85a090fe125a862f.png b/_images/math/86c7fdea249af54b2c4b55bb85a090fe125a862f.png new file mode 100644 index 000000000..3237073ea Binary files /dev/null and b/_images/math/86c7fdea249af54b2c4b55bb85a090fe125a862f.png differ diff --git a/_images/math/871fe6541feaaaf2364957d649f57484485b87bb.png b/_images/math/871fe6541feaaaf2364957d649f57484485b87bb.png new file mode 100644 index 000000000..0d017f1c6 Binary files /dev/null and b/_images/math/871fe6541feaaaf2364957d649f57484485b87bb.png differ diff --git a/_images/math/87a0378a8ba57f2b76c8e66facf031ff6125eafd.png b/_images/math/87a0378a8ba57f2b76c8e66facf031ff6125eafd.png new file mode 100644 index 000000000..4a36de1fc Binary files /dev/null and b/_images/math/87a0378a8ba57f2b76c8e66facf031ff6125eafd.png differ diff --git a/_images/math/87a3c6dab8a217f6c5fb3c0b5761096527b4f1e8.png b/_images/math/87a3c6dab8a217f6c5fb3c0b5761096527b4f1e8.png new file mode 100644 index 000000000..5a8c5c958 Binary files /dev/null and b/_images/math/87a3c6dab8a217f6c5fb3c0b5761096527b4f1e8.png differ diff --git a/_images/math/88690a927ae0da03920201434403ddb6da75a4d2.png b/_images/math/88690a927ae0da03920201434403ddb6da75a4d2.png new file mode 100644 index 000000000..3d65fc426 Binary files /dev/null and b/_images/math/88690a927ae0da03920201434403ddb6da75a4d2.png differ diff --git a/_images/math/8c4c9dd89ed681963329199e24469bfce8a7a5ab.png b/_images/math/8c4c9dd89ed681963329199e24469bfce8a7a5ab.png new file mode 100644 index 000000000..a0e0b9adc Binary files /dev/null and b/_images/math/8c4c9dd89ed681963329199e24469bfce8a7a5ab.png differ diff --git a/_images/math/8c62066b6fd82a8da734b015b734d7cde2c9b469.png b/_images/math/8c62066b6fd82a8da734b015b734d7cde2c9b469.png new file mode 100644 index 000000000..0a907c5b4 Binary files /dev/null and b/_images/math/8c62066b6fd82a8da734b015b734d7cde2c9b469.png differ diff --git a/_images/math/8d08575f5bfab62301a9311cb3896da806443ec6.png b/_images/math/8d08575f5bfab62301a9311cb3896da806443ec6.png new file mode 100644 index 000000000..3cb6c0ff2 Binary files /dev/null and b/_images/math/8d08575f5bfab62301a9311cb3896da806443ec6.png differ diff --git a/_images/math/8d3ce8ee017c993378edd5faffef3dcccea99701.png b/_images/math/8d3ce8ee017c993378edd5faffef3dcccea99701.png new file mode 100644 index 000000000..c6db75c7c Binary files /dev/null and b/_images/math/8d3ce8ee017c993378edd5faffef3dcccea99701.png differ diff --git a/_images/math/8db95e5d5d1effbae907758f6ab676b9f0b98047.png b/_images/math/8db95e5d5d1effbae907758f6ab676b9f0b98047.png new file mode 100644 index 000000000..b1b5361b9 Binary files /dev/null and b/_images/math/8db95e5d5d1effbae907758f6ab676b9f0b98047.png differ diff --git a/_images/math/91a20b74d76c0c30fe87c48742d16fbf4a8f1ffa.png b/_images/math/91a20b74d76c0c30fe87c48742d16fbf4a8f1ffa.png new file mode 100644 index 000000000..73de48663 Binary files /dev/null and b/_images/math/91a20b74d76c0c30fe87c48742d16fbf4a8f1ffa.png differ diff --git a/_images/math/941aa3a868e0d311fee43d16e3b158f58d0920ff.png b/_images/math/941aa3a868e0d311fee43d16e3b158f58d0920ff.png new file mode 100644 index 000000000..3faea8600 Binary files /dev/null and b/_images/math/941aa3a868e0d311fee43d16e3b158f58d0920ff.png differ diff --git a/_images/math/96df6109e1a61e3d54c6ded967bb870982f1ffd8.png b/_images/math/96df6109e1a61e3d54c6ded967bb870982f1ffd8.png new file mode 100644 index 000000000..f43ce7037 Binary files /dev/null and b/_images/math/96df6109e1a61e3d54c6ded967bb870982f1ffd8.png differ diff --git a/_images/math/96f49e3dc3f113f895f1b05fc2b217dd1fcc6e0e.png b/_images/math/96f49e3dc3f113f895f1b05fc2b217dd1fcc6e0e.png new file mode 100644 index 000000000..8ab528747 Binary files /dev/null and b/_images/math/96f49e3dc3f113f895f1b05fc2b217dd1fcc6e0e.png differ diff --git a/_images/math/97c3431ae9c6f23af431a890fd87fad1c1357ace.png b/_images/math/97c3431ae9c6f23af431a890fd87fad1c1357ace.png new file mode 100644 index 000000000..f8eb5f22f Binary files /dev/null and b/_images/math/97c3431ae9c6f23af431a890fd87fad1c1357ace.png differ diff --git a/_images/math/9937605052e86fe23588ba32b37b9e76b51e094a.png b/_images/math/9937605052e86fe23588ba32b37b9e76b51e094a.png new file mode 100644 index 000000000..3c5ae068b Binary files /dev/null and b/_images/math/9937605052e86fe23588ba32b37b9e76b51e094a.png differ diff --git a/_images/math/9c706f6b47111d944121cb1f45a8dc404429ef0e.png b/_images/math/9c706f6b47111d944121cb1f45a8dc404429ef0e.png new file mode 100644 index 000000000..e5bd07fe2 Binary files /dev/null and b/_images/math/9c706f6b47111d944121cb1f45a8dc404429ef0e.png differ diff --git a/_images/math/9c8499ac8c37cc47e3296e76d44f0f604df44132.png b/_images/math/9c8499ac8c37cc47e3296e76d44f0f604df44132.png new file mode 100644 index 000000000..15dabddd4 Binary files /dev/null and b/_images/math/9c8499ac8c37cc47e3296e76d44f0f604df44132.png differ diff --git a/_images/math/9e066869ef3bbcf0ad0ac5a852dd8ef2169a426a.png b/_images/math/9e066869ef3bbcf0ad0ac5a852dd8ef2169a426a.png new file mode 100644 index 000000000..f0bb6a1c0 Binary files /dev/null and b/_images/math/9e066869ef3bbcf0ad0ac5a852dd8ef2169a426a.png differ diff --git a/_images/math/9ebc7e819672ba9afece767f3abf1d83dbcd63a0.png b/_images/math/9ebc7e819672ba9afece767f3abf1d83dbcd63a0.png new file mode 100644 index 000000000..c66dc4f1e Binary files /dev/null and b/_images/math/9ebc7e819672ba9afece767f3abf1d83dbcd63a0.png differ diff --git a/_images/math/9ece7c680ec5d61ddfdddcd18c5d4efc72c66406.png b/_images/math/9ece7c680ec5d61ddfdddcd18c5d4efc72c66406.png new file mode 100644 index 000000000..abff054a6 Binary files /dev/null and b/_images/math/9ece7c680ec5d61ddfdddcd18c5d4efc72c66406.png differ diff --git a/_images/math/a4c8cfe28fa16fd756cd7e56855023f49b2eb072.png b/_images/math/a4c8cfe28fa16fd756cd7e56855023f49b2eb072.png new file mode 100644 index 000000000..2fb4d2db3 Binary files /dev/null and b/_images/math/a4c8cfe28fa16fd756cd7e56855023f49b2eb072.png differ diff --git a/_images/math/a7d5b17ba374282d4d9ce296ebbc8dbf5b097029.png b/_images/math/a7d5b17ba374282d4d9ce296ebbc8dbf5b097029.png new file mode 100644 index 000000000..c086cc535 Binary files /dev/null and b/_images/math/a7d5b17ba374282d4d9ce296ebbc8dbf5b097029.png differ diff --git a/_images/math/af834034a6c53018daeeceac62fe9275ddec5283.png b/_images/math/af834034a6c53018daeeceac62fe9275ddec5283.png new file mode 100644 index 000000000..d3f7e9d19 Binary files /dev/null and b/_images/math/af834034a6c53018daeeceac62fe9275ddec5283.png differ diff --git a/_images/math/bafb8d1c7a134fa0fdb9c181a95eb1d1a8ec1127.png b/_images/math/bafb8d1c7a134fa0fdb9c181a95eb1d1a8ec1127.png new file mode 100644 index 000000000..d11da84e3 Binary files /dev/null and b/_images/math/bafb8d1c7a134fa0fdb9c181a95eb1d1a8ec1127.png differ diff --git a/_images/math/bb6d5b51f013ecfd583f1bedad02c90b72bcc763.png b/_images/math/bb6d5b51f013ecfd583f1bedad02c90b72bcc763.png new file mode 100644 index 000000000..5a8318a66 Binary files /dev/null and b/_images/math/bb6d5b51f013ecfd583f1bedad02c90b72bcc763.png differ diff --git a/_images/math/bdc6fb5b814dab83afafbbf13ad35a8781599d91.png b/_images/math/bdc6fb5b814dab83afafbbf13ad35a8781599d91.png new file mode 100644 index 000000000..d33b83f0b Binary files /dev/null and b/_images/math/bdc6fb5b814dab83afafbbf13ad35a8781599d91.png differ diff --git a/_images/math/c0c0a28f277af72c69c5a93e91e8860ebccdc6d5.png b/_images/math/c0c0a28f277af72c69c5a93e91e8860ebccdc6d5.png new file mode 100644 index 000000000..7594154f0 Binary files /dev/null and b/_images/math/c0c0a28f277af72c69c5a93e91e8860ebccdc6d5.png differ diff --git a/_images/math/c2803dd22c9c72f0b0a940778c8ea97f20fbd20e.png b/_images/math/c2803dd22c9c72f0b0a940778c8ea97f20fbd20e.png new file mode 100644 index 000000000..453dc55a0 Binary files /dev/null and b/_images/math/c2803dd22c9c72f0b0a940778c8ea97f20fbd20e.png differ diff --git a/_images/math/c9c17fbbe59fbb7f5105ae6bd64125c048741aa7.png b/_images/math/c9c17fbbe59fbb7f5105ae6bd64125c048741aa7.png new file mode 100644 index 000000000..ff51c09c7 Binary files /dev/null and b/_images/math/c9c17fbbe59fbb7f5105ae6bd64125c048741aa7.png differ diff --git a/_images/math/cbcbe5b70673f82ab16297c75ab686153cdd1fbe.png b/_images/math/cbcbe5b70673f82ab16297c75ab686153cdd1fbe.png new file mode 100644 index 000000000..76e3412f4 Binary files /dev/null and b/_images/math/cbcbe5b70673f82ab16297c75ab686153cdd1fbe.png differ diff --git a/_images/math/ce9e03b3333a3e30bd09c1045ef8f6a66aa2aca2.png b/_images/math/ce9e03b3333a3e30bd09c1045ef8f6a66aa2aca2.png new file mode 100644 index 000000000..f46ae1f4a Binary files /dev/null and b/_images/math/ce9e03b3333a3e30bd09c1045ef8f6a66aa2aca2.png differ diff --git a/_images/math/d6447dccb982e1aeb477f4f9480c858f6914f6ab.png b/_images/math/d6447dccb982e1aeb477f4f9480c858f6914f6ab.png new file mode 100644 index 000000000..fe06cdb0d Binary files /dev/null and b/_images/math/d6447dccb982e1aeb477f4f9480c858f6914f6ab.png differ diff --git a/_images/math/dccd042b2581b9305938c8b45bcb0fa1fd150aeb.png b/_images/math/dccd042b2581b9305938c8b45bcb0fa1fd150aeb.png new file mode 100644 index 000000000..3f7e7a347 Binary files /dev/null and b/_images/math/dccd042b2581b9305938c8b45bcb0fa1fd150aeb.png differ diff --git a/_images/math/dedd7e039eb032e146f787a81be4109511bf5057.png b/_images/math/dedd7e039eb032e146f787a81be4109511bf5057.png new file mode 100644 index 000000000..1cf8b2f61 Binary files /dev/null and b/_images/math/dedd7e039eb032e146f787a81be4109511bf5057.png differ diff --git a/_images/math/e12fe74eef1183ffde178dcb29139bfd6adc40db.png b/_images/math/e12fe74eef1183ffde178dcb29139bfd6adc40db.png new file mode 100644 index 000000000..a4a1c3cfa Binary files /dev/null and b/_images/math/e12fe74eef1183ffde178dcb29139bfd6adc40db.png differ diff --git a/_images/math/e1a94c50c06dfd981c2aea7b5fb169f8b0ef1f49.png b/_images/math/e1a94c50c06dfd981c2aea7b5fb169f8b0ef1f49.png new file mode 100644 index 000000000..027220b16 Binary files /dev/null and b/_images/math/e1a94c50c06dfd981c2aea7b5fb169f8b0ef1f49.png differ diff --git a/_images/math/e48e495cd54ebcbbc8d80c879bb3b60984f62f2c.png b/_images/math/e48e495cd54ebcbbc8d80c879bb3b60984f62f2c.png new file mode 100644 index 000000000..e2c903edf Binary files /dev/null and b/_images/math/e48e495cd54ebcbbc8d80c879bb3b60984f62f2c.png differ diff --git a/_images/math/e5b2830928a0645b2478fedf0d18b14a63734f6c.png b/_images/math/e5b2830928a0645b2478fedf0d18b14a63734f6c.png new file mode 100644 index 000000000..726e45045 Binary files /dev/null and b/_images/math/e5b2830928a0645b2478fedf0d18b14a63734f6c.png differ diff --git a/_images/math/e71c3c9bb5e4d716694dbc5971834609700d2fdd.png b/_images/math/e71c3c9bb5e4d716694dbc5971834609700d2fdd.png new file mode 100644 index 000000000..2441b3a67 Binary files /dev/null and b/_images/math/e71c3c9bb5e4d716694dbc5971834609700d2fdd.png differ diff --git a/_images/math/e779dcb84440b985f094daf6e0e2d40e396f6d17.png b/_images/math/e779dcb84440b985f094daf6e0e2d40e396f6d17.png new file mode 100644 index 000000000..09223bbe9 Binary files /dev/null and b/_images/math/e779dcb84440b985f094daf6e0e2d40e396f6d17.png differ diff --git a/_images/math/ea0593b649e82af2501fa460dd9ef2da4a3df929.png b/_images/math/ea0593b649e82af2501fa460dd9ef2da4a3df929.png new file mode 100644 index 000000000..e276ac159 Binary files /dev/null and b/_images/math/ea0593b649e82af2501fa460dd9ef2da4a3df929.png differ diff --git a/_images/math/eab9fe524e3d4a293fb616d4473cb9b8e76bd84d.png b/_images/math/eab9fe524e3d4a293fb616d4473cb9b8e76bd84d.png new file mode 100644 index 000000000..c637c6f76 Binary files /dev/null and b/_images/math/eab9fe524e3d4a293fb616d4473cb9b8e76bd84d.png differ diff --git a/_images/math/f5625ee54ea1ae00751c9217bac7326617e7304e.png b/_images/math/f5625ee54ea1ae00751c9217bac7326617e7304e.png new file mode 100644 index 000000000..290cbcb22 Binary files /dev/null and b/_images/math/f5625ee54ea1ae00751c9217bac7326617e7304e.png differ diff --git a/_images/math/f61b5da8650ff7cadf9af583af4995d46719b05d.png b/_images/math/f61b5da8650ff7cadf9af583af4995d46719b05d.png new file mode 100644 index 000000000..3f93e3481 Binary files /dev/null and b/_images/math/f61b5da8650ff7cadf9af583af4995d46719b05d.png differ diff --git a/_images/math/f70563e6a076f5d5f06da4937280c9634551df1d.png b/_images/math/f70563e6a076f5d5f06da4937280c9634551df1d.png new file mode 100644 index 000000000..222f936e6 Binary files /dev/null and b/_images/math/f70563e6a076f5d5f06da4937280c9634551df1d.png differ diff --git a/_images/math/f793141d72b47f06d9b7de9b22f291463af662f7.png b/_images/math/f793141d72b47f06d9b7de9b22f291463af662f7.png new file mode 100644 index 000000000..7ca781adf Binary files /dev/null and b/_images/math/f793141d72b47f06d9b7de9b22f291463af662f7.png differ diff --git a/_images/math/fd5b2d7072e97ff273b49fd72fdc55ef2cccd453.png b/_images/math/fd5b2d7072e97ff273b49fd72fdc55ef2cccd453.png new file mode 100644 index 000000000..03ba470bb Binary files /dev/null and b/_images/math/fd5b2d7072e97ff273b49fd72fdc55ef2cccd453.png differ diff --git a/_images/math/fde8d210591ae11ee09a77cfd60ba28c104389c9.png b/_images/math/fde8d210591ae11ee09a77cfd60ba28c104389c9.png new file mode 100644 index 000000000..438aede6e Binary files /dev/null and b/_images/math/fde8d210591ae11ee09a77cfd60ba28c104389c9.png differ diff --git a/_images/moonlanding.png b/_images/moonlanding.png new file mode 100644 index 000000000..15e27b1e2 Binary files /dev/null and b/_images/moonlanding.png differ diff --git a/_images/morpho_mat.png b/_images/morpho_mat.png new file mode 100644 index 000000000..c4912868e Binary files /dev/null and b/_images/morpho_mat.png differ diff --git a/_images/morpho_mat1.png b/_images/morpho_mat1.png new file mode 100644 index 000000000..c4912868e Binary files /dev/null and b/_images/morpho_mat1.png differ diff --git a/_images/numpy_broadcasting.png b/_images/numpy_broadcasting.png new file mode 100644 index 000000000..3a7a0b43d Binary files /dev/null and b/_images/numpy_broadcasting.png differ diff --git a/_images/numpy_fancy_indexing.png b/_images/numpy_fancy_indexing.png new file mode 100644 index 000000000..87424985f Binary files /dev/null and b/_images/numpy_fancy_indexing.png differ diff --git a/_images/numpy_indexing.png b/_images/numpy_indexing.png new file mode 100644 index 000000000..72b5eb22f Binary files /dev/null and b/_images/numpy_indexing.png differ diff --git a/_images/plusBox.png b/_images/plusBox.png new file mode 100644 index 000000000..06b9a370b Binary files /dev/null and b/_images/plusBox.png differ diff --git a/_images/prime-sieve.png b/_images/prime-sieve.png new file mode 100644 index 000000000..c8511b525 Binary files /dev/null and b/_images/prime-sieve.png differ diff --git a/_images/python-logo.png b/_images/python-logo.png new file mode 100644 index 000000000..998f914c5 Binary files /dev/null and b/_images/python-logo.png differ diff --git a/_images/random_walk.png b/_images/random_walk.png new file mode 100644 index 000000000..281754a98 Binary files /dev/null and b/_images/random_walk.png differ diff --git a/_images/random_walk_schema.png b/_images/random_walk_schema.png new file mode 100644 index 000000000..cf14fbadb Binary files /dev/null and b/_images/random_walk_schema.png differ diff --git a/_images/reductions.png b/_images/reductions.png new file mode 100644 index 000000000..0e3131a1b Binary files /dev/null and b/_images/reductions.png differ diff --git a/_images/route66.png b/_images/route66.png new file mode 100644 index 000000000..1dadb5682 Binary files /dev/null and b/_images/route66.png differ diff --git a/_images/sands.png b/_images/sands.png new file mode 100644 index 000000000..189c62f49 Binary files /dev/null and b/_images/sands.png differ diff --git a/_images/scikit-learn-logo.png b/_images/scikit-learn-logo.png new file mode 100644 index 000000000..00bb261bd Binary files /dev/null and b/_images/scikit-learn-logo.png differ diff --git a/_images/scikit_image_logo.png b/_images/scikit_image_logo.png new file mode 100644 index 000000000..efd71678a Binary files /dev/null and b/_images/scikit_image_logo.png differ diff --git a/_images/sphx_glr_plot_1d_optim_001.png b/_images/sphx_glr_plot_1d_optim_001.png new file mode 100644 index 000000000..b189be7cf Binary files /dev/null and b/_images/sphx_glr_plot_1d_optim_001.png differ diff --git a/_images/sphx_glr_plot_1d_optim_002.png b/_images/sphx_glr_plot_1d_optim_002.png new file mode 100644 index 000000000..943baa9c5 Binary files /dev/null and b/_images/sphx_glr_plot_1d_optim_002.png differ diff --git a/_images/sphx_glr_plot_1d_optim_003.png b/_images/sphx_glr_plot_1d_optim_003.png new file mode 100644 index 000000000..5c886a5ea Binary files /dev/null and b/_images/sphx_glr_plot_1d_optim_003.png differ diff --git a/_images/sphx_glr_plot_1d_optim_004.png b/_images/sphx_glr_plot_1d_optim_004.png new file mode 100644 index 000000000..700197e75 Binary files /dev/null and b/_images/sphx_glr_plot_1d_optim_004.png differ diff --git a/_images/sphx_glr_plot_1d_optim_thumb.png b/_images/sphx_glr_plot_1d_optim_thumb.png new file mode 100644 index 000000000..41acc8fd1 Binary files /dev/null and b/_images/sphx_glr_plot_1d_optim_thumb.png differ diff --git a/_images/sphx_glr_plot_2d_minimization_001.png b/_images/sphx_glr_plot_2d_minimization_001.png new file mode 100644 index 000000000..1c654a43a Binary files /dev/null and b/_images/sphx_glr_plot_2d_minimization_001.png differ diff --git a/_images/sphx_glr_plot_2d_minimization_002.png b/_images/sphx_glr_plot_2d_minimization_002.png new file mode 100644 index 000000000..41da4c5a1 Binary files /dev/null and b/_images/sphx_glr_plot_2d_minimization_002.png differ diff --git a/_images/sphx_glr_plot_2d_minimization_003.png b/_images/sphx_glr_plot_2d_minimization_003.png new file mode 100644 index 000000000..9816de92f Binary files /dev/null and b/_images/sphx_glr_plot_2d_minimization_003.png differ diff --git a/_images/sphx_glr_plot_2d_minimization_thumb.png b/_images/sphx_glr_plot_2d_minimization_thumb.png new file mode 100644 index 000000000..284377efc Binary files /dev/null and b/_images/sphx_glr_plot_2d_minimization_thumb.png differ diff --git a/_images/sphx_glr_plot_GMM_001.png b/_images/sphx_glr_plot_GMM_001.png new file mode 100644 index 000000000..922378aa5 Binary files /dev/null and b/_images/sphx_glr_plot_GMM_001.png differ diff --git a/_images/sphx_glr_plot_GMM_thumb.png b/_images/sphx_glr_plot_GMM_thumb.png new file mode 100644 index 000000000..6cc376702 Binary files /dev/null and b/_images/sphx_glr_plot_GMM_thumb.png differ diff --git a/_images/sphx_glr_plot_ML_flow_chart_001.png b/_images/sphx_glr_plot_ML_flow_chart_001.png new file mode 100644 index 000000000..f510ad4d3 Binary files /dev/null and b/_images/sphx_glr_plot_ML_flow_chart_001.png differ diff --git a/_images/sphx_glr_plot_ML_flow_chart_002.png b/_images/sphx_glr_plot_ML_flow_chart_002.png new file mode 100644 index 000000000..ae0574e7d Binary files /dev/null and b/_images/sphx_glr_plot_ML_flow_chart_002.png differ diff --git a/_images/sphx_glr_plot_ML_flow_chart_003.png b/_images/sphx_glr_plot_ML_flow_chart_003.png new file mode 100644 index 000000000..efc4ef6dd Binary files /dev/null and b/_images/sphx_glr_plot_ML_flow_chart_003.png differ diff --git a/_images/sphx_glr_plot_ML_flow_chart_thumb.png b/_images/sphx_glr_plot_ML_flow_chart_thumb.png new file mode 100644 index 000000000..f018e763c Binary files /dev/null and b/_images/sphx_glr_plot_ML_flow_chart_thumb.png differ diff --git a/_images/sphx_glr_plot_airfare_001.png b/_images/sphx_glr_plot_airfare_001.png new file mode 100644 index 000000000..f39fc477b Binary files /dev/null and b/_images/sphx_glr_plot_airfare_001.png differ diff --git a/_images/sphx_glr_plot_airfare_002.png b/_images/sphx_glr_plot_airfare_002.png new file mode 100644 index 000000000..de0a8c683 Binary files /dev/null and b/_images/sphx_glr_plot_airfare_002.png differ diff --git a/_images/sphx_glr_plot_airfare_003.png b/_images/sphx_glr_plot_airfare_003.png new file mode 100644 index 000000000..a516ee48e Binary files /dev/null and b/_images/sphx_glr_plot_airfare_003.png differ diff --git a/_images/sphx_glr_plot_airfare_004.png b/_images/sphx_glr_plot_airfare_004.png new file mode 100644 index 000000000..1fdf3c20e Binary files /dev/null and b/_images/sphx_glr_plot_airfare_004.png differ diff --git a/_images/sphx_glr_plot_airfare_005.png b/_images/sphx_glr_plot_airfare_005.png new file mode 100644 index 000000000..af1f585a4 Binary files /dev/null and b/_images/sphx_glr_plot_airfare_005.png differ diff --git a/_images/sphx_glr_plot_airfare_thumb.png b/_images/sphx_glr_plot_airfare_thumb.png new file mode 100644 index 000000000..dbe62e8a0 Binary files /dev/null and b/_images/sphx_glr_plot_airfare_thumb.png differ diff --git a/_images/sphx_glr_plot_aliased_001.png b/_images/sphx_glr_plot_aliased_001.png new file mode 100644 index 000000000..d95e89c7c Binary files /dev/null and b/_images/sphx_glr_plot_aliased_001.png differ diff --git a/_images/sphx_glr_plot_aliased_thumb.png b/_images/sphx_glr_plot_aliased_thumb.png new file mode 100644 index 000000000..83dc9b0b9 Binary files /dev/null and b/_images/sphx_glr_plot_aliased_thumb.png differ diff --git a/_images/sphx_glr_plot_alpha_001.png b/_images/sphx_glr_plot_alpha_001.png new file mode 100644 index 000000000..191134e47 Binary files /dev/null and b/_images/sphx_glr_plot_alpha_001.png differ diff --git a/_images/sphx_glr_plot_alpha_thumb.png b/_images/sphx_glr_plot_alpha_thumb.png new file mode 100644 index 000000000..828443842 Binary files /dev/null and b/_images/sphx_glr_plot_alpha_thumb.png differ diff --git a/_images/sphx_glr_plot_antialiased_001.png b/_images/sphx_glr_plot_antialiased_001.png new file mode 100644 index 000000000..fc6ed6181 Binary files /dev/null and b/_images/sphx_glr_plot_antialiased_001.png differ diff --git a/_images/sphx_glr_plot_antialiased_thumb.png b/_images/sphx_glr_plot_antialiased_thumb.png new file mode 100644 index 000000000..58131d659 Binary files /dev/null and b/_images/sphx_glr_plot_antialiased_thumb.png differ diff --git a/_images/sphx_glr_plot_axes-2_001.png b/_images/sphx_glr_plot_axes-2_001.png new file mode 100644 index 000000000..f1db510ba Binary files /dev/null and b/_images/sphx_glr_plot_axes-2_001.png differ diff --git a/_images/sphx_glr_plot_axes-2_thumb.png b/_images/sphx_glr_plot_axes-2_thumb.png new file mode 100644 index 000000000..713b20cd6 Binary files /dev/null and b/_images/sphx_glr_plot_axes-2_thumb.png differ diff --git a/_images/sphx_glr_plot_axes_001.png b/_images/sphx_glr_plot_axes_001.png new file mode 100644 index 000000000..64a5a33b4 Binary files /dev/null and b/_images/sphx_glr_plot_axes_001.png differ diff --git a/_images/sphx_glr_plot_axes_thumb.png b/_images/sphx_glr_plot_axes_thumb.png new file mode 100644 index 000000000..050388c8d Binary files /dev/null and b/_images/sphx_glr_plot_axes_thumb.png differ diff --git a/_images/sphx_glr_plot_bad_001.png b/_images/sphx_glr_plot_bad_001.png new file mode 100644 index 000000000..fb2a30e76 Binary files /dev/null and b/_images/sphx_glr_plot_bad_001.png differ diff --git a/_images/sphx_glr_plot_bad_thumb.png b/_images/sphx_glr_plot_bad_thumb.png new file mode 100644 index 000000000..4191cb238 Binary files /dev/null and b/_images/sphx_glr_plot_bad_thumb.png differ diff --git a/_images/sphx_glr_plot_bar_001.png b/_images/sphx_glr_plot_bar_001.png new file mode 100644 index 000000000..e55b445e9 Binary files /dev/null and b/_images/sphx_glr_plot_bar_001.png differ diff --git a/_images/sphx_glr_plot_bar_ext_001.png b/_images/sphx_glr_plot_bar_ext_001.png new file mode 100644 index 000000000..6779cf6b1 Binary files /dev/null and b/_images/sphx_glr_plot_bar_ext_001.png differ diff --git a/_images/sphx_glr_plot_bar_ext_thumb.png b/_images/sphx_glr_plot_bar_ext_thumb.png new file mode 100644 index 000000000..58ada37fa Binary files /dev/null and b/_images/sphx_glr_plot_bar_ext_thumb.png differ diff --git a/_images/sphx_glr_plot_bar_thumb.png b/_images/sphx_glr_plot_bar_thumb.png new file mode 100644 index 000000000..ed4203531 Binary files /dev/null and b/_images/sphx_glr_plot_bar_thumb.png differ diff --git a/_images/sphx_glr_plot_basic1dplot_001.png b/_images/sphx_glr_plot_basic1dplot_001.png new file mode 100644 index 000000000..76649b223 Binary files /dev/null and b/_images/sphx_glr_plot_basic1dplot_001.png differ diff --git a/_images/sphx_glr_plot_basic1dplot_thumb.png b/_images/sphx_glr_plot_basic1dplot_thumb.png new file mode 100644 index 000000000..811dbbbd6 Binary files /dev/null and b/_images/sphx_glr_plot_basic1dplot_thumb.png differ diff --git a/_images/sphx_glr_plot_basic2dplot_001.png b/_images/sphx_glr_plot_basic2dplot_001.png new file mode 100644 index 000000000..7be8f4931 Binary files /dev/null and b/_images/sphx_glr_plot_basic2dplot_001.png differ diff --git a/_images/sphx_glr_plot_basic2dplot_thumb.png b/_images/sphx_glr_plot_basic2dplot_thumb.png new file mode 100644 index 000000000..41514233c Binary files /dev/null and b/_images/sphx_glr_plot_basic2dplot_thumb.png differ diff --git a/_images/sphx_glr_plot_bias_variance_001.png b/_images/sphx_glr_plot_bias_variance_001.png new file mode 100644 index 000000000..f9af9e710 Binary files /dev/null and b/_images/sphx_glr_plot_bias_variance_001.png differ diff --git a/_images/sphx_glr_plot_bias_variance_002.png b/_images/sphx_glr_plot_bias_variance_002.png new file mode 100644 index 000000000..4b80e6d36 Binary files /dev/null and b/_images/sphx_glr_plot_bias_variance_002.png differ diff --git a/_images/sphx_glr_plot_bias_variance_003.png b/_images/sphx_glr_plot_bias_variance_003.png new file mode 100644 index 000000000..ab9cab0fc Binary files /dev/null and b/_images/sphx_glr_plot_bias_variance_003.png differ diff --git a/_images/sphx_glr_plot_bias_variance_004.png b/_images/sphx_glr_plot_bias_variance_004.png new file mode 100644 index 000000000..21911b0da Binary files /dev/null and b/_images/sphx_glr_plot_bias_variance_004.png differ diff --git a/_images/sphx_glr_plot_bias_variance_005.png b/_images/sphx_glr_plot_bias_variance_005.png new file mode 100644 index 000000000..d0cb9338d Binary files /dev/null and b/_images/sphx_glr_plot_bias_variance_005.png differ diff --git a/_images/sphx_glr_plot_bias_variance_006.png b/_images/sphx_glr_plot_bias_variance_006.png new file mode 100644 index 000000000..0e5f0bc69 Binary files /dev/null and b/_images/sphx_glr_plot_bias_variance_006.png differ diff --git a/_images/sphx_glr_plot_bias_variance_thumb.png b/_images/sphx_glr_plot_bias_variance_thumb.png new file mode 100644 index 000000000..810e791d9 Binary files /dev/null and b/_images/sphx_glr_plot_bias_variance_thumb.png differ diff --git a/_images/sphx_glr_plot_block_mean_001.png b/_images/sphx_glr_plot_block_mean_001.png new file mode 100644 index 000000000..cc91ec39a Binary files /dev/null and b/_images/sphx_glr_plot_block_mean_001.png differ diff --git a/_images/sphx_glr_plot_block_mean_thumb.png b/_images/sphx_glr_plot_block_mean_thumb.png new file mode 100644 index 000000000..128fe01c5 Binary files /dev/null and b/_images/sphx_glr_plot_block_mean_thumb.png differ diff --git a/_images/sphx_glr_plot_blur_001.png b/_images/sphx_glr_plot_blur_001.png new file mode 100644 index 000000000..cae19083a Binary files /dev/null and b/_images/sphx_glr_plot_blur_001.png differ diff --git a/_images/sphx_glr_plot_blur_thumb.png b/_images/sphx_glr_plot_blur_thumb.png new file mode 100644 index 000000000..64f3c3f8b Binary files /dev/null and b/_images/sphx_glr_plot_blur_thumb.png differ diff --git a/_images/sphx_glr_plot_boundaries_001.png b/_images/sphx_glr_plot_boundaries_001.png new file mode 100644 index 000000000..9b6c287ab Binary files /dev/null and b/_images/sphx_glr_plot_boundaries_001.png differ diff --git a/_images/sphx_glr_plot_boundaries_thumb.png b/_images/sphx_glr_plot_boundaries_thumb.png new file mode 100644 index 000000000..4c2b51aff Binary files /dev/null and b/_images/sphx_glr_plot_boundaries_thumb.png differ diff --git a/_images/sphx_glr_plot_boxplot_ext_001.png b/_images/sphx_glr_plot_boxplot_ext_001.png new file mode 100644 index 000000000..e906b2b36 Binary files /dev/null and b/_images/sphx_glr_plot_boxplot_ext_001.png differ diff --git a/_images/sphx_glr_plot_boxplot_ext_thumb.png b/_images/sphx_glr_plot_boxplot_ext_thumb.png new file mode 100644 index 000000000..42c74bfc2 Binary files /dev/null and b/_images/sphx_glr_plot_boxplot_ext_thumb.png differ diff --git a/_images/sphx_glr_plot_brain_size_001.png b/_images/sphx_glr_plot_brain_size_001.png new file mode 100644 index 000000000..b1d9a75a9 Binary files /dev/null and b/_images/sphx_glr_plot_brain_size_001.png differ diff --git a/_images/sphx_glr_plot_brain_size_thumb.png b/_images/sphx_glr_plot_brain_size_thumb.png new file mode 100644 index 000000000..25d4aa87c Binary files /dev/null and b/_images/sphx_glr_plot_brain_size_thumb.png differ diff --git a/_images/sphx_glr_plot_california_prediction_001.png b/_images/sphx_glr_plot_california_prediction_001.png new file mode 100644 index 000000000..37fc0e186 Binary files /dev/null and b/_images/sphx_glr_plot_california_prediction_001.png differ diff --git a/_images/sphx_glr_plot_california_prediction_002.png b/_images/sphx_glr_plot_california_prediction_002.png new file mode 100644 index 000000000..9dec2b412 Binary files /dev/null and b/_images/sphx_glr_plot_california_prediction_002.png differ diff --git a/_images/sphx_glr_plot_california_prediction_003.png b/_images/sphx_glr_plot_california_prediction_003.png new file mode 100644 index 000000000..dd84615d9 Binary files /dev/null and b/_images/sphx_glr_plot_california_prediction_003.png differ diff --git a/_images/sphx_glr_plot_california_prediction_004.png b/_images/sphx_glr_plot_california_prediction_004.png new file mode 100644 index 000000000..bebec8339 Binary files /dev/null and b/_images/sphx_glr_plot_california_prediction_004.png differ diff --git a/_images/sphx_glr_plot_california_prediction_005.png b/_images/sphx_glr_plot_california_prediction_005.png new file mode 100644 index 000000000..50ef0dc9c Binary files /dev/null and b/_images/sphx_glr_plot_california_prediction_005.png differ diff --git a/_images/sphx_glr_plot_california_prediction_006.png b/_images/sphx_glr_plot_california_prediction_006.png new file mode 100644 index 000000000..cef0f36d4 Binary files /dev/null and b/_images/sphx_glr_plot_california_prediction_006.png differ diff --git a/_images/sphx_glr_plot_california_prediction_007.png b/_images/sphx_glr_plot_california_prediction_007.png new file mode 100644 index 000000000..59c2c15c1 Binary files /dev/null and b/_images/sphx_glr_plot_california_prediction_007.png differ diff --git a/_images/sphx_glr_plot_california_prediction_008.png b/_images/sphx_glr_plot_california_prediction_008.png new file mode 100644 index 000000000..7f4f31f64 Binary files /dev/null and b/_images/sphx_glr_plot_california_prediction_008.png differ diff --git a/_images/sphx_glr_plot_california_prediction_009.png b/_images/sphx_glr_plot_california_prediction_009.png new file mode 100644 index 000000000..1614cea8d Binary files /dev/null and b/_images/sphx_glr_plot_california_prediction_009.png differ diff --git a/_images/sphx_glr_plot_california_prediction_010.png b/_images/sphx_glr_plot_california_prediction_010.png new file mode 100644 index 000000000..3e7067c13 Binary files /dev/null and b/_images/sphx_glr_plot_california_prediction_010.png differ diff --git a/_images/sphx_glr_plot_california_prediction_011.png b/_images/sphx_glr_plot_california_prediction_011.png new file mode 100644 index 000000000..1ecabf459 Binary files /dev/null and b/_images/sphx_glr_plot_california_prediction_011.png differ diff --git a/_images/sphx_glr_plot_california_prediction_thumb.png b/_images/sphx_glr_plot_california_prediction_thumb.png new file mode 100644 index 000000000..992194dcb Binary files /dev/null and b/_images/sphx_glr_plot_california_prediction_thumb.png differ diff --git a/_images/sphx_glr_plot_camera_001.png b/_images/sphx_glr_plot_camera_001.png new file mode 100644 index 000000000..cf0326337 Binary files /dev/null and b/_images/sphx_glr_plot_camera_001.png differ diff --git a/_images/sphx_glr_plot_camera_thumb.png b/_images/sphx_glr_plot_camera_thumb.png new file mode 100644 index 000000000..b42d9659d Binary files /dev/null and b/_images/sphx_glr_plot_camera_thumb.png differ diff --git a/_images/sphx_glr_plot_camera_uint_001.png b/_images/sphx_glr_plot_camera_uint_001.png new file mode 100644 index 000000000..e6df4ea67 Binary files /dev/null and b/_images/sphx_glr_plot_camera_uint_001.png differ diff --git a/_images/sphx_glr_plot_camera_uint_thumb.png b/_images/sphx_glr_plot_camera_uint_thumb.png new file mode 100644 index 000000000..9597d7d14 Binary files /dev/null and b/_images/sphx_glr_plot_camera_uint_thumb.png differ diff --git a/_images/sphx_glr_plot_chebyfit_001.png b/_images/sphx_glr_plot_chebyfit_001.png new file mode 100644 index 000000000..97c7e548e Binary files /dev/null and b/_images/sphx_glr_plot_chebyfit_001.png differ diff --git a/_images/sphx_glr_plot_chebyfit_thumb.png b/_images/sphx_glr_plot_chebyfit_thumb.png new file mode 100644 index 000000000..9b8d60077 Binary files /dev/null and b/_images/sphx_glr_plot_chebyfit_thumb.png differ diff --git a/_images/sphx_glr_plot_check_001.png b/_images/sphx_glr_plot_check_001.png new file mode 100644 index 000000000..e9ea4d1e0 Binary files /dev/null and b/_images/sphx_glr_plot_check_001.png differ diff --git a/_images/sphx_glr_plot_check_thumb.png b/_images/sphx_glr_plot_check_thumb.png new file mode 100644 index 000000000..0f71752b2 Binary files /dev/null and b/_images/sphx_glr_plot_check_thumb.png differ diff --git a/_images/sphx_glr_plot_clean_morpho_001.png b/_images/sphx_glr_plot_clean_morpho_001.png new file mode 100644 index 000000000..4bb066de5 Binary files /dev/null and b/_images/sphx_glr_plot_clean_morpho_001.png differ diff --git a/_images/sphx_glr_plot_clean_morpho_thumb.png b/_images/sphx_glr_plot_clean_morpho_thumb.png new file mode 100644 index 000000000..69b7230e8 Binary files /dev/null and b/_images/sphx_glr_plot_clean_morpho_thumb.png differ diff --git a/_images/sphx_glr_plot_color_001.png b/_images/sphx_glr_plot_color_001.png new file mode 100644 index 000000000..d4c70e811 Binary files /dev/null and b/_images/sphx_glr_plot_color_001.png differ diff --git a/_images/sphx_glr_plot_color_thumb.png b/_images/sphx_glr_plot_color_thumb.png new file mode 100644 index 000000000..1c6d1571e Binary files /dev/null and b/_images/sphx_glr_plot_color_thumb.png differ diff --git a/_images/sphx_glr_plot_colormaps_001.png b/_images/sphx_glr_plot_colormaps_001.png new file mode 100644 index 000000000..db5d5bfb2 Binary files /dev/null and b/_images/sphx_glr_plot_colormaps_001.png differ diff --git a/_images/sphx_glr_plot_colormaps_thumb.png b/_images/sphx_glr_plot_colormaps_thumb.png new file mode 100644 index 000000000..37c55ed2f Binary files /dev/null and b/_images/sphx_glr_plot_colormaps_thumb.png differ diff --git a/_images/sphx_glr_plot_compare_classifiers_thumb.png b/_images/sphx_glr_plot_compare_classifiers_thumb.png new file mode 100644 index 000000000..8a5fed589 Binary files /dev/null and b/_images/sphx_glr_plot_compare_classifiers_thumb.png differ diff --git a/_images/sphx_glr_plot_compare_optimizers_001.png b/_images/sphx_glr_plot_compare_optimizers_001.png new file mode 100644 index 000000000..49a0050ef Binary files /dev/null and b/_images/sphx_glr_plot_compare_optimizers_001.png differ diff --git a/_images/sphx_glr_plot_compare_optimizers_thumb.png b/_images/sphx_glr_plot_compare_optimizers_thumb.png new file mode 100644 index 000000000..ab0f87313 Binary files /dev/null and b/_images/sphx_glr_plot_compare_optimizers_thumb.png differ diff --git a/_images/sphx_glr_plot_connect_measurements_001.png b/_images/sphx_glr_plot_connect_measurements_001.png new file mode 100644 index 000000000..04bb7772e Binary files /dev/null and b/_images/sphx_glr_plot_connect_measurements_001.png differ diff --git a/_images/sphx_glr_plot_connect_measurements_002.png b/_images/sphx_glr_plot_connect_measurements_002.png new file mode 100644 index 000000000..15963f8db Binary files /dev/null and b/_images/sphx_glr_plot_connect_measurements_002.png differ diff --git a/_images/sphx_glr_plot_connect_measurements_003.png b/_images/sphx_glr_plot_connect_measurements_003.png new file mode 100644 index 000000000..98622f978 Binary files /dev/null and b/_images/sphx_glr_plot_connect_measurements_003.png differ diff --git a/_images/sphx_glr_plot_connect_measurements_thumb.png b/_images/sphx_glr_plot_connect_measurements_thumb.png new file mode 100644 index 000000000..7ef983111 Binary files /dev/null and b/_images/sphx_glr_plot_connect_measurements_thumb.png differ diff --git a/_images/sphx_glr_plot_constraints_001.png b/_images/sphx_glr_plot_constraints_001.png new file mode 100644 index 000000000..4aee9a18e Binary files /dev/null and b/_images/sphx_glr_plot_constraints_001.png differ diff --git a/_images/sphx_glr_plot_constraints_002.png b/_images/sphx_glr_plot_constraints_002.png new file mode 100644 index 000000000..3756e5bf3 Binary files /dev/null and b/_images/sphx_glr_plot_constraints_002.png differ diff --git a/_images/sphx_glr_plot_constraints_thumb.png b/_images/sphx_glr_plot_constraints_thumb.png new file mode 100644 index 000000000..9d0aa77a7 Binary files /dev/null and b/_images/sphx_glr_plot_constraints_thumb.png differ diff --git a/_images/sphx_glr_plot_contour_001.png b/_images/sphx_glr_plot_contour_001.png new file mode 100644 index 000000000..7789a196c Binary files /dev/null and b/_images/sphx_glr_plot_contour_001.png differ diff --git a/_images/sphx_glr_plot_contour_ext_001.png b/_images/sphx_glr_plot_contour_ext_001.png new file mode 100644 index 000000000..84df17e59 Binary files /dev/null and b/_images/sphx_glr_plot_contour_ext_001.png differ diff --git a/_images/sphx_glr_plot_contour_ext_thumb.png b/_images/sphx_glr_plot_contour_ext_thumb.png new file mode 100644 index 000000000..998cb9c6e Binary files /dev/null and b/_images/sphx_glr_plot_contour_ext_thumb.png differ diff --git a/_images/sphx_glr_plot_contour_thumb.png b/_images/sphx_glr_plot_contour_thumb.png new file mode 100644 index 000000000..554d104a3 Binary files /dev/null and b/_images/sphx_glr_plot_contour_thumb.png differ diff --git a/_images/sphx_glr_plot_convex_001.png b/_images/sphx_glr_plot_convex_001.png new file mode 100644 index 000000000..c27a076ea Binary files /dev/null and b/_images/sphx_glr_plot_convex_001.png differ diff --git a/_images/sphx_glr_plot_convex_002.png b/_images/sphx_glr_plot_convex_002.png new file mode 100644 index 000000000..0adcb744f Binary files /dev/null and b/_images/sphx_glr_plot_convex_002.png differ diff --git a/_images/sphx_glr_plot_convex_thumb.png b/_images/sphx_glr_plot_convex_thumb.png new file mode 100644 index 000000000..2da90a8c0 Binary files /dev/null and b/_images/sphx_glr_plot_convex_thumb.png differ diff --git a/_images/sphx_glr_plot_cumulative_wind_speed_prediction_001.png b/_images/sphx_glr_plot_cumulative_wind_speed_prediction_001.png new file mode 100644 index 000000000..f86a743d6 Binary files /dev/null and b/_images/sphx_glr_plot_cumulative_wind_speed_prediction_001.png differ diff --git a/_images/sphx_glr_plot_cumulative_wind_speed_prediction_thumb.png b/_images/sphx_glr_plot_cumulative_wind_speed_prediction_thumb.png new file mode 100644 index 000000000..69eae9ea6 Binary files /dev/null and b/_images/sphx_glr_plot_cumulative_wind_speed_prediction_thumb.png differ diff --git a/_images/sphx_glr_plot_curve_fit_001.png b/_images/sphx_glr_plot_curve_fit_001.png new file mode 100644 index 000000000..d44c0a776 Binary files /dev/null and b/_images/sphx_glr_plot_curve_fit_001.png differ diff --git a/_images/sphx_glr_plot_curve_fit_002.png b/_images/sphx_glr_plot_curve_fit_002.png new file mode 100644 index 000000000..3232f5665 Binary files /dev/null and b/_images/sphx_glr_plot_curve_fit_002.png differ diff --git a/_images/sphx_glr_plot_curve_fit_thumb.png b/_images/sphx_glr_plot_curve_fit_thumb.png new file mode 100644 index 000000000..ac3e9e570 Binary files /dev/null and b/_images/sphx_glr_plot_curve_fit_thumb.png differ diff --git a/_images/sphx_glr_plot_curve_fitting_001.png b/_images/sphx_glr_plot_curve_fitting_001.png new file mode 100644 index 000000000..f003fa232 Binary files /dev/null and b/_images/sphx_glr_plot_curve_fitting_001.png differ diff --git a/_images/sphx_glr_plot_curve_fitting_thumb.png b/_images/sphx_glr_plot_curve_fitting_thumb.png new file mode 100644 index 000000000..7db603d5d Binary files /dev/null and b/_images/sphx_glr_plot_curve_fitting_thumb.png differ diff --git a/_images/sphx_glr_plot_curvefit_temperature_data_001.png b/_images/sphx_glr_plot_curvefit_temperature_data_001.png new file mode 100644 index 000000000..7b09a78b4 Binary files /dev/null and b/_images/sphx_glr_plot_curvefit_temperature_data_001.png differ diff --git a/_images/sphx_glr_plot_curvefit_temperature_data_002.png b/_images/sphx_glr_plot_curvefit_temperature_data_002.png new file mode 100644 index 000000000..02b7ac596 Binary files /dev/null and b/_images/sphx_glr_plot_curvefit_temperature_data_002.png differ diff --git a/_images/sphx_glr_plot_curvefit_temperature_data_thumb.png b/_images/sphx_glr_plot_curvefit_temperature_data_thumb.png new file mode 100644 index 000000000..5f2a28547 Binary files /dev/null and b/_images/sphx_glr_plot_curvefit_temperature_data_thumb.png differ diff --git a/_images/sphx_glr_plot_dash_capstyle_001.png b/_images/sphx_glr_plot_dash_capstyle_001.png new file mode 100644 index 000000000..b86251cf2 Binary files /dev/null and b/_images/sphx_glr_plot_dash_capstyle_001.png differ diff --git a/_images/sphx_glr_plot_dash_capstyle_thumb.png b/_images/sphx_glr_plot_dash_capstyle_thumb.png new file mode 100644 index 000000000..12aebebfe Binary files /dev/null and b/_images/sphx_glr_plot_dash_capstyle_thumb.png differ diff --git a/_images/sphx_glr_plot_dash_joinstyle_001.png b/_images/sphx_glr_plot_dash_joinstyle_001.png new file mode 100644 index 000000000..7b7f211a7 Binary files /dev/null and b/_images/sphx_glr_plot_dash_joinstyle_001.png differ diff --git a/_images/sphx_glr_plot_dash_joinstyle_thumb.png b/_images/sphx_glr_plot_dash_joinstyle_thumb.png new file mode 100644 index 000000000..9f1d39317 Binary files /dev/null and b/_images/sphx_glr_plot_dash_joinstyle_thumb.png differ diff --git a/_images/sphx_glr_plot_denoising_001.png b/_images/sphx_glr_plot_denoising_001.png new file mode 100644 index 000000000..9c1e426af Binary files /dev/null and b/_images/sphx_glr_plot_denoising_001.png differ diff --git a/_images/sphx_glr_plot_denoising_thumb.png b/_images/sphx_glr_plot_denoising_thumb.png new file mode 100644 index 000000000..e9fd7212d Binary files /dev/null and b/_images/sphx_glr_plot_denoising_thumb.png differ diff --git a/_images/sphx_glr_plot_detrend_001.png b/_images/sphx_glr_plot_detrend_001.png new file mode 100644 index 000000000..7150c58d8 Binary files /dev/null and b/_images/sphx_glr_plot_detrend_001.png differ diff --git a/_images/sphx_glr_plot_detrend_thumb.png b/_images/sphx_glr_plot_detrend_thumb.png new file mode 100644 index 000000000..6b33c822a Binary files /dev/null and b/_images/sphx_glr_plot_detrend_thumb.png differ diff --git a/_images/sphx_glr_plot_digits_simple_classif_001.png b/_images/sphx_glr_plot_digits_simple_classif_001.png new file mode 100644 index 000000000..9000a3f52 Binary files /dev/null and b/_images/sphx_glr_plot_digits_simple_classif_001.png differ diff --git a/_images/sphx_glr_plot_digits_simple_classif_002.png b/_images/sphx_glr_plot_digits_simple_classif_002.png new file mode 100644 index 000000000..a63078d94 Binary files /dev/null and b/_images/sphx_glr_plot_digits_simple_classif_002.png differ diff --git a/_images/sphx_glr_plot_digits_simple_classif_003.png b/_images/sphx_glr_plot_digits_simple_classif_003.png new file mode 100644 index 000000000..ce0189765 Binary files /dev/null and b/_images/sphx_glr_plot_digits_simple_classif_003.png differ diff --git a/_images/sphx_glr_plot_digits_simple_classif_thumb.png b/_images/sphx_glr_plot_digits_simple_classif_thumb.png new file mode 100644 index 000000000..702fe9543 Binary files /dev/null and b/_images/sphx_glr_plot_digits_simple_classif_thumb.png differ diff --git a/_images/sphx_glr_plot_display_face_001.png b/_images/sphx_glr_plot_display_face_001.png new file mode 100644 index 000000000..56d3b6f19 Binary files /dev/null and b/_images/sphx_glr_plot_display_face_001.png differ diff --git a/_images/sphx_glr_plot_display_face_thumb.png b/_images/sphx_glr_plot_display_face_thumb.png new file mode 100644 index 000000000..22ab32db0 Binary files /dev/null and b/_images/sphx_glr_plot_display_face_thumb.png differ diff --git a/_images/sphx_glr_plot_distances_001.png b/_images/sphx_glr_plot_distances_001.png new file mode 100644 index 000000000..5a8c214b3 Binary files /dev/null and b/_images/sphx_glr_plot_distances_001.png differ diff --git a/_images/sphx_glr_plot_distances_thumb.png b/_images/sphx_glr_plot_distances_thumb.png new file mode 100644 index 000000000..4a86eefa3 Binary files /dev/null and b/_images/sphx_glr_plot_distances_thumb.png differ diff --git a/_images/sphx_glr_plot_eigenfaces_001.png b/_images/sphx_glr_plot_eigenfaces_001.png new file mode 100644 index 000000000..615bb9e20 Binary files /dev/null and b/_images/sphx_glr_plot_eigenfaces_001.png differ diff --git a/_images/sphx_glr_plot_eigenfaces_002.png b/_images/sphx_glr_plot_eigenfaces_002.png new file mode 100644 index 000000000..445e1b63b Binary files /dev/null and b/_images/sphx_glr_plot_eigenfaces_002.png differ diff --git a/_images/sphx_glr_plot_eigenfaces_003.png b/_images/sphx_glr_plot_eigenfaces_003.png new file mode 100644 index 000000000..4ad848402 Binary files /dev/null and b/_images/sphx_glr_plot_eigenfaces_003.png differ diff --git a/_images/sphx_glr_plot_eigenfaces_004.png b/_images/sphx_glr_plot_eigenfaces_004.png new file mode 100644 index 000000000..7f1b75ee3 Binary files /dev/null and b/_images/sphx_glr_plot_eigenfaces_004.png differ diff --git a/_images/sphx_glr_plot_eigenfaces_thumb.png b/_images/sphx_glr_plot_eigenfaces_thumb.png new file mode 100644 index 000000000..2b5a4abd3 Binary files /dev/null and b/_images/sphx_glr_plot_eigenfaces_thumb.png differ diff --git a/_images/sphx_glr_plot_elephant_001.png b/_images/sphx_glr_plot_elephant_001.png new file mode 100644 index 000000000..47718ea84 Binary files /dev/null and b/_images/sphx_glr_plot_elephant_001.png differ diff --git a/_images/sphx_glr_plot_elephant_002.png b/_images/sphx_glr_plot_elephant_002.png new file mode 100644 index 000000000..ae57b8cc3 Binary files /dev/null and b/_images/sphx_glr_plot_elephant_002.png differ diff --git a/_images/sphx_glr_plot_elephant_003.png b/_images/sphx_glr_plot_elephant_003.png new file mode 100644 index 000000000..0f9200df0 Binary files /dev/null and b/_images/sphx_glr_plot_elephant_003.png differ diff --git a/_images/sphx_glr_plot_elephant_thumb.png b/_images/sphx_glr_plot_elephant_thumb.png new file mode 100644 index 000000000..b627d17af Binary files /dev/null and b/_images/sphx_glr_plot_elephant_thumb.png differ diff --git a/_images/sphx_glr_plot_equalize_hist_001.png b/_images/sphx_glr_plot_equalize_hist_001.png new file mode 100644 index 000000000..68eedcec3 Binary files /dev/null and b/_images/sphx_glr_plot_equalize_hist_001.png differ diff --git a/_images/sphx_glr_plot_equalize_hist_thumb.png b/_images/sphx_glr_plot_equalize_hist_thumb.png new file mode 100644 index 000000000..9ee39df96 Binary files /dev/null and b/_images/sphx_glr_plot_equalize_hist_thumb.png differ diff --git a/_images/sphx_glr_plot_exercise_10_001.png b/_images/sphx_glr_plot_exercise_10_001.png new file mode 100644 index 000000000..c1560ee14 Binary files /dev/null and b/_images/sphx_glr_plot_exercise_10_001.png differ diff --git a/_images/sphx_glr_plot_exercise_10_thumb.png b/_images/sphx_glr_plot_exercise_10_thumb.png new file mode 100644 index 000000000..e1ef0d88a Binary files /dev/null and b/_images/sphx_glr_plot_exercise_10_thumb.png differ diff --git a/_images/sphx_glr_plot_exercise_1_001.png b/_images/sphx_glr_plot_exercise_1_001.png new file mode 100644 index 000000000..5b0712e42 Binary files /dev/null and b/_images/sphx_glr_plot_exercise_1_001.png differ diff --git a/_images/sphx_glr_plot_exercise_1_thumb.png b/_images/sphx_glr_plot_exercise_1_thumb.png new file mode 100644 index 000000000..c1420e4b6 Binary files /dev/null and b/_images/sphx_glr_plot_exercise_1_thumb.png differ diff --git a/_images/sphx_glr_plot_exercise_2_001.png b/_images/sphx_glr_plot_exercise_2_001.png new file mode 100644 index 000000000..8d1234a66 Binary files /dev/null and b/_images/sphx_glr_plot_exercise_2_001.png differ diff --git a/_images/sphx_glr_plot_exercise_2_thumb.png b/_images/sphx_glr_plot_exercise_2_thumb.png new file mode 100644 index 000000000..123d8bd31 Binary files /dev/null and b/_images/sphx_glr_plot_exercise_2_thumb.png differ diff --git a/_images/sphx_glr_plot_exercise_3_001.png b/_images/sphx_glr_plot_exercise_3_001.png new file mode 100644 index 000000000..561a0685e Binary files /dev/null and b/_images/sphx_glr_plot_exercise_3_001.png differ diff --git a/_images/sphx_glr_plot_exercise_3_thumb.png b/_images/sphx_glr_plot_exercise_3_thumb.png new file mode 100644 index 000000000..753b9613e Binary files /dev/null and b/_images/sphx_glr_plot_exercise_3_thumb.png differ diff --git a/_images/sphx_glr_plot_exercise_4_001.png b/_images/sphx_glr_plot_exercise_4_001.png new file mode 100644 index 000000000..f4ea6b56c Binary files /dev/null and b/_images/sphx_glr_plot_exercise_4_001.png differ diff --git a/_images/sphx_glr_plot_exercise_4_thumb.png b/_images/sphx_glr_plot_exercise_4_thumb.png new file mode 100644 index 000000000..51f4b3c02 Binary files /dev/null and b/_images/sphx_glr_plot_exercise_4_thumb.png differ diff --git a/_images/sphx_glr_plot_exercise_5_001.png b/_images/sphx_glr_plot_exercise_5_001.png new file mode 100644 index 000000000..520c99912 Binary files /dev/null and b/_images/sphx_glr_plot_exercise_5_001.png differ diff --git a/_images/sphx_glr_plot_exercise_5_thumb.png b/_images/sphx_glr_plot_exercise_5_thumb.png new file mode 100644 index 000000000..2cb9667a0 Binary files /dev/null and b/_images/sphx_glr_plot_exercise_5_thumb.png differ diff --git a/_images/sphx_glr_plot_exercise_6_001.png b/_images/sphx_glr_plot_exercise_6_001.png new file mode 100644 index 000000000..449ec4ab5 Binary files /dev/null and b/_images/sphx_glr_plot_exercise_6_001.png differ diff --git a/_images/sphx_glr_plot_exercise_6_thumb.png b/_images/sphx_glr_plot_exercise_6_thumb.png new file mode 100644 index 000000000..fec5f886f Binary files /dev/null and b/_images/sphx_glr_plot_exercise_6_thumb.png differ diff --git a/_images/sphx_glr_plot_exercise_7_001.png b/_images/sphx_glr_plot_exercise_7_001.png new file mode 100644 index 000000000..fcf34893f Binary files /dev/null and b/_images/sphx_glr_plot_exercise_7_001.png differ diff --git a/_images/sphx_glr_plot_exercise_7_thumb.png b/_images/sphx_glr_plot_exercise_7_thumb.png new file mode 100644 index 000000000..d4076d8ef Binary files /dev/null and b/_images/sphx_glr_plot_exercise_7_thumb.png differ diff --git a/_images/sphx_glr_plot_exercise_8_001.png b/_images/sphx_glr_plot_exercise_8_001.png new file mode 100644 index 000000000..c9e5762d4 Binary files /dev/null and b/_images/sphx_glr_plot_exercise_8_001.png differ diff --git a/_images/sphx_glr_plot_exercise_8_thumb.png b/_images/sphx_glr_plot_exercise_8_thumb.png new file mode 100644 index 000000000..6d20c79fe Binary files /dev/null and b/_images/sphx_glr_plot_exercise_8_thumb.png differ diff --git a/_images/sphx_glr_plot_exercise_9_001.png b/_images/sphx_glr_plot_exercise_9_001.png new file mode 100644 index 000000000..3f13507a7 Binary files /dev/null and b/_images/sphx_glr_plot_exercise_9_001.png differ diff --git a/_images/sphx_glr_plot_exercise_9_thumb.png b/_images/sphx_glr_plot_exercise_9_thumb.png new file mode 100644 index 000000000..3dfe16c9a Binary files /dev/null and b/_images/sphx_glr_plot_exercise_9_thumb.png differ diff --git a/_images/sphx_glr_plot_exercise_flat_minimum_001.png b/_images/sphx_glr_plot_exercise_flat_minimum_001.png new file mode 100644 index 000000000..7cdd7b64d Binary files /dev/null and b/_images/sphx_glr_plot_exercise_flat_minimum_001.png differ diff --git a/_images/sphx_glr_plot_exercise_flat_minimum_002.png b/_images/sphx_glr_plot_exercise_flat_minimum_002.png new file mode 100644 index 000000000..8f9ad5066 Binary files /dev/null and b/_images/sphx_glr_plot_exercise_flat_minimum_002.png differ diff --git a/_images/sphx_glr_plot_exercise_flat_minimum_thumb.png b/_images/sphx_glr_plot_exercise_flat_minimum_thumb.png new file mode 100644 index 000000000..66a090b34 Binary files /dev/null and b/_images/sphx_glr_plot_exercise_flat_minimum_thumb.png differ diff --git a/_images/sphx_glr_plot_exercise_ill_conditioned_001.png b/_images/sphx_glr_plot_exercise_ill_conditioned_001.png new file mode 100644 index 000000000..a8a30a00c Binary files /dev/null and b/_images/sphx_glr_plot_exercise_ill_conditioned_001.png differ diff --git a/_images/sphx_glr_plot_exercise_ill_conditioned_thumb.png b/_images/sphx_glr_plot_exercise_ill_conditioned_thumb.png new file mode 100644 index 000000000..bcb2425c0 Binary files /dev/null and b/_images/sphx_glr_plot_exercise_ill_conditioned_thumb.png differ diff --git a/_images/sphx_glr_plot_face_001.png b/_images/sphx_glr_plot_face_001.png new file mode 100644 index 000000000..13dd28fd4 Binary files /dev/null and b/_images/sphx_glr_plot_face_001.png differ diff --git a/_images/sphx_glr_plot_face_denoise_001.png b/_images/sphx_glr_plot_face_denoise_001.png new file mode 100644 index 000000000..f077a9722 Binary files /dev/null and b/_images/sphx_glr_plot_face_denoise_001.png differ diff --git a/_images/sphx_glr_plot_face_denoise_thumb.png b/_images/sphx_glr_plot_face_denoise_thumb.png new file mode 100644 index 000000000..c2506d4da Binary files /dev/null and b/_images/sphx_glr_plot_face_denoise_thumb.png differ diff --git a/_images/sphx_glr_plot_face_thumb.png b/_images/sphx_glr_plot_face_thumb.png new file mode 100644 index 000000000..2fe2b4976 Binary files /dev/null and b/_images/sphx_glr_plot_face_thumb.png differ diff --git a/_images/sphx_glr_plot_face_tv_denoise_001.png b/_images/sphx_glr_plot_face_tv_denoise_001.png new file mode 100644 index 000000000..0d7fa506f Binary files /dev/null and b/_images/sphx_glr_plot_face_tv_denoise_001.png differ diff --git a/_images/sphx_glr_plot_face_tv_denoise_thumb.png b/_images/sphx_glr_plot_face_tv_denoise_thumb.png new file mode 100644 index 000000000..07dcf8451 Binary files /dev/null and b/_images/sphx_glr_plot_face_tv_denoise_thumb.png differ diff --git a/_images/sphx_glr_plot_features_001.png b/_images/sphx_glr_plot_features_001.png new file mode 100644 index 000000000..87433f16f Binary files /dev/null and b/_images/sphx_glr_plot_features_001.png differ diff --git a/_images/sphx_glr_plot_features_thumb.png b/_images/sphx_glr_plot_features_thumb.png new file mode 100644 index 000000000..f4053076e Binary files /dev/null and b/_images/sphx_glr_plot_features_thumb.png differ diff --git a/_images/sphx_glr_plot_fft_image_denoise_001.png b/_images/sphx_glr_plot_fft_image_denoise_001.png new file mode 100644 index 000000000..410cccd40 Binary files /dev/null and b/_images/sphx_glr_plot_fft_image_denoise_001.png differ diff --git a/_images/sphx_glr_plot_fft_image_denoise_002.png b/_images/sphx_glr_plot_fft_image_denoise_002.png new file mode 100644 index 000000000..1713e814e Binary files /dev/null and b/_images/sphx_glr_plot_fft_image_denoise_002.png differ diff --git a/_images/sphx_glr_plot_fft_image_denoise_003.png b/_images/sphx_glr_plot_fft_image_denoise_003.png new file mode 100644 index 000000000..836bb7c42 Binary files /dev/null and b/_images/sphx_glr_plot_fft_image_denoise_003.png differ diff --git a/_images/sphx_glr_plot_fft_image_denoise_004.png b/_images/sphx_glr_plot_fft_image_denoise_004.png new file mode 100644 index 000000000..a33433d4b Binary files /dev/null and b/_images/sphx_glr_plot_fft_image_denoise_004.png differ diff --git a/_images/sphx_glr_plot_fft_image_denoise_005.png b/_images/sphx_glr_plot_fft_image_denoise_005.png new file mode 100644 index 000000000..1f67c871b Binary files /dev/null and b/_images/sphx_glr_plot_fft_image_denoise_005.png differ diff --git a/_images/sphx_glr_plot_fft_image_denoise_thumb.png b/_images/sphx_glr_plot_fft_image_denoise_thumb.png new file mode 100644 index 000000000..82f0558a1 Binary files /dev/null and b/_images/sphx_glr_plot_fft_image_denoise_thumb.png differ diff --git a/_images/sphx_glr_plot_fftpack_001.png b/_images/sphx_glr_plot_fftpack_001.png new file mode 100644 index 000000000..6d3d3d4c2 Binary files /dev/null and b/_images/sphx_glr_plot_fftpack_001.png differ diff --git a/_images/sphx_glr_plot_fftpack_002.png b/_images/sphx_glr_plot_fftpack_002.png new file mode 100644 index 000000000..da4a539cf Binary files /dev/null and b/_images/sphx_glr_plot_fftpack_002.png differ diff --git a/_images/sphx_glr_plot_fftpack_003.png b/_images/sphx_glr_plot_fftpack_003.png new file mode 100644 index 000000000..ffefe3d8f Binary files /dev/null and b/_images/sphx_glr_plot_fftpack_003.png differ diff --git a/_images/sphx_glr_plot_fftpack_thumb.png b/_images/sphx_glr_plot_fftpack_thumb.png new file mode 100644 index 000000000..5e82e8a82 Binary files /dev/null and b/_images/sphx_glr_plot_fftpack_thumb.png differ diff --git a/_images/sphx_glr_plot_filter_coins_001.png b/_images/sphx_glr_plot_filter_coins_001.png new file mode 100644 index 000000000..d20b08b08 Binary files /dev/null and b/_images/sphx_glr_plot_filter_coins_001.png differ diff --git a/_images/sphx_glr_plot_filter_coins_thumb.png b/_images/sphx_glr_plot_filter_coins_thumb.png new file mode 100644 index 000000000..f558bf298 Binary files /dev/null and b/_images/sphx_glr_plot_filter_coins_thumb.png differ diff --git a/_images/sphx_glr_plot_find_edges_001.png b/_images/sphx_glr_plot_find_edges_001.png new file mode 100644 index 000000000..258d5d8eb Binary files /dev/null and b/_images/sphx_glr_plot_find_edges_001.png differ diff --git a/_images/sphx_glr_plot_find_edges_thumb.png b/_images/sphx_glr_plot_find_edges_thumb.png new file mode 100644 index 000000000..c08f334f3 Binary files /dev/null and b/_images/sphx_glr_plot_find_edges_thumb.png differ diff --git a/_images/sphx_glr_plot_find_object_001.png b/_images/sphx_glr_plot_find_object_001.png new file mode 100644 index 000000000..cd46e995a Binary files /dev/null and b/_images/sphx_glr_plot_find_object_001.png differ diff --git a/_images/sphx_glr_plot_find_object_thumb.png b/_images/sphx_glr_plot_find_object_thumb.png new file mode 100644 index 000000000..b17647b20 Binary files /dev/null and b/_images/sphx_glr_plot_find_object_thumb.png differ diff --git a/_images/sphx_glr_plot_geom_face_001.png b/_images/sphx_glr_plot_geom_face_001.png new file mode 100644 index 000000000..4f7fff7bf Binary files /dev/null and b/_images/sphx_glr_plot_geom_face_001.png differ diff --git a/_images/sphx_glr_plot_geom_face_thumb.png b/_images/sphx_glr_plot_geom_face_thumb.png new file mode 100644 index 000000000..30dd3a59b Binary files /dev/null and b/_images/sphx_glr_plot_geom_face_thumb.png differ diff --git a/_images/sphx_glr_plot_good_001.png b/_images/sphx_glr_plot_good_001.png new file mode 100644 index 000000000..bf069d768 Binary files /dev/null and b/_images/sphx_glr_plot_good_001.png differ diff --git a/_images/sphx_glr_plot_good_thumb.png b/_images/sphx_glr_plot_good_thumb.png new file mode 100644 index 000000000..2a7eb601d Binary files /dev/null and b/_images/sphx_glr_plot_good_thumb.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_001.png b/_images/sphx_glr_plot_gradient_descent_001.png new file mode 100644 index 000000000..7278c095c Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_001.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_002.png b/_images/sphx_glr_plot_gradient_descent_002.png new file mode 100644 index 000000000..00aed0aec Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_002.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_003.png b/_images/sphx_glr_plot_gradient_descent_003.png new file mode 100644 index 000000000..3fee37463 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_003.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_004.png b/_images/sphx_glr_plot_gradient_descent_004.png new file mode 100644 index 000000000..e15cefdc2 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_004.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_005.png b/_images/sphx_glr_plot_gradient_descent_005.png new file mode 100644 index 000000000..e6474674a Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_005.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_006.png b/_images/sphx_glr_plot_gradient_descent_006.png new file mode 100644 index 000000000..78a040d7c Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_006.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_007.png b/_images/sphx_glr_plot_gradient_descent_007.png new file mode 100644 index 000000000..5ce8e8218 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_007.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_008.png b/_images/sphx_glr_plot_gradient_descent_008.png new file mode 100644 index 000000000..72e5df7dd Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_008.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_009.png b/_images/sphx_glr_plot_gradient_descent_009.png new file mode 100644 index 000000000..b5427a660 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_009.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_010.png b/_images/sphx_glr_plot_gradient_descent_010.png new file mode 100644 index 000000000..7b3371b15 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_010.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_011.png b/_images/sphx_glr_plot_gradient_descent_011.png new file mode 100644 index 000000000..21358538c Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_011.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_012.png b/_images/sphx_glr_plot_gradient_descent_012.png new file mode 100644 index 000000000..196be25b1 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_012.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_013.png b/_images/sphx_glr_plot_gradient_descent_013.png new file mode 100644 index 000000000..b1a52aba1 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_013.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_014.png b/_images/sphx_glr_plot_gradient_descent_014.png new file mode 100644 index 000000000..14a485c9a Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_014.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_015.png b/_images/sphx_glr_plot_gradient_descent_015.png new file mode 100644 index 000000000..701214757 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_015.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_016.png b/_images/sphx_glr_plot_gradient_descent_016.png new file mode 100644 index 000000000..f018ea99d Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_016.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_017.png b/_images/sphx_glr_plot_gradient_descent_017.png new file mode 100644 index 000000000..3486c9584 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_017.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_018.png b/_images/sphx_glr_plot_gradient_descent_018.png new file mode 100644 index 000000000..a693c2264 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_018.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_019.png b/_images/sphx_glr_plot_gradient_descent_019.png new file mode 100644 index 000000000..5f30aec58 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_019.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_020.png b/_images/sphx_glr_plot_gradient_descent_020.png new file mode 100644 index 000000000..a10381e13 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_020.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_021.png b/_images/sphx_glr_plot_gradient_descent_021.png new file mode 100644 index 000000000..73bd238ab Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_021.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_022.png b/_images/sphx_glr_plot_gradient_descent_022.png new file mode 100644 index 000000000..1d5679650 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_022.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_023.png b/_images/sphx_glr_plot_gradient_descent_023.png new file mode 100644 index 000000000..d272bf1ec Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_023.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_024.png b/_images/sphx_glr_plot_gradient_descent_024.png new file mode 100644 index 000000000..c17912170 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_024.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_025.png b/_images/sphx_glr_plot_gradient_descent_025.png new file mode 100644 index 000000000..ad396235c Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_025.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_026.png b/_images/sphx_glr_plot_gradient_descent_026.png new file mode 100644 index 000000000..48f725400 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_026.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_027.png b/_images/sphx_glr_plot_gradient_descent_027.png new file mode 100644 index 000000000..f69c7d598 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_027.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_028.png b/_images/sphx_glr_plot_gradient_descent_028.png new file mode 100644 index 000000000..fdfe3611e Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_028.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_029.png b/_images/sphx_glr_plot_gradient_descent_029.png new file mode 100644 index 000000000..8b67ed047 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_029.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_030.png b/_images/sphx_glr_plot_gradient_descent_030.png new file mode 100644 index 000000000..055f0c69e Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_030.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_031.png b/_images/sphx_glr_plot_gradient_descent_031.png new file mode 100644 index 000000000..33d22578b Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_031.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_032.png b/_images/sphx_glr_plot_gradient_descent_032.png new file mode 100644 index 000000000..a1f5ca37a Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_032.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_033.png b/_images/sphx_glr_plot_gradient_descent_033.png new file mode 100644 index 000000000..091dc26d7 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_033.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_034.png b/_images/sphx_glr_plot_gradient_descent_034.png new file mode 100644 index 000000000..e3ba395d3 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_034.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_035.png b/_images/sphx_glr_plot_gradient_descent_035.png new file mode 100644 index 000000000..24f944f2c Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_035.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_036.png b/_images/sphx_glr_plot_gradient_descent_036.png new file mode 100644 index 000000000..6d8cc0945 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_036.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_037.png b/_images/sphx_glr_plot_gradient_descent_037.png new file mode 100644 index 000000000..bb6c526ab Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_037.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_038.png b/_images/sphx_glr_plot_gradient_descent_038.png new file mode 100644 index 000000000..beae94089 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_038.png differ diff --git a/_images/sphx_glr_plot_gradient_descent_thumb.png b/_images/sphx_glr_plot_gradient_descent_thumb.png new file mode 100644 index 000000000..a9b8d8380 Binary files /dev/null and b/_images/sphx_glr_plot_gradient_descent_thumb.png differ diff --git a/_images/sphx_glr_plot_granulo_001.png b/_images/sphx_glr_plot_granulo_001.png new file mode 100644 index 000000000..57be51231 Binary files /dev/null and b/_images/sphx_glr_plot_granulo_001.png differ diff --git a/_images/sphx_glr_plot_granulo_thumb.png b/_images/sphx_glr_plot_granulo_thumb.png new file mode 100644 index 000000000..5b4dd535e Binary files /dev/null and b/_images/sphx_glr_plot_granulo_thumb.png differ diff --git a/_images/sphx_glr_plot_greyscale_dilation_001.png b/_images/sphx_glr_plot_greyscale_dilation_001.png new file mode 100644 index 000000000..5c570699e Binary files /dev/null and b/_images/sphx_glr_plot_greyscale_dilation_001.png differ diff --git a/_images/sphx_glr_plot_greyscale_dilation_thumb.png b/_images/sphx_glr_plot_greyscale_dilation_thumb.png new file mode 100644 index 000000000..3d0405cd2 Binary files /dev/null and b/_images/sphx_glr_plot_greyscale_dilation_thumb.png differ diff --git a/_images/sphx_glr_plot_grid_001.png b/_images/sphx_glr_plot_grid_001.png new file mode 100644 index 000000000..5adde0e2e Binary files /dev/null and b/_images/sphx_glr_plot_grid_001.png differ diff --git a/_images/sphx_glr_plot_grid_ext_001.png b/_images/sphx_glr_plot_grid_ext_001.png new file mode 100644 index 000000000..430e8640f Binary files /dev/null and b/_images/sphx_glr_plot_grid_ext_001.png differ diff --git a/_images/sphx_glr_plot_grid_ext_thumb.png b/_images/sphx_glr_plot_grid_ext_thumb.png new file mode 100644 index 000000000..9bdf90217 Binary files /dev/null and b/_images/sphx_glr_plot_grid_ext_thumb.png differ diff --git a/_images/sphx_glr_plot_grid_thumb.png b/_images/sphx_glr_plot_grid_thumb.png new file mode 100644 index 000000000..141c3a53a Binary files /dev/null and b/_images/sphx_glr_plot_grid_thumb.png differ diff --git a/_images/sphx_glr_plot_gridspec_001.png b/_images/sphx_glr_plot_gridspec_001.png new file mode 100644 index 000000000..951d5e0cf Binary files /dev/null and b/_images/sphx_glr_plot_gridspec_001.png differ diff --git a/_images/sphx_glr_plot_gridspec_thumb.png b/_images/sphx_glr_plot_gridspec_thumb.png new file mode 100644 index 000000000..01df791d9 Binary files /dev/null and b/_images/sphx_glr_plot_gridspec_thumb.png differ diff --git a/_images/sphx_glr_plot_gumbell_wind_speed_prediction_001.png b/_images/sphx_glr_plot_gumbell_wind_speed_prediction_001.png new file mode 100644 index 000000000..69833ddc1 Binary files /dev/null and b/_images/sphx_glr_plot_gumbell_wind_speed_prediction_001.png differ diff --git a/_images/sphx_glr_plot_gumbell_wind_speed_prediction_thumb.png b/_images/sphx_glr_plot_gumbell_wind_speed_prediction_thumb.png new file mode 100644 index 000000000..c14d2aab2 Binary files /dev/null and b/_images/sphx_glr_plot_gumbell_wind_speed_prediction_thumb.png differ diff --git a/_images/sphx_glr_plot_histo_segmentation_001.png b/_images/sphx_glr_plot_histo_segmentation_001.png new file mode 100644 index 000000000..a999afbe5 Binary files /dev/null and b/_images/sphx_glr_plot_histo_segmentation_001.png differ diff --git a/_images/sphx_glr_plot_histo_segmentation_thumb.png b/_images/sphx_glr_plot_histo_segmentation_thumb.png new file mode 100644 index 000000000..42df554e4 Binary files /dev/null and b/_images/sphx_glr_plot_histo_segmentation_thumb.png differ diff --git a/_images/sphx_glr_plot_image_blur_001.png b/_images/sphx_glr_plot_image_blur_001.png new file mode 100644 index 000000000..47718ea84 Binary files /dev/null and b/_images/sphx_glr_plot_image_blur_001.png differ diff --git a/_images/sphx_glr_plot_image_blur_002.png b/_images/sphx_glr_plot_image_blur_002.png new file mode 100644 index 000000000..25f189690 Binary files /dev/null and b/_images/sphx_glr_plot_image_blur_002.png differ diff --git a/_images/sphx_glr_plot_image_blur_003.png b/_images/sphx_glr_plot_image_blur_003.png new file mode 100644 index 000000000..61f074e70 Binary files /dev/null and b/_images/sphx_glr_plot_image_blur_003.png differ diff --git a/_images/sphx_glr_plot_image_blur_thumb.png b/_images/sphx_glr_plot_image_blur_thumb.png new file mode 100644 index 000000000..b627d17af Binary files /dev/null and b/_images/sphx_glr_plot_image_blur_thumb.png differ diff --git a/_images/sphx_glr_plot_image_filters_001.png b/_images/sphx_glr_plot_image_filters_001.png new file mode 100644 index 000000000..0d2742060 Binary files /dev/null and b/_images/sphx_glr_plot_image_filters_001.png differ diff --git a/_images/sphx_glr_plot_image_filters_thumb.png b/_images/sphx_glr_plot_image_filters_thumb.png new file mode 100644 index 000000000..ba00f7b74 Binary files /dev/null and b/_images/sphx_glr_plot_image_filters_thumb.png differ diff --git a/_images/sphx_glr_plot_image_transform_001.png b/_images/sphx_glr_plot_image_transform_001.png new file mode 100644 index 000000000..038e248fb Binary files /dev/null and b/_images/sphx_glr_plot_image_transform_001.png differ diff --git a/_images/sphx_glr_plot_image_transform_thumb.png b/_images/sphx_glr_plot_image_transform_thumb.png new file mode 100644 index 000000000..cf35f2478 Binary files /dev/null and b/_images/sphx_glr_plot_image_transform_thumb.png differ diff --git a/_images/sphx_glr_plot_imshow_001.png b/_images/sphx_glr_plot_imshow_001.png new file mode 100644 index 000000000..0a1eb49bd Binary files /dev/null and b/_images/sphx_glr_plot_imshow_001.png differ diff --git a/_images/sphx_glr_plot_imshow_ext_001.png b/_images/sphx_glr_plot_imshow_ext_001.png new file mode 100644 index 000000000..af41cd208 Binary files /dev/null and b/_images/sphx_glr_plot_imshow_ext_001.png differ diff --git a/_images/sphx_glr_plot_imshow_ext_thumb.png b/_images/sphx_glr_plot_imshow_ext_thumb.png new file mode 100644 index 000000000..96af2daea Binary files /dev/null and b/_images/sphx_glr_plot_imshow_ext_thumb.png differ diff --git a/_images/sphx_glr_plot_imshow_thumb.png b/_images/sphx_glr_plot_imshow_thumb.png new file mode 100644 index 000000000..06e092962 Binary files /dev/null and b/_images/sphx_glr_plot_imshow_thumb.png differ diff --git a/_images/sphx_glr_plot_interpolation_001.png b/_images/sphx_glr_plot_interpolation_001.png new file mode 100644 index 000000000..54f627de6 Binary files /dev/null and b/_images/sphx_glr_plot_interpolation_001.png differ diff --git a/_images/sphx_glr_plot_interpolation_002.png b/_images/sphx_glr_plot_interpolation_002.png new file mode 100644 index 000000000..1bf41babd Binary files /dev/null and b/_images/sphx_glr_plot_interpolation_002.png differ diff --git a/_images/sphx_glr_plot_interpolation_003.png b/_images/sphx_glr_plot_interpolation_003.png new file mode 100644 index 000000000..df9dc43b7 Binary files /dev/null and b/_images/sphx_glr_plot_interpolation_003.png differ diff --git a/_images/sphx_glr_plot_interpolation_face_001.png b/_images/sphx_glr_plot_interpolation_face_001.png new file mode 100644 index 000000000..5050a8e12 Binary files /dev/null and b/_images/sphx_glr_plot_interpolation_face_001.png differ diff --git a/_images/sphx_glr_plot_interpolation_face_thumb.png b/_images/sphx_glr_plot_interpolation_face_thumb.png new file mode 100644 index 000000000..928e5bfee Binary files /dev/null and b/_images/sphx_glr_plot_interpolation_face_thumb.png differ diff --git a/_images/sphx_glr_plot_interpolation_thumb.png b/_images/sphx_glr_plot_interpolation_thumb.png new file mode 100644 index 000000000..70e1d1502 Binary files /dev/null and b/_images/sphx_glr_plot_interpolation_thumb.png differ diff --git a/_images/sphx_glr_plot_iris_analysis_001.png b/_images/sphx_glr_plot_iris_analysis_001.png new file mode 100644 index 000000000..7f98fe074 Binary files /dev/null and b/_images/sphx_glr_plot_iris_analysis_001.png differ diff --git a/_images/sphx_glr_plot_iris_analysis_thumb.png b/_images/sphx_glr_plot_iris_analysis_thumb.png new file mode 100644 index 000000000..1ef9d3b29 Binary files /dev/null and b/_images/sphx_glr_plot_iris_analysis_thumb.png differ diff --git a/_images/sphx_glr_plot_iris_knn_001.png b/_images/sphx_glr_plot_iris_knn_001.png new file mode 100644 index 000000000..3e382ae53 Binary files /dev/null and b/_images/sphx_glr_plot_iris_knn_001.png differ diff --git a/_images/sphx_glr_plot_iris_knn_002.png b/_images/sphx_glr_plot_iris_knn_002.png new file mode 100644 index 000000000..dbc8c0a7a Binary files /dev/null and b/_images/sphx_glr_plot_iris_knn_002.png differ diff --git a/_images/sphx_glr_plot_iris_knn_thumb.png b/_images/sphx_glr_plot_iris_knn_thumb.png new file mode 100644 index 000000000..03cc1366e Binary files /dev/null and b/_images/sphx_glr_plot_iris_knn_thumb.png differ diff --git a/_images/sphx_glr_plot_iris_scatter_001.png b/_images/sphx_glr_plot_iris_scatter_001.png new file mode 100644 index 000000000..f00906ce2 Binary files /dev/null and b/_images/sphx_glr_plot_iris_scatter_001.png differ diff --git a/_images/sphx_glr_plot_iris_scatter_thumb.png b/_images/sphx_glr_plot_iris_scatter_thumb.png new file mode 100644 index 000000000..9b0e9a417 Binary files /dev/null and b/_images/sphx_glr_plot_iris_scatter_thumb.png differ diff --git a/_images/sphx_glr_plot_labels_001.png b/_images/sphx_glr_plot_labels_001.png new file mode 100644 index 000000000..ad2161fb5 Binary files /dev/null and b/_images/sphx_glr_plot_labels_001.png differ diff --git a/_images/sphx_glr_plot_labels_thumb.png b/_images/sphx_glr_plot_labels_thumb.png new file mode 100644 index 000000000..a592651dd Binary files /dev/null and b/_images/sphx_glr_plot_labels_thumb.png differ diff --git a/_images/sphx_glr_plot_linear_model_cv_001.png b/_images/sphx_glr_plot_linear_model_cv_001.png new file mode 100644 index 000000000..6599e49a1 Binary files /dev/null and b/_images/sphx_glr_plot_linear_model_cv_001.png differ diff --git a/_images/sphx_glr_plot_linear_model_cv_thumb.png b/_images/sphx_glr_plot_linear_model_cv_thumb.png new file mode 100644 index 000000000..1abe6e8bb Binary files /dev/null and b/_images/sphx_glr_plot_linear_model_cv_thumb.png differ diff --git a/_images/sphx_glr_plot_linear_regression_001.png b/_images/sphx_glr_plot_linear_regression_001.png new file mode 100644 index 000000000..0ba9717e2 Binary files /dev/null and b/_images/sphx_glr_plot_linear_regression_001.png differ diff --git a/_images/sphx_glr_plot_linear_regression_thumb.png b/_images/sphx_glr_plot_linear_regression_thumb.png new file mode 100644 index 000000000..68f999073 Binary files /dev/null and b/_images/sphx_glr_plot_linear_regression_thumb.png differ diff --git a/_images/sphx_glr_plot_linestyles_001.png b/_images/sphx_glr_plot_linestyles_001.png new file mode 100644 index 000000000..1ca3ece42 Binary files /dev/null and b/_images/sphx_glr_plot_linestyles_001.png differ diff --git a/_images/sphx_glr_plot_linestyles_thumb.png b/_images/sphx_glr_plot_linestyles_thumb.png new file mode 100644 index 000000000..a3663b78e Binary files /dev/null and b/_images/sphx_glr_plot_linestyles_thumb.png differ diff --git a/_images/sphx_glr_plot_linewidth_001.png b/_images/sphx_glr_plot_linewidth_001.png new file mode 100644 index 000000000..488df33c1 Binary files /dev/null and b/_images/sphx_glr_plot_linewidth_001.png differ diff --git a/_images/sphx_glr_plot_linewidth_thumb.png b/_images/sphx_glr_plot_linewidth_thumb.png new file mode 100644 index 000000000..ef3fc1fb1 Binary files /dev/null and b/_images/sphx_glr_plot_linewidth_thumb.png differ diff --git a/_images/sphx_glr_plot_mandelbrot_001.png b/_images/sphx_glr_plot_mandelbrot_001.png new file mode 100644 index 000000000..224f45a74 Binary files /dev/null and b/_images/sphx_glr_plot_mandelbrot_001.png differ diff --git a/_images/sphx_glr_plot_mandelbrot_thumb.png b/_images/sphx_glr_plot_mandelbrot_thumb.png new file mode 100644 index 000000000..e49676191 Binary files /dev/null and b/_images/sphx_glr_plot_mandelbrot_thumb.png differ diff --git a/_images/sphx_glr_plot_markers_001.png b/_images/sphx_glr_plot_markers_001.png new file mode 100644 index 000000000..c0ac4bf34 Binary files /dev/null and b/_images/sphx_glr_plot_markers_001.png differ diff --git a/_images/sphx_glr_plot_markers_thumb.png b/_images/sphx_glr_plot_markers_thumb.png new file mode 100644 index 000000000..60c8b44b3 Binary files /dev/null and b/_images/sphx_glr_plot_markers_thumb.png differ diff --git a/_images/sphx_glr_plot_maskedstats_001.png b/_images/sphx_glr_plot_maskedstats_001.png new file mode 100644 index 000000000..e5edd4509 Binary files /dev/null and b/_images/sphx_glr_plot_maskedstats_001.png differ diff --git a/_images/sphx_glr_plot_maskedstats_thumb.png b/_images/sphx_glr_plot_maskedstats_thumb.png new file mode 100644 index 000000000..50a9d2c54 Binary files /dev/null and b/_images/sphx_glr_plot_maskedstats_thumb.png differ diff --git a/_images/sphx_glr_plot_mathematical_morpho_001.png b/_images/sphx_glr_plot_mathematical_morpho_001.png new file mode 100644 index 000000000..235eab208 Binary files /dev/null and b/_images/sphx_glr_plot_mathematical_morpho_001.png differ diff --git a/_images/sphx_glr_plot_mathematical_morpho_thumb.png b/_images/sphx_glr_plot_mathematical_morpho_thumb.png new file mode 100644 index 000000000..f69a7f3e0 Binary files /dev/null and b/_images/sphx_glr_plot_mathematical_morpho_thumb.png differ diff --git a/_images/sphx_glr_plot_measure_data_001.png b/_images/sphx_glr_plot_measure_data_001.png new file mode 100644 index 000000000..66e664a3e Binary files /dev/null and b/_images/sphx_glr_plot_measure_data_001.png differ diff --git a/_images/sphx_glr_plot_measure_data_thumb.png b/_images/sphx_glr_plot_measure_data_thumb.png new file mode 100644 index 000000000..4ca801b23 Binary files /dev/null and b/_images/sphx_glr_plot_measure_data_thumb.png differ diff --git a/_images/sphx_glr_plot_measuring_performance_001.png b/_images/sphx_glr_plot_measuring_performance_001.png new file mode 100644 index 000000000..edd6ad384 Binary files /dev/null and b/_images/sphx_glr_plot_measuring_performance_001.png differ diff --git a/_images/sphx_glr_plot_measuring_performance_thumb.png b/_images/sphx_glr_plot_measuring_performance_thumb.png new file mode 100644 index 000000000..794a52b53 Binary files /dev/null and b/_images/sphx_glr_plot_measuring_performance_thumb.png differ diff --git a/_images/sphx_glr_plot_mec_001.png b/_images/sphx_glr_plot_mec_001.png new file mode 100644 index 000000000..e49422077 Binary files /dev/null and b/_images/sphx_glr_plot_mec_001.png differ diff --git a/_images/sphx_glr_plot_mec_thumb.png b/_images/sphx_glr_plot_mec_thumb.png new file mode 100644 index 000000000..e8e969745 Binary files /dev/null and b/_images/sphx_glr_plot_mec_thumb.png differ diff --git a/_images/sphx_glr_plot_mew_001.png b/_images/sphx_glr_plot_mew_001.png new file mode 100644 index 000000000..91122f837 Binary files /dev/null and b/_images/sphx_glr_plot_mew_001.png differ diff --git a/_images/sphx_glr_plot_mew_thumb.png b/_images/sphx_glr_plot_mew_thumb.png new file mode 100644 index 000000000..fac6125e4 Binary files /dev/null and b/_images/sphx_glr_plot_mew_thumb.png differ diff --git a/_images/sphx_glr_plot_mfc_001.png b/_images/sphx_glr_plot_mfc_001.png new file mode 100644 index 000000000..b10728dc5 Binary files /dev/null and b/_images/sphx_glr_plot_mfc_001.png differ diff --git a/_images/sphx_glr_plot_mfc_thumb.png b/_images/sphx_glr_plot_mfc_thumb.png new file mode 100644 index 000000000..540577a74 Binary files /dev/null and b/_images/sphx_glr_plot_mfc_thumb.png differ diff --git a/_images/sphx_glr_plot_ms_001.png b/_images/sphx_glr_plot_ms_001.png new file mode 100644 index 000000000..865cd4e41 Binary files /dev/null and b/_images/sphx_glr_plot_ms_001.png differ diff --git a/_images/sphx_glr_plot_ms_thumb.png b/_images/sphx_glr_plot_ms_thumb.png new file mode 100644 index 000000000..04e7e2e14 Binary files /dev/null and b/_images/sphx_glr_plot_ms_thumb.png differ diff --git a/_images/sphx_glr_plot_multiplot_001.png b/_images/sphx_glr_plot_multiplot_001.png new file mode 100644 index 000000000..2ea492d20 Binary files /dev/null and b/_images/sphx_glr_plot_multiplot_001.png differ diff --git a/_images/sphx_glr_plot_multiplot_ext_001.png b/_images/sphx_glr_plot_multiplot_ext_001.png new file mode 100644 index 000000000..c61302c93 Binary files /dev/null and b/_images/sphx_glr_plot_multiplot_ext_001.png differ diff --git a/_images/sphx_glr_plot_multiplot_ext_thumb.png b/_images/sphx_glr_plot_multiplot_ext_thumb.png new file mode 100644 index 000000000..6638ecfd0 Binary files /dev/null and b/_images/sphx_glr_plot_multiplot_ext_thumb.png differ diff --git a/_images/sphx_glr_plot_multiplot_thumb.png b/_images/sphx_glr_plot_multiplot_thumb.png new file mode 100644 index 000000000..8e42bc6b8 Binary files /dev/null and b/_images/sphx_glr_plot_multiplot_thumb.png differ diff --git a/_images/sphx_glr_plot_noisy_001.png b/_images/sphx_glr_plot_noisy_001.png new file mode 100644 index 000000000..f49459756 Binary files /dev/null and b/_images/sphx_glr_plot_noisy_001.png differ diff --git a/_images/sphx_glr_plot_noisy_thumb.png b/_images/sphx_glr_plot_noisy_thumb.png new file mode 100644 index 000000000..e7ed0af67 Binary files /dev/null and b/_images/sphx_glr_plot_noisy_thumb.png differ diff --git a/_images/sphx_glr_plot_non_bounds_constraints_001.png b/_images/sphx_glr_plot_non_bounds_constraints_001.png new file mode 100644 index 000000000..31363dec9 Binary files /dev/null and b/_images/sphx_glr_plot_non_bounds_constraints_001.png differ diff --git a/_images/sphx_glr_plot_non_bounds_constraints_thumb.png b/_images/sphx_glr_plot_non_bounds_constraints_thumb.png new file mode 100644 index 000000000..9094e2ca2 Binary files /dev/null and b/_images/sphx_glr_plot_non_bounds_constraints_thumb.png differ diff --git a/_images/sphx_glr_plot_normal_distribution_001.png b/_images/sphx_glr_plot_normal_distribution_001.png new file mode 100644 index 000000000..204ed6b82 Binary files /dev/null and b/_images/sphx_glr_plot_normal_distribution_001.png differ diff --git a/_images/sphx_glr_plot_normal_distribution_thumb.png b/_images/sphx_glr_plot_normal_distribution_thumb.png new file mode 100644 index 000000000..b61ff89e5 Binary files /dev/null and b/_images/sphx_glr_plot_normal_distribution_thumb.png differ diff --git a/_images/sphx_glr_plot_numpy_array_001.png b/_images/sphx_glr_plot_numpy_array_001.png new file mode 100644 index 000000000..99c9249f0 Binary files /dev/null and b/_images/sphx_glr_plot_numpy_array_001.png differ diff --git a/_images/sphx_glr_plot_numpy_array_thumb.png b/_images/sphx_glr_plot_numpy_array_thumb.png new file mode 100644 index 000000000..53a06dcd8 Binary files /dev/null and b/_images/sphx_glr_plot_numpy_array_thumb.png differ diff --git a/_images/sphx_glr_plot_optimize_example1_001.png b/_images/sphx_glr_plot_optimize_example1_001.png new file mode 100644 index 000000000..f2ab4f0fa Binary files /dev/null and b/_images/sphx_glr_plot_optimize_example1_001.png differ diff --git a/_images/sphx_glr_plot_optimize_example1_thumb.png b/_images/sphx_glr_plot_optimize_example1_thumb.png new file mode 100644 index 000000000..3a11be943 Binary files /dev/null and b/_images/sphx_glr_plot_optimize_example1_thumb.png differ diff --git a/_images/sphx_glr_plot_optimize_example2_001.png b/_images/sphx_glr_plot_optimize_example2_001.png new file mode 100644 index 000000000..ae1fc06c6 Binary files /dev/null and b/_images/sphx_glr_plot_optimize_example2_001.png differ diff --git a/_images/sphx_glr_plot_optimize_example2_thumb.png b/_images/sphx_glr_plot_optimize_example2_thumb.png new file mode 100644 index 000000000..322d06a96 Binary files /dev/null and b/_images/sphx_glr_plot_optimize_example2_thumb.png differ diff --git a/_images/sphx_glr_plot_optimize_lidar_complex_data_001.png b/_images/sphx_glr_plot_optimize_lidar_complex_data_001.png new file mode 100644 index 000000000..00225002d Binary files /dev/null and b/_images/sphx_glr_plot_optimize_lidar_complex_data_001.png differ diff --git a/_images/sphx_glr_plot_optimize_lidar_complex_data_fit_001.png b/_images/sphx_glr_plot_optimize_lidar_complex_data_fit_001.png new file mode 100644 index 000000000..ce3f54484 Binary files /dev/null and b/_images/sphx_glr_plot_optimize_lidar_complex_data_fit_001.png differ diff --git a/_images/sphx_glr_plot_optimize_lidar_complex_data_fit_thumb.png b/_images/sphx_glr_plot_optimize_lidar_complex_data_fit_thumb.png new file mode 100644 index 000000000..f5bba00c1 Binary files /dev/null and b/_images/sphx_glr_plot_optimize_lidar_complex_data_fit_thumb.png differ diff --git a/_images/sphx_glr_plot_optimize_lidar_complex_data_thumb.png b/_images/sphx_glr_plot_optimize_lidar_complex_data_thumb.png new file mode 100644 index 000000000..a34dd85fd Binary files /dev/null and b/_images/sphx_glr_plot_optimize_lidar_complex_data_thumb.png differ diff --git a/_images/sphx_glr_plot_optimize_lidar_data_001.png b/_images/sphx_glr_plot_optimize_lidar_data_001.png new file mode 100644 index 000000000..28306de19 Binary files /dev/null and b/_images/sphx_glr_plot_optimize_lidar_data_001.png differ diff --git a/_images/sphx_glr_plot_optimize_lidar_data_fit_001.png b/_images/sphx_glr_plot_optimize_lidar_data_fit_001.png new file mode 100644 index 000000000..d592aff52 Binary files /dev/null and b/_images/sphx_glr_plot_optimize_lidar_data_fit_001.png differ diff --git a/_images/sphx_glr_plot_optimize_lidar_data_fit_thumb.png b/_images/sphx_glr_plot_optimize_lidar_data_fit_thumb.png new file mode 100644 index 000000000..89079c813 Binary files /dev/null and b/_images/sphx_glr_plot_optimize_lidar_data_fit_thumb.png differ diff --git a/_images/sphx_glr_plot_optimize_lidar_data_thumb.png b/_images/sphx_glr_plot_optimize_lidar_data_thumb.png new file mode 100644 index 000000000..9753aa093 Binary files /dev/null and b/_images/sphx_glr_plot_optimize_lidar_data_thumb.png differ diff --git a/_images/sphx_glr_plot_paired_boxplots_001.png b/_images/sphx_glr_plot_paired_boxplots_001.png new file mode 100644 index 000000000..d55032a7b Binary files /dev/null and b/_images/sphx_glr_plot_paired_boxplots_001.png differ diff --git a/_images/sphx_glr_plot_paired_boxplots_002.png b/_images/sphx_glr_plot_paired_boxplots_002.png new file mode 100644 index 000000000..97a6f4800 Binary files /dev/null and b/_images/sphx_glr_plot_paired_boxplots_002.png differ diff --git a/_images/sphx_glr_plot_paired_boxplots_thumb.png b/_images/sphx_glr_plot_paired_boxplots_thumb.png new file mode 100644 index 000000000..24b511f69 Binary files /dev/null and b/_images/sphx_glr_plot_paired_boxplots_thumb.png differ diff --git a/_images/sphx_glr_plot_pandas_001.png b/_images/sphx_glr_plot_pandas_001.png new file mode 100644 index 000000000..eba5f9cc3 Binary files /dev/null and b/_images/sphx_glr_plot_pandas_001.png differ diff --git a/_images/sphx_glr_plot_pandas_002.png b/_images/sphx_glr_plot_pandas_002.png new file mode 100644 index 000000000..51901ffae Binary files /dev/null and b/_images/sphx_glr_plot_pandas_002.png differ diff --git a/_images/sphx_glr_plot_pandas_003.png b/_images/sphx_glr_plot_pandas_003.png new file mode 100644 index 000000000..ab9f7da92 Binary files /dev/null and b/_images/sphx_glr_plot_pandas_003.png differ diff --git a/_images/sphx_glr_plot_pandas_thumb.png b/_images/sphx_glr_plot_pandas_thumb.png new file mode 100644 index 000000000..2ffd6d27d Binary files /dev/null and b/_images/sphx_glr_plot_pandas_thumb.png differ diff --git a/_images/sphx_glr_plot_pca_001.png b/_images/sphx_glr_plot_pca_001.png new file mode 100644 index 000000000..f2c7d963b Binary files /dev/null and b/_images/sphx_glr_plot_pca_001.png differ diff --git a/_images/sphx_glr_plot_pca_thumb.png b/_images/sphx_glr_plot_pca_thumb.png new file mode 100644 index 000000000..a07daf1e7 Binary files /dev/null and b/_images/sphx_glr_plot_pca_thumb.png differ diff --git a/_images/sphx_glr_plot_periodicity_finder_001.png b/_images/sphx_glr_plot_periodicity_finder_001.png new file mode 100644 index 000000000..953a80d51 Binary files /dev/null and b/_images/sphx_glr_plot_periodicity_finder_001.png differ diff --git a/_images/sphx_glr_plot_periodicity_finder_002.png b/_images/sphx_glr_plot_periodicity_finder_002.png new file mode 100644 index 000000000..d6d35ca75 Binary files /dev/null and b/_images/sphx_glr_plot_periodicity_finder_002.png differ diff --git a/_images/sphx_glr_plot_periodicity_finder_thumb.png b/_images/sphx_glr_plot_periodicity_finder_thumb.png new file mode 100644 index 000000000..bcd915983 Binary files /dev/null and b/_images/sphx_glr_plot_periodicity_finder_thumb.png differ diff --git a/_images/sphx_glr_plot_pie_001.png b/_images/sphx_glr_plot_pie_001.png new file mode 100644 index 000000000..57676abd8 Binary files /dev/null and b/_images/sphx_glr_plot_pie_001.png differ diff --git a/_images/sphx_glr_plot_pie_ext_001.png b/_images/sphx_glr_plot_pie_ext_001.png new file mode 100644 index 000000000..ee9528783 Binary files /dev/null and b/_images/sphx_glr_plot_pie_ext_001.png differ diff --git a/_images/sphx_glr_plot_pie_ext_thumb.png b/_images/sphx_glr_plot_pie_ext_thumb.png new file mode 100644 index 000000000..dce46c358 Binary files /dev/null and b/_images/sphx_glr_plot_pie_ext_thumb.png differ diff --git a/_images/sphx_glr_plot_pie_thumb.png b/_images/sphx_glr_plot_pie_thumb.png new file mode 100644 index 000000000..dbf8961d7 Binary files /dev/null and b/_images/sphx_glr_plot_pie_thumb.png differ diff --git a/_images/sphx_glr_plot_plot3d-2_001.png b/_images/sphx_glr_plot_plot3d-2_001.png new file mode 100644 index 000000000..033384741 Binary files /dev/null and b/_images/sphx_glr_plot_plot3d-2_001.png differ diff --git a/_images/sphx_glr_plot_plot3d-2_thumb.png b/_images/sphx_glr_plot_plot3d-2_thumb.png new file mode 100644 index 000000000..e1b2d67bc Binary files /dev/null and b/_images/sphx_glr_plot_plot3d-2_thumb.png differ diff --git a/_images/sphx_glr_plot_plot3d_001.png b/_images/sphx_glr_plot_plot3d_001.png new file mode 100644 index 000000000..9ad546b65 Binary files /dev/null and b/_images/sphx_glr_plot_plot3d_001.png differ diff --git a/_images/sphx_glr_plot_plot3d_ext_001.png b/_images/sphx_glr_plot_plot3d_ext_001.png new file mode 100644 index 000000000..61649018b Binary files /dev/null and b/_images/sphx_glr_plot_plot3d_ext_001.png differ diff --git a/_images/sphx_glr_plot_plot3d_ext_thumb.png b/_images/sphx_glr_plot_plot3d_ext_thumb.png new file mode 100644 index 000000000..ba6b00261 Binary files /dev/null and b/_images/sphx_glr_plot_plot3d_ext_thumb.png differ diff --git a/_images/sphx_glr_plot_plot3d_thumb.png b/_images/sphx_glr_plot_plot3d_thumb.png new file mode 100644 index 000000000..631ab1416 Binary files /dev/null and b/_images/sphx_glr_plot_plot3d_thumb.png differ diff --git a/_images/sphx_glr_plot_plot_001.png b/_images/sphx_glr_plot_plot_001.png new file mode 100644 index 000000000..4a39c75fc Binary files /dev/null and b/_images/sphx_glr_plot_plot_001.png differ diff --git a/_images/sphx_glr_plot_plot_ext_001.png b/_images/sphx_glr_plot_plot_ext_001.png new file mode 100644 index 000000000..64ad28f5a Binary files /dev/null and b/_images/sphx_glr_plot_plot_ext_001.png differ diff --git a/_images/sphx_glr_plot_plot_ext_thumb.png b/_images/sphx_glr_plot_plot_ext_thumb.png new file mode 100644 index 000000000..3267510b5 Binary files /dev/null and b/_images/sphx_glr_plot_plot_ext_thumb.png differ diff --git a/_images/sphx_glr_plot_plot_thumb.png b/_images/sphx_glr_plot_plot_thumb.png new file mode 100644 index 000000000..35153ae63 Binary files /dev/null and b/_images/sphx_glr_plot_plot_thumb.png differ diff --git a/_images/sphx_glr_plot_polar_001.png b/_images/sphx_glr_plot_polar_001.png new file mode 100644 index 000000000..9360b3b55 Binary files /dev/null and b/_images/sphx_glr_plot_polar_001.png differ diff --git a/_images/sphx_glr_plot_polar_ext_001.png b/_images/sphx_glr_plot_polar_ext_001.png new file mode 100644 index 000000000..8d419fc33 Binary files /dev/null and b/_images/sphx_glr_plot_polar_ext_001.png differ diff --git a/_images/sphx_glr_plot_polar_ext_thumb.png b/_images/sphx_glr_plot_polar_ext_thumb.png new file mode 100644 index 000000000..715ed6992 Binary files /dev/null and b/_images/sphx_glr_plot_polar_ext_thumb.png differ diff --git a/_images/sphx_glr_plot_polar_thumb.png b/_images/sphx_glr_plot_polar_thumb.png new file mode 100644 index 000000000..fb4f9d570 Binary files /dev/null and b/_images/sphx_glr_plot_polar_thumb.png differ diff --git a/_images/sphx_glr_plot_polyfit_001.png b/_images/sphx_glr_plot_polyfit_001.png new file mode 100644 index 000000000..8e98804d2 Binary files /dev/null and b/_images/sphx_glr_plot_polyfit_001.png differ diff --git a/_images/sphx_glr_plot_polyfit_thumb.png b/_images/sphx_glr_plot_polyfit_thumb.png new file mode 100644 index 000000000..ddb075cbb Binary files /dev/null and b/_images/sphx_glr_plot_polyfit_thumb.png differ diff --git a/_images/sphx_glr_plot_polynomial_regression_001.png b/_images/sphx_glr_plot_polynomial_regression_001.png new file mode 100644 index 000000000..46ae525a1 Binary files /dev/null and b/_images/sphx_glr_plot_polynomial_regression_001.png differ diff --git a/_images/sphx_glr_plot_polynomial_regression_002.png b/_images/sphx_glr_plot_polynomial_regression_002.png new file mode 100644 index 000000000..7810d815f Binary files /dev/null and b/_images/sphx_glr_plot_polynomial_regression_002.png differ diff --git a/_images/sphx_glr_plot_polynomial_regression_003.png b/_images/sphx_glr_plot_polynomial_regression_003.png new file mode 100644 index 000000000..77584e29f Binary files /dev/null and b/_images/sphx_glr_plot_polynomial_regression_003.png differ diff --git a/_images/sphx_glr_plot_polynomial_regression_thumb.png b/_images/sphx_glr_plot_polynomial_regression_thumb.png new file mode 100644 index 000000000..15465ba3e Binary files /dev/null and b/_images/sphx_glr_plot_polynomial_regression_thumb.png differ diff --git a/_images/sphx_glr_plot_populations_001.png b/_images/sphx_glr_plot_populations_001.png new file mode 100644 index 000000000..74e21cd34 Binary files /dev/null and b/_images/sphx_glr_plot_populations_001.png differ diff --git a/_images/sphx_glr_plot_populations_thumb.png b/_images/sphx_glr_plot_populations_thumb.png new file mode 100644 index 000000000..a2ba4ad0c Binary files /dev/null and b/_images/sphx_glr_plot_populations_thumb.png differ diff --git a/_images/sphx_glr_plot_propagation_001.png b/_images/sphx_glr_plot_propagation_001.png new file mode 100644 index 000000000..1224fe3bf Binary files /dev/null and b/_images/sphx_glr_plot_propagation_001.png differ diff --git a/_images/sphx_glr_plot_propagation_thumb.png b/_images/sphx_glr_plot_propagation_thumb.png new file mode 100644 index 000000000..8a8a65375 Binary files /dev/null and b/_images/sphx_glr_plot_propagation_thumb.png differ diff --git a/_images/sphx_glr_plot_quiver_001.png b/_images/sphx_glr_plot_quiver_001.png new file mode 100644 index 000000000..cc89f01ec Binary files /dev/null and b/_images/sphx_glr_plot_quiver_001.png differ diff --git a/_images/sphx_glr_plot_quiver_ext_001.png b/_images/sphx_glr_plot_quiver_ext_001.png new file mode 100644 index 000000000..9bbc04746 Binary files /dev/null and b/_images/sphx_glr_plot_quiver_ext_001.png differ diff --git a/_images/sphx_glr_plot_quiver_ext_thumb.png b/_images/sphx_glr_plot_quiver_ext_thumb.png new file mode 100644 index 000000000..32475cd0e Binary files /dev/null and b/_images/sphx_glr_plot_quiver_ext_thumb.png differ diff --git a/_images/sphx_glr_plot_quiver_thumb.png b/_images/sphx_glr_plot_quiver_thumb.png new file mode 100644 index 000000000..45b698641 Binary files /dev/null and b/_images/sphx_glr_plot_quiver_thumb.png differ diff --git a/_images/sphx_glr_plot_radial_mean_001.png b/_images/sphx_glr_plot_radial_mean_001.png new file mode 100644 index 000000000..450a483b4 Binary files /dev/null and b/_images/sphx_glr_plot_radial_mean_001.png differ diff --git a/_images/sphx_glr_plot_radial_mean_thumb.png b/_images/sphx_glr_plot_radial_mean_thumb.png new file mode 100644 index 000000000..b99399b4a Binary files /dev/null and b/_images/sphx_glr_plot_radial_mean_thumb.png differ diff --git a/_images/sphx_glr_plot_randomwalk_001.png b/_images/sphx_glr_plot_randomwalk_001.png new file mode 100644 index 000000000..8966c8bb2 Binary files /dev/null and b/_images/sphx_glr_plot_randomwalk_001.png differ diff --git a/_images/sphx_glr_plot_randomwalk_thumb.png b/_images/sphx_glr_plot_randomwalk_thumb.png new file mode 100644 index 000000000..3fc056aa6 Binary files /dev/null and b/_images/sphx_glr_plot_randomwalk_thumb.png differ diff --git a/_images/sphx_glr_plot_regression_001.png b/_images/sphx_glr_plot_regression_001.png new file mode 100644 index 000000000..5967a1715 Binary files /dev/null and b/_images/sphx_glr_plot_regression_001.png differ diff --git a/_images/sphx_glr_plot_regression_002.png b/_images/sphx_glr_plot_regression_002.png new file mode 100644 index 000000000..dcc8438b2 Binary files /dev/null and b/_images/sphx_glr_plot_regression_002.png differ diff --git a/_images/sphx_glr_plot_regression_3d_001.png b/_images/sphx_glr_plot_regression_3d_001.png new file mode 100644 index 000000000..a083a41b1 Binary files /dev/null and b/_images/sphx_glr_plot_regression_3d_001.png differ diff --git a/_images/sphx_glr_plot_regression_3d_thumb.png b/_images/sphx_glr_plot_regression_3d_thumb.png new file mode 100644 index 000000000..9adf72776 Binary files /dev/null and b/_images/sphx_glr_plot_regression_3d_thumb.png differ diff --git a/_images/sphx_glr_plot_regression_thumb.png b/_images/sphx_glr_plot_regression_thumb.png new file mode 100644 index 000000000..23027b7d5 Binary files /dev/null and b/_images/sphx_glr_plot_regression_thumb.png differ diff --git a/_images/sphx_glr_plot_resample_001.png b/_images/sphx_glr_plot_resample_001.png new file mode 100644 index 000000000..f49a66b2d Binary files /dev/null and b/_images/sphx_glr_plot_resample_001.png differ diff --git a/_images/sphx_glr_plot_resample_thumb.png b/_images/sphx_glr_plot_resample_thumb.png new file mode 100644 index 000000000..01129b2a9 Binary files /dev/null and b/_images/sphx_glr_plot_resample_thumb.png differ diff --git a/_images/sphx_glr_plot_scatter_001.png b/_images/sphx_glr_plot_scatter_001.png new file mode 100644 index 000000000..838fd141a Binary files /dev/null and b/_images/sphx_glr_plot_scatter_001.png differ diff --git a/_images/sphx_glr_plot_scatter_ext_001.png b/_images/sphx_glr_plot_scatter_ext_001.png new file mode 100644 index 000000000..528dc80eb Binary files /dev/null and b/_images/sphx_glr_plot_scatter_ext_001.png differ diff --git a/_images/sphx_glr_plot_scatter_ext_thumb.png b/_images/sphx_glr_plot_scatter_ext_thumb.png new file mode 100644 index 000000000..f42aafae2 Binary files /dev/null and b/_images/sphx_glr_plot_scatter_ext_thumb.png differ diff --git a/_images/sphx_glr_plot_scatter_thumb.png b/_images/sphx_glr_plot_scatter_thumb.png new file mode 100644 index 000000000..e048a1d39 Binary files /dev/null and b/_images/sphx_glr_plot_scatter_thumb.png differ diff --git a/_images/sphx_glr_plot_segmentations_001.png b/_images/sphx_glr_plot_segmentations_001.png new file mode 100644 index 000000000..80b0480c0 Binary files /dev/null and b/_images/sphx_glr_plot_segmentations_001.png differ diff --git a/_images/sphx_glr_plot_segmentations_thumb.png b/_images/sphx_glr_plot_segmentations_thumb.png new file mode 100644 index 000000000..6e1ebe96f Binary files /dev/null and b/_images/sphx_glr_plot_segmentations_thumb.png differ diff --git a/_images/sphx_glr_plot_separator_001.png b/_images/sphx_glr_plot_separator_001.png new file mode 100644 index 000000000..f133476e7 Binary files /dev/null and b/_images/sphx_glr_plot_separator_001.png differ diff --git a/_images/sphx_glr_plot_separator_thumb.png b/_images/sphx_glr_plot_separator_thumb.png new file mode 100644 index 000000000..bca619ab3 Binary files /dev/null and b/_images/sphx_glr_plot_separator_thumb.png differ diff --git a/_images/sphx_glr_plot_sharpen_001.png b/_images/sphx_glr_plot_sharpen_001.png new file mode 100644 index 000000000..405184dc9 Binary files /dev/null and b/_images/sphx_glr_plot_sharpen_001.png differ diff --git a/_images/sphx_glr_plot_sharpen_thumb.png b/_images/sphx_glr_plot_sharpen_thumb.png new file mode 100644 index 000000000..45e8cb945 Binary files /dev/null and b/_images/sphx_glr_plot_sharpen_thumb.png differ diff --git a/_images/sphx_glr_plot_simple_001.png b/_images/sphx_glr_plot_simple_001.png new file mode 100644 index 000000000..51d2e3e6b Binary files /dev/null and b/_images/sphx_glr_plot_simple_001.png differ diff --git a/_images/sphx_glr_plot_simple_thumb.png b/_images/sphx_glr_plot_simple_thumb.png new file mode 100644 index 000000000..e39c0db32 Binary files /dev/null and b/_images/sphx_glr_plot_simple_thumb.png differ diff --git a/_images/sphx_glr_plot_smooth_001.png b/_images/sphx_glr_plot_smooth_001.png new file mode 100644 index 000000000..2e9d04f3e Binary files /dev/null and b/_images/sphx_glr_plot_smooth_001.png differ diff --git a/_images/sphx_glr_plot_smooth_002.png b/_images/sphx_glr_plot_smooth_002.png new file mode 100644 index 000000000..780d70c0b Binary files /dev/null and b/_images/sphx_glr_plot_smooth_002.png differ diff --git a/_images/sphx_glr_plot_smooth_thumb.png b/_images/sphx_glr_plot_smooth_thumb.png new file mode 100644 index 000000000..53fda704b Binary files /dev/null and b/_images/sphx_glr_plot_smooth_thumb.png differ diff --git a/_images/sphx_glr_plot_sobel_001.png b/_images/sphx_glr_plot_sobel_001.png new file mode 100644 index 000000000..268597ae2 Binary files /dev/null and b/_images/sphx_glr_plot_sobel_001.png differ diff --git a/_images/sphx_glr_plot_sobel_thumb.png b/_images/sphx_glr_plot_sobel_thumb.png new file mode 100644 index 000000000..de306bf8b Binary files /dev/null and b/_images/sphx_glr_plot_sobel_thumb.png differ diff --git a/_images/sphx_glr_plot_solid_capstyle_001.png b/_images/sphx_glr_plot_solid_capstyle_001.png new file mode 100644 index 000000000..b86251cf2 Binary files /dev/null and b/_images/sphx_glr_plot_solid_capstyle_001.png differ diff --git a/_images/sphx_glr_plot_solid_capstyle_thumb.png b/_images/sphx_glr_plot_solid_capstyle_thumb.png new file mode 100644 index 000000000..12aebebfe Binary files /dev/null and b/_images/sphx_glr_plot_solid_capstyle_thumb.png differ diff --git a/_images/sphx_glr_plot_solid_joinstyle_001.png b/_images/sphx_glr_plot_solid_joinstyle_001.png new file mode 100644 index 000000000..d651e925e Binary files /dev/null and b/_images/sphx_glr_plot_solid_joinstyle_001.png differ diff --git a/_images/sphx_glr_plot_solid_joinstyle_thumb.png b/_images/sphx_glr_plot_solid_joinstyle_thumb.png new file mode 100644 index 000000000..c6e83f1a6 Binary files /dev/null and b/_images/sphx_glr_plot_solid_joinstyle_thumb.png differ diff --git a/_images/sphx_glr_plot_solve_ivp_damped_spring_mass_001.png b/_images/sphx_glr_plot_solve_ivp_damped_spring_mass_001.png new file mode 100644 index 000000000..a2d30a91b Binary files /dev/null and b/_images/sphx_glr_plot_solve_ivp_damped_spring_mass_001.png differ diff --git a/_images/sphx_glr_plot_solve_ivp_damped_spring_mass_thumb.png b/_images/sphx_glr_plot_solve_ivp_damped_spring_mass_thumb.png new file mode 100644 index 000000000..24ee88ccf Binary files /dev/null and b/_images/sphx_glr_plot_solve_ivp_damped_spring_mass_thumb.png differ diff --git a/_images/sphx_glr_plot_solve_ivp_simple_001.png b/_images/sphx_glr_plot_solve_ivp_simple_001.png new file mode 100644 index 000000000..5b6fee3e9 Binary files /dev/null and b/_images/sphx_glr_plot_solve_ivp_simple_001.png differ diff --git a/_images/sphx_glr_plot_solve_ivp_simple_thumb.png b/_images/sphx_glr_plot_solve_ivp_simple_thumb.png new file mode 100644 index 000000000..cc06598fb Binary files /dev/null and b/_images/sphx_glr_plot_solve_ivp_simple_thumb.png differ diff --git a/_images/sphx_glr_plot_spectral_clustering_001.png b/_images/sphx_glr_plot_spectral_clustering_001.png new file mode 100644 index 000000000..3987d9c03 Binary files /dev/null and b/_images/sphx_glr_plot_spectral_clustering_001.png differ diff --git a/_images/sphx_glr_plot_spectral_clustering_thumb.png b/_images/sphx_glr_plot_spectral_clustering_thumb.png new file mode 100644 index 000000000..03be31546 Binary files /dev/null and b/_images/sphx_glr_plot_spectral_clustering_thumb.png differ diff --git a/_images/sphx_glr_plot_spectrogram_001.png b/_images/sphx_glr_plot_spectrogram_001.png new file mode 100644 index 000000000..935757190 Binary files /dev/null and b/_images/sphx_glr_plot_spectrogram_001.png differ diff --git a/_images/sphx_glr_plot_spectrogram_002.png b/_images/sphx_glr_plot_spectrogram_002.png new file mode 100644 index 000000000..a8247f916 Binary files /dev/null and b/_images/sphx_glr_plot_spectrogram_002.png differ diff --git a/_images/sphx_glr_plot_spectrogram_003.png b/_images/sphx_glr_plot_spectrogram_003.png new file mode 100644 index 000000000..eb4a29719 Binary files /dev/null and b/_images/sphx_glr_plot_spectrogram_003.png differ diff --git a/_images/sphx_glr_plot_spectrogram_thumb.png b/_images/sphx_glr_plot_spectrogram_thumb.png new file mode 100644 index 000000000..a6106fe15 Binary files /dev/null and b/_images/sphx_glr_plot_spectrogram_thumb.png differ diff --git a/_images/sphx_glr_plot_sprog_annual_maxima_001.png b/_images/sphx_glr_plot_sprog_annual_maxima_001.png new file mode 100644 index 000000000..c25f44a2a Binary files /dev/null and b/_images/sphx_glr_plot_sprog_annual_maxima_001.png differ diff --git a/_images/sphx_glr_plot_sprog_annual_maxima_thumb.png b/_images/sphx_glr_plot_sprog_annual_maxima_thumb.png new file mode 100644 index 000000000..ceb4000f2 Binary files /dev/null and b/_images/sphx_glr_plot_sprog_annual_maxima_thumb.png differ diff --git a/_images/sphx_glr_plot_subplot-grid_001.png b/_images/sphx_glr_plot_subplot-grid_001.png new file mode 100644 index 000000000..99a0f54bd Binary files /dev/null and b/_images/sphx_glr_plot_subplot-grid_001.png differ diff --git a/_images/sphx_glr_plot_subplot-grid_thumb.png b/_images/sphx_glr_plot_subplot-grid_thumb.png new file mode 100644 index 000000000..75666387c Binary files /dev/null and b/_images/sphx_glr_plot_subplot-grid_thumb.png differ diff --git a/_images/sphx_glr_plot_subplot-horizontal_001.png b/_images/sphx_glr_plot_subplot-horizontal_001.png new file mode 100644 index 000000000..b5aa6bc39 Binary files /dev/null and b/_images/sphx_glr_plot_subplot-horizontal_001.png differ diff --git a/_images/sphx_glr_plot_subplot-horizontal_thumb.png b/_images/sphx_glr_plot_subplot-horizontal_thumb.png new file mode 100644 index 000000000..6fd5ccc88 Binary files /dev/null and b/_images/sphx_glr_plot_subplot-horizontal_thumb.png differ diff --git a/_images/sphx_glr_plot_subplot-vertical_001.png b/_images/sphx_glr_plot_subplot-vertical_001.png new file mode 100644 index 000000000..78c7fea87 Binary files /dev/null and b/_images/sphx_glr_plot_subplot-vertical_001.png differ diff --git a/_images/sphx_glr_plot_subplot-vertical_thumb.png b/_images/sphx_glr_plot_subplot-vertical_thumb.png new file mode 100644 index 000000000..346095e91 Binary files /dev/null and b/_images/sphx_glr_plot_subplot-vertical_thumb.png differ diff --git a/_images/sphx_glr_plot_svm_non_linear_001.png b/_images/sphx_glr_plot_svm_non_linear_001.png new file mode 100644 index 000000000..21fee1878 Binary files /dev/null and b/_images/sphx_glr_plot_svm_non_linear_001.png differ diff --git a/_images/sphx_glr_plot_svm_non_linear_002.png b/_images/sphx_glr_plot_svm_non_linear_002.png new file mode 100644 index 000000000..49f3a0607 Binary files /dev/null and b/_images/sphx_glr_plot_svm_non_linear_002.png differ diff --git a/_images/sphx_glr_plot_svm_non_linear_thumb.png b/_images/sphx_glr_plot_svm_non_linear_thumb.png new file mode 100644 index 000000000..fbe4ceb47 Binary files /dev/null and b/_images/sphx_glr_plot_svm_non_linear_thumb.png differ diff --git a/_images/sphx_glr_plot_synthetic_data_001.png b/_images/sphx_glr_plot_synthetic_data_001.png new file mode 100644 index 000000000..605bd97a0 Binary files /dev/null and b/_images/sphx_glr_plot_synthetic_data_001.png differ diff --git a/_images/sphx_glr_plot_synthetic_data_thumb.png b/_images/sphx_glr_plot_synthetic_data_thumb.png new file mode 100644 index 000000000..ab1ca7f2a Binary files /dev/null and b/_images/sphx_glr_plot_synthetic_data_thumb.png differ diff --git a/_images/sphx_glr_plot_t_test_001.png b/_images/sphx_glr_plot_t_test_001.png new file mode 100644 index 000000000..adbea4df6 Binary files /dev/null and b/_images/sphx_glr_plot_t_test_001.png differ diff --git a/_images/sphx_glr_plot_t_test_thumb.png b/_images/sphx_glr_plot_t_test_thumb.png new file mode 100644 index 000000000..025170a6f Binary files /dev/null and b/_images/sphx_glr_plot_t_test_thumb.png differ diff --git a/_images/sphx_glr_plot_text_001.png b/_images/sphx_glr_plot_text_001.png new file mode 100644 index 000000000..5bb7b21a1 Binary files /dev/null and b/_images/sphx_glr_plot_text_001.png differ diff --git a/_images/sphx_glr_plot_text_ext_001.png b/_images/sphx_glr_plot_text_ext_001.png new file mode 100644 index 000000000..236acd678 Binary files /dev/null and b/_images/sphx_glr_plot_text_ext_001.png differ diff --git a/_images/sphx_glr_plot_text_ext_thumb.png b/_images/sphx_glr_plot_text_ext_thumb.png new file mode 100644 index 000000000..ebfaa2c50 Binary files /dev/null and b/_images/sphx_glr_plot_text_ext_thumb.png differ diff --git a/_images/sphx_glr_plot_text_thumb.png b/_images/sphx_glr_plot_text_thumb.png new file mode 100644 index 000000000..da5f97976 Binary files /dev/null and b/_images/sphx_glr_plot_text_thumb.png differ diff --git a/_images/sphx_glr_plot_threshold_001.png b/_images/sphx_glr_plot_threshold_001.png new file mode 100644 index 000000000..233391405 Binary files /dev/null and b/_images/sphx_glr_plot_threshold_001.png differ diff --git a/_images/sphx_glr_plot_threshold_thumb.png b/_images/sphx_glr_plot_threshold_thumb.png new file mode 100644 index 000000000..e345e775d Binary files /dev/null and b/_images/sphx_glr_plot_threshold_thumb.png differ diff --git a/_images/sphx_glr_plot_ticks_001.png b/_images/sphx_glr_plot_ticks_001.png new file mode 100644 index 000000000..1c76a1e99 Binary files /dev/null and b/_images/sphx_glr_plot_ticks_001.png differ diff --git a/_images/sphx_glr_plot_ticks_thumb.png b/_images/sphx_glr_plot_ticks_thumb.png new file mode 100644 index 000000000..9db664700 Binary files /dev/null and b/_images/sphx_glr_plot_ticks_thumb.png differ diff --git a/_images/sphx_glr_plot_tsne_001.png b/_images/sphx_glr_plot_tsne_001.png new file mode 100644 index 000000000..738338a31 Binary files /dev/null and b/_images/sphx_glr_plot_tsne_001.png differ diff --git a/_images/sphx_glr_plot_tsne_thumb.png b/_images/sphx_glr_plot_tsne_thumb.png new file mode 100644 index 000000000..eb4a2d044 Binary files /dev/null and b/_images/sphx_glr_plot_tsne_thumb.png differ diff --git a/_images/sphx_glr_plot_ugly_001.png b/_images/sphx_glr_plot_ugly_001.png new file mode 100644 index 000000000..2b9fb864b Binary files /dev/null and b/_images/sphx_glr_plot_ugly_001.png differ diff --git a/_images/sphx_glr_plot_ugly_thumb.png b/_images/sphx_glr_plot_ugly_thumb.png new file mode 100644 index 000000000..3142252b1 Binary files /dev/null and b/_images/sphx_glr_plot_ugly_thumb.png differ diff --git a/_images/sphx_glr_plot_variance_linear_regr_001.png b/_images/sphx_glr_plot_variance_linear_regr_001.png new file mode 100644 index 000000000..236b78b29 Binary files /dev/null and b/_images/sphx_glr_plot_variance_linear_regr_001.png differ diff --git a/_images/sphx_glr_plot_variance_linear_regr_002.png b/_images/sphx_glr_plot_variance_linear_regr_002.png new file mode 100644 index 000000000..6d807c16b Binary files /dev/null and b/_images/sphx_glr_plot_variance_linear_regr_002.png differ diff --git a/_images/sphx_glr_plot_variance_linear_regr_003.png b/_images/sphx_glr_plot_variance_linear_regr_003.png new file mode 100644 index 000000000..0f14e51a3 Binary files /dev/null and b/_images/sphx_glr_plot_variance_linear_regr_003.png differ diff --git a/_images/sphx_glr_plot_variance_linear_regr_thumb.png b/_images/sphx_glr_plot_variance_linear_regr_thumb.png new file mode 100644 index 000000000..74a0ced92 Binary files /dev/null and b/_images/sphx_glr_plot_variance_linear_regr_thumb.png differ diff --git a/_images/sphx_glr_plot_wage_data_001.png b/_images/sphx_glr_plot_wage_data_001.png new file mode 100644 index 000000000..757072431 Binary files /dev/null and b/_images/sphx_glr_plot_wage_data_001.png differ diff --git a/_images/sphx_glr_plot_wage_data_002.png b/_images/sphx_glr_plot_wage_data_002.png new file mode 100644 index 000000000..70c90ffb3 Binary files /dev/null and b/_images/sphx_glr_plot_wage_data_002.png differ diff --git a/_images/sphx_glr_plot_wage_data_003.png b/_images/sphx_glr_plot_wage_data_003.png new file mode 100644 index 000000000..f33cd4564 Binary files /dev/null and b/_images/sphx_glr_plot_wage_data_003.png differ diff --git a/_images/sphx_glr_plot_wage_data_004.png b/_images/sphx_glr_plot_wage_data_004.png new file mode 100644 index 000000000..71577a4a1 Binary files /dev/null and b/_images/sphx_glr_plot_wage_data_004.png differ diff --git a/_images/sphx_glr_plot_wage_data_005.png b/_images/sphx_glr_plot_wage_data_005.png new file mode 100644 index 000000000..7cb8ce5b0 Binary files /dev/null and b/_images/sphx_glr_plot_wage_data_005.png differ diff --git a/_images/sphx_glr_plot_wage_data_thumb.png b/_images/sphx_glr_plot_wage_data_thumb.png new file mode 100644 index 000000000..983fe38d1 Binary files /dev/null and b/_images/sphx_glr_plot_wage_data_thumb.png differ diff --git a/_images/sphx_glr_plot_wage_education_gender_001.png b/_images/sphx_glr_plot_wage_education_gender_001.png new file mode 100644 index 000000000..779877506 Binary files /dev/null and b/_images/sphx_glr_plot_wage_education_gender_001.png differ diff --git a/_images/sphx_glr_plot_wage_education_gender_thumb.png b/_images/sphx_glr_plot_wage_education_gender_thumb.png new file mode 100644 index 000000000..7f026a942 Binary files /dev/null and b/_images/sphx_glr_plot_wage_education_gender_thumb.png differ diff --git a/_images/sphx_glr_plot_watershed_segmentation_001.png b/_images/sphx_glr_plot_watershed_segmentation_001.png new file mode 100644 index 000000000..f70d462c7 Binary files /dev/null and b/_images/sphx_glr_plot_watershed_segmentation_001.png differ diff --git a/_images/sphx_glr_plot_watershed_segmentation_thumb.png b/_images/sphx_glr_plot_watershed_segmentation_thumb.png new file mode 100644 index 000000000..cd62eb1d5 Binary files /dev/null and b/_images/sphx_glr_plot_watershed_segmentation_thumb.png differ diff --git a/_images/test.png b/_images/test.png new file mode 100644 index 000000000..d4775a833 Binary files /dev/null and b/_images/test.png differ diff --git a/_images/test2.png b/_images/test2.png new file mode 100644 index 000000000..9aa48cba1 Binary files /dev/null and b/_images/test2.png differ diff --git a/_images/test_cos_doubles.png b/_images/test_cos_doubles.png new file mode 100644 index 000000000..cd5e636ae Binary files /dev/null and b/_images/test_cos_doubles.png differ diff --git a/_images/test_cos_doubles1.png b/_images/test_cos_doubles1.png new file mode 100644 index 000000000..cd5e636ae Binary files /dev/null and b/_images/test_cos_doubles1.png differ diff --git a/_images/test_cos_doubles2.png b/_images/test_cos_doubles2.png new file mode 100644 index 000000000..cd5e636ae Binary files /dev/null and b/_images/test_cos_doubles2.png differ diff --git a/_images/test_cos_module_np.png b/_images/test_cos_module_np.png new file mode 100644 index 000000000..cd5e636ae Binary files /dev/null and b/_images/test_cos_module_np.png differ diff --git a/_images/three_phases.png b/_images/three_phases.png new file mode 100644 index 000000000..28c9f25e5 Binary files /dev/null and b/_images/three_phases.png differ diff --git a/_images/threefundamental.png b/_images/threefundamental.png new file mode 100644 index 000000000..de252fc9d Binary files /dev/null and b/_images/threefundamental.png differ diff --git a/_images/two_sided.png b/_images/two_sided.png new file mode 100644 index 000000000..a6756f283 Binary files /dev/null and b/_images/two_sided.png differ diff --git a/_images/vim_pyflakes.png b/_images/vim_pyflakes.png new file mode 100644 index 000000000..c6aeceed6 Binary files /dev/null and b/_images/vim_pyflakes.png differ diff --git a/_images/vim_syntastic.png b/_images/vim_syntastic.png new file mode 100644 index 000000000..08e6ea404 Binary files /dev/null and b/_images/vim_syntastic.png differ diff --git a/_sources/AUTHORS.rst.txt b/_sources/AUTHORS.rst.txt new file mode 100644 index 000000000..0572132f7 --- /dev/null +++ b/_sources/AUTHORS.rst.txt @@ -0,0 +1,277 @@ + +Authors +======== + +Editors +-------- + +- Gaël Varoquaux + +- Emmanuelle Gouillart + +- Olav Vahtras + +- Pierre de Buyl + +- K\. Jarrod Millman + +- Stéfan van der Walt + + +Chapter authors +---------------- + +Listed by alphabetical order. + +- Christopher Burns + +- Adrian Chauve + +- Robert Cimrman + +- Christophe Combelles + +- André Espaze + +- Emmanuelle Gouillart + +- Mike Müller + +- Fabian Pedregosa + +- Didrik Pinte + +- Nicolas Rougier + +- Gaël Varoquaux + +- Pauli Virtanen + +- Zbigniew Jędrzejewski-Szmek + +- Valentin Haenel (editor from 2011 to 2015) + +Additional Contributions +------------------------ + +Listed by alphabetical order + +- Osayd Abdu + +- arunpersaud + +- Ross Barnowski + +- Sebastian Berg + +- Lilian Besson + +- Matthieu Boileau + +- Joris Van den Bossche + +- Michael Boyle + +- Matthew Brett + +- BSGalvan + +- Lars Buitinck + +- Pierre de Buyl + +- Ozan Çağlayan + +- Lawrence Chan + +- Adrien Chauve + +- Robert Cimrman + +- Christophe Combelles + +- David Cournapeau + +- Dave + +- dogacan dugmeci + +- Török Edwin + +- egens + +- Andre Espaze + +- André Espaze + +- Loïc Estève + +- Corey Farwell + +- Tim Gates + +- Stuart Geiger + +- Olivier Georg + +- Daniel Gerigk + +- Robert Gieseke + +- Philip Gillißen + +- Ralf Gommers + +- Emmanuelle Gouillart + +- Julia Gustavsen + +- Omar Gutiérrez + +- Matt Haberland + +- Valentin Haenel + +- Pierre Haessig + +- Bruno Hanzen + +- Michael Hartmann + +- Jonathan Helmus + +- Andreas Hilboll + +- Himanshu + +- Julian Hofer + +- Tim Hoffmann + +- B\. Hohl + +- Tarek Hoteit + +- Gert-Ludwig Ingold + +- Zbigniew Jędrzejewski-Szmek + +- Thouis (Ray) Jones + +- jorgeprietoarranz + +- josephsalmon + +- Greg Kiar + +- kikocorreoso + +- Vince Knight + +- LFP6 + +- Manuel López-Ibáñez + +- Marco Mangan + +- Nicola Masarone + +- John McLaughlin + +- mhemantha + +- michelemaroni89 + +- K\. Jarrod Millman + +- Mohammad + +- Zachary Moon + +- Mike Mueller + +- negm + +- John B Nelson + +- nicoguaro + +- Sergio Oller + +- Theofilos Papapanagiotou + +- patniharshit + +- Fabian Pedregosa + +- Philippe Pepiot + +- Tiago M. D. Pereira + +- Nicolas Pettiaux + +- Didrik Pinte + +- Evgeny Pogrebnyak + +- reverland + +- Maximilien Riehl + +- Kristian Rother + +- Nicolas P. Rougier + +- Pamphile Roy + +- Rutzmoser + +- Sander + +- João Felipe Santos + +- Mark Setchell + +- Helen Sherwood-Taylor + +- Shoeboxam + +- Simon + +- solarjoe + +- ssmiller + +- Scott Staniewicz + +- strpeter + +- surfer190 + +- Bartosz Telenczuk + +- tommyod + +- Wes Turner + +- Akihiro Uchida + +- Utkarsh Upadhyay + +- Olav Vahtras + +- Stéfan van der Walt + +- Gaël Varoquaux + +- Nelle Varoquaux + +- Olivier Verdier + +- VirgileFritsch + +- Pauli Virtanen + +- Yosh Wakeham + +- yasutomo57jp diff --git a/_sources/CHANGES.rst.txt b/_sources/CHANGES.rst.txt new file mode 100644 index 000000000..a3a7cd8bd --- /dev/null +++ b/_sources/CHANGES.rst.txt @@ -0,0 +1,261 @@ +What's new +========== + +Release 2024.1 (April 2024) +--------------------------- + +- Python 3.10, 3.11, 3.12 + +- Renamed Scientific Python Lectures + +- Removed old content + +- Major updates to support recent packages + +- Updates to the SciPy and scikit-image chapters + + +Release 2022.1 (August 2022) +---------------------------- + +* Replace scikit-learn housing example with California data (Marco Mangan) + +* Fix links and typos (Zachary Moon, Tim Gates, Marco Mangan, Gert-Ludwig Ingold) + +* Fix fftpack figure (Osayd Abdu) + +* Update software version (Pierre de Buyl) + +Release 2020.2 (September 2020) +------------------------------- + +* Replace image i/o from scipy.misc by imageio (Pierre de Buyl) + +* Update information on dict ordering (Bharath Saiguhan) + +* Suppress warnings for mandelbrot example (Pierre de Buyl) + +* Update NumPy introduction and advanced usage for changes to NumPy: wording, bytes + representation, floating point argument to np.zeros (Ross Barnowski) + +* Fix links to NumPy documentation to use numpy.org (Ross Barnowski) + +* Update note on transposed arrays (Ross Barnowski with Eric Wieser) + +* Use generated figure file for lidar data processing (Lawrence Chan) + +* Update link from PyMC2 to PyMC3 (B. Hohl) + +* Fix transparent popup menu to have a background (Pierre de Buyl) + + +Release 2020.1 (March 2020) +----------------------------- + +* Fix outdated URLs (Gert-Ludwig Ingold) + +* Update packages (Pierre de Buyl) + +* Remove Python 2 continuous integration (Olav Vahtras - EuroSciPy 2019 sprint) + +* Fix chessboard size (Mark Setchell) + +* Add objectives and design choices (Gert-Ludwig Ingold and Pierre de Buyl) + +* Make the numpy advanced iterator example more elaborate (Sebastian Berg) + +* Use empty list instead of empty tuple to deactivate ticks (Tim Hoffmann) + +* Fix typos (Sander van Rijn, cydave, Michel Corne) and off by 2 errors + (Andreas Hilboll) + +* Improve readability of Polynomials example code (Michel Corne) + +* Replace suggestions for debugging environments (Gert-Ludwig Ingold) + +* Add section on Python 2 vs Python 3 (Pierre de Buyl) + + +Release 2019.1 (May 2019) +------------------------- + +* Update matplotlib compatibility to version 2.2 (Mike Mueller, Joris Van den + Bossche, Pierre de Buyl) + +* Make C-API example cos_module_np Python 2/3 compatible (Michael Boyle) + +* Fix typos and outdated URLs (Dogacan Dugmeci, Matthieu Boileau, Stuart Geiger, Omar + Gutiérrez, Himanshu, Julian Hofer, Joseph Salmon, Manuel López-Ibáñez, + Nicola Masarone, michelemaroni89, Evgeny Pogrebnyak, tommyod) + + +Release 2018.1 (September 2018) +------------------------------------- + +* Fix wordings, typos, colours (Pierre de Buyl, Greg Kiar, Olav Vahtras + Kristian Rother) + +* Fix interpolation example code (Scott Staniewicz) + +* Fix CSS for high density displays (Gaël Varoquaux) + +* Generate indexing figures with PyX (Gert Ingold) + +* Warn clearly against the use of Python 2 (Bruno Hanzen) + +* Update external links (Bruno Hanzen) + +* Update versions of dependencies: sphinx-gallery, pandas, statsmodels + (Gaël Varoquaux) + + +Release 2017.1 (October 2017) +------------------------------------- + +* Update optimization chapter (Michael Hartmann, Gaël Varoquaux) + +* Update SymPy chapter (Vince Knight) + +* Update advanced NumPy (Bartosz Teleńczuk) + +* Update scikit-learn chapter (Gaël Varoquaux) + +* Update SciPy chapter (Gaël Varoquaux) + +* Make '>>>' in the prompts unselectable (Pierre de Buyl) + +* Use common package requirements for pip and conda and improve the build + instructions (Gert-Ludwig Ingold, Vince Knight, Pierre de Buyl) + +* Set up Circle CI (Loïc Estève) + +* Improved support for Python 3 integer divisions and calls to print (Loïc + Estève, Gert-Ludwig Ingold, Pierre de Buyl, Gaël Varoquaux) + +* Change test runner to pytest (Pierre de Buyl) + +* Replace the plot directive by sphinx-gallery (Gert-Ludwig Ingold) + +Release 2016.1 (September 2016) +------------------------------------- + +* Rework of intro chapter (Gaël Varoquaux) + +* Integrate sphinx-gallery: examples are now Jupyter notebooks (Gaël + Varoquaux, Gert-Ludwig Ingold, Óscar Nájera) + +* Better Python 3 tests and support (Gert-Ludwig Ingold) + +* Adapt examples to Matplotlib 1.5 (Gaël Varoquaux) + +* Modernize numpy chapter (Bartosz Telenczuk) + +Release 2015.3 (November 2015) +------------------------------------- + +* Collapsed sidebar can now pop up for mid-sized display (Gaël Varoquaux) + +* Replaced pictures of Lena by raccoon face (Thouis Jones) + +Release 2015.2 (October 2015) +------------------------------------- + +* Authors on cover ordered as in bibtex entry (Nicolas Rougier) + +* Better rendering on mobile (Gaël Varoquaux) + +* Fix restructured text markup errors (Olav Vahtras) + +Release 2015.1 (September 2015) +------------------------------------- + +* New chapter on statistics with Python (Gaël Varoquaux) + +* Better layout in PDF (Gaël Varoquaux) + +* New HTML layout, simplified formatting, mobile-friendly and sidebar + (Gaël Varoquaux, Nelle Varoquaux) + +* Logos on the HTML front page and on the PDF cover (Nicolas Rougier) + +* Python 3 compatible code (Gaël Varoquaux, Olav Vahtras) + +* Code put up to date for more recent versions of project (Pierre de + Buyl, Emmanuelle Gouillart, Gert-Ludwig Ingold, Nicolas Pettiaux, Olav + Vahtras, Gaël Varoquaux, Nelle Varoquaux) + +* Matplotlib updated with removal of deprecated pylab interface (Nicolas + Rougier) + +Release 2013.2 (21 August 2013) +------------------------------------- + +* NumPy chapter simplified (Valentin Haenel) + +* New layout for the HTML rendering (Gaël Varoquaux) + +Release 2013.1 (10 Feb 2013) +---------------------------- + +* Improvements to the advanced image manipulation chapter (Emmanuelle Gouillart) + +* Upgrade of the introductory language chapter (Valentin Haenel) + +* Upgrade of the introductory numpy chapter (Valentin Haenel) + +* New advanced chapter on interfacing with C (Valentin Haenel) + +* Minor fixes and improvements in various places (Robert Gieseke, Ozan Çağlayan, + Sergio Oller, kikocorreo, Valentin Haenel) + + +Release 2012.3 (26 Nov 2012) +---------------------------- + +This release integrates the changes written for the Euroscipy conference: + +* Matplotlib chapter completely redone (Nicolas Rougier, Gaël Varoquaux) + +* New advanced chapter on mathematical optimization (Gaël Varoquaux) + +* Mayavi chapter redone (Gaël Varoquaux) + +* Front page layout slightly improved: folding TOC (Gaël Varoquaux) + +Release 2012.2 (22 Jun 2012) +---------------------------- + +Minor release with a few clean ups (Gael Varoquaux). + +Release 2012.1 (20 Jun 2012) +---------------------------- + +This is a minor release with many clean ups. In particular, clean up of +the layout (Gael Varoquaux), shortening of the numpy chapters and +deduplications across the intro and advanced chapters (Gael Varoquaux) +and doctesting of all the code (Gael Varoquaux). + +Release 2012.0 (22 Apr 2012) +---------------------------- + +This is a minor release with a few clean ups. In particular, clean up the +scikit-learn chapter (Lars Buitinck), more informative section titles +(Gael Varoquaux), and misc fixes (Valentin Haenel, Virgile Fritsch). + +Release 2011.1 (16 Oct 2011) +---------------------------- + +This release is a reworked version of the Euroscipy 2011 tutorial. Layout +has been cleaned and optimized (Valentin Haenel and many others), the Traits +chapter has been merged in (Didrik Pinte) + +Release 2011 (1 Sept 2011) +--------------------------- + +This release is used for the Euroscipy 2011 tutorial. The numpy +introductory chapter has been rewamped (Pauli Virtanen). The outline of +the introductory chapters has been simplified (Gaël Varoquaux). Advanced +chapters have been added: advanced Python constructs (Zbigniew +Jędrzejewski-Szmek), debugging code (Gaël Varoquaux), optimizing code +(Gaël Varoquaux), image processing (Emmanuelle Gouillart), scikit-learn +(Fabian Pedregosa). diff --git a/_sources/CONTRIBUTING.rst.txt b/_sources/CONTRIBUTING.rst.txt new file mode 100644 index 000000000..93ecb3dca --- /dev/null +++ b/_sources/CONTRIBUTING.rst.txt @@ -0,0 +1,106 @@ +Contributing +============= + +The Scientific Python Lectures are a community-based effort and require +constant maintenance and improvements. New contributions such as wording +improvements or inclusion of new topics are welcome. + +To propose bugfixes or straightforward improvements to the lectures, see the +contribution guide below. + +For new topics, read the objectives first and `open an issue on the GitHub +project `_ to +discuss it with the editors. + + +Objectives and design choices for the lectures +---------------------------------------------- + +Contributors should keep the following objectives and design choices of +the Scientific Python Lectures in mind. + +Objectives: + +* Provide a self-contained introduction to Python and its primary computational + packages, the ”Scientific Python stack“. +* Provide tutorials for a selection of widely-used and stable computational + libraries. + Currently, we cover pandas, statmodels, seaborn, scikit-image, + scikit-learn, and sympy. +* Automated testing is applied to the code examples as much as possible. + +Design choices: + +* Each chapter should provide a useful basis for a 1‒2 h tutorial. +* The code should be readable. +* An idomatic style should be followed, e.g. ``import numpy as np``, + preference for array operations, PEP8 coding conventions. + + +Contributing guide +------------------ + +The directory ``guide`` contains instructions on how to contribute: + +.. topic:: **Example chapter** + + .. toctree:: + + guide/index.rst + +Building instructions +---------------------- + +To generate the html output for on-screen display, Type:: + + make html + +the generated html files can be found in ``build/html`` + +The first build takes a long time, but information is cached and +subsequent builds will be faster. + +To generate the pdf file for printing:: + + make pdf + +The pdf builder is a bit difficult and you might have some TeX errors. +Tweaking the layout in the ``*.rst`` files is usually enough to work +around these problems. + +Requirements +............ + +Build requirements are listed in the +:download:`requirements file `: + +.. literalinclude:: requirements.txt + +Ensure that you have a `virtual environment +`__ or conda environment +set up, then install requirements with:: + + pip install -r requirements.txt + +Note that you will also need the following system packages: + + - Python C development headers (the `python3-dev` package on Debian, e.g.), + - a C compiler like gcc, + - `GNU Make `__, + - a full LaTeX distribution such as `TeX Live + `__ (``texlive-latex-base``, + ``texlive-latex-extra``, ``texlive-fonts-extra``, and ``latexmk`` + on Debian/Ubuntu), + - `dvipng `__, + - `latexmk `__, + - `git `__. + +Updating the cover +.................. + +Use inkscape to modify the cover in ``images/``, then export to PDF:: + + inkscape --export-filename=cover-2024.pdf cover-2024.svg + +Ensure that the ``images/cover.pdf`` symlink points to the correct +file. diff --git a/_sources/LICENSE.rst.txt b/_sources/LICENSE.rst.txt new file mode 100644 index 000000000..c59ed1103 --- /dev/null +++ b/_sources/LICENSE.rst.txt @@ -0,0 +1,10 @@ +License +======== + +All code and material is licensed under a + +Creative Commons Attribution 4.0 International License (CC-by) + +https://creativecommons.org/licenses/by/4.0/ + +See the AUTHORS.rst file for a list of contributors. diff --git a/_sources/about.rst.txt b/_sources/about.rst.txt new file mode 100644 index 000000000..908062e31 --- /dev/null +++ b/_sources/about.rst.txt @@ -0,0 +1,29 @@ +.. only:: latex + + ==================================== + About the Scientific Python Lectures + ==================================== + + + About the Scientific Python Lectures + ==================================== + + Release: |release| + + The lectures are archived on zenodo: http://dx.doi.org/10.5281/zenodo.594102 + + All code and material is licensed under a + Creative Commons Attribution 4.0 International License (CC-by) + http://creativecommons.org/licenses/by/4.0/ + + .. raw:: latex + + \begin{multicols}{2} + + .. toctree:: + + AUTHORS.rst + + .. raw:: latex + + \end{multicols} diff --git a/_sources/advanced/advanced_numpy/auto_examples/index.rst.txt b/_sources/advanced/advanced_numpy/auto_examples/index.rst.txt new file mode 100644 index 000000000..a86232149 --- /dev/null +++ b/_sources/advanced/advanced_numpy/auto_examples/index.rst.txt @@ -0,0 +1,61 @@ +:orphan: + +Examples for the advanced NumPy chapter +======================================= + + + +.. raw:: html + +
+ +.. thumbnail-parent-div-open + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/advanced_numpy/auto_examples/images/thumb/sphx_glr_plot_maskedstats_thumb.png + :alt: + + :ref:`sphx_glr_advanced_advanced_numpy_auto_examples_plot_maskedstats.py` + +.. raw:: html + +
Example: Masked statistics
+
+ + +.. thumbnail-parent-div-close + +.. raw:: html + +
+ + +.. toctree:: + :hidden: + + /advanced/advanced_numpy/auto_examples/plot_maskedstats + + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-gallery + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download all examples in Python source code: auto_examples_python.zip ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download all examples in Jupyter notebooks: auto_examples_jupyter.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/advanced_numpy/auto_examples/plot_maskedstats.rst.txt b/_sources/advanced/advanced_numpy/auto_examples/plot_maskedstats.rst.txt new file mode 100644 index 000000000..c1a5c4eab --- /dev/null +++ b/_sources/advanced/advanced_numpy/auto_examples/plot_maskedstats.rst.txt @@ -0,0 +1,85 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/advanced_numpy/auto_examples/plot_maskedstats.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_advanced_numpy_auto_examples_plot_maskedstats.py: + + +Example: Masked statistics +========================== + +Plot a masked statistics + +.. GENERATED FROM PYTHON SOURCE LINES 8-22 + + + +.. image-sg:: /advanced/advanced_numpy/auto_examples/images/sphx_glr_plot_maskedstats_001.png + :alt: plot maskedstats + :srcset: /advanced/advanced_numpy/auto_examples/images/sphx_glr_plot_maskedstats_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + data = np.loadtxt("../../../../data/populations.txt") + populations = np.ma.masked_array(data[:, 1:]) # type: ignore[var-annotated] + year = data[:, 0] + + bad_years = ((year >= 1903) & (year <= 1910)) | ((year >= 1917) & (year <= 1918)) + populations[bad_years, 0] = np.ma.masked + populations[bad_years, 1] = np.ma.masked + + plt.plot(year, populations, "o-") + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.062 seconds) + + +.. _sphx_glr_download_advanced_advanced_numpy_auto_examples_plot_maskedstats.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_maskedstats.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_maskedstats.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_maskedstats.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/advanced_numpy/auto_examples/sg_execution_times.rst.txt b/_sources/advanced/advanced_numpy/auto_examples/sg_execution_times.rst.txt new file mode 100644 index 000000000..c59ac206e --- /dev/null +++ b/_sources/advanced/advanced_numpy/auto_examples/sg_execution_times.rst.txt @@ -0,0 +1,37 @@ + +:orphan: + +.. _sphx_glr_advanced_advanced_numpy_auto_examples_sg_execution_times: + + +Computation times +================= +**00:00.062** total execution time for 1 file **from advanced/advanced_numpy/auto_examples**: + +.. container:: + + .. raw:: html + + + + + + + + .. list-table:: + :header-rows: 1 + :class: table table-striped sg-datatable + + * - Example + - Time + - Mem (MB) + * - :ref:`sphx_glr_advanced_advanced_numpy_auto_examples_plot_maskedstats.py` (``plot_maskedstats.py``) + - 00:00.062 + - 0.0 diff --git a/_sources/advanced/advanced_numpy/index.rst.txt b/_sources/advanced/advanced_numpy/index.rst.txt new file mode 100644 index 000000000..d7e1d11ff --- /dev/null +++ b/_sources/advanced/advanced_numpy/index.rst.txt @@ -0,0 +1,1669 @@ +.. For doctests + >>> import numpy as np + >>> rng = np.random.default_rng(27446968) + >>> # For doctest on headless environments + >>> import matplotlib.pyplot as plt + +.. _advanced_numpy: + +============== +Advanced NumPy +============== + +**Author**: *Pauli Virtanen* + +NumPy is at the base of Python's scientific stack of tools. Its purpose +to implement efficient operations on many items in a block of memory. +Understanding how it works in detail helps in making efficient use of its +flexibility, taking useful shortcuts. + +This section covers: + +- Anatomy of NumPy arrays, and its consequences. Tips and + tricks. + +- Universal functions: what, why, and what to do if you want + a new one. + +- Integration with other tools: NumPy offers several ways to + wrap any data in an ndarray, without unnecessary copies. + +- Recently added features, and what's in them: PEP + 3118 buffers, generalized ufuncs, ... + +.. currentmodule:: numpy + +.. topic:: Prerequisites + + * NumPy + * Cython + * Pillow (Python imaging library, used in a couple of examples) + +.. contents:: Chapter contents + :local: + :depth: 2 + +.. tip:: + + In this section, NumPy will be imported as follows:: + + >>> import numpy as np + + +Life of ndarray +=============== + +It's... +------- + +**ndarray** = + + block of memory + indexing scheme + data type descriptor + + - raw data + - how to locate an element + - how to interpret an element + +.. image:: threefundamental.png + +.. code-block:: c + + typedef struct PyArrayObject { + PyObject_HEAD + + /* Block of memory */ + char *data; + + /* Data type descriptor */ + PyArray_Descr *descr; + + /* Indexing scheme */ + int nd; + npy_intp *dimensions; + npy_intp *strides; + + /* Other stuff */ + PyObject *base; + int flags; + PyObject *weakreflist; + } PyArrayObject; + + +Block of memory +--------------- + +>>> x = np.array([1, 2, 3], dtype=np.int32) +>>> x.data +<... at ...> +>>> bytes(x.data) +b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00' + +Memory address of the data: + +>>> x.__array_interface__['data'][0] # doctest: +SKIP +64803824 + +The whole ``__array_interface__``: + +>>> x.__array_interface__ +{'data': (..., False), 'strides': None, 'descr': [('', '` may share the same memory:: + + >>> x = np.array([1, 2, 3, 4]) + >>> y = x[:-1] + >>> x[0] = 9 + >>> y + array([9, 2, 3]) + +Memory does not need to be owned by an :class:`ndarray`:: + + >>> x = b'1234' + +x is a string (in Python 3 a bytes), we can represent its data as an +array of ints:: + + >>> y = np.frombuffer(x, dtype=np.int8) + >>> y.data + <... at ...> + >>> y.base is x + True + + >>> y.flags + C_CONTIGUOUS : True + F_CONTIGUOUS : True + OWNDATA : False + WRITEABLE : False + ALIGNED : True + WRITEBACKIFCOPY : False + + +The ``owndata`` and ``writeable`` flags indicate status of the memory +block. + +.. seealso:: `array interface `_ + +Data types +---------- + +The descriptor +^^^^^^^^^^^^^^ + +:class:`dtype` describes a single item in the array: + +========= =================================================== +type **scalar type** of the data, one of: + + int8, int16, float64, *et al.* (fixed size) + + str, unicode, void (flexible size) + +itemsize **size** of the data block +byteorder **byte order**: big-endian ``>`` / little-endian ``<`` / not applicable ``|`` +fields sub-dtypes, if it's a **structured data type** +shape shape of the array, if it's a **sub-array** +========= =================================================== + +>>> np.dtype(int).type + +>>> np.dtype(int).itemsize +8 +>>> np.dtype(int).byteorder +'=' + + +Example: reading ``.wav`` files +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The ``.wav`` file header: + +================ ========================================== +chunk_id ``"RIFF"`` +chunk_size 4-byte unsigned little-endian integer +format ``"WAVE"`` +fmt_id ``"fmt "`` +fmt_size 4-byte unsigned little-endian integer +audio_fmt 2-byte unsigned little-endian integer +num_channels 2-byte unsigned little-endian integer +sample_rate 4-byte unsigned little-endian integer +byte_rate 4-byte unsigned little-endian integer +block_align 2-byte unsigned little-endian integer +bits_per_sample 2-byte unsigned little-endian integer +data_id ``"data"`` +data_size 4-byte unsigned little-endian integer +================ ========================================== + +- 44-byte block of raw data (in the beginning of the file) +- ... followed by ``data_size`` bytes of actual sound data. + +The ``.wav`` file header as a NumPy *structured* data type:: + + >>> wav_header_dtype = np.dtype([ + ... ("chunk_id", (bytes, 4)), # flexible-sized scalar type, item size 4 + ... ("chunk_size", ">> wav_header_dtype['format'] + dtype('S4') + >>> wav_header_dtype.fields + mappingproxy({'chunk_id': (dtype('S4'), 0), 'chunk_size': (dtype('uint32'), 4), 'format': (dtype('S4'), 8), 'fmt_id': (dtype('S4'), 12), 'fmt_size': (dtype('uint32'), 16), 'audio_fmt': (dtype('uint16'), 20), 'num_channels': (dtype('uint16'), 22), 'sample_rate': (dtype('uint32'), 24), 'byte_rate': (dtype('uint32'), 28), 'block_align': (dtype('uint16'), 32), 'bits_per_sample': (dtype('uint16'), 34), 'data_id': (dtype(('S1', (2, 2))), 36), 'data_size': (dtype('uint32'), 40)}) + >>> wav_header_dtype.fields['format'] + (dtype('S4'), 8) + +- The first element is the sub-dtype in the structured data, corresponding + to the name ``format`` + +- The second one is its offset (in bytes) from the beginning of the item + +.. topic:: Exercise + :class: green + + Mini-exercise, make a "sparse" dtype by using offsets, and only some + of the fields:: + + >>> wav_header_dtype = np.dtype(dict( + ... names=['format', 'sample_rate', 'data_id'], + ... offsets=[offset_1, offset_2, offset_3], # counted from start of structure in bytes + ... formats=list of dtypes for each of the fields, + ... )) # doctest: +SKIP + + and use that to read the sample rate, and ``data_id`` (as sub-array). + +>>> f = open('data/test.wav', 'r') +>>> wav_header = np.fromfile(f, dtype=wav_header_dtype, count=1) +>>> f.close() +>>> print(wav_header) # doctest: +SKIP +[ ('RIFF', 17402L, 'WAVE', 'fmt ', 16L, 1, 1, 16000L, 32000L, 2, 16, [['d', 'a'], ['t', 'a']], 17366L)] +>>> wav_header['sample_rate'] +array([16000], dtype=uint32) + +Let's try accessing the sub-array: + +>>> wav_header['data_id'] # doctest: +SKIP +array([[['d', 'a'], + ['t', 'a']]], + dtype='|S1') +>>> wav_header.shape +(1,) +>>> wav_header['data_id'].shape +(1, 2, 2) + +When accessing sub-arrays, the dimensions get added to the end! + +.. note:: + + There are existing modules such as ``wavfile``, ``audiolab``, + etc. for loading sound data... + + +Casting and re-interpretation/views +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +**casting** + + - on assignment + - on array construction + - on arithmetic + - etc. + - and manually: ``.astype(dtype)`` + +**data re-interpretation** + + - manually: ``.view(dtype)`` + + +Casting +........ + +- Casting in arithmetic, in nutshell: + + - only type (not value!) of operands matters + + - largest "safe" type able to represent both is picked + + - scalars can "lose" to arrays in some situations + +- Casting in general copies data:: + + >>> x = np.array([1, 2, 3, 4], dtype=float) + >>> x + array([1., 2., 3., 4.]) + >>> y = x.astype(np.int8) + >>> y + array([1, 2, 3, 4], dtype=int8) + >>> y + 1 + array([2, 3, 4, 5], dtype=int8) + >>> y + 256 + Traceback (most recent call last): + File "", line 1, in + OverflowError: Python integer 256 out of bounds for int8 + >>> y + 256.0 + array([257., 258., 259., 260.]) + >>> y + np.array([256], dtype=np.int32) + array([257, 258, 259, 260], dtype=int32) + +- Casting on setitem: dtype of the array is not changed on item assignment:: + + >>> y[:] = y + 1.5 + >>> y + array([2, 3, 4, 5], dtype=int8) + +.. note:: + + Exact rules: see `NumPy documentation + `_ + + +Re-interpretation / viewing +............................ + +- Data block in memory (4 bytes) + + ========== ==== ========== ==== ========== ==== ========== + ``0x01`` || ``0x02`` || ``0x03`` || ``0x04`` + ========== ==== ========== ==== ========== ==== ========== + + - 4 of uint8, OR, + - 4 of int8, OR, + - 2 of int16, OR, + - 1 of int32, OR, + - 1 of float32, OR, + - ... + + How to switch from one to another? + +1. Switch the dtype: + + >>> x = np.array([1, 2, 3, 4], dtype=np.uint8) + >>> x.dtype = ">> x + array([ 513, 1027], dtype=int16) + >>> 0x0201, 0x0403 + (513, 1027) + + ========== ========== ==== ========== ========== + ``0x01`` ``0x02`` || ``0x03`` ``0x04`` + ========== ========== ==== ========== ========== + + + .. note:: little-endian: least significant byte is on the *left* in memory + + +2. Create a new view of type ``uint32``, shorthand ``i4``: + + >>> y = x.view(">> y + array([67305985], dtype=int32) + >>> 0x04030201 + 67305985 + + ========== ========== ========== ========== + ``0x01`` ``0x02`` ``0x03`` ``0x04`` + ========== ========== ========== ========== + +.. note:: + + - ``.view()`` makes *views*, does not copy (or alter) the memory block + - only changes the dtype (and adjusts array shape):: + + >>> x[1] = 5 + >>> y + array([328193], dtype=int32) + >>> y.base is x + True + +.. rubric:: Mini-exercise: data re-interpretation + +.. seealso:: view-colors.py + +You have RGBA data in an array:: + + >>> x = np.zeros((10, 10, 4), dtype=np.int8) + >>> x[:, :, 0] = 1 + >>> x[:, :, 1] = 2 + >>> x[:, :, 2] = 3 + >>> x[:, :, 3] = 4 + +where the last three dimensions are the R, B, and G, and alpha channels. + +How to make a (10, 10) structured array with field names 'r', 'g', 'b', 'a' +without copying data? :: + + >>> y = ... # doctest: +SKIP + + >>> assert (y['r'] == 1).all() # doctest: +SKIP + >>> assert (y['g'] == 2).all() # doctest: +SKIP + >>> assert (y['b'] == 3).all() # doctest: +SKIP + >>> assert (y['a'] == 4).all() # doctest: +SKIP + +*Solution* + + .. raw:: html + + ... + + +.. warning:: + + Another two arrays, each occupying exactly 4 bytes of memory: + + >>> x = np.array([[1, 3], [2, 4]], dtype=np.uint8) + >>> x + array([[1, 3], + [2, 4]], dtype=uint8) + >>> y = x.transpose() + >>> y + array([[1, 2], + [3, 4]], dtype=uint8) + + We view the elements of ``x`` (1 byte each) as ``int16`` (2 bytes each): + + >>> x.view(np.int16) + array([[ 769], + [1026]], dtype=int16) + + What is happening here? Take a look at the bytes stored in memory + by ``x``: + + >>> x.tobytes() + b'\x01\x03\x02\x04' + + The ``\x`` stands for heXadecimal, so what we are seeing is:: + + 0x01 0x03 0x02 0x04 + + We ask NumPy to interpret these bytes as elements of dtype + ``int16``—each of which occupies *two* bytes in memory. Therefore, + ``0x01 0x03`` becomes the first ``uint16`` and ``0x02 0x04`` the + second. + + You may then expect to see ``0x0103`` (259, when converting from + hexadecimal to decimal) as the first result. But your computer + likely stores most significant bytes first, and as such reads the + number as ``0x0301`` or 769 (go on and type `0x0301` into your Python + terminal to verify). + + We can do the same on a copy of ``y`` (why doesn't it work on ``y`` + directly?): + + >>> y.copy().view(np.int16) + array([[ 513], + [1027]], dtype=int16) + + Can you explain these numbers, 513 and 1027, as well as the output + shape of the resulting array? + + +Indexing scheme: strides +------------------------ + +Main point +^^^^^^^^^^ + +**The question**:: + + >>> x = np.array([[1, 2, 3], + ... [4, 5, 6], + ... [7, 8, 9]], dtype=np.int8) + >>> x.tobytes('A') + b'\x01\x02\x03\x04\x05\x06\x07\x08\t' + + At which byte in ``x.data`` does the item ``x[1, 2]`` begin? + +**The answer** (in NumPy) + + - **strides**: the number of bytes to jump to find the next element + - 1 stride per dimension + +.. code-block:: pycon + + >>> x.strides + (3, 1) + >>> byte_offset = 3 * 1 + 1 * 2 # to find x[1, 2] + >>> x.flat[byte_offset] + np.int8(6) + >>> x[1, 2] + np.int8(6) + +simple, **flexible** + + +C and Fortran order +..................... + +.. note:: + The Python built-in :py:class:`bytes` returns bytes in C-order by default + which can cause confusion when trying to inspect memory layout. We use + :meth:`numpy.ndarray.tobytes` with ``order=A`` instead, which preserves + the C or F ordering of the bytes in memory. + +:: + + >>> x = np.array([[1, 2, 3], + ... [4, 5, 6]], dtype=np.int16, order='C') + >>> x.strides + (6, 2) + >>> x.tobytes('A') + b'\x01\x00\x02\x00\x03\x00\x04\x00\x05\x00\x06\x00' + +* Need to jump 6 bytes to find the next row +* Need to jump 2 bytes to find the next column + +:: + + >>> y = np.array(x, order='F') + >>> y.strides + (2, 4) + >>> y.tobytes('A') + b'\x01\x00\x04\x00\x02\x00\x05\x00\x03\x00\x06\x00' + +* Need to jump 2 bytes to find the next row +* Need to jump 4 bytes to find the next column + + +- Similarly to higher dimensions: + + - C: last dimensions vary fastest (= smaller strides) + - F: first dimensions vary fastest + + .. math:: + + \mathrm{shape} &= (d_1, d_2, ..., d_n) + \\ + \mathrm{strides} &= (s_1, s_2, ..., s_n) + \\ + s_j^C &= d_{j+1} d_{j+2} ... d_{n} \times \mathrm{itemsize} + \\ + s_j^F &= d_{1} d_{2} ... d_{j-1} \times \mathrm{itemsize} + + +.. note:: + + Now we can understand the behavior of ``.view()``: + + >>> y = np.array([[1, 3], [2, 4]], dtype=np.uint8).transpose() + >>> x = y.copy() + + Transposition does not affect the memory layout of the data, only strides + + >>> x.strides + (2, 1) + >>> y.strides + (1, 2) + + >>> x.tobytes('A') + b'\x01\x02\x03\x04' + >>> y.tobytes('A') + b'\x01\x03\x02\x04' + + - the results are different when interpreted as 2 of int16 + - ``.copy()`` creates new arrays in the C order (by default) + +.. note:: **In-place operations with views** + + Prior to NumPy version 1.13, in-place operations with views could result in + **incorrect** results for large arrays. + Since :doc:`version 1.13 `, + NumPy includes checks for *memory overlap* to + guarantee that results are consistent with the non in-place version + (e.g. ``a = a + a.T`` produces the same result as ``a += a.T``). + Note however that this may result in the data being copied (as if using + ``a += a.T.copy()``), ultimately resulting in more memory being used than + might otherwise be expected for in-place operations! + + +Slicing with integers +....................... + +- *Everything* can be represented by changing only ``shape``, ``strides``, + and possibly adjusting the ``data`` pointer! +- Never makes copies of the data + +:: + + >>> x = np.array([1, 2, 3, 4, 5, 6], dtype=np.int32) + >>> y = x[::-1] + >>> y + array([6, 5, 4, 3, 2, 1], dtype=int32) + >>> y.strides + (-4,) + + >>> y = x[2:] + >>> y.__array_interface__['data'][0] - x.__array_interface__['data'][0] + 8 + + >>> x = np.zeros((10, 10, 10), dtype=float) + >>> x.strides + (800, 80, 8) + >>> x[::2,::3,::4].strides + (1600, 240, 32) + +- Similarly, transposes never make copies (it just swaps strides):: + + >>> x = np.zeros((10, 10, 10), dtype=float) + >>> x.strides + (800, 80, 8) + >>> x.T.strides + (8, 80, 800) + +But: not all reshaping operations can be represented by playing with +strides:: + + >>> a = np.arange(6, dtype=np.int8).reshape(3, 2) + >>> b = a.T + >>> b.strides + (1, 2) + +So far, so good. However:: + + >>> bytes(a.data) + b'\x00\x01\x02\x03\x04\x05' + >>> b + array([[0, 2, 4], + [1, 3, 5]], dtype=int8) + >>> c = b.reshape(3*2) + >>> c + array([0, 2, 4, 1, 3, 5], dtype=int8) + +Here, there is no way to represent the array ``c`` given one stride +and the block of memory for ``a``. Therefore, the ``reshape`` +operation needs to make a copy here. + +.. _stride-manipulation-label: + +Example: fake dimensions with strides +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. rubric:: Stride manipulation + +>>> from numpy.lib.stride_tricks import as_strided +>>> help(as_strided) +Help on function as_strided in module numpy.lib.stride_tricks: +... + +.. warning:: + + ``as_strided`` does **not** check that you stay inside the memory + block bounds... + +>>> x = np.array([1, 2, 3, 4], dtype=np.int16) +>>> as_strided(x, strides=(2*2, ), shape=(2, )) +array([1, 3], dtype=int16) +>>> x[::2] +array([1, 3], dtype=int16) + + +.. seealso:: stride-fakedims.py + +**Exercise** + + :: + + array([1, 2, 3, 4], dtype=np.int8) + + -> array([[1, 2, 3, 4], + [1, 2, 3, 4], + [1, 2, 3, 4]], dtype=np.int8) + + using only ``as_strided``.:: + + Hint: byte_offset = stride[0]*index[0] + stride[1]*index[1] + ... + +*Spoiler* + + .. raw:: html + + ... + + + +.. _broadcasting_advanced: + +Broadcasting +^^^^^^^^^^^^ + +- Doing something useful with it: outer product + of ``[1, 2, 3, 4]`` and ``[5, 6, 7]`` + +>>> x = np.array([1, 2, 3, 4], dtype=np.int16) +>>> x2 = as_strided(x, strides=(0, 1*2), shape=(3, 4)) +>>> x2 +array([[1, 2, 3, 4], + [1, 2, 3, 4], + [1, 2, 3, 4]], dtype=int16) + +>>> y = np.array([5, 6, 7], dtype=np.int16) +>>> y2 = as_strided(y, strides=(1*2, 0), shape=(3, 4)) +>>> y2 +array([[5, 5, 5, 5], + [6, 6, 6, 6], + [7, 7, 7, 7]], dtype=int16) + +>>> x2 * y2 +array([[ 5, 10, 15, 20], + [ 6, 12, 18, 24], + [ 7, 14, 21, 28]], dtype=int16) + +.. rubric:: ... seems somehow familiar ... + +>>> x = np.array([1, 2, 3, 4], dtype=np.int16) +>>> y = np.array([5, 6, 7], dtype=np.int16) +>>> x[np.newaxis,:] * y[:,np.newaxis] +array([[ 5, 10, 15, 20], + [ 6, 12, 18, 24], + [ 7, 14, 21, 28]], dtype=int16) + +- Internally, array **broadcasting** is indeed implemented using 0-strides. + + +More tricks: diagonals +^^^^^^^^^^^^^^^^^^^^^^ + +.. seealso:: stride-diagonals.py + +**Challenge** + + * Pick diagonal entries of the matrix: (assume C memory order):: + + >>> x = np.array([[1, 2, 3], + ... [4, 5, 6], + ... [7, 8, 9]], dtype=np.int32) + + >>> x_diag = as_strided(x, shape=(3,), strides=(???,)) # doctest: +SKIP + + * Pick the first super-diagonal entries ``[2, 6]``. + + * And the sub-diagonals? + + (Hint to the last two: slicing first moves the point where striding + starts from.) + +*Solution* + + .. raw:: html + + ... + + +.. seealso:: stride-diagonals.py + +**Challenge** + + Compute the tensor trace:: + + >>> x = np.arange(5*5*5*5).reshape(5, 5, 5, 5) + >>> s = 0 + >>> for i in range(5): + ... for j in range(5): + ... s += x[j, i, j, i] + + by striding, and using ``sum()`` on the result. :: + + >>> y = as_strided(x, shape=(5, 5), strides=(TODO, TODO)) # doctest: +SKIP + >>> s2 = ... # doctest: +SKIP + >>> assert s == s2 # doctest: +SKIP + +*Solution* + + .. raw:: html + + ... + + + +.. _cache_effects: + +CPU cache effects +^^^^^^^^^^^^^^^^^ + +Memory layout can affect performance: + +.. ipython:: + + In [1]: x = np.zeros((20000,)) + + In [2]: y = np.zeros((20000*67,))[::67] + + In [3]: x.shape, y.shape + ((20000,), (20000,)) + + In [4]: %timeit x.sum() + 100000 loops, best of 3: 0.180 ms per loop + + In [5]: %timeit y.sum() + 100000 loops, best of 3: 2.34 ms per loop + + In [6]: x.strides, y.strides + ((8,), (536,)) + + +.. rubric:: Smaller strides are faster? + +.. image:: cpu-cacheline.png + +- CPU pulls data from main memory to its cache in blocks + +- If many array items consecutively operated on fit in a single block (small stride): + + - :math:`\Rightarrow` fewer transfers needed + + - :math:`\Rightarrow` faster + +.. seealso:: + + * `numexpr `_ is designed to mitigate + cache effects when evaluating array expressions. + + * `numba `_ is a compiler for Python code, + that is aware of numpy arrays. + +Findings in dissection +---------------------- + +.. image:: threefundamental.png + +- *memory block*: may be shared, ``.base``, ``.data`` + +- *data type descriptor*: structured data, sub-arrays, byte order, + casting, viewing, ``.astype()``, ``.view()`` + +- *strided indexing*: strides, C/F-order, slicing w/ integers, + ``as_strided``, broadcasting, stride tricks, ``diag``, CPU cache + coherence + + +Universal functions +=================== + +What they are? +-------------- + +- Ufunc performs and elementwise operation on all elements of an array. + + Examples:: + + np.add, np.subtract, scipy.special.*, ... + +- Automatically support: broadcasting, casting, ... + +- The author of an ufunc only has to supply the elementwise operation, + NumPy takes care of the rest. + +- The elementwise operation needs to be implemented in C (or, e.g., Cython) + + +Parts of an Ufunc +^^^^^^^^^^^^^^^^^^ + +1. Provided by user + + .. sourcecode:: c + + void ufunc_loop(void **args, int *dimensions, int *steps, void *data) + { + /* + * int8 output = elementwise_function(int8 input_1, int8 input_2) + * + * This function must compute the ufunc for many values at once, + * in the way shown below. + */ + char *input_1 = (char*)args[0]; + char *input_2 = (char*)args[1]; + char *output = (char*)args[2]; + int i; + + for (i = 0; i < dimensions[0]; ++i) { + *output = elementwise_function(*input_1, *input_2); + input_1 += steps[0]; + input_2 += steps[1]; + output += steps[2]; + } + } + +2. The NumPy part, built by + + .. sourcecode:: c + + char types[3] + + types[0] = NPY_BYTE /* type of first input arg */ + types[1] = NPY_BYTE /* type of second input arg */ + types[2] = NPY_BYTE /* type of third input arg */ + + PyObject *python_ufunc = PyUFunc_FromFuncAndData( + ufunc_loop, + NULL, + types, + 1, /* ntypes */ + 2, /* num_inputs */ + 1, /* num_outputs */ + identity_element, + name, + docstring, + unused) + + - A ufunc can also support multiple different input-output type + combinations. + +Making it easier +^^^^^^^^^^^^^^^^ + +3. ``ufunc_loop`` is of very generic form, and NumPy provides + pre-made ones + + ================ ======================================================= + ``PyUfunc_f_f`` ``float elementwise_func(float input_1)`` + ``PyUfunc_ff_f`` ``float elementwise_func(float input_1, float input_2)`` + ``PyUfunc_d_d`` ``double elementwise_func(double input_1)`` + ``PyUfunc_dd_d`` ``double elementwise_func(double input_1, double input_2)`` + ``PyUfunc_D_D`` ``elementwise_func(npy_cdouble *input, npy_cdouble* output)`` + ``PyUfunc_DD_D`` ``elementwise_func(npy_cdouble *in1, npy_cdouble *in2, npy_cdouble* out)`` + ================ ======================================================= + + * Only ``elementwise_func`` needs to be supplied + + * ... except when your elementwise function is not in one of the above forms + +Exercise: building an ufunc from scratch +---------------------------------------- + +The Mandelbrot fractal is defined by the iteration + +.. math:: + + z \leftarrow z^2 + c + +where :math:`c = x + i y` is a complex number. This iteration is +repeated -- if :math:`z` stays finite no matter how long the iteration +runs, :math:`c` belongs to the Mandelbrot set. + +- Make ufunc called ``mandel(z0, c)`` that computes:: + + z = z0 + for k in range(iterations): + z = z*z + c + + say, 100 iterations or until ``z.real**2 + z.imag**2 > 1000``. + Use it to determine which `c` are in the Mandelbrot set. + +- Our function is a simple one, so make use of the ``PyUFunc_*`` helpers. + +- Write it in Cython + +.. seealso:: mandel.pyx, mandelplot.py + +.. only:: latex + + .. literalinclude:: examples/mandel.pyx + +Reminder: some pre-made Ufunc loops: + +================ ======================================================= +``PyUfunc_f_f`` ``float elementwise_func(float input_1)`` +``PyUfunc_ff_f`` ``float elementwise_func(float input_1, float input_2)`` +``PyUfunc_d_d`` ``double elementwise_func(double input_1)`` +``PyUfunc_dd_d`` ``double elementwise_func(double input_1, double input_2)`` +``PyUfunc_D_D`` ``elementwise_func(complex_double *input, complex_double* output)`` +``PyUfunc_DD_D`` ``elementwise_func(complex_double *in1, complex_double *in2, complex_double* out)`` +================ ======================================================= + +Type codes:: + + NPY_BOOL, NPY_BYTE, NPY_UBYTE, NPY_SHORT, NPY_USHORT, NPY_INT, NPY_UINT, + NPY_LONG, NPY_ULONG, NPY_LONGLONG, NPY_ULONGLONG, NPY_FLOAT, NPY_DOUBLE, + NPY_LONGDOUBLE, NPY_CFLOAT, NPY_CDOUBLE, NPY_CLONGDOUBLE, NPY_DATETIME, + NPY_TIMEDELTA, NPY_OBJECT, NPY_STRING, NPY_UNICODE, NPY_VOID + + +Solution: building an ufunc from scratch +---------------------------------------- + +.. literalinclude:: examples/mandel-answer.pyx + :language: python + +.. literalinclude:: examples/mandelplot.py + :language: python + +.. image:: mandelbrot.png + +.. note:: + + Most of the boilerplate could be automated by these Cython modules: + + https://github.com/cython/cython/wiki/MarkLodato-CreatingUfuncs + +.. rubric:: Several accepted input types + +E.g. supporting both single- and double-precision versions + +.. sourcecode:: cython + + cdef void mandel_single_point(double complex *z_in, + double complex *c_in, + double complex *z_out) nogil: + ... + + cdef void mandel_single_point_singleprec(float complex *z_in, + float complex *c_in, + float complex *z_out) nogil: + ... + + cdef PyUFuncGenericFunction loop_funcs[2] + cdef char input_output_types[3*2] + cdef void *elementwise_funcs[1*2] + + loop_funcs[0] = PyUFunc_DD_D + input_output_types[0] = NPY_CDOUBLE + input_output_types[1] = NPY_CDOUBLE + input_output_types[2] = NPY_CDOUBLE + elementwise_funcs[0] = mandel_single_point + + loop_funcs[1] = PyUFunc_FF_F + input_output_types[3] = NPY_CFLOAT + input_output_types[4] = NPY_CFLOAT + input_output_types[5] = NPY_CFLOAT + elementwise_funcs[1] = mandel_single_point_singleprec + + mandel = PyUFunc_FromFuncAndData( + loop_func, + elementwise_funcs, + input_output_types, + 2, # number of supported input types <---------------- + 2, # number of input args + 1, # number of output args + 0, # `identity` element, never mind this + "mandel", # function name + "mandel(z, c) -> computes iterated z*z + c", # docstring + 0 # unused + ) + + + +Generalized ufuncs +------------------ + +**ufunc** + + ``output = elementwise_function(input)`` + + Both ``output`` and ``input`` can be a single array element only. + +**generalized ufunc** + + ``output`` and ``input`` can be arrays with a fixed number of dimensions + + For example, matrix trace (sum of diag elements):: + + input shape = (n, n) + output shape = () i.e. scalar + + (n, n) -> () + + Matrix product:: + + input_1 shape = (m, n) + input_2 shape = (n, p) + output shape = (m, p) + + (m, n), (n, p) -> (m, p) + + * This is called the *"signature"* of the generalized ufunc + * The dimensions on which the g-ufunc acts, are *"core dimensions"* + +.. rubric:: Status in NumPy + +* g-ufuncs are in NumPy already ... +* new ones can be created with ``PyUFunc_FromFuncAndDataAndSignature`` +* most linear-algebra functions are implemented as g-ufuncs to enable working + with stacked arrays:: + + >>> import numpy as np + >>> rng = np.random.default_rng(27446968) + >>> np.linalg.det(rng.random((3, 5, 5))) + array([ 0.01829761, -0.0077266 , -0.05336566]) + >>> np.linalg._umath_linalg.det.signature + '(m,m)->()' + + * matrix multiplication this way could be useful for operating on + many small matrices at once + + * Also see ``tensordot`` and ``einsum`` + +.. The below gufunc examples were from `np.core.umath_tests`, + which is now deprecated. We need another source of example + gufuncs. See the discussion at: + + https://mail.python.org/archives/list/numpy-discussion@python.org/thread/ZG7AUSPYYUNSPQU3YUZS2XCFD7AT3BJP/ + +.. >>> import numpy.core.umath_tests as ut +.. >>> ut.matrix_multiply.signature +.. '(m,n),(n,p)->(m,p)' +.. +.. >>> x = np.ones((10, 2, 4)) +.. >>> y = np.ones((10, 4, 5)) +.. >>> ut.matrix_multiply(x, y).shape +.. (10, 2, 5) + +.. * in both examples the last two dimensions became *core dimensions*, +.. and are modified as per the *signature* +.. * otherwise, the g-ufunc operates "elementwise" + + +.. rubric:: Generalized ufunc loop + +Matrix multiplication ``(m,n),(n,p) -> (m,p)`` + +.. sourcecode:: c + + void gufunc_loop(void **args, int *dimensions, int *steps, void *data) + { + char *input_1 = (char*)args[0]; /* these are as previously */ + char *input_2 = (char*)args[1]; + char *output = (char*)args[2]; + + int input_1_stride_m = steps[3]; /* strides for the core dimensions */ + int input_1_stride_n = steps[4]; /* are added after the non-core */ + int input_2_strides_n = steps[5]; /* steps */ + int input_2_strides_p = steps[6]; + int output_strides_n = steps[7]; + int output_strides_p = steps[8]; + + int m = dimension[1]; /* core dimensions are added after */ + int n = dimension[2]; /* the main dimension; order as in */ + int p = dimension[3]; /* signature */ + + int i; + + for (i = 0; i < dimensions[0]; ++i) { + matmul_for_strided_matrices(input_1, input_2, output, + strides for each array...); + + input_1 += steps[0]; + input_2 += steps[1]; + output += steps[2]; + } + } + + +Interoperability features +========================= + +Sharing multidimensional, typed data +------------------------------------ + +Suppose you + +1. Write a library than handles (multidimensional) binary data, + +2. Want to make it easy to manipulate the data with NumPy, or whatever + other library, + +3. ... but would **not** like to have NumPy as a dependency. + +Currently, 3 solutions: + +1. the "old" buffer interface + +2. the array interface + +3. the "new" buffer interface (:pep:`3118`) + + +The old buffer protocol +----------------------- + +- Only 1-D buffers +- No data type information +- C-level interface; ``PyBufferProcs tp_as_buffer`` in the type object +- But it's integrated into Python (e.g. strings support it) + +Mini-exercise using `Pillow `_ (Python +Imaging Library): + +.. seealso:: pilbuffer.py + +>>> from PIL import Image +>>> data = np.zeros((200, 200, 4), dtype=np.uint8) +>>> data[:, :] = [255, 0, 0, 255] # Red +>>> # In PIL, RGBA images consist of 32-bit integers whose bytes are [RR,GG,BB,AA] +>>> data = data.view(np.int32).squeeze() +>>> img = Image.frombuffer("RGBA", (200, 200), data, "raw", "RGBA", 0, 1) +>>> img.save('test.png') + +**Q:** + + Check what happens if ``data`` is now modified, and ``img`` saved again. + +The old buffer protocol +----------------------- + +.. literalinclude:: examples/pilbuffer-answer.py + :language: python + +.. image:: test.png + +.. image:: test2.png + + +Array interface protocol +------------------------ + +- Multidimensional buffers +- Data type information present +- NumPy-specific approach; slowly deprecated (but not going away) +- Not integrated in Python otherwise + +.. seealso:: + + Documentation: + https://numpy.org/doc/stable/reference/arrays.interface.html + +:: + + >>> x = np.array([[1, 2], [3, 4]]) + >>> x.__array_interface__ # doctest: +SKIP + {'data': (171694552, False), # memory address of data, is readonly? + 'descr': [('', '>> import matplotlib + >>> matplotlib.use('Agg') + >>> import matplotlib.pyplot as plt + >>> import os + >>> if not os.path.exists('data'): os.mkdir('data') + >>> plt.imsave('data/test.png', data) + + +:: + >>> from PIL import Image + >>> img = Image.open('data/test.png') + >>> img.__array_interface__ + {'version': 3, + 'data': ..., + 'shape': (200, 200, 4), + 'typestr': '|u1'} + >>> x = np.asarray(img) + >>> x.shape + (200, 200, 4) + + +.. note:: + + A more C-friendly variant of the array interface is also defined. + +.. _array_siblings: + +Array siblings: :class:`chararray`, :class:`maskedarray` +======================================================== + +:class:`chararray`: vectorized string operations +-------------------------------------------------- + +>>> x = np.char.asarray(['a', ' bbb', ' ccc']) +>>> x +chararray(['a', ' bbb', ' ccc'], dtype='>> x.upper() +chararray(['A', ' BBB', ' CCC'], dtype='>> x = np.array([1, 2, 3, -99, 5]) + +One way to describe this is to create a masked array:: + + >>> mx = np.ma.masked_array(x, mask=[0, 0, 0, 1, 0]) + >>> mx + masked_array(data=[1, 2, 3, --, 5], + mask=[False, False, False, True, False], + fill_value=999999) + +Masked mean ignores masked data:: + + >>> mx.mean() + np.float64(2.75) + >>> np.mean(mx) + np.float64(2.75) + +.. warning:: Not all NumPy functions respect masks, for instance + ``np.dot``, so check the return types. + +The ``masked_array`` returns a **view** to the original array:: + + >>> mx[1] = 9 + >>> x + array([ 1, 9, 3, -99, 5]) + +The mask +^^^^^^^^ + +You can modify the mask by assigning:: + + >>> mx[1] = np.ma.masked + >>> mx + masked_array(data=[1, --, 3, --, 5], + mask=[False, True, False, True, False], + fill_value=999999) + + +The mask is cleared on assignment:: + + >>> mx[1] = 9 + >>> mx + masked_array(data=[1, 9, 3, --, 5], + mask=[False, False, False, True, False], + fill_value=999999) + + +The mask is also available directly:: + + >>> mx.mask + array([False, False, False, True, False]) + +The masked entries can be filled with a given value to get an usual +array back:: + + >>> x2 = mx.filled(-1) + >>> x2 + array([ 1, 9, 3, -1, 5]) + +The mask can also be cleared:: + + >>> mx.mask = np.ma.nomask + >>> mx + masked_array(data=[1, 9, 3, -99, 5], + mask=[False, False, False, False, False], + fill_value=999999) + + +Domain-aware functions +^^^^^^^^^^^^^^^^^^^^^^ + +The masked array package also contains domain-aware functions:: + + >>> np.ma.log(np.array([1, 2, -1, -2, 3, -5])) + masked_array(data=[0.0, 0.693147180559..., --, --, 1.098612288668..., --], + mask=[False, False, True, True, False, True], + fill_value=1e+20) + + +.. note:: + + Streamlined and more seamless support for dealing with missing data + in arrays is making its way into NumPy 1.7. Stay tuned! + +.. topic:: Example: Masked statistics + + Canadian rangers were distracted when counting hares and lynxes in + 1903-1910 and 1917-1918, and got the numbers are wrong. (Carrot + farmers stayed alert, though.) Compute the mean populations over + time, ignoring the invalid numbers. :: + + >>> data = np.loadtxt('data/populations.txt') + >>> populations = np.ma.masked_array(data[:,1:]) + >>> year = data[:, 0] + + >>> bad_years = (((year >= 1903) & (year <= 1910)) + ... | ((year >= 1917) & (year <= 1918))) + >>> # '&' means 'and' and '|' means 'or' + >>> populations[bad_years, 0] = np.ma.masked + >>> populations[bad_years, 1] = np.ma.masked + + >>> populations.mean(axis=0) + masked_array(data=[40472.72727272727, 18627.272727272728, 42400.0], + mask=[False, False, False], + fill_value=1e+20) + + >>> populations.std(axis=0) + masked_array(data=[21087.656489006717, 15625.799814240254, 3322.5062255844787], + mask=[False, False, False], + fill_value=1e+20) + + + Note that Matplotlib knows about masked arrays:: + + >>> plt.plot(year, populations, 'o-') + [, ...] + +.. image:: auto_examples/images/sphx_glr_plot_maskedstats_001.png + :width: 50% + :target: auto_examples/plot_maskedstats.html + :align: center + + +:class:`recarray`: purely convenience +--------------------------------------- + +>>> arr = np.array([('a', 1), ('b', 2)], dtype=[('x', 'S1'), ('y', int)]) +>>> arr2 = arr.view(np.recarray) +>>> arr2.x +array([b'a', b'b'], dtype='|S1') +>>> arr2.y +array([1, 2]) + + +Summary +======= + +* Anatomy of the ndarray: data, dtype, strides. + +* Universal functions: elementwise operations, how to make new ones + +* Ndarray subclasses + +* Various buffer interfaces for integration with other tools + +* Recent additions: PEP 3118, generalized ufuncs + + +Contributing to NumPy/SciPy +=========================== + + Get this tutorial: https://www.euroscipy.org/talk/882 + +Why +--- + +- "There's a bug?" + +- "I don't understand what this is supposed to do?" + +- "I have this fancy code. Would you like to have it?" + +- "I'd like to help! What can I do?" + +Reporting bugs +-------------- + +- Bug tracker (prefer **this**) + + - https://github.com/numpy/numpy/issues + + - https://github.com/scipy/scipy/issues + + - Click the "Sign up" link to get an account + +- Mailing lists (https://numpy.org/community/) + + - If you're unsure + + - No replies in a week or so? Just file a bug ticket. + + +Good bug report +^^^^^^^^^^^^^^^^ + +:: + + Title: numpy.random.permutations fails for non-integer arguments + + I'm trying to generate random permutations, using numpy.random.permutations + + When calling numpy.random.permutation with non-integer arguments + it fails with a cryptic error message:: + + >>> rng.permutation(12) + array([ 2, 6, 4, 1, 8, 11, 10, 5, 9, 3, 7, 0]) + >>> rng.permutation(12.) #doctest: +SKIP + Traceback (most recent call last): + File "", line 1, in + File "_generator.pyx", line 4844, in numpy.random._generator.Generator.permutation + numpy.exceptions.AxisError: axis 0 is out of bounds for array of dimension 0 + + This also happens with long arguments, and so + np.random.permutation(X.shape[0]) where X is an array fails on 64 + bit windows (where shape is a tuple of longs). + + It would be great if it could cast to integer or at least raise a + proper error for non-integer types. + + I'm using NumPy 1.4.1, built from the official tarball, on Windows + 64 with Visual studio 2008, on Python.org 64-bit Python. + +0. What are you trying to do? + +1. **Small code snippet reproducing the bug** (if possible) + + - What actually happens + + - What you'd expect + +2. Platform (Windows / Linux / OSX, 32/64 bits, x86/PPC, ...) + +3. Version of NumPy/SciPy + + >>> print(np.__version__) + 2... + + **Check that the following is what you expect** + + >>> print(np.__file__) + /... + + In case you have old/broken NumPy installations lying around. + + If unsure, try to remove existing NumPy installations, and reinstall... + +Contributing to documentation +----------------------------- + +1. Documentation editor + + - https://numpy.org/doc/stable/ + + - Registration + + - Register an account + + - Subscribe to ``scipy-dev`` mailing list (subscribers-only) + + - Problem with mailing lists: you get mail + + - But: **you can turn mail delivery off** + + - "change your subscription options", at the bottom of + + https://mail.python.org/mailman3/lists/scipy-dev.python.org/ + + - Send a mail @ ``scipy-dev`` mailing list; ask for activation:: + + To: scipy-dev@scipy.org + + Hi, + + I'd like to edit NumPy/SciPy docstrings. My account is XXXXX + + Cheers, + N. N. + + - Check the style guide: + + - https://numpy.org/doc/stable/ + + - Don't be intimidated; to fix a small thing, just fix it + + - Edit + +2. Edit sources and send patches (as for bugs) + +3. Complain on the mailing list + + +Contributing features +--------------------- + + The contribution of features is documented on https://numpy.org/doc/stable/dev/ + +How to help, in general +----------------------- + +- Bug fixes always welcome! + + - What irks you most + - Browse the tracker + +- Documentation work + + - API docs: improvements to docstrings + + - Know some SciPy module well? + + - *User guide* + + - https://numpy.org/doc/stable/user/ + +- Ask on communication channels: + + - ``numpy-discussion`` list + - ``scipy-dev`` list diff --git a/_sources/advanced/advanced_python/index.rst.txt b/_sources/advanced/advanced_python/index.rst.txt new file mode 100644 index 000000000..7bca59539 --- /dev/null +++ b/_sources/advanced/advanced_python/index.rst.txt @@ -0,0 +1,1133 @@ +.. |==>| unicode:: U+02794 .. thick rightwards arrow + +.. default-role:: py:obj + +========================== +Advanced Python Constructs +========================== + +**Author** *Zbigniew Jędrzejewski-Szmek* + +This section covers some features of the Python language which can +be considered advanced --- in the sense that not every language has +them, and also in the sense that they are more useful in more +complicated programs or libraries, but not in the sense of being +particularly specialized, or particularly complicated. + +It is important to underline that this chapter is purely about the +language itself --- about features supported through special syntax +complemented by functionality of the Python stdlib, which could not be +implemented through clever external modules. + +The process of developing the Python programming language, its syntax, +is very transparent; proposed changes are +evaluated from various angles and discussed via *Python Enhancement +Proposals* --- PEPs_. As a result, features described in this chapter +were added after it was shown that they indeed solve real problems and +that their use is as simple as possible. + +.. _PEPs: https://peps.python.org/ + +.. contents:: Chapter contents + :local: + :depth: 4 + + + +Iterators, generator expressions and generators +=============================================== + +Iterators +^^^^^^^^^ + +.. sidebar:: Simplicity + + Duplication of effort is wasteful, and replacing the various + home-grown approaches with a standard feature usually ends up + making things more readable, and interoperable as well. + + *Guido van Rossum* --- `Adding Optional Static Typing to Python`_ + +.. _`Adding Optional Static Typing to Python`: + https://www.artima.com/weblogs/viewpost.jsp?thread=86641 + + +An iterator is an object adhering to the `iterator protocol`_ +--- basically this means that it has a `next ` method, +which, when called, returns the next item in the sequence, and when +there's nothing to return, raises the +`StopIteration ` exception. + +.. _`iterator protocol`: https://docs.python.org/dev/library/stdtypes.html#iterator-types + +An iterator object allows to loop just once. It +holds the state (position) of a single iteration, or from the other +side, each loop over a sequence requires a single iterator +object. This means that we can iterate over the same sequence more +than once concurrently. Separating the iteration logic from the +sequence allows us to have more than one way of iteration. + +Calling the `__iter__ ` method on a container to +create an iterator object is the most straightforward way to get hold +of an iterator. The `iter` function does that for us, saving a few +keystrokes. :: + + >>> nums = [1, 2, 3] # note that ... varies: these are different objects + >>> iter(nums) + <...iterator object at ...> + >>> nums.__iter__() + <...iterator object at ...> + >>> nums.__reversed__() + <...reverseiterator object at ...> + + >>> it = iter(nums) + >>> next(it) + 1 + >>> next(it) + 2 + >>> next(it) + 3 + >>> next(it) + Traceback (most recent call last): + File "", line 1, in + StopIteration + +When used in a loop, `StopIteration ` is +swallowed and causes the loop to finish. But with explicit invocation, +we can see that once the iterator is exhausted, accessing it raises an +exception. + +Using the :compound:`for..in ` loop also uses the ``__iter__`` +method. This allows us to transparently start the iteration over a +sequence. But if we already have the iterator, we want to be able to +use it in an ``for`` loop in the same way. In order to achieve this, +iterators in addition to ``next`` are also required to have a method +called ``__iter__`` which returns the iterator (``self``). + +Support for iteration is pervasive in Python: +all sequences and unordered containers in the standard library allow +this. The concept is also stretched to other things: +e.g. ``file`` objects support iteration over lines. + + >>> with open("/etc/fstab") as f: # doctest: +SKIP + ... f is f.__iter__() + ... + True + +The ``file`` is an iterator itself and it's ``__iter__`` method +doesn't create a separate object: only a single thread of sequential +access is allowed. + +Generator expressions +^^^^^^^^^^^^^^^^^^^^^ + +A second way in which iterator objects are created is through +**generator expressions**, the basis for **list comprehensions**. To +increase clarity, a generator expression must always be enclosed in +parentheses or an expression. If round parentheses are used, then a +generator iterator is created. If rectangular parentheses are used, +the process is short-circuited and we get a ``list``. :: + + >>> (i for i in nums) + at 0x...> + >>> [i for i in nums] + [1, 2, 3] + >>> list(i for i in nums) + [1, 2, 3] + +The list comprehension syntax also extends to +**dictionary and set comprehensions**. +A ``set`` is created when the generator expression is enclosed in curly +braces. A ``dict`` is created when the generator expression contains +"pairs" of the form ``key:value``:: + + >>> {i for i in range(3)} + {0, 1, 2} + >>> {i:i**2 for i in range(3)} + {0: 0, 1: 1, 2: 4} + +One *gotcha* should be mentioned: in old Pythons the index variable +(``i``) would leak, and in versions >= 3 this is fixed. + +Generators +^^^^^^^^^^ + +.. sidebar:: Generators + + A generator is a function that produces a + sequence of results instead of a single value. + + *David Beazley* --- `A Curious Course on Coroutines and Concurrency`_ + +.. _`A Curious Course on Coroutines and Concurrency`: + https://www.dabeaz.com/coroutines/ + +A third way to create iterator objects is to call a generator function. +A **generator** is a function containing the keyword :simple:`yield`. It must be +noted that the mere presence of this keyword completely changes the +nature of the function: this ``yield`` statement doesn't have to be +invoked, or even reachable, but causes the function to be marked as a +generator. When a normal function is called, the instructions +contained in the body start to be executed. When a generator is +called, the execution stops before the first instruction in the body. +An invocation of a generator function creates a generator object, +adhering to the iterator protocol. As with normal function +invocations, concurrent and recursive invocations are allowed. + +When ``next`` is called, the function is executed until the first ``yield``. +Each encountered ``yield`` statement gives a value becomes the return +value of ``next``. After executing the ``yield`` statement, the +execution of this function is suspended. :: + + >>> def f(): + ... yield 1 + ... yield 2 + >>> f() + + >>> gen = f() + >>> next(gen) + 1 + >>> next(gen) + 2 + >>> next(gen) + Traceback (most recent call last): + File "", line 1, in + StopIteration + +Let's go over the life of the single invocation of the generator +function. :: + + >>> def f(): + ... print("-- start --") + ... yield 3 + ... print("-- finish --") + ... yield 4 + >>> gen = f() + >>> next(gen) + -- start -- + 3 + >>> next(gen) + -- finish -- + 4 + >>> next(gen) + Traceback (most recent call last): + ... + StopIteration + +Contrary to a normal function, where executing ``f()`` would +immediately cause the first ``print`` to be executed, ``gen`` is +assigned without executing any statements in the function body. Only +when ``gen.__next__()`` is invoked by ``next``, the statements up to +the first ``yield`` are executed. The second ``next`` prints +``-- finish --`` and execution halts on the second ``yield``. The third +``next`` falls of the end of the function. +Since no ``yield`` was reached, an exception is raised. + +What happens with the function after a yield, when the control passes +to the caller? The state of each generator is stored in the generator +object. From the point of view of the generator function, is looks +almost as if it was running in a separate thread, but this is just an +illusion: execution is strictly single-threaded, but the interpreter +keeps and restores the state in between the requests for the next value. + +Why are generators useful? As noted in the parts about iterators, a +generator function is just a different way to create an iterator +object. Everything that can be done with ``yield`` statements, could +also be done with ``next`` methods. Nevertheless, using a +function and having the interpreter perform its magic to create an +iterator has advantages. A function can be much shorter +than the definition of a class with the required ``next`` and +``__iter__`` methods. What is more important, it is easier for the author +of the generator to understand the state which is kept in local +variables, as opposed to instance attributes, which have to be +used to pass data between consecutive invocations of ``next`` on +an iterator object. + +A broader question is why are iterators useful? When an iterator is +used to power a loop, the loop becomes very simple. The code to +initialise the state, to decide if the loop is finished, and to find +the next value is extracted into a separate place. This highlights the +body of the loop --- the interesting part. In addition, it is possible +to reuse the iterator code in other places. + +Bidirectional communication +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Each ``yield`` statement causes a value to be passed to the +caller. This is the reason for the introduction of generators +by :pep:`255`. But communication in the +reverse direction is also useful. One obvious way would be some +external state, either a global variable or a shared mutable +object. Direct communication is possible thanks to :pep:`342`. +It is achieved by turning the previously boring +``yield`` statement into an expression. When the generator resumes +execution after a ``yield`` statement, the caller can call a method on +the generator object to either pass a value **into** the generator, +which then is returned by the ``yield`` statement, or a +different method to inject an exception into the generator. + +The first of the new methods is `send(value) `, which +is similar to `next() `, but passes ``value`` into +the generator to be used for the value of the ``yield`` expression. In +fact, ``g.next()`` and ``g.send(None)`` are equivalent. + +The second of the new methods is +`throw(type, value=None, traceback=None) ` +which is equivalent to:: + + raise type, value, traceback + +at the point of the ``yield`` statement. + +Unlike :simple:`raise` (which immediately raises an exception from the +current execution point), ``throw()`` first resumes the generator, and +only then raises the exception. The word throw was picked because +it is suggestive of putting the exception in another location, and is +associated with exceptions in other languages. + +What happens when an exception is raised inside the generator? It can +be either raised explicitly or when executing some statements or it +can be injected at the point of a ``yield`` statement by means of the +``throw()`` method. In either case, such an exception propagates in the +standard manner: it can be intercepted by an ``except`` or ``finally`` +clause, or otherwise it causes the execution of the generator function +to be aborted and propagates in the caller. + +For completeness' sake, it's worth mentioning that generator iterators +also have a `close() ` method, which can be used to +force a generator that would otherwise be able to provide more values +to finish immediately. It allows the generator `__del__ ` +method to destroy objects holding the state of generator. +Let's define a generator which just prints what is passed in through +send and throw. :: + + >>> import itertools + >>> def g(): + ... print('--start--') + ... for i in itertools.count(): + ... print('--yielding %i--' % i) + ... try: + ... ans = yield i + ... except GeneratorExit: + ... print('--closing--') + ... raise + ... except Exception as e: + ... print('--yield raised %r--' % e) + ... else: + ... print('--yield returned %s--' % ans) + + >>> it = g() + >>> next(it) + --start-- + --yielding 0-- + 0 + >>> it.send(11) + --yield returned 11-- + --yielding 1-- + 1 + >>> it.throw(IndexError) + --yield raised IndexError()-- + --yielding 2-- + 2 + >>> it.close() + --closing-- + +Chaining generators +^^^^^^^^^^^^^^^^^^^ + +.. note:: + + This is a preview of :pep:`380` (not yet implemented, but accepted + for Python 3.3). + +Let's say we are writing a generator and we want to yield a number of +values generated by a second generator, a **subgenerator**. +If yielding of values is the only concern, this can be performed +without much difficulty using a loop such as + +.. code-block:: pycon + + subgen = some_other_generator() + for v in subgen: + yield v + +However, if the subgenerator is to interact properly with the caller +in the case of calls to ``send()``, ``throw()`` and ``close()``, +things become considerably more difficult. The ``yield`` statement has +to be guarded by a :compound:`try..except..finally ` structure +similar to the one defined in the previous section to "debug" the +generator function. Such code is provided in :pep:`380#id13`, here it +suffices to say that new syntax to properly yield from a subgenerator +is being introduced in Python 3.3: + +.. code-block:: pycon + + yield from some_other_generator() + +This behaves like the explicit loop above, repeatedly yielding values +from ``some_other_generator`` until it is exhausted, but also forwards +``send``, ``throw`` and ``close`` to the subgenerator. + +Decorators +========== + +.. sidebar:: Summary + + This amazing feature appeared in the language almost apologetically + and with concern that it might not be that useful. + + *Bruce Eckel* --- An Introduction to Python Decorators + +Since functions and classes are objects, they can be passed +around. Since they are mutable objects, they can be modified. The act +of altering a function or class object after it has been constructed +but before is is bound to its name is called decorating. + +There are two things hiding behind the name "decorator" --- one is the +function which does the work of decorating, i.e. performs the real +work, and the other one is the expression adhering to the decorator +syntax, i.e. an at-symbol and the name of the decorating function. + +Function can be decorated by using the decorator syntax for +functions:: + + @decorator # ② + def function(): # ① + pass + +- A function is defined in the standard way. ① +- An expression starting with ``@`` placed before the function + definition is the decorator ②. The part after ``@`` must be a simple + expression, usually this is just the name of a function or class. This + part is evaluated first, and after the function defined below is + ready, the decorator is called with the newly defined function object + as the single argument. The value returned by the decorator is + attached to the original name of the function. + +Decorators can be applied to functions and to classes. For +classes the semantics are identical --- the original class definition +is used as an argument to call the decorator and whatever is returned +is assigned under the original name. + +Before the decorator syntax was implemented (:pep:`318`), it was +possible to achieve the same effect by assigning the function or class +object to a temporary variable and then invoking the decorator +explicitly and then assigning the return value to the name of the +function. This sounds like more typing, and it is, and also the name of +the decorated function doubling as a temporary variable must be used +at least three times, which is prone to errors. Nevertheless, the +example above is equivalent to:: + + def function(): # ① + pass + function = decorator(function) # ② + +Decorators can be stacked --- the order of application is +bottom-to-top, or inside-out. The semantics are such that the originally +defined function is used as an argument for the first decorator, +whatever is returned by the first decorator is used as an argument for +the second decorator, ..., and whatever is returned by the last +decorator is attached under the name of the original function. + +The decorator syntax was chosen for its readability. Since the +decorator is specified before the header of the function, it is +obvious that its is not a part of the function body and its clear that +it can only operate on the whole function. Because the expression is +prefixed with ``@`` is stands out and is hard to miss ("in your face", +according to the PEP :) ). When more than one decorator is applied, +each one is placed on a separate line in an easy to read way. + + +Replacing or tweaking the original object +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Decorators can either return the same function or class object or they +can return a completely different object. In the first case, the +decorator can exploit the fact that function and class objects are +mutable and add attributes, e.g. add a docstring to a class. A +decorator might do something useful even without modifying the object, +for example register the decorated class in a global registry. In the +second case, virtually anything is possible: when something +different is substituted for the original function or class, the new +object can be completely different. Nevertheless, such behaviour is +not the purpose of decorators: they are intended to tweak the +decorated object, not do something unpredictable. Therefore, when a +function is "decorated" by replacing it with a different function, the +new function usually calls the original function, after doing some +preparatory work. Likewise, when a class is "decorated" by replacing +if with a new class, the new class is usually derived from the +original class. When the purpose of the decorator is to do something +"every time", like to log every call to a decorated function, only the +second type of decorators can be used. On the other hand, if the first +type is sufficient, it is better to use it, because it is simpler. + +Decorators implemented as classes and as functions +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The only *requirement* on decorators is that they can be called with a +single argument. This means that decorators can be implemented as +normal functions, or as classes with a `__call__ ` +method, or in theory, even as lambda functions. + +Let's compare the function and class approaches. The decorator +expression (the part after ``@``) can be either just a name, or a +call. The bare-name approach is nice (less to type, looks cleaner, +etc.), but is only possible when no arguments are needed to customise +the decorator. Decorators written as functions can be used in those +two cases:: + + >>> def simple_decorator(function): + ... print("doing decoration") + ... return function + >>> @simple_decorator + ... def function(): + ... print("inside function") + doing decoration + >>> function() + inside function + + >>> def decorator_with_arguments(arg): + ... print("defining the decorator") + ... def _decorator(function): + ... # in this inner function, arg is available too + ... print("doing decoration, %r" % arg) + ... return function + ... return _decorator + >>> @decorator_with_arguments("abc") + ... def function(): + ... print("inside function") + defining the decorator + doing decoration, 'abc' + >>> function() + inside function + +The two trivial decorators above fall into the category of decorators +which return the original function. If they were to return a new +function, an extra level of nestedness would be required. +In the worst case, three levels of nested functions. :: + + >>> def replacing_decorator_with_args(arg): + ... print("defining the decorator") + ... def _decorator(function): + ... # in this inner function, arg is available too + ... print("doing decoration, %r" % arg) + ... def _wrapper(*args, **kwargs): + ... print("inside wrapper, %r %r" % (args, kwargs)) + ... return function(*args, **kwargs) + ... return _wrapper + ... return _decorator + >>> @replacing_decorator_with_args("abc") + ... def function(*args, **kwargs): + ... print("inside function, %r %r" % (args, kwargs)) + ... return 14 + defining the decorator + doing decoration, 'abc' + >>> function(11, 12) + inside wrapper, (11, 12) {} + inside function, (11, 12) {} + 14 + +The ``_wrapper`` function is defined to accept all positional and +keyword arguments. In general we cannot know what arguments the +decorated function is supposed to accept, so the wrapper function +just passes everything to the wrapped function. One unfortunate +consequence is that the apparent argument list is misleading. + +Compared to decorators defined as functions, complex decorators +defined as classes are simpler. When an object is created, the +`__init__ ` method is only allowed to return `None`, +and the type of the created object cannot be changed. This means that +when a decorator is defined as a class, it doesn't make much sense to +use the argument-less form: the final decorated object would just be +an instance of the decorating class, returned by the constructor call, +which is not very useful. Therefore it's enough to discuss class-based +decorators where arguments are given in the decorator expression and +the decorator ``__init__`` method is used for decorator construction. :: + + >>> class decorator_class(object): + ... def __init__(self, arg): + ... # this method is called in the decorator expression + ... print("in decorator init, %s" % arg) + ... self.arg = arg + ... def __call__(self, function): + ... # this method is called to do the job + ... print("in decorator call, %s" % self.arg) + ... return function + >>> deco_instance = decorator_class('foo') + in decorator init, foo + >>> @deco_instance + ... def function(*args, **kwargs): + ... print("in function, %s %s" % (args, kwargs)) + in decorator call, foo + >>> function() + in function, () {} + +Contrary to normal rules (:PEP:`8`) decorators written as classes +behave more like functions and therefore their name often starts with a +lowercase letter. + +In reality, it doesn't make much sense to create a new class just to +have a decorator which returns the original function. Objects are +supposed to hold state, and such decorators are more useful when the +decorator returns a new object. :: + + >>> class replacing_decorator_class(object): + ... def __init__(self, arg): + ... # this method is called in the decorator expression + ... print("in decorator init, %s" % arg) + ... self.arg = arg + ... def __call__(self, function): + ... # this method is called to do the job + ... print("in decorator call, %s" % self.arg) + ... self.function = function + ... return self._wrapper + ... def _wrapper(self, *args, **kwargs): + ... print("in the wrapper, %s %s" % (args, kwargs)) + ... return self.function(*args, **kwargs) + >>> deco_instance = replacing_decorator_class('foo') + in decorator init, foo + >>> @deco_instance + ... def function(*args, **kwargs): + ... print("in function, %s %s" % (args, kwargs)) + in decorator call, foo + >>> function(11, 12) + in the wrapper, (11, 12) {} + in function, (11, 12) {} + +A decorator like this can do pretty much anything, since it can modify +the original function object and mangle the arguments, call the +original function or not, and afterwards mangle the return value. + +Copying the docstring and other attributes of the original function +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +When a new function is returned by the decorator to replace the +original function, an unfortunate consequence is that the original +function name, the original docstring, the original argument list are +lost. Those attributes of the original function can partially be "transplanted" +to the new function by setting ``__doc__`` (the docstring), ``__module__`` +and ``__name__`` (the full name of the function), and +``__annotations__`` (extra information about arguments and the return +value of the function available in Python 3). This can be done +automatically by using `functools.update_wrapper`. + +.. topic:: `functools.update_wrapper(wrapper, wrapped) ` + + "Update a wrapper function to look like the wrapped function." + + :: + + >>> import functools + >>> def replacing_decorator_with_args(arg): + ... print("defining the decorator") + ... def _decorator(function): + ... print("doing decoration, %r" % arg) + ... def _wrapper(*args, **kwargs): + ... print("inside wrapper, %r %r" % (args, kwargs)) + ... return function(*args, **kwargs) + ... return functools.update_wrapper(_wrapper, function) + ... return _decorator + >>> @replacing_decorator_with_args("abc") + ... def function(): + ... "extensive documentation" + ... print("inside function") + ... return 14 + defining the decorator + doing decoration, 'abc' + >>> function + + >>> print(function.__doc__) + extensive documentation + +One important thing is missing from the list of attributes which can +be copied to the replacement function: the argument list. The default +values for arguments can be modified through the ``__defaults__``, +``__kwdefaults__`` attributes, but unfortunately the argument list +itself cannot be set as an attribute. This means that +``help(function)`` will display a useless argument list which will be +confusing for the user of the function. An effective but ugly way +around this problem is to create the wrapper dynamically, using +``eval``. This can be automated by using the external ``decorator`` +module. It provides support for the ``decorator`` decorator, which takes a +wrapper and turns it into a decorator which preserves the function +signature. + +To sum things up, decorators should always use ``functools.update_wrapper`` +or some other means of copying function attributes. + +Examples in the standard library +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +First, it should be mentioned that there's a number of useful +decorators available in the standard library. There are three decorators +which really form a part of the language: + +- `classmethod` causes a method to become a "class method", + which means that it can be invoked without creating an instance of + the class. When a normal method is invoked, the interpreter inserts + the instance object as the first positional parameter, + ``self``. When a class method is invoked, the class itself is given + as the first parameter, often called ``cls``. + + Class methods are still accessible through the class' namespace, so + they don't pollute the module's namespace. Class methods can be used + to provide alternative constructors:: + + class Array(object): + def __init__(self, data): + self.data = data + + @classmethod + def fromfile(cls, file): + data = numpy.load(file) + return cls(data) + + This is cleaner than using a multitude of flags to ``__init__``. + +- `staticmethod` is applied to methods to make them "static", + i.e. basically a normal function, but accessible through the class + namespace. This can be useful when the function is only needed + inside this class (its name would then be prefixed with ``_``), or when we + want the user to think of the method as connected to the class, + despite an implementation which doesn't require this. + +- `property` is the pythonic answer to the problem of getters + and setters. A method decorated with ``property`` becomes a getter + which is automatically called on attribute access. + + >>> class A(object): + ... @property + ... def a(self): + ... "an important attribute" + ... return "a value" + >>> A.a + + >>> A().a + 'a value' + + In this example, ``A.a`` is an read-only attribute. It is also + documented: ``help(A)`` includes the docstring for attribute ``a`` + taken from the getter method. Defining ``a`` as a property allows it + to be a calculated on the fly, and has the side effect of making it + read-only, because no setter is defined. + + To have a setter and a getter, two methods are required, + obviously:: + + class Rectangle(object): + def __init__(self, edge): + self.edge = edge + + @property + def area(self): + """Computed area. + + Setting this updates the edge length to the proper value. + """ + return self.edge**2 + + @area.setter + def area(self, area): + self.edge = area ** 0.5 + + The way that this works, is that the ``property`` decorator replaces + the getter method with a property object. This object in turn has + three methods, ``getter``, ``setter``, and ``deleter``, which can be + used as decorators. Their job is to set the getter, setter and + deleter of the property object (stored as attributes ``fget``, + ``fset``, and ``fdel``). The getter can be set like in the example + above, when creating the object. When defining the setter, we + already have the property object under ``area``, and we add the + setter to it by using the ``setter`` method. All this happens when + we are creating the class. + + Afterwards, when an instance of the class has been created, the + property object is special. When the interpreter executes attribute + access, assignment, or deletion, the job is delegated to the methods + of the property object. + + To make everything crystal clear, let's define a "debug" example:: + + >>> class D(object): + ... @property + ... def a(self): + ... print("getting 1") + ... return 1 + ... @a.setter + ... def a(self, value): + ... print("setting %r" % value) + ... @a.deleter + ... def a(self): + ... print("deleting") + >>> D.a + + >>> D.a.fget + + >>> D.a.fset + + >>> D.a.fdel + + >>> d = D() # ... varies, this is not the same `a` function + >>> d.a + getting 1 + 1 + >>> d.a = 2 + setting 2 + >>> del d.a + deleting + >>> d.a + getting 1 + 1 + + Properties are a bit of a stretch for the decorator syntax. One of the + premises of the decorator syntax --- that the name is not duplicated + --- is violated, but nothing better has been invented so far. It is + just good style to use the same name for the getter, setter, and + deleter methods. + + .. property documentation mentions that this only works for + old-style classes, but this seems to be an error. + +Some newer examples include: + +- `functools.lru_cache` memoizes an arbitrary function + maintaining a limited cache of arguments:answer pairs (Python 3.2) + +- `functools.total_ordering` is a class decorator which fills in + missing ordering methods + (`__lt__ `, `__gt__ `, + `__le__ `, ...) + based on a single available one. + + +.. + - `packaging.pypi.simple.socket_timeout` (in Python 3.3) adds + a socket timeout when retrieving data through a socket. + + +Deprecation of functions +^^^^^^^^^^^^^^^^^^^^^^^^ + +Let's say we want to print a deprecation warning on stderr on the +first invocation of a function we don't like anymore. If we don't want +to modify the function, we can use a decorator:: + + class deprecated(object): + """Print a deprecation warning once on first use of the function. + + >>> @deprecated() # doctest: +SKIP + ... def f(): + ... pass + >>> f() # doctest: +SKIP + f is deprecated + """ + def __call__(self, func): + self.func = func + self.count = 0 + return self._wrapper + def _wrapper(self, *args, **kwargs): + self.count += 1 + if self.count == 1: + print(self.func.__name__, 'is deprecated') + return self.func(*args, **kwargs) + +.. TODO: use update_wrapper here + +It can also be implemented as a function:: + + def deprecated(func): + """Print a deprecation warning once on first use of the function. + + >>> @deprecated # doctest: +SKIP + ... def f(): + ... pass + >>> f() # doctest: +SKIP + f is deprecated + """ + count = [0] + def wrapper(*args, **kwargs): + count[0] += 1 + if count[0] == 1: + print(func.__name__, 'is deprecated') + return func(*args, **kwargs) + return wrapper + +A ``while``-loop removing decorator +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Let's say we have function which returns a lists of things, and this +list created by running a loop. If we don't know how many objects will +be needed, the standard way to do this is something like:: + + def find_answers(): + answers = [] + while True: + ans = look_for_next_answer() + if ans is None: + break + answers.append(ans) + return answers + +This is fine, as long as the body of the loop is fairly compact. Once +it becomes more complicated, as often happens in real code, this +becomes pretty unreadable. We could simplify this by using ``yield`` +statements, but then the user would have to explicitly call +``list(find_answers())``. + +We can define a decorator which constructs the list for us:: + + def vectorized(generator_func): + def wrapper(*args, **kwargs): + return list(generator_func(*args, **kwargs)) + return functools.update_wrapper(wrapper, generator_func) + +Our function then becomes:: + + @vectorized + def find_answers(): + while True: + ans = look_for_next_answer() + if ans is None: + break + yield ans + +A plugin registration system +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +This is a class decorator which doesn't modify the class, but just +puts it in a global registry. It falls into the category of decorators +returning the original object:: + + class WordProcessor(object): + PLUGINS = [] + def process(self, text): + for plugin in self.PLUGINS: + text = plugin().cleanup(text) + return text + + @classmethod + def plugin(cls, plugin): + cls.PLUGINS.append(plugin) + + @WordProcessor.plugin + class CleanMdashesExtension(object): + def cleanup(self, text): + return text.replace('—', u'\N{em dash}') + +Here we use a decorator to decentralise the registration of +plugins. We call our decorator with a noun, instead of a verb, because +we use it to declare that our class is a plugin for +``WordProcessor``. Method ``plugin`` simply appends the class to the +list of plugins. + +A word about the plugin itself: it replaces HTML entity for em-dash +with a real Unicode em-dash character. It exploits the `unicode +literal notation`_ to insert a character by using its name in the +unicode database ("EM DASH"). If the Unicode character was inserted +directly, it would be impossible to distinguish it from an en-dash in +the source of a program. + +.. _`unicode literal notation`: + https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals + +.. seealso:: **More examples and reading** + + * :pep:`318` (function and method decorator syntax) + * :pep:`3129` (class decorator syntax) + * https://wiki.python.org/moin/PythonDecoratorLibrary + * https://docs.python.org/dev/library/functools.html + * https://pypi.org/project/decorator + * Bruce Eckel + + - `Decorators I`_: Introduction to Python Decorators + - `Python Decorators II`_: Decorator Arguments + - `Python Decorators III`_: A Decorator-Based Build System + + .. _`Decorators I`: https://www.artima.com/weblogs/viewpost.jsp?thread=240808 + .. _`Python Decorators II`: https://www.artima.com/weblogs/viewpost.jsp?thread=240845 + .. _`Python Decorators III`: https://www.artima.com/weblogs/viewpost.jsp?thread=241209 + + +Context managers +================ + +A context manager is an object with `__enter__ ` and +`__exit__ ` methods which can be used in the :compound:`with` +statement:: + + with manager as var: + do_something(var) + +is in the simplest case +equivalent to :: + + var = manager.__enter__() + try: + do_something(var) + finally: + manager.__exit__() + +In other words, the context manager protocol defined in :pep:`343` +permits the extraction of the boring part of a +:compound:`try..except..finally ` structure into a separate class +leaving only the interesting ``do_something`` block. + +1. The `__enter__ ` method is called first. It can + return a value which will be assigned to ``var``. + The ``as``-part is optional: if it isn't present, the value + returned by ``__enter__`` is simply ignored. +2. The block of code underneath ``with`` is executed. Just like with + ``try`` clauses, it can either execute successfully to the end, or + it can :simple:`break`, :simple:`continue` or :simple:`return`, or + it can throw an exception. Either way, after the block is finished, + the `__exit__ ` method is called. + If an exception was thrown, the information about the exception is + passed to ``__exit__``, which is described below in the next + subsection. In the normal case, exceptions can be ignored, just + like in a ``finally`` clause, and will be rethrown after + ``__exit__`` is finished. + +Let's say we want to make sure that a file is closed immediately after +we are done writing to it:: + + >>> class closing(object): + ... def __init__(self, obj): + ... self.obj = obj + ... def __enter__(self): + ... return self.obj + ... def __exit__(self, *args): + ... self.obj.close() + >>> with closing(open('/tmp/file', 'w')) as f: + ... f.write('the contents\n') # doctest: +SKIP + +Here we have made sure that the ``f.close()`` is called when the +``with`` block is exited. Since closing files is such a common +operation, the support for this is already present in the ``file`` +class. It has an ``__exit__`` method which calls ``close`` and can be +used as a context manager itself:: + + >>> with open('/tmp/file', 'a') as f: + ... f.write('more contents\n') # doctest: +SKIP + +The common use for ``try..finally`` is releasing resources. Various +different cases are implemented similarly: in the ``__enter__`` +phase the resource is acquired, in the ``__exit__`` phase it is +released, and the exception, if thrown, is propagated. As with files, +there's often a natural operation to perform after the object has been +used and it is most convenient to have the support built in. With each +release, Python provides support in more places: + +* all file-like objects: + + - `file` |==>| automatically closed + - `fileinput`, `tempfile` + - `bz2.BZ2File`, `gzip.GzipFile`, + `tarfile.TarFile`, `zipfile.ZipFile` + - `ftplib`, `nntplib` |==>| close connection +* locks + + - `multiprocessing.RLock` |==>| lock and unlock + - `multiprocessing.Semaphore` + - `memoryview` |==>| automatically release +* `decimal.localcontext` |==>| modify precision of computations temporarily +* `_winreg.PyHKEY <_winreg.OpenKey>` |==>| open and close hive key +* `warnings.catch_warnings` |==>| kill warnings temporarily +* `contextlib.closing` |==>| the same as the example above, call ``close`` +* parallel programming + + - `concurrent.futures.ThreadPoolExecutor` |==>| invoke in parallel then kill thread pool + - `concurrent.futures.ProcessPoolExecutor` |==>| invoke in parallel then kill process pool + - `nogil` |==>| solve the GIL problem temporarily (cython only :( ) + + +Catching exceptions +^^^^^^^^^^^^^^^^^^^ + +When an exception is thrown in the ``with``-block, it is passed as +arguments to ``__exit__``. Three arguments are used, the same as +returned by :py:func:`sys.exc_info`: type, value, traceback. When no +exception is thrown, ``None`` is used for all three arguments. The +context manager can "swallow" the exception by returning a true value +from ``__exit__``. Exceptions can be easily ignored, because if +``__exit__`` doesn't use ``return`` and just falls of the end, +``None`` is returned, a false value, and therefore the exception is +rethrown after ``__exit__`` is finished. + +The ability to catch exceptions opens interesting possibilities. A +classic example comes from unit-tests --- we want to make sure that +some code throws the right kind of exception:: + + class assert_raises(object): + # based on pytest and unittest.TestCase + def __init__(self, type): + self.type = type + def __enter__(self): + pass + def __exit__(self, type, value, traceback): + if type is None: + raise AssertionError('exception expected') + if issubclass(type, self.type): + return True # swallow the expected exception + raise AssertionError('wrong exception type') + + with assert_raises(KeyError): + {}['foo'] + +Using generators to define context managers +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +When discussing generators_, it was said that we prefer generators to +iterators implemented as classes because they are shorter, sweeter, +and the state is stored as local, not instance, variables. On the +other hand, as described in `Bidirectional communication`_, the flow +of data between the generator and its caller can be bidirectional. +This includes exceptions, which can be thrown into the +generator. We would like to implement context managers as special +generator functions. In fact, the generator protocol was designed to +support this use case. + +.. code-block:: pycon + + @contextlib.contextmanager + def some_generator(): + + try: + yield + finally: + + +The `contextlib.contextmanager` helper takes a generator and turns it +into a context manager. The generator has to obey some rules which are +enforced by the wrapper function --- most importantly it must +``yield`` exactly once. The part before the ``yield`` is executed from +``__enter__``, the block of code protected by the context manager is +executed when the generator is suspended in ``yield``, and the rest is +executed in ``__exit__``. If an exception is thrown, the interpreter +hands it to the wrapper through ``__exit__`` arguments, and the +wrapper function then throws it at the point of the ``yield`` +statement. Through the use of generators, the context manager is +shorter and simpler. + +Let's rewrite the ``closing`` example as a generator:: + + @contextlib.contextmanager + def closing(obj): + try: + yield obj + finally: + obj.close() + +Let's rewrite the ``assert_raises`` example as a generator:: + + @contextlib.contextmanager + def assert_raises(type): + try: + yield + except type: + return + except Exception as value: + raise AssertionError('wrong exception type') + else: + raise AssertionError('exception expected') + +Here we use a decorator to turn generator functions into context managers! diff --git a/_sources/advanced/debugging/index.rst.txt b/_sources/advanced/debugging/index.rst.txt new file mode 100644 index 000000000..dde341d8b --- /dev/null +++ b/_sources/advanced/debugging/index.rst.txt @@ -0,0 +1,665 @@ +.. _debugging_chapter: + +============== +Debugging code +============== + +**Author**: *Gaël Varoquaux* + +This section explores tools to understand better your code base: +debugging, to find and fix bugs. + +It is not specific to the scientific Python community, but the strategies +that we will employ are tailored to its needs. + +.. topic:: Prerequisites + + * NumPy + * IPython + * `nosetests `__ + * `pyflakes `__ + * gdb for the C-debugging part. + +.. contents:: Chapter contents + :local: + :depth: 2 + + +Avoiding bugs +============= + +Coding best practices to avoid getting in trouble +-------------------------------------------------- + +.. sidebar:: Brian Kernighan + + *“Everyone knows that debugging is twice as hard as writing a + program in the first place. So if you're as clever as you can be + when you write it, how will you ever debug it?”* + +* We all write buggy code. Accept it. Deal with it. +* Write your code with testing and debugging in mind. +* Keep It Simple, Stupid (KISS). + + * What is the simplest thing that could possibly work? + +* Don't Repeat Yourself (DRY). + + * Every piece of knowledge must have a single, unambiguous, + authoritative representation within a system. + * Constants, algorithms, etc... + +* Try to limit interdependencies of your code. (Loose Coupling) +* Give your variables, functions and modules meaningful names (not + mathematics names) + +pyflakes: fast static analysis +------------------------------- + +They are several static analysis tools in Python; to name a few: + +* `pylint `_ +* `pychecker `_ +* `pyflakes `_ +* `flake8 `_ + +Here we focus on `pyflakes`, which is the simplest tool. + + * **Fast, simple** + + * Detects syntax errors, missing imports, typos on names. + +Another good recommendation is the `flake8` tool which is a combination of +pyflakes and pep8. Thus, in addition to the types of errors that pyflakes +catches, flake8 detects violations of the recommendation in `PEP8 +`_ style guide. + +Integrating pyflakes (or flake8) in your editor or IDE is highly +recommended, it **does yield productivity gains**. + +Running pyflakes on the current edited file +............................................ + +You can bind a key to run pyflakes in the current buffer. + +* **In kate** + Menu: 'settings -> configure kate + + * In plugins enable 'external tools' + + * In external Tools', add `pyflakes`:: + + kdialog --title "pyflakes %filename" --msgbox "$(pyflakes %filename)" + +* **In TextMate** + + Menu: TextMate -> Preferences -> Advanced -> Shell variables, add a + shell variable:: + + TM_PYCHECKER = /Library/Frameworks/Python.framework/Versions/Current/bin/pyflakes + + Then `Ctrl-Shift-V` is binded to a pyflakes report + + +* **In vim** + In your `.vimrc` (binds F5 to `pyflakes`):: + + autocmd FileType python let &mp = 'echo "*** running % ***" ; pyflakes %' + autocmd FileType tex,mp,rst,python imap [15~ :make!^M + autocmd FileType tex,mp,rst,python map [15~ :make!^M + autocmd FileType tex,mp,rst,python set autowrite + +* **In emacs** + In your `.emacs` (binds F5 to `pyflakes`):: + + (defun pyflakes-thisfile () (interactive) + (compile (format "pyflakes %s" (buffer-file-name))) + ) + + (define-minor-mode pyflakes-mode + "Toggle pyflakes mode. + With no argument, this command toggles the mode. + Non-null prefix argument turns on the mode. + Null prefix argument turns off the mode." + ;; The initial value. + nil + ;; The indicator for the mode line. + " Pyflakes" + ;; The minor mode bindings. + '( ([f5] . pyflakes-thisfile) ) + ) + + (add-hook 'python-mode-hook (lambda () (pyflakes-mode t))) + +A type-as-go spell-checker like integration +............................................ + +* **In vim** + + * Use the pyflakes.vim plugin: + + #. download the zip file from + https://www.vim.org/scripts/script.php?script_id=2441 + + #. extract the files in ``~/.vim/ftplugin/python`` + + #. make sure your vimrc has ``filetype plugin indent on`` + + .. image:: vim_pyflakes.png + + * Alternatively: use the `syntastic + `_ + plugin. This can be configured to use ``flake8`` too and also handles + on-the-fly checking for many other languages. + + .. image:: vim_syntastic.png + +* **In emacs** + + Use the flymake mode with pyflakes, documented on + https://www.emacswiki.org/emacs/FlyMake and included in Emacs 26 and + more recent. To activate it, use ``M-x`` (meta-key then x) and enter + `flymake-mode` at the prompt. To enable it automatically when + opening a Python file, add the following line to your .emacs file:: + + (add-hook 'python-mode-hook '(lambda () (flymake-mode))) + + +Debugging workflow +=================== + +If you do have a non trivial bug, this is when debugging strategies kick +in. There is no silver bullet. Yet, strategies help: + + **For debugging a given problem, the favorable situation is when the + problem is isolated in a small number of lines of code, outside + framework or application code, with short modify-run-fail cycles** + +#. Make it fail reliably. Find a test case that makes the code fail + every time. +#. Divide and Conquer. Once you have a failing test case, isolate the + failing code. + + * Which module. + * Which function. + * Which line of code. + + => isolate a small reproducible failure: a test case + +#. Change one thing at a time and re-run the failing test case. +#. Use the debugger to understand what is going wrong. +#. Take notes and be patient. It may take a while. + +.. note:: + + Once you have gone through this process: isolated a tight piece of + code reproducing the bug and fix the bug using this piece of code, add + the corresponding code to your test suite. + +Using the Python debugger +========================= + +The python debugger, ``pdb``: https://docs.python.org/3/library/pdb.html, +allows you to inspect your code interactively. + +Specifically it allows you to: + + * View the source code. + * Walk up and down the call stack. + * Inspect values of variables. + * Modify values of variables. + * Set breakpoints. + +.. topic:: **print** + + Yes, ``print`` statements do work as a debugging tool. However to + inspect runtime, it is often more efficient to use the debugger. + +Invoking the debugger +----------------------- + +Ways to launch the debugger: + +#. Postmortem, launch debugger after module errors. +#. Launch the module with the debugger. +#. Call the debugger inside the module + + +Postmortem +........... + +**Situation**: You're working in IPython and you get a traceback. + +Here we debug the file :download:`index_error.py`. When running it, an +:class:`IndexError` is raised. Type ``%debug`` and drop into the debugger. + +.. code-block:: ipython + + In [1]: %run index_error.py + --------------------------------------------------------------------------- + IndexError Traceback (most recent call last) + File ~/src/scientific-python-lectures/advanced/debugging/index_error.py:10 + 6 print(lst[len(lst)]) + 9 if __name__ == "__main__": + ---> 10 index_error() + + File ~/src/scientific-python-lectures/advanced/debugging/index_error.py:6, in index_error() + 4 def index_error(): + 5 lst = list("foobar") + ----> 6 print(lst[len(lst)]) + + IndexError: list index out of range + + In [2]: %debug + > /home/jarrod/src/scientific-python-lectures/advanced/debugging/index_error.py(6)index_error() + 4 def index_error(): + 5 lst = list("foobar") + ----> 6 print(lst[len(lst)]) + 7 + 8 + + ipdb> list + 1 """Small snippet to raise an IndexError.""" + 2 + 3 + 4 def index_error(): + 5 lst = list("foobar") + ----> 6 print(lst[len(lst)]) + 7 + 8 + 9 if __name__ == "__main__": + 10 index_error() + + ipdb> len(lst) + 6 + ipdb> print(lst[len(lst) - 1]) + r + ipdb> quit + +.. topic:: Post-mortem debugging without IPython + + In some situations you cannot use IPython, for instance to debug a + script that wants to be called from the command line. In this case, + you can call the script with ``python -m pdb script.py``:: + + $ python -m pdb index_error.py + > /home/jarrod/src/scientific-python-lectures/advanced/debugging/index_error.py(1)() + -> """Small snippet to raise an IndexError.""" + (Pdb) continue + Traceback (most recent call last): + File "/usr/lib64/python3.11/pdb.py", line 1793, in main + pdb._run(target) + File "/usr/lib64/python3.11/pdb.py", line 1659, in _run + self.run(target.code) + File "/usr/lib64/python3.11/bdb.py", line 600, in run + exec(cmd, globals, locals) + File "", line 1, in + File "/home/jarrod/src/scientific-python-lectures/advanced/debugging/index_error.py", line 10, in + index_error() + File "/home/jarrod/src/scientific-python-lectures/advanced/debugging/index_error.py", line 6, in index_error + print(lst[len(lst)]) + ~~~^^^^^^^^^^ + IndexError: list index out of range + Uncaught exception. Entering post mortem debugging + Running 'cont' or 'step' will restart the program + > /home/jarrod/src/scientific-python-lectures/advanced/debugging/index_error.py(6)index_error() + -> print(lst[len(lst)]) + (Pdb) + +Step-by-step execution +....................... + +**Situation**: You believe a bug exists in a module but are not sure where. + +For instance we are trying to debug :download:`wiener_filtering.py`. +Indeed the code runs, but the filtering does not work well. + +* Run the script in IPython with the debugger using ``%run -d + wiener_filtering.py`` : + + .. code-block:: ipython + + In [1]: %run -d wiener_filtering.py + *** Blank or comment + *** Blank or comment + *** Blank or comment + NOTE: Enter 'c' at the ipdb> prompt to continue execution. + > /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_filtering.py(1)() + ----> 1 """Wiener filtering a noisy raccoon face: this module is buggy""" + 2 + 3 import numpy as np + 4 import scipy as sp + 5 import matplotlib.pyplot as plt + +* Set a break point at line 29 using ``b 29``: + + .. code-block:: ipython + + ipdb> n + > /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_filtering.py(3)() + 1 """Wiener filtering a noisy raccoon face: this module is buggy""" + 2 + ----> 3 import numpy as np + 4 import scipy as sp + 5 import matplotlib.pyplot as plt + + ipdb> b 29 + Breakpoint 1 at /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_filtering.py:29 + +* Continue execution to next breakpoint with ``c(ont(inue))``: + + .. code-block:: ipython + + ipdb> c + > /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_filtering.py(29)iterated_wiener() + 27 Do not use this: this is crappy code to demo bugs! + 28 """ + 1--> 29 noisy_img = noisy_img + 30 denoised_img = local_mean(noisy_img, size=size) + 31 l_var = local_var(noisy_img, size=size) + +* Step into code with ``n(ext)`` and ``s(tep)``: ``next`` jumps to the next + statement in the current execution context, while ``step`` will go across + execution contexts, i.e. enable exploring inside function calls: + + .. code-block:: ipython + + ipdb> s + > /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_filtering.py(30)iterated_wiener() + 28 """ + 1 29 noisy_img = noisy_img + ---> 30 denoised_img = local_mean(noisy_img, size=size) + 31 l_var = local_var(noisy_img, size=size) + 32 for i in range(3): + + ipdb> n + > /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_filtering.py(31)iterated_wiener() + 1 29 noisy_img = noisy_img + 30 denoised_img = local_mean(noisy_img, size=size) + ---> 31 l_var = local_var(noisy_img, size=size) + 32 for i in range(3): + 33 res = noisy_img - denoised_img + +* Step a few lines and explore the local variables: + + .. code-block:: ipython + + ipdb> n + > /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_filtering.py(32)iterated_wiener() + 30 denoised_img = local_mean(noisy_img, size=size) + 31 l_var = local_var(noisy_img, size=size) + ---> 32 for i in range(3): + 33 res = noisy_img - denoised_img + 34 noise = (res**2).sum() / res.size + + ipdb> print(l_var) + [[2571 2782 3474 ... 3008 2922 3141] + [2105 708 475 ... 469 354 2884] + [1697 420 645 ... 273 236 2517] + ... + [2437 345 432 ... 413 387 4188] + [2598 179 247 ... 367 441 3909] + [2808 2525 3117 ... 4413 4454 4385]] + ipdb> print(l_var.min()) + 0 + +Oh dear, nothing but integers, and 0 variation. Here is our bug, we are +doing integer arithmetic. + +.. topic:: Raising exception on numerical errors + + When we run the :download:`wiener_filtering.py` file, the following + warnings are raised: + + .. code-block:: ipython + + In [2]: %run wiener_filtering.py + /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_filtering.py:35: RuntimeWarning: divide by zero encountered in divide + noise_level = 1 - noise / l_var + + We can turn these warnings in exception, which enables us to do + post-mortem debugging on them, and find our problem more quickly: + + .. code-block:: ipython + + In [3]: np.seterr(all='raise') + Out[3]: {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'} + + In [4]: %run wiener_filtering.py + --------------------------------------------------------------------------- + FloatingPointError Traceback (most recent call last) + File ~/src/scientific-python-lectures/advanced/debugging/wiener_filtering.py:52 + 49 plt.matshow(face[cut], cmap=plt.cm.gray) + 50 plt.matshow(noisy_face[cut], cmap=plt.cm.gray) + ---> 52 denoised_face = iterated_wiener(noisy_face) + 53 plt.matshow(denoised_face[cut], cmap=plt.cm.gray) + 55 plt.show() + + File ~/src/scientific-python-lectures/advanced/debugging/wiener_filtering.py:35, in iterated_wiener(noisy_img, size) + 33 res = noisy_img - denoised_img + 34 noise = (res**2).sum() / res.size + ---> 35 noise_level = 1 - noise / l_var + 36 noise_level[noise_level < 0] = 0 + 37 denoised_img = np.int64(noise_level * res) + + FloatingPointError: divide by zero encountered in divide + + +Other ways of starting a debugger +.................................... + +* **Raising an exception as a poor man break point** + + If you find it tedious to note the line number to set a break point, + you can simply raise an exception at the point that you want to + inspect and use IPython's ``%debug``. Note that in this case you cannot + step or continue the execution. + +* **Debugging test failures using nosetests** + + You can run ``nosetests --pdb`` to drop in post-mortem debugging on + exceptions, and ``nosetests --pdb-failure`` to inspect test failures + using the debugger. + + In addition, you can use the IPython interface for the debugger in nose + by installing the nose plugin + `ipdbplugin `_. You can than + pass ``--ipdb`` and ``--ipdb-failure`` options to nosetests. + +* **Calling the debugger explicitly** + + Insert the following line where you want to drop in the debugger:: + + import pdb; pdb.set_trace() + +.. warning:: + + When running ``nosetests``, the output is captured, and thus it seems + that the debugger does not work. Simply run the nosetests with the ``-s`` + flag. + + +.. topic:: Graphical debuggers and alternatives + + * `pudb `_ is a good semi-graphical + debugger with a text user interface in the console. + + * The `Visual Studio Code `_ integrated + development environment includes a debugging mode. + + * The `Mu editor `_ is a simple Python editor that + includes a debugging mode. + + +Debugger commands and interaction +---------------------------------- + +============ ====================================================================== +``l(list)`` Lists the code at the current position +``u(p)`` Walk up the call stack +``d(own)`` Walk down the call stack +``n(ext)`` Execute the next line (does not go down in new functions) +``s(tep)`` Execute the next statement (goes down in new functions) +``bt`` Print the call stack +``a`` Print the local variables +``!command`` Execute the given **Python** command (by opposition to pdb commands +============ ====================================================================== + +.. warning:: **Debugger commands are not Python code** + + You cannot name the variables the way you want. For instance, if in + you cannot override the variables in the current frame with the same + name: **use different names than your local variable when typing code + in the debugger**. + +Getting help when in the debugger +................................. + +Type ``h`` or ``help`` to access the interactive help: + +.. sourcecode:: pycon + + ipdb> help + + Documented commands (type help ): + ======================================== + EOF commands enable ll pp s until + a condition exceptions longlist psource skip_hidden up + alias cont exit n q skip_predicates w + args context h next quit source whatis + b continue help p r step where + break d ignore pdef restart tbreak + bt debug j pdoc return u + c disable jump pfile retval unalias + cl display l pinfo run undisplay + clear down list pinfo2 rv unt + + Miscellaneous help topics: + ========================== + exec pdb + + Undocumented commands: + ====================== + interact + +Debugging segmentation faults using gdb +========================================== + +If you have a segmentation fault, you cannot debug it with pdb, as it +crashes the Python interpreter before it can drop in the debugger. +Similarly, if you have a bug in C code embedded in Python, pdb is +useless. For this we turn to the gnu debugger, +`gdb `_, available on Linux. + +Before we start with gdb, let us add a few Python-specific tools to it. +For this we add a few macros to our ``~/.gdbinit``. The optimal choice of +macro depends on your Python version and your gdb version. I have added a +simplified version in :download:`gdbinit`, but feel free to read +`DebuggingWithGdb `_. + +To debug with gdb the Python script :download:`segfault.py`, we can run the +script in gdb as follows + +.. sourcecode:: console + + $ gdb python + ... + (gdb) run segfault.py + Starting program: /usr/bin/python segfault.py + [Thread debugging using libthread_db enabled] + + Program received signal SIGSEGV, Segmentation fault. + _strided_byte_copy (dst=0x8537478 "\360\343G", outstrides=4, src= + 0x86c0690
, instrides=32, N=3, + elsize=4) + at numpy/core/src/multiarray/ctors.c:365 + 365 _FAST_MOVE(Int32); + (gdb) + +We get a segfault, and gdb captures it for post-mortem debugging in the C +level stack (not the Python call stack). We can debug the C call stack +using gdb's commands: + +.. sourcecode:: console + + (gdb) up + #1 0x004af4f5 in _copy_from_same_shape (dest=, + src=, myfunc=0x496780 <_strided_byte_copy>, + swap=0) + at numpy/core/src/multiarray/ctors.c:748 + 748 myfunc(dit->dataptr, dest->strides[maxaxis], + +As you can see, right now, we are in the C code of numpy. We would like +to know what is the Python code that triggers this segfault, so we go up +the stack until we hit the Python execution loop: + +.. sourcecode:: console + + (gdb) up + #8 0x080ddd23 in call_function (f= + Frame 0x85371ec, for file /home/varoquau/usr/lib/python2.6/site-packages/numpy/core/arrayprint.py, line 156, in _leading_trailing (a=, _nc=), throwflag=0) + at ../Python/ceval.c:3750 + 3750 ../Python/ceval.c: No such file or directory. + in ../Python/ceval.c + + (gdb) up + #9 PyEval_EvalFrameEx (f= + Frame 0x85371ec, for file /home/varoquau/usr/lib/python2.6/site-packages/numpy/core/arrayprint.py, line 156, in _leading_trailing (a=, _nc=), throwflag=0) + at ../Python/ceval.c:2412 + 2412 in ../Python/ceval.c + (gdb) + +Once we are in the Python execution loop, we can use our special Python +helper function. For instance we can find the corresponding Python code: + +.. sourcecode:: console + + (gdb) pyframe + /home/varoquau/usr/lib/python2.6/site-packages/numpy/core/arrayprint.py (158): _leading_trailing + (gdb) + +This is numpy code, we need to go up until we find code that we have +written: + +.. sourcecode:: console + + (gdb) up + ... + (gdb) up + #34 0x080dc97a in PyEval_EvalFrameEx (f= + Frame 0x82f064c, for file segfault.py, line 11, in print_big_array (small_array=, big_array=), throwflag=0) at ../Python/ceval.c:1630 + 1630 ../Python/ceval.c: No such file or directory. + in ../Python/ceval.c + (gdb) pyframe + segfault.py (12): print_big_array + +The corresponding code is: + +.. literalinclude:: segfault.py + :language: py + :lines: 8-14 + +Thus the segfault happens when printing ``big_array[-10:]``. The reason is +simply that ``big_array`` has been allocated with its end outside the +program memory. + +.. note:: + + For a list of Python-specific commands defined in the `gdbinit`, read + the source of this file. + + +____ + +.. topic:: **Wrap up exercise** + :class: green + + The following script is well documented and hopefully legible. It + seeks to answer a problem of actual interest for numerical computing, + but it does not work... Can you debug it? + + **Python source code:** :download:`to_debug.py ` + + .. only:: html + + .. literalinclude:: to_debug.py diff --git a/_sources/advanced/image_processing/auto_examples/index.rst.txt b/_sources/advanced/image_processing/auto_examples/index.rst.txt new file mode 100644 index 000000000..984cb6c68 --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/index.rst.txt @@ -0,0 +1,475 @@ +:orphan: + +Examples for the image processing chapter +========================================= + + + +.. raw:: html + +
+ +.. thumbnail-parent-div-open + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_face_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_face.py` + +.. raw:: html + +
Displaying a Raccoon Face
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_interpolation_face_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_interpolation_face.py` + +.. raw:: html + +
Image interpolation
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_block_mean_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_block_mean.py` + +.. raw:: html + +
Plot the block mean of an image
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_numpy_array_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_numpy_array.py` + +.. raw:: html + +
Image manipulation and NumPy arrays
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_radial_mean_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_radial_mean.py` + +.. raw:: html + +
Radial mean
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_display_face_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_display_face.py` + +.. raw:: html + +
Display a Raccoon Face
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_sharpen_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_sharpen.py` + +.. raw:: html + +
Image sharpening
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_blur_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_blur.py` + +.. raw:: html + +
Blurring of images
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_synthetic_data_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_synthetic_data.py` + +.. raw:: html + +
Synthetic data
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_propagation_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_propagation.py` + +.. raw:: html + +
Opening, erosion, and propagation
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_face_denoise_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_face_denoise.py` + +.. raw:: html + +
Image denoising
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_geom_face_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_geom_face.py` + +.. raw:: html + +
Geometrical transformations
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_face_tv_denoise_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_face_tv_denoise.py` + +.. raw:: html + +
Total Variation denoising
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_measure_data_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_measure_data.py` + +.. raw:: html + +
Measurements from images
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_find_object_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_find_object.py` + +.. raw:: html + +
Find the bounding box of an object
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_denoising_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_denoising.py` + +.. raw:: html + +
Denoising an image with the median filter
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_histo_segmentation_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_histo_segmentation.py` + +.. raw:: html + +
Histogram segmentation
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_greyscale_dilation_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_greyscale_dilation.py` + +.. raw:: html + +
Greyscale dilation
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_find_edges_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_find_edges.py` + +.. raw:: html + +
Finding edges with Sobel filters
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_clean_morpho_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_clean_morpho.py` + +.. raw:: html + +
Cleaning segmentation with mathematical morphology
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_GMM_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_GMM.py` + +.. raw:: html + +
Segmentation with Gaussian mixture models
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_watershed_segmentation_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_watershed_segmentation.py` + +.. raw:: html + +
Watershed segmentation
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_granulo_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_granulo.py` + +.. raw:: html + +
Granulometry
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/image_processing/auto_examples/images/thumb/sphx_glr_plot_spectral_clustering_thumb.png + :alt: + + :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_spectral_clustering.py` + +.. raw:: html + +
Segmentation with spectral clustering
+
+ + +.. thumbnail-parent-div-close + +.. raw:: html + +
+ + +.. toctree:: + :hidden: + + /advanced/image_processing/auto_examples/plot_face + /advanced/image_processing/auto_examples/plot_interpolation_face + /advanced/image_processing/auto_examples/plot_block_mean + /advanced/image_processing/auto_examples/plot_numpy_array + /advanced/image_processing/auto_examples/plot_radial_mean + /advanced/image_processing/auto_examples/plot_display_face + /advanced/image_processing/auto_examples/plot_sharpen + /advanced/image_processing/auto_examples/plot_blur + /advanced/image_processing/auto_examples/plot_synthetic_data + /advanced/image_processing/auto_examples/plot_propagation + /advanced/image_processing/auto_examples/plot_face_denoise + /advanced/image_processing/auto_examples/plot_geom_face + /advanced/image_processing/auto_examples/plot_face_tv_denoise + /advanced/image_processing/auto_examples/plot_measure_data + /advanced/image_processing/auto_examples/plot_find_object + /advanced/image_processing/auto_examples/plot_denoising + /advanced/image_processing/auto_examples/plot_histo_segmentation + /advanced/image_processing/auto_examples/plot_greyscale_dilation + /advanced/image_processing/auto_examples/plot_find_edges + /advanced/image_processing/auto_examples/plot_clean_morpho + /advanced/image_processing/auto_examples/plot_GMM + /advanced/image_processing/auto_examples/plot_watershed_segmentation + /advanced/image_processing/auto_examples/plot_granulo + /advanced/image_processing/auto_examples/plot_spectral_clustering + + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-gallery + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download all examples in Python source code: auto_examples_python.zip ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download all examples in Jupyter notebooks: auto_examples_jupyter.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_GMM.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_GMM.rst.txt new file mode 100644 index 000000000..0658aa229 --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_GMM.rst.txt @@ -0,0 +1,118 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_GMM.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_GMM.py: + + +Segmentation with Gaussian mixture models +========================================= + +This example performs a Gaussian mixture model analysis of the image +histogram to find the right thresholds for separating foreground from +background. + +.. GENERATED FROM PYTHON SOURCE LINES 10-55 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_GMM_001.png + :alt: plot GMM + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_GMM_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + from sklearn.mixture import GaussianMixture + + rng = np.random.default_rng(27446968) + n = 10 + l = 256 + im = np.zeros((l, l)) + points = l * rng.random((2, n**2)) + im[(points[0]).astype(int), (points[1]).astype(int)] = 1 + im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) + + mask = (im > im.mean()).astype(float) + + + img = mask + 0.3 * rng.normal(size=mask.shape) + + hist, bin_edges = np.histogram(img, bins=60) + bin_centers = 0.5 * (bin_edges[:-1] + bin_edges[1:]) + + classif = GaussianMixture(n_components=2) + classif.fit(img.reshape((img.size, 1))) + + threshold = np.mean(classif.means_) + binary_img = img > threshold + + + plt.figure(figsize=(11, 4)) + + plt.subplot(131) + plt.imshow(img) + plt.axis("off") + plt.subplot(132) + plt.plot(bin_centers, hist, lw=2) + plt.axvline(0.5, color="r", ls="--", lw=2) + plt.text(0.57, 0.8, "histogram", fontsize=20, transform=plt.gca().transAxes) + plt.yticks([]) + plt.subplot(133) + plt.imshow(binary_img, cmap="gray", interpolation="nearest") + plt.axis("off") + + plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.780 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_GMM.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_GMM.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_GMM.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_GMM.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_block_mean.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_block_mean.rst.txt new file mode 100644 index 000000000..6ef2b2450 --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_block_mean.rst.txt @@ -0,0 +1,90 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_block_mean.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_block_mean.py: + + +Plot the block mean of an image +================================ + +An example showing how to use broad-casting to plot the mean of +blocks of an image. + +.. GENERATED FROM PYTHON SOURCE LINES 8-26 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_block_mean_001.png + :alt: plot block mean + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_block_mean_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + f = sp.datasets.face(gray=True) + sx, sy = f.shape + X, Y = np.ogrid[0:sx, 0:sy] + + regions = sy // 6 * (X // 4) + Y // 6 + block_mean = sp.ndimage.mean(f, labels=regions, index=np.arange(1, regions.max() + 1)) + block_mean.shape = (sx // 4, sy // 6) + + plt.figure(figsize=(5, 5)) + plt.imshow(block_mean, cmap="gray") + plt.axis("off") + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.190 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_block_mean.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_block_mean.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_block_mean.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_block_mean.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_blur.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_blur.rst.txt new file mode 100644 index 000000000..23f5985ff --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_blur.rst.txt @@ -0,0 +1,94 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_blur.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_blur.py: + + +Blurring of images +=================== + +An example showing various processes that blur an image. + +.. GENERATED FROM PYTHON SOURCE LINES 7-30 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_blur_001.png + :alt: plot blur + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_blur_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import scipy as sp + import matplotlib.pyplot as plt + + face = sp.datasets.face(gray=True) + blurred_face = sp.ndimage.gaussian_filter(face, sigma=3) + very_blurred = sp.ndimage.gaussian_filter(face, sigma=5) + local_mean = sp.ndimage.uniform_filter(face, size=11) + + plt.figure(figsize=(9, 3)) + plt.subplot(131) + plt.imshow(blurred_face, cmap="gray") + plt.axis("off") + plt.subplot(132) + plt.imshow(very_blurred, cmap="gray") + plt.axis("off") + plt.subplot(133) + plt.imshow(local_mean, cmap="gray") + plt.axis("off") + + plt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.01, right=0.99) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.282 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_blur.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_blur.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_blur.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_blur.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_clean_morpho.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_clean_morpho.rst.txt new file mode 100644 index 000000000..88030a00c --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_clean_morpho.rst.txt @@ -0,0 +1,118 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_clean_morpho.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_clean_morpho.py: + + +Cleaning segmentation with mathematical morphology +=================================================== + +An example showing how to clean segmentation with mathematical +morphology: removing small regions and holes. + +.. GENERATED FROM PYTHON SOURCE LINES 9-55 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_clean_morpho_001.png + :alt: plot clean morpho + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_clean_morpho_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + rng = np.random.default_rng(27446968) + n = 10 + l = 256 + im = np.zeros((l, l)) + points = l * rng.random((2, n**2)) + im[(points[0]).astype(int), (points[1]).astype(int)] = 1 + im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) + + mask = (im > im.mean()).astype(float) + + + img = mask + 0.3 * rng.normal(size=mask.shape) + + binary_img = img > 0.5 + + # Remove small white regions + open_img = sp.ndimage.binary_opening(binary_img) + # Remove small black hole + close_img = sp.ndimage.binary_closing(open_img) + + plt.figure(figsize=(12, 3)) + + l = 128 + + plt.subplot(141) + plt.imshow(binary_img[:l, :l], cmap="gray") + plt.axis("off") + plt.subplot(142) + plt.imshow(open_img[:l, :l], cmap="gray") + plt.axis("off") + plt.subplot(143) + plt.imshow(close_img[:l, :l], cmap="gray") + plt.axis("off") + plt.subplot(144) + plt.imshow(mask[:l, :l], cmap="gray") + plt.contour(close_img[:l, :l], [0.5], linewidths=2, colors="r") + plt.axis("off") + + plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.087 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_clean_morpho.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_clean_morpho.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_clean_morpho.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_clean_morpho.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_denoising.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_denoising.rst.txt new file mode 100644 index 000000000..0186be0b4 --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_denoising.rst.txt @@ -0,0 +1,109 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_denoising.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_denoising.py: + + +Denoising an image with the median filter +========================================== + +This example shows the original image, the noisy image, the denoised +one (with the median filter) and the difference between the two. + +.. GENERATED FROM PYTHON SOURCE LINES 8-45 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_denoising_001.png + :alt: Original image, Noisy image, Median filter, Error + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_denoising_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + rng = np.random.default_rng(27446968) + + im = np.zeros((20, 20)) + im[5:-5, 5:-5] = 1 + im = sp.ndimage.distance_transform_bf(im) + im_noise = im + 0.2 * rng.normal(size=im.shape) + + im_med = sp.ndimage.median_filter(im_noise, 3) + + plt.figure(figsize=(16, 5)) + + plt.subplot(141) + plt.imshow(im, interpolation="nearest") + plt.axis("off") + plt.title("Original image", fontsize=20) + plt.subplot(142) + plt.imshow(im_noise, interpolation="nearest", vmin=0, vmax=5) + plt.axis("off") + plt.title("Noisy image", fontsize=20) + plt.subplot(143) + plt.imshow(im_med, interpolation="nearest", vmin=0, vmax=5) + plt.axis("off") + plt.title("Median filter", fontsize=20) + plt.subplot(144) + plt.imshow(np.abs(im - im_med), cmap="hot", interpolation="nearest") + plt.axis("off") + plt.title("Error", fontsize=20) + + + plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.131 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_denoising.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_denoising.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_denoising.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_denoising.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_display_face.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_display_face.rst.txt new file mode 100644 index 000000000..2dcc4e020 --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_display_face.rst.txt @@ -0,0 +1,93 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_display_face.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_display_face.py: + + +Display a Raccoon Face +====================== + +An example that displays a raccoon face with matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-29 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_display_face_001.png + :alt: plot display face + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_display_face_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import scipy as sp + import matplotlib.pyplot as plt + + f = sp.datasets.face(gray=True) + + plt.figure(figsize=(10, 3.6)) + + plt.subplot(131) + plt.imshow(f, cmap="gray") + + plt.subplot(132) + plt.imshow(f, cmap="gray", vmin=30, vmax=200) + plt.axis("off") + + plt.subplot(133) + plt.imshow(f, cmap="gray") + plt.contour(f, [50, 200]) + plt.axis("off") + + plt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.05, right=0.99) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.341 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_display_face.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_display_face.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_display_face.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_display_face.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_face.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_face.rst.txt new file mode 100644 index 000000000..6193348c5 --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_face.rst.txt @@ -0,0 +1,82 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_face.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_face.py: + + +Displaying a Raccoon Face +========================= + +Small example to plot a raccoon face. + +.. GENERATED FROM PYTHON SOURCE LINES 7-18 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_face_001.png + :alt: plot face + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_face_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import scipy as sp + import imageio.v3 as iio + + f = sp.datasets.face() + iio.imwrite("face.png", f) # uses the Image module (PIL) + + import matplotlib.pyplot as plt + + plt.imshow(f) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.533 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_face.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_face.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_face.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_face.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_face_denoise.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_face_denoise.rst.txt new file mode 100644 index 000000000..3a90f4aad --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_face_denoise.rst.txt @@ -0,0 +1,104 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_face_denoise.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_face_denoise.py: + + +Image denoising +================ + +This example demoes image denoising on a Raccoon face. + +.. GENERATED FROM PYTHON SOURCE LINES 7-40 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_face_denoise_001.png + :alt: noisy, Gaussian filter, Median filter + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_face_denoise_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + rng = np.random.default_rng(27446968) + + f = sp.datasets.face(gray=True) + f = f[230:290, 220:320] + + noisy = f + 0.4 * f.std() * rng.random(f.shape) + + gauss_denoised = sp.ndimage.gaussian_filter(noisy, 2) + med_denoised = sp.ndimage.median_filter(noisy, 3) + + + plt.figure(figsize=(12, 2.8)) + + plt.subplot(131) + plt.imshow(noisy, cmap="gray", vmin=40, vmax=220) + plt.axis("off") + plt.title("noisy", fontsize=20) + plt.subplot(132) + plt.imshow(gauss_denoised, cmap="gray", vmin=40, vmax=220) + plt.axis("off") + plt.title("Gaussian filter", fontsize=20) + plt.subplot(133) + plt.imshow(med_denoised, cmap="gray", vmin=40, vmax=220) + plt.axis("off") + plt.title("Median filter", fontsize=20) + + plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.201 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_face_denoise.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_face_denoise.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_face_denoise.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_face_denoise.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_face_tv_denoise.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_face_tv_denoise.rst.txt new file mode 100644 index 000000000..6b8748a05 --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_face_tv_denoise.rst.txt @@ -0,0 +1,107 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_face_tv_denoise.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_face_tv_denoise.py: + + +Total Variation denoising +=========================== + +This example demoes Total-Variation (TV) denoising on a Raccoon face. + +.. GENERATED FROM PYTHON SOURCE LINES 7-43 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_face_tv_denoise_001.png + :alt: noisy, TV denoising, (more) TV denoising + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_face_tv_denoise_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + from skimage.restoration import denoise_tv_chambolle + + rng = np.random.default_rng(27446968) + + f = sp.datasets.face(gray=True) + f = f[230:290, 220:320] + + noisy = f + 0.4 * f.std() * rng.random(f.shape) + + tv_denoised = denoise_tv_chambolle(noisy, weight=10) + + + plt.figure(figsize=(12, 2.8)) + + plt.subplot(131) + plt.imshow(noisy, cmap="gray", vmin=40, vmax=220) + plt.axis("off") + plt.title("noisy", fontsize=20) + plt.subplot(132) + plt.imshow(tv_denoised, cmap="gray", vmin=40, vmax=220) + plt.axis("off") + plt.title("TV denoising", fontsize=20) + + tv_denoised = denoise_tv_chambolle(noisy, weight=50) + plt.subplot(133) + plt.imshow(tv_denoised, cmap="gray", vmin=40, vmax=220) + plt.axis("off") + plt.title("(more) TV denoising", fontsize=20) + + plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.215 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_face_tv_denoise.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_face_tv_denoise.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_face_tv_denoise.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_face_tv_denoise.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_find_edges.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_find_edges.rst.txt new file mode 100644 index 000000000..f13088984 --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_find_edges.rst.txt @@ -0,0 +1,117 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_find_edges.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_find_edges.py: + + +Finding edges with Sobel filters +================================== + +The Sobel filter is one of the simplest way of finding edges. + +.. GENERATED FROM PYTHON SOURCE LINES 7-53 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_find_edges_001.png + :alt: square, Sobel (x direction), Sobel filter, Sobel for noisy image + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_find_edges_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + rng = np.random.default_rng(27446968) + + im = np.zeros((256, 256)) + im[64:-64, 64:-64] = 1 + + im = sp.ndimage.rotate(im, 15, mode="constant") + im = sp.ndimage.gaussian_filter(im, 8) + + sx = sp.ndimage.sobel(im, axis=0, mode="constant") + sy = sp.ndimage.sobel(im, axis=1, mode="constant") + sob = np.hypot(sx, sy) + + plt.figure(figsize=(16, 5)) + plt.subplot(141) + plt.imshow(im, cmap="gray") + plt.axis("off") + plt.title("square", fontsize=20) + plt.subplot(142) + plt.imshow(sx) + plt.axis("off") + plt.title("Sobel (x direction)", fontsize=20) + plt.subplot(143) + plt.imshow(sob) + plt.axis("off") + plt.title("Sobel filter", fontsize=20) + + im += 0.07 * rng.random(im.shape) + + sx = sp.ndimage.sobel(im, axis=0, mode="constant") + sy = sp.ndimage.sobel(im, axis=1, mode="constant") + sob = np.hypot(sx, sy) + + plt.subplot(144) + plt.imshow(sob) + plt.axis("off") + plt.title("Sobel for noisy image", fontsize=20) + + + plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=0.9) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.203 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_find_edges.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_find_edges.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_find_edges.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_find_edges.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_find_object.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_find_object.rst.txt new file mode 100644 index 000000000..24ab5fe20 --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_find_object.rst.txt @@ -0,0 +1,106 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_find_object.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_find_object.py: + + +Find the bounding box of an object +=================================== + +This example shows how to extract the bounding box of the largest object + +.. GENERATED FROM PYTHON SOURCE LINES 8-43 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_find_object_001.png + :alt: plot find object + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_find_object_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + rng = np.random.default_rng(27446968) + n = 10 + l = 256 + im = np.zeros((l, l)) + points = l * rng.random((2, n**2)) + im[(points[0]).astype(int), (points[1]).astype(int)] = 1 + im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) + + mask = im > im.mean() + + label_im, nb_labels = sp.ndimage.label(mask) + + # Find the largest connected component + sizes = sp.ndimage.sum(mask, label_im, range(nb_labels + 1)) + mask_size = sizes < 1000 + remove_pixel = mask_size[label_im] + label_im[remove_pixel] = 0 + labels = np.unique(label_im) + label_im = np.searchsorted(labels, label_im) + + # Now that we have only one connected component, extract it's bounding box + slice_x, slice_y = sp.ndimage.find_objects(label_im == 4)[0] + roi = im[slice_x, slice_y] + + plt.figure(figsize=(4, 2)) + plt.axes((0, 0, 1, 1)) + plt.imshow(roi) + plt.axis("off") + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.020 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_find_object.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_find_object.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_find_object.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_find_object.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_geom_face.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_geom_face.rst.txt new file mode 100644 index 000000000..50a3a1d94 --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_geom_face.rst.txt @@ -0,0 +1,108 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_geom_face.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_geom_face.py: + + +Geometrical transformations +============================== + +This examples demos some simple geometrical transformations on a Raccoon face. + +.. GENERATED FROM PYTHON SOURCE LINES 7-44 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_geom_face_001.png + :alt: plot geom face + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_geom_face_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + face = sp.datasets.face(gray=True) + lx, ly = face.shape + # Cropping + crop_face = face[lx // 4 : -lx // 4, ly // 4 : -ly // 4] + # up <-> down flip + flip_ud_face = np.flipud(face) + # rotation + rotate_face = sp.ndimage.rotate(face, 45) + rotate_face_noreshape = sp.ndimage.rotate(face, 45, reshape=False) + + plt.figure(figsize=(12.5, 2.5)) + + + plt.subplot(151) + plt.imshow(face, cmap="gray") + plt.axis("off") + plt.subplot(152) + plt.imshow(crop_face, cmap="gray") + plt.axis("off") + plt.subplot(153) + plt.imshow(flip_ud_face, cmap="gray") + plt.axis("off") + plt.subplot(154) + plt.imshow(rotate_face, cmap="gray") + plt.axis("off") + plt.subplot(155) + plt.imshow(rotate_face_noreshape, cmap="gray") + plt.axis("off") + + plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.468 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_geom_face.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_geom_face.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_geom_face.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_geom_face.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_granulo.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_granulo.rst.txt new file mode 100644 index 000000000..ce894cf5f --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_granulo.rst.txt @@ -0,0 +1,123 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_granulo.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_granulo.py: + + +Granulometry +============ + +This example performs a simple granulometry analysis. + +.. GENERATED FROM PYTHON SOURCE LINES 7-59 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_granulo_001.png + :alt: plot granulo + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_granulo_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + + def disk_structure(n): + struct = np.zeros((2 * n + 1, 2 * n + 1)) + x, y = np.indices((2 * n + 1, 2 * n + 1)) + mask = (x - n) ** 2 + (y - n) ** 2 <= n**2 + struct[mask] = 1 + return struct.astype(bool) + + + def granulometry(data, sizes=None): + s = max(data.shape) + if sizes is None: + sizes = range(1, s / 2, 2) + granulo = [ + sp.ndimage.binary_opening(data, structure=disk_structure(n)).sum() + for n in sizes + ] + return granulo + + + rng = np.random.default_rng(27446968) + n = 10 + l = 256 + im = np.zeros((l, l)) + points = l * rng.random((2, n**2)) + im[(points[0]).astype(int), (points[1]).astype(int)] = 1 + im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) + + mask = im > im.mean() + + granulo = granulometry(mask, sizes=np.arange(2, 19, 4)) + + plt.figure(figsize=(6, 2.2)) + + plt.subplot(121) + plt.imshow(mask, cmap="gray") + opened = sp.ndimage.binary_opening(mask, structure=disk_structure(10)) + opened_more = sp.ndimage.binary_opening(mask, structure=disk_structure(14)) + plt.contour(opened, [0.5], colors="b", linewidths=2) + plt.contour(opened_more, [0.5], colors="r", linewidths=2) + plt.axis("off") + plt.subplot(122) + plt.plot(np.arange(2, 19, 4), granulo, "ok", ms=8) + + + plt.subplots_adjust(wspace=0.02, hspace=0.15, top=0.95, bottom=0.15, left=0, right=0.95) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.250 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_granulo.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_granulo.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_granulo.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_granulo.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_greyscale_dilation.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_greyscale_dilation.rst.txt new file mode 100644 index 000000000..9bd7d5f36 --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_greyscale_dilation.rst.txt @@ -0,0 +1,104 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_greyscale_dilation.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_greyscale_dilation.py: + + +Greyscale dilation +==================== + +This example illustrates greyscale mathematical morphology. + +.. GENERATED FROM PYTHON SOURCE LINES 7-40 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_greyscale_dilation_001.png + :alt: plot greyscale dilation + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_greyscale_dilation_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + im = np.zeros((64, 64)) + rng = np.random.default_rng(27446968) + x, y = (63 * rng.random((2, 8))).astype(int) + im[x, y] = np.arange(8) + + bigger_points = sp.ndimage.grey_dilation(im, size=(5, 5), structure=np.ones((5, 5))) + + square = np.zeros((16, 16)) + square[4:-4, 4:-4] = 1 + dist = sp.ndimage.distance_transform_bf(square) + dilate_dist = sp.ndimage.grey_dilation(dist, size=(3, 3), structure=np.ones((3, 3))) + + plt.figure(figsize=(12.5, 3)) + plt.subplot(141) + plt.imshow(im, interpolation="nearest", cmap="nipy_spectral") + plt.axis("off") + plt.subplot(142) + plt.imshow(bigger_points, interpolation="nearest", cmap="nipy_spectral") + plt.axis("off") + plt.subplot(143) + plt.imshow(dist, interpolation="nearest", cmap="nipy_spectral") + plt.axis("off") + plt.subplot(144) + plt.imshow(dilate_dist, interpolation="nearest", cmap="nipy_spectral") + plt.axis("off") + + plt.subplots_adjust(wspace=0, hspace=0.02, top=0.99, bottom=0.01, left=0.01, right=0.99) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.060 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_greyscale_dilation.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_greyscale_dilation.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_greyscale_dilation.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_greyscale_dilation.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_histo_segmentation.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_histo_segmentation.rst.txt new file mode 100644 index 000000000..586c3778c --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_histo_segmentation.rst.txt @@ -0,0 +1,111 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_histo_segmentation.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_histo_segmentation.py: + + +Histogram segmentation +====================== + +This example does simple histogram analysis to perform segmentation. + +.. GENERATED FROM PYTHON SOURCE LINES 7-47 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_histo_segmentation_001.png + :alt: plot histo segmentation + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_histo_segmentation_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + rng = np.random.default_rng(27446968) + n = 10 + l = 256 + im = np.zeros((l, l)) + points = l * rng.random((2, n**2)) + im[(points[0]).astype(int), (points[1]).astype(int)] = 1 + im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) + + mask = (im > im.mean()).astype(float) + + mask += 0.1 * im + + img = mask + 0.2 * rng.normal(size=mask.shape) + + hist, bin_edges = np.histogram(img, bins=60) + bin_centers = 0.5 * (bin_edges[:-1] + bin_edges[1:]) + + binary_img = img > 0.5 + + plt.figure(figsize=(11, 4)) + + plt.subplot(131) + plt.imshow(img) + plt.axis("off") + plt.subplot(132) + plt.plot(bin_centers, hist, lw=2) + plt.axvline(0.5, color="r", ls="--", lw=2) + plt.text(0.57, 0.8, "histogram", fontsize=20, transform=plt.gca().transAxes) + plt.yticks([]) + plt.subplot(133) + plt.imshow(binary_img, cmap="gray", interpolation="nearest") + plt.axis("off") + + plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.110 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_histo_segmentation.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_histo_segmentation.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_histo_segmentation.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_histo_segmentation.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_interpolation_face.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_interpolation_face.rst.txt new file mode 100644 index 000000000..180f28478 --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_interpolation_face.rst.txt @@ -0,0 +1,89 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_interpolation_face.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_interpolation_face.py: + + +Image interpolation +===================== + +The example demonstrates image interpolation on a Raccoon face. + +.. GENERATED FROM PYTHON SOURCE LINES 7-25 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_interpolation_face_001.png + :alt: plot interpolation face + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_interpolation_face_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import scipy as sp + import matplotlib.pyplot as plt + + f = sp.datasets.face(gray=True) + + plt.figure(figsize=(8, 4)) + + plt.subplot(1, 2, 1) + plt.imshow(f[320:340, 510:530], cmap="gray") + plt.axis("off") + + plt.subplot(1, 2, 2) + plt.imshow(f[320:340, 510:530], cmap="gray", interpolation="nearest") + plt.axis("off") + + plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.157 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_interpolation_face.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_interpolation_face.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_interpolation_face.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_interpolation_face.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_measure_data.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_measure_data.rst.txt new file mode 100644 index 000000000..bc4dd5ed7 --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_measure_data.rst.txt @@ -0,0 +1,107 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_measure_data.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_measure_data.py: + + +Measurements from images +========================== + +This examples shows how to measure quantities from various images. + +.. GENERATED FROM PYTHON SOURCE LINES 8-44 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_measure_data_001.png + :alt: plot measure data + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_measure_data_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + rng = np.random.default_rng(27446968) + n = 10 + l = 256 + im = np.zeros((l, l)) + points = l * rng.random((2, n**2)) + im[(points[0]).astype(int), (points[1]).astype(int)] = 1 + im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) + + mask = im > im.mean() + + label_im, nb_labels = sp.ndimage.label(mask) + + sizes = sp.ndimage.sum(mask, label_im, range(nb_labels + 1)) + mask_size = sizes < 1000 + remove_pixel = mask_size[label_im] + label_im[remove_pixel] = 0 + labels = np.unique(label_im) + label_clean = np.searchsorted(labels, label_im) + + + plt.figure(figsize=(6, 3)) + + plt.subplot(121) + plt.imshow(label_im, cmap="nipy_spectral") + plt.axis("off") + plt.subplot(122) + plt.imshow(label_clean, vmax=nb_labels, cmap="nipy_spectral") + plt.axis("off") + + plt.subplots_adjust(wspace=0.01, hspace=0.01, top=1, bottom=0, left=0, right=1) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.044 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_measure_data.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_measure_data.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_measure_data.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_measure_data.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_numpy_array.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_numpy_array.rst.txt new file mode 100644 index 000000000..35cca6948 --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_numpy_array.rst.txt @@ -0,0 +1,93 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_numpy_array.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_numpy_array.py: + + +Image manipulation and NumPy arrays +==================================== + +This example shows how to do image manipulation using common NumPy arrays +tricks. + +.. GENERATED FROM PYTHON SOURCE LINES 9-30 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_numpy_array_001.png + :alt: plot numpy array + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_numpy_array_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + face = sp.datasets.face(gray=True) + face[10:13, 20:23] + face[100:120] = 255 + + lx, ly = face.shape + X, Y = np.ogrid[0:lx, 0:ly] + mask = (X - lx / 2) ** 2 + (Y - ly / 2) ** 2 > lx * ly / 4 + face[mask] = 0 + face[range(400), range(400)] = 255 + + plt.figure(figsize=(3, 3)) + plt.axes((0, 0, 1, 1)) + plt.imshow(face, cmap="gray") + plt.axis("off") + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.162 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_numpy_array.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_numpy_array.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_numpy_array.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_numpy_array.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_propagation.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_propagation.rst.txt new file mode 100644 index 000000000..05456b41c --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_propagation.rst.txt @@ -0,0 +1,100 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_propagation.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_propagation.py: + + +Opening, erosion, and propagation +================================== + +This example shows simple operations of mathematical morphology. + +.. GENERATED FROM PYTHON SOURCE LINES 7-36 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_propagation_001.png + :alt: plot propagation + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_propagation_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + square = np.zeros((32, 32)) + square[10:-10, 10:-10] = 1 + rng = np.random.default_rng(27446968) + x, y = (32 * rng.random((2, 20))).astype(int) + square[x, y] = 1 + + open_square = sp.ndimage.binary_opening(square) + + eroded_square = sp.ndimage.binary_erosion(square) + reconstruction = sp.ndimage.binary_propagation(eroded_square, mask=square) + + plt.figure(figsize=(9.5, 3)) + plt.subplot(131) + plt.imshow(square, cmap="gray", interpolation="nearest") + plt.axis("off") + plt.subplot(132) + plt.imshow(open_square, cmap="gray", interpolation="nearest") + plt.axis("off") + plt.subplot(133) + plt.imshow(reconstruction, cmap="gray", interpolation="nearest") + plt.axis("off") + + plt.subplots_adjust(wspace=0, hspace=0.02, top=0.99, bottom=0.01, left=0.01, right=0.99) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.045 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_propagation.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_propagation.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_propagation.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_propagation.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_radial_mean.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_radial_mean.rst.txt new file mode 100644 index 000000000..5e44b902d --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_radial_mean.rst.txt @@ -0,0 +1,92 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_radial_mean.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_radial_mean.py: + + +Radial mean +============ + +This example shows how to do a radial mean with scikit-image. + +.. GENERATED FROM PYTHON SOURCE LINES 7-28 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_radial_mean_001.png + :alt: plot radial mean + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_radial_mean_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + f = sp.datasets.face(gray=True) + sx, sy = f.shape + X, Y = np.ogrid[0:sx, 0:sy] + + + r = np.hypot(X - sx / 2, Y - sy / 2) + + rbin = (20 * r / r.max()).astype(int) + radial_mean = sp.ndimage.mean(f, labels=rbin, index=np.arange(1, rbin.max() + 1)) + + plt.figure(figsize=(5, 5)) + plt.axes((0, 0, 1, 1)) + plt.imshow(rbin, cmap="nipy_spectral") + plt.axis("off") + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.176 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_radial_mean.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_radial_mean.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_radial_mean.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_radial_mean.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_sharpen.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_sharpen.rst.txt new file mode 100644 index 000000000..6575a6c8f --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_sharpen.rst.txt @@ -0,0 +1,98 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_sharpen.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_sharpen.py: + + +Image sharpening +================= + +This example shows how to sharpen an image in noiseless situation by +applying the filter inverse to the blur. + +.. GENERATED FROM PYTHON SOURCE LINES 8-34 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_sharpen_001.png + :alt: plot sharpen + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_sharpen_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import scipy as sp + import matplotlib.pyplot as plt + + f = sp.datasets.face(gray=True).astype(float) + blurred_f = sp.ndimage.gaussian_filter(f, 3) + + filter_blurred_f = sp.ndimage.gaussian_filter(blurred_f, 1) + + alpha = 30 + sharpened = blurred_f + alpha * (blurred_f - filter_blurred_f) + + plt.figure(figsize=(12, 4)) + + plt.subplot(131) + plt.imshow(f, cmap="gray") + plt.axis("off") + plt.subplot(132) + plt.imshow(blurred_f, cmap="gray") + plt.axis("off") + plt.subplot(133) + plt.imshow(sharpened, cmap="gray") + plt.axis("off") + + plt.tight_layout() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.419 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_sharpen.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_sharpen.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_sharpen.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_sharpen.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_spectral_clustering.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_spectral_clustering.rst.txt new file mode 100644 index 000000000..8d7c341b7 --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_spectral_clustering.rst.txt @@ -0,0 +1,150 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_spectral_clustering.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_spectral_clustering.py: + + +Segmentation with spectral clustering +====================================== + +This example uses spectral clustering to do segmentation. + +.. GENERATED FROM PYTHON SOURCE LINES 7-14 + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + from sklearn.feature_extraction import image + from sklearn.cluster import spectral_clustering + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 15-30 + +.. code-block:: Python + + l = 100 + x, y = np.indices((l, l)) + + center1 = (28, 24) + center2 = (40, 50) + center3 = (67, 58) + center4 = (24, 70) + + radius1, radius2, radius3, radius4 = 16, 14, 15, 14 + + circle1 = (x - center1[0]) ** 2 + (y - center1[1]) ** 2 < radius1**2 + circle2 = (x - center2[0]) ** 2 + (y - center2[1]) ** 2 < radius2**2 + circle3 = (x - center3[0]) ** 2 + (y - center3[1]) ** 2 < radius3**2 + circle4 = (x - center4[0]) ** 2 + (y - center4[1]) ** 2 < radius4**2 + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 31-32 + +4 circles + +.. GENERATED FROM PYTHON SOURCE LINES 32-63 + +.. code-block:: Python + + img = circle1 + circle2 + circle3 + circle4 + mask = img.astype(bool) + img = img.astype(float) + + rng = np.random.default_rng(27446968) + img += 1 + 0.2 * rng.normal(size=img.shape) + + # Convert the image into a graph with the value of the gradient on the + # edges. + graph = image.img_to_graph(img, mask=mask) + + # Take a decreasing function of the gradient: we take it weakly + # dependent from the gradient the segmentation is close to a voronoi + graph.data = np.exp(-graph.data / graph.data.std()) + + # Force the solver to be arpack, since amg is numerically + # unstable on this example + labels = spectral_clustering(graph, n_clusters=4) + label_im = -np.ones(mask.shape) + label_im[mask] = labels + + plt.figure(figsize=(6, 3)) + plt.subplot(121) + plt.imshow(img, cmap="nipy_spectral", interpolation="nearest") + plt.axis("off") + plt.subplot(122) + plt.imshow(label_im, cmap="nipy_spectral", interpolation="nearest") + plt.axis("off") + + plt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.01, right=0.99) + plt.show() + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_spectral_clustering_001.png + :alt: plot spectral clustering + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_spectral_clustering_001.png + :class: sphx-glr-single-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.182 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_spectral_clustering.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_spectral_clustering.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_spectral_clustering.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_spectral_clustering.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_synthetic_data.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_synthetic_data.rst.txt new file mode 100644 index 000000000..0e280c134 --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_synthetic_data.rst.txt @@ -0,0 +1,102 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_synthetic_data.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_synthetic_data.py: + + +Synthetic data +=============== + +The example generates and displays simple synthetic data. + +.. GENERATED FROM PYTHON SOURCE LINES 7-38 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_synthetic_data_001.png + :alt: plot synthetic data + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_synthetic_data_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + rng = np.random.default_rng(27446968) + n = 10 + l = 256 + im = np.zeros((l, l)) + points = l * rng.random((2, n**2)) + im[(points[0]).astype(int), (points[1]).astype(int)] = 1 + im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) + + mask = im > im.mean() + + label_im, nb_labels = sp.ndimage.label(mask) + + plt.figure(figsize=(9, 3)) + + plt.subplot(131) + plt.imshow(im) + plt.axis("off") + plt.subplot(132) + plt.imshow(mask, cmap="gray") + plt.axis("off") + plt.subplot(133) + plt.imshow(label_im, cmap="nipy_spectral") + plt.axis("off") + + plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.081 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_synthetic_data.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_synthetic_data.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_synthetic_data.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_synthetic_data.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/plot_watershed_segmentation.rst.txt b/_sources/advanced/image_processing/auto_examples/plot_watershed_segmentation.rst.txt new file mode 100644 index 000000000..2230aef6f --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/plot_watershed_segmentation.rst.txt @@ -0,0 +1,108 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/image_processing/auto_examples/plot_watershed_segmentation.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_image_processing_auto_examples_plot_watershed_segmentation.py: + + +Watershed segmentation +======================= + +This example shows how to do segmentation with watershed. + +.. GENERATED FROM PYTHON SOURCE LINES 7-44 + + + +.. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_watershed_segmentation_001.png + :alt: plot watershed segmentation + :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_watershed_segmentation_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + from skimage.segmentation import watershed + from skimage.feature import peak_local_max + import matplotlib.pyplot as plt + import scipy as sp + + # Generate an initial image with two overlapping circles + x, y = np.indices((80, 80)) + x1, y1, x2, y2 = 28, 28, 44, 52 + r1, r2 = 16, 20 + mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1**2 + mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2**2 + image = np.logical_or(mask_circle1, mask_circle2) + # Now we want to separate the two objects in image + # Generate the markers as local maxima of the distance + # to the background + distance = sp.ndimage.distance_transform_edt(image) + peak_idx = peak_local_max(distance, footprint=np.ones((3, 3)), labels=image) + peak_mask = np.zeros_like(distance, dtype=bool) + peak_mask[tuple(peak_idx.T)] = True + markers = sp.ndimage.label(peak_mask)[0] + labels = watershed(-distance, markers, mask=image) + + plt.figure(figsize=(9, 3.5)) + plt.subplot(131) + plt.imshow(image, cmap="gray", interpolation="nearest") + plt.axis("off") + plt.subplot(132) + plt.imshow(-distance, interpolation="nearest") + plt.axis("off") + plt.subplot(133) + plt.imshow(labels, cmap="nipy_spectral", interpolation="nearest") + plt.axis("off") + + plt.subplots_adjust(hspace=0.01, wspace=0.01, top=1, bottom=0, left=0, right=1) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.064 seconds) + + +.. _sphx_glr_download_advanced_image_processing_auto_examples_plot_watershed_segmentation.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_watershed_segmentation.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_watershed_segmentation.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_watershed_segmentation.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/image_processing/auto_examples/sg_execution_times.rst.txt b/_sources/advanced/image_processing/auto_examples/sg_execution_times.rst.txt new file mode 100644 index 000000000..5d1553f69 --- /dev/null +++ b/_sources/advanced/image_processing/auto_examples/sg_execution_times.rst.txt @@ -0,0 +1,106 @@ + +:orphan: + +.. _sphx_glr_advanced_image_processing_auto_examples_sg_execution_times: + + +Computation times +================= +**00:05.201** total execution time for 24 files **from advanced/image_processing/auto_examples**: + +.. container:: + + .. raw:: html + + + + + + + + .. list-table:: + :header-rows: 1 + :class: table table-striped sg-datatable + + * - Example + - Time + - Mem (MB) + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_GMM.py` (``plot_GMM.py``) + - 00:00.780 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_face.py` (``plot_face.py``) + - 00:00.533 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_geom_face.py` (``plot_geom_face.py``) + - 00:00.468 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_sharpen.py` (``plot_sharpen.py``) + - 00:00.419 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_display_face.py` (``plot_display_face.py``) + - 00:00.341 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_blur.py` (``plot_blur.py``) + - 00:00.282 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_granulo.py` (``plot_granulo.py``) + - 00:00.250 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_face_tv_denoise.py` (``plot_face_tv_denoise.py``) + - 00:00.215 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_find_edges.py` (``plot_find_edges.py``) + - 00:00.203 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_face_denoise.py` (``plot_face_denoise.py``) + - 00:00.201 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_block_mean.py` (``plot_block_mean.py``) + - 00:00.190 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_spectral_clustering.py` (``plot_spectral_clustering.py``) + - 00:00.182 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_radial_mean.py` (``plot_radial_mean.py``) + - 00:00.176 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_numpy_array.py` (``plot_numpy_array.py``) + - 00:00.162 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_interpolation_face.py` (``plot_interpolation_face.py``) + - 00:00.157 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_denoising.py` (``plot_denoising.py``) + - 00:00.131 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_histo_segmentation.py` (``plot_histo_segmentation.py``) + - 00:00.110 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_clean_morpho.py` (``plot_clean_morpho.py``) + - 00:00.087 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_synthetic_data.py` (``plot_synthetic_data.py``) + - 00:00.081 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_watershed_segmentation.py` (``plot_watershed_segmentation.py``) + - 00:00.064 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_greyscale_dilation.py` (``plot_greyscale_dilation.py``) + - 00:00.060 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_propagation.py` (``plot_propagation.py``) + - 00:00.045 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_measure_data.py` (``plot_measure_data.py``) + - 00:00.044 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_find_object.py` (``plot_find_object.py``) + - 00:00.020 + - 0.0 diff --git a/_sources/advanced/image_processing/index.rst.txt b/_sources/advanced/image_processing/index.rst.txt new file mode 100644 index 000000000..25afce1bf --- /dev/null +++ b/_sources/advanced/image_processing/index.rst.txt @@ -0,0 +1,909 @@ +.. for doctests + >>> import numpy as np + >>> import matplotlib.pyplot as plt + + +.. _basic_image: + +======================================================= +Image manipulation and processing using NumPy and SciPy +======================================================= + +**Authors**: *Emmanuelle Gouillart, Gaël Varoquaux* + + +This section addresses basic image manipulation and processing using the +core scientific modules NumPy and SciPy. Some of the operations covered +by this tutorial may be useful for other kinds of multidimensional array +processing than image processing. In particular, the submodule +:mod:`scipy.ndimage` provides functions operating on n-dimensional NumPy +arrays. + +.. seealso:: + + For more advanced image processing and image-specific routines, see the + tutorial :ref:`scikit_image`, dedicated to the :mod:`skimage` module. + +.. topic:: + Image = 2-D numerical array + + (or 3-D: CT, MRI, 2D + time; 4-D, ...) + + Here, **image == NumPy array** ``np.array`` + +**Tools used in this tutorial**: + +* ``numpy``: basic array manipulation + +* ``scipy``: ``scipy.ndimage`` submodule dedicated to image processing + (n-dimensional images). See the `documentation + `_:: + + >>> import scipy as sp + + +**Common tasks in image processing**: + +* Input/Output, displaying images + +* Basic manipulations: cropping, flipping, rotating, ... + +* Image filtering: denoising, sharpening + +* Image segmentation: labeling pixels corresponding to different objects + +* Classification + +* Feature extraction + +* Registration + +* ... + + +.. contents:: Chapters contents + :local: + :depth: 4 + + + +Opening and writing to image files +================================== + +Writing an array to a file: + +.. literalinclude:: examples/plot_face.py + :lines: 8- + +.. image:: examples/face.png + :align: center + :scale: 50 + +Creating a NumPy array from an image file:: + + >>> import imageio.v3 as iio + >>> face = sp.datasets.face() + >>> iio.imwrite('face.png', face) # First we need to create the PNG file + + >>> face = iio.imread('face.png') + >>> type(face) + + >>> face.shape, face.dtype + ((768, 1024, 3), dtype('uint8')) + +dtype is uint8 for 8-bit images (0-255) + +Opening raw files (camera, 3-D images) :: + + >>> face.tofile('face.raw') # Create raw file + >>> face_from_raw = np.fromfile('face.raw', dtype=np.uint8) + >>> face_from_raw.shape + (2359296,) + >>> face_from_raw.shape = (768, 1024, 3) + +Need to know the shape and dtype of the image (how to separate data +bytes). + +For large data, use ``np.memmap`` for memory mapping:: + + >>> face_memmap = np.memmap('face.raw', dtype=np.uint8, shape=(768, 1024, 3)) + +(data are read from the file, and not loaded into memory) + +Working on a list of image files :: + + >>> rng = np.random.default_rng(27446968) + >>> for i in range(10): + ... im = rng.integers(0, 256, 10000, dtype=np.uint8).reshape((100, 100)) + ... iio.imwrite(f'random_{i:02d}.png', im) + >>> from glob import glob + >>> filelist = glob('random*.png') + >>> filelist.sort() + +Displaying images +================= + +Use ``matplotlib`` and ``imshow`` to display an image inside a +``matplotlib figure``:: + + >>> f = sp.datasets.face(gray=True) # retrieve a grayscale image + >>> import matplotlib.pyplot as plt + >>> plt.imshow(f, cmap=plt.cm.gray) + + +Increase contrast by setting min and max values:: + + >>> plt.imshow(f, cmap=plt.cm.gray, vmin=30, vmax=200) + + >>> # Remove axes and ticks + >>> plt.axis('off') + (np.float64(-0.5), np.float64(1023.5), np.float64(767.5), np.float64(-0.5)) + +Draw contour lines:: + + >>> plt.contour(f, [50, 200]) + + + +.. figure:: auto_examples/images/sphx_glr_plot_display_face_001.png + :scale: 80 + :target: auto_examples/plot_display_face.html + +.. only:: html + + [:ref:`Python source code `] + +For smooth intensity variations, use ``interpolation='bilinear'``. For fine inspection of intensity variations, use +``interpolation='nearest'``:: + + >>> plt.imshow(f[320:340, 510:530], cmap=plt.cm.gray, interpolation='bilinear') + + >>> plt.imshow(f[320:340, 510:530], cmap=plt.cm.gray, interpolation='nearest') + + +.. figure:: auto_examples/images/sphx_glr_plot_interpolation_face_001.png + :scale: 80 + :target: auto_examples/plot_interpolation_face.html + +.. only:: html + + [:ref:`Python source code `] + + +.. seealso:: + + More interpolation methods are in `Matplotlib's examples `_. + + + + +Basic manipulations +=================== + +Images are arrays: use the whole ``numpy`` machinery. + +.. image:: axis_convention.png + :align: center + :scale: 65 + +:: + + >>> face = sp.datasets.face(gray=True) + >>> face[0, 40] + np.uint8(127) + >>> # Slicing + >>> face[10:13, 20:23] + array([[141, 153, 145], + [133, 134, 125], + [ 96, 92, 94]], dtype=uint8) + >>> face[100:120] = 255 + >>> + >>> lx, ly = face.shape + >>> X, Y = np.ogrid[0:lx, 0:ly] + >>> mask = (X - lx / 2) ** 2 + (Y - ly / 2) ** 2 > lx * ly / 4 + >>> # Masks + >>> face[mask] = 0 + >>> # Fancy indexing + >>> face[range(400), range(400)] = 255 + +.. figure:: auto_examples/images/sphx_glr_plot_numpy_array_001.png + :scale: 100 + :target: auto_examples/plot_numpy_array.html + +.. only:: html + + [:ref:`Python source code `] + + +Statistical information +----------------------- + +:: + + >>> face = sp.datasets.face(gray=True) + >>> face.mean() + np.float64(113.48026784261067) + >>> face.max(), face.min() + (np.uint8(250), np.uint8(0)) + + +``np.histogram`` + +.. topic:: **Exercise** + :class: green + + + * Open as an array the ``scikit-image`` logo + (https://scikit-image.org/_static/img/logo.png), or an + image that you have on your computer. + + * Crop a meaningful part of the image, for example the python circle + in the logo. + + * Display the image array using ``matplotlib``. Change the + interpolation method and zoom to see the difference. + + * Transform your image to greyscale + + * Increase the contrast of the image by changing its minimum and + maximum values. **Optional**: use ``scipy.stats.scoreatpercentile`` + (read the docstring!) to saturate 5% of the darkest pixels and 5% + of the lightest pixels. + + * Save the array to two different file formats (png, jpg, tiff) + + .. image:: scikit_image_logo.png + :align: center + + +Geometrical transformations +--------------------------- +:: + + >>> face = sp.datasets.face(gray=True) + >>> lx, ly = face.shape + >>> # Cropping + >>> crop_face = face[lx // 4: - lx // 4, ly // 4: - ly // 4] + >>> # up <-> down flip + >>> flip_ud_face = np.flipud(face) + >>> # rotation + >>> rotate_face = sp.ndimage.rotate(face, 45) + >>> rotate_face_noreshape = sp.ndimage.rotate(face, 45, reshape=False) + +.. figure:: auto_examples/images/sphx_glr_plot_geom_face_001.png + :scale: 65 + :target: auto_examples/plot_geom_face.html + +.. only:: html + + [:ref:`Python source code `] + +Image filtering +=============== + +**Local filters**: replace the value of pixels by a function of the values of +neighboring pixels. + +Neighbourhood: square (choose size), disk, or more complicated *structuring +element*. + +.. figure:: kernels.png + :align: center + :scale: 90 + +Blurring/smoothing +------------------ + +**Gaussian filter** from ``scipy.ndimage``:: + + >>> face = sp.datasets.face(gray=True) + >>> blurred_face = sp.ndimage.gaussian_filter(face, sigma=3) + >>> very_blurred = sp.ndimage.gaussian_filter(face, sigma=5) + +**Uniform filter** :: + + >>> local_mean = sp.ndimage.uniform_filter(face, size=11) + +.. figure:: auto_examples/images/sphx_glr_plot_blur_001.png + :scale: 90 + :target: auto_examples/plot_blur.html + +.. only:: html + + [:ref:`Python source code `] + +Sharpening +---------- + +Sharpen a blurred image:: + + >>> face = sp.datasets.face(gray=True).astype(float) + >>> blurred_f = sp.ndimage.gaussian_filter(face, 3) + +increase the weight of edges by adding an approximation of the +Laplacian:: + + >>> filter_blurred_f = sp.ndimage.gaussian_filter(blurred_f, 1) + >>> alpha = 30 + >>> sharpened = blurred_f + alpha * (blurred_f - filter_blurred_f) + +.. figure:: auto_examples/images/sphx_glr_plot_sharpen_001.png + :scale: 65 + :target: auto_examples/plot_sharpen.html + +.. only:: html + + [:ref:`Python source code `] + + +Denoising +--------- + +Noisy face:: + + >>> f = sp.datasets.face(gray=True) + >>> f = f[230:290, 220:320] + >>> rng = np.random.default_rng() + >>> noisy = f + 0.4 * f.std() * rng.random(f.shape) + +A **Gaussian filter** smoothes the noise out... and the edges as well:: + + >>> gauss_denoised = sp.ndimage.gaussian_filter(noisy, 2) + +Most local linear isotropic filters blur the image (``scipy.ndimage.uniform_filter``) + +A **median filter** preserves better the edges:: + + >>> med_denoised = sp.ndimage.median_filter(noisy, 3) + +.. figure:: auto_examples/images/sphx_glr_plot_face_denoise_001.png + :scale: 60 + :target: auto_examples/plot_face_denoise.html + +.. only:: html + + [:ref:`Python source code `] + + +Median filter: better result for straight boundaries (**low curvature**):: + + >>> im = np.zeros((20, 20)) + >>> im[5:-5, 5:-5] = 1 + >>> im = sp.ndimage.distance_transform_bf(im) + >>> rng = np.random.default_rng() + >>> im_noise = im + 0.2 * rng.standard_normal(im.shape) + >>> im_med = sp.ndimage.median_filter(im_noise, 3) + +.. figure:: auto_examples/images/sphx_glr_plot_denoising_001.png + :scale: 50 + :target: auto_examples/plot_denoising.html + +.. only:: html + + [:ref:`Python source code `] + + +Other rank filter: ``scipy.ndimage.maximum_filter``, +``scipy.ndimage.percentile_filter`` + +Other local non-linear filters: Wiener (``scipy.signal.wiener``), etc. + +**Non-local filters** + +.. topic:: **Exercise: denoising** + :class: green + + * Create a binary image (of 0s and 1s) with several objects (circles, + ellipses, squares, or random shapes). + + * Add some noise (e.g., 20% of noise) + + * Try two different denoising methods for denoising the image: + gaussian filtering and median filtering. + + * Compare the histograms of the two different denoised images. + Which one is the closest to the histogram of the original (noise-free) + image? + +.. seealso:: + + More denoising filters are available in :mod:`skimage.denoising`, + see the :ref:`scikit_image` tutorial. + + + +Mathematical morphology +----------------------- + +See `wikipedia `_ +for a definition of mathematical morphology. + +Probe an image with a simple shape (a **structuring element**), and +modify this image according to how the shape locally fits or misses the +image. + +**Structuring element**:: + + >>> el = sp.ndimage.generate_binary_structure(2, 1) + >>> el + array([[False, True, False], + [ True, True, True], + [False, True, False]]) + >>> el.astype(int) + array([[0, 1, 0], + [1, 1, 1], + [0, 1, 0]]) + +.. figure:: diamond_kernel.png + :align: center + +**Erosion** = minimum filter. Replace the value of a pixel by the minimal value covered by the structuring element.:: + + >>> a = np.zeros((7,7), dtype=int) + >>> a[1:6, 2:5] = 1 + >>> a + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> sp.ndimage.binary_erosion(a).astype(a.dtype) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> # Erosion removes objects smaller than the structure + >>> sp.ndimage.binary_erosion(a, structure=np.ones((5,5))).astype(a.dtype) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + + +.. image:: morpho_mat.png + :align: center + + +**Dilation**: maximum filter:: + + >>> a = np.zeros((5, 5)) + >>> a[2, 2] = 1 + >>> a + array([[0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0.], + [0., 0., 1., 0., 0.], + [0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0.]]) + >>> sp.ndimage.binary_dilation(a).astype(a.dtype) + array([[0., 0., 0., 0., 0.], + [0., 0., 1., 0., 0.], + [0., 1., 1., 1., 0.], + [0., 0., 1., 0., 0.], + [0., 0., 0., 0., 0.]]) + + +Also works for grey-valued images:: + + >>> rng = np.random.default_rng(27446968) + >>> im = np.zeros((64, 64)) + >>> x, y = (63*rng.random((2, 8))).astype(int) + >>> im[x, y] = np.arange(8) + + >>> bigger_points = sp.ndimage.grey_dilation(im, size=(5, 5), structure=np.ones((5, 5))) + + >>> square = np.zeros((16, 16)) + >>> square[4:-4, 4:-4] = 1 + >>> dist = sp.ndimage.distance_transform_bf(square) + >>> dilate_dist = sp.ndimage.grey_dilation(dist, size=(3, 3), \ + ... structure=np.ones((3, 3))) + + +.. figure:: auto_examples/images/sphx_glr_plot_greyscale_dilation_001.png + :scale: 40 + :target: auto_examples/plot_greyscale_dilation.html + +.. only:: html + + [:ref:`Python source code `] + +**Opening**: erosion + dilation:: + + >>> a = np.zeros((5,5), dtype=int) + >>> a[1:4, 1:4] = 1; a[4, 4] = 1 + >>> a + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 1]]) + >>> # Opening removes small objects + >>> sp.ndimage.binary_opening(a, structure=np.ones((3,3))).astype(int) + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]]) + >>> # Opening can also smooth corners + >>> sp.ndimage.binary_opening(a).astype(int) + array([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 1, 1, 1, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]]) + +**Application**: remove noise:: + + >>> square = np.zeros((32, 32)) + >>> square[10:-10, 10:-10] = 1 + >>> rng = np.random.default_rng(27446968) + >>> x, y = (32*rng.random((2, 20))).astype(int) + >>> square[x, y] = 1 + + >>> open_square = sp.ndimage.binary_opening(square) + + >>> eroded_square = sp.ndimage.binary_erosion(square) + >>> reconstruction = sp.ndimage.binary_propagation(eroded_square, mask=square) + +.. figure:: auto_examples/images/sphx_glr_plot_propagation_001.png + :scale: 40 + :target: auto_examples/plot_propagation.html + +.. only:: html + + [:ref:`Python source code `] + +**Closing**: dilation + erosion + +Many other mathematical morphology operations: hit and miss transform, tophat, +etc. + +Feature extraction +================== + +Edge detection +-------------- + +Synthetic data:: + + >>> im = np.zeros((256, 256)) + >>> im[64:-64, 64:-64] = 1 + >>> + >>> im = sp.ndimage.rotate(im, 15, mode='constant') + >>> im = sp.ndimage.gaussian_filter(im, 8) + +Use a **gradient operator** (**Sobel**) to find high intensity variations:: + + >>> sx = sp.ndimage.sobel(im, axis=0, mode='constant') + >>> sy = sp.ndimage.sobel(im, axis=1, mode='constant') + >>> sob = np.hypot(sx, sy) + +.. figure:: auto_examples/images/sphx_glr_plot_find_edges_001.png + :scale: 40 + :target: auto_examples/plot_find_edges.html + +.. only:: html + + [:ref:`Python source code `] + + +Segmentation +------------ + +* **Histogram-based** segmentation (no spatial information) + +:: + + >>> n = 10 + >>> l = 256 + >>> im = np.zeros((l, l)) + >>> rng = np.random.default_rng(27446968) + >>> points = l*rng.random((2, n**2)) + >>> im[(points[0]).astype(int), (points[1]).astype(int)] = 1 + >>> im = sp.ndimage.gaussian_filter(im, sigma=l/(4.*n)) + + >>> mask = (im > im.mean()).astype(float) + >>> mask += 0.1 * im + >>> img = mask + 0.2*rng.standard_normal(mask.shape) + + >>> hist, bin_edges = np.histogram(img, bins=60) + >>> bin_centers = 0.5*(bin_edges[:-1] + bin_edges[1:]) + + >>> binary_img = img > 0.5 + +.. figure:: auto_examples/images/sphx_glr_plot_histo_segmentation_001.png + :scale: 65 + :target: auto_examples/plot_histo_segmentation.html + +.. only:: html + + [:ref:`Python source code `] + +Use mathematical morphology to clean up the result:: + + >>> # Remove small white regions + >>> open_img = sp.ndimage.binary_opening(binary_img) + >>> # Remove small black hole + >>> close_img = sp.ndimage.binary_closing(open_img) + +.. figure:: auto_examples/images/sphx_glr_plot_clean_morpho_001.png + :scale: 65 + :target: auto_examples/plot_clean_morpho.html + +.. only:: html + + [:ref:`Python source code `] + +.. topic:: **Exercise** + :class: green + + Check that reconstruction operations (erosion + propagation) produce a + better result than opening/closing:: + + >>> eroded_img = sp.ndimage.binary_erosion(binary_img) + >>> reconstruct_img = sp.ndimage.binary_propagation(eroded_img, mask=binary_img) + >>> tmp = np.logical_not(reconstruct_img) + >>> eroded_tmp = sp.ndimage.binary_erosion(tmp) + >>> reconstruct_final = np.logical_not(sp.ndimage.binary_propagation(eroded_tmp, mask=tmp)) + >>> np.abs(mask - close_img).mean() + np.float64(0.00640699...) + >>> np.abs(mask - reconstruct_final).mean() + np.float64(0.00082232...) + +.. topic:: **Exercise** + :class: green + + Check how a first denoising step (e.g. with a median filter) + modifies the histogram, and check that the resulting histogram-based + segmentation is more accurate. + + +.. seealso:: + + More advanced segmentation algorithms are found in the + ``scikit-image``: see :ref:`scikit_image`. + +.. seealso:: + + Other Scientific Packages provide algorithms that can be useful for + image processing. In this example, we use the spectral clustering + function of the ``scikit-learn`` in order to segment glued objects. + + + :: + + >>> from sklearn.feature_extraction import image + >>> from sklearn.cluster import spectral_clustering + + >>> l = 100 + >>> x, y = np.indices((l, l)) + + >>> center1 = (28, 24) + >>> center2 = (40, 50) + >>> center3 = (67, 58) + >>> center4 = (24, 70) + >>> radius1, radius2, radius3, radius4 = 16, 14, 15, 14 + + >>> circle1 = (x - center1[0])**2 + (y - center1[1])**2 < radius1**2 + >>> circle2 = (x - center2[0])**2 + (y - center2[1])**2 < radius2**2 + >>> circle3 = (x - center3[0])**2 + (y - center3[1])**2 < radius3**2 + >>> circle4 = (x - center4[0])**2 + (y - center4[1])**2 < radius4**2 + + >>> # 4 circles + >>> img = circle1 + circle2 + circle3 + circle4 + >>> mask = img.astype(bool) + >>> img = img.astype(float) + + >>> rng = np.random.default_rng() + >>> img += 1 + 0.2*rng.standard_normal(img.shape) + >>> # Convert the image into a graph with the value of the gradient on + >>> # the edges. + >>> graph = image.img_to_graph(img, mask=mask) + + >>> # Take a decreasing function of the gradient: we take it weakly + >>> # dependent from the gradient the segmentation is close to a voronoi + >>> graph.data = np.exp(-graph.data/graph.data.std()) + + >>> labels = spectral_clustering(graph, n_clusters=4, eigen_solver='arpack') + >>> label_im = -np.ones(mask.shape) + >>> label_im[mask] = labels + + + .. image:: image_spectral_clustering.png + :align: center + + + +Measuring objects properties: ``scipy.ndimage.measurements`` +============================================================ + +Synthetic data:: + + >>> n = 10 + >>> l = 256 + >>> im = np.zeros((l, l)) + >>> rng = np.random.default_rng(27446968) + >>> points = l * rng.random((2, n**2)) + >>> im[(points[0]).astype(int), (points[1]).astype(int)] = 1 + >>> im = sp.ndimage.gaussian_filter(im, sigma=l/(4.*n)) + >>> mask = im > im.mean() + +* **Analysis of connected components** + +Label connected components: ``scipy.dimage.label``:: + + >>> label_im, nb_labels = sp.ndimage.label(mask) + >>> nb_labels # how many regions? + 28 + >>> plt.imshow(label_im) + + +.. figure:: auto_examples/images/sphx_glr_plot_synthetic_data_001.png + :scale: 90 + :target: auto_examples/plot_synthetic_data.html + +.. only:: html + + [:ref:`Python source code `] + +Compute size, mean_value, etc. of each region:: + + >>> sizes = sp.ndimage.sum(mask, label_im, range(nb_labels + 1)) + >>> mean_vals = sp.ndimage.sum(im, label_im, range(1, nb_labels + 1)) + +Clean up small connect components:: + + >>> mask_size = sizes < 1000 + >>> remove_pixel = mask_size[label_im] + >>> remove_pixel.shape + (256, 256) + >>> label_im[remove_pixel] = 0 + >>> plt.imshow(label_im) + + +Now reassign labels with ``np.searchsorted``:: + + >>> labels = np.unique(label_im) + >>> label_im = np.searchsorted(labels, label_im) + +.. figure:: auto_examples/images/sphx_glr_plot_measure_data_001.png + :scale: 90 + :target: auto_examples/plot_measure_data.html + +.. only:: html + + [:ref:`Python source code `] + +Find region of interest enclosing object:: + + >>> slice_x, slice_y = sp.ndimage.find_objects(label_im)[3] + >>> roi = im[slice_x, slice_y] + >>> plt.imshow(roi) + + +.. figure:: auto_examples/images/sphx_glr_plot_find_object_001.png + :scale: 130 + :target: auto_examples/plot_find_object.html + +.. only:: html + + [:ref:`Python source code `] + +Other spatial measures: ``scipy.ndimage.center_of_mass``, +``scipy.ndimage.maximum_position``, etc. + +Can be used outside the limited scope of segmentation applications. + +Example: block mean:: + + >>> f = sp.datasets.face(gray=True) + >>> sx, sy = f.shape + >>> X, Y = np.ogrid[0:sx, 0:sy] + >>> regions = (sy//6) * (X//4) + (Y//6) # note that we use broadcasting + >>> block_mean = sp.ndimage.mean(f, labels=regions, index=np.arange(1, + ... regions.max() +1)) + >>> block_mean.shape = (sx // 4, sy // 6) + +.. figure:: auto_examples/images/sphx_glr_plot_block_mean_001.png + :scale: 70 + :target: auto_examples/plot_block_mean.html + +.. only:: html + + [:ref:`Python source code `] + +When regions are regular blocks, it is more efficient to use stride +tricks (:ref:`stride-manipulation-label`). + +Non-regularly-spaced blocks: radial mean:: + + >>> sx, sy = f.shape + >>> X, Y = np.ogrid[0:sx, 0:sy] + >>> r = np.hypot(X - sx/2, Y - sy/2) + >>> rbin = (20* r/r.max()).astype(int) + >>> radial_mean = sp.ndimage.mean(f, labels=rbin, index=np.arange(1, rbin.max() +1)) + +.. figure:: auto_examples/images/sphx_glr_plot_radial_mean_001.png + :scale: 70 + :target: auto_examples/plot_radial_mean.html + +.. only:: html + + [:ref:`Python source code `] + + +* **Other measures** + +Correlation function, Fourier/wavelet spectrum, etc. + +One example with mathematical morphology: `granulometry +`_ + +:: + + >>> def disk_structure(n): + ... struct = np.zeros((2 * n + 1, 2 * n + 1)) + ... x, y = np.indices((2 * n + 1, 2 * n + 1)) + ... mask = (x - n)**2 + (y - n)**2 <= n**2 + ... struct[mask] = 1 + ... return struct.astype(bool) + ... + >>> + >>> def granulometry(data, sizes=None): + ... s = max(data.shape) + ... if sizes is None: + ... sizes = range(1, s/2, 2) + ... granulo = [sp.ndimage.binary_opening(data, \ + ... structure=disk_structure(n)).sum() for n in sizes] + ... return granulo + ... + >>> + >>> rng = np.random.default_rng(27446968) + >>> n = 10 + >>> l = 256 + >>> im = np.zeros((l, l)) + >>> points = l*rng.random((2, n**2)) + >>> im[(points[0]).astype(int), (points[1]).astype(int)] = 1 + >>> im = sp.ndimage.gaussian_filter(im, sigma=l/(4.*n)) + >>> + >>> mask = im > im.mean() + >>> + >>> granulo = granulometry(mask, sizes=np.arange(2, 19, 4)) + + +.. figure:: auto_examples/images/sphx_glr_plot_granulo_001.png + :scale: 100 + :target: auto_examples/plot_granulo.html + +.. only:: html + + [:ref:`Python source code `] + + +Full code examples +================== + +.. include the gallery. Skip the first line to avoid the "orphan" + declaration + +.. include:: auto_examples/index.rst + :start-line: 1 + +| + + +.. seealso:: More on image-processing: + + * The chapter on :ref:`Scikit-image ` + + * Other, more powerful and complete modules: `OpenCV + `_ + (Python bindings), `CellProfiler `_, + `ITK `_ with Python bindings diff --git a/_sources/advanced/index.rst.txt b/_sources/advanced/index.rst.txt new file mode 100644 index 000000000..fd8b6026a --- /dev/null +++ b/_sources/advanced/index.rst.txt @@ -0,0 +1,26 @@ +.. _advanced_topics_part: + +Advanced topics +================ + +This part of the *Scientific Python Lectures* is dedicated to advanced usage. +It strives to educate the proficient Python coder to be an expert and +tackles various specific topics. + +| + +.. include:: ../includes/big_toc_css.rst + :start-line: 1 + +.. rst-class:: tune + + .. toctree:: + + advanced_python/index.rst + advanced_numpy/index.rst + debugging/index.rst + optimizing/index.rst + scipy_sparse/index.rst + image_processing/index.rst + mathematical_optimization/index.rst + interfacing_with_c/interfacing_with_c.rst diff --git a/_sources/advanced/interfacing_with_c/interfacing_with_c.rst.txt b/_sources/advanced/interfacing_with_c/interfacing_with_c.rst.txt new file mode 100644 index 000000000..8cb261948 --- /dev/null +++ b/_sources/advanced/interfacing_with_c/interfacing_with_c.rst.txt @@ -0,0 +1,916 @@ +================== +Interfacing with C +================== + +**Author**: *Valentin Haenel* + +.. TODO: + + * Download links + * Timing? + * Additional documentation + * What about overflow? + +This chapter contains an *introduction* to the many different routes for +making your native code (primarily ``C/C++``) available from Python, a +process commonly referred to *wrapping*. The goal of this chapter is to +give you a flavour of what technologies exist and what their respective +merits and shortcomings are, so that you can select the appropriate one +for your specific needs. In any case, once you do start wrapping, you +almost certainly will want to consult the respective documentation for +your selected technique. + +.. contents:: Chapters contents + :local: + :depth: 1 + +Introduction +============ + +This chapter covers the following techniques: + +* `Python-C-Api `_ +* `Ctypes `_ +* `SWIG (Simplified Wrapper and Interface Generator) `_ +* `Cython `__ + +These four techniques are perhaps the most well known ones, of which Cython is +probably the most advanced one and the one you should consider using first. The +others are also important, if you want to understand the wrapping problem from +different angles. Having said that, there are other alternatives out there, +but having understood the basics of the ones above, you will be in a position +to evaluate the technique of your choice to see if it fits your needs. + +The following criteria may be useful when evaluating a technology: + +* Are additional libraries required? +* Is the code autogenerated? +* Does it need to be compiled? +* Is there good support for interacting with NumPy arrays? +* Does it support C++? + +Before you set out, you should consider your use case. When interfacing with +native code, there are usually two use-cases that come up: + +* Existing code in C/C++ that needs to be leveraged, either because it already + exists, or because it is faster. +* Python code too slow, push inner loops to native code + +Each technology is demonstrated by wrapping the ``cos`` function from +``math.h``. While this is a mostly a trivial example, it should serve us well +to demonstrate the basics of the wrapping solution. Since each technique also +includes some form of NumPy support, this is also demonstrated using an +example where the cosine is computed on some kind of array. + +Last but not least, two small warnings: + +* All of these techniques may crash (segmentation fault) the Python + interpreter, which is (usually) due to bugs in the C code. +* All the examples have been done on Linux, they *should* be possible on other + operating systems. +* You will need a C compiler for most of the examples. + + +Python-C-Api +============ + +The `Python-C-API `_ is the backbone of the +standard Python interpreter (a.k.a *CPython*). Using this API it is possible to +write Python extension module in C and C++. Obviously, these extension modules +can, by virtue of language compatibility, call any function written in C or +C++. + +When using the Python-C-API, one usually writes much boilerplate code, first to +parse the arguments that were given to a function, and later to construct the +return type. + +**Advantages** + +* Requires no additional libraries +* Lots of low-level control +* Entirely usable from C++ + +**Disadvantages** + +* May require a substantial amount of effort +* Much overhead in the code +* Must be compiled +* High maintenance cost +* No forward compatibility across Python versions as C-API changes +* Reference count bugs are easy to create and very hard to track down. + +.. note:: + + The Python-C-Api example here serves mainly for didactic reasons. Many of + the other techniques actually depend on this, so it is good to have a + high-level understanding of how it works. In 99% of the use-cases you will + be better off, using an alternative technique. + +.. note:: + + Since reference counting bugs are easy to create and hard to track down, + anyone really needing to use the Python C-API should read the `section + about objects, types and reference counts + `_ + from the official python documentation. Additionally, there is a tool by the + name of `cpychecker + `_ + which can help discover common errors with reference counting. + +Example +------- + +The following C-extension module, make the ``cos`` function from the standard +math library available to Python: + +.. literalinclude:: python_c_api/cos_module.c + :language: c + +As you can see, there is much boilerplate, both to «massage» the arguments and +return types into place and for the module initialisation. Although some of +this is amortised, as the extension grows, the boilerplate required for each +function(s) remains. + +The standard python build system, ``setuptools``, supports compiling +C-extensions via a ``setup.py`` file: + +.. literalinclude:: python_c_api/setup.py + :language: python + +The setup file is called as follows: + +.. sourcecode:: console + + $ cd advanced/interfacing_with_c/python_c_api + + $ ls + cos_module.c setup.py + + $ python setup.py build_ext --inplace + running build_ext + building 'cos_module' extension + creating build + creating build/temp.linux-x86_64-2.7 + gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module.c -o build/temp.linux-x86_64-2.7/cos_module.o + gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_module.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/python_c_api/cos_module.so + + $ ls + build/ cos_module.c cos_module.so setup.py + +* ``build_ext`` is to build extension modules +* ``--inplace`` will output the compiled extension module into the current directory + +The file ``cos_module.so`` contains the compiled extension, which we can now load in the IPython interpreter: + +.. note:: + + In Python 3, the filename for compiled modules includes metadata on the Python + interpreter (see `PEP 3149 `_) and is thus + longer. The import statement is not affected by this. + +.. ipython:: + :verbatim: + + In [1]: import cos_module + + In [2]: cos_module? + Type: module + String Form: + File: /home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/python_c_api/cos_module.so + Docstring: + + In [3]: dir(cos_module) + Out[3]: ['__doc__', '__file__', '__name__', '__package__', 'cos_func'] + + In [4]: cos_module.cos_func(1.0) + Out[4]: 0.5403023058681398 + + In [5]: cos_module.cos_func(0.0) + Out[5]: 1.0 + + In [6]: cos_module.cos_func(3.14159265359) + Out[7]: -1.0 + +Now let's see how robust this is: + +.. ipython:: + :verbatim: + + In [10]: cos_module.cos_func('foo') + --------------------------------------------------------------------------- + TypeError Traceback (most recent call last) + in () + ----> 1 cos_module.cos_func('foo') + TypeError: a float is required + +NumPy Support +------------- + +Analog to the Python-C-API, NumPy, which is itself implemented as a +C-extension, comes with the `NumPy-C-API +`_. This API can be used +to create and manipulate NumPy arrays from C, when writing a custom +C-extension. See also: :ref:`advanced_numpy`. + +.. note:: + + If you do ever need to use the NumPy C-API refer to the documentation about + `Arrays `_ and + `Iterators + `_. + +The following example shows how to pass NumPy arrays as arguments to functions +and how to iterate over NumPy arrays using the (old) NumPy-C-API. It simply +takes an array as argument applies the cosine function from the ``math.h`` and +returns a resulting new array. + +.. literalinclude:: numpy_c_api/cos_module_np.c + :language: c + +To compile this we can use ``setuptools`` again. However we need to be sure to +include the NumPy headers by using :func:`numpy.get_include`. + +.. literalinclude:: numpy_c_api/setup.py + :language: python + +To convince ourselves if this does actually works, we run the following test +script: + +.. literalinclude:: numpy_c_api/test_cos_module_np.py + :language: numpy + +And this should result in the following figure: + +.. image:: numpy_c_api/test_cos_module_np.png + :scale: 50 + + +Ctypes +====== + +`Ctypes `_ is a *foreign +function library* for Python. It provides C compatible data types, and allows +calling functions in DLLs or shared libraries. It can be used to wrap these +libraries in pure Python. + +**Advantages** + +* Part of the Python standard library +* Does not need to be compiled +* Wrapping code entirely in Python + +**Disadvantages** + +* Requires code to be wrapped to be available as a shared library + (roughly speaking ``*.dll`` in Windows ``*.so`` in Linux and ``*.dylib`` in Mac OSX.) +* No good support for C++ + +Example +------- + +As advertised, the wrapper code is in pure Python. + +.. literalinclude:: ctypes/cos_module.py + :language: python + +* Finding and loading the library may vary depending on your operating system, + check `the documentation + `_ + for details +* This may be somewhat deceptive, since the math library exists in compiled + form on the system already. If you were to wrap a in-house library, you would + have to compile it first, which may or may not require some additional effort. + +We may now use this, as before: + +.. ipython:: + :verbatim: + + In [1]: import cos_module + + In [2]: cos_module? + Type: module + String Form: + File: /home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/ctypes/cos_module.py + Docstring: + + In [3]: dir(cos_module) + Out[3]: + ['__builtins__', + '__doc__', + '__file__', + '__name__', + '__package__', + 'cos_func', + 'ctypes', + 'find_library', + 'libm'] + + In [4]: cos_module.cos_func(1.0) + Out[4]: 0.5403023058681398 + + In [5]: cos_module.cos_func(0.0) + Out[5]: 1.0 + + In [6]: cos_module.cos_func(3.14159265359) + Out[6]: -1.0 + +As with the previous example, this code is somewhat robust, although the error +message is not quite as helpful, since it does not tell us what the type should be. + +.. ipython:: + :verbatim: + + In [7]: cos_module.cos_func('foo') + --------------------------------------------------------------------------- + ArgumentError Traceback (most recent call last) + in () + ----> 1 cos_module.cos_func('foo') + /home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/ctypes/cos_module.py in cos_func(arg) + 12 def cos_func(arg): + 13 ''' Wrapper for cos from math.h ''' + ---> 14 return libm.cos(arg) + ArgumentError: argument 1: : wrong type + +NumPy Support +------------- + +NumPy contains some support for interfacing with ctypes. In particular there is +support for exporting certain attributes of a NumPy array as ctypes data-types +and there are functions to convert from C arrays to NumPy arrays and back. + +.. XXX Should use :mod: and :class: + +For more information, consult the corresponding section in the `NumPy Cookbook +`_ and the API documentation for +`numpy.ndarray.ctypes `_ +and `numpy.ctypeslib `_. + +For the following example, let's consider a C function in a library that takes +an input and an output array, computes the cosine of the input array and +stores the result in the output array. + +The library consists of the following header file (although this is not +strictly needed for this example, we list it for completeness): + +.. literalinclude:: ctypes_numpy/cos_doubles.h + :language: c + +The function implementation resides in the following C source file: + +.. literalinclude:: ctypes_numpy/cos_doubles.c + :language: c + +And since the library is pure C, we can't use ``setuptools`` to compile it, but +must use a combination of ``make`` and ``gcc``: + +.. literalinclude:: ctypes_numpy/makefile + :language: make + +We can then compile this (on Linux) into the shared library +``libcos_doubles.so``: + +.. sourcecode:: console + + $ ls + cos_doubles.c cos_doubles.h cos_doubles.py makefile test_cos_doubles.py + $ make + gcc -c -fPIC cos_doubles.c -o cos_doubles.o + gcc -shared -Wl,-soname,libcos_doubles.so -o libcos_doubles.so cos_doubles.o + $ ls + cos_doubles.c cos_doubles.o libcos_doubles.so* test_cos_doubles.py + cos_doubles.h cos_doubles.py makefile + +Now we can proceed to wrap this library via ctypes with direct support for +(certain kinds of) NumPy arrays: + +.. literalinclude:: ctypes_numpy/cos_doubles.py + :language: numpy + +* Note the inherent limitation of contiguous single dimensional NumPy arrays, + since the C functions requires this kind of buffer. +* Also note that the output array must be preallocated, for example with + :func:`numpy.zeros` and the function will write into it's buffer. +* Although the original signature of the ``cos_doubles`` function is ``ARRAY, + ARRAY, int`` the final ``cos_doubles_func`` takes only two NumPy arrays as + arguments. + +And, as before, we convince ourselves that it worked: + +.. literalinclude:: ctypes_numpy/test_cos_doubles.py + :language: numpy + +.. image:: ctypes_numpy/test_cos_doubles.png + :scale: 50 + +SWIG +==== + +`SWIG `_, the Simplified Wrapper Interface Generator, +is a software development tool that connects programs written in C and C++ +with a variety of high-level programming languages, including Python. The +important thing with SWIG is, that it can autogenerate the wrapper code for you. +While this is an advantage in terms of development time, it can also be a +burden. The generated file tend to be quite large and may not be too human +readable and the multiple levels of indirection which are a result of +the wrapping process, may be a bit tricky to understand. + +.. note:: + + The autogenerated C code uses the Python-C-Api. + +**Advantages** + +* Can automatically wrap entire libraries given the headers +* Works nicely with C++ + +**Disadvantages** + +* Autogenerates enormous files +* Hard to debug if something goes wrong +* Steep learning curve + +Example +------- + +Let's imagine that our ``cos`` function lives in a ``cos_module`` which has +been written in ``c`` and consists of the source file ``cos_module.c``: + +.. literalinclude:: swig/cos_module.c + :language: c + +and the header file ``cos_module.h``: + +.. literalinclude:: swig/cos_module.h + :language: c + +And our goal is to expose the ``cos_func`` to Python. To achieve this with +SWIG, we must write an *interface file* which contains the instructions for SWIG. + +.. literalinclude:: swig/cos_module.i + :language: c + +As you can see, not too much code is needed here. For this simple example it is +enough to simply include the header file in the interface file, to expose the +function to Python. However, SWIG does allow for more fine grained +inclusion/exclusion of functions found in header files, check the documentation +for details. + +Generating the compiled wrappers is a two stage process: + +#. Run the ``swig`` executable on the interface file to generate the files + ``cos_module_wrap.c``, which is the source file for the autogenerated Python + C-extension and ``cos_module.py``, which is the autogenerated pure python + module. + +#. Compile the ``cos_module_wrap.c`` into the ``_cos_module.so``. Luckily, + ``setuptools`` knows how to handle SWIG interface files, so that our + ``setup.py`` is simply: + +.. literalinclude:: swig/setup.py + :language: python + +.. sourcecode:: console + + $ cd advanced/interfacing_with_c/swig + + $ ls + cos_module.c cos_module.h cos_module.i setup.py + + $ python setup.py build_ext --inplace + running build_ext + building '_cos_module' extension + swigging cos_module.i to cos_module_wrap.c + swig -python -o cos_module_wrap.c cos_module.i + creating build + creating build/temp.linux-x86_64-2.7 + gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module.c -o build/temp.linux-x86_64-2.7/cos_module.o + gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module_wrap.c -o build/temp.linux-x86_64-2.7/cos_module_wrap.o + gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_module.o build/temp.linux-x86_64-2.7/cos_module_wrap.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/swig/_cos_module.so + + $ ls + build/ cos_module.c cos_module.h cos_module.i cos_module.py _cos_module.so* cos_module_wrap.c setup.py + +We can now load and execute the ``cos_module`` as we have done in the previous examples: + +.. ipython:: + :verbatim: + + In [1]: import cos_module + + In [2]: cos_module? + Type: module + String Form: + File: /home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/swig/cos_module.py + Docstring: + + In [3]: dir(cos_module) + Out[3]: + ['__builtins__', + '__doc__', + '__file__', + '__name__', + '__package__', + '_cos_module', + '_newclass', + '_object', + '_swig_getattr', + '_swig_property', + '_swig_repr', + '_swig_setattr', + '_swig_setattr_nondynamic', + 'cos_func'] + + In [4]: cos_module.cos_func(1.0) + Out[4]: 0.5403023058681398 + + In [5]: cos_module.cos_func(0.0) + Out[5]: 1.0 + + In [6]: cos_module.cos_func(3.14159265359) + Out[6]: -1.0 + +Again we test for robustness, and we see that we get a better error message +(although, strictly speaking in Python there is no ``double`` type): + +.. ipython:: + :verbatim: + + In [7]: cos_module.cos_func('foo') + --------------------------------------------------------------------------- + TypeError Traceback (most recent call last) + in () + ----> 1 cos_module.cos_func('foo') + TypeError: in method 'cos_func', argument 1 of type 'double' + +NumPy Support +------------- + +NumPy provides `support for SWIG +`_ with the ``numpy.i`` +file. This interface file defines various so-called *typemaps* which support +conversion between NumPy arrays and C-Arrays. In the following example we will +take a quick look at how such typemaps work in practice. + +We have the same ``cos_doubles`` function as in the ctypes example: + +.. literalinclude:: swig_numpy/cos_doubles.h + :language: c + +.. literalinclude:: swig_numpy/cos_doubles.c + :language: c + +This is wrapped as ``cos_doubles_func`` using the following SWIG interface +file: + +.. literalinclude:: swig_numpy/cos_doubles.i + :language: c + +* To use the NumPy typemaps, we need include the ``numpy.i`` file. +* Observe the call to ``import_array()`` which we encountered already in the + NumPy-C-API example. +* Since the type maps only support the signature ``ARRAY, SIZE`` we need to + wrap the ``cos_doubles`` as ``cos_doubles_func`` which takes two arrays + including sizes as input. +* As opposed to the simple SWIG example, we don't include the ``cos_doubles.h`` + header, There is nothing there that we wish to expose to Python since we + expose the functionality through ``cos_doubles_func``. + +And, as before we can use ``setuptools`` to wrap this: + +.. literalinclude:: swig_numpy/setup.py + :language: python + +As previously, we need to use ``include_dirs`` to specify the location. + +.. sourcecode:: console + + $ ls + cos_doubles.c cos_doubles.h cos_doubles.i numpy.i setup.py test_cos_doubles.py + $ python setup.py build_ext -i + running build_ext + building '_cos_doubles' extension + swigging cos_doubles.i to cos_doubles_wrap.c + swig -python -o cos_doubles_wrap.c cos_doubles.i + cos_doubles.i:24: Warning(490): Fragment 'NumPy_Backward_Compatibility' not found. + cos_doubles.i:24: Warning(490): Fragment 'NumPy_Backward_Compatibility' not found. + cos_doubles.i:24: Warning(490): Fragment 'NumPy_Backward_Compatibility' not found. + creating build + creating build/temp.linux-x86_64-2.7 + gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include -I/home/esc/anaconda/include/python2.7 -c cos_doubles.c -o build/temp.linux-x86_64-2.7/cos_doubles.o + gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include -I/home/esc/anaconda/include/python2.7 -c cos_doubles_wrap.c -o build/temp.linux-x86_64-2.7/cos_doubles_wrap.o + In file included from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1722, + from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:17, + from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/arrayobject.h:15, + from cos_doubles_wrap.c:2706: + /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/npy_deprecated_api.h:11:2: warning: #warning "Using deprecated NumPy API, disable it by #defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" + gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_doubles.o build/temp.linux-x86_64-2.7/cos_doubles_wrap.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/swig_numpy/_cos_doubles.so + $ ls + build/ cos_doubles.h cos_doubles.py cos_doubles_wrap.c setup.py + cos_doubles.c cos_doubles.i _cos_doubles.so* numpy.i test_cos_doubles.py + +And, as before, we convince ourselves that it worked: + +.. literalinclude:: swig_numpy/test_cos_doubles.py + :language: numpy + +.. image:: swig_numpy/test_cos_doubles.png + :scale: 50 + + +Cython +====== + +`Cython `__ is both a Python-like language for writing +C-extensions and an advanced compiler for this language. The Cython *language* +is a superset of Python, which comes with additional constructs that allow you +call C functions and annotate variables and class attributes with c types. In +this sense one could also call it a *Python with types*. + +In addition to the basic use case of wrapping native code, Cython supports an +additional use-case, namely interactive optimization. Basically, one starts out +with a pure-Python script and incrementally adds Cython types to the bottleneck +code to optimize only those code paths that really matter. + +In this sense it is quite similar to SWIG, since the code can be autogenerated +but in a sense it also quite similar to ctypes since the wrapping code can +(almost) be written in Python. + +While others solutions that autogenerate code can be quite difficult to debug +(for example SWIG) Cython comes with an extension to the GNU debugger that +helps debug Python, Cython and C code. + +.. note:: + + The autogenerated C code uses the Python-C-Api. + +**Advantages** + +* Python like language for writing C-extensions +* Autogenerated code +* Supports incremental optimization +* Includes a GNU debugger extension +* Support for C++ (Since version 0.13) + +**Disadvantages** + +* Must be compiled +* Requires an additional library ( but only at build time, at this problem can be + overcome by shipping the generated C files) + +Example +------- + +The main Cython code for our ``cos_module`` is contained in the file +``cos_module.pyx``: + +.. literalinclude:: cython/cos_module.pyx + :language: cython + +Note the additional keywords such as ``cdef`` and ``extern``. Also the +``cos_func`` is then pure Python. + +Again we can use the standard ``setuptools`` module, but this time we need some +additional pieces from ``Cython.Build``: + +.. literalinclude:: cython/setup.py + +Compiling this: + +.. sourcecode:: console + + $ cd advanced/interfacing_with_c/cython + $ ls + cos_module.pyx setup.py + $ python setup.py build_ext --inplace + running build_ext + cythoning cos_module.pyx to cos_module.c + building 'cos_module' extension + creating build + creating build/temp.linux-x86_64-2.7 + gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module.c -o build/temp.linux-x86_64-2.7/cos_module.o + gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_module.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/cython/cos_module.so + $ ls + build/ cos_module.c cos_module.pyx cos_module.so* setup.py + +And running it: + +.. ipython:: + :verbatim: + + In [1]: import cos_module + + In [2]: cos_module? + Type: module + String Form: + File: /home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/cython/cos_module.so + Docstring: + + In [3]: dir(cos_module) + Out[3]: + ['__builtins__', + '__doc__', + '__file__', + '__name__', + '__package__', + '__test__', + 'cos_func'] + + In [4]: cos_module.cos_func(1.0) + Out[4]: 0.5403023058681398 + + In [5]: cos_module.cos_func(0.0) + Out[5]: 1.0 + + In [6]: cos_module.cos_func(3.14159265359) + Out[6]: -1.0 + +And, testing a little for robustness, we can see that we get good error messages: + +.. ipython:: + :verbatim: + + In [7]: cos_module.cos_func('foo') + --------------------------------------------------------------------------- + TypeError Traceback (most recent call last) + in () + ----> 1 cos_module.cos_func('foo') + /home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/cython/cos_module.so in cos_module.cos_func (cos_module.c:506)() + TypeError: a float is required + + +Additionally, it is worth noting that ``Cython`` ships with complete +declarations for the C math library, which simplifies the code above to become: + +.. literalinclude:: cython_simple/cos_module.pyx + :language: cython + +In this case the ``cimport`` statement is used to import the ``cos`` function. + +NumPy Support +------------- + +Cython has support for NumPy via the ``numpy.pyx`` file which allows you to add +the NumPy array type to your Cython code. I.e. like specifying that variable +``i`` is of type ``int``, you can specify that variable ``a`` is of type +``numpy.ndarray`` with a given ``dtype``. Also, certain optimizations such as +bounds checking are supported. Look at the corresponding section in the `Cython +documentation `_. In case you +want to pass NumPy arrays as C arrays to your Cython wrapped C functions, there +is a `section about this in the Cython documentation +`__. + +In the following example, we will show how to wrap the familiar ``cos_doubles`` +function using Cython. + +.. literalinclude:: cython_numpy/cos_doubles.h + :language: c + +.. literalinclude:: cython_numpy/cos_doubles.c + :language: c + +This is wrapped as ``cos_doubles_func`` using the following Cython code: + +.. literalinclude:: cython_numpy/_cos_doubles.pyx + :language: cython + +And can be compiled using ``setuptools``: + +.. literalinclude:: cython_numpy/setup.py + :language: python + +* As with the previous compiled NumPy examples, we need the ``include_dirs`` option. + +.. sourcecode:: console + + $ ls + cos_doubles.c cos_doubles.h _cos_doubles.pyx setup.py test_cos_doubles.py + $ python setup.py build_ext -i + running build_ext + cythoning _cos_doubles.pyx to _cos_doubles.c + building 'cos_doubles' extension + creating build + creating build/temp.linux-x86_64-2.7 + gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include -I/home/esc/anaconda/include/python2.7 -c _cos_doubles.c -o build/temp.linux-x86_64-2.7/_cos_doubles.o + In file included from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1722, + from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:17, + from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/arrayobject.h:15, + from _cos_doubles.c:253: + /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/npy_deprecated_api.h:11:2: warning: #warning "Using deprecated NumPy API, disable it by #defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" + /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/__ufunc_api.h:236: warning: ‘_import_umath’ defined but not used + gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include -I/home/esc/anaconda/include/python2.7 -c cos_doubles.c -o build/temp.linux-x86_64-2.7/cos_doubles.o + gcc -pthread -shared build/temp.linux-x86_64-2.7/_cos_doubles.o build/temp.linux-x86_64-2.7/cos_doubles.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/cython_numpy/cos_doubles.so + $ ls + build/ _cos_doubles.c cos_doubles.c cos_doubles.h _cos_doubles.pyx cos_doubles.so* setup.py test_cos_doubles.py + +And, as before, we convince ourselves that it worked: + +.. literalinclude:: cython_numpy/test_cos_doubles.py + :language: numpy + +.. image:: cython_numpy/test_cos_doubles.png + :scale: 50 + + + +Summary +======= + +In this section four different techniques for interfacing with native code +have been presented. The table below roughly summarizes some of the aspects of +the techniques. + +============ =============== ========= ============= ============= +x Part of CPython Compiled Autogenerated NumPy Support +============ =============== ========= ============= ============= +Python-C-API ``True`` ``True`` ``False`` ``True`` +Ctypes ``True`` ``False`` ``False`` ``True`` +Swig ``False`` ``True`` ``True`` ``True`` +Cython ``False`` ``True`` ``True`` ``True`` +============ =============== ========= ============= ============= + +Of all three presented techniques, Cython is the most modern and advanced. In +particular, the ability to optimize code incrementally by adding types to your +Python code is unique. + +Further Reading and References +============================== + +* `Gaël Varoquaux's blog post about avoiding data copies + `_ provides some insight on how to + handle memory management cleverly. If you ever run into issues with large + datasets, this is a reference to come back to for some inspiration. + +Exercises +========= + +Since this is a brand new section, the exercises are considered more as +pointers as to what to look at next, so pick the ones that you find more +interesting. If you have good ideas for exercises, please let us know! + +#. Download the source code for each example and compile and run them on your + machine. +#. Make trivial changes to each example and convince yourself that this works. ( + E.g. change ``cos`` for ``sin``.) +#. Most of the examples, especially the ones involving NumPy may still be + fragile and respond badly to input errors. Look for ways to crash the + examples, figure what the problem is and devise a potential solution. + Here are some ideas: + + #. Numerical overflow. + #. Input and output arrays that have different lengths. + #. Multidimensional array. + #. Empty array + #. Arrays with non-``double`` types + +#. Use the ``%timeit`` IPython magic to measure the execution time of the + various solutions + + +Python-C-API +------------ + +#. Modify the NumPy example such that the function takes two input arguments, where + the second is the preallocated output array, making it similar to the other NumPy examples. +#. Modify the example such that the function only takes a single input array + and modifies this in place. +#. Try to fix the example to use the new `NumPy iterator protocol + `_. If you + manage to obtain a working solution, please submit a pull-request on github. +#. You may have noticed, that the NumPy-C-API example is the only NumPy example + that does not wrap ``cos_doubles`` but instead applies the ``cos`` function + directly to the elements of the NumPy array. Does this have any advantages + over the other techniques. +#. Can you wrap ``cos_doubles`` using only the NumPy-C-API. You may need to + ensure that the arrays have the correct type, are one dimensional and + contiguous in memory. + +Ctypes +------ + +#. Modify the NumPy example such that ``cos_doubles_func`` handles the preallocation for + you, thus making it more like the NumPy-C-API example. + +SWIG +---- + +#. Look at the code that SWIG autogenerates, how much of it do you + understand? +#. Modify the NumPy example such that ``cos_doubles_func`` handles the preallocation for + you, thus making it more like the NumPy-C-API example. +#. Modify the ``cos_doubles`` C function so that it returns an allocated array. + Can you wrap this using SWIG typemaps? If not, why not? Is there a + workaround for this specific situation? (Hint: you know the size of the + output array, so it may be possible to construct a NumPy array from the + returned ``double *``.) + +Cython +------ + +#. Look at the code that Cython autogenerates. Take a closer look at some of the + comments that Cython inserts. What do you see? +#. Look at the section `Working with NumPy + `_ from the Cython + documentation to learn how to incrementally optimize a pure python script that uses NumPy. +#. Modify the NumPy example such that ``cos_doubles_func`` handles the preallocation for + you, thus making it more like the NumPy-C-API example. diff --git a/_sources/advanced/mathematical_optimization/auto_examples/index.rst.txt b/_sources/advanced/mathematical_optimization/auto_examples/index.rst.txt new file mode 100644 index 000000000..6f1f751e1 --- /dev/null +++ b/_sources/advanced/mathematical_optimization/auto_examples/index.rst.txt @@ -0,0 +1,241 @@ +:orphan: + +Examples for the mathematical optimization chapter +================================================== + + + +.. raw:: html + +
+ +.. thumbnail-parent-div-open + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/mathematical_optimization/auto_examples/images/thumb/sphx_glr_plot_noisy_thumb.png + :alt: + + :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_noisy.py` + +.. raw:: html + +
Noisy optimization problem
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/mathematical_optimization/auto_examples/images/thumb/sphx_glr_plot_smooth_thumb.png + :alt: + + :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_smooth.py` + +.. raw:: html + +
Smooth vs non-smooth
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/mathematical_optimization/auto_examples/images/thumb/sphx_glr_plot_curve_fitting_thumb.png + :alt: + + :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_curve_fitting.py` + +.. raw:: html + +
Curve fitting
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/mathematical_optimization/auto_examples/images/thumb/sphx_glr_plot_convex_thumb.png + :alt: + + :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_convex.py` + +.. raw:: html + +
Convex function
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/mathematical_optimization/auto_examples/images/thumb/sphx_glr_plot_exercise_flat_minimum_thumb.png + :alt: + + :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_exercise_flat_minimum.py` + +.. raw:: html + +
Finding a minimum in a flat neighborhood
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/mathematical_optimization/auto_examples/images/thumb/sphx_glr_plot_non_bounds_constraints_thumb.png + :alt: + + :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_non_bounds_constraints.py` + +.. raw:: html + +
Optimization with constraints
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/mathematical_optimization/auto_examples/images/thumb/sphx_glr_plot_1d_optim_thumb.png + :alt: + + :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_1d_optim.py` + +.. raw:: html + +
Brent's method
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/mathematical_optimization/auto_examples/images/thumb/sphx_glr_plot_constraints_thumb.png + :alt: + + :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_constraints.py` + +.. raw:: html + +
Constraint optimization: visualizing the geometry
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/mathematical_optimization/auto_examples/images/thumb/sphx_glr_plot_exercise_ill_conditioned_thumb.png + :alt: + + :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_exercise_ill_conditioned.py` + +.. raw:: html + +
Alternating optimization
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/mathematical_optimization/auto_examples/images/thumb/sphx_glr_plot_compare_optimizers_thumb.png + :alt: + + :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_compare_optimizers.py` + +.. raw:: html + +
Plotting the comparison of optimizers
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /advanced/mathematical_optimization/auto_examples/images/thumb/sphx_glr_plot_gradient_descent_thumb.png + :alt: + + :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_gradient_descent.py` + +.. raw:: html + +
Gradient descent
+
+ + +.. thumbnail-parent-div-close + +.. raw:: html + +
+ + +.. toctree:: + :hidden: + + /advanced/mathematical_optimization/auto_examples/plot_noisy + /advanced/mathematical_optimization/auto_examples/plot_smooth + /advanced/mathematical_optimization/auto_examples/plot_curve_fitting + /advanced/mathematical_optimization/auto_examples/plot_convex + /advanced/mathematical_optimization/auto_examples/plot_exercise_flat_minimum + /advanced/mathematical_optimization/auto_examples/plot_non_bounds_constraints + /advanced/mathematical_optimization/auto_examples/plot_1d_optim + /advanced/mathematical_optimization/auto_examples/plot_constraints + /advanced/mathematical_optimization/auto_examples/plot_exercise_ill_conditioned + /advanced/mathematical_optimization/auto_examples/plot_compare_optimizers + /advanced/mathematical_optimization/auto_examples/plot_gradient_descent + + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-gallery + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download all examples in Python source code: auto_examples_python.zip ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download all examples in Jupyter notebooks: auto_examples_jupyter.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/mathematical_optimization/auto_examples/plot_1d_optim.rst.txt b/_sources/advanced/mathematical_optimization/auto_examples/plot_1d_optim.rst.txt new file mode 100644 index 000000000..d3983fbae --- /dev/null +++ b/_sources/advanced/mathematical_optimization/auto_examples/plot_1d_optim.rst.txt @@ -0,0 +1,168 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/mathematical_optimization/auto_examples/plot_1d_optim.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_mathematical_optimization_auto_examples_plot_1d_optim.py: + + +Brent's method +================ + +Illustration of 1D optimization: Brent's method + +.. GENERATED FROM PYTHON SOURCE LINES 7-67 + + + +.. rst-class:: sphx-glr-horizontal + + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_1d_optim_001.png + :alt: plot 1d optim + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_1d_optim_001.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_1d_optim_002.png + :alt: plot 1d optim + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_1d_optim_002.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_1d_optim_003.png + :alt: plot 1d optim + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_1d_optim_003.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_1d_optim_004.png + :alt: plot 1d optim + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_1d_optim_004.png + :class: sphx-glr-multi-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + Converged at 6 + Converged at 23 + + + + + + +| + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + import scipy as sp + + x = np.linspace(-1, 3, 100) + x_0 = np.exp(-1) + + + def f(x): + return (x - x_0) ** 2 + epsilon * np.exp(-5 * (x - 0.5 - x_0) ** 2) + + + for epsilon in (0, 1): + plt.figure(figsize=(3, 2.5)) + plt.axes((0, 0, 1, 1)) + + # A convex function + plt.plot(x, f(x), linewidth=2) + + # Apply brent method. To have access to the iteration, do this in an + # artificial way: allow the algorithm to iter only once + all_x = [] + all_y = [] + for iter in range(30): + result = sp.optimize.minimize_scalar( + f, + bracket=(-5, 2.9, 4.5), + method="Brent", + options={"maxiter": iter}, + tol=np.finfo(1.0).eps, + ) + if result.success: + print("Converged at ", iter) + break + + this_x = result.x + all_x.append(this_x) + all_y.append(f(this_x)) + if iter < 6: + plt.text( + this_x - 0.05 * np.sign(this_x) - 0.05, + f(this_x) + 1.2 * (0.3 - iter % 2), + str(iter + 1), + size=12, + ) + + plt.plot(all_x[:10], all_y[:10], "k+", markersize=12, markeredgewidth=2) + + plt.plot(all_x[-1], all_y[-1], "rx", markersize=12) + plt.axis("off") + plt.ylim(ymin=-1, ymax=8) + + plt.figure(figsize=(4, 3)) + plt.semilogy(np.abs(all_y - all_y[-1]), linewidth=2) + plt.ylabel("Error on f(x)") + plt.xlabel("Iteration") + plt.tight_layout() + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.231 seconds) + + +.. _sphx_glr_download_advanced_mathematical_optimization_auto_examples_plot_1d_optim.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_1d_optim.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_1d_optim.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_1d_optim.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/mathematical_optimization/auto_examples/plot_compare_optimizers.rst.txt b/_sources/advanced/mathematical_optimization/auto_examples/plot_compare_optimizers.rst.txt new file mode 100644 index 000000000..f2729cfe6 --- /dev/null +++ b/_sources/advanced/mathematical_optimization/auto_examples/plot_compare_optimizers.rst.txt @@ -0,0 +1,169 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/mathematical_optimization/auto_examples/plot_compare_optimizers.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_mathematical_optimization_auto_examples_plot_compare_optimizers.py: + + +Plotting the comparison of optimizers +====================================== + +Plots the results from the comparison of optimizers. + +.. GENERATED FROM PYTHON SOURCE LINES 8-106 + + + +.. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_compare_optimizers_001.png + :alt: plot compare optimizers + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_compare_optimizers_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import pickle + import sys + + import numpy as np + + import matplotlib + import matplotlib.pyplot as plt + + results = pickle.load( + open(f"helper/compare_optimizers_py{sys.version_info[0]}.pkl", "rb") + ) + n_methods = len(list(results.values())[0]["Rosenbrock "]) + n_dims = len(results) + + symbols = "o>*Ds" + + plt.figure(1, figsize=(10, 4)) + plt.clf() + + nipy_spectral = matplotlib.colormaps["nipy_spectral"] + colors = nipy_spectral(np.linspace(0, 1, n_dims))[:, :3] + + method_names = list(list(results.values())[0]["Rosenbrock "].keys()) + method_names.sort(key=lambda x: x[::-1], reverse=True) + + for n_dim_index, ((n_dim, n_dim_bench), color) in enumerate( + zip(sorted(results.items()), colors, strict=True) + ): + for (cost_name, cost_bench), symbol in zip( + sorted(n_dim_bench.items()), symbols, strict=True + ): + for ( + method_index, + method_name, + ) in enumerate(method_names): + this_bench = cost_bench[method_name] + bench = np.mean(this_bench) + plt.semilogy( + [ + method_index + 0.1 * n_dim_index, + ], + [ + bench, + ], + marker=symbol, + color=color, + ) + + # Create a legend for the problem type + for cost_name, symbol in zip(sorted(n_dim_bench.keys()), symbols, strict=True): + plt.semilogy( + [ + -10, + ], + [ + 0, + ], + symbol, + color=".5", + label=cost_name, + ) + + plt.xticks(np.arange(n_methods), method_names, size=11) + plt.xlim(-0.2, n_methods - 0.5) + plt.legend(loc="best", numpoints=1, handletextpad=0, prop={"size": 12}, frameon=False) + plt.ylabel("# function calls (a.u.)") + + # Create a second legend for the problem dimensionality + plt.twinx() + + for n_dim, color in zip(sorted(results.keys()), colors, strict=True): + plt.plot( + [ + -10, + ], + [ + 0, + ], + "o", + color=color, + label="# dim: %i" % n_dim, + ) + plt.legend( + loc=(0.47, 0.07), + numpoints=1, + handletextpad=0, + prop={"size": 12}, + frameon=False, + ncol=2, + ) + plt.xlim(-0.2, n_methods - 0.5) + + plt.xticks(np.arange(n_methods), method_names) + plt.yticks(()) + + plt.tight_layout() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.569 seconds) + + +.. _sphx_glr_download_advanced_mathematical_optimization_auto_examples_plot_compare_optimizers.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_compare_optimizers.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_compare_optimizers.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_compare_optimizers.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/mathematical_optimization/auto_examples/plot_constraints.rst.txt b/_sources/advanced/mathematical_optimization/auto_examples/plot_constraints.rst.txt new file mode 100644 index 000000000..752bbb7c5 --- /dev/null +++ b/_sources/advanced/mathematical_optimization/auto_examples/plot_constraints.rst.txt @@ -0,0 +1,142 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/mathematical_optimization/auto_examples/plot_constraints.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_mathematical_optimization_auto_examples_plot_constraints.py: + + +Constraint optimization: visualizing the geometry +================================================== + +A small figure explaining optimization with constraints + +.. GENERATED FROM PYTHON SOURCE LINES 7-66 + + + +.. rst-class:: sphx-glr-horizontal + + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_constraints_001.png + :alt: plot constraints + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_constraints_001.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_constraints_002.png + :alt: plot constraints + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_constraints_002.png + :class: sphx-glr-multi-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + import scipy as sp + + x, y = np.mgrid[-2.9:5.8:0.05, -2.5:5:0.05] # type: ignore[misc] + x = x.T + y = y.T + + for i in (1, 2): + # Create 2 figure: only the second one will have the optimization + # path + plt.figure(i, figsize=(3, 2.5)) + plt.clf() + plt.axes((0, 0, 1, 1)) + + contours = plt.contour( + np.sqrt((x - 3) ** 2 + (y - 2) ** 2), + extent=[-3, 6, -2.5, 5], + cmap="gnuplot", + ) + plt.clabel(contours, inline=1, fmt="%1.1f", fontsize=14) + plt.plot( + [-1.5, -1.5, 1.5, 1.5, -1.5], [-1.5, 1.5, 1.5, -1.5, -1.5], "k", linewidth=2 + ) + plt.fill_between([-1.5, 1.5], [-1.5, -1.5], [1.5, 1.5], color=".8") + plt.axvline(0, color="k") + plt.axhline(0, color="k") + + plt.text(-0.9, 4.4, "$x_2$", size=20) + plt.text(5.6, -0.6, "$x_1$", size=20) + plt.axis("equal") + plt.axis("off") + + # And now plot the optimization path + accumulator = [] + + + def f(x): + # Store the list of function calls + accumulator.append(x) + return np.sqrt((x[0] - 3) ** 2 + (x[1] - 2) ** 2) + + + # We don't use the gradient, as with the gradient, L-BFGS is too fast, + # and finds the optimum without showing us a pretty path + def f_prime(x): + r = np.sqrt((x[0] - 3) ** 2 + (x[0] - 2) ** 2) + return np.array(((x[0] - 3) / r, (x[0] - 2) / r)) + + + sp.optimize.minimize( + f, np.array([0, 0]), method="L-BFGS-B", bounds=((-1.5, 1.5), (-1.5, 1.5)) + ) + + accumulated = np.array(accumulator) + plt.plot(accumulated[:, 0], accumulated[:, 1]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.089 seconds) + + +.. _sphx_glr_download_advanced_mathematical_optimization_auto_examples_plot_constraints.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_constraints.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_constraints.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_constraints.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/mathematical_optimization/auto_examples/plot_convex.rst.txt b/_sources/advanced/mathematical_optimization/auto_examples/plot_convex.rst.txt new file mode 100644 index 000000000..a31f7e1b4 --- /dev/null +++ b/_sources/advanced/mathematical_optimization/auto_examples/plot_convex.rst.txt @@ -0,0 +1,122 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/mathematical_optimization/auto_examples/plot_convex.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_mathematical_optimization_auto_examples_plot_convex.py: + + +Convex function +================ + +A figure showing the definition of a convex function + +.. GENERATED FROM PYTHON SOURCE LINES 7-46 + + + +.. rst-class:: sphx-glr-horizontal + + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_convex_001.png + :alt: plot convex + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_convex_001.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_convex_002.png + :alt: plot convex + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_convex_002.png + :class: sphx-glr-multi-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + x = np.linspace(-1, 2) + + plt.figure(1, figsize=(3, 2.5)) + plt.clf() + + # A convex function + plt.plot(x, x**2, linewidth=2) + plt.text(-0.7, -(0.6**2), "$f$", size=20) + + # The tangent in one point + plt.plot(x, 2 * x - 1) + plt.plot(1, 1, "k+") + plt.text(0.3, -0.75, "Tangent to $f$", size=15) + plt.text(1, 1 - 0.5, "C", size=15) + + # Convexity as barycenter + plt.plot([0.35, 1.85], [0.35**2, 1.85**2]) + plt.plot([0.35, 1.85], [0.35**2, 1.85**2], "k+") + plt.text(0.35 - 0.2, 0.35**2 + 0.1, "A", size=15) + plt.text(1.85 - 0.2, 1.85**2, "B", size=15) + + plt.ylim(ymin=-1) + plt.axis("off") + plt.tight_layout() + + # Convexity as barycenter + plt.figure(2, figsize=(3, 2.5)) + plt.clf() + plt.plot(x, x**2 + np.exp(-5 * (x - 0.5) ** 2), linewidth=2) + plt.text(-0.7, -(0.6**2), "$f$", size=20) + + plt.ylim(ymin=-1) + plt.axis("off") + plt.tight_layout() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.047 seconds) + + +.. _sphx_glr_download_advanced_mathematical_optimization_auto_examples_plot_convex.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_convex.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_convex.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_convex.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/mathematical_optimization/auto_examples/plot_curve_fitting.rst.txt b/_sources/advanced/mathematical_optimization/auto_examples/plot_curve_fitting.rst.txt new file mode 100644 index 000000000..9ea62bf79 --- /dev/null +++ b/_sources/advanced/mathematical_optimization/auto_examples/plot_curve_fitting.rst.txt @@ -0,0 +1,100 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/mathematical_optimization/auto_examples/plot_curve_fitting.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_mathematical_optimization_auto_examples_plot_curve_fitting.py: + + +Curve fitting +============= + +A curve fitting example + +.. GENERATED FROM PYTHON SOURCE LINES 7-36 + + + +.. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_curve_fitting_001.png + :alt: plot curve fitting + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_curve_fitting_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + rng = np.random.default_rng(27446968) + + + # Our test function + def f(t, omega, phi): + return np.cos(omega * t + phi) + + + # Our x and y data + x = np.linspace(0, 3, 50) + y = f(x, 1.5, 1) + 0.1 * np.random.normal(size=50) + + # Fit the model: the parameters omega and phi can be found in the + # `params` vector + params, params_cov = sp.optimize.curve_fit(f, x, y) + + # plot the data and the fitted curve + t = np.linspace(0, 3, 1000) + + plt.figure(1) + plt.clf() + plt.plot(x, y, "bx") + plt.plot(t, f(t, *params), "r-") + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.053 seconds) + + +.. _sphx_glr_download_advanced_mathematical_optimization_auto_examples_plot_curve_fitting.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_curve_fitting.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_curve_fitting.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_curve_fitting.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/mathematical_optimization/auto_examples/plot_exercise_flat_minimum.rst.txt b/_sources/advanced/mathematical_optimization/auto_examples/plot_exercise_flat_minimum.rst.txt new file mode 100644 index 000000000..637e47a48 --- /dev/null +++ b/_sources/advanced/mathematical_optimization/auto_examples/plot_exercise_flat_minimum.rst.txt @@ -0,0 +1,154 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/mathematical_optimization/auto_examples/plot_exercise_flat_minimum.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_mathematical_optimization_auto_examples_plot_exercise_flat_minimum.py: + + +Finding a minimum in a flat neighborhood +========================================= + +An exercise of finding minimum. This exercise is hard because the +function is very flat around the minimum (all its derivatives are zero). +Thus gradient information is unreliable. + +The function admits a minimum in [0, 0]. The challenge is to get within +1e-7 of this minimum, starting at x0 = [1, 1]. + +The solution that we adopt here is to give up on using gradient or +information based on local differences, and to rely on the Powell +algorithm. With 162 function evaluations, we get to 1e-8 of the +solution. + +.. GENERATED FROM PYTHON SOURCE LINES 17-41 + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + + def f(x): + return np.exp(-1 / (0.01 * x[0] ** 2 + x[1] ** 2)) + + + # A well-conditionned version of f: + def g(x): + return f([10 * x[0], x[1]]) + + + # The gradient of g. We won't use it here for the optimization. + def g_prime(x): + r = np.sqrt(x[0] ** 2 + x[1] ** 2) + return 2 / r**3 * g(x) * x / r + + + result = sp.optimize.minimize(g, [1, 1], method="Powell", tol=1e-10) + x_min = result.x + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 42-43 + +Some pretty plotting + +.. GENERATED FROM PYTHON SOURCE LINES 43-65 + +.. code-block:: Python + + + plt.figure(0) + plt.clf() + t = np.linspace(-1.1, 1.1, 100) + plt.plot(t, f([0, t])) + + plt.figure(1) + plt.clf() + X, Y = np.mgrid[-1.5:1.5:100j, -1.1:1.1:100j] # type: ignore[misc] + plt.imshow(f([X, Y]).T, cmap="gray_r", extent=(-1.5, 1.5, -1.1, 1.1), origin="lower") + plt.contour(X, Y, f([X, Y]), cmap="gnuplot") + + # Plot the gradient + dX, dY = g_prime([0.1 * X[::5, ::5], Y[::5, ::5]]) + # Adjust for our preconditioning + dX *= 0.1 + plt.quiver(X[::5, ::5], Y[::5, ::5], dX, dY, color=".5") + + # Plot our solution + plt.plot(x_min[0], x_min[1], "r+", markersize=15) + + plt.show() + + + +.. rst-class:: sphx-glr-horizontal + + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_exercise_flat_minimum_001.png + :alt: plot exercise flat minimum + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_exercise_flat_minimum_001.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_exercise_flat_minimum_002.png + :alt: plot exercise flat minimum + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_exercise_flat_minimum_002.png + :class: sphx-glr-multi-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.117 seconds) + + +.. _sphx_glr_download_advanced_mathematical_optimization_auto_examples_plot_exercise_flat_minimum.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_exercise_flat_minimum.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_exercise_flat_minimum.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_exercise_flat_minimum.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/mathematical_optimization/auto_examples/plot_exercise_ill_conditioned.rst.txt b/_sources/advanced/mathematical_optimization/auto_examples/plot_exercise_ill_conditioned.rst.txt new file mode 100644 index 000000000..e58f6ccc0 --- /dev/null +++ b/_sources/advanced/mathematical_optimization/auto_examples/plot_exercise_ill_conditioned.rst.txt @@ -0,0 +1,178 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/mathematical_optimization/auto_examples/plot_exercise_ill_conditioned.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_mathematical_optimization_auto_examples_plot_exercise_ill_conditioned.py: + + +Alternating optimization +========================= + +The challenge here is that Hessian of the problem is a very +ill-conditioned matrix. This can easily be seen, as the Hessian of the +first term in simply 2 * K.T @ K. Thus the conditioning of the +problem can be judged from looking at the conditioning of K. + +.. GENERATED FROM PYTHON SOURCE LINES 10-35 + +.. code-block:: Python + + + import time + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + rng = np.random.default_rng(27446968) + + K = rng.normal(size=(100, 100)) + + + def f(x): + return np.sum((K @ (x - 1)) ** 2) + np.sum(x**2) ** 2 + + + def f_prime(x): + return 2 * K.T @ K @ (x - 1) + 4 * np.sum(x**2) * x + + + def hessian(x): + H = 2 * K.T @ K + 4 * 2 * x * x[:, np.newaxis] + return H + 4 * np.eye(H.shape[0]) * np.sum(x**2) + + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 36-37 + +Some pretty plotting + +.. GENERATED FROM PYTHON SOURCE LINES 37-90 + +.. code-block:: Python + + + plt.figure(1) + plt.clf() + Z = X, Y = np.mgrid[-1.5:1.5:100j, -1.1:1.1:100j] # type: ignore[misc] + # Complete in the additional dimensions with zeros + Z = np.reshape(Z, (2, -1)).copy() + Z.resize((100, Z.shape[-1])) + Z = np.apply_along_axis(f, 0, Z) + Z = np.reshape(Z, X.shape) + plt.imshow(Z.T, cmap="gray_r", extent=(-1.5, 1.5, -1.1, 1.1), origin="lower") + plt.contour(X, Y, Z, cmap="gnuplot") + + # A reference but slow solution: + t0 = time.time() + x_ref = sp.optimize.minimize(f, K[0], method="Powell").x + print(f" Powell: time {time.time() - t0:.2f}s") + f_ref = f(x_ref) + + # Compare different approaches + t0 = time.time() + x_bfgs = sp.optimize.minimize(f, K[0], method="BFGS").x + print( + f" BFGS: time {time.time() - t0:.2f}s, x error {np.sqrt(np.sum((x_bfgs - x_ref) ** 2)):.2f}, f error {f(x_bfgs) - f_ref:.2f}" + ) + + t0 = time.time() + x_l_bfgs = sp.optimize.minimize(f, K[0], method="L-BFGS-B").x + print( + f" L-BFGS: time {time.time() - t0:.2f}s, x error {np.sqrt(np.sum((x_l_bfgs - x_ref) ** 2)):.2f}, f error {f(x_l_bfgs) - f_ref:.2f}" + ) + + + t0 = time.time() + x_bfgs = sp.optimize.minimize(f, K[0], jac=f_prime, method="BFGS").x + print( + f" BFGS w f': time {time.time() - t0:.2f}s, x error {np.sqrt(np.sum((x_bfgs - x_ref) ** 2)):.2f}, f error {f(x_bfgs) - f_ref:.2f}" + ) + + t0 = time.time() + x_l_bfgs = sp.optimize.minimize(f, K[0], jac=f_prime, method="L-BFGS-B").x + print( + f"L-BFGS w f': time {time.time() - t0:.2f}s, x error {np.sqrt(np.sum((x_l_bfgs - x_ref) ** 2)):.2f}, f error {f(x_l_bfgs) - f_ref:.2f}" + ) + + t0 = time.time() + x_newton = sp.optimize.minimize( + f, K[0], jac=f_prime, hess=hessian, method="Newton-CG" + ).x + print( + f" Newton: time {time.time() - t0:.2f}s, x error {np.sqrt(np.sum((x_newton - x_ref) ** 2)):.2f}, f error {f(x_newton) - f_ref:.2f}" + ) + + plt.show() + + + +.. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_exercise_ill_conditioned_001.png + :alt: plot exercise ill conditioned + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_exercise_ill_conditioned_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + Powell: time 0.13s + BFGS: time 0.82s, x error 0.02, f error -0.03 + L-BFGS: time 0.06s, x error 0.02, f error -0.03 + BFGS w f': time 0.06s, x error 0.02, f error -0.03 + L-BFGS w f': time 0.00s, x error 0.02, f error -0.03 + Newton: time 0.00s, x error 0.02, f error -0.03 + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 1.296 seconds) + + +.. _sphx_glr_download_advanced_mathematical_optimization_auto_examples_plot_exercise_ill_conditioned.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_exercise_ill_conditioned.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_exercise_ill_conditioned.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_exercise_ill_conditioned.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/mathematical_optimization/auto_examples/plot_gradient_descent.rst.txt b/_sources/advanced/mathematical_optimization/auto_examples/plot_gradient_descent.rst.txt new file mode 100644 index 000000000..f82ae4262 --- /dev/null +++ b/_sources/advanced/mathematical_optimization/auto_examples/plot_gradient_descent.rst.txt @@ -0,0 +1,672 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/mathematical_optimization/auto_examples/plot_gradient_descent.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_mathematical_optimization_auto_examples_plot_gradient_descent.py: + + +Gradient descent +================== + +An example demoing gradient descent by creating figures that trace the +evolution of the optimizer. + +.. GENERATED FROM PYTHON SOURCE LINES 8-32 + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + import scipy as sp + + import collections + import sys + import os + + sys.path.append(os.path.abspath("helper")) + from cost_functions import ( + mk_quad, + mk_gauss, + rosenbrock, + rosenbrock_prime, + rosenbrock_hessian, + LoggingFunction, + CountingFunction, + ) + + x_min, x_max = -1, 2 + y_min, y_max = 2.25 / 3 * x_min - 0.2, 2.25 / 3 * x_max - 0.2 + + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 33-34 + +A formatter to print values on contours + +.. GENERATED FROM PYTHON SOURCE LINES 34-51 + +.. code-block:: Python + + def super_fmt(value): + if value > 1: + if np.abs(int(value) - value) < 0.1: + out = f"$10^{{{int(value):d}}}$" + else: + out = f"$10^{{{value:.1f}}}$" + else: + value = np.exp(value - 0.01) + if value > 0.1: + out = f"{value:1.1f}" + elif value > 0.01: + out = f"{value:.2f}" + else: + out = f"{value:.2e}" + return out + + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 52-54 + +A gradient descent algorithm +do not use: its a toy, use scipy's optimize.fmin_cg + +.. GENERATED FROM PYTHON SOURCE LINES 54-185 + +.. code-block:: Python + + + + def gradient_descent(x0, f, f_prime, hessian=None, adaptative=False): + x_i, y_i = x0 + all_x_i = [] + all_y_i = [] + all_f_i = [] + + for i in range(1, 100): + all_x_i.append(x_i) + all_y_i.append(y_i) + all_f_i.append(f([x_i, y_i])) + dx_i, dy_i = f_prime(np.asarray([x_i, y_i])) + if adaptative: + # Compute a step size using a line_search to satisfy the Wolf + # conditions + step = sp.optimize.line_search( + f, + f_prime, + np.r_[x_i, y_i], + -np.r_[dx_i, dy_i], + np.r_[dx_i, dy_i], + c2=0.05, + ) + step = step[0] + if step is None: + step = 0 + else: + step = 1 + x_i += -step * dx_i + y_i += -step * dy_i + if np.abs(all_f_i[-1]) < 1e-16: + break + return all_x_i, all_y_i, all_f_i + + + def gradient_descent_adaptative(x0, f, f_prime, hessian=None): + return gradient_descent(x0, f, f_prime, adaptative=True) + + + def conjugate_gradient(x0, f, f_prime, hessian=None): + all_x_i = [x0[0]] + all_y_i = [x0[1]] + all_f_i = [f(x0)] + + def store(X): + x, y = X + all_x_i.append(x) + all_y_i.append(y) + all_f_i.append(f(X)) + + sp.optimize.minimize( + f, x0, jac=f_prime, method="CG", callback=store, options={"gtol": 1e-12} + ) + return all_x_i, all_y_i, all_f_i + + + def newton_cg(x0, f, f_prime, hessian): + all_x_i = [x0[0]] + all_y_i = [x0[1]] + all_f_i = [f(x0)] + + def store(X): + x, y = X + all_x_i.append(x) + all_y_i.append(y) + all_f_i.append(f(X)) + + sp.optimize.minimize( + f, + x0, + method="Newton-CG", + jac=f_prime, + hess=hessian, + callback=store, + options={"xtol": 1e-12}, + ) + return all_x_i, all_y_i, all_f_i + + + def bfgs(x0, f, f_prime, hessian=None): + all_x_i = [x0[0]] + all_y_i = [x0[1]] + all_f_i = [f(x0)] + + def store(X): + x, y = X + all_x_i.append(x) + all_y_i.append(y) + all_f_i.append(f(X)) + + sp.optimize.minimize( + f, x0, method="BFGS", jac=f_prime, callback=store, options={"gtol": 1e-12} + ) + return all_x_i, all_y_i, all_f_i + + + def powell(x0, f, f_prime, hessian=None): + all_x_i = [x0[0]] + all_y_i = [x0[1]] + all_f_i = [f(x0)] + + def store(X): + x, y = X + all_x_i.append(x) + all_y_i.append(y) + all_f_i.append(f(X)) + + sp.optimize.minimize( + f, x0, method="Powell", callback=store, options={"ftol": 1e-12} + ) + return all_x_i, all_y_i, all_f_i + + + def nelder_mead(x0, f, f_prime, hessian=None): + all_x_i = [x0[0]] + all_y_i = [x0[1]] + all_f_i = [f(x0)] + + def store(X): + x, y = X + all_x_i.append(x) + all_y_i.append(y) + all_f_i.append(f(X)) + + sp.optimize.minimize( + f, x0, method="Nelder-Mead", callback=store, options={"ftol": 1e-12} + ) + return all_x_i, all_y_i, all_f_i + + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 186-187 + +Run different optimizers on these problems + +.. GENERATED FROM PYTHON SOURCE LINES 187-292 + +.. code-block:: Python + + levels = {} + + for index, ((f, f_prime, hessian), optimizer) in enumerate( + ( + (mk_quad(0.7), gradient_descent), + (mk_quad(0.7), gradient_descent_adaptative), + (mk_quad(0.02), gradient_descent), + (mk_quad(0.02), gradient_descent_adaptative), + (mk_gauss(0.02), gradient_descent_adaptative), + ( + (rosenbrock, rosenbrock_prime, rosenbrock_hessian), + gradient_descent_adaptative, + ), + (mk_gauss(0.02), conjugate_gradient), + ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), conjugate_gradient), + (mk_quad(0.02), newton_cg), + (mk_gauss(0.02), newton_cg), + ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), newton_cg), + (mk_quad(0.02), bfgs), + (mk_gauss(0.02), bfgs), + ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), bfgs), + (mk_quad(0.02), powell), + (mk_gauss(0.02), powell), + ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), powell), + (mk_gauss(0.02), nelder_mead), + ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), nelder_mead), + ) + ): + # Compute a gradient-descent + x_i, y_i = 1.6, 1.1 + counting_f_prime = CountingFunction(f_prime) + counting_hessian = CountingFunction(hessian) + logging_f = LoggingFunction(f, counter=counting_f_prime.counter) + all_x_i, all_y_i, all_f_i = optimizer( + np.array([x_i, y_i]), logging_f, counting_f_prime, hessian=counting_hessian + ) + + # Plot the contour plot + if not max(all_y_i) < y_max: + x_min *= 1.2 + x_max *= 1.2 + y_min *= 1.2 + y_max *= 1.2 + x, y = np.mgrid[x_min:x_max:100j, y_min:y_max:100j] + x = x.T + y = y.T + + plt.figure(index, figsize=(3, 2.5)) + plt.clf() + plt.axes([0, 0, 1, 1]) + + X = np.concatenate((x[np.newaxis, ...], y[np.newaxis, ...]), axis=0) + z = np.apply_along_axis(f, 0, X) + log_z = np.log(z + 0.01) + plt.imshow( + log_z, + extent=[x_min, x_max, y_min, y_max], + cmap=plt.cm.gray_r, + origin="lower", + vmax=log_z.min() + 1.5 * np.ptp(log_z), + ) + contours = plt.contour( + log_z, + levels=levels.get(f), + extent=[x_min, x_max, y_min, y_max], + cmap=plt.cm.gnuplot, + origin="lower", + ) + levels[f] = contours.levels + plt.clabel(contours, inline=1, fmt=super_fmt, fontsize=14) + + plt.plot(all_x_i, all_y_i, "b-", linewidth=2) + plt.plot(all_x_i, all_y_i, "k+") + + plt.plot(logging_f.all_x_i, logging_f.all_y_i, "k.", markersize=2) + + plt.plot([0], [0], "rx", markersize=12) + + plt.xticks(()) + plt.yticks(()) + plt.xlim(x_min, x_max) + plt.ylim(y_min, y_max) + plt.draw() + + plt.figure(index + 100, figsize=(4, 3)) + plt.clf() + plt.semilogy(np.maximum(np.abs(all_f_i), 1e-30), linewidth=2, label="# iterations") + plt.ylabel("Error on f(x)") + plt.semilogy( + logging_f.counts, + np.maximum(np.abs(logging_f.all_f_i), 1e-30), + linewidth=2, + color="g", + label="# function calls", + ) + plt.legend( + loc="upper right", + frameon=True, + prop={"size": 11}, + borderaxespad=0, + handlelength=1.5, + handletextpad=0.5, + ) + plt.tight_layout() + plt.draw() + + + +.. rst-class:: sphx-glr-horizontal + + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_001.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_001.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_002.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_002.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_003.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_003.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_004.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_004.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_005.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_005.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_006.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_006.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_007.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_007.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_008.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_008.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_009.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_009.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_010.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_010.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_011.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_011.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_012.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_012.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_013.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_013.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_014.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_014.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_015.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_015.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_016.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_016.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_017.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_017.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_018.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_018.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_019.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_019.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_020.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_020.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_021.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_021.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_022.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_022.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_023.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_023.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_024.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_024.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_025.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_025.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_026.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_026.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_027.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_027.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_028.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_028.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_029.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_029.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_030.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_030.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_031.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_031.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_032.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_032.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_033.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_033.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_034.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_034.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_035.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_035.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_036.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_036.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_037.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_037.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_038.png + :alt: plot gradient descent + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_gradient_descent_038.png + :class: sphx-glr-multi-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + /opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages/scipy/optimize/_linesearch.py:312: LineSearchWarning: The line search algorithm did not converge + alpha_star, phi_star, old_fval, derphi_star = scalar_search_wolfe2( + /home/runner/work/scientific-python-lectures/scientific-python-lectures/advanced/mathematical_optimization/examples/plot_gradient_descent.py:70: LineSearchWarning: The line search algorithm did not converge + step = sp.optimize.line_search( + /home/runner/work/scientific-python-lectures/scientific-python-lectures/advanced/mathematical_optimization/examples/plot_gradient_descent.py:234: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`). Consider using `matplotlib.pyplot.close()`. + plt.figure(index, figsize=(3, 2.5)) + /home/runner/work/scientific-python-lectures/scientific-python-lectures/advanced/mathematical_optimization/examples/plot_gradient_descent.py:179: OptimizeWarning: Unknown solver options: ftol + sp.optimize.minimize( + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 6.858 seconds) + + +.. _sphx_glr_download_advanced_mathematical_optimization_auto_examples_plot_gradient_descent.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_gradient_descent.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_gradient_descent.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_gradient_descent.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/mathematical_optimization/auto_examples/plot_noisy.rst.txt b/_sources/advanced/mathematical_optimization/auto_examples/plot_noisy.rst.txt new file mode 100644 index 000000000..e60038936 --- /dev/null +++ b/_sources/advanced/mathematical_optimization/auto_examples/plot_noisy.rst.txt @@ -0,0 +1,96 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/mathematical_optimization/auto_examples/plot_noisy.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_mathematical_optimization_auto_examples_plot_noisy.py: + + +Noisy optimization problem +=========================== + +Draws a figure explaining noisy vs non-noisy optimization + +.. GENERATED FROM PYTHON SOURCE LINES 7-32 + + + +.. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_noisy_001.png + :alt: plot noisy + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_noisy_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + rng = np.random.default_rng(27446968) + + x = np.linspace(-5, 5, 101) + x_ = np.linspace(-5, 5, 31) + + + def f(x): + return -np.exp(-(x**2)) + + + # A smooth function + plt.figure(1, figsize=(3, 2.5)) + plt.clf() + + plt.plot(x_, f(x_) + 0.2 * np.random.normal(size=31), linewidth=2) + plt.plot(x, f(x), linewidth=2) + + plt.ylim(ymin=-1.3) + plt.axis("off") + plt.tight_layout() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.017 seconds) + + +.. _sphx_glr_download_advanced_mathematical_optimization_auto_examples_plot_noisy.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_noisy.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_noisy.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_noisy.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/mathematical_optimization/auto_examples/plot_non_bounds_constraints.rst.txt b/_sources/advanced/mathematical_optimization/auto_examples/plot_non_bounds_constraints.rst.txt new file mode 100644 index 000000000..9679972ed --- /dev/null +++ b/_sources/advanced/mathematical_optimization/auto_examples/plot_non_bounds_constraints.rst.txt @@ -0,0 +1,123 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/mathematical_optimization/auto_examples/plot_non_bounds_constraints.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_mathematical_optimization_auto_examples_plot_non_bounds_constraints.py: + + +Optimization with constraints +================================ + +An example showing how to do optimization with general constraints using +SLSQP and cobyla. + +.. GENERATED FROM PYTHON SOURCE LINES 8-59 + + + +.. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_non_bounds_constraints_001.png + :alt: plot non bounds constraints + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_non_bounds_constraints_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + import scipy as sp + + x, y = np.mgrid[-2.03:4.2:0.04, -1.6:3.2:0.04] # type: ignore[misc] + x = x.T + y = y.T + + plt.figure(1, figsize=(3, 2.5)) + plt.clf() + plt.axes((0, 0, 1, 1)) + + contours = plt.contour( + np.sqrt((x - 3) ** 2 + (y - 2) ** 2), + extent=[-2.03, 4.2, -1.6, 3.2], + cmap="gnuplot", + ) + plt.clabel(contours, inline=1, fmt="%1.1f", fontsize=14) + plt.plot([-1.5, 0, 1.5, 0, -1.5], [0, 1.5, 0, -1.5, 0], "k", linewidth=2) + plt.fill_between([-1.5, 0, 1.5], [0, -1.5, 0], [0, 1.5, 0], color=".8") + plt.axvline(0, color="k") + plt.axhline(0, color="k") + + plt.text(-0.9, 2.8, "$x_2$", size=20) + plt.text(3.6, -0.6, "$x_1$", size=20) + plt.axis("tight") + plt.axis("off") + + # And now plot the optimization path + accumulator = [] + + + def f(x): + # Store the list of function calls + accumulator.append(x) + return np.sqrt((x[0] - 3) ** 2 + (x[1] - 2) ** 2) + + + def constraint(x): + return np.atleast_1d(1.5 - np.sum(np.abs(x))) + + + sp.optimize.minimize( + f, np.array([0, 0]), method="SLSQP", constraints={"fun": constraint, "type": "ineq"} + ) + + accumulated = np.array(accumulator) + plt.plot(accumulated[:, 0], accumulated[:, 1]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.049 seconds) + + +.. _sphx_glr_download_advanced_mathematical_optimization_auto_examples_plot_non_bounds_constraints.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_non_bounds_constraints.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_non_bounds_constraints.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_non_bounds_constraints.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/mathematical_optimization/auto_examples/plot_smooth.rst.txt b/_sources/advanced/mathematical_optimization/auto_examples/plot_smooth.rst.txt new file mode 100644 index 000000000..68044866d --- /dev/null +++ b/_sources/advanced/mathematical_optimization/auto_examples/plot_smooth.rst.txt @@ -0,0 +1,110 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "advanced/mathematical_optimization/auto_examples/plot_smooth.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_advanced_mathematical_optimization_auto_examples_plot_smooth.py: + + +Smooth vs non-smooth +===================== + +Draws a figure to explain smooth versus non smooth optimization. + +.. GENERATED FROM PYTHON SOURCE LINES 7-34 + + + +.. rst-class:: sphx-glr-horizontal + + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_smooth_001.png + :alt: plot smooth + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_smooth_001.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_smooth_002.png + :alt: plot smooth + :srcset: /advanced/mathematical_optimization/auto_examples/images/sphx_glr_plot_smooth_002.png + :class: sphx-glr-multi-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + x = np.linspace(-1.5, 1.5, 101) + + # A smooth function + plt.figure(1, figsize=(3, 2.5)) + plt.clf() + + plt.plot(x, np.sqrt(0.2 + x**2), linewidth=2) + plt.text(-1, 0, "$f$", size=20) + + plt.ylim(ymin=-0.2) + plt.axis("off") + plt.tight_layout() + + # A non-smooth function + plt.figure(2, figsize=(3, 2.5)) + plt.clf() + plt.plot(x, np.abs(x), linewidth=2) + plt.text(-1, 0, "$f$", size=20) + + plt.ylim(ymin=-0.2) + plt.axis("off") + plt.tight_layout() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.041 seconds) + + +.. _sphx_glr_download_advanced_mathematical_optimization_auto_examples_plot_smooth.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_smooth.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_smooth.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_smooth.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/advanced/mathematical_optimization/auto_examples/sg_execution_times.rst.txt b/_sources/advanced/mathematical_optimization/auto_examples/sg_execution_times.rst.txt new file mode 100644 index 000000000..4f09ecac2 --- /dev/null +++ b/_sources/advanced/mathematical_optimization/auto_examples/sg_execution_times.rst.txt @@ -0,0 +1,67 @@ + +:orphan: + +.. _sphx_glr_advanced_mathematical_optimization_auto_examples_sg_execution_times: + + +Computation times +================= +**00:09.366** total execution time for 11 files **from advanced/mathematical_optimization/auto_examples**: + +.. container:: + + .. raw:: html + + + + + + + + .. list-table:: + :header-rows: 1 + :class: table table-striped sg-datatable + + * - Example + - Time + - Mem (MB) + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_gradient_descent.py` (``plot_gradient_descent.py``) + - 00:06.858 + - 0.0 + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_exercise_ill_conditioned.py` (``plot_exercise_ill_conditioned.py``) + - 00:01.296 + - 0.0 + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_compare_optimizers.py` (``plot_compare_optimizers.py``) + - 00:00.569 + - 0.0 + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_1d_optim.py` (``plot_1d_optim.py``) + - 00:00.231 + - 0.0 + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_exercise_flat_minimum.py` (``plot_exercise_flat_minimum.py``) + - 00:00.117 + - 0.0 + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_constraints.py` (``plot_constraints.py``) + - 00:00.089 + - 0.0 + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_curve_fitting.py` (``plot_curve_fitting.py``) + - 00:00.053 + - 0.0 + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_non_bounds_constraints.py` (``plot_non_bounds_constraints.py``) + - 00:00.049 + - 0.0 + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_convex.py` (``plot_convex.py``) + - 00:00.047 + - 0.0 + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_smooth.py` (``plot_smooth.py``) + - 00:00.041 + - 0.0 + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_noisy.py` (``plot_noisy.py``) + - 00:00.017 + - 0.0 diff --git a/_sources/advanced/mathematical_optimization/index.rst.txt b/_sources/advanced/mathematical_optimization/index.rst.txt new file mode 100644 index 000000000..eab149559 --- /dev/null +++ b/_sources/advanced/mathematical_optimization/index.rst.txt @@ -0,0 +1,1044 @@ +.. + For doctesting + >>> import numpy as np + +.. _mathematical_optimization: + +======================================================= +Mathematical optimization: finding minima of functions +======================================================= + +**Authors**: *Gaël Varoquaux* + +`Mathematical optimization +`_ deals with the +problem of finding numerically minimums (or maximums or zeros) of +a function. In this context, the function is called *cost function*, or +*objective function*, or *energy*. + +Here, we are interested in using :mod:`scipy.optimize` for black-box +optimization: we do not rely on the mathematical expression of the +function that we are optimizing. Note that this expression can often be +used for more efficient, non black-box, optimization. + +.. topic:: Prerequisites + + .. rst-class:: horizontal + + * :ref:`NumPy ` + * :ref:`SciPy ` + * :ref:`Matplotlib ` + +.. seealso:: **References** + + Mathematical optimization is very ... mathematical. If you want + performance, it really pays to read the books: + + * `Convex Optimization `_ + by Boyd and Vandenberghe (pdf available free online). + + * `Numerical Optimization + `_, + by Nocedal and Wright. Detailed reference on gradient descent methods. + + * `Practical Methods of Optimization + `_ by Fletcher: good at hand-waving explanations. + +.. include:: ../../includes/big_toc_css.rst + :start-line: 1 + + +.. contents:: Chapters contents + :local: + :depth: 2 + +.. XXX: should I discuss root finding? + + +Knowing your problem +====================== + +Not all optimization problems are equal. Knowing your problem enables you +to choose the right tool. + +.. topic:: **Dimensionality of the problem** + + The scale of an optimization problem is pretty much set by the + *dimensionality of the problem*, i.e. the number of scalar variables + on which the search is performed. + +Convex versus non-convex optimization +--------------------------------------- + +.. |convex_1d_1| image:: auto_examples/images/sphx_glr_plot_convex_001.png + +.. |convex_1d_2| image:: auto_examples/images/sphx_glr_plot_convex_002.png + +.. list-table:: + + * - |convex_1d_1| + + - |convex_1d_2| + + * - **A convex function**: + + - `f` is above all its tangents. + - equivalently, for two point A, B, f(C) lies below the segment + [f(A), f(B])], if A < C < B + + - **A non-convex function** + +**Optimizing convex functions is easy. Optimizing non-convex functions can +be very hard.** + +.. note:: It can be proven that for a convex function a local minimum is + also a global minimum. Then, in some sense, the minimum is unique. + +Smooth and non-smooth problems +------------------------------- + +.. |smooth_1d_1| image:: auto_examples/images/sphx_glr_plot_smooth_001.png + +.. |smooth_1d_2| image:: auto_examples/images/sphx_glr_plot_smooth_002.png + +.. list-table:: + + * - |smooth_1d_1| + + - |smooth_1d_2| + + * - **A smooth function**: + + The gradient is defined everywhere, and is a continuous function + + - **A non-smooth function** + +**Optimizing smooth functions is easier** +(true in the context of *black-box* optimization, otherwise +`Linear Programming `_ +is an example of methods which deal very efficiently with +piece-wise linear functions). + + + +Noisy versus exact cost functions +---------------------------------- + +.. |noisy| image:: auto_examples/images/sphx_glr_plot_noisy_001.png + +.. list-table:: + + * - Noisy (blue) and non-noisy (green) functions + + - |noisy| + +.. topic:: **Noisy gradients** + + Many optimization methods rely on gradients of the objective function. + If the gradient function is not given, they are computed numerically, + which induces errors. In such situation, even if the objective + function is not noisy, a gradient-based optimization may be a noisy + optimization. + +Constraints +------------ + +.. |constraints| image:: auto_examples/images/sphx_glr_plot_constraints_001.png + :target: auto_examples/plot_constraints.html + +.. list-table:: + + * - Optimizations under constraints + + Here: + + :math:`-1 < x_1 < 1` + + :math:`-1 < x_2 < 1` + + - |constraints| + + +A review of the different optimizers +====================================== + +Getting started: 1D optimization +--------------------------------- + +Let's get started by finding the minimum of the scalar function +:math:`f(x)=\exp[(x-0.5)^2]`. :func:`scipy.optimize.minimize_scalar` uses +Brent's method to find the minimum of a function: + +:: + + >>> import numpy as np + >>> import scipy as sp + >>> def f(x): + ... return -np.exp(-(x - 0.5)**2) + >>> result = sp.optimize.minimize_scalar(f) + >>> result.success # check if solver was successful + True + >>> x_min = result.x + >>> x_min + np.float64(0.50...) + >>> x_min - 0.5 + np.float64(5.8...e-09) + + +.. |1d_optim_1| image:: auto_examples/images/sphx_glr_plot_1d_optim_001.png + :scale: 90% + +.. |1d_optim_2| image:: auto_examples/images/sphx_glr_plot_1d_optim_002.png + :scale: 75% + +.. |1d_optim_3| image:: auto_examples/images/sphx_glr_plot_1d_optim_003.png + :scale: 90% + +.. |1d_optim_4| image:: auto_examples/images/sphx_glr_plot_1d_optim_004.png + :scale: 75% + +.. list-table:: **Brent's method on a quadratic function**: it + converges in 3 iterations, as the quadratic + approximation is then exact. + + * - |1d_optim_1| + + - |1d_optim_2| + +.. list-table:: **Brent's method on a non-convex function**: note that + the fact that the optimizer avoided the local minimum + is a matter of luck. + + * - |1d_optim_3| + + - |1d_optim_4| + +.. note:: + + You can use different solvers using the parameter ``method``. + +.. note:: + + :func:`scipy.optimize.minimize_scalar` can also be used for optimization + constrained to an interval using the parameter ``bounds``. + +Gradient based methods +----------------------- + +Some intuitions about gradient descent +....................................... + +Here we focus on **intuitions**, not code. Code will follow. + +`Gradient descent `_ +basically consists in taking small steps in the direction of the +gradient, that is the direction of the *steepest descent*. + +.. |gradient_quad_cond| image:: auto_examples/images/sphx_glr_plot_gradient_descent_001.png + :scale: 90% + +.. |gradient_quad_cond_conv| image:: auto_examples/images/sphx_glr_plot_gradient_descent_020.png + :scale: 75% + +.. |gradient_quad_icond| image:: auto_examples/images/sphx_glr_plot_gradient_descent_003.png + :scale: 90% + +.. |gradient_quad_icond_conv| image:: auto_examples/images/sphx_glr_plot_gradient_descent_022.png + :scale: 75% + +.. list-table:: **Fixed step gradient descent** + :widths: 1 1 1 + + * - **A well-conditioned quadratic function.** + + - |gradient_quad_cond| + + - |gradient_quad_cond_conv| + + * - **An ill-conditioned quadratic function.** + + The core problem of gradient-methods on ill-conditioned problems is + that the gradient tends not to point in the direction of the + minimum. + + - |gradient_quad_icond| + + - |gradient_quad_icond_conv| + +We can see that very anisotropic (`ill-conditioned +`_) functions are harder +to optimize. + +.. topic:: **Take home message: conditioning number and preconditioning** + + If you know natural scaling for your variables, prescale them so that + they behave similarly. This is related to `preconditioning + `_. + +Also, it clearly can be advantageous to take bigger steps. This +is done in gradient descent code using a +`line search `_. + +.. |agradient_quad_cond| image:: auto_examples/images/sphx_glr_plot_gradient_descent_002.png + :scale: 90% + +.. |agradient_quad_cond_conv| image:: auto_examples/images/sphx_glr_plot_gradient_descent_021.png + :scale: 75% + +.. |agradient_quad_icond| image:: auto_examples/images/sphx_glr_plot_gradient_descent_004.png + :scale: 90% + +.. |agradient_quad_icond_conv| image:: auto_examples/images/sphx_glr_plot_gradient_descent_023.png + :scale: 75% + +.. |agradient_gauss_icond| image:: auto_examples/images/sphx_glr_plot_gradient_descent_005.png + :scale: 90% + +.. |agradient_gauss_icond_conv| image:: auto_examples/images/sphx_glr_plot_gradient_descent_024.png + :scale: 75% + +.. |agradient_rosen_icond| image:: auto_examples/images/sphx_glr_plot_gradient_descent_006.png + :scale: 90% + +.. |agradient_rosen_icond_conv| image:: auto_examples/images/sphx_glr_plot_gradient_descent_025.png + :scale: 75% + + +.. list-table:: **Adaptive step gradient descent** + :widths: 1 1 1 + + * - A well-conditioned quadratic function. + + - |agradient_quad_cond| + + - |agradient_quad_cond_conv| + + * - An ill-conditioned quadratic function. + + - |agradient_quad_icond| + + - |agradient_quad_icond_conv| + + * - An ill-conditioned non-quadratic function. + + - |agradient_gauss_icond| + + - |agradient_gauss_icond_conv| + + * - An ill-conditioned very non-quadratic function. + + - |agradient_rosen_icond| + + - |agradient_rosen_icond_conv| + +The more a function looks like a quadratic function (elliptic +iso-curves), the easier it is to optimize. + +Conjugate gradient descent +........................... + +The gradient descent algorithms above are toys not to be used on real +problems. + +As can be seen from the above experiments, one of the problems of the +simple gradient descent algorithms, is that it tends to oscillate across +a valley, each time following the direction of the gradient, that makes +it cross the valley. The conjugate gradient solves this problem by adding +a *friction* term: each step depends on the two last values of the +gradient and sharp turns are reduced. + +.. |cg_gauss_icond| image:: auto_examples/images/sphx_glr_plot_gradient_descent_007.png + :scale: 90% + +.. |cg_gauss_icond_conv| image:: auto_examples/images/sphx_glr_plot_gradient_descent_026.png + :scale: 75% + +.. |cg_rosen_icond| image:: auto_examples/images/sphx_glr_plot_gradient_descent_008.png + :scale: 90% + +.. |cg_rosen_icond_conv| image:: auto_examples/images/sphx_glr_plot_gradient_descent_027.png + :scale: 75% + + +.. list-table:: **Conjugate gradient descent** + :widths: 1 1 1 + + * - An ill-conditioned non-quadratic function. + + - |cg_gauss_icond| + + - |cg_gauss_icond_conv| + + * - An ill-conditioned very non-quadratic function. + + - |cg_rosen_icond| + + - |cg_rosen_icond_conv| + +SciPy provides :func:`scipy.optimize.minimize` to find the minimum of scalar +functions of one or more variables. The simple conjugate gradient method can +be used by setting the parameter ``method`` to CG :: + + >>> def f(x): # The rosenbrock function + ... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2 + >>> sp.optimize.minimize(f, [2, -1], method="CG") + message: Optimization terminated successfully. + success: True + status: 0 + fun: 1.650...e-11 + x: [ 1.000e+00 1.000e+00] + nit: 13 + jac: [-6.15...e-06 2.53...e-07] + nfev: 81 + njev: 27 + +Gradient methods need the Jacobian (gradient) of the function. They can compute it +numerically, but will perform better if you can pass them the gradient:: + + >>> def jacobian(x): + ... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] - x[0]**2))) + >>> sp.optimize.minimize(f, [2, 1], method="CG", jac=jacobian) + message: Optimization terminated successfully. + success: True + status: 0 + fun: 2.95786...e-14 + x: [ 1.000e+00 1.000e+00] + nit: 8 + jac: [ 7.183e-07 -2.990e-07] + nfev: 16 + njev: 16 + +Note that the function has only been evaluated 27 times, compared to 108 +without the gradient. + +Newton and quasi-newton methods +-------------------------------- + +Newton methods: using the Hessian (2nd differential) +..................................................... + +`Newton methods +`_ use a +local quadratic approximation to compute the jump direction. For this +purpose, they rely on the 2 first derivative of the function: the +*gradient* and the `Hessian +`_. + +.. |ncg_quad_icond| image:: auto_examples/images/sphx_glr_plot_gradient_descent_009.png + :scale: 90% + +.. |ncg_quad_icond_conv| image:: auto_examples/images/sphx_glr_plot_gradient_descent_028.png + :scale: 75% + +.. |ncg_gauss_icond| image:: auto_examples/images/sphx_glr_plot_gradient_descent_010.png + :scale: 90% + +.. |ncg_gauss_icond_conv| image:: auto_examples/images/sphx_glr_plot_gradient_descent_029.png + :scale: 75% + +.. |ncg_rosen_icond| image:: auto_examples/images/sphx_glr_plot_gradient_descent_011.png + :scale: 90% + +.. |ncg_rosen_icond_conv| image:: auto_examples/images/sphx_glr_plot_gradient_descent_030.png + :scale: 75% + + +.. list-table:: + :widths: 1 1 1 + + * - **An ill-conditioned quadratic function:** + + Note that, as the quadratic approximation is exact, the Newton + method is blazing fast + + - |ncg_quad_icond| + + - |ncg_quad_icond_conv| + + * - **An ill-conditioned non-quadratic function:** + + Here we are optimizing a Gaussian, which is always below its + quadratic approximation. As a result, the Newton method overshoots + and leads to oscillations. + + - |ncg_gauss_icond| + + - |ncg_gauss_icond_conv| + + * - **An ill-conditioned very non-quadratic function:** + + - |ncg_rosen_icond| + + - |ncg_rosen_icond_conv| + +In SciPy, you can use the Newton method by setting ``method`` to Newton-CG in +:func:`scipy.optimize.minimize`. Here, CG refers to the fact that an internal +inversion of the Hessian is performed by conjugate gradient :: + + >>> def f(x): # The rosenbrock function + ... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2 + >>> def jacobian(x): + ... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] - x[0]**2))) + >>> sp.optimize.minimize(f, [2,-1], method="Newton-CG", jac=jacobian) + message: Optimization terminated successfully. + success: True + status: 0 + fun: 1.5601357400786612e-15 + x: [ 1.000e+00 1.000e+00] + nit: 10 + jac: [ 1.058e-07 -7.483e-08] + nfev: 11 + njev: 33 + nhev: 0 + +Note that compared to a conjugate gradient (above), Newton's method has +required less function evaluations, but more gradient evaluations, as it +uses it to approximate the Hessian. Let's compute the Hessian and pass it +to the algorithm:: + + >>> def hessian(x): # Computed with sympy + ... return np.array(((1 - 4*x[1] + 12*x[0]**2, -4*x[0]), (-4*x[0], 2))) + >>> sp.optimize.minimize(f, [2,-1], method="Newton-CG", jac=jacobian, hess=hessian) + message: Optimization terminated successfully. + success: True + status: 0 + fun: 1.6277298383706738e-15 + x: [ 1.000e+00 1.000e+00] + nit: 10 + jac: [ 1.110e-07 -7.781e-08] + nfev: 11 + njev: 11 + nhev: 10 + +.. note:: + + At very high-dimension, the inversion of the Hessian can be costly + and unstable (large scale > 250). + +.. note:: + + Newton optimizers should not to be confused with Newton's root finding + method, based on the same principles, :func:`scipy.optimize.newton`. + +.. _quasi_newton: + +Quasi-Newton methods: approximating the Hessian on the fly +........................................................... + +**BFGS**: BFGS (Broyden-Fletcher-Goldfarb-Shanno algorithm) refines at +each step an approximation of the Hessian. + +.. |bfgs_quad_icond| image:: auto_examples/images/sphx_glr_plot_gradient_descent_012.png + :scale: 90% + +.. |bfgs_quad_icond_conv| image:: auto_examples/images/sphx_glr_plot_gradient_descent_031.png + :scale: 75% + +.. |bfgs_gauss_icond| image:: auto_examples/images/sphx_glr_plot_gradient_descent_013.png + :scale: 90% + +.. |bfgs_gauss_icond_conv| image:: auto_examples/images/sphx_glr_plot_gradient_descent_032.png + :scale: 75% + +Full code examples +================== + +.. include the gallery. Skip the first line to avoid the "orphan" + declaration + +.. include:: auto_examples/index.rst + :start-line: 1 + + +.. |bfgs_rosen_icond| image:: auto_examples/images/sphx_glr_plot_gradient_descent_014.png + :scale: 90% + +.. |bfgs_rosen_icond_conv| image:: auto_examples/images/sphx_glr_plot_gradient_descent_033.png + :scale: 75% + + +.. list-table:: + :widths: 1 1 1 + + * - **An ill-conditioned quadratic function:** + + On a exactly quadratic function, BFGS is not as fast as Newton's + method, but still very fast. + + - |bfgs_quad_icond| + + - |bfgs_quad_icond_conv| + + * - **An ill-conditioned non-quadratic function:** + + Here BFGS does better than Newton, as its empirical estimate of the + curvature is better than that given by the Hessian. + + - |bfgs_gauss_icond| + + - |bfgs_gauss_icond_conv| + + * - **An ill-conditioned very non-quadratic function:** + + - |bfgs_rosen_icond| + + - |bfgs_rosen_icond_conv| + +:: + + >>> def f(x): # The rosenbrock function + ... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2 + >>> def jacobian(x): + ... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] - x[0]**2))) + >>> sp.optimize.minimize(f, [2, -1], method="BFGS", jac=jacobian) + message: Optimization terminated successfully. + success: True + status: 0 + fun: 2.630637192365927e-16 + x: [ 1.000e+00 1.000e+00] + nit: 8 + jac: [ 6.709e-08 -3.222e-08] + hess_inv: [[ 9.999e-01 2.000e+00] + [ 2.000e+00 4.499e+00]] + nfev: 10 + njev: 10 + +**L-BFGS:** Limited-memory BFGS Sits between BFGS and conjugate gradient: +in very high dimensions (> 250) the Hessian matrix is too costly to +compute and invert. L-BFGS keeps a low-rank version. In addition, box bounds +are also supported by L-BFGS-B:: + + >>> def f(x): # The rosenbrock function + ... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2 + >>> def jacobian(x): + ... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] - x[0]**2))) + >>> sp.optimize.minimize(f, [2, 2], method="L-BFGS-B", jac=jacobian) + message: CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL + success: True + status: 0 + fun: 1.4417677473...e-15 + x: [ 1.000e+00 1.000e+00] + nit: 16 + jac: [ 1.023e-07 -2.593e-08] + nfev: 17 + njev: 17 + hess_inv: <2x2 LbfgsInvHessProduct with dtype=float64> + +Gradient-less methods +---------------------- + +A shooting method: the Powell algorithm +........................................ + +Almost a gradient approach + +.. |powell_quad_icond| image:: auto_examples/images/sphx_glr_plot_gradient_descent_015.png + :scale: 90% + +.. |powell_quad_icond_conv| image:: auto_examples/images/sphx_glr_plot_gradient_descent_034.png + :scale: 75% + +.. |powell_gauss_icond| image:: auto_examples/images/sphx_glr_plot_gradient_descent_016.png + :scale: 90% + +.. |powell_gauss_icond_conv| image:: auto_examples/images/sphx_glr_plot_gradient_descent_035.png + :scale: 75% + + +.. |powell_rosen_icond| image:: auto_examples/images/sphx_glr_plot_gradient_descent_017.png + :scale: 90% + +.. |powell_rosen_icond_conv| image:: auto_examples/images/sphx_glr_plot_gradient_descent_036.png + :scale: 75% + + +.. list-table:: + :widths: 1 1 1 + + * - **An ill-conditioned quadratic function:** + + Powell's method isn't too sensitive to local ill-conditionning in + low dimensions + + - |powell_quad_icond| + + - |powell_quad_icond_conv| + + * - **An ill-conditioned very non-quadratic function:** + + - |powell_rosen_icond| + + - |powell_rosen_icond_conv| + + +Simplex method: the Nelder-Mead +................................ + +The Nelder-Mead algorithms is a generalization of dichotomy approaches to +high-dimensional spaces. The algorithm works by refining a `simplex +`_, the generalization of intervals +and triangles to high-dimensional spaces, to bracket the minimum. + +**Strong points**: it is robust to noise, as it does not rely on +computing gradients. Thus it can work on functions that are not locally +smooth such as experimental data points, as long as they display a +large-scale bell-shape behavior. However it is slower than gradient-based +methods on smooth, non-noisy functions. + +.. |nm_gauss_icond| image:: auto_examples/images/sphx_glr_plot_gradient_descent_018.png + :scale: 90% + +.. |nm_gauss_icond_conv| image:: auto_examples/images/sphx_glr_plot_gradient_descent_037.png + :scale: 75% + + +.. |nm_rosen_icond| image:: auto_examples/images/sphx_glr_plot_gradient_descent_019.png + :scale: 90% + +.. |nm_rosen_icond_conv| image:: auto_examples/images/sphx_glr_plot_gradient_descent_038.png + :scale: 75% + + +.. list-table:: + :widths: 1 1 1 + + * - **An ill-conditioned non-quadratic function:** + + - |nm_gauss_icond| + + - |nm_gauss_icond_conv| + + * - **An ill-conditioned very non-quadratic function:** + + - |nm_rosen_icond| + + - |nm_rosen_icond_conv| + +Using the Nelder-Mead solver in :func:`scipy.optimize.minimize`:: + + >>> def f(x): # The rosenbrock function + ... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2 + >>> sp.optimize.minimize(f, [2, -1], method="Nelder-Mead") + message: Optimization terminated successfully. + success: True + status: 0 + fun: 1.11527915993744e-10 + x: [ 1.000e+00 1.000e+00] + nit: 58 + nfev: 111 + final_simplex: (array([[ 1.000e+00, 1.000e+00], + [ 1.000e+00, 1.000e+00], + [ 1.000e+00, 1.000e+00]]), array([ 1.115e-10, 1.537e-10, 4.988e-10])) + +Global optimizers +------------------ + +If your problem does not admit a unique local minimum (which can be hard +to test unless the function is convex), and you do not have prior +information to initialize the optimization close to the solution, you +may need a global optimizer. + +Brute force: a grid search +.......................... + +:func:`scipy.optimize.brute` evaluates the function on a given grid of +parameters and returns the parameters corresponding to the minimum +value. The parameters are specified with ranges given to +:obj:`numpy.mgrid`. By default, 20 steps are taken in each direction:: + + >>> def f(x): # The rosenbrock function + ... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2 + >>> sp.optimize.brute(f, ((-1, 2), (-1, 2))) # doctest: +ELLIPSIS + array([1.0000..., 1.0000...]) + + +Practical guide to optimization with SciPy +========================================== + +Choosing a method +------------------ + +All methods are exposed as the ``method`` argument of +:func:`scipy.optimize.minimize`. + +.. image:: auto_examples/images/sphx_glr_plot_compare_optimizers_001.png + :align: center + :width: 95% + +:Without knowledge of the gradient: + + * In general, prefer **BFGS** or **L-BFGS**, even if you have to approximate + numerically gradients. These are also the default if you omit the parameter + ``method`` - depending if the problem has constraints or bounds + + * On well-conditioned problems, **Powell** + and **Nelder-Mead**, both gradient-free methods, work well in + high dimension, but they collapse for ill-conditioned problems. + +:With knowledge of the gradient: + + * **BFGS** or **L-BFGS**. + + * Computational overhead of BFGS is larger than that L-BFGS, itself + larger than that of conjugate gradient. On the other side, BFGS usually + needs less function evaluations than CG. Thus conjugate gradient method + is better than BFGS at optimizing computationally cheap functions. + +:With the Hessian: + + * If you can compute the Hessian, prefer the Newton method + (**Newton-CG** or **TCG**). + +:If you have noisy measurements: + + * Use **Nelder-Mead** or **Powell**. + +Making your optimizer faster +----------------------------- + +* Choose the right method (see above), do compute analytically the + gradient and Hessian, if you can. + +* Use `preconditionning `_ + when possible. + +* Choose your initialization points wisely. For instance, if you are + running many similar optimizations, warm-restart one with the results of + another. + +* Relax the tolerance if you don't need precision using the parameter ``tol``. + +Computing gradients +------------------- + +Computing gradients, and even more Hessians, is very tedious but worth +the effort. Symbolic computation with :ref:`Sympy ` may come in +handy. + +.. warning:: + + A *very* common source of optimization not converging well is human + error in the computation of the gradient. You can use + :func:`scipy.optimize.check_grad` to check that your gradient is + correct. It returns the norm of the different between the gradient + given, and a gradient computed numerically: + + >>> sp.optimize.check_grad(f, jacobian, [2, -1]) + np.float64(2.384185791015625e-07) + + See also :func:`scipy.optimize.approx_fprime` to find your errors. + +Synthetic exercises +------------------- + +.. |flat_min_0| image:: auto_examples/images/sphx_glr_plot_exercise_flat_minimum_001.png + :scale: 48% + :target: auto_examples/plot_exercise_flat_minimum.html + +.. |flat_min_1| image:: auto_examples/images/sphx_glr_plot_exercise_flat_minimum_002.png + :scale: 48% + :target: auto_examples/plot_exercise_flat_minimum.html + +.. image:: auto_examples/images/sphx_glr_plot_exercise_ill_conditioned_001.png + :scale: 35% + :target: auto_examples/plot_exercise_ill_conditioned.html + :align: right + +.. topic:: **Exercise: A simple (?) quadratic function** + :class: green + + Optimize the following function, using K[0] as a starting point:: + + rng = np.random.default_rng(27446968) + K = rng.normal(size=(100, 100)) + + def f(x): + return np.sum((K @ (x - 1))**2) + np.sum(x**2)**2 + + Time your approach. Find the fastest approach. Why is BFGS not + working well? + +.. topic:: **Exercise: A locally flat minimum** + :class: green + + Consider the function `exp(-1/(.1*x**2 + y**2)`. This function admits + a minimum in (0, 0). Starting from an initialization at (1, 1), try + to get within 1e-8 of this minimum point. + + .. centered:: |flat_min_0| |flat_min_1| + + +Special case: non-linear least-squares +======================================== + +Minimizing the norm of a vector function +------------------------------------------- + +Least square problems, minimizing the norm of a vector function, have a +specific structure that can be used in the `Levenberg–Marquardt algorithm +`_ +implemented in :func:`scipy.optimize.leastsq`. + +Lets try to minimize the norm of the following vectorial function:: + + >>> def f(x): + ... return np.arctan(x) - np.arctan(np.linspace(0, 1, len(x))) + + >>> x0 = np.zeros(10) + >>> sp.optimize.leastsq(f, x0) + (array([0. , 0.11111111, 0.22222222, 0.33333333, 0.44444444, + 0.55555556, 0.66666667, 0.77777778, 0.88888889, 1. ]), 2) + +This took 67 function evaluations (check it with 'full_output=1'). What +if we compute the norm ourselves and use a good generic optimizer +(BFGS):: + + >>> def g(x): + ... return np.sum(f(x)**2) + >>> result = sp.optimize.minimize(g, x0, method="BFGS") + >>> result.fun + np.float64(2.6940...e-11) + +BFGS needs more function calls, and gives a less precise result. + +.. note:: + + `leastsq` is interesting compared to BFGS only if the + dimensionality of the output vector is large, and larger than the number + of parameters to optimize. + +.. warning:: + + If the function is linear, this is a linear-algebra problem, and + should be solved with :func:`scipy.linalg.lstsq`. + +Curve fitting +-------------- + +.. image:: auto_examples/images/sphx_glr_plot_curve_fitting_001.png + :scale: 48% + :target: auto_examples/plot_curve_fitting.html + :align: right + +Least square problems occur often when fitting a non-linear to data. +While it is possible to construct our optimization problem ourselves, +SciPy provides a helper function for this purpose: +:func:`scipy.optimize.curve_fit`:: + + + >>> def f(t, omega, phi): + ... return np.cos(omega * t + phi) + + >>> x = np.linspace(0, 3, 50) + >>> rng = np.random.default_rng(27446968) + >>> y = f(x, 1.5, 1) + .1*rng.normal(size=50) + + >>> sp.optimize.curve_fit(f, x, y) + (array([1.4812..., 0.9999...]), array([[ 0.0003..., -0.0004...], + [-0.0004..., 0.0010...]])) + + +.. topic:: **Exercise** + :class: green + + Do the same with omega = 3. What is the difficulty? + +Optimization with constraints +============================== + +Box bounds +---------- + +Box bounds correspond to limiting each of the individual parameters of +the optimization. Note that some problems that are not originally written +as box bounds can be rewritten as such via change of variables. Both +:func:`scipy.optimize.minimize_scalar` and :func:`scipy.optimize.minimize` +support bound constraints with the parameter ``bounds``:: + + >>> def f(x): + ... return np.sqrt((x[0] - 3)**2 + (x[1] - 2)**2) + >>> sp.optimize.minimize(f, np.array([0, 0]), bounds=((-1.5, 1.5), (-1.5, 1.5))) + message: CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL + success: True + status: 0 + fun: 1.5811388300841898 + x: [ 1.500e+00 1.500e+00] + nit: 2 + jac: [-9.487e-01 -3.162e-01] + nfev: 9 + njev: 3 + hess_inv: <2x2 LbfgsInvHessProduct with dtype=float64> + +.. image:: auto_examples/images/sphx_glr_plot_constraints_002.png + :target: auto_examples/plot_constraints.html + :align: right + :scale: 75% + + +General constraints +-------------------- + +Equality and inequality constraints specified as functions: :math:`f(x) = 0` +and :math:`g(x) < 0`. + +* :func:`scipy.optimize.fmin_slsqp` Sequential least square programming: + equality and inequality constraints: + + .. image:: auto_examples/images/sphx_glr_plot_non_bounds_constraints_001.png + :target: auto_examples/plot_non_bounds_constraints.html + :align: right + :scale: 75% + + :: + + >>> def f(x): + ... return np.sqrt((x[0] - 3)**2 + (x[1] - 2)**2) + + >>> def constraint(x): + ... return np.atleast_1d(1.5 - np.sum(np.abs(x))) + + >>> x0 = np.array([0, 0]) + >>> sp.optimize.minimize(f, x0, constraints={"fun": constraint, "type": "ineq"}) + message: Optimization terminated successfully + success: True + status: 0 + fun: 2.47487373504... + x: [ 1.250e+00 2.500e-01] + nit: 5 + jac: [-7.071e-01 -7.071e-01] + nfev: 15 + njev: 5 + +.. warning:: + + The above problem is known as the `Lasso + `_ + problem in statistics, and there exist very efficient solvers for it + (for instance in `scikit-learn `_). In + general do not use generic solvers when specific ones exist. + +.. topic:: **Lagrange multipliers** + + If you are ready to do a bit of math, many constrained optimization + problems can be converted to non-constrained optimization problems + using a mathematical trick known as `Lagrange multipliers + `_. + +Full code examples +================== + +.. include the gallery. Skip the first line to avoid the "orphan" + declaration + +.. include:: auto_examples/index.rst + :start-line: 1 + +.. seealso:: **Other Software** + + SciPy tries to include the best well-established, general-use, + and permissively-licensed optimization algorithms available. However, + even better options for a given task may be available in other libraries; + please also see IPOPT_ and PyGMO_. + +.. _IPOPT: https://github.com/xuy/pyipopt +.. _PyGMO: https://esa.github.io/pygmo2/ diff --git a/_sources/advanced/optimizing/index.rst.txt b/_sources/advanced/optimizing/index.rst.txt new file mode 100644 index 000000000..3d0b73304 --- /dev/null +++ b/_sources/advanced/optimizing/index.rst.txt @@ -0,0 +1,441 @@ +.. _optimizing_code_chapter: + +================= +Optimizing code +================= + +.. sidebar:: Donald Knuth + + *“Premature optimization is the root of all evil”* + +**Author**: *Gaël Varoquaux* + +This chapter deals with strategies to make Python code go faster. + +.. topic:: Prerequisites + + * `line_profiler `_ + +.. contents:: Chapters contents + :local: + :depth: 4 + + +Optimization workflow +====================== + +#. Make it work: write the code in a simple **legible** ways. + +#. Make it work reliably: write automated test cases, make really sure + that your algorithm is right and that if you break it, the tests will + capture the breakage. + +#. Optimize the code by profiling simple use-cases to find the + bottlenecks and speeding up these bottleneck, finding a better + algorithm or implementation. Keep in mind that a trade off should be + found between profiling on a realistic example and the simplicity and + speed of execution of the code. For efficient work, it is best to work + with profiling runs lasting around 10s. + + +Profiling Python code +===================== + +.. topic:: **No optimization without measuring!** + + * **Measure:** profiling, timing + + * You'll have surprises: the fastest code is not always what you + think + + +Timeit +--------- + +In IPython, use ``timeit`` (https://docs.python.org/3/library/timeit.html) to time elementary operations: + +.. ipython:: + + In [1]: import numpy as np + + In [2]: a = np.arange(1000) + + In [3]: %timeit a ** 2 + 100000 loops, best of 3: 5.73 us per loop + + In [4]: %timeit a ** 2.1 + 1000 loops, best of 3: 154 us per loop + + In [5]: %timeit a * a + 100000 loops, best of 3: 5.56 us per loop + +Use this to guide your choice between strategies. + +.. note:: + + For long running calls, using ``%time`` instead of ``%timeit``; it is + less precise but faster + +Profiler +----------- + +Useful when you have a large program to profile, for example the +:download:`following file `: + +.. literalinclude:: demo.py + + +.. note:: + This is a combination of two unsupervised learning techniques, principal + component analysis (`PCA + `_) and + independent component analysis + (`ICA `_). PCA + is a technique for dimensionality reduction, i.e. an algorithm to explain + the observed variance in your data using less dimensions. ICA is a source + separation technique, for example to unmix multiple signals that have been + recorded through multiple sensors. Doing a PCA first and then an ICA can be + useful if you have more sensors than signals. For more information see: + `the FastICA example from scikits-learn `_. + +To run it, you also need to download the :download:`ica module `. +In IPython we can time the script: + +.. ipython:: + :verbatim: + + In [1]: %run -t demo.py + IPython CPU timings (estimated): + User : 14.3929 s. + System: 0.256016 s. + +and profile it: + +.. ipython:: + :verbatim: + + In [2]: %run -p demo.py + 916 function calls in 14.551 CPU seconds + Ordered by: internal time + ncalls tottime percall cumtime percall filename:lineno (function) + 1 14.457 14.457 14.479 14.479 decomp.py:849 (svd) + 1 0.054 0.054 0.054 0.054 {method 'random_sample' of 'mtrand.RandomState' objects} + 1 0.017 0.017 0.021 0.021 function_base.py:645 (asarray_chkfinite) + 54 0.011 0.000 0.011 0.000 {numpy.core._dotblas.dot} + 2 0.005 0.002 0.005 0.002 {method 'any' of 'numpy.ndarray' objects} + 6 0.001 0.000 0.001 0.000 ica.py:195 (gprime) + 6 0.001 0.000 0.001 0.000 ica.py:192 (g) + 14 0.001 0.000 0.001 0.000 {numpy.linalg.lapack_lite.dsyevd} + 19 0.001 0.000 0.001 0.000 twodim_base.py:204 (diag) + 1 0.001 0.001 0.008 0.008 ica.py:69 (_ica_par) + 1 0.001 0.001 14.551 14.551 {execfile} + 107 0.000 0.000 0.001 0.000 defmatrix.py:239 (__array_finalize__) + 7 0.000 0.000 0.004 0.001 ica.py:58 (_sym_decorrelation) + 7 0.000 0.000 0.002 0.000 linalg.py:841 (eigh) + 172 0.000 0.000 0.000 0.000 {isinstance} + 1 0.000 0.000 14.551 14.551 demo.py:1 () + 29 0.000 0.000 0.000 0.000 numeric.py:180 (asarray) + 35 0.000 0.000 0.000 0.000 defmatrix.py:193 (__new__) + 35 0.000 0.000 0.001 0.000 defmatrix.py:43 (asmatrix) + 21 0.000 0.000 0.001 0.000 defmatrix.py:287 (__mul__) + 41 0.000 0.000 0.000 0.000 {numpy.core.multiarray.zeros} + 28 0.000 0.000 0.000 0.000 {method 'transpose' of 'numpy.ndarray' objects} + 1 0.000 0.000 0.008 0.008 ica.py:97 (fastica) + ... + +Clearly the ``svd`` (in `decomp.py`) is what takes most of our time, a.k.a. the +bottleneck. We have to find a way to make this step go faster, or to avoid this +step (algorithmic optimization). Spending time on the rest of the code is +useless. + +.. topic:: **Profiling outside of IPython, running ``cProfile``** + + Similar profiling can be done outside of IPython, simply calling the + built-in `Python profilers + `_ ``cProfile`` and + ``profile``. + + .. sourcecode:: console + + $ python -m cProfile -o demo.prof demo.py + + Using the ``-o`` switch will output the profiler results to the file + ``demo.prof`` to view with an external tool. This can be useful if + you wish to process the profiler output with a visualization tool. + + +Line-profiler +-------------- + +The profiler tells us which function takes most of the time, but not +where it is called. + +For this, we use the +`line_profiler `_: in the +source file, we decorate a few functions that we want to inspect with +``@profile`` (no need to import it) + +.. sourcecode:: python + + @profile + def test(): + rng = np.random.default_rng() + data = rng.random((5000, 100)) + u, s, v = linalg.svd(data) + pca = u[:, :10] @ data + results = fastica(pca.T, whiten=False) + +Then we run the script using the `kernprof +`_ command, with switches ``-l, --line-by-line`` and ``-v, --view`` to use the line-by-line profiler and view the results in addition to saving them: + +.. sourcecode:: console + + $ kernprof -l -v demo.py + + Wrote profile results to demo.py.lprof + Timer unit: 1e-06 s + + Total time: 1.27874 s + File: demo.py + Function: test at line 9 + + Line # Hits Time Per Hit % Time Line Contents + ============================================================== + 9 @profile + 10 def test(): + 11 1 69.0 69.0 0.0 rng = np.random.default_rng() + 12 1 2453.0 2453.0 0.2 data = rng.random((5000, 100)) + 13 1 1274715.0 1274715.0 99.7 u, s, v = sp.linalg.svd(data) + 14 1 413.0 413.0 0.0 pca = u[:, :10].T @ data + 15 1 1094.0 1094.0 0.1 results = fastica(pca.T, whiten=False) + +**The SVD is taking all the time.** We need to optimise this line. + + +Making code go faster +====================== + +Once we have identified the bottlenecks, we need to make the +corresponding code go faster. + +Algorithmic optimization +------------------------- + +The first thing to look for is algorithmic optimization: are there ways +to compute less, or better? + +For a high-level view of the problem, a good understanding of the maths +behind the algorithm helps. However, it is not uncommon to find simple +changes, like **moving computation or memory allocation outside a for +loop**, that bring in big gains. + +Example of the SVD +................... + +In both examples above, the SVD - +`Singular Value Decomposition `_ +- is what +takes most of the time. Indeed, the computational cost of this algorithm is +roughly :math:`n^3` in the size of the input matrix. + +However, in both of these example, we are not using all the output of +the SVD, but only the first few rows of its first return argument. If +we use the ``svd`` implementation of SciPy, we can ask for an incomplete +version of the SVD. Note that implementations of linear algebra in +SciPy are richer then those in NumPy and should be preferred. + +.. ipython:: + :verbatim: + + In [3]: %timeit np.linalg.svd(data) + 1 loops, best of 3: 14.5 s per loop + + In [4]: import scipy as sp + + In [5]: %timeit sp.linalg.svd(data) + 1 loops, best of 3: 14.2 s per loop + + In [6]: %timeit sp.linalg.svd(data, full_matrices=False) + 1 loops, best of 3: 295 ms per loop + + In [7]: %timeit np.linalg.svd(data, full_matrices=False) + 1 loops, best of 3: 293 ms per loop + +We can then use this insight to :download:`optimize the previous code `: + +.. literalinclude:: demo_opt.py + :pyobject: test + +.. ipython:: + :verbatim: + + In [1]: import demo + + In [2]: %timeit demo. + demo.fastica demo.np demo.prof.pdf demo.py demo.pyc + demo.linalg demo.prof demo.prof.png demo.py.lprof demo.test + + In [2]: %timeit demo.test() + ica.py:65: RuntimeWarning: invalid value encountered in sqrt + W = (u * np.diag(1.0/np.sqrt(s)) * u.T) * W # W = (W * W.T) ^{-1/2} * W + 1 loops, best of 3: 17.5 s per loop + + In [3]: import demo_opt + + In [4]: %timeit demo_opt.test() + 1 loops, best of 3: 208 ms per loop + +Real incomplete SVDs, e.g. computing only the first 10 eigenvectors, can +be computed with arpack, available in ``scipy.sparse.linalg.eigsh``. + +.. topic:: Computational linear algebra + + For certain algorithms, many of the bottlenecks will be linear + algebra computations. In this case, using the right function to solve + the right problem is key. For instance, an eigenvalue problem with a + symmetric matrix is easier to solve than with a general matrix. Also, + most often, you can avoid inverting a matrix and use a less costly + (and more numerically stable) operation. + + Know your computational linear algebra. When in doubt, explore + ``scipy.linalg``, and use ``%timeit`` to try out different alternatives + on your data. + +Writing faster numerical code +=============================== + +A complete discussion on advanced use of NumPy is found in chapter +:ref:`advanced_numpy`, or in the article `The NumPy array: a structure +for efficient numerical computation +`_ +by van der Walt et al. Here we +discuss only some commonly encountered tricks to make code faster. + +* **Vectorizing for loops** + + Find tricks to avoid for loops using NumPy arrays. For this, masks and + indices arrays can be useful. + +* **Broadcasting** + + Use :ref:`broadcasting ` to do operations on arrays as + small as possible before combining them. + +.. XXX: complement broadcasting in the NumPy chapter with the example of + the 3D grid + +* **In place operations** + + .. ipython:: + :verbatim: + + In [1]: a = np.zeros(1e7) + + In [2]: %timeit global a ; a = 0*a + 10 loops, best of 3: 111 ms per loop + + In [3]: %timeit global a ; a *= 0 + 10 loops, best of 3: 48.4 ms per loop + + **note**: we need `global a` in the timeit so that it work, as it is + assigning to `a`, and thus considers it as a local variable. + +* **Be easy on the memory: use views, and not copies** + + Copying big arrays is as costly as making simple numerical operations + on them: + + .. ipython:: + :verbatim: + + In [1]: a = np.zeros(1e7) + + In [2]: %timeit a.copy() + 10 loops, best of 3: 124 ms per loop + + In [3]: %timeit a + 1 + 10 loops, best of 3: 112 ms per loop + +* **Beware of cache effects** + + Memory access is cheaper when it is grouped: accessing a big array in a + continuous way is much faster than random access. This implies amongst + other things that **smaller strides are faster** (see + :ref:`cache_effects`): + + .. ipython:: + :verbatim: + + In [1]: c = np.zeros((1e4, 1e4), order='C') + + In [2]: %timeit c.sum(axis=0) + 1 loops, best of 3: 3.89 s per loop + + In [3]: %timeit c.sum(axis=1) + 1 loops, best of 3: 188 ms per loop + + In [4]: c.strides + Out[4]: (80000, 8) + + This is the reason why Fortran ordering or C ordering may make a big + difference on operations: + + .. ipython:: + + In [5]: rng = np.random.default_rng() + + In [6]: a = rng.random((20, 2**18)) + + In [7]: b = rng.random((20, 2**18)) + + In [8]: %timeit b @ a.T + 1 loops, best of 3: 194 ms per loop + + In [9]: c = np.ascontiguousarray(a.T) + + In [10]: %timeit b @ c + 10 loops, best of 3: 84.2 ms per loop + + Note that copying the data to work around this effect may not be worth it: + + .. ipython:: + + In [11]: %timeit c = np.ascontiguousarray(a.T) + 10 loops, best of 3: 106 ms per loop + + Using `numexpr `_ can be useful to + automatically optimize code for such effects. + +* **Use compiled code** + + The last resort, once you are sure that all the high-level + optimizations have been explored, is to transfer the hot spots, i.e. + the few lines or functions in which most of the time is spent, to + compiled code. For compiled code, the preferred option is to use + `Cython `_: it is easy to transform exiting + Python code in compiled code, and with a good use of the + `NumPy support `_ + yields efficient code on NumPy arrays, for instance by unrolling loops. + +.. warning:: + + For all the above: profile and time your choices. Don't base your + optimization on theoretical considerations. + +Additional Links +---------------- + +* If you need to profile memory usage, you could try the `memory_profiler + `_ + +* If you need to profile down into C extensions, you could try using + `gperftools `_ + from Python with + `yep `_. + +* If you would like to track performance of your code across time, i.e. as you + make new commits to your repository, you could try: + `asv `_ + +* If you need some interactive visualization why not try `RunSnakeRun + `_ diff --git a/_sources/advanced/scipy_sparse/bsr_array.rst.txt b/_sources/advanced/scipy_sparse/bsr_array.rst.txt new file mode 100644 index 000000000..a01d26436 --- /dev/null +++ b/_sources/advanced/scipy_sparse/bsr_array.rst.txt @@ -0,0 +1,118 @@ +.. For doctests + >>> import numpy as np + >>> import scipy as sp + + +Block Compressed Row Format (BSR) +================================= + +* basically a CSR with dense sub-matrices of fixed shape instead of scalar items + * block size `(R, C)` must evenly divide the shape of the matrix `(M, N)` + * three NumPy arrays: `indices`, `indptr`, `data` + * `indices` is array of column indices for each block + * `data` is array of corresponding nonzero values of shape `(nnz, R, C)` + * ... + * subclass of :class:`_cs_matrix` (common CSR/CSC functionality) + * subclass of :class:`_data_matrix` (sparse matrix classes with + `.data` attribute) +* fast matrix vector products and other arithmetic (sparsetools) +* constructor accepts: + * dense array/matrix + * sparse array/matrix + * shape tuple (create empty array) + * `(data, coords)` tuple + * `(data, indices, indptr)` tuple +* many arithmetic operations considerably more efficient than CSR for + sparse matrices with dense sub-matrices +* use: + * like CSR + * vector-valued finite element discretizations + +Examples +-------- + +* create empty BSR array with (1, 1) block size (like CSR...):: + + >>> mtx = sp.sparse.bsr_array((3, 4), dtype=np.int8) + >>> mtx + + >>> mtx.toarray() + array([[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]], dtype=int8) + +* create empty BSR array with (3, 2) block size:: + + >>> mtx = sp.sparse.bsr_array((3, 4), blocksize=(3, 2), dtype=np.int8) + >>> mtx + + >>> mtx.toarray() + array([[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]], dtype=int8) + + * a bug? + +* create using `(data, coords)` tuple with (1, 1) block size (like CSR...):: + + >>> row = np.array([0, 0, 1, 2, 2, 2]) + >>> col = np.array([0, 2, 2, 0, 1, 2]) + >>> data = np.array([1, 2, 3, 4, 5, 6]) + >>> mtx = sp.sparse.bsr_array((data, (row, col)), shape=(3, 3)) + >>> mtx + + >>> mtx.toarray() + array([[1, 0, 2], + [0, 0, 3], + [4, 5, 6]]...) + >>> mtx.data + array([[[1]], + + [[2]], + + [[3]], + + [[4]], + + [[5]], + + [[6]]]...) + >>> mtx.indices + array([0, 2, 2, 0, 1, 2]) + >>> mtx.indptr + array([0, 2, 3, 6]) + +* create using `(data, indices, indptr)` tuple with (2, 2) block size:: + + >>> indptr = np.array([0, 2, 3, 6]) + >>> indices = np.array([0, 2, 2, 0, 1, 2]) + >>> data = np.array([1, 2, 3, 4, 5, 6]).repeat(4).reshape(6, 2, 2) + >>> mtx = sp.sparse.bsr_array((data, indices, indptr), shape=(6, 6)) + >>> mtx.toarray() + array([[1, 1, 0, 0, 2, 2], + [1, 1, 0, 0, 2, 2], + [0, 0, 0, 0, 3, 3], + [0, 0, 0, 0, 3, 3], + [4, 4, 5, 5, 6, 6], + [4, 4, 5, 5, 6, 6]]) + >>> data + array([[[1, 1], + [1, 1]], + + [[2, 2], + [2, 2]], + + [[3, 3], + [3, 3]], + + [[4, 4], + [4, 4]], + + [[5, 5], + [5, 5]], + + [[6, 6], + [6, 6]]]) diff --git a/_sources/advanced/scipy_sparse/coo_array.rst.txt b/_sources/advanced/scipy_sparse/coo_array.rst.txt new file mode 100644 index 000000000..595178eaf --- /dev/null +++ b/_sources/advanced/scipy_sparse/coo_array.rst.txt @@ -0,0 +1,77 @@ +.. for doctests + >>> import numpy as np + >>> import scipy as sp + + +Coordinate Format (COO) +======================= + +* also known as the 'ijv' or 'triplet' format + * three NumPy arrays: `row`, `col`, `data`. + * attribute `coords` is the tuple `(row, col)` + * `data[i]` is value at `(row[i], col[i])` position + * permits duplicate entries + * subclass of :class:`_data_matrix` (sparse matrix classes with + `.data` attribute) +* fast format for constructing sparse arrays +* constructor accepts: + * dense array/matrix + * sparse array/matrix + * shape tuple (create empty matrix) + * `(data, coords)` tuple +* very fast conversion to and from CSR/CSC formats +* fast matrix * vector (sparsetools) +* fast and easy item-wise operations + * manipulate data array directly (fast NumPy machinery) +* no slicing, no arithmetic (directly, converts to CSR) +* use: + * facilitates fast conversion among sparse formats + * when converting to other format (usually CSR or CSC), duplicate + entries are summed together + + * facilitates efficient construction of finite element matrices + +Examples +-------- + +* create empty COO array:: + + >>> mtx = sp.sparse.coo_array((3, 4), dtype=np.int8) + >>> mtx.toarray() + array([[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]], dtype=int8) + +* create using `(data, ij)` tuple:: + + >>> row = np.array([0, 3, 1, 0]) + >>> col = np.array([0, 3, 1, 2]) + >>> data = np.array([4, 5, 7, 9]) + >>> mtx = sp.sparse.coo_array((data, (row, col)), shape=(4, 4)) + >>> mtx + + >>> mtx.toarray() + array([[4, 0, 9, 0], + [0, 7, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 5]]) + +* duplicates entries are summed together:: + + >>> row = np.array([0, 0, 1, 3, 1, 0, 0]) + >>> col = np.array([0, 2, 1, 3, 1, 0, 0]) + >>> data = np.array([1, 1, 1, 1, 1, 1, 1]) + >>> mtx = sp.sparse.coo_array((data, (row, col)), shape=(4, 4)) + >>> mtx.toarray() + array([[3, 0, 1, 0], + [0, 2, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 1]]) + +* no slicing...:: + + >>> mtx[2, 3] + Traceback (most recent call last): + ... + TypeError: 'coo_array' object ... diff --git a/_sources/advanced/scipy_sparse/csc_array.rst.txt b/_sources/advanced/scipy_sparse/csc_array.rst.txt new file mode 100644 index 000000000..3b709733c --- /dev/null +++ b/_sources/advanced/scipy_sparse/csc_array.rst.txt @@ -0,0 +1,75 @@ +.. For doctests + >>> import numpy as np + >>> import scipy as sp + + +Compressed Sparse Column Format (CSC) +===================================== + +* column oriented + * three NumPy arrays: `indices`, `indptr`, `data` + * `indices` is array of row indices + * `data` is array of corresponding nonzero values + * `indptr` points to column starts in `indices` and `data` + * length is `n_col + 1`, last item = number of values = length of both + `indices` and `data` + * nonzero values of the `i`-th column are `data[indptr[i]:indptr[i+1]]` + with row indices `indices[indptr[i]:indptr[i+1]]` + * item `(i, j)` can be accessed as `data[indptr[j]+k]`, where `k` is + position of `i` in `indices[indptr[j]:indptr[j+1]]` + * subclass of :class:`_cs_matrix` (common CSR/CSC functionality) + * subclass of :class:`_data_matrix` (sparse array classes with + `.data` attribute) +* fast matrix vector products and other arithmetic (sparsetools) +* constructor accepts: + * dense array/matrix + * sparse array/matrix + * shape tuple (create empty array) + * `(data, coords)` tuple + * `(data, indices, indptr)` tuple +* efficient column slicing, column-oriented operations +* slow row slicing, expensive changes to the sparsity structure +* use: + * actual computations (most linear solvers support this format) + +Examples +-------- + +* create empty CSC array:: + + >>> mtx = sp.sparse.csc_array((3, 4), dtype=np.int8) + >>> mtx.toarray() + array([[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]], dtype=int8) + +* create using `(data, coords)` tuple:: + + >>> row = np.array([0, 0, 1, 2, 2, 2]) + >>> col = np.array([0, 2, 2, 0, 1, 2]) + >>> data = np.array([1, 2, 3, 4, 5, 6]) + >>> mtx = sp.sparse.csc_array((data, (row, col)), shape=(3, 3)) + >>> mtx + + >>> mtx.toarray() + array([[1, 0, 2], + [0, 0, 3], + [4, 5, 6]]...) + >>> mtx.data + array([1, 4, 5, 2, 3, 6]...) + >>> mtx.indices + array([0, 2, 2, 0, 1, 2]) + >>> mtx.indptr + array([0, 2, 3, 6]) + +* create using `(data, indices, indptr)` tuple:: + + >>> data = np.array([1, 4, 5, 2, 3, 6]) + >>> indices = np.array([0, 2, 2, 0, 1, 2]) + >>> indptr = np.array([0, 2, 3, 6]) + >>> mtx = sp.sparse.csc_array((data, indices, indptr), shape=(3, 3)) + >>> mtx.toarray() + array([[1, 0, 2], + [0, 0, 3], + [4, 5, 6]]) diff --git a/_sources/advanced/scipy_sparse/csr_array.rst.txt b/_sources/advanced/scipy_sparse/csr_array.rst.txt new file mode 100644 index 000000000..f8d997b3e --- /dev/null +++ b/_sources/advanced/scipy_sparse/csr_array.rst.txt @@ -0,0 +1,74 @@ +.. for doctests + >>> import numpy as np + >>> import scipy as sp + +Compressed Sparse Row Format (CSR) +================================== + +* row oriented + * three NumPy arrays: `indices`, `indptr`, `data` + * `indices` is array of column indices + * `data` is array of corresponding nonzero values + * `indptr` points to row starts in `indices` and `data` + * length of `indptr` is `n_row + 1`, + last item = number of values = length of both `indices` and `data` + * nonzero values of the `i`-th row are `data[indptr[i]:indptr[i + 1]]` + with column indices `indices[indptr[i]:indptr[i + 1]]` + * item `(i, j)` can be accessed as `data[indptr[i] + k]`, where `k` is + position of `j` in `indices[indptr[i]:indptr[i + 1]]` + * subclass of :class:`_cs_matrix` (common CSR/CSC functionality) + * subclass of :class:`_data_matrix` (sparse array classes with + `.data` attribute) +* fast matrix vector products and other arithmetic (sparsetools) +* constructor accepts: + * dense array/matrix + * sparse array/matrix + * shape tuple (create empty array) + * `(data, coords)` tuple + * `(data, indices, indptr)` tuple +* efficient row slicing, row-oriented operations +* slow column slicing, expensive changes to the sparsity structure +* use: + * actual computations (most linear solvers support this format) + +Examples +-------- + +* create empty CSR array:: + + >>> mtx = sp.sparse.csr_array((3, 4), dtype=np.int8) + >>> mtx.toarray() + array([[0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]], dtype=int8) + +* create using `(data, coords)` tuple:: + + >>> row = np.array([0, 0, 1, 2, 2, 2]) + >>> col = np.array([0, 2, 2, 0, 1, 2]) + >>> data = np.array([1, 2, 3, 4, 5, 6]) + >>> mtx = sp.sparse.csr_array((data, (row, col)), shape=(3, 3)) + >>> mtx + + >>> mtx.toarray() + array([[1, 0, 2], + [0, 0, 3], + [4, 5, 6]]...) + >>> mtx.data + array([1, 2, 3, 4, 5, 6]...) + >>> mtx.indices + array([0, 2, 2, 0, 1, 2]) + >>> mtx.indptr + array([0, 2, 3, 6]) + +* create using `(data, indices, indptr)` tuple:: + + >>> data = np.array([1, 2, 3, 4, 5, 6]) + >>> indices = np.array([0, 2, 2, 0, 1, 2]) + >>> indptr = np.array([0, 2, 3, 6]) + >>> mtx = sp.sparse.csr_array((data, indices, indptr), shape=(3, 3)) + >>> mtx.toarray() + array([[1, 0, 2], + [0, 0, 3], + [4, 5, 6]]) diff --git a/_sources/advanced/scipy_sparse/dia_array.rst.txt b/_sources/advanced/scipy_sparse/dia_array.rst.txt new file mode 100644 index 000000000..1afc79193 --- /dev/null +++ b/_sources/advanced/scipy_sparse/dia_array.rst.txt @@ -0,0 +1,107 @@ +.. for doctests + >>> import numpy as np + >>> import scipy as sp + + +Diagonal Format (DIA) +===================== + +* very simple scheme +* diagonals in dense NumPy array of shape `(n_diag, length)` + * fixed length -> waste space a bit when far from main diagonal + * subclass of :class:`_data_matrix` (sparse array classes with + `.data` attribute) +* offset for each diagonal + * 0 is the main diagonal + * negative offset = below + * positive offset = above +* fast matrix * vector (sparsetools) +* fast and easy item-wise operations + * manipulate data array directly (fast NumPy machinery) +* constructor accepts: + * dense array/matrix + * sparse array/matrix + * shape tuple (create empty array) + * `(data, offsets)` tuple +* no slicing, no individual item access +* use: + * rather specialized + * solving PDEs by finite differences + * with an iterative solver + +Examples +-------- + +* create some DIA arrays:: + + >>> data = np.array([[1, 2, 3, 4]]).repeat(3, axis=0) + >>> data + array([[1, 2, 3, 4], + [1, 2, 3, 4], + [1, 2, 3, 4]]) + >>> offsets = np.array([0, -1, 2]) + >>> mtx = sp.sparse.dia_array((data, offsets), shape=(4, 4)) + >>> mtx + + >>> mtx.toarray() + array([[1, 0, 3, 0], + [1, 2, 0, 4], + [0, 2, 3, 0], + [0, 0, 3, 4]]) + + >>> data = np.arange(12).reshape((3, 4)) + 1 + >>> data + array([[ 1, 2, 3, 4], + [ 5, 6, 7, 8], + [ 9, 10, 11, 12]]) + >>> mtx = sp.sparse.dia_array((data, offsets), shape=(4, 4)) + >>> mtx.data + array([[ 1, 2, 3, 4], + [ 5, 6, 7, 8], + [ 9, 10, 11, 12]]) + >>> mtx.offsets + array([ 0, -1, 2], dtype=int32) + >>> print(mtx) + + Coords Values + (0, 0) 1 + (1, 1) 2 + (2, 2) 3 + (3, 3) 4 + (1, 0) 5 + (2, 1) 6 + (3, 2) 7 + (0, 2) 11 + (1, 3) 12 + >>> mtx.toarray() + array([[ 1, 0, 11, 0], + [ 5, 2, 0, 12], + [ 0, 6, 3, 0], + [ 0, 0, 7, 4]]) + +* explanation with a scheme:: + + offset: row + + 2: 9 + 1: --10------ + 0: 1 . 11 . + -1: 5 2 . 12 + -2: . 6 3 . + -3: . . 7 4 + ---------8 + +* matrix-vector multiplication + + >>> vec = np.ones((4, )) + >>> vec + array([1., 1., 1., 1.]) + >>> mtx @ vec + array([12., 19., 9., 11.]) + >>> (mtx * vec).toarray() + array([[ 1., 0., 11., 0.], + [ 5., 2., 0., 12.], + [ 0., 6., 3., 0.], + [ 0., 0., 7., 4.]]) diff --git a/_sources/advanced/scipy_sparse/dok_array.rst.txt b/_sources/advanced/scipy_sparse/dok_array.rst.txt new file mode 100644 index 000000000..fb1a90a1f --- /dev/null +++ b/_sources/advanced/scipy_sparse/dok_array.rst.txt @@ -0,0 +1,57 @@ +.. For doctests + >>> import numpy as np + >>> import scipy as sp + + +Dictionary of Keys Format (DOK) +=============================== + +* subclass of Python dict + * keys are `(row, column)` index tuples (no duplicate entries allowed) + * values are corresponding non-zero values +* efficient for constructing sparse arrays incrementally +* constructor accepts: + * dense array/matrix + * sparse array/matrix + * shape tuple (create empty array) +* efficient O(1) access to individual elements +* flexible slicing, changing sparsity structure is efficient +* can be efficiently converted to a coo_array once constructed +* slow arithmetic (`for` loops with `dict.items()`) +* use: + * when sparsity pattern is not known apriori or changes + +Examples +-------- + +* create a DOK array element by element:: + + >>> mtx = sp.sparse.dok_array((5, 5), dtype=np.float64) + >>> mtx + + >>> for ir in range(5): + ... for ic in range(5): + ... mtx[ir, ic] = 1.0 * (ir != ic) + >>> mtx + + >>> mtx.toarray() + array([[0., 1., 1., 1., 1.], + [1., 0., 1., 1., 1.], + [1., 1., 0., 1., 1.], + [1., 1., 1., 0., 1.], + [1., 1., 1., 1., 0.]]) + +* slicing and indexing:: + + >>> mtx[1, 1] + np.float64(0.0) + >>> mtx[[1], 1:3] + + >>> mtx[[1], 1:3].toarray() + array([[0., 1.]]) + >>> mtx[[2, 1], 1:3].toarray() + array([[1., 0.], + [0., 1.]]) diff --git a/_sources/advanced/scipy_sparse/index.rst.txt b/_sources/advanced/scipy_sparse/index.rst.txt new file mode 100644 index 000000000..dd449b245 --- /dev/null +++ b/_sources/advanced/scipy_sparse/index.rst.txt @@ -0,0 +1,14 @@ +Sparse Arrays in SciPy +====================== + +**Author**: *Robert Cimrman* + +| + +.. toctree:: + :maxdepth: 3 + + introduction + storage_schemes + solvers + other_packages diff --git a/_sources/advanced/scipy_sparse/introduction.rst.txt b/_sources/advanced/scipy_sparse/introduction.rst.txt new file mode 100644 index 000000000..17107c5e1 --- /dev/null +++ b/_sources/advanced/scipy_sparse/introduction.rst.txt @@ -0,0 +1,75 @@ +.. For doctests + >>> import numpy as np + >>> # For doctest on headless environments + >>> import matplotlib.pyplot as plt + +Introduction +============ + +(dense) matrix is: + +* mathematical object +* data structure for storing a 2D array of values + +important features: + +* memory allocated once for all items + * usually a contiguous chunk, think NumPy ndarray +* *fast* access to individual items (*) + +Why Sparse Matrices? +-------------------- + +* the memory grows like `n**2` for dense matrix +* small example (double precision matrix):: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> x = np.linspace(0, 1e6, 10) + >>> plt.plot(x, 8.0 * (x**2) / 1e6, lw=5) + [] + >>> plt.xlabel('size n') + Text(...'size n') + >>> plt.ylabel('memory [MB]') + Text(...'memory [MB]') + +Sparse Matrices vs. Sparse Matrix Storage Schemes +------------------------------------------------- + +* sparse matrix is a matrix, which is *almost empty* +* storing all the zeros is wasteful -> store only nonzero items +* think **compression** +* pros: huge memory savings +* cons: slow access to individual items, but it depends on actual storage scheme. + +Typical Applications +-------------------- + +* solution of partial differential equations (PDEs) + * the *finite element method* + * mechanical engineering, electrotechnics, physics, ... +* graph theory + * nonzero at `(i, j)` means that node `i` is connected to node `j` +* natural language processing + * nonzero at `(i, j)` means that the document `i` contains the word `j` +* ... + +Prerequisites +------------- + +.. rst-class:: horizontal + + * :ref:`numpy ` + * :ref:`scipy ` + * :ref:`matplotlib (optional) ` + * :ref:`ipython (the enhancements come handy) ` + +Sparsity Structure Visualization +-------------------------------- + +* :func:`spy` from ``matplotlib`` +* example plots: + +.. image:: figures/graph.png +.. image:: figures/graph_g.png +.. image:: figures/graph_rcm.png diff --git a/_sources/advanced/scipy_sparse/lil_array.rst.txt b/_sources/advanced/scipy_sparse/lil_array.rst.txt new file mode 100644 index 000000000..5e1d5c24a --- /dev/null +++ b/_sources/advanced/scipy_sparse/lil_array.rst.txt @@ -0,0 +1,90 @@ +.. + >>> import numpy as np + >>> import scipy as sp + +List of Lists Format (LIL) +========================== + +* row-based linked list + * each row is a Python list (sorted) of column indices of non-zero elements + * rows stored in a NumPy array (`dtype=np.object`) + * non-zero values data stored analogously +* efficient for constructing sparse arrays incrementally +* constructor accepts: + * dense array/matrix + * sparse array/matrix + * shape tuple (create empty array) +* flexible slicing, changing sparsity structure is efficient +* slow arithmetic, slow column slicing due to being row-based +* use: + * when sparsity pattern is not known apriori or changes + * example: reading a sparse array from a text file + +Examples +-------- + +* create an empty LIL array:: + + >>> mtx = sp.sparse.lil_array((4, 5)) + +* prepare random data:: + + >>> rng = np.random.default_rng(27446968) + >>> data = np.round(rng.random((2, 3))) + >>> data + array([[1., 0., 1.], + [0., 0., 1.]]) + +* assign the data using fancy indexing:: + + >>> mtx[:2, [1, 2, 3]] = data + >>> mtx + + >>> print(mtx) + + Coords Values + (0, 1) 1.0 + (0, 3) 1.0 + (1, 3) 1.0 + >>> mtx.toarray() + array([[0., 1., 0., 1., 0.], + [0., 0., 0., 1., 0.], + [0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0.]]) + >>> mtx.toarray() + array([[0., 1., 0., 1., 0.], + [0., 0., 0., 1., 0.], + [0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0.]]) + +* more slicing and indexing:: + + >>> mtx = sp.sparse.lil_array([[0, 1, 2, 0], [3, 0, 1, 0], [1, 0, 0, 1]]) + >>> mtx.toarray() + array([[0, 1, 2, 0], + [3, 0, 1, 0], + [1, 0, 0, 1]]...) + >>> print(mtx) + + Coords Values + (0, 1) 1 + (0, 2) 2 + (1, 0) 3 + (1, 2) 1 + (2, 0) 1 + (2, 3) 1 + >>> mtx[:2, :] + + >>> mtx[:2, :].toarray() + array([[0, 1, 2, 0], + [3, 0, 1, 0]]...) + >>> mtx[1:2, [0,2]].toarray() + array([[3, 1]]...) + >>> mtx.toarray() + array([[0, 1, 2, 0], + [3, 0, 1, 0], + [1, 0, 0, 1]]...) diff --git a/_sources/advanced/scipy_sparse/other_packages.rst.txt b/_sources/advanced/scipy_sparse/other_packages.rst.txt new file mode 100644 index 000000000..d6514f1e8 --- /dev/null +++ b/_sources/advanced/scipy_sparse/other_packages.rst.txt @@ -0,0 +1,10 @@ +Other Interesting Packages +========================== + +* PyAMG + * algebraic multigrid solvers + * https://github.com/pyamg/pyamg +* Pysparse + * own sparse matrix classes + * matrix and eigenvalue problem solvers + * https://pysparse.sourceforge.net/ diff --git a/_sources/advanced/scipy_sparse/solvers.rst.txt b/_sources/advanced/scipy_sparse/solvers.rst.txt new file mode 100644 index 000000000..cd88a8660 --- /dev/null +++ b/_sources/advanced/scipy_sparse/solvers.rst.txt @@ -0,0 +1,202 @@ +Linear System Solvers +===================== + +* sparse matrix/eigenvalue problem solvers live in :mod:`scipy.sparse.linalg` +* the submodules: + * :mod:`dsolve`: direct factorization methods for solving linear systems + * :mod:`isolve`: iterative methods for solving linear systems + * :mod:`eigen`: sparse eigenvalue problem solvers + +* all solvers are accessible from:: + + >>> import scipy as sp + >>> sp.sparse.linalg.__all__ + ['ArpackError', 'ArpackNoConvergence', ..., 'use_solver'] + + +Sparse Direct Solvers +--------------------- + +* default solver: SuperLU + * included in SciPy + * real and complex systems + * both single and double precision +* optional: umfpack + * real and complex systems + * double precision only + * recommended for performance + * wrappers now live in :mod:`scikits.umfpack` + * check-out the new :mod:`scikits.suitesparse` by Nathaniel Smith + +Examples +^^^^^^^^ +* import the whole module, and see its docstring:: + + >>> help(sp.sparse.linalg.spsolve) + Help on function spsolve in module scipy.sparse.linalg._dsolve.linsolve: + ... + +* both superlu and umfpack can be used (if the latter is installed) as + follows: + + * prepare a linear system:: + + >>> import numpy as np + >>> mtx = sp.sparse.spdiags([[1, 2, 3, 4, 5], [6, 5, 8, 9, 10]], [0, 1], 5, 5, "csc") + >>> mtx.toarray() + array([[ 1, 5, 0, 0, 0], + [ 0, 2, 8, 0, 0], + [ 0, 0, 3, 9, 0], + [ 0, 0, 0, 4, 10], + [ 0, 0, 0, 0, 5]]) + >>> rhs = np.array([1, 2, 3, 4, 5], dtype=np.float32) + + * solve as single precision real:: + + >>> mtx1 = mtx.astype(np.float32) + >>> x = sp.sparse.linalg.spsolve(mtx1, rhs, use_umfpack=False) + >>> print(x) + [106. -21. 5.5 -1.5 1. ] + >>> print("Error: %s" % (mtx1 * x - rhs)) + Error: [0. 0. 0. 0. 0.] + + * solve as double precision real:: + + >>> mtx2 = mtx.astype(np.float64) + >>> x = sp.sparse.linalg.spsolve(mtx2, rhs, use_umfpack=True) + >>> print(x) + [106. -21. 5.5 -1.5 1. ] + >>> print("Error: %s" % (mtx2 * x - rhs)) + Error: [0. 0. 0. 0. 0.] + + * solve as single precision complex:: + + >>> mtx1 = mtx.astype(np.complex64) + >>> x = sp.sparse.linalg.spsolve(mtx1, rhs, use_umfpack=False) + >>> print(x) + [106. +0.j -21. +0.j 5.5+0.j -1.5+0.j 1. +0.j] + >>> print("Error: %s" % (mtx1 * x - rhs)) + Error: [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j] + + * solve as double precision complex:: + + >>> mtx2 = mtx.astype(np.complex128) + >>> x = sp.sparse.linalg.spsolve(mtx2, rhs, use_umfpack=True) + >>> print(x) + [106. +0.j -21. +0.j 5.5+0.j -1.5+0.j 1. +0.j] + >>> print("Error: %s" % (mtx2 * x - rhs)) + Error: [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j] + +.. literalinclude:: examples/direct_solve.py + +* :download:`examples/direct_solve.py` + +Iterative Solvers +----------------- + +* the :mod:`isolve` module contains the following solvers: + * ``bicg`` (BIConjugate Gradient) + * ``bicgstab`` (BIConjugate Gradient STABilized) + * ``cg`` (Conjugate Gradient) - symmetric positive definite matrices + only + * ``cgs`` (Conjugate Gradient Squared) + * ``gmres`` (Generalized Minimal RESidual) + * ``minres`` (MINimum RESidual) + * ``qmr`` (Quasi-Minimal Residual) + +Common Parameters +^^^^^^^^^^^^^^^^^ + +* mandatory: + + A : {sparse array/matrix, dense array/matrix, LinearOperator} + The N-by-N matrix of the linear system. + b : {array, matrix} + Right hand side of the linear system. Has shape (N,) or (N,1). + +* optional: + + x0 : {array, matrix} + Starting guess for the solution. + tol : float + Relative tolerance to achieve before terminating. + maxiter : integer + Maximum number of iterations. Iteration will stop after maxiter + steps even if the specified tolerance has not been achieved. + M : {sparse array/matrix, dense array/matrix, LinearOperator} + Preconditioner for A. The preconditioner should approximate the + inverse of A. Effective preconditioning dramatically improves the + rate of convergence, which implies that fewer iterations are needed + to reach a given error tolerance. + callback : function + User-supplied function to call after each iteration. It is called + as callback(xk), where xk is the current solution vector. + +LinearOperator Class +^^^^^^^^^^^^^^^^^^^^ + +* common interface for performing matrix vector products +* useful abstraction that enables using dense and sparse matrices within + the solvers, as well as *matrix-free* solutions +* has `shape` and `matvec()` (+ some optional parameters) +* example: + +.. code-block:: pycon + + >>> import numpy as np + >>> import scipy as sp + >>> def mv(v): + ... return np.array([2 * v[0], 3 * v[1]]) + ... + >>> A = sp.sparse.linalg.LinearOperator((2, 2), matvec=mv) + >>> A + <2x2 _CustomLinearOperator with dtype=float64> + >>> A.matvec(np.ones(2)) + array([2., 3.]) + >>> A * np.ones(2) + array([2., 3.]) + +A Few Notes on Preconditioning +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +* problem specific +* often hard to develop +* if not sure, try ILU + * available in :mod:`scipy.sparse.linalg` as :func:`spilu()` + +Eigenvalue Problem Solvers +-------------------------- + +The :mod:`eigen` module +^^^^^^^^^^^^^^^^^^^^^^^^ + +* ``arpack`` + * a collection of Fortran77 subroutines designed to solve large scale eigenvalue problems + +* ``lobpcg`` (Locally Optimal Block Preconditioned Conjugate + Gradient Method) + * works very well in combination with `PyAMG `_ + * example by Nathan Bell: + + .. literalinclude:: examples/pyamg_with_lobpcg.py + + * :download:`examples/pyamg_with_lobpcg.py` + +* example by Nils Wagner: + + * :download:`examples/lobpcg_sakurai.py` + +* output:: + + $ python examples/lobpcg_sakurai.py + Results by LOBPCG for n=2500 + + [ 0.06250083 0.06250028 0.06250007] + + Exact eigenvalues + + [ 0.06250005 0.0625002 0.06250044] + + Elapsed time 7.01 + +.. image:: figures/lobpcg_eigenvalues.png diff --git a/_sources/advanced/scipy_sparse/storage_schemes.rst.txt b/_sources/advanced/scipy_sparse/storage_schemes.rst.txt new file mode 100644 index 000000000..17ca03818 --- /dev/null +++ b/_sources/advanced/scipy_sparse/storage_schemes.rst.txt @@ -0,0 +1,132 @@ +Storage Schemes +=============== + +* seven sparse array types in scipy.sparse: + 1. csr_array: Compressed Sparse Row format + 2. csc_array: Compressed Sparse Column format + 3. bsr_array: Block Sparse Row format + 4. lil_array: List of Lists format + 5. dok_array: Dictionary of Keys format + 6. coo_array: COOrdinate format (aka IJV, triplet format) + 7. dia_array: DIAgonal format +* each suitable for some tasks +* many employ sparsetools C++ module by Nathan Bell +* assume the following is imported:: + + >>> import numpy as np + >>> import scipy as sp + >>> import matplotlib.pyplot as plt + + +* **warning** for Numpy users: + * passing a sparse array object to NumPy functions that expect + ndarray/matrix does not work. Use sparse functions. + * the older csr_matrix classes use '*' for matrix multiplication (dot product) + and 'A.multiply(B)' for elementwise multiplication. + * the newer csr_array uses '@' for dot product and '*' for elementwise multiplication + * sparse arrays can be 1D or 2D, but not nD for n > 2 (unlike Numpy arrays). + +Common Methods +-------------- + +* all scipy.sparse array classes are subclasses of :class:`sparray` + * default implementation of arithmetic operations + * always converts to CSR + * subclasses override for efficiency + * shape, data type, set/get + * indices of nonzero values in the array + * format conversion, interaction with NumPy (`toarray()`) + * ... +* attributes: + * `mtx.T` - transpose (same as mtx.transpose()) + * `mtx.real` - real part of complex matrix + * `mtx.imag` - imaginary part of complex matrix + * `mtx.size` - the number of nonzeros (same as self.getnnz()) + * `mtx.shape` - the number of rows and columns (tuple) +* data and indices usually stored in 1D NumPy arrays + +Sparse Array Classes +--------------------- + +.. toctree:: + :maxdepth: 2 + + dia_array + lil_array + dok_array + coo_array + csr_array + csc_array + bsr_array + +Summary +------- + +.. list-table:: Summary of storage schemes. + :widths: 10 10 10 10 10 10 10 30 + :header-rows: 1 + + * - format + - matrix * vector + - get item + - fancy get + - set item + - fancy set + - solvers + - note + * - CSR + - sparsetools + - yes + - yes + - slow + - . + - any + - has data array, fast row-wise ops + * - CSC + - sparsetools + - yes + - yes + - slow + - . + - any + - has data array, fast column-wise ops + * - BSR + - sparsetools + - . + - . + - . + - . + - specialized + - has data array, specialized + * - COO + - sparsetools + - . + - . + - . + - . + - iterative + - has data array, facilitates fast conversion + * - DIA + - sparsetools + - . + - . + - . + - . + - iterative + - has data array, specialized + * - LIL + - via CSR + - yes + - yes + - yes + - yes + - iterative + - arithmetic via CSR, incremental construction + * - DOK + - python + - yes + - one axis only + - yes + - yes + - iterative + - O(1) item access, incremental construction, slow arithmetic diff --git a/_sources/guide/auto_examples/index.rst.txt b/_sources/guide/auto_examples/index.rst.txt new file mode 100644 index 000000000..308c16dff --- /dev/null +++ b/_sources/guide/auto_examples/index.rst.txt @@ -0,0 +1,63 @@ +:orphan: + +Examples for the contribution guide +==================================== + +Note that every example directory needs to have a README.txt + + + +.. raw:: html + +
+ +.. thumbnail-parent-div-open + +.. raw:: html + +
+ +.. only:: html + + .. image:: /guide/auto_examples/images/thumb/sphx_glr_plot_simple_thumb.png + :alt: + + :ref:`sphx_glr_guide_auto_examples_plot_simple.py` + +.. raw:: html + +
A simple example
+
+ + +.. thumbnail-parent-div-close + +.. raw:: html + +
+ + +.. toctree:: + :hidden: + + /guide/auto_examples/plot_simple + + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-gallery + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download all examples in Python source code: auto_examples_python.zip ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download all examples in Jupyter notebooks: auto_examples_jupyter.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/guide/auto_examples/plot_simple.rst.txt b/_sources/guide/auto_examples/plot_simple.rst.txt new file mode 100644 index 000000000..1eb6ecad2 --- /dev/null +++ b/_sources/guide/auto_examples/plot_simple.rst.txt @@ -0,0 +1,78 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "guide/auto_examples/plot_simple.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_guide_auto_examples_plot_simple.py: + + +A simple example +================= + +.. GENERATED FROM PYTHON SOURCE LINES 6-15 + + + +.. image-sg:: /guide/auto_examples/images/sphx_glr_plot_simple_001.png + :alt: plot simple + :srcset: /guide/auto_examples/images/sphx_glr_plot_simple_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + X = np.linspace(-np.pi, np.pi, 100) + Y = np.sin(X) + + plt.plot(X, Y, linewidth=2) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.052 seconds) + + +.. _sphx_glr_download_guide_auto_examples_plot_simple.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_simple.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_simple.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_simple.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/guide/auto_examples/sg_execution_times.rst.txt b/_sources/guide/auto_examples/sg_execution_times.rst.txt new file mode 100644 index 000000000..c32b3d65f --- /dev/null +++ b/_sources/guide/auto_examples/sg_execution_times.rst.txt @@ -0,0 +1,37 @@ + +:orphan: + +.. _sphx_glr_guide_auto_examples_sg_execution_times: + + +Computation times +================= +**00:00.052** total execution time for 1 file **from guide/auto_examples**: + +.. container:: + + .. raw:: html + + + + + + + + .. list-table:: + :header-rows: 1 + :class: table table-striped sg-datatable + + * - Example + - Time + - Mem (MB) + * - :ref:`sphx_glr_guide_auto_examples_plot_simple.py` (``plot_simple.py``) + - 00:00.052 + - 0.0 diff --git a/_sources/guide/index.rst.txt b/_sources/guide/index.rst.txt new file mode 100644 index 000000000..122f5d5c8 --- /dev/null +++ b/_sources/guide/index.rst.txt @@ -0,0 +1,212 @@ +.. _guide: + +================= +How to contribute +================= + +**Author**: *Nicolas Rougier* + +.. topic:: Foreword + + Use the ``topic`` keyword for any forewords + + +.. contents:: Chapters contents + :local: + :depth: 1 + + +Make sure to read this `Documentation style guide`_ as well as these +`tips, tricks`_ and conventions about documentation content and workflows. + + +How to contribute ? +=================== + +* If you spot typos, unclear or clumsy wording in the lectures, please + help to improve them. Simple text editing can be done by `editing files + in your GitHub fork + `_ of + the lectures. On every html page of the lectures, an **edit** + button on the top right links to the editable source of the page (you still + need to create a fork of the project). Edit the source and choose + "Create a new branch for this commit and start a pull request". + +* Choose a topic that is not yet covered and write it up ! + + First create a new issue on GitHub to explain the topic which you would + like to cover, in order to discuss with editors and contributors about + the scope of the future tutorial. + + Then create a new directory inside one of the chapters directories + (``intro``, ``advanced``, or ``packages``) and create a file ``index.rst`` + for the new tutorial. Add the new file in the table of contents of the + corresponding chapter (in its ``index.rst``). + +Keep in mind that tutorials are to be taught at different places and +different parts may be combined into a course on Python for scientific +computing. Thus you want them to be interactive and reasonably short (one +to two hours). + +Last but not least, the goal of this material is to provide a concise +text to learn the main features of the scientific Python ecosystem. If +you want to contribute to reference material, we suggest that you +contribute to the documentation of the specific packages that you are +interested in. + +Using GitHub +============ + +The easiest way to make your own version of this teaching material +is to fork it under GitHub, and use the git version control system to +maintain your own fork. For this, all you have to do is create an account +on GitHub and click on the *fork* button, on the top right of `this +page `_. You can use git to pull from your *fork*, and push back to it the +changes. If you want to contribute the changes back, just fill a +*pull request*, using the button on the top of your fork's page. + +Several resources are available online to learn git and GitHub, such as +https://try.github.io for complete beginners. + +Please refrain from modifying the Makefile unless it is absolutely +necessary. + +Keeping it concise: collapsing paragraphs +=========================================== + +The HTML output is used for displaying on screen while teaching. The goal +is to have the same material displayed as in the notes. Thus there needs +to be a very concise display, with bullet-lists rather than full-blown +paragraphs and sentences. For more elaborate discussions that people can +read and refer to, please use the ``tip`` sphinx directive. It creates +collapsible paragraphs, that can be hidden during an oral +presentation:: + + .. tip:: + + Here insert a full-blown discussion, that will be collapsible in + the HTML version. + + It can span on multiple paragraphs + +This renders as: + + .. tip:: + + Here insert a full-blown discussion, that will be collapsible in + the HTML version. + + It can span on multiple paragraphs + +Figures and code examples +========================== + +**We do not check figures in the repository**. +Any figure must be generated from a python script that needs to be named +``plot_xxx.py`` (xxx can be anything of course) and put into the ``examples`` +directory. The generated image will be named from the script name. + +.. image:: auto_examples/images/sphx_glr_plot_simple_001.png + :target: auto_examples/plot_simple.html + + +This is the way to include your image and link it to the code: + +.. code-block:: rst + + .. image:: auto_examples/images/sphx_glr_plot_simple_001.png + :target: auto_examples/plot_simple.html + +You can display the corresponding code using the ``literal-include`` +directive. + +.. literalinclude:: examples/plot_simple.py + +.. note:: + + The transformation of Python scripts into figures and galleries of + examples is provided by the `sphinx-gallery + `_ package. + +Using Markup +============ + +There are three main kinds of markup that should be used: *italics*, **bold** +and ``fixed-font``. *Italics* should be used when introducing a new technical +term, **bold** should be used for emphasis and ``fixed-font`` for source code. + +.. topic:: Example: + + When using *object-oriented programming* in Python you **must** use the + ``class`` keyword to define your *classes*. + +In restructured-text markup this is:: + + when using *object-oriented programming* in Python you **must** use the + ``class`` keyword to define your *classes*. + + +Linking to package documentations +================================== + +The goal of the Scientific Python Lectures is not to duplicate or replace +the documentation of the various packages. You should link as much as +possible to the original documentation. + +For cross-referencing API documentation we prefer to use the `intersphinx +extension `_. This provides +the directives ``:mod:``, ``:class:`` and ``:func:`` to cross-link to modules, +classes and functions respectively. For example the ``:func:`numpy.var``` will +create a link like :func:`numpy.var`. + +Chapter, section, subsection, paragraph +======================================= + +Try to avoid to go below paragraph granularity or your document might become +difficult to read: + +.. code-block:: rst + + ============= + Chapter title + ============= + + Sample content. + + Section + ======= + + Subsection + ---------- + + Paragraph + ......... + + And some text. + + +Admonitions +============ + +.. note:: + + This is a note + +.. warning:: + + This is a warning + +Clearing floats +================ + +Figures positioned with `:align: right` are float. To flush them, use:: + + |clear-floats| + +References +========== + +.. target-notes:: + +.. _`Documentation style guide`: https://documentation-style-guide-sphinx.readthedocs.org/en/latest/style-guide.html +.. _`tips, tricks`: https://docness.readthedocs.org/en/latest/index.html diff --git a/_sources/includes/big_toc_css.rst.txt b/_sources/includes/big_toc_css.rst.txt new file mode 100644 index 000000000..454e9ace1 --- /dev/null +++ b/_sources/includes/big_toc_css.rst.txt @@ -0,0 +1,43 @@ +:orphan: + +.. + File to ..include in a document with a big table of content, to give + it 'style' + +.. raw:: html + + diff --git a/_sources/includes/bigger_toc_css.rst.txt b/_sources/includes/bigger_toc_css.rst.txt new file mode 100644 index 000000000..66563bd73 --- /dev/null +++ b/_sources/includes/bigger_toc_css.rst.txt @@ -0,0 +1,59 @@ +:orphan: + +.. + File to ..include in a document with a very big table of content, to + give it 'style' + +.. raw:: html + + diff --git a/_sources/index.rst.txt b/_sources/index.rst.txt new file mode 100644 index 000000000..21495e712 --- /dev/null +++ b/_sources/index.rst.txt @@ -0,0 +1,153 @@ +Scientific Python Lectures +========================== + +.. only:: html + + One document to learn numerics, science, and data with Python + -------------------------------------------------------------- + +.. raw html to center the title + +.. raw:: html + + + +.. nice layout in the toc + +.. Icons from https://fonts.google.com/icons + +.. |pdf-icon| image:: images/icon-pdf.svg + :width: 1em + :class: vcenter + :alt: PDF icon + +.. |html-icon| image:: images/icon-archive.svg + :width: 1em + :class: vcenter + :alt: Archive icon + + +.. |github-icon| image:: images/icon-github.svg + :width: 1em + :class: vcenter + :alt: GitHub icon + + +.. only:: html + + .. sidebar:: Download + + |pdf-icon| `PDF, 2 pages per side <./_downloads/ScientificPythonLectures.pdf>`_ + + |pdf-icon| `PDF, 1 page per side <./_downloads/ScientificPythonLectures-simple.pdf>`_ + + |github-icon| `Source code (github) `_ + + + Tutorials on the scientific Python ecosystem: a quick introduction to + central tools and techniques. The different chapters each correspond + to a 1 to 2 hours course with increasing level of expertise, from + beginner to expert. + + Release: |release| + + .. rst-class:: preface + + .. toctree:: + :maxdepth: 2 + + preface.rst + +| + +.. rst-class:: tune + + .. toctree:: + :numbered: 4 + + intro/index.rst + advanced/index.rst + packages/index.rst + about.rst + +| + +.. + FIXME: I need the link below to make sure the banner gets copied to the + target directory. + +.. only:: html + + .. raw:: html + +
+ + :download:`ScientificPythonLectures.pdf` :download:`ScientificPythonLectures-simple.pdf` + + .. image:: themes/plusBox.png + + .. image:: images/logo.svg + + .. raw:: html + +
+ + + +.. + >>> # For doctest on headless environments (needs to happen early) + >>> import matplotlib + >>> matplotlib.use('Agg') diff --git a/_sources/intro/help/help.rst.txt b/_sources/intro/help/help.rst.txt new file mode 100644 index 000000000..e3cdb2146 --- /dev/null +++ b/_sources/intro/help/help.rst.txt @@ -0,0 +1,72 @@ +.. _help: + +Getting help and finding documentation +========================================= + +**Author**: *Emmanuelle Gouillart* + +Rather than knowing all functions in NumPy and SciPy, it is important to +find rapidly information throughout the documentation and the available +help. Here are some ways to get information: + +* In Ipython, ``help function`` opens the docstring of the function. Only + type the beginning of the function's name and use tab completion to + display the matching functions. + + .. ipython:: + + @verbatim + In [204]: help(np.van + + In [204]: help(np.vander) + +In Ipython it is not possible to open a separated window for help and +documentation; however one can always open a second ``Ipython`` shell +just to display help and docstrings... + +* Numpy's and Scipy's documentations can be browsed online on + https://scipy.org and https://numpy.org. The ``search`` button is quite + useful inside + the reference documentation of the two packages. + + Tutorials on various topics as well as the complete API with all + docstrings are found on this website. + +* Numpy's and Scipy's documentation is enriched and updated on a regular + basis by users on a wiki https://numpy.org/doc/stable/. As a result, + some docstrings are clearer or more detailed on the wiki, and you may + want to read directly the documentation on the wiki instead of the + official documentation website. Note that anyone can create an account on + the wiki and write better documentation; this is an easy way to + contribute to an open-source project and improve the tools you are + using! + +* The SciPy Cookbook https://scipy-cookbook.readthedocs.io gives recipes on many + common problems frequently encountered, such as fitting data points, + solving ODE, etc. + +* Matplotlib's website https://matplotlib.org/ features a very + nice **gallery** with a large number of plots, each of them shows both + the source code and the resulting plot. This is very useful for + learning by example. More standard documentation is also available. + + +* In Ipython, the magical function ``%psearch`` search for objects + matching patterns. This is useful if, for example, one does not know + the exact name of a function. + + + .. ipython:: + + In [3]: import numpy as np + In [4]: %psearch np.diag* + +* If everything listed above fails (and Google doesn't have the + answer)... don't despair! There is a vibrant Scientific Python community. + Scientific Python is present on various platform. + https://scientific-python.org/community/ + + + Packages like SciPy and NumPy also have their own channels. Have a look at + their respective websites to find out how to engage with users and + maintainers. diff --git a/_sources/intro/index.rst.txt b/_sources/intro/index.rst.txt new file mode 100644 index 000000000..42ab9d671 --- /dev/null +++ b/_sources/intro/index.rst.txt @@ -0,0 +1,23 @@ +Getting started with Python for science +======================================= + +This part of the *Scientific Python Lectures* is a self-contained +introduction to everything that is needed to use Python for science, +from the language itself, to numerical computing or plotting. + +| + + +.. include:: ../includes/big_toc_css.rst + :start-line: 1 + +.. rst-class:: tune + + .. toctree:: + + intro.rst + language/python_language.rst + numpy/index.rst + matplotlib/index.rst + scipy/index.rst + help/help.rst diff --git a/_sources/intro/intro.rst.txt b/_sources/intro/intro.rst.txt new file mode 100644 index 000000000..8f09cf2bd --- /dev/null +++ b/_sources/intro/intro.rst.txt @@ -0,0 +1,472 @@ +Python scientific computing ecosystem +====================================== + +**Authors**: *Fernando Perez, Emmanuelle Gouillart, Gaël Varoquaux, +Valentin Haenel* + +Why Python? +------------ + +The scientist's needs +....................... + +* Get data (simulation, experiment control), + +* Manipulate and process data, + +* Visualize results, quickly to understand, but also with high quality + figures, for reports or publications. + +Python's strengths +.................. + +* **Batteries included** Rich collection of already existing **bricks** + of classic numerical methods, plotting or data processing tools. We + don't want to re-program the plotting of a curve, a Fourier transform + or a fitting algorithm. Don't reinvent the wheel! + +* **Easy to learn** Most scientists are not paid as programmers, neither + have they been trained so. They need to be able to draw a curve, smooth + a signal, do a Fourier transform in a few minutes. + +* **Easy communication** To keep code alive within a lab or a company + it should be as readable as a book by collaborators, students, or + maybe customers. Python syntax is simple, avoiding strange symbols or + lengthy routine specifications that would divert the reader from + mathematical or scientific understanding of the code. + +* **Efficient code** Python numerical modules are computationally + efficient. But needless to say that a very fast code becomes useless if + too much time is spent writing it. Python aims for quick development + times and quick execution times. + +* **Universal** Python is a language used for many different problems. + Learning Python avoids learning a new software for each new problem. + +How does Python compare to other solutions? +............................................ + +Compiled languages: C, C++, Fortran... +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +:Pros: + + * Very fast. For heavy computations, it's difficult to outperform these + languages. + +:Cons: + + * Painful usage: no interactivity during development, mandatory + compilation steps, verbose syntax, manual memory management. These + are **difficult languages** for non programmers. + +Matlab scripting language +~~~~~~~~~~~~~~~~~~~~~~~~~ + +:Pros: + + * Very rich collection of libraries with numerous algorithms, for many + different domains. Fast execution because these libraries are often written + in a compiled language. + + * Pleasant development environment: comprehensive and help, integrated + editor, etc. + + * Commercial support is available. + +:Cons: + + * Base language is quite poor and can become restrictive for advanced users. + + * Not free and not everything is open sourced. + +Julia +~~~~~~~ + +:Pros: + + * Fast code, yet interactive and simple. + + * Easily connects to Python or C. + +:Cons: + + * Ecosystem limited to numerical computing. + + * Still young. + +Other scripting languages: Scilab, Octave, R, IDL, etc. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +:Pros: + + * Open-source, free, or at least cheaper than Matlab. + + * Some features can be very advanced (statistics in R, etc.) + +:Cons: + + * Fewer available algorithms than in Matlab, and the language + is not more advanced. + + * Some software are dedicated to one domain. Ex: Gnuplot to draw + curves. These programs are very powerful, but they are restricted to + a single type of usage, such as plotting. + +Python +~~~~~~ + +:Pros: + + * Very rich scientific computing libraries + + * Well thought out language, allowing to write very readable and well + structured code: we "code what we think". + + * Many libraries beyond scientific computing (web server, + serial port access, etc.) + + * Free and open-source software, widely spread, with a vibrant community. + + * A variety of powerful environments to work in, such as + `IPython `__, + `Spyder `__, + `Jupyter notebooks `__, + `Pycharm `__, + `Visual Studio Code `__ + +:Cons: + + * Not all the algorithms that can be found in more specialized + software or toolboxes. + +The scientific Python ecosystem +------------------------------- + +Unlike Matlab, or R, Python does not come with a pre-bundled set +of modules for scientific computing. Below are the basic building blocks +that can be combined to obtain a scientific computing environment: + +| + +**Python**, a generic and modern computing language + +* The language: flow control, data types (``string``, ``int``), + data collections (lists, dictionaries), etc. + +* Modules of the standard library: string processing, file + management, simple network protocols. + +* A large number of specialized modules or applications written in + Python: web framework, etc. ... and scientific + computing. + +* Development tools (automatic testing, documentation generation) + +.. seealso:: + + :ref:`chapter on Python language ` + +**Core numeric libraries** + +* **NumPy**: numerical computing with powerful **numerical arrays** + objects, and routines to manipulate them. https://numpy.org/ + + .. seealso:: + + :ref:`chapter on numpy ` + +* **SciPy** : high-level numerical routines. + Optimization, regression, interpolation, etc https://scipy.org/ + + .. seealso:: + + :ref:`chapter on SciPy ` + +* **Matplotlib** : 2-D visualization, "publication-ready" plots + https://matplotlib.org/ + + .. seealso:: + + :ref:`chapter on matplotlib ` + +**Advanced interactive environments**: + +* **IPython**, an advanced **Python console** https://ipython.org/ + +* **Jupyter**, **notebooks** in the browser https://jupyter.org/ + + +**Domain-specific packages**, + +* **pandas, statsmodels, seaborn** for :ref:`statistics ` + +* **sympy** for :ref:`symbolic computing ` + +* **scikit-image** for :ref:`image processing ` + +* **scikit-learn** for :ref:`machine learning ` + +and many more packages not documented in the Scientific Python Lectures. + +.. seealso:: + + :ref:`chapters on advanced topics ` + + :ref:`chapters on packages and applications ` + +|clear-floats| + +.. + >>> import numpy as np + + +Before starting: Installing a working environment +-------------------------------------------------- +Python comes in many flavors, and there are many ways to install it. +However, we recommend to install a scientific-computing distribution, +that comes readily with optimized versions of scientific modules. + +**Under Linux** + +If you have a recent distribution, most of the tools are probably +packaged, and it is recommended to use your package manager. + +**Other systems** + +There are several fully-featured scientific Python distributions: + + +.. rst-class:: horizontal + + * `Anaconda `_ + * `WinPython `_ + + +The workflow: interactive environments and text editors +---------------------------------------------------------- + +**Interactive work to test and understand algorithms:** In this section, we +describe a workflow combining interactive work and consolidation. + +Python is a general-purpose language. As such, there is not one blessed +environment to work in, and not only one way of using it. Although +this makes it harder for beginners to find their way, it makes it +possible for Python to be used for programs, in web servers, or +embedded devices. + +.. _interactive_work: + +Interactive work +................. + +We recommend an interactive work with the `IPython +`__ console, or its offspring, the `Jupyter notebook +`_. They +are handy to explore and understand algorithms. + +.. sidebar:: Under the notebook + + To execute code, press "shift enter" + +Start `ipython`: + +.. ipython:: + :verbatim: + + In [1]: print('Hello world') + Hello world + +Getting help by using the **?** operator after an object: + +.. ipython:: + + In [1]: print? + +.. seealso:: + + * IPython user manual: https://ipython.readthedocs.io/en/stable/ + + * Jupyter Notebook QuickStart: + https://docs.jupyter.org/en/latest/start/index.html + +Elaboration of the work in an editor +.......................................... + +As you move forward, it will be important to not only work interactively, +but also to create and reuse Python files. For this, a powerful code editor +will get you far. Here are several good easy-to-use editors: + + * `Spyder `_: integrates an IPython + console, a debugger, a profiler... + * `PyCharm `_: integrates an IPython + console, notebooks, a debugger... (freely available, + but commercial) + * `Visual Studio Code `_: + integrates a Python console, notebooks, a debugger, ... + +Some of these are shipped by the various scientific Python distributions, +and you can find them in the menus. + + +As an exercise, create a file `my_file.py` in a code editor, and add the +following lines:: + + s = 'Hello world' + print(s) + +Now, you can run it in IPython console or a notebook and explore the +resulting variables: + +.. ipython:: + + @suppress + In [1]: s = 'Hello world' + + @verbatim + In [1]: %run my_file.py + Hello world + + @doctest + In [2]: s + Out[2]: 'Hello world' + + @verbatim + In [3]: %whos + Variable Type Data/Info + ---------------------------- + s str Hello world + + +.. topic:: **From a script to functions** + + While it is tempting to work only with scripts, that is a file full + of instructions following each other, do plan to progressively evolve + the script to a set of functions: + + * A script is not reusable, functions are. + + * Thinking in terms of functions helps breaking the problem in small + blocks. + + +IPython and Jupyter Tips and Tricks +.................................... + +The user manuals contain a wealth of information. Here we give a quick +introduction to four useful features: *history*, *tab completion*, *magic +functions*, and *aliases*. + +| + +**Command history** Like a UNIX shell, the IPython console supports +command history. Type *up* and *down* to navigate previously typed +commands: + +.. ipython:: + + In [1]: x = 10 + + @verbatim + In [2]: + + In [2]: x = 10 + +| + +**Tab completion** Tab completion, is a convenient way to explore the +structure of any object you’re dealing with. Simply type object_name. to +view the object’s attributes. Besides Python objects and keywords, tab +completion also works on file and directory names.* + +.. ipython:: + + In [1]: x = 10 + + @verbatim + In [2]: x. + as_integer_ratio() conjugate() imag to_bytes() + bit_count() denominator numerator + bit_length() from_bytes() real + +| + +**Magic functions** +The console and the notebooks support so-called *magic* functions by prefixing a command with the +``%`` character. For example, the ``run`` and ``whos`` functions from the +previous section are magic functions. Note that, the setting ``automagic``, +which is enabled by default, allows you to omit the preceding ``%`` sign. Thus, +you can just type the magic function and it will work. + +Other useful magic functions are: + +* ``%cd`` to change the current directory. + + .. ipython:: + + In [1]: cd /tmp + /tmp + +* ``%cpaste`` allows you to paste code, especially code from websites which has + been prefixed with the standard Python prompt (e.g. ``>>>``) or with an ipython + prompt, (e.g. ``in [3]``): + + .. ipython:: + + In [2]: %cpaste + Pasting code; enter '--' alone on the line to stop or use Ctrl-D. + :>>> for i in range(3): + :... print(i) + :-- + 0 + 1 + 2 + +* ``%timeit`` allows you to time the execution of short snippets using the + ``timeit`` module from the standard library: + + .. ipython:: + + In [3]: %timeit x = 10 + 10000000 loops, best of 3: 39 ns per loop + + .. seealso:: :ref:`Chapter on optimizing code ` + +* ``%debug`` allows you to enter post-mortem debugging. That is to say, if the + code you try to execute, raises an exception, using ``%debug`` will enter the + debugger at the point where the exception was thrown. + + .. ipython:: + :okexcept: + + In [4]: x === 10 + + @verbatim + In [5]: %debug + > /home/jarrod/.venv/lectures/lib64/python3.11/site-packages/IPython/core/compilerop.py(86)ast_parse() + 84 Arguments are exactly the same as ast.parse (in the standard library), + 85 and are passed to the built-in compile function.""" + ---> 86 return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1) + 87 + 88 def reset_compiler_flags(self): + ipdb> locals() + {'self': , 'source': 'x === 10\n', 'filename': '', 'symbol': 'exec'} + ipdb> + + .. seealso:: :ref:`Chapter on debugging ` + +| + +**Aliases** +Furthermore IPython ships with various *aliases* which emulate common UNIX +command line tools such as ``ls`` to list files, ``cp`` to copy files and ``rm`` to +remove files (a full list of aliases is shown when typing ``alias``). + +.. topic:: **Getting help** + + * The built-in cheat-sheet is accessible via the ``%quickref`` magic + function. + + * A list of all available magic functions is shown when typing ``%magic``. + +.. :vim:spell: diff --git a/_sources/intro/language/basic_types.rst.txt b/_sources/intro/language/basic_types.rst.txt new file mode 100644 index 000000000..8af186cb4 --- /dev/null +++ b/_sources/intro/language/basic_types.rst.txt @@ -0,0 +1,472 @@ +Basic types +============ + +Numerical types +---------------- + +.. tip:: + + Python supports the following numerical, scalar types: + +:Integer: + + >>> 1 + 1 + 2 + >>> a = 4 + >>> type(a) + + +:Floats: + + >>> c = 2.1 + >>> type(c) + + +:Complex: + + >>> a = 1.5 + 0.5j + >>> a.real + 1.5 + >>> a.imag + 0.5 + >>> type(1. + 0j) + + +:Booleans: + + >>> 3 > 4 + False + >>> test = (3 > 4) + >>> test + False + >>> type(test) + + +.. tip:: + + A Python shell can therefore replace your pocket calculator, with the + basic arithmetic operations ``+``, ``-``, ``*``, ``/``, ``%`` (modulo) + natively implemented + +:: + + >>> 7 * 3. + 21.0 + >>> 2**10 + 1024 + >>> 8 % 3 + 2 + +Type conversion (casting):: + + >>> float(1) + 1.0 + + +Containers +------------ + +.. tip:: + + Python provides many efficient types of containers, in which + collections of objects can be stored. + +Lists +~~~~~ + +.. tip:: + + A list is an ordered collection of objects, that may have different + types. For example: + +:: + + >>> colors = ['red', 'blue', 'green', 'black', 'white'] + >>> type(colors) + + +Indexing: accessing individual objects contained in the list:: + + >>> colors[2] + 'green' + +Counting from the end with negative indices:: + + >>> colors[-1] + 'white' + >>> colors[-2] + 'black' + +.. warning:: + + **Indexing starts at 0** (as in C), not at 1 (as in Fortran or Matlab)! + +Slicing: obtaining sublists of regularly-spaced elements:: + + >>> colors + ['red', 'blue', 'green', 'black', 'white'] + >>> colors[2:4] + ['green', 'black'] + +.. Warning:: + + Note that ``colors[start:stop]`` contains the elements with indices ``i`` + such as ``start<= i < stop`` (``i`` ranging from ``start`` to + ``stop-1``). Therefore, ``colors[start:stop]`` has ``(stop - start)`` elements. + +**Slicing syntax**: ``colors[start:stop:stride]`` + +.. tip:: + + All slicing parameters are optional:: + + >>> colors + ['red', 'blue', 'green', 'black', 'white'] + >>> colors[3:] + ['black', 'white'] + >>> colors[:3] + ['red', 'blue', 'green'] + >>> colors[::2] + ['red', 'green', 'white'] + +Lists are *mutable* objects and can be modified:: + + >>> colors[0] = 'yellow' + >>> colors + ['yellow', 'blue', 'green', 'black', 'white'] + >>> colors[2:4] = ['gray', 'purple'] + >>> colors + ['yellow', 'blue', 'gray', 'purple', 'white'] + +.. Note:: + + The elements of a list may have different types:: + + >>> colors = [3, -200, 'hello'] + >>> colors + [3, -200, 'hello'] + >>> colors[1], colors[2] + (-200, 'hello') + + .. tip:: + + For collections of numerical data that all have the same type, it + is often **more efficient** to use the ``array`` type provided by + the ``numpy`` module. A NumPy array is a chunk of memory + containing fixed-sized items. With NumPy arrays, operations on + elements can be faster because elements are regularly spaced in + memory and more operations are performed through specialized C + functions instead of Python loops. + + +.. tip:: + + Python offers a large panel of functions to modify lists, or query + them. Here are a few examples; for more details, see + https://docs.python.org/3/tutorial/datastructures.html#more-on-lists + +Add and remove elements:: + + >>> colors = ['red', 'blue', 'green', 'black', 'white'] + >>> colors.append('pink') + >>> colors + ['red', 'blue', 'green', 'black', 'white', 'pink'] + >>> colors.pop() # removes and returns the last item + 'pink' + >>> colors + ['red', 'blue', 'green', 'black', 'white'] + >>> colors.extend(['pink', 'purple']) # extend colors, in-place + >>> colors + ['red', 'blue', 'green', 'black', 'white', 'pink', 'purple'] + >>> colors = colors[:-2] + >>> colors + ['red', 'blue', 'green', 'black', 'white'] + +Reverse:: + + >>> rcolors = colors[::-1] + >>> rcolors + ['white', 'black', 'green', 'blue', 'red'] + >>> rcolors2 = list(colors) # new object that is a copy of colors in a different memory area + >>> rcolors2 + ['red', 'blue', 'green', 'black', 'white'] + >>> rcolors2.reverse() # in-place; reversing rcolors2 does not affect colors + >>> rcolors2 + ['white', 'black', 'green', 'blue', 'red'] + +Concatenate and repeat lists:: + + >>> rcolors + colors + ['white', 'black', 'green', 'blue', 'red', 'red', 'blue', 'green', 'black', 'white'] + >>> rcolors * 2 + ['white', 'black', 'green', 'blue', 'red', 'white', 'black', 'green', 'blue', 'red'] + + +.. tip:: + + Sort:: + + >>> sorted(rcolors) # new object + ['black', 'blue', 'green', 'red', 'white'] + >>> rcolors + ['white', 'black', 'green', 'blue', 'red'] + >>> rcolors.sort() # in-place + >>> rcolors + ['black', 'blue', 'green', 'red', 'white'] + +.. topic:: **Methods and Object-Oriented Programming** + + The notation ``rcolors.method()`` (e.g. ``rcolors.append(3)`` and ``colors.pop()``) is our + first example of object-oriented programming (OOP). Being a ``list``, the + object `rcolors` owns the *method* `function` that is called using the notation + **.**. No further knowledge of OOP than understanding the notation **.** is + necessary for going through this tutorial. + + +.. topic:: **Discovering methods:** + + Reminder: in Ipython: tab-completion (press tab) + + .. ipython:: + + @verbatim + In [28]: rcolors. + append() count() insert() reverse() + clear() extend() pop() sort() + copy() index() remove() + +Strings +~~~~~~~ + +Different string syntaxes (simple, double or triple quotes):: + + s = 'Hello, how are you?' + s = "Hi, what's up" + s = '''Hello, + how are you''' # tripling the quotes allows the + # string to span more than one line + s = """Hi, + what's up?""" + +.. ipython:: + :okexcept: + + In [1]: 'Hi, what's up?' + +This syntax error can be avoided by enclosing the string in double quotes +instead of single quotes. Alternatively, one can prepend a backslash to the +second single quote. Other uses of the backslash are, e.g., the newline character +``\n`` and the tab character ``\t``. + +.. tip:: + + Strings are collections like lists. Hence they can be indexed and + sliced, using the same syntax and rules. + +Indexing:: + + >>> a = "hello" + >>> a[0] + 'h' + >>> a[1] + 'e' + >>> a[-1] + 'o' + +.. tip:: + + (Remember that negative indices correspond to counting from the right + end.) + +Slicing:: + + + >>> a = "hello, world!" + >>> a[3:6] # 3rd to 6th (excluded) elements: elements 3, 4, 5 + 'lo,' + >>> a[2:10:2] # Syntax: a[start:stop:step] + 'lo o' + >>> a[::3] # every three characters, from beginning to end + 'hl r!' + +.. tip:: + + Accents and special characters can also be handled as in Python 3 + strings consist of Unicode characters. + + +A string is an **immutable object** and it is not possible to modify its +contents. One may however create new strings from the original one. + +.. ipython:: + + In [53]: a = "hello, world!" + In [54]: a[2] = 'z' + --------------------------------------------------------------------------- + Traceback (most recent call last): + File "", line 1, in + TypeError: 'str' object does not support item assignment + + In [55]: a.replace('l', 'z', 1) + Out[55]: 'hezlo, world!' + In [56]: a.replace('l', 'z') + Out[56]: 'hezzo, worzd!' + +.. tip:: + + Strings have many useful methods, such as ``a.replace`` as seen + above. Remember the ``a.`` object-oriented notation and use tab + completion or ``help(str)`` to search for new methods. + +.. seealso:: + + Python offers advanced possibilities for manipulating strings, + looking for patterns or formatting. The interested reader is referred to + https://docs.python.org/3/library/stdtypes.html#string-methods and + https://docs.python.org/3/library/string.html#format-string-syntax + +String formatting:: + + >>> 'An integer: %i; a float: %f; another string: %s' % (1, 0.1, 'string') # with more values use tuple after % + 'An integer: 1; a float: 0.100000; another string: string' + + >>> i = 102 + >>> filename = 'processing_of_dataset_%d.txt' % i # no need for tuples with just one value after % + >>> filename + 'processing_of_dataset_102.txt' + +Dictionaries +~~~~~~~~~~~~~ + +.. tip:: + + A dictionary is basically an efficient table that **maps keys to + values**. + +:: + + >>> tel = {'emmanuelle': 5752, 'sebastian': 5578} + >>> tel['francis'] = 5915 + >>> tel + {'emmanuelle': 5752, 'sebastian': 5578, 'francis': 5915} + >>> tel['sebastian'] + 5578 + >>> tel.keys() + dict_keys(['emmanuelle', 'sebastian', 'francis']) + >>> tel.values() + dict_values([5752, 5578, 5915]) + >>> 'francis' in tel + True + +.. tip:: + + It can be used to conveniently store and retrieve values + associated with a name (a string for a date, a name, etc.). See + https://docs.python.org/3/tutorial/datastructures.html#dictionaries + for more information. + + A dictionary can have keys (resp. values) with different types:: + + >>> d = {'a':1, 'b':2, 3:'hello'} + >>> d + {'a': 1, 'b': 2, 3: 'hello'} + +More container types +~~~~~~~~~~~~~~~~~~~~ + +**Tuples** + +Tuples are basically immutable lists. The elements of a tuple are written +between parentheses, or just separated by commas:: + + >>> t = 12345, 54321, 'hello!' + >>> t[0] + 12345 + >>> t + (12345, 54321, 'hello!') + >>> u = (0, 2) + +**Sets:** unordered, unique items:: + + >>> s = set(('a', 'b', 'c', 'a')) + >>> s # doctest: +SKIP + {'a', 'b', 'c'} + >>> s.difference(('a', 'b')) + {'c'} + +Assignment operator +------------------- + +.. tip:: + + `Python library reference + `_ + says: + + Assignment statements are used to (re)bind names to values and to + modify attributes or items of mutable objects. + + In short, it works as follows (simple assignment): + + #. an expression on the right hand side is evaluated, the corresponding + object is created/obtained + #. a **name** on the left hand side is assigned, or bound, to the + r.h.s. object + +Things to note: + +* A single object can have several names bound to it: + +.. ipython:: + + In [1]: a = [1, 2, 3] + + In [2]: b = a + + In [3]: a + Out[3]: [1, 2, 3] + + In [4]: b + Out[4]: [1, 2, 3] + + In [5]: a is b + Out[5]: True + + In [6]: b[1] = 'hi!' + + In [7]: a + Out[7]: [1, 'hi!', 3] + +* to change a list *in place*, use indexing/slices: + +.. ipython:: + + In [1]: a = [1, 2, 3] + + In [3]: a + Out[3]: [1, 2, 3] + + In [4]: a = ['a', 'b', 'c'] # Creates another object. + + In [5]: a + Out[5]: ['a', 'b', 'c'] + + In [6]: id(a) + Out[6]: 138641676 + + In [7]: a[:] = [1, 2, 3] # Modifies object in place. + + In [8]: a + Out[8]: [1, 2, 3] + + In [9]: id(a) + Out[9]: 138641676 # Same as in Out[6], yours will differ... + +* the key concept here is **mutable vs. immutable** + + * mutable objects can be changed in place + * immutable objects cannot be modified once created + +.. seealso:: A very good and detailed explanation of the above issues can + be found in David M. Beazley's article `Types and Objects in Python + `_. diff --git a/_sources/intro/language/control_flow.rst.txt b/_sources/intro/language/control_flow.rst.txt new file mode 100644 index 000000000..0d073100b --- /dev/null +++ b/_sources/intro/language/control_flow.rst.txt @@ -0,0 +1,257 @@ +Control Flow +============ + +Controls the order in which the code is executed. + +if/elif/else +------------ + +.. code-block:: pycon + + >>> if 2**2 == 4: + ... print("Obvious!") + ... + Obvious! + + +**Blocks are delimited by indentation** + +.. tip:: + + Type the following lines in your Python interpreter, and be careful + to **respect the indentation depth**. The Ipython shell automatically + increases the indentation depth after a colon ``:`` sign; to + decrease the indentation depth, go four spaces to the left with the + Backspace key. Press the Enter key twice to leave the logical block. + +.. code-block:: pycon + + >>> a = 10 + + >>> if a == 1: + ... print(1) + ... elif a == 2: + ... print(2) + ... else: + ... print("A lot") + ... + A lot + +Indentation is compulsory in scripts as well. As an exercise, re-type the +previous lines with the same indentation in a script ``condition.py``, and +execute the script with ``run condition.py`` in Ipython. + +for/range +---------- + +Iterating with an index:: + + >>> for i in range(4): + ... print(i) + 0 + 1 + 2 + 3 + +But most often, it is more readable to iterate over values:: + + >>> for word in ('cool', 'powerful', 'readable'): + ... print('Python is %s' % word) + Python is cool + Python is powerful + Python is readable + + +while/break/continue +--------------------- + +Typical C-style while loop (Mandelbrot problem):: + + >>> z = 1 + 1j + >>> while abs(z) < 100: + ... z = z**2 + 1 + >>> z + (-134+352j) + +**More advanced features** + +``break`` out of enclosing for/while loop:: + + >>> z = 1 + 1j + + >>> while abs(z) < 100: + ... if z.imag == 0: + ... break + ... z = z**2 + 1 + + +``continue`` the next iteration of a loop.:: + + >>> a = [1, 0, 2, 4] + >>> for element in a: + ... if element == 0: + ... continue + ... print(1. / element) + 1.0 + 0.5 + 0.25 + + + +Conditional Expressions +----------------------- + +:``if ``: + + Evaluates to False: + * any number equal to zero (0, 0.0, 0+0j) + * an empty container (list, tuple, set, dictionary, ...) + * ``False``, ``None`` + + Evaluates to True: + * everything else + +:``a == b``: + + Tests equality, with logics:: + + >>> 1 == 1. + True + +:``a is b``: + + Tests identity: both sides are the same object:: + + >>> a = 1 + >>> b = 1. + >>> a == b + True + >>> a is b + False + + >>> a = 1 + >>> b = 1 + >>> a is b + True + +:``a in b``: + + For any collection ``b``: ``b`` contains ``a`` :: + + >>> b = [1, 2, 3] + >>> 2 in b + True + >>> 5 in b + False + + + If ``b`` is a dictionary, this tests that ``a`` is a key of ``b``. + +Advanced iteration +------------------------- + +Iterate over any *sequence* +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can iterate over any sequence (string, list, keys in a dictionary, lines in +a file, ...):: + + >>> vowels = 'aeiouy' + + >>> for i in 'powerful': + ... if i in vowels: + ... print(i) + o + e + u + +:: + + >>> message = "Hello how are you?" + >>> message.split() # returns a list + ['Hello', 'how', 'are', 'you?'] + >>> for word in message.split(): + ... print(word) + ... + Hello + how + are + you? + +.. tip:: + + Few languages (in particular, languages for scientific computing) allow to + loop over anything but integers/indices. With Python it is possible to + loop exactly over the objects of interest without bothering with indices + you often don't care about. This feature can often be used to make + code more readable. + + +.. warning:: Not safe to modify the sequence you are iterating over. + +Keeping track of enumeration number +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Common task is to iterate over a sequence while keeping track of the +item number. + +* Could use while loop with a counter as above. Or a for loop:: + + >>> words = ('cool', 'powerful', 'readable') + >>> for i in range(0, len(words)): + ... print((i, words[i])) + (0, 'cool') + (1, 'powerful') + (2, 'readable') + +* But, Python provides a built-in function - ``enumerate`` - for this:: + + >>> for index, item in enumerate(words): + ... print((index, item)) + (0, 'cool') + (1, 'powerful') + (2, 'readable') + + + +Looping over a dictionary +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Use **items**:: + + >>> d = {'a': 1, 'b':1.2, 'c':1j} + + >>> for key, val in sorted(d.items()): + ... print('Key: %s has value: %s' % (key, val)) + Key: a has value: 1 + Key: b has value: 1.2 + Key: c has value: 1j + +.. note:: + + The ordering of a dictionary is random, thus we use :func:`sorted` + which will sort on the keys. + +List Comprehensions +------------------- + +Instead of creating a list by means of a loop, one can make use +of a list comprehension with a rather self-explaining syntax. + +:: + + >>> [i**2 for i in range(4)] + [0, 1, 4, 9] + +_____ + + +.. topic:: Exercise + :class: green + + Compute the decimals of Pi using the Wallis formula: + + .. math:: + \pi = 2 \prod_{i=1}^{\infty} \frac{4i^2}{4i^2 - 1} + +.. :ref:`pi_wallis` diff --git a/_sources/intro/language/exceptions.rst.txt b/_sources/intro/language/exceptions.rst.txt new file mode 100644 index 000000000..3c333a79f --- /dev/null +++ b/_sources/intro/language/exceptions.rst.txt @@ -0,0 +1,161 @@ +Exception handling in Python +============================ + +It is likely that you have raised Exceptions if you have +typed all the previous commands of the tutorial. For example, you may +have raised an exception if you entered a command with a typo. + +Exceptions are raised by different kinds of errors arising when executing +Python code. In your own code, you may also catch errors, or define custom +error types. You may want to look at the descriptions of the `the built-in +Exceptions `_ when looking +for the right exception type. + +Exceptions +----------- + +Exceptions are raised by errors in Python: + +.. ipython:: + :okexcept: + + In [1]: 1/0 + + In [2]: 1 + 'e' + + In [3]: d = {1:1, 2:2} + + In [4]: d[3] + + In [5]: l = [1, 2, 3] + + In [6]: l[4] + + In [7]: l.foobar + +As you can see, there are **different types** of exceptions for different errors. + +Catching exceptions +-------------------- + +try/except +~~~~~~~~~~~ + +.. ipython:: + :verbatim: + + In [10]: while True: + ....: try: + ....: x = int(input('Please enter a number: ')) + ....: break + ....: except ValueError: + ....: print('That was no valid number. Try again...') + ....: + Please enter a number: a + That was no valid number. Try again... + Please enter a number: 1 + + In [9]: x + Out[9]: 1 + +try/finally +~~~~~~~~~~~~ + +.. ipython:: + :verbatim: + + In [10]: try: + ....: x = int(input('Please enter a number: ')) + ....: finally: + ....: print('Thank you for your input') + ....: + Please enter a number: a + Thank you for your input + --------------------------------------------------------------------------- + ValueError Traceback (most recent call last) + Cell In[10], line 2 + 1 try: + ----> 2 x = int(input('Please enter a number: ')) + 3 finally: + 4 print('Thank you for your input') + ValueError: invalid literal for int() with base 10: 'a' + +Important for resource management (e.g. closing a file) + +Easier to ask for forgiveness than for permission +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +.. ipython:: + + In [11]: def print_sorted(collection): + ....: try: + ....: collection.sort() + ....: except AttributeError: + ....: pass # The pass statement does nothing + ....: print(collection) + ....: + + In [12]: print_sorted([1, 3, 2]) + [1, 2, 3] + + In [13]: print_sorted(set((1, 3, 2))) + set([1, 2, 3]) + + In [14]: print_sorted('132') + 132 + + +Raising exceptions +------------------ + +* Capturing and reraising an exception: + + .. ipython:: + :okexcept: + + In [15]: def filter_name(name): + ....: try: + ....: name = name.encode('ascii') + ....: except UnicodeError as e: + ....: if name == 'Gaël': + ....: print('OK, Gaël') + ....: else: + ....: raise e + ....: return name + ....: + + In [16]: filter_name('Gaël') + OK, Gaël + Out[16]: 'Ga\xc3\xabl' + + In [17]: filter_name('Stéfan') + + +* Exceptions to pass messages between parts of the code: + + .. ipython:: + + In [17]: def achilles_arrow(x): + ....: if abs(x - 1) < 1e-3: + ....: raise StopIteration + ....: x = 1 - (1-x)/2. + ....: return x + ....: + + In [18]: x = 0 + + In [19]: while True: + ....: try: + ....: x = achilles_arrow(x) + ....: except StopIteration: + ....: break + ....: + ....: + + In [20]: x + Out[20]: 0.9990234375 + + +Use exceptions to notify certain conditions are met (e.g. +StopIteration) or not (e.g. custom error raising) diff --git a/_sources/intro/language/first_steps.rst.txt b/_sources/intro/language/first_steps.rst.txt new file mode 100644 index 000000000..1ea1d3353 --- /dev/null +++ b/_sources/intro/language/first_steps.rst.txt @@ -0,0 +1,68 @@ +First steps +------------- + + +Start the **Ipython** shell (an enhanced interactive Python shell): + +* by typing "ipython" from a Linux/Mac terminal, or from the Windows cmd shell, +* **or** by starting the program from a menu, e.g. the `Anaconda Navigator`_, + the `Python(x,y)`_ menu if you have installed one of these + scientific-Python suites. + +.. _`Python(x,y)`: https://python-xy.github.io/ +.. _`Anaconda Navigator`: https://anaconda.org/anaconda/anaconda-navigator + +.. tip:: + + If you don't have Ipython installed on your computer, other Python + shells are available, such as the plain Python shell started by + typing "python" in a terminal, or the Idle interpreter. However, we + advise to use the Ipython shell because of its enhanced features, + especially for interactive scientific computing. + +Once you have started the interpreter, type :: + + >>> print("Hello, world!") + Hello, world! + +.. tip:: + + The message "Hello, world!" is then displayed. You just executed your + first Python instruction, congratulations! + +To get yourself started, type the following stack of instructions :: + + >>> a = 3 + >>> b = 2*a + >>> type(b) + + >>> print(b) + 6 + >>> a*b + 18 + >>> b = 'hello' + >>> type(b) + + >>> b + b + 'hellohello' + >>> 2*b + 'hellohello' + +.. tip:: + + Two variables ``a`` and ``b`` have been defined above. Note that one does + not declare the type of a variable before assigning its value. In C, + conversely, one should write: + + .. sourcecode:: c + + int a = 3; + + In addition, the type of a variable may change, in the sense that at + one point in time it can be equal to a value of a certain type, and a + second point in time, it can be equal to a value of a different + type. `b` was first equal to an integer, but it became equal to a + string when it was assigned the value `'hello'`. Operations on + integers (``b=2*a``) are coded natively in Python, and so are some + operations on strings such as additions and multiplications, which + amount respectively to concatenation and repetition. diff --git a/_sources/intro/language/functions.rst.txt b/_sources/intro/language/functions.rst.txt new file mode 100644 index 000000000..7894204a4 --- /dev/null +++ b/_sources/intro/language/functions.rst.txt @@ -0,0 +1,392 @@ +Defining functions +===================== + +Function definition +------------------- + +.. ipython:: + + In [56]: def test(): + ....: print('in test function') + ....: + ....: + + In [57]: test() + in test function + +.. Warning:: + + Function blocks must be indented as other control-flow blocks. + +Return statement +---------------- + +Functions can *optionally* return values. + +.. ipython:: + + In [6]: def disk_area(radius): + ...: return 3.14 * radius * radius + ...: + + In [8]: disk_area(1.5) + Out[8]: 7.0649999999999995 + +.. Note:: By default, functions return ``None``. + +.. Note:: Note the syntax to define a function: + + * the ``def`` keyword; + + * is followed by the function's **name**, then + + * the arguments of the function are given between parentheses followed + by a colon. + + * the function body; + + * and ``return object`` for optionally returning values. + + +Parameters +---------- + +Mandatory parameters (positional arguments) + +.. ipython:: + :okexcept: + + In [81]: def double_it(x): + ....: return x * 2 + ....: + + In [82]: double_it(3) + Out[82]: 6 + + In [83]: double_it() + +Optional parameters (keyword or named arguments) + +.. ipython:: + + In [84]: def double_it(x=2): + ....: return x * 2 + ....: + + In [85]: double_it() + Out[85]: 4 + + In [86]: double_it(3) + Out[86]: 6 + +Keyword arguments allow you to specify *default values*. + +.. warning:: + + Default values are evaluated when the function is defined, not when + it is called. This can be problematic when using mutable types (e.g. + dictionary or list) and modifying them in the function body, since the + modifications will be persistent across invocations of the function. + + Using an immutable type in a keyword argument: + + .. ipython:: + + In [124]: bigx = 10 + + In [125]: def double_it(x=bigx): + .....: return x * 2 + .....: + + In [126]: bigx = 1e9 # Now really big + + In [128]: double_it() + Out[128]: 20 + + Using an mutable type in a keyword argument (and modifying it inside the + function body): + + .. ipython:: + + In [2]: def add_to_dict(args={'a': 1, 'b': 2}): + ...: for i in args.keys(): + ...: args[i] += 1 + ...: print(args) + ...: + + In [3]: add_to_dict + Out[3]: + + In [4]: add_to_dict() + {'a': 2, 'b': 3} + + In [5]: add_to_dict() + {'a': 3, 'b': 4} + + In [6]: add_to_dict() + {'a': 4, 'b': 5} + +.. tip:: + + More involved example implementing python's slicing: + + .. ipython:: + + In [98]: def slicer(seq, start=None, stop=None, step=None): + ....: """Implement basic python slicing.""" + ....: return seq[start:stop:step] + ....: + + In [101]: rhyme = 'one fish, two fish, red fish, blue fish'.split() + + In [102]: rhyme + Out[102]: ['one', 'fish,', 'two', 'fish,', 'red', 'fish,', 'blue', 'fish'] + + In [103]: slicer(rhyme) + Out[103]: ['one', 'fish,', 'two', 'fish,', 'red', 'fish,', 'blue', 'fish'] + + In [104]: slicer(rhyme, step=2) + Out[104]: ['one', 'two', 'red', 'blue'] + + In [105]: slicer(rhyme, 1, step=2) + Out[105]: ['fish,', 'fish,', 'fish,', 'fish'] + + In [106]: slicer(rhyme, start=1, stop=4, step=2) + Out[106]: ['fish,', 'fish,'] + + The order of the keyword arguments does not matter: + + .. ipython:: + + In [107]: slicer(rhyme, step=2, start=1, stop=4) + Out[107]: ['fish,', 'fish,'] + + but it is good practice to use the same ordering as the function's + definition. + +*Keyword arguments* are a very convenient feature for defining functions +with a variable number of arguments, especially when default values are +to be used in most calls to the function. + +Passing by value +---------------- + +.. tip:: + + Can you modify the value of a variable inside a function? Most languages + (C, Java, ...) distinguish "passing by value" and "passing by reference". + In Python, such a distinction is somewhat artificial, and it is a bit + subtle whether your variables are going to be modified or not. + Fortunately, there exist clear rules. + + Parameters to functions are references to objects, which are passed by + value. When you pass a variable to a function, python passes the + reference to the object to which the variable refers (the **value**). + Not the variable itself. + +If the **value** passed in a function is immutable, the function does not +modify the caller's variable. If the **value** is mutable, the function +may modify the caller's variable in-place:: + + >>> def try_to_modify(x, y, z): + ... x = 23 + ... y.append(42) + ... z = [99] # new reference + ... print(x) + ... print(y) + ... print(z) + ... + >>> a = 77 # immutable variable + >>> b = [99] # mutable variable + >>> c = [28] + >>> try_to_modify(a, b, c) + 23 + [99, 42] + [99] + >>> print(a) + 77 + >>> print(b) + [99, 42] + >>> print(c) + [28] + + + +Functions have a local variable table called a *local namespace*. + +The variable ``x`` only exists within the function ``try_to_modify``. + + +Global variables +---------------- + +Variables declared outside the function can be referenced within the +function: + +.. ipython:: + + In [114]: x = 5 + + In [115]: def addx(y): + .....: return x + y + .....: + + In [116]: addx(10) + Out[116]: 15 + +But these "global" variables cannot be modified within the function, +unless declared **global** in the function. + +This doesn't work: + +.. ipython:: + + In [117]: def setx(y): + .....: x = y + .....: print('x is %d' % x) + .....: + .....: + + In [118]: setx(10) + x is 10 + + In [120]: x + Out[120]: 5 + +This works: + +.. ipython:: + + In [121]: def setx(y): + .....: global x + .....: x = y + .....: print('x is %d' % x) + .....: + .....: + + In [122]: setx(10) + x is 10 + + In [123]: x + Out[123]: 10 + + +Variable number of parameters +----------------------------- +Special forms of parameters: + * ``*args``: any number of positional arguments packed into a tuple + * ``**kwargs``: any number of keyword arguments packed into a dictionary + +.. ipython:: + + In [35]: def variable_args(*args, **kwargs): + ....: print('args is', args) + ....: print('kwargs is', kwargs) + ....: + + In [36]: variable_args('one', 'two', x=1, y=2, z=3) + args is ('one', 'two') + kwargs is {'x': 1, 'y': 2, 'z': 3} + + +Docstrings +---------- + +Documentation about what the function does and its parameters. General +convention: + +.. ipython:: + + In [67]: def funcname(params): + ....: """Concise one-line sentence describing the function. + ....: + ....: Extended summary which can contain multiple paragraphs. + ....: """ + ....: # function body + ....: pass + ....: + + @verbatim + In [68]: funcname? + Signature: funcname(params) + Docstring: + Concise one-line sentence describing the function. + Extended summary which can contain multiple paragraphs. + File: ~/src/scientific-python-lectures/ + Type: function + +.. Note:: **Docstring guidelines** + + + For the sake of standardization, the `Docstring + Conventions `_ webpage + documents the semantics and conventions associated with Python + docstrings. + + Also, the NumPy and SciPy modules have defined a precise standard + for documenting scientific functions, that you may want to follow for + your own functions, with a ``Parameters`` section, an ``Examples`` + section, etc. See + https://numpydoc.readthedocs.io/en/latest/format.html#docstring-standard + +Functions are objects +--------------------- +Functions are first-class objects, which means they can be: + * assigned to a variable + * an item in a list (or any collection) + * passed as an argument to another function. + +.. ipython:: + + In [38]: va = variable_args + + In [39]: va('three', x=1, y=2) + args is ('three',) + kwargs is {'x': 1, 'y': 2} + + +Methods +------- + +Methods are functions attached to objects. You've seen these in our +examples on *lists*, *dictionaries*, *strings*, etc... + + +Exercises +--------- + +.. topic:: Exercise: Fibonacci sequence + :class: green + + Write a function that displays the ``n`` first terms of the Fibonacci + sequence, defined by: + + .. math:: + \left\{ + \begin{array}{ll} + U_{0} = 0 \\ + U_{1} = 1 \\ + U_{n+2} = U_{n+1} + U_{n} + \end{array} + \right. + +.. :ref:`fibonacci` + +.. topic:: Exercise: Quicksort + :class: green + + Implement the quicksort algorithm, as defined by wikipedia + +.. parsed-literal:: + + function quicksort(array) + var list less, greater + if length(array) < 2 + return array + select and remove a pivot value pivot from array + for each x in array + if x < pivot + 1 then append x to less + else append x to greater + return concatenate(quicksort(less), pivot, quicksort(greater)) + +.. :ref:`quick_sort` diff --git a/_sources/intro/language/io.rst.txt b/_sources/intro/language/io.rst.txt new file mode 100644 index 000000000..17e08cbed --- /dev/null +++ b/_sources/intro/language/io.rst.txt @@ -0,0 +1,65 @@ +Input and Output +================ + +To be exhaustive, here are some information about input and output in +Python. Since we will use the NumPy methods to read and write files, +**you may skip this chapter at first reading**. + +We write or read **strings** to/from files (other types must be converted to +strings). To write in a file:: + + >>> f = open('workfile', 'w') # opens the workfile file + >>> type(f) + + >>> f.write('This is a test \nand another test') # doctest: +SKIP + >>> f.close() + +To read from a file + +.. ipython:: + :verbatim: + + In [1]: f = open('workfile', 'r') + + In [2]: s = f.read() + + In [3]: print(s) + This is a test + and another test + + In [4]: f.close() + + +.. seealso:: + + For more details: https://docs.python.org/3/tutorial/inputoutput.html + +Iterating over a file +~~~~~~~~~~~~~~~~~~~~~ + +.. ipython:: + :verbatim: + + In [6]: f = open('workfile', 'r') + + In [7]: for line in f: + ...: print(line) + ...: + This is a test + and another test + + In [8]: f.close() + +File modes +---------- + +* Read-only: ``r`` +* Write-only: ``w`` + + * Note: Create a new file or *overwrite* existing file. + +* Append a file: ``a`` +* Read and Write: ``r+`` +* Binary mode: ``b`` + + * Note: Use for binary files, especially on Windows. diff --git a/_sources/intro/language/oop.rst.txt b/_sources/intro/language/oop.rst.txt new file mode 100644 index 000000000..24274b63d --- /dev/null +++ b/_sources/intro/language/oop.rst.txt @@ -0,0 +1,57 @@ +Object-oriented programming (OOP) +================================= + +Python supports object-oriented programming (OOP). The goals of OOP are: + + * to organize the code, and + + * to reuse code in similar contexts. + + +Here is a small example: we create a Student *class*, which is an object +gathering several custom functions (*methods*) and variables (*attributes*), +we will be able to use:: + + >>> class Student(object): + ... def __init__(self, name): + ... self.name = name + ... def set_age(self, age): + ... self.age = age + ... def set_major(self, major): + ... self.major = major + ... + >>> anna = Student('anna') + >>> anna.set_age(21) + >>> anna.set_major('physics') + +In the previous example, the Student class has ``__init__``, ``set_age`` and +``set_major`` methods. Its attributes are ``name``, ``age`` and ``major``. We +can call these methods and attributes with the following notation: +``classinstance.method`` or ``classinstance.attribute``. The ``__init__`` +constructor is a special method we call with: ``MyClass(init parameters if +any)``. + +Now, suppose we want to create a new class MasterStudent with the same +methods and attributes as the previous one, but with an additional +``internship`` attribute. We won't copy the previous class, but +**inherit** from it:: + + >>> class MasterStudent(Student): + ... internship = 'mandatory, from March to June' + ... + >>> james = MasterStudent('james') + >>> james.internship + 'mandatory, from March to June' + >>> james.set_age(23) + >>> james.age + 23 + +The MasterStudent class inherited from the Student attributes and methods. + +Thanks to classes and object-oriented programming, we can organize code +with different classes corresponding to different objects we encounter +(an Experiment class, an Image class, a Flow class, etc.), with their own +methods and attributes. Then we can use inheritance to consider +variations around a base class and **reuse** code. Ex : from a Flow +base class, we can create derived StokesFlow, TurbulentFlow, +PotentialFlow, etc. diff --git a/_sources/intro/language/python_language.rst.txt b/_sources/intro/language/python_language.rst.txt new file mode 100644 index 000000000..f80173377 --- /dev/null +++ b/_sources/intro/language/python_language.rst.txt @@ -0,0 +1,71 @@ +.. _python_language_chapter: + +The Python language +===================================== + +**Authors**: *Chris Burns, Christophe Combelles, Emmanuelle Gouillart, +Gaël Varoquaux* + +.. topic:: Python for scientific computing + + We introduce here the Python language. Only the bare minimum + necessary for getting started with NumPy and SciPy is addressed here. + To learn more about the language, consider going through the + excellent tutorial https://docs.python.org/3/tutorial. Dedicated books + are also available, such as `Dive into Python 3 `__. + + +.. image:: python-logo.png + :align: right + +.. tip:: + + Python is a **programming language**, as are C, Fortran, BASIC, PHP, + etc. Some specific features of Python are as follows: + + * an *interpreted* (as opposed to *compiled*) language. Contrary to e.g. + C or Fortran, one does not compile Python code before executing it. In + addition, Python can be used **interactively**: many Python + interpreters are available, from which commands and scripts can be + executed. + + * a free software released under an **open-source** license: Python can + be used and distributed free of charge, even for building commercial + software. + + * **multi-platform**: Python is available for all major operating + systems, Windows, Linux/Unix, MacOS X, most likely your mobile phone + OS, etc. + + * a very readable language with clear non-verbose syntax + + * a language for which a large variety of high-quality packages are + available for various applications, from web frameworks to scientific + computing. + + * a language very easy to interface with other languages, in particular C + and C++. + + * Some other features of the language are illustrated just below. For + example, Python is an object-oriented language, with dynamic typing + (the same variable can contain objects of different types during the + course of a program). + + + See https://www.python.org/about/ for more information about + distinguishing features of Python. + +_____ + +.. toctree:: + :maxdepth: 2 + + first_steps.rst + basic_types.rst + control_flow.rst + functions.rst + reusing_code.rst + io.rst + standard_library.rst + exceptions.rst + oop.rst diff --git a/_sources/intro/language/reusing_code.rst.txt b/_sources/intro/language/reusing_code.rst.txt new file mode 100644 index 000000000..548902f74 --- /dev/null +++ b/_sources/intro/language/reusing_code.rst.txt @@ -0,0 +1,513 @@ +Reusing code: scripts and modules +================================= + +For now, we have typed all instructions in the interpreter. For longer +sets of instructions we need to change track and write the code in text +files (using a text editor), that we will call either *scripts* or +*modules*. Use your favorite text editor (provided it offers syntax +highlighting for Python), or the editor that comes with the Scientific +Python Suite you may be using. + +Scripts +------- + +.. tip:: + + Let us first write a *script*, that is a file with a sequence of + instructions that are executed each time the script is called. + Instructions may be e.g. copied-and-pasted from the interpreter (but + take care to respect indentation rules!). + +The extension for Python files is ``.py``. Write or copy-and-paste the +following lines in a file called ``test.py`` :: + + message = "Hello how are you?" + for word in message.split(): + print(word) + +.. tip:: + + Let us now execute the script interactively, that is inside the + Ipython interpreter. This is maybe the most common use of scripts in + scientific computing. + +.. note:: + + in Ipython, the syntax to execute a script is ``%run script.py``. For + example, + +.. ipython:: + :verbatim: + + In [1]: %run test.py + Hello + how + are + you? + + In [2]: message + Out[2]: 'Hello how are you?' + + +The script has been executed. Moreover the variables defined in the +script (such as ``message``) are now available inside the interpreter's +namespace. + +.. tip:: + + Other interpreters also offer the possibility to execute scripts + (e.g., ``execfile`` in the plain Python interpreter, etc.). + +It is also possible In order to execute this script as a *standalone +program*, by executing the script inside a shell terminal (Linux/Mac +console or cmd Windows console). For example, if we are in the same +directory as the test.py file, we can execute this in a console: + +.. sourcecode:: bash + + $ python test.py + Hello + how + are + you? + +.. tip:: + + Standalone scripts may also take command-line arguments + + In ``file.py``:: + + import sys + print(sys.argv) + + .. sourcecode:: bash + + $ python file.py test arguments + ['file.py', 'test', 'arguments'] + + .. warning:: + + Don't implement option parsing yourself. Use a dedicated module such as + :mod:`argparse`. + + +Importing objects from modules +------------------------------ + +.. ipython:: + + In [1]: import os + + In [2]: os + Out[2]: + + In [3]: os.listdir('.') + Out[3]: + ['conf.py', + 'basic_types.rst', + 'control_flow.rst', + 'functions.rst', + 'python_language.rst', + 'reusing.rst', + 'file_io.rst', + 'exceptions.rst', + 'workflow.rst', + 'index.rst'] + +And also: + +.. ipython:: + + In [4]: from os import listdir + +Importing shorthands: + +.. ipython:: + + In [5]: import numpy as np + +.. warning:: + + :: + + from os import * + + This is called the *star import* and please, **Do not use it** + + * Makes the code harder to read and understand: where do symbols come + from? + + * Makes it impossible to guess the functionality by the context and + the name (hint: `os.name` is the name of the OS), and to profit + usefully from tab completion. + + * Restricts the variable names you can use: `os.name` might override + `name`, or vise-versa. + + * Creates possible name clashes between modules. + + * Makes the code impossible to statically check for undefined + symbols. + +.. tip:: + + Modules are thus a good way to organize code in a hierarchical way. Actually, + all the scientific computing tools we are going to use are modules:: + + >>> import numpy as np # data arrays + >>> np.linspace(0, 10, 6) + array([ 0., 2., 4., 6., 8., 10.]) + >>> import scipy as sp # scientific computing + + +Creating modules +----------------- + +.. tip:: + + If we want to write larger and better organized programs (compared to + simple scripts), where some objects are defined, (variables, + functions, classes) and that we want to reuse several times, we have + to create our own *modules*. + +Let us create a module ``demo`` contained in the file ``demo.py``: + + .. literalinclude:: demo.py + +.. tip:: + + In this file, we defined two functions ``print_a`` and ``print_b``. Suppose + we want to call the ``print_a`` function from the interpreter. We could + execute the file as a script, but since we just want to have access to + the function ``print_a``, we are rather going to **import it as a module**. + The syntax is as follows. + + +.. ipython:: + :verbatim: + + In [1]: import demo + + + In [2]: demo.print_a() + a + + In [3]: demo.print_b() + b + +Importing the module gives access to its objects, using the +``module.object`` syntax. Don't forget to put the module's name before the +object's name, otherwise Python won't recognize the instruction. + + +Introspection + +.. ipython:: + :verbatim: + + In [4]: demo? + Type: module + Base Class: + String Form: + Namespace: Interactive + File: /home/varoquau/Projects/Python_talks/scipy_2009_tutorial/source/demo.py + Docstring: + A demo module. + + + In [5]: who + demo + + In [6]: whos + Variable Type Data/Info + ------------------------------ + demo module + + In [7]: dir(demo) + Out[7]: + ['__builtins__', + '__doc__', + '__file__', + '__name__', + '__package__', + 'c', + 'd', + 'print_a', + 'print_b'] + + + In [8]: demo. + demo.c demo.print_a demo.py + demo.d demo.print_b demo.pyc + + +Importing objects from modules into the main namespace + +.. ipython:: + :verbatim: + + In [9]: from demo import print_a, print_b + + In [10]: whos + Variable Type Data/Info + -------------------------------- + demo module + print_a function + print_b function + + In [11]: print_a() + a + +.. warning:: + + **Module caching** + + Modules are cached: if you modify ``demo.py`` and re-import it in the + old session, you will get the old one. + + Solution: + + .. sourcecode :: ipython + + In [10]: importlib.reload(demo) + +'__main__' and module loading +------------------------------ + +.. tip:: + + Sometimes we want code to be executed when a module is + run directly, but not when it is imported by another module. + ``if __name__ == '__main__'`` allows us to check whether the + module is being run directly. + +File ``demo2.py``: + + .. literalinclude:: demo2.py + +Importing it: + +.. ipython:: + :verbatim: + + In [11]: import demo2 + b + + In [12]: import demo2 + +Running it: + +.. ipython:: + :verbatim: + + In [13]: %run demo2 + b + a + + +Scripts or modules? How to organize your code +--------------------------------------------- + +.. Note:: Rule of thumb + + * Sets of instructions that are called several times should be + written inside **functions** for better code reusability. + + * Functions (or other bits of code) that are called from several + scripts should be written inside a **module**, so that only the + module is imported in the different scripts (do not copy-and-paste + your functions in the different scripts!). + +How modules are found and imported +.................................. + + +When the ``import mymodule`` statement is executed, the module ``mymodule`` +is searched in a given list of directories. This list includes a list +of installation-dependent default path (e.g., ``/usr/lib64/python3.11``) as +well as the list of directories specified by the environment variable +``PYTHONPATH``. + +The list of directories searched by Python is given by the ``sys.path`` +variable + +.. ipython:: + + In [1]: import sys + + In [2]: sys.path + Out[2]: + ['/home/jarrod/.venv/lectures/bin', + '/usr/lib64/python311.zip', + '/usr/lib64/python3.11', + '/usr/lib64/python3.11/lib-dynload', + '', + '/home/jarrod/.venv/lectures/lib64/python3.11/site-packages', + '/home/jarrod/.venv/lectures/lib/python3.11/site-packages'] + +Modules must be located in the search path, therefore you can: + +* write your own modules within directories already defined in the + search path (e.g. ``$HOME/.venv/lectures/lib64/python3.11/site-packages``). + You may use symbolic links (on Linux) to keep the code somewhere else. + +* modify the environment variable ``PYTHONPATH`` to include the + directories containing the user-defined modules. + + .. tip:: + + On Linux/Unix, add the following line to a file read by the shell at + startup (e.g. /etc/profile, .profile) + + :: + + export PYTHONPATH=$PYTHONPATH:/home/emma/user_defined_modules + + On Windows, https://support.microsoft.com/kb/310519 explains how to + handle environment variables. + +* or modify the ``sys.path`` variable itself within a Python script. + + .. tip:: + + :: + + import sys + new_path = '/home/emma/user_defined_modules' + if new_path not in sys.path: + sys.path.append(new_path) + + This method is not very robust, however, because it makes the code + less portable (user-dependent path) and because you have to add the + directory to your sys.path each time you want to import from a module + in this directory. + +.. seealso:: + + See https://docs.python.org/3/tutorial/modules.html for more information + about modules. + +Packages +-------- + +A directory that contains many modules is called a *package*. A package +is a module with submodules (which can have submodules themselves, etc.). +A special file called ``__init__.py`` (which may be empty) tells Python +that the directory is a Python package, from which modules can be +imported. + +.. sourcecode:: bash + + $ ls + _build_utils/ fft/ _lib/ odr/ spatial/ + cluster/ fftpack/ linalg/ optimize/ special/ + conftest.py __init__.py linalg.pxd optimize.pxd special.pxd + constants/ integrate/ meson.build setup.py stats/ + datasets/ interpolate/ misc/ signal/ + _distributor_init.py io/ ndimage/ sparse/ + $ cd ndimage + $ ls + _filters.py __init__.py _measurements.py morphology.py src/ + filters.py _interpolation.py measurements.py _ni_docstrings.py tests/ + _fourier.py interpolation.py meson.build _ni_support.py utils/ + fourier.py LICENSE.txt _morphology.py setup.py + + +From Ipython: + +.. ipython:: + + In [1]: import scipy as sp + + In [2]: sp.__file__ + + In [3]: sp.version.version + + @verbatim + In [4]: sp.ndimage.morphology.binary_dilation? + Signature: + sp.ndimage.morphology.binary_dilation( + input, + structure=None, + iterations=1, + mask=None, + output=None, + border_value=0, + origin=0, + brute_force=False, + ) + Docstring: + Multidimensional binary dilation with the given structuring element. + ... + + +Good practices +-------------- + +* Use **meaningful** object **names** + +* **Indentation: no choice!** + + .. tip:: + + Indenting is compulsory in Python! Every command block following a + colon bears an additional indentation level with respect to the + previous line with a colon. One must therefore indent after + ``def f():`` or ``while:``. At the end of such logical blocks, one + decreases the indentation depth (and re-increases it if a new block + is entered, etc.) + + Strict respect of indentation is the price to pay for getting rid of + ``{`` or ``;`` characters that delineate logical blocks in other + languages. Improper indentation leads to errors such as + + .. code-block:: ipython + + ------------------------------------------------------------ + IndentationError: unexpected indent (test.py, line 2) + + All this indentation business can be a bit confusing in the + beginning. However, with the clear indentation, and in the absence of + extra characters, the resulting code is very nice to read compared to + other languages. + +* **Indentation depth**: Inside your text editor, you may choose to + indent with any positive number of spaces (1, 2, 3, 4, ...). However, + it is considered good practice to **indent with 4 spaces**. You may + configure your editor to map the ``Tab`` key to a 4-space + indentation. + +* **Style guidelines** + + **Long lines**: you should not write very long lines that span over more + than (e.g.) 80 characters. Long lines can be broken with the ``\`` + character :: + + >>> long_line = "Here is a very very long line \ + ... that we break in two parts." + + **Spaces** + + Write well-spaced code: put whitespaces after commas, around arithmetic + operators, etc.:: + + >>> a = 1 # yes + >>> a=1 # too cramped + + A certain number of rules + for writing "beautiful" code (and more importantly using the same + conventions as anybody else!) are given in the `Style Guide for Python + Code `_. + + +____ + + +.. topic:: **Quick read** + + If you want to do a first quick pass through the Scientific Python Lectures + to learn the ecosystem, you can directly skip to the next chapter: + :ref:`numpy`. + + The remainder of this chapter is not necessary to follow the rest of + the intro part. But be sure to come back and finish this chapter later. diff --git a/_sources/intro/language/standard_library.rst.txt b/_sources/intro/language/standard_library.rst.txt new file mode 100644 index 000000000..12d5d4f97 --- /dev/null +++ b/_sources/intro/language/standard_library.rst.txt @@ -0,0 +1,276 @@ +Standard Library +================ + +.. note:: Reference document for this section: + + * The Python Standard Library documentation: + https://docs.python.org/3/library/index.html + + * Python Essential Reference, David Beazley, Addison-Wesley Professional + +``os`` module: operating system functionality +----------------------------------------------- + +*"A portable way of using operating system dependent functionality."* + +Directory and file manipulation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Current directory: + +.. ipython:: + + In [1]: import os + + In [2]: os.getcwd() + Out[2]: '/home/jarrod/src/scientific-python-lectures/intro' + +List a directory: + +.. ipython:: + + In [3]: os.listdir(os.curdir) + Out[3]: ['intro.rst', 'scipy', 'language', 'matplotlib', 'index.rst', 'numpy', 'help'] + +Make a directory: + +.. ipython:: + + In [4]: os.mkdir('junkdir') + + In [5]: 'junkdir' in os.listdir(os.curdir) + Out[5]: True + +Rename the directory: + +.. ipython:: + + In [6]: os.rename('junkdir', 'foodir') + + In [7]: 'junkdir' in os.listdir(os.curdir) + Out[7]: False + + In [8]: 'foodir' in os.listdir(os.curdir) + Out[8]: True + + In [9]: os.rmdir('foodir') + + In [10]: 'foodir' in os.listdir(os.curdir) + Out[10]: False + +Delete a file: + +.. ipython:: + + In [11]: fp = open('junk.txt', 'w') + + In [12]: fp.close() + + In [13]: 'junk.txt' in os.listdir(os.curdir) + Out[13]: True + + In [14]: os.remove('junk.txt') + + In [15]: 'junk.txt' in os.listdir(os.curdir) + Out[15]: False + +``os.path``: path manipulations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``os.path`` provides common operations on pathnames. + +.. ipython:: + + In [16]: fp = open('junk.txt', 'w') + + In [17]: fp.close() + + In [18]: a = os.path.abspath('junk.txt') + + In [19]: a + Out[19]: '/home/jarrod/src/scientific-python-lectures/intro/junk.txt' + + In [20]: os.path.split(a) + Out[20]: ('/home/jarrod/src/scientific-python-lectures/intro', 'junk.txt') + + In [21]: os.path.dirname(a) + Out[21]: '/home/jarrod/src/scientific-python-lectures/intro' + + In [22]: os.path.basename(a) + Out[22]: 'junk.txt' + + In [23]: os.path.splitext(os.path.basename(a)) + Out[23]: ('junk', '.txt') + + In [24]: os.path.exists('junk.txt') + Out[24]: True + + In [25]: os.path.isfile('junk.txt') + Out[25]: True + + In [26]: os.path.isdir('junk.txt') + Out[26]: False + + In [27]: os.path.expanduser('~/local') + Out[27]: '/home/jarrod/local' + + In [28]: os.path.join(os.path.expanduser('~'), 'local', 'bin') + Out[28]: '/home/jarrod/local/bin' + +Running an external command +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. ipython:: + + In [29]: os.system('ls') + help index.rst intro.rst junk.txt language matplotlib numpy scipy + Out[29]: 0 + +.. note:: Alternative to ``os.system`` + + A noteworthy alternative to ``os.system`` is the `sh module + `_. Which provides much more convenient ways to + obtain the output, error stream and exit code of the external command. + + .. ipython:: + :verbatim: + + In [30]: import sh + In [31]: com = sh.ls() + + In [32]: print(com) + basic_types.rst exceptions.rst oop.rst standard_library.rst + control_flow.rst first_steps.rst python_language.rst + demo2.py functions.rst python-logo.png + demo.py io.rst reusing_code.rst + + In [33]: type(com) + Out[33]: str + +Walking a directory +~~~~~~~~~~~~~~~~~~~~ + +``os.path.walk`` generates a list of filenames in a directory tree. + +.. ipython:: + + In [10]: for dirpath, dirnames, filenames in os.walk(os.curdir): + ....: for fp in filenames: + ....: print(os.path.abspath(fp)) + ....: + ....: + /home/jarrod/src/scientific-python-lectures/intro/language/basic_types.rst + /home/jarrod/src/scientific-python-lectures/intro/language/control_flow.rst + /home/jarrod/src/scientific-python-lectures/intro/language/python_language.rst + /home/jarrod/src/scientific-python-lectures/intro/language/reusing_code.rst + /home/jarrod/src/scientific-python-lectures/intro/language/standard_library.rst + ... + +Environment variables: +~~~~~~~~~~~~~~~~~~~~~~ + +.. ipython:: + :verbatim: + + In [32]: os.environ.keys() + Out[32]: KeysView(environ({'SHELL': '/bin/bash', 'COLORTERM': 'truecolor', ...})) + + + In [34]: os.environ['SHELL'] + Out[34]: '/bin/bash' + + +``shutil``: high-level file operations +--------------------------------------- + +The ``shutil`` provides useful file operations: + + * ``shutil.rmtree``: Recursively delete a directory tree. + * ``shutil.move``: Recursively move a file or directory to another location. + * ``shutil.copy``: Copy files or directories. + +``glob``: Pattern matching on files +------------------------------------- + +The ``glob`` module provides convenient file pattern matching. + +Find all files ending in ``.txt``: + +.. ipython:: + + In [36]: import glob + + In [37]: glob.glob('*.txt') + Out[37]: ['junk.txt'] + +``sys`` module: system-specific information +-------------------------------------------- + +System-specific information related to the Python interpreter. + +* Which version of python are you running and where is it installed: + +.. ipython:: + + + In [39]: import sys + + In [40]: sys.platform + Out[40]: 'linux' + + In [41]: sys.version + Out[41]: '3.11.8 (main, Feb 28 2024, 00:00:00) [GCC 13.2.1 20231011 (Red Hat 13.2.1-4)]' + + In [42]: sys.prefix + Out[42]: '/home/jarrod/.venv/nx' + +* List of command line arguments passed to a Python script: + +.. ipython:: + + In [43]: sys.argv + Out[43]: ['/home/jarrod/.venv/nx/bin/ipython'] + +``sys.path`` is a list of strings that specifies the search path for +modules. Initialized from PYTHONPATH: + +.. ipython:: + + In [44]: sys.path + Out[44]: + ['/home/jarrod/.venv/nx/bin', + '/usr/lib64/python311.zip', + '/usr/lib64/python3.11', + '/usr/lib64/python3.11/lib-dynload', + '', + '/home/jarrod/.venv/nx/lib64/python3.11/site-packages', + '/home/jarrod/.venv/nx/lib/python3.11/site-packages'] + +``pickle``: easy persistence +------------------------------- + +Useful to store arbitrary objects to a file. Not safe or fast! + +.. ipython:: + + In [45]: import pickle + + In [46]: l = [1, None, 'Stan'] + + In [3]: with open('test.pkl', 'wb') as file: + ...: pickle.dump(l, file) + ...: + + In [4]: with open('test.pkl', 'rb') as file: + ...: out = pickle.load(file) + ...: + + In [49]: out + Out[49]: [1, None, 'Stan'] + + +.. topic:: Exercise + + Write a program to search your ``PYTHONPATH`` for the module ``site.py``. + +:ref:`path_site` diff --git a/_sources/intro/matplotlib/auto_examples/exercises/index.rst.txt b/_sources/intro/matplotlib/auto_examples/exercises/index.rst.txt new file mode 100644 index 000000000..099c4d38a --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/exercises/index.rst.txt @@ -0,0 +1,208 @@ + + +.. _sphx_glr_intro_matplotlib_auto_examples_exercises: + + + +Code for the chapter's exercises +-------------------------------- + + + +.. raw:: html + +
+ +.. thumbnail-parent-div-open + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/exercises/images/thumb/sphx_glr_plot_exercise_1_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_1.py` + +.. raw:: html + +
Exercise 1
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/exercises/images/thumb/sphx_glr_plot_exercise_4_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_4.py` + +.. raw:: html + +
Exercise 4
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/exercises/images/thumb/sphx_glr_plot_exercise_3_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_3.py` + +.. raw:: html + +
Exercise 3
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/exercises/images/thumb/sphx_glr_plot_exercise_5_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_5.py` + +.. raw:: html + +
Exercise 5
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/exercises/images/thumb/sphx_glr_plot_exercise_6_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_6.py` + +.. raw:: html + +
Exercise 6
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/exercises/images/thumb/sphx_glr_plot_exercise_2_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_2.py` + +.. raw:: html + +
Exercise 2
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/exercises/images/thumb/sphx_glr_plot_exercise_7_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_7.py` + +.. raw:: html + +
Exercise 7
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/exercises/images/thumb/sphx_glr_plot_exercise_8_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_8.py` + +.. raw:: html + +
Exercise 8
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/exercises/images/thumb/sphx_glr_plot_exercise_9_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_9.py` + +.. raw:: html + +
Exercise 9
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/exercises/images/thumb/sphx_glr_plot_exercise_10_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_10.py` + +.. raw:: html + +
Exercise
+
+ + +.. thumbnail-parent-div-close + +.. raw:: html + +
+ + +.. toctree:: + :hidden: + + /intro/matplotlib/auto_examples/exercises/plot_exercise_1 + /intro/matplotlib/auto_examples/exercises/plot_exercise_4 + /intro/matplotlib/auto_examples/exercises/plot_exercise_3 + /intro/matplotlib/auto_examples/exercises/plot_exercise_5 + /intro/matplotlib/auto_examples/exercises/plot_exercise_6 + /intro/matplotlib/auto_examples/exercises/plot_exercise_2 + /intro/matplotlib/auto_examples/exercises/plot_exercise_7 + /intro/matplotlib/auto_examples/exercises/plot_exercise_8 + /intro/matplotlib/auto_examples/exercises/plot_exercise_9 + /intro/matplotlib/auto_examples/exercises/plot_exercise_10 + diff --git a/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_1.rst.txt b/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_1.rst.txt new file mode 100644 index 000000000..96bf4b06b --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_1.rst.txt @@ -0,0 +1,82 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/exercises/plot_exercise_1.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_1.py: + + +Exercise 1 +=========== + +Solution of the exercise 1 with matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-18 + + + +.. image-sg:: /intro/matplotlib/auto_examples/exercises/images/sphx_glr_plot_exercise_1_001.png + :alt: plot exercise 1 + :srcset: /intro/matplotlib/auto_examples/exercises/images/sphx_glr_plot_exercise_1_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + n = 256 + X = np.linspace(-np.pi, np.pi, 256) + C, S = np.cos(X), np.sin(X) + plt.plot(X, C) + plt.plot(X, S) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.059 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_exercises_plot_exercise_1.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_exercise_1.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_exercise_1.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_exercise_1.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_10.rst.txt b/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_10.rst.txt new file mode 100644 index 000000000..4d10d29f4 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_10.rst.txt @@ -0,0 +1,151 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/exercises/plot_exercise_10.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_10.py: + + +Exercise +========= + +Exercises with matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-87 + + + +.. image-sg:: /intro/matplotlib/auto_examples/exercises/images/sphx_glr_plot_exercise_10_001.png + :alt: plot exercise 10 + :srcset: /intro/matplotlib/auto_examples/exercises/images/sphx_glr_plot_exercise_10_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + plt.figure(figsize=(8, 5), dpi=80) + plt.subplot(111) + + X = np.linspace(-np.pi, np.pi, 256) + C, S = np.cos(X), np.sin(X) + + plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine") + plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine") + + ax = plt.gca() + ax.spines["right"].set_color("none") + ax.spines["top"].set_color("none") + ax.xaxis.set_ticks_position("bottom") + ax.spines["bottom"].set_position(("data", 0)) + ax.yaxis.set_ticks_position("left") + ax.spines["left"].set_position(("data", 0)) + + plt.xlim(X.min() * 1.1, X.max() * 1.1) + plt.xticks( + [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], + [r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"], + ) + + plt.ylim(C.min() * 1.1, C.max() * 1.1) + plt.yticks([-1, 1], [r"$-1$", r"$+1$"]) + + plt.legend(loc="upper left") + + t = 2 * np.pi / 3 + plt.plot([t, t], [0, np.cos(t)], color="blue", linewidth=1.5, linestyle="--") + plt.scatter( + [ + t, + ], + [ + np.cos(t), + ], + 50, + color="blue", + ) + plt.annotate( + r"$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$", + xy=(t, np.sin(t)), + xycoords="data", + xytext=(10, 30), + textcoords="offset points", + fontsize=16, + arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=.2"}, + ) + + plt.plot([t, t], [0, np.sin(t)], color="red", linewidth=1.5, linestyle="--") + plt.scatter( + [ + t, + ], + [ + np.sin(t), + ], + 50, + color="red", + ) + plt.annotate( + r"$cos(\frac{2\pi}{3})=-\frac{1}{2}$", + xy=(t, np.cos(t)), + xycoords="data", + xytext=(-90, -50), + textcoords="offset points", + fontsize=16, + arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=.2"}, + ) + + for label in ax.get_xticklabels() + ax.get_yticklabels(): + label.set_fontsize(16) + label.set_bbox({"facecolor": "white", "edgecolor": "None", "alpha": 0.65}) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.102 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_exercises_plot_exercise_10.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_exercise_10.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_exercise_10.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_exercise_10.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_2.rst.txt b/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_2.rst.txt new file mode 100644 index 000000000..6b024a3f3 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_2.rst.txt @@ -0,0 +1,104 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/exercises/plot_exercise_2.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_2.py: + + +Exercise 2 +=========== + +Exercise 2 with matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-40 + + + +.. image-sg:: /intro/matplotlib/auto_examples/exercises/images/sphx_glr_plot_exercise_2_001.png + :alt: plot exercise 2 + :srcset: /intro/matplotlib/auto_examples/exercises/images/sphx_glr_plot_exercise_2_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + # Create a new figure of size 8x6 points, using 100 dots per inch + plt.figure(figsize=(8, 6), dpi=80) + + # Create a new subplot from a grid of 1x1 + plt.subplot(111) + + X = np.linspace(-np.pi, np.pi, 256) + C, S = np.cos(X), np.sin(X) + + # Plot cosine using blue color with a continuous line of width 1 (pixels) + plt.plot(X, C, color="blue", linewidth=1.0, linestyle="-") + + # Plot sine using green color with a continuous line of width 1 (pixels) + plt.plot(X, S, color="green", linewidth=1.0, linestyle="-") + + # Set x limits + plt.xlim(-4.0, 4.0) + + # Set x ticks + plt.xticks(np.linspace(-4, 4, 9)) + + # Set y limits + plt.ylim(-1.0, 1.0) + + # Set y ticks + plt.yticks(np.linspace(-1, 1, 5)) + + # Show result on screen + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.051 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_exercises_plot_exercise_2.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_exercise_2.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_exercise_2.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_exercise_2.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_3.rst.txt b/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_3.rst.txt new file mode 100644 index 000000000..1970a163b --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_3.rst.txt @@ -0,0 +1,91 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/exercises/plot_exercise_3.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_3.py: + + +Exercise 3 +========== + +Exercise 3 with matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-27 + + + +.. image-sg:: /intro/matplotlib/auto_examples/exercises/images/sphx_glr_plot_exercise_3_001.png + :alt: plot exercise 3 + :srcset: /intro/matplotlib/auto_examples/exercises/images/sphx_glr_plot_exercise_3_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + plt.figure(figsize=(8, 5), dpi=80) + plt.subplot(111) + + X = np.linspace(-np.pi, np.pi, 256) + C, S = np.cos(X), np.sin(X) + + plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") + plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") + + plt.xlim(-4.0, 4.0) + plt.xticks(np.linspace(-4, 4, 9)) + + plt.ylim(-1.0, 1.0) + plt.yticks(np.linspace(-1, 1, 5)) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.048 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_exercises_plot_exercise_3.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_exercise_3.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_exercise_3.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_exercise_3.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_4.rst.txt b/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_4.rst.txt new file mode 100644 index 000000000..068622d66 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_4.rst.txt @@ -0,0 +1,89 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/exercises/plot_exercise_4.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_4.py: + + +Exercise 4 +=========== + +Exercise 4 with matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-25 + + + +.. image-sg:: /intro/matplotlib/auto_examples/exercises/images/sphx_glr_plot_exercise_4_001.png + :alt: plot exercise 4 + :srcset: /intro/matplotlib/auto_examples/exercises/images/sphx_glr_plot_exercise_4_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + plt.figure(figsize=(8, 5), dpi=80) + plt.subplot(111) + + X = np.linspace(-np.pi, np.pi, 256) + S = np.sin(X) + C = np.cos(X) + + plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") + plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") + + plt.xlim(X.min() * 1.1, X.max() * 1.1) + plt.ylim(C.min() * 1.1, C.max() * 1.1) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.056 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_exercises_plot_exercise_4.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_exercise_4.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_exercise_4.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_exercise_4.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_5.rst.txt b/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_5.rst.txt new file mode 100644 index 000000000..c65764b33 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_5.rst.txt @@ -0,0 +1,92 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/exercises/plot_exercise_5.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_5.py: + + +Exercise 5 +=========== + +Exercise 5 with matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-28 + + + +.. image-sg:: /intro/matplotlib/auto_examples/exercises/images/sphx_glr_plot_exercise_5_001.png + :alt: plot exercise 5 + :srcset: /intro/matplotlib/auto_examples/exercises/images/sphx_glr_plot_exercise_5_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + plt.figure(figsize=(8, 5), dpi=80) + plt.subplot(111) + + X = np.linspace(-np.pi, np.pi, 256) + S = np.sin(X) + C = np.cos(X) + + plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") + plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") + + plt.xlim(X.min() * 1.1, X.max() * 1.1) + plt.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi]) + + plt.ylim(C.min() * 1.1, C.max() * 1.1) + plt.yticks([-1, 0, +1]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.039 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_exercises_plot_exercise_5.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_exercise_5.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_exercise_5.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_exercise_5.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_6.rst.txt b/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_6.rst.txt new file mode 100644 index 000000000..8c7682096 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_6.rst.txt @@ -0,0 +1,95 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/exercises/plot_exercise_6.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_6.py: + + +Exercise 6 +=========== + +Exercise 6 with matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-31 + + + +.. image-sg:: /intro/matplotlib/auto_examples/exercises/images/sphx_glr_plot_exercise_6_001.png + :alt: plot exercise 6 + :srcset: /intro/matplotlib/auto_examples/exercises/images/sphx_glr_plot_exercise_6_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + plt.figure(figsize=(8, 5), dpi=80) + plt.subplot(111) + + X = np.linspace(-np.pi, np.pi, 256) + C = np.cos(X) + S = np.sin(X) + + plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") + plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") + + plt.xlim(X.min() * 1.1, X.max() * 1.1) + plt.xticks( + [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], + [r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"], + ) + + plt.ylim(C.min() * 1.1, C.max() * 1.1) + plt.yticks([-1, 0, +1], [r"$-1$", r"$0$", r"$+1$"]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.049 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_exercises_plot_exercise_6.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_exercise_6.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_exercise_6.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_exercise_6.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_7.rst.txt b/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_7.rst.txt new file mode 100644 index 000000000..32db49887 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_7.rst.txt @@ -0,0 +1,103 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/exercises/plot_exercise_7.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_7.py: + + +Exercise 7 +=========== + +Exercise 7 with matplotlib + +.. GENERATED FROM PYTHON SOURCE LINES 7-39 + + + +.. image-sg:: /intro/matplotlib/auto_examples/exercises/images/sphx_glr_plot_exercise_7_001.png + :alt: plot exercise 7 + :srcset: /intro/matplotlib/auto_examples/exercises/images/sphx_glr_plot_exercise_7_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + plt.figure(figsize=(8, 5), dpi=80) + plt.subplot(111) + + X = np.linspace(-np.pi, np.pi, 256, endpoint=True) + C = np.cos(X) + S = np.sin(X) + + plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") + plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") + + ax = plt.gca() + ax.spines["right"].set_color("none") + ax.spines["top"].set_color("none") + ax.xaxis.set_ticks_position("bottom") + ax.spines["bottom"].set_position(("data", 0)) + ax.yaxis.set_ticks_position("left") + ax.spines["left"].set_position(("data", 0)) + + plt.xlim(X.min() * 1.1, X.max() * 1.1) + plt.xticks( + [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], + [r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"], + ) + + plt.ylim(C.min() * 1.1, C.max() * 1.1) + plt.yticks([-1, 0, +1], [r"$-1$", r"$0$", r"$+1$"]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.055 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_exercises_plot_exercise_7.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_exercise_7.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_exercise_7.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_exercise_7.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_8.rst.txt b/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_8.rst.txt new file mode 100644 index 000000000..4e1887e54 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_8.rst.txt @@ -0,0 +1,105 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/exercises/plot_exercise_8.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_8.py: + + +Exercise 8 +========== + +Exercise 8 with matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-41 + + + +.. image-sg:: /intro/matplotlib/auto_examples/exercises/images/sphx_glr_plot_exercise_8_001.png + :alt: plot exercise 8 + :srcset: /intro/matplotlib/auto_examples/exercises/images/sphx_glr_plot_exercise_8_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + plt.figure(figsize=(8, 5), dpi=80) + plt.subplot(111) + + X = np.linspace(-np.pi, np.pi, 256, endpoint=True) + C = np.cos(X) + S = np.sin(X) + + plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine") + plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine") + + ax = plt.gca() + ax.spines["right"].set_color("none") + ax.spines["top"].set_color("none") + ax.xaxis.set_ticks_position("bottom") + ax.spines["bottom"].set_position(("data", 0)) + ax.yaxis.set_ticks_position("left") + ax.spines["left"].set_position(("data", 0)) + + plt.xlim(X.min() * 1.1, X.max() * 1.1) + plt.xticks( + [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], + [r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"], + ) + + plt.ylim(C.min() * 1.1, C.max() * 1.1) + plt.yticks([-1, +1], [r"$-1$", r"$+1$"]) + + plt.legend(loc="upper left") + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.061 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_exercises_plot_exercise_8.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_exercise_8.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_exercise_8.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_exercise_8.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_9.rst.txt b/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_9.rst.txt new file mode 100644 index 000000000..6debfd9a3 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/exercises/plot_exercise_9.rst.txt @@ -0,0 +1,148 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/exercises/plot_exercise_9.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_9.py: + + +Exercise 9 +========== + +Exercise 9 with matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-84 + + + +.. image-sg:: /intro/matplotlib/auto_examples/exercises/images/sphx_glr_plot_exercise_9_001.png + :alt: plot exercise 9 + :srcset: /intro/matplotlib/auto_examples/exercises/images/sphx_glr_plot_exercise_9_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + plt.figure(figsize=(8, 5), dpi=80) + plt.subplot(111) + + X = np.linspace(-np.pi, np.pi, 256, endpoint=True) + C = np.cos(X) + S = np.sin(X) + + plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine") + plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine") + + ax = plt.gca() + ax.spines["right"].set_color("none") + ax.spines["top"].set_color("none") + ax.xaxis.set_ticks_position("bottom") + ax.spines["bottom"].set_position(("data", 0)) + ax.yaxis.set_ticks_position("left") + ax.spines["left"].set_position(("data", 0)) + + plt.xlim(X.min() * 1.1, X.max() * 1.1) + plt.xticks( + [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], + [r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"], + ) + + plt.ylim(C.min() * 1.1, C.max() * 1.1) + plt.yticks([-1, +1], [r"$-1$", r"$+1$"]) + + t = 2 * np.pi / 3 + plt.plot([t, t], [0, np.cos(t)], color="blue", linewidth=1.5, linestyle="--") + plt.scatter( + [ + t, + ], + [ + np.cos(t), + ], + 50, + color="blue", + ) + plt.annotate( + r"$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$", + xy=(t, np.sin(t)), + xycoords="data", + xytext=(+10, +30), + textcoords="offset points", + fontsize=16, + arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=.2"}, + ) + + plt.plot([t, t], [0, np.sin(t)], color="red", linewidth=1.5, linestyle="--") + plt.scatter( + [ + t, + ], + [ + np.sin(t), + ], + 50, + color="red", + ) + plt.annotate( + r"$cos(\frac{2\pi}{3})=-\frac{1}{2}$", + xy=(t, np.cos(t)), + xycoords="data", + xytext=(-90, -50), + textcoords="offset points", + fontsize=16, + arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=.2"}, + ) + + plt.legend(loc="upper left") + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.104 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_exercises_plot_exercise_9.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_exercise_9.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_exercise_9.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_exercise_9.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/exercises/sg_execution_times.rst.txt b/_sources/intro/matplotlib/auto_examples/exercises/sg_execution_times.rst.txt new file mode 100644 index 000000000..8ab42b51c --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/exercises/sg_execution_times.rst.txt @@ -0,0 +1,64 @@ + +:orphan: + +.. _sphx_glr_intro_matplotlib_auto_examples_exercises_sg_execution_times: + + +Computation times +================= +**00:00.624** total execution time for 10 files **from intro/matplotlib/auto_examples/exercises**: + +.. container:: + + .. raw:: html + + + + + + + + .. list-table:: + :header-rows: 1 + :class: table table-striped sg-datatable + + * - Example + - Time + - Mem (MB) + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_9.py` (``plot_exercise_9.py``) + - 00:00.104 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_10.py` (``plot_exercise_10.py``) + - 00:00.102 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_8.py` (``plot_exercise_8.py``) + - 00:00.061 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_1.py` (``plot_exercise_1.py``) + - 00:00.059 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_4.py` (``plot_exercise_4.py``) + - 00:00.056 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_7.py` (``plot_exercise_7.py``) + - 00:00.055 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_2.py` (``plot_exercise_2.py``) + - 00:00.051 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_6.py` (``plot_exercise_6.py``) + - 00:00.049 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_3.py` (``plot_exercise_3.py``) + - 00:00.048 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_5.py` (``plot_exercise_5.py``) + - 00:00.039 + - 0.0 diff --git a/_sources/intro/matplotlib/auto_examples/index.rst.txt b/_sources/intro/matplotlib/auto_examples/index.rst.txt new file mode 100644 index 000000000..6e5ef7343 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/index.rst.txt @@ -0,0 +1,1191 @@ +:orphan: + + + +Code samples for Matplotlib +---------------------------- + +The examples here are only examples relevant to the points raised in this +chapter. The matplotlib documentation comes with a much more exhaustive +`gallery `__. + + + +.. raw:: html + +
+ +.. thumbnail-parent-div-open + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_pie_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_pie.py` + +.. raw:: html + +
Pie chart
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_good_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_good.py` + +.. raw:: html + +
A simple, good-looking plot
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_scatter_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_scatter.py` + +.. raw:: html + +
Plotting a scatter of points
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_multiplot_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_multiplot.py` + +.. raw:: html + +
Subplots
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_subplot-horizontal_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_subplot-horizontal.py` + +.. raw:: html + +
Horizontal arrangement of subplots
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_bad_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_bad.py` + +.. raw:: html + +
A simple plotting example
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_subplot-vertical_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_subplot-vertical.py` + +.. raw:: html + +
Subplot plot arrangement vertical
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_axes_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_axes.py` + +.. raw:: html + +
Simple axes example
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_plot3d_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_plot3d.py` + +.. raw:: html + +
3D plotting
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_imshow_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_imshow.py` + +.. raw:: html + +
Imshow elaborate
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_quiver_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_quiver.py` + +.. raw:: html + +
Plotting a vector field: quiver
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_contour_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_contour.py` + +.. raw:: html + +
Displaying the contours of a function
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_ugly_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_ugly.py` + +.. raw:: html + +
A example of plotting not quite right
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_plot_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_plot.py` + +.. raw:: html + +
Plot and filled plots
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_polar_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_polar.py` + +.. raw:: html + +
Plotting in polar coordinates
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_subplot-grid_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_subplot-grid.py` + +.. raw:: html + +
Subplot grid
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_bar_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_bar.py` + +.. raw:: html + +
Bar plots
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_axes-2_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_axes-2.py` + +.. raw:: html + +
Axes
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_grid_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_grid.py` + +.. raw:: html + +
Grid
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_plot3d-2_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_plot3d-2.py` + +.. raw:: html + +
3D plotting
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_gridspec_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_gridspec.py` + +.. raw:: html + +
GridSpec
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/images/thumb/sphx_glr_plot_text_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_text.py` + +.. raw:: html + +
Demo text printing
+
+ + +.. thumbnail-parent-div-close + +.. raw:: html + +
+ + +.. toctree:: + :hidden: + + /intro/matplotlib/auto_examples/plot_pie + /intro/matplotlib/auto_examples/plot_good + /intro/matplotlib/auto_examples/plot_scatter + /intro/matplotlib/auto_examples/plot_multiplot + /intro/matplotlib/auto_examples/plot_subplot-horizontal + /intro/matplotlib/auto_examples/plot_bad + /intro/matplotlib/auto_examples/plot_subplot-vertical + /intro/matplotlib/auto_examples/plot_axes + /intro/matplotlib/auto_examples/plot_plot3d + /intro/matplotlib/auto_examples/plot_imshow + /intro/matplotlib/auto_examples/plot_quiver + /intro/matplotlib/auto_examples/plot_contour + /intro/matplotlib/auto_examples/plot_ugly + /intro/matplotlib/auto_examples/plot_plot + /intro/matplotlib/auto_examples/plot_polar + /intro/matplotlib/auto_examples/plot_subplot-grid + /intro/matplotlib/auto_examples/plot_bar + /intro/matplotlib/auto_examples/plot_axes-2 + /intro/matplotlib/auto_examples/plot_grid + /intro/matplotlib/auto_examples/plot_plot3d-2 + /intro/matplotlib/auto_examples/plot_gridspec + /intro/matplotlib/auto_examples/plot_text + + + +Code for the chapter's exercises +-------------------------------- + + + +.. raw:: html + +
+ +.. thumbnail-parent-div-open + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/exercises/images/thumb/sphx_glr_plot_exercise_1_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_1.py` + +.. raw:: html + +
Exercise 1
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/exercises/images/thumb/sphx_glr_plot_exercise_4_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_4.py` + +.. raw:: html + +
Exercise 4
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/exercises/images/thumb/sphx_glr_plot_exercise_3_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_3.py` + +.. raw:: html + +
Exercise 3
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/exercises/images/thumb/sphx_glr_plot_exercise_5_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_5.py` + +.. raw:: html + +
Exercise 5
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/exercises/images/thumb/sphx_glr_plot_exercise_6_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_6.py` + +.. raw:: html + +
Exercise 6
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/exercises/images/thumb/sphx_glr_plot_exercise_2_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_2.py` + +.. raw:: html + +
Exercise 2
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/exercises/images/thumb/sphx_glr_plot_exercise_7_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_7.py` + +.. raw:: html + +
Exercise 7
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/exercises/images/thumb/sphx_glr_plot_exercise_8_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_8.py` + +.. raw:: html + +
Exercise 8
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/exercises/images/thumb/sphx_glr_plot_exercise_9_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_9.py` + +.. raw:: html + +
Exercise 9
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/exercises/images/thumb/sphx_glr_plot_exercise_10_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_10.py` + +.. raw:: html + +
Exercise
+
+ + +.. thumbnail-parent-div-close + +.. raw:: html + +
+ + + +Example demoing choices for an option +-------------------------------------- + + + +.. raw:: html + +
+ +.. thumbnail-parent-div-open + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_color_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_color.py` + +.. raw:: html + +
The colors matplotlib line plots
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_linewidth_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_linewidth.py` + +.. raw:: html + +
Linewidth
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_alpha_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_alpha.py` + +.. raw:: html + +
Alpha: transparency
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_aliased_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_aliased.py` + +.. raw:: html + +
Aliased versus anti-aliased
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_antialiased_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_antialiased.py` + +.. raw:: html + +
Aliased versus anti-aliased
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_ms_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_ms.py` + +.. raw:: html + +
Marker size
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_mew_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_mew.py` + +.. raw:: html + +
Marker edge width
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_colormaps_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_colormaps.py` + +.. raw:: html + +
Colormaps
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_solid_joinstyle_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_solid_joinstyle.py` + +.. raw:: html + +
Solid joint style
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_solid_capstyle_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_solid_capstyle.py` + +.. raw:: html + +
Solid cap style
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_mec_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_mec.py` + +.. raw:: html + +
Marker edge color
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_mfc_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_mfc.py` + +.. raw:: html + +
Marker face color
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_dash_capstyle_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_dash_capstyle.py` + +.. raw:: html + +
Dash capstyle
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_dash_joinstyle_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_dash_joinstyle.py` + +.. raw:: html + +
Dash join style
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_markers_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_markers.py` + +.. raw:: html + +
Markers
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_linestyles_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_linestyles.py` + +.. raw:: html + +
Linestyles
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_ticks_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_ticks.py` + +.. raw:: html + +
Locators for tick on axis
+
+ + +.. thumbnail-parent-div-close + +.. raw:: html + +
+ + +Code generating the summary figures with a title +------------------------------------------------- + + + +.. raw:: html + +
+ +.. thumbnail-parent-div-open + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_plot3d_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_plot3d_ext.py` + +.. raw:: html + +
3D plotting vignette
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_polar_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_polar_ext.py` + +.. raw:: html + +
Plotting in polar, decorated
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_plot_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_plot_ext.py` + +.. raw:: html + +
Plot example vignette
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_multiplot_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_multiplot_ext.py` + +.. raw:: html + +
Multiple plots vignette
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_boxplot_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_boxplot_ext.py` + +.. raw:: html + +
Boxplot with matplotlib
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_scatter_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_scatter_ext.py` + +.. raw:: html + +
Plot scatter decorated
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_pie_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_pie_ext.py` + +.. raw:: html + +
Pie chart vignette
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_imshow_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_imshow_ext.py` + +.. raw:: html + +
Imshow demo
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_bar_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_bar_ext.py` + +.. raw:: html + +
Bar plot advanced
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_quiver_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_quiver_ext.py` + +.. raw:: html + +
Plotting quiver decorated
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_contour_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_contour_ext.py` + +.. raw:: html + +
Display the contours of a function
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_grid_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_grid_ext.py` + +.. raw:: html + +
Grid elaborate
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_text_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_text_ext.py` + +.. raw:: html + +
Text printing decorated
+
+ + +.. thumbnail-parent-div-close + +.. raw:: html + +
+ + +.. toctree:: + :hidden: + :includehidden: + + + /intro/matplotlib/auto_examples/exercises/index.rst + /intro/matplotlib/auto_examples/options/index.rst + /intro/matplotlib/auto_examples/pretty_plots/index.rst + + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-gallery + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download all examples in Python source code: auto_examples_python.zip ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download all examples in Jupyter notebooks: auto_examples_jupyter.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/options/index.rst.txt b/_sources/intro/matplotlib/auto_examples/options/index.rst.txt new file mode 100644 index 000000000..ff6a1741d --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/options/index.rst.txt @@ -0,0 +1,334 @@ + + +.. _sphx_glr_intro_matplotlib_auto_examples_options: + + + +Example demoing choices for an option +-------------------------------------- + + + +.. raw:: html + +
+ +.. thumbnail-parent-div-open + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_color_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_color.py` + +.. raw:: html + +
The colors matplotlib line plots
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_linewidth_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_linewidth.py` + +.. raw:: html + +
Linewidth
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_alpha_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_alpha.py` + +.. raw:: html + +
Alpha: transparency
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_aliased_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_aliased.py` + +.. raw:: html + +
Aliased versus anti-aliased
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_antialiased_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_antialiased.py` + +.. raw:: html + +
Aliased versus anti-aliased
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_ms_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_ms.py` + +.. raw:: html + +
Marker size
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_mew_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_mew.py` + +.. raw:: html + +
Marker edge width
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_colormaps_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_colormaps.py` + +.. raw:: html + +
Colormaps
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_solid_joinstyle_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_solid_joinstyle.py` + +.. raw:: html + +
Solid joint style
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_solid_capstyle_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_solid_capstyle.py` + +.. raw:: html + +
Solid cap style
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_mec_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_mec.py` + +.. raw:: html + +
Marker edge color
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_mfc_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_mfc.py` + +.. raw:: html + +
Marker face color
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_dash_capstyle_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_dash_capstyle.py` + +.. raw:: html + +
Dash capstyle
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_dash_joinstyle_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_dash_joinstyle.py` + +.. raw:: html + +
Dash join style
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_markers_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_markers.py` + +.. raw:: html + +
Markers
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_linestyles_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_linestyles.py` + +.. raw:: html + +
Linestyles
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/options/images/thumb/sphx_glr_plot_ticks_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_ticks.py` + +.. raw:: html + +
Locators for tick on axis
+
+ + +.. thumbnail-parent-div-close + +.. raw:: html + +
+ + +.. toctree:: + :hidden: + + /intro/matplotlib/auto_examples/options/plot_color + /intro/matplotlib/auto_examples/options/plot_linewidth + /intro/matplotlib/auto_examples/options/plot_alpha + /intro/matplotlib/auto_examples/options/plot_aliased + /intro/matplotlib/auto_examples/options/plot_antialiased + /intro/matplotlib/auto_examples/options/plot_ms + /intro/matplotlib/auto_examples/options/plot_mew + /intro/matplotlib/auto_examples/options/plot_colormaps + /intro/matplotlib/auto_examples/options/plot_solid_joinstyle + /intro/matplotlib/auto_examples/options/plot_solid_capstyle + /intro/matplotlib/auto_examples/options/plot_mec + /intro/matplotlib/auto_examples/options/plot_mfc + /intro/matplotlib/auto_examples/options/plot_dash_capstyle + /intro/matplotlib/auto_examples/options/plot_dash_joinstyle + /intro/matplotlib/auto_examples/options/plot_markers + /intro/matplotlib/auto_examples/options/plot_linestyles + /intro/matplotlib/auto_examples/options/plot_ticks + diff --git a/_sources/intro/matplotlib/auto_examples/options/plot_aliased.rst.txt b/_sources/intro/matplotlib/auto_examples/options/plot_aliased.rst.txt new file mode 100644 index 000000000..3f4d20982 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/options/plot_aliased.rst.txt @@ -0,0 +1,91 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/options/plot_aliased.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_options_plot_aliased.py: + + +Aliased versus anti-aliased +============================= + +This example demonstrates aliased versus anti-aliased text. + +.. GENERATED FROM PYTHON SOURCE LINES 7-27 + + + +.. image-sg:: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_aliased_001.png + :alt: plot aliased + :srcset: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_aliased_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import matplotlib.pyplot as plt + + size = 128, 16 + dpi = 72.0 + figsize = size[0] / float(dpi), size[1] / float(dpi) + fig = plt.figure(figsize=figsize, dpi=dpi) + fig.patch.set_alpha(0) + + plt.axes((0, 0, 1, 1), frameon=False) + + plt.rcParams["text.antialiased"] = False + plt.text(0.5, 0.5, "Aliased", ha="center", va="center") + + plt.xlim(0, 1) + plt.ylim(0, 1) + plt.xticks([]) + plt.yticks([]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.012 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_options_plot_aliased.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_aliased.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_aliased.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_aliased.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/options/plot_alpha.rst.txt b/_sources/intro/matplotlib/auto_examples/options/plot_alpha.rst.txt new file mode 100644 index 000000000..08dad74fc --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/options/plot_alpha.rst.txt @@ -0,0 +1,88 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/options/plot_alpha.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_options_plot_alpha.py: + + +Alpha: transparency +=================== + +This example demonstrates using alpha for transparency. + +.. GENERATED FROM PYTHON SOURCE LINES 7-24 + + + +.. image-sg:: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_alpha_001.png + :alt: plot alpha + :srcset: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_alpha_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import matplotlib.pyplot as plt + + size = 256, 16 + dpi = 72.0 + figsize = size[0] / float(dpi), size[1] / float(dpi) + fig = plt.figure(figsize=figsize, dpi=dpi) + fig.patch.set_alpha(0) + plt.axes((0, 0.1, 1, 0.8), frameon=False) + + for i in range(1, 11): + plt.axvline(i, linewidth=1, color="blue", alpha=0.25 + 0.75 * i / 10.0) + + plt.xlim(0, 11) + plt.xticks([]) + plt.yticks([]) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.019 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_options_plot_alpha.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_alpha.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_alpha.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_alpha.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/options/plot_antialiased.rst.txt b/_sources/intro/matplotlib/auto_examples/options/plot_antialiased.rst.txt new file mode 100644 index 000000000..5df71ad55 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/options/plot_antialiased.rst.txt @@ -0,0 +1,90 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/options/plot_antialiased.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_options_plot_antialiased.py: + + +Aliased versus anti-aliased +============================= + +The example shows aliased versus anti-aliased text. + +.. GENERATED FROM PYTHON SOURCE LINES 7-26 + + + +.. image-sg:: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_antialiased_001.png + :alt: plot antialiased + :srcset: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_antialiased_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import matplotlib.pyplot as plt + + size = 128, 16 + dpi = 72.0 + figsize = size[0] / float(dpi), size[1] / float(dpi) + fig = plt.figure(figsize=figsize, dpi=dpi) + fig.patch.set_alpha(0) + plt.axes((0, 0, 1, 1), frameon=False) + + plt.rcParams["text.antialiased"] = True + plt.text(0.5, 0.5, "Anti-aliased", ha="center", va="center") + + plt.xlim(0, 1) + plt.ylim(0, 1) + plt.xticks([]) + plt.yticks([]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.013 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_options_plot_antialiased.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_antialiased.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_antialiased.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_antialiased.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/options/plot_color.rst.txt b/_sources/intro/matplotlib/auto_examples/options/plot_color.rst.txt new file mode 100644 index 000000000..c2492270d --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/options/plot_color.rst.txt @@ -0,0 +1,88 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/options/plot_color.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_options_plot_color.py: + + +The colors matplotlib line plots +================================== + +An example demoing the various colors taken by matplotlib's plot. + +.. GENERATED FROM PYTHON SOURCE LINES 7-24 + + + +.. image-sg:: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_color_001.png + :alt: plot color + :srcset: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_color_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import matplotlib.pyplot as plt + + size = 256, 16 + dpi = 72.0 + figsize = size[0] / float(dpi), size[1] / float(dpi) + fig = plt.figure(figsize=figsize, dpi=dpi) + fig.patch.set_alpha(0) + plt.axes((0, 0.1, 1, 0.8), frameon=False) + + for i in range(1, 11): + plt.plot([i, i], [0, 1], lw=1.5) + + plt.xlim(0, 11) + plt.xticks([]) + plt.yticks([]) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.018 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_options_plot_color.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_color.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_color.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_color.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/options/plot_colormaps.rst.txt b/_sources/intro/matplotlib/auto_examples/options/plot_colormaps.rst.txt new file mode 100644 index 000000000..f292f40bd --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/options/plot_colormaps.rst.txt @@ -0,0 +1,94 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/options/plot_colormaps.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_options_plot_colormaps.py: + + +Colormaps +========= + +An example plotting the matplotlib colormaps. + +.. GENERATED FROM PYTHON SOURCE LINES 7-30 + + + +.. image-sg:: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_colormaps_001.png + :alt: Accent, Blues, BrBG, BuGn, BuPu, CMRmap, Dark2, GnBu, Grays, Greens, Greys, OrRd, Oranges, PRGn, Paired, Pastel1, Pastel2, PiYG, PuBu, PuBuGn, PuOr, PuRd, Purples, RdBu, RdGy, RdPu, RdYlBu, RdYlGn, Reds, Set1, Set2, Set3, Spectral, Wistia, YlGn, YlGnBu, YlOrBr, YlOrRd, afmhot, autumn, binary, bone, brg, bwr, cividis, cool, coolwarm, copper, cubehelix, flag, gist_earth, gist_gray, gist_grey, gist_heat, gist_ncar, gist_rainbow, gist_stern, gist_yarg, gist_yerg, gnuplot, gnuplot2, gray, grey, hot, hsv, inferno, jet, magma, nipy_spectral, ocean, pink, plasma, prism, rainbow, seismic, spring, summer, tab10, tab20, tab20b, tab20c, terrain, turbo, twilight, twilight_shifted, viridis, winter + :srcset: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_colormaps_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + + import matplotlib + import matplotlib.pyplot as plt + + + plt.rc("text", usetex=False) + a = np.outer(np.arange(0, 1, 0.01), np.ones(10)) + + plt.figure(figsize=(10, 5)) + plt.subplots_adjust(top=0.8, bottom=0.05, left=0.01, right=0.99) + maps = [m for m in matplotlib.colormaps if not m.endswith("_r")] + maps.sort() + l = len(maps) + 1 + + for i, m in enumerate(maps): + plt.subplot(1, l, i + 1) + plt.axis("off") + plt.imshow(a, aspect="auto", cmap=plt.get_cmap(m), origin="lower") + plt.title(m, rotation=90, fontsize=10, va="bottom") + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 1.807 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_options_plot_colormaps.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_colormaps.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_colormaps.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_colormaps.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/options/plot_dash_capstyle.rst.txt b/_sources/intro/matplotlib/auto_examples/options/plot_dash_capstyle.rst.txt new file mode 100644 index 000000000..ec12b3273 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/options/plot_dash_capstyle.rst.txt @@ -0,0 +1,114 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/options/plot_dash_capstyle.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_options_plot_dash_capstyle.py: + + +Dash capstyle +============= + +An example demoing the dash capstyle. + +.. GENERATED FROM PYTHON SOURCE LINES 7-50 + + + +.. image-sg:: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_dash_capstyle_001.png + :alt: plot dash capstyle + :srcset: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_dash_capstyle_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + size = 256, 16 + dpi = 72.0 + figsize = size[0] / float(dpi), size[1] / float(dpi) + fig = plt.figure(figsize=figsize, dpi=dpi) + fig.patch.set_alpha(0) + plt.axes((0, 0, 1, 1), frameon=False) + + plt.plot( + np.arange(4), + np.ones(4), + color="blue", + dashes=[15, 15], + linewidth=8, + dash_capstyle="butt", + ) + + plt.plot( + 5 + np.arange(4), + np.ones(4), + color="blue", + dashes=[15, 15], + linewidth=8, + dash_capstyle="round", + ) + + plt.plot( + 10 + np.arange(4), + np.ones(4), + color="blue", + dashes=[15, 15], + linewidth=8, + dash_capstyle="projecting", + ) + + plt.xlim(0, 14) + plt.xticks([]) + plt.yticks([]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.014 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_options_plot_dash_capstyle.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_dash_capstyle.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_dash_capstyle.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_dash_capstyle.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/options/plot_dash_joinstyle.rst.txt b/_sources/intro/matplotlib/auto_examples/options/plot_dash_joinstyle.rst.txt new file mode 100644 index 000000000..7bc575b2c --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/options/plot_dash_joinstyle.rst.txt @@ -0,0 +1,113 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/options/plot_dash_joinstyle.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_options_plot_dash_joinstyle.py: + + +Dash join style +================ + +Example demoing the dash join style. + +.. GENERATED FROM PYTHON SOURCE LINES 7-49 + + + +.. image-sg:: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_dash_joinstyle_001.png + :alt: plot dash joinstyle + :srcset: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_dash_joinstyle_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + size = 256, 16 + dpi = 72.0 + figsize = size[0] / float(dpi), size[1] / float(dpi) + fig = plt.figure(figsize=figsize, dpi=dpi) + fig.patch.set_alpha(0) + plt.axes((0, 0, 1, 1), frameon=False) + + plt.plot( + np.arange(3), + [0, 1, 0], + color="blue", + dashes=[12, 5], + linewidth=8, + dash_joinstyle="miter", + ) + plt.plot( + 4 + np.arange(3), + [0, 1, 0], + color="blue", + dashes=[12, 5], + linewidth=8, + dash_joinstyle="bevel", + ) + plt.plot( + 8 + np.arange(3), + [0, 1, 0], + color="blue", + dashes=[12, 5], + linewidth=8, + dash_joinstyle="round", + ) + + plt.xlim(0, 12) + plt.ylim(-1, 2) + plt.xticks([]) + plt.yticks([]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.014 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_options_plot_dash_joinstyle.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_dash_joinstyle.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_dash_joinstyle.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_dash_joinstyle.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/options/plot_linestyles.rst.txt b/_sources/intro/matplotlib/auto_examples/options/plot_linestyles.rst.txt new file mode 100644 index 000000000..817858e1a --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/options/plot_linestyles.rst.txt @@ -0,0 +1,135 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/options/plot_linestyles.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_options_plot_linestyles.py: + + +Linestyles +========== + +Plot the different line styles. + +.. GENERATED FROM PYTHON SOURCE LINES 7-71 + + + +.. image-sg:: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_linestyles_001.png + :alt: plot linestyles + :srcset: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_linestyles_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + + def linestyle(ls, i): + X = i * 0.5 * np.ones(11) + Y = np.arange(11) + plt.plot( + X, + Y, + ls, + color=(0.0, 0.0, 1, 1), + lw=3, + ms=8, + mfc=(0.75, 0.75, 1, 1), + mec=(0, 0, 1, 1), + ) + plt.text(0.5 * i, 10.25, ls, rotation=90, fontsize=15, va="bottom") + + + linestyles = [ + "-", + "--", + ":", + "-.", + ".", + ",", + "o", + "^", + "v", + "<", + ">", + "s", + "+", + "x", + "d", + "1", + "2", + "3", + "4", + "h", + "p", + "|", + "_", + "D", + "H", + ] + n_lines = len(linestyles) + + size = 20 * n_lines, 300 + dpi = 72.0 + figsize = size[0] / float(dpi), size[1] / float(dpi) + fig = plt.figure(figsize=figsize, dpi=dpi) + plt.axes((0, 0.01, 1, 0.9), frameon=False) + + for i, ls in enumerate(linestyles): + linestyle(ls, i) + + plt.xlim(-0.2, 0.2 + 0.5 * n_lines) + plt.xticks([]) + plt.yticks([]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.044 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_options_plot_linestyles.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_linestyles.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_linestyles.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_linestyles.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/options/plot_linewidth.rst.txt b/_sources/intro/matplotlib/auto_examples/options/plot_linewidth.rst.txt new file mode 100644 index 000000000..d72977a57 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/options/plot_linewidth.rst.txt @@ -0,0 +1,90 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/options/plot_linewidth.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_options_plot_linewidth.py: + + +Linewidth +========= + +Plot various linewidth with matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-26 + + + +.. image-sg:: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_linewidth_001.png + :alt: plot linewidth + :srcset: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_linewidth_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import matplotlib.pyplot as plt + + size = 256, 16 + dpi = 72.0 + figsize = size[0] / float(dpi), size[1] / float(dpi) + fig = plt.figure(figsize=figsize, dpi=dpi) + fig.patch.set_alpha(0) + plt.axes((0, 0.1, 1, 0.8), frameon=False) + + for i in range(1, 11): + plt.plot([i, i], [0, 1], color="b", lw=i / 2.0) + + plt.xlim(0, 11) + plt.ylim(0, 1) + plt.xticks([]) + plt.yticks([]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.020 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_options_plot_linewidth.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_linewidth.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_linewidth.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_linewidth.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/options/plot_markers.rst.txt b/_sources/intro/matplotlib/auto_examples/options/plot_markers.rst.txt new file mode 100644 index 000000000..8912df459 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/options/plot_markers.rst.txt @@ -0,0 +1,135 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/options/plot_markers.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_options_plot_markers.py: + + +Markers +======= + +Show the different markers of matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-71 + + + +.. image-sg:: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_markers_001.png + :alt: plot markers + :srcset: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_markers_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + + def marker(m, i): + X = i * 0.5 * np.ones(11) + Y = np.arange(11) + + plt.plot(X, Y, lw=1, marker=m, ms=10, mfc=(0.75, 0.75, 1, 1), mec=(0, 0, 1, 1)) + plt.text(0.5 * i, 10.25, repr(m), rotation=90, fontsize=15, va="bottom") + + + markers = [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + "o", + "h", + "_", + "1", + "2", + "3", + "4", + "8", + "p", + "^", + "v", + "<", + ">", + "|", + "d", + ",", + "+", + "s", + "*", + "|", + "x", + "D", + "H", + ".", + ] + + n_markers = len(markers) + + size = 20 * n_markers, 300 + dpi = 72.0 + figsize = size[0] / float(dpi), size[1] / float(dpi) + fig = plt.figure(figsize=figsize, dpi=dpi) + plt.axes((0, 0.01, 1, 0.9), frameon=False) + + for i, m in enumerate(markers): + marker(m, i) + + plt.xlim(-0.2, 0.2 + 0.5 * n_markers) + plt.xticks([]) + plt.yticks([]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.073 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_options_plot_markers.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_markers.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_markers.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_markers.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/options/plot_mec.rst.txt b/_sources/intro/matplotlib/auto_examples/options/plot_mec.rst.txt new file mode 100644 index 000000000..a9b700e4b --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/options/plot_mec.rst.txt @@ -0,0 +1,105 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/options/plot_mec.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_options_plot_mec.py: + + +Marker edge color +================== + +Demo the marker edge color of matplotlib's markers. + +.. GENERATED FROM PYTHON SOURCE LINES 7-41 + + + +.. image-sg:: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_mec_001.png + :alt: plot mec + :srcset: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_mec_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + size = 256, 16 + dpi = 72.0 + figsize = size[0] / float(dpi), size[1] / float(dpi) + fig = plt.figure(figsize=figsize, dpi=dpi) + fig.patch.set_alpha(0) + plt.axes((0, 0, 1, 1), frameon=False) + + rng = np.random.default_rng() + + for i in range(1, 11): + r, g, b = np.random.uniform(0, 1, 3) + plt.plot( + [ + i, + ], + [ + 1, + ], + "s", + markersize=5, + markerfacecolor="w", + markeredgewidth=1.5, + markeredgecolor=(r, g, b, 1), + ) + + plt.xlim(0, 11) + plt.xticks([]) + plt.yticks([]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.017 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_options_plot_mec.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_mec.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_mec.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_mec.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/options/plot_mew.rst.txt b/_sources/intro/matplotlib/auto_examples/options/plot_mew.rst.txt new file mode 100644 index 000000000..3b2058c49 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/options/plot_mew.rst.txt @@ -0,0 +1,100 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/options/plot_mew.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_options_plot_mew.py: + + +Marker edge width +================= + +Demo the marker edge widths of matplotlib's markers. + +.. GENERATED FROM PYTHON SOURCE LINES 7-36 + + + +.. image-sg:: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_mew_001.png + :alt: plot mew + :srcset: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_mew_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import matplotlib.pyplot as plt + + size = 256, 16 + dpi = 72.0 + figsize = size[0] / float(dpi), size[1] / float(dpi) + fig = plt.figure(figsize=figsize, dpi=dpi) + fig.patch.set_alpha(0) + plt.axes((0, 0, 1, 1), frameon=False) + + for i in range(1, 11): + plt.plot( + [ + i, + ], + [ + 1, + ], + "s", + markersize=5, + markeredgewidth=1 + i / 10.0, + markeredgecolor="k", + markerfacecolor="w", + ) + plt.xlim(0, 11) + plt.xticks([]) + plt.yticks([]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.017 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_options_plot_mew.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_mew.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_mew.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_mew.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/options/plot_mfc.rst.txt b/_sources/intro/matplotlib/auto_examples/options/plot_mfc.rst.txt new file mode 100644 index 000000000..6a08d6f95 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/options/plot_mfc.rst.txt @@ -0,0 +1,103 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/options/plot_mfc.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_options_plot_mfc.py: + + +Marker face color +================== + +Demo the marker face color of matplotlib's markers. + +.. GENERATED FROM PYTHON SOURCE LINES 7-39 + + + +.. image-sg:: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_mfc_001.png + :alt: plot mfc + :srcset: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_mfc_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + size = 256, 16 + dpi = 72.0 + figsize = size[0] / float(dpi), size[1] / float(dpi) + fig = plt.figure(figsize=figsize, dpi=dpi) + fig.patch.set_alpha(0) + plt.axes((0, 0, 1, 1), frameon=False) + + rng = np.random.default_rng() + + for i in range(1, 11): + r, g, b = np.random.uniform(0, 1, 3) + plt.plot( + [ + i, + ], + [ + 1, + ], + "s", + markersize=8, + markerfacecolor=(r, g, b, 1), + markeredgewidth=0.1, + markeredgecolor=(0, 0, 0, 0.5), + ) + plt.xlim(0, 11) + plt.xticks([]) + plt.yticks([]) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.017 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_options_plot_mfc.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_mfc.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_mfc.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_mfc.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/options/plot_ms.rst.txt b/_sources/intro/matplotlib/auto_examples/options/plot_ms.rst.txt new file mode 100644 index 000000000..a5cefd9ce --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/options/plot_ms.rst.txt @@ -0,0 +1,101 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/options/plot_ms.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_options_plot_ms.py: + + +Marker size +=========== + +Demo the marker size control in matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-37 + + + +.. image-sg:: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_ms_001.png + :alt: plot ms + :srcset: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_ms_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import matplotlib.pyplot as plt + + size = 256, 16 + dpi = 72.0 + figsize = size[0] / float(dpi), size[1] / float(dpi) + fig = plt.figure(figsize=figsize, dpi=dpi) + fig.patch.set_alpha(0) + plt.axes((0, 0, 1, 1), frameon=False) + + for i in range(1, 11): + plt.plot( + [ + i, + ], + [ + 1, + ], + "s", + markersize=i, + markerfacecolor="w", + markeredgewidth=0.5, + markeredgecolor="k", + ) + + plt.xlim(0, 11) + plt.xticks([]) + plt.yticks([]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.017 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_options_plot_ms.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_ms.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_ms.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_ms.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/options/plot_solid_capstyle.rst.txt b/_sources/intro/matplotlib/auto_examples/options/plot_solid_capstyle.rst.txt new file mode 100644 index 000000000..6dd2b7e7f --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/options/plot_solid_capstyle.rst.txt @@ -0,0 +1,101 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/options/plot_solid_capstyle.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_options_plot_solid_capstyle.py: + + +Solid cap style +================ + +An example demoing the solide cap style in matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-37 + + + +.. image-sg:: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_solid_capstyle_001.png + :alt: plot solid capstyle + :srcset: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_solid_capstyle_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + size = 256, 16 + dpi = 72.0 + figsize = size[0] / float(dpi), size[1] / float(dpi) + fig = plt.figure(figsize=figsize, dpi=dpi) + fig.patch.set_alpha(0) + plt.axes((0, 0, 1, 1), frameon=False) + + plt.plot(np.arange(4), np.ones(4), color="blue", linewidth=8, solid_capstyle="butt") + + plt.plot( + 5 + np.arange(4), np.ones(4), color="blue", linewidth=8, solid_capstyle="round" + ) + + plt.plot( + 10 + np.arange(4), + np.ones(4), + color="blue", + linewidth=8, + solid_capstyle="projecting", + ) + + plt.xlim(0, 14) + plt.xticks([]) + plt.yticks([]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.013 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_options_plot_solid_capstyle.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_solid_capstyle.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_solid_capstyle.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_solid_capstyle.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/options/plot_solid_joinstyle.rst.txt b/_sources/intro/matplotlib/auto_examples/options/plot_solid_joinstyle.rst.txt new file mode 100644 index 000000000..b834ef636 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/options/plot_solid_joinstyle.rst.txt @@ -0,0 +1,96 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/options/plot_solid_joinstyle.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_options_plot_solid_joinstyle.py: + + +Solid joint style +================== + +An example showing the different solid joint styles in matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-32 + + + +.. image-sg:: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_solid_joinstyle_001.png + :alt: plot solid joinstyle + :srcset: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_solid_joinstyle_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + size = 256, 16 + dpi = 72.0 + figsize = size[0] / float(dpi), size[1] / float(dpi) + fig = plt.figure(figsize=figsize, dpi=dpi) + fig.patch.set_alpha(0) + plt.axes((0, 0, 1, 1), frameon=False) + + plt.plot(np.arange(3), [0, 1, 0], color="blue", linewidth=8, solid_joinstyle="miter") + plt.plot( + 4 + np.arange(3), [0, 1, 0], color="blue", linewidth=8, solid_joinstyle="bevel" + ) + plt.plot( + 8 + np.arange(3), [0, 1, 0], color="blue", linewidth=8, solid_joinstyle="round" + ) + + plt.xlim(0, 12) + plt.ylim(-1, 2) + plt.xticks([]) + plt.yticks([]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.014 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_options_plot_solid_joinstyle.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_solid_joinstyle.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_solid_joinstyle.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_solid_joinstyle.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/options/plot_ticks.rst.txt b/_sources/intro/matplotlib/auto_examples/options/plot_ticks.rst.txt new file mode 100644 index 000000000..4940cfad9 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/options/plot_ticks.rst.txt @@ -0,0 +1,120 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/options/plot_ticks.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_options_plot_ticks.py: + + +Locators for tick on axis +========================== + +An example demoing different locators to position ticks on axis for +matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 8-56 + + + +.. image-sg:: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_ticks_001.png + :alt: plot ticks + :srcset: /intro/matplotlib/auto_examples/options/images/sphx_glr_plot_ticks_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + + from matplotlib import ticker + import matplotlib.pyplot as plt + + + def tickline(): + plt.xlim(0, 10), plt.ylim(-1, 1), plt.yticks([]) + ax = plt.gca() + ax.spines["right"].set_color("none") + ax.spines["left"].set_color("none") + ax.spines["top"].set_color("none") + ax.xaxis.set_ticks_position("bottom") + ax.spines["bottom"].set_position(("data", 0)) + ax.yaxis.set_ticks_position("none") + ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.1)) + ax.plot(np.arange(11), np.zeros(11)) + return ax + + + locators = [ + "ticker.NullLocator()", + "ticker.MultipleLocator(1.0)", + "ticker.FixedLocator([0, 2, 8, 9, 10])", + "ticker.IndexLocator(3, 1)", + "ticker.LinearLocator(5)", + "ticker.LogLocator(2, [1.0])", + "ticker.AutoLocator()", + ] + + n_locators = len(locators) + + size = 512, 40 * n_locators + dpi = 72.0 + figsize = size[0] / float(dpi), size[1] / float(dpi) + fig = plt.figure(figsize=figsize, dpi=dpi) + fig.patch.set_alpha(0) + + + for i, locator in enumerate(locators): + plt.subplot(n_locators, 1, i + 1) + ax = tickline() + ax.xaxis.set_major_locator(eval(locator)) + plt.text(5, 0.3, locator[7:], ha="center") + + plt.subplots_adjust(bottom=0.01, top=0.99, left=0.01, right=0.99) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.923 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_options_plot_ticks.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_ticks.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_ticks.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_ticks.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/options/sg_execution_times.rst.txt b/_sources/intro/matplotlib/auto_examples/options/sg_execution_times.rst.txt new file mode 100644 index 000000000..244da3ff7 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/options/sg_execution_times.rst.txt @@ -0,0 +1,85 @@ + +:orphan: + +.. _sphx_glr_intro_matplotlib_auto_examples_options_sg_execution_times: + + +Computation times +================= +**00:03.052** total execution time for 17 files **from intro/matplotlib/auto_examples/options**: + +.. container:: + + .. raw:: html + + + + + + + + .. list-table:: + :header-rows: 1 + :class: table table-striped sg-datatable + + * - Example + - Time + - Mem (MB) + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_colormaps.py` (``plot_colormaps.py``) + - 00:01.807 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_ticks.py` (``plot_ticks.py``) + - 00:00.923 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_markers.py` (``plot_markers.py``) + - 00:00.073 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_linestyles.py` (``plot_linestyles.py``) + - 00:00.044 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_linewidth.py` (``plot_linewidth.py``) + - 00:00.020 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_alpha.py` (``plot_alpha.py``) + - 00:00.019 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_color.py` (``plot_color.py``) + - 00:00.018 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_mec.py` (``plot_mec.py``) + - 00:00.017 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_mfc.py` (``plot_mfc.py``) + - 00:00.017 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_ms.py` (``plot_ms.py``) + - 00:00.017 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_mew.py` (``plot_mew.py``) + - 00:00.017 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_solid_joinstyle.py` (``plot_solid_joinstyle.py``) + - 00:00.014 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_dash_joinstyle.py` (``plot_dash_joinstyle.py``) + - 00:00.014 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_dash_capstyle.py` (``plot_dash_capstyle.py``) + - 00:00.014 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_solid_capstyle.py` (``plot_solid_capstyle.py``) + - 00:00.013 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_antialiased.py` (``plot_antialiased.py``) + - 00:00.013 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_aliased.py` (``plot_aliased.py``) + - 00:00.012 + - 0.0 diff --git a/_sources/intro/matplotlib/auto_examples/plot_axes-2.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_axes-2.rst.txt new file mode 100644 index 000000000..6f88f559b --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_axes-2.rst.txt @@ -0,0 +1,103 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_axes-2.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_axes-2.py: + + +Axes +==== + +This example shows various axes command to position matplotlib axes. + +.. GENERATED FROM PYTHON SOURCE LINES 8-40 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_axes-2_001.png + :alt: plot axes 2 + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_axes-2_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import matplotlib.pyplot as plt + + plt.axes((0.1, 0.1, 0.5, 0.5)) + plt.xticks([]) + plt.yticks([]) + plt.text( + 0.1, 0.1, "axes((0.1, 0.1, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5 + ) + + plt.axes((0.2, 0.2, 0.5, 0.5)) + plt.xticks([]) + plt.yticks([]) + plt.text( + 0.1, 0.1, "axes((0.2, 0.2, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5 + ) + + plt.axes((0.3, 0.3, 0.5, 0.5)) + plt.xticks([]) + plt.yticks([]) + plt.text( + 0.1, 0.1, "axes((0.3, 0.3, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5 + ) + + plt.axes((0.4, 0.4, 0.5, 0.5)) + plt.xticks([]) + plt.yticks([]) + plt.text( + 0.1, 0.1, "axes((0.4, 0.4, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5 + ) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.058 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_axes-2.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_axes-2.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_axes-2.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_axes-2.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/plot_axes.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_axes.rst.txt new file mode 100644 index 000000000..7244e7e77 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_axes.rst.txt @@ -0,0 +1,89 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_axes.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_axes.py: + + +Simple axes example +==================== + +This example shows a couple of simple usage of axes. + +.. GENERATED FROM PYTHON SOURCE LINES 8-26 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_axes_001.png + :alt: plot axes + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_axes_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import matplotlib.pyplot as plt + + plt.axes((0.1, 0.1, 0.8, 0.8)) + plt.xticks([]) + plt.yticks([]) + plt.text( + 0.6, 0.6, "axes([0.1, 0.1, 0.8, 0.8])", ha="center", va="center", size=20, alpha=0.5 + ) + + plt.axes((0.2, 0.2, 0.3, 0.3)) + plt.xticks([]) + plt.yticks([]) + plt.text( + 0.5, 0.5, "axes([0.2, 0.2, 0.3, 0.3])", ha="center", va="center", size=16, alpha=0.5 + ) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.048 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_axes.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_axes.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_axes.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_axes.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/plot_bad.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_bad.rst.txt new file mode 100644 index 000000000..7593324f3 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_bad.rst.txt @@ -0,0 +1,87 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_bad.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_bad.py: + + +A simple plotting example +========================== + +A plotting example with a few simple tweaks + +.. GENERATED FROM PYTHON SOURCE LINES 7-23 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_bad_001.png + :alt: plot bad + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_bad_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + fig = plt.figure(figsize=(5, 4), dpi=72) + axes = fig.add_axes((0.01, 0.01, 0.98, 0.98)) + x = np.linspace(0, 2, 200) + y = np.sin(2 * np.pi * x) + plt.plot(x, y, lw=0.25, c="k") + plt.xticks(np.arange(0.0, 2.0, 0.1)) + plt.yticks(np.arange(-1.0, 1.0, 0.1)) + plt.grid() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.086 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_bad.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_bad.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_bad.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_bad.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/plot_bar.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_bar.rst.txt new file mode 100644 index 000000000..9cc6d0362 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_bar.rst.txt @@ -0,0 +1,97 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_bar.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_bar.py: + + +Bar plots +========== + +An example of bar plots with matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-33 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_bar_001.png + :alt: plot bar + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_bar_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + n = 12 + X = np.arange(n) + rng = np.random.default_rng() + Y1 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n) + Y2 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n) + + plt.axes((0.025, 0.025, 0.95, 0.95)) + plt.bar(X, +Y1, facecolor="#9999ff", edgecolor="white") + plt.bar(X, -Y2, facecolor="#ff9999", edgecolor="white") + + for x, y in zip(X, Y1, strict=True): + plt.text(x + 0.4, y + 0.05, f"{y:.2f}", ha="center", va="bottom") + + for x, y in zip(X, Y2, strict=True): + plt.text(x + 0.4, -y - 0.05, f"{y:.2f}", ha="center", va="top") + + plt.xlim(-0.5, n) + plt.xticks([]) + plt.ylim(-1.25, 1.25) + plt.yticks([]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.056 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_bar.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_bar.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_bar.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_bar.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/plot_contour.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_contour.rst.txt new file mode 100644 index 000000000..440d3f441 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_contour.rst.txt @@ -0,0 +1,95 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_contour.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_contour.py: + + +Displaying the contours of a function +====================================== + +An example showing how to display the contours of a function with +matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 8-31 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_contour_001.png + :alt: plot contour + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_contour_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + + def f(x, y): + return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2) + + + n = 256 + x = np.linspace(-3, 3, n) + y = np.linspace(-3, 3, n) + X, Y = np.meshgrid(x, y) + + plt.axes((0.025, 0.025, 0.95, 0.95)) + + plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap="hot") + C = plt.contour(X, Y, f(X, Y), 8, colors="black", linewidths=0.5) + plt.clabel(C, inline=1, fontsize=10) + + plt.xticks([]) + plt.yticks([]) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.079 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_contour.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_contour.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_contour.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_contour.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/plot_good.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_good.rst.txt new file mode 100644 index 000000000..225fc4964 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_good.rst.txt @@ -0,0 +1,87 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_good.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_good.py: + + +A simple, good-looking plot +=========================== + +Demoing some simple features of matplotlib + +.. GENERATED FROM PYTHON SOURCE LINES 7-23 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_good_001.png + :alt: plot good + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_good_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + fig = plt.figure(figsize=(5, 4), dpi=72) + axes = fig.add_axes((0.01, 0.01, 0.98, 0.98)) + X = np.linspace(0, 2, 200) + Y = np.sin(2 * np.pi * X) + plt.plot(X, Y, lw=2) + plt.ylim(-1.1, 1.1) + plt.grid() + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.053 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_good.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_good.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_good.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_good.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/plot_grid.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_grid.rst.txt new file mode 100644 index 000000000..e4faa7b60 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_grid.rst.txt @@ -0,0 +1,91 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_grid.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_grid.py: + + +Grid +==== + +Displaying a grid on the axes in matploblib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-27 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_grid_001.png + :alt: plot grid + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_grid_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import matplotlib.pyplot as plt + from matplotlib import ticker + + ax = plt.axes((0.025, 0.025, 0.95, 0.95)) + + ax.set_xlim(0, 4) + ax.set_ylim(0, 3) + ax.xaxis.set_major_locator(ticker.MultipleLocator(1.0)) + ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.1)) + ax.yaxis.set_major_locator(ticker.MultipleLocator(1.0)) + ax.yaxis.set_minor_locator(ticker.MultipleLocator(0.1)) + ax.grid(which="major", axis="x", linewidth=0.75, linestyle="-", color="0.75") + ax.grid(which="minor", axis="x", linewidth=0.25, linestyle="-", color="0.75") + ax.grid(which="major", axis="y", linewidth=0.75, linestyle="-", color="0.75") + ax.grid(which="minor", axis="y", linewidth=0.25, linestyle="-", color="0.75") + ax.set_xticklabels([]) + ax.set_yticklabels([]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.106 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_grid.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_grid.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_grid.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_grid.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/plot_gridspec.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_gridspec.rst.txt new file mode 100644 index 000000000..bff4a64a0 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_gridspec.rst.txt @@ -0,0 +1,105 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_gridspec.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_gridspec.py: + + +GridSpec +========= + +An example demoing gridspec + +.. GENERATED FROM PYTHON SOURCE LINES 7-41 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_gridspec_001.png + :alt: plot gridspec + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_gridspec_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import matplotlib.pyplot as plt + from matplotlib import gridspec + + plt.figure(figsize=(6, 4)) + G = gridspec.GridSpec(3, 3) + + axes_1 = plt.subplot(G[0, :]) + plt.xticks([]) + plt.yticks([]) + plt.text(0.5, 0.5, "Axes 1", ha="center", va="center", size=24, alpha=0.5) + + axes_2 = plt.subplot(G[1, :-1]) + plt.xticks([]) + plt.yticks([]) + plt.text(0.5, 0.5, "Axes 2", ha="center", va="center", size=24, alpha=0.5) + + axes_3 = plt.subplot(G[1:, -1]) + plt.xticks([]) + plt.yticks([]) + plt.text(0.5, 0.5, "Axes 3", ha="center", va="center", size=24, alpha=0.5) + + axes_4 = plt.subplot(G[-1, 0]) + plt.xticks([]) + plt.yticks([]) + plt.text(0.5, 0.5, "Axes 4", ha="center", va="center", size=24, alpha=0.5) + + axes_5 = plt.subplot(G[-1, -2]) + plt.xticks([]) + plt.yticks([]) + plt.text(0.5, 0.5, "Axes 5", ha="center", va="center", size=24, alpha=0.5) + + plt.tight_layout() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.086 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_gridspec.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_gridspec.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_gridspec.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_gridspec.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/plot_imshow.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_imshow.rst.txt new file mode 100644 index 000000000..78bfa1d59 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_imshow.rst.txt @@ -0,0 +1,93 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_imshow.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_imshow.py: + + +Imshow elaborate +================= + +An example demoing imshow and styling the figure. + +.. GENERATED FROM PYTHON SOURCE LINES 7-29 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_imshow_001.png + :alt: plot imshow + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_imshow_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + + def f(x, y): + return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2) + + + n = 10 + x = np.linspace(-3, 3, int(3.5 * n)) + y = np.linspace(-3, 3, int(3.0 * n)) + X, Y = np.meshgrid(x, y) + Z = f(X, Y) + + plt.axes((0.025, 0.025, 0.95, 0.95)) + plt.imshow(Z, interpolation="nearest", cmap="bone", origin="lower") + plt.colorbar(shrink=0.92) + + plt.xticks([]) + plt.yticks([]) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.122 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_imshow.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_imshow.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_imshow.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_imshow.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/plot_multiplot.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_multiplot.rst.txt new file mode 100644 index 000000000..333a9df50 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_multiplot.rst.txt @@ -0,0 +1,93 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_multiplot.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_multiplot.py: + + +Subplots +========= + +Show multiple subplots in matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-29 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_multiplot_001.png + :alt: plot multiplot + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_multiplot_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import matplotlib.pyplot as plt + + fig = plt.figure() + fig.subplots_adjust(bottom=0.025, left=0.025, top=0.975, right=0.975) + + plt.subplot(2, 1, 1) + plt.xticks([]), plt.yticks([]) + + plt.subplot(2, 3, 4) + plt.xticks([]) + plt.yticks([]) + + plt.subplot(2, 3, 5) + plt.xticks([]) + plt.yticks([]) + + plt.subplot(2, 3, 6) + plt.xticks([]) + plt.yticks([]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.049 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_multiplot.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_multiplot.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_multiplot.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_multiplot.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/plot_pie.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_pie.rst.txt new file mode 100644 index 000000000..ad8c706d0 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_pie.rst.txt @@ -0,0 +1,87 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_pie.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_pie.py: + + +Pie chart +========= + +A simple pie chart example with matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-23 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_pie_001.png + :alt: plot pie + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_pie_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + n = 20 + Z = np.ones(n) + Z[-1] *= 2 + + plt.axes((0.025, 0.025, 0.95, 0.95)) + + plt.pie(Z, explode=Z * 0.05, colors=[f"{i / float(n):f}" for i in range(n)]) + plt.axis("equal") + plt.xticks([]) + plt.yticks() + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.059 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_pie.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_pie.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_pie.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_pie.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/plot_plot.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_plot.rst.txt new file mode 100644 index 000000000..8ee029e0a --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_plot.rst.txt @@ -0,0 +1,94 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_plot.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_plot.py: + + +Plot and filled plots +===================== + +Simple example of plots and filling between them with matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-30 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_plot_001.png + :alt: plot plot + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_plot_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + n = 256 + X = np.linspace(-np.pi, np.pi, n) + Y = np.sin(2 * X) + + plt.axes((0.025, 0.025, 0.95, 0.95)) + + plt.plot(X, Y + 1, color="blue", alpha=1.00) + plt.fill_between(X, 1, Y + 1, color="blue", alpha=0.25) + + plt.plot(X, Y - 1, color="blue", alpha=1.00) + plt.fill_between(X, -1, Y - 1, (Y - 1) > -1, color="blue", alpha=0.25) + plt.fill_between(X, -1, Y - 1, (Y - 1) < -1, color="red", alpha=0.25) + + plt.xlim(-np.pi, np.pi) + plt.xticks([]) + plt.ylim(-2.5, 2.5) + plt.yticks([]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.033 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_plot.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_plot.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_plot.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_plot.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/plot_plot3d-2.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_plot3d-2.rst.txt new file mode 100644 index 000000000..7cef19d62 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_plot3d-2.rst.txt @@ -0,0 +1,109 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_plot3d-2.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_plot3d-2.py: + + +3D plotting +============ + +Demo 3D plotting with matplotlib and style the figure. + +.. GENERATED FROM PYTHON SOURCE LINES 7-45 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_plot3d-2_001.png + :alt: plot plot3d 2 + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_plot3d-2_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import matplotlib.pyplot as plt + from mpl_toolkits.mplot3d.axes3d import Axes3D, get_test_data + + ax: Axes3D = plt.figure().add_subplot(projection="3d") + X, Y, Z = get_test_data(0.05) + cset = ax.contourf(X, Y, Z) + ax.clabel(cset, fontsize=9, inline=1) + + plt.xticks([]) + plt.yticks([]) + ax.set_zticks([]) + + + ax.text2D( + -0.05, + 1.05, + " 3D plots \n", + horizontalalignment="left", + verticalalignment="top", + bbox={"facecolor": "white", "alpha": 1.0}, + family="DejaVu Sans", + size="x-large", + transform=plt.gca().transAxes, + ) + + ax.text2D( + -0.05, + 0.975, + " Plot 2D or 3D data", + horizontalalignment="left", + verticalalignment="top", + family="DejaVu Sans", + size="medium", + transform=plt.gca().transAxes, + ) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.053 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_plot3d-2.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_plot3d-2.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_plot3d-2.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_plot3d-2.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/plot_plot3d.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_plot3d.rst.txt new file mode 100644 index 000000000..df82bb9e3 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_plot3d.rst.txt @@ -0,0 +1,88 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_plot3d.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_plot3d.py: + + +3D plotting +=========== + +A simple example of 3D plotting. + +.. GENERATED FROM PYTHON SOURCE LINES 7-24 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_plot3d_001.png + :alt: plot plot3d + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_plot3d_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + from mpl_toolkits.mplot3d import Axes3D + + ax: Axes3D = plt.figure().add_subplot(projection="3d") + X = np.arange(-4, 4, 0.25) + Y = np.arange(-4, 4, 0.25) + X, Y = np.meshgrid(X, Y) + R = np.sqrt(X**2 + Y**2) + Z = np.sin(R) + + ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap="hot") + ax.contourf(X, Y, Z, zdir="z", offset=-2, cmap="hot") + ax.set_zlim(-2, 2) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.106 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_plot3d.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_plot3d.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_plot3d.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_plot3d.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/plot_polar.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_polar.rst.txt new file mode 100644 index 000000000..563d64ad2 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_polar.rst.txt @@ -0,0 +1,97 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_polar.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_polar.py: + + +Plotting in polar coordinates +============================= + +A simple example showing how to plot in polar coordinates with +matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 8-33 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_polar_001.png + :alt: plot polar + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_polar_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + + import matplotlib + import matplotlib.pyplot as plt + + + jet = matplotlib.colormaps["jet"] + + ax = plt.axes((0.025, 0.025, 0.95, 0.95), polar=True) + + N = 20 + theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N) + rng = np.random.default_rng() + radii = 10 * rng.random(N) + width = np.pi / 4 * rng.random(N) + bars = plt.bar(theta, radii, width=width, bottom=0.0) + + for r, bar in zip(radii, bars, strict=True): + bar.set_facecolor(jet(r / 10.0)) + bar.set_alpha(0.5) + + ax.set_xticklabels([]) + ax.set_yticklabels([]) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.096 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_polar.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_polar.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_polar.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_polar.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/plot_quiver.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_quiver.rst.txt new file mode 100644 index 000000000..cd1fea329 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_quiver.rst.txt @@ -0,0 +1,92 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_quiver.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_quiver.py: + + +Plotting a vector field: quiver +================================ + +A simple example showing how to plot a vector field (quiver) with +matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 8-28 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_quiver_001.png + :alt: plot quiver + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_quiver_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + n = 8 + X, Y = np.mgrid[0:n, 0:n] + T = np.arctan2(Y - n / 2.0, X - n / 2.0) + R = 10 + np.sqrt((Y - n / 2.0) ** 2 + (X - n / 2.0) ** 2) + U, V = R * np.cos(T), R * np.sin(T) + + plt.axes((0.025, 0.025, 0.95, 0.95)) + plt.quiver(X, Y, U, V, R, alpha=0.5) + plt.quiver(X, Y, U, V, edgecolor="k", facecolor="None", linewidth=0.5) + + plt.xlim(-1, n) + plt.xticks([]) + plt.ylim(-1, n) + plt.yticks([]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.034 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_quiver.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_quiver.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_quiver.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_quiver.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/plot_scatter.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_scatter.rst.txt new file mode 100644 index 000000000..989595912 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_scatter.rst.txt @@ -0,0 +1,90 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_scatter.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_scatter.py: + + +Plotting a scatter of points +============================== + +A simple example showing how to plot a scatter of points with matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-26 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_scatter_001.png + :alt: plot scatter + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_scatter_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + n = 1024 + rng = np.random.default_rng() + X = rng.normal(0, 1, n) + Y = rng.normal(0, 1, n) + T = np.arctan2(Y, X) + + plt.axes((0.025, 0.025, 0.95, 0.95)) + plt.scatter(X, Y, s=75, c=T, alpha=0.5) + + plt.xlim(-1.5, 1.5) + plt.xticks([]) + plt.ylim(-1.5, 1.5) + plt.yticks([]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.060 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_scatter.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_scatter.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_scatter.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_scatter.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/plot_subplot-grid.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_subplot-grid.rst.txt new file mode 100644 index 000000000..826c0774b --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_subplot-grid.rst.txt @@ -0,0 +1,98 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_subplot-grid.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_subplot-grid.py: + + +Subplot grid +============= + +An example showing the subplot grid in matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-34 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_subplot-grid_001.png + :alt: plot subplot grid + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_subplot-grid_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import matplotlib.pyplot as plt + + plt.figure(figsize=(6, 4)) + plt.subplot(2, 2, 1) + plt.xticks([]) + plt.yticks([]) + plt.text(0.5, 0.5, "subplot(2,2,1)", ha="center", va="center", size=20, alpha=0.5) + + plt.subplot(2, 2, 2) + plt.xticks([]) + plt.yticks([]) + plt.text(0.5, 0.5, "subplot(2,2,2)", ha="center", va="center", size=20, alpha=0.5) + + plt.subplot(2, 2, 3) + plt.xticks([]) + plt.yticks([]) + + plt.text(0.5, 0.5, "subplot(2,2,3)", ha="center", va="center", size=20, alpha=0.5) + + plt.subplot(2, 2, 4) + plt.xticks([]) + plt.yticks([]) + plt.text(0.5, 0.5, "subplot(2,2,4)", ha="center", va="center", size=20, alpha=0.5) + + plt.tight_layout() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.072 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_subplot-grid.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_subplot-grid.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_subplot-grid.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_subplot-grid.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/plot_subplot-horizontal.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_subplot-horizontal.rst.txt new file mode 100644 index 000000000..21c312119 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_subplot-horizontal.rst.txt @@ -0,0 +1,87 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_subplot-horizontal.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_subplot-horizontal.py: + + +Horizontal arrangement of subplots +================================== + +An example showing horizontal arrangement of subplots with matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-23 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_subplot-horizontal_001.png + :alt: plot subplot horizontal + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_subplot-horizontal_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import matplotlib.pyplot as plt + + plt.figure(figsize=(6, 4)) + plt.subplot(2, 1, 1) + plt.xticks([]) + plt.yticks([]) + plt.text(0.5, 0.5, "subplot(2,1,1)", ha="center", va="center", size=24, alpha=0.5) + + plt.subplot(2, 1, 2) + plt.xticks([]) + plt.yticks([]) + plt.text(0.5, 0.5, "subplot(2,1,2)", ha="center", va="center", size=24, alpha=0.5) + + plt.tight_layout() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.050 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_subplot-horizontal.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_subplot-horizontal.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_subplot-horizontal.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_subplot-horizontal.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/plot_subplot-vertical.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_subplot-vertical.rst.txt new file mode 100644 index 000000000..817bb94ec --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_subplot-vertical.rst.txt @@ -0,0 +1,88 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_subplot-vertical.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_subplot-vertical.py: + + +Subplot plot arrangement vertical +================================== + +An example showing vertical arrangement of subplots with matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-24 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_subplot-vertical_001.png + :alt: plot subplot vertical + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_subplot-vertical_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import matplotlib.pyplot as plt + + + plt.figure(figsize=(6, 4)) + plt.subplot(1, 2, 1) + plt.xticks([]) + plt.yticks([]) + plt.text(0.5, 0.5, "subplot(1,2,1)", ha="center", va="center", size=24, alpha=0.5) + + plt.subplot(1, 2, 2) + plt.xticks([]) + plt.yticks([]) + plt.text(0.5, 0.5, "subplot(1,2,2)", ha="center", va="center", size=24, alpha=0.5) + + plt.tight_layout() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.041 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_subplot-vertical.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_subplot-vertical.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_subplot-vertical.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_subplot-vertical.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/plot_text.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_text.rst.txt new file mode 100644 index 000000000..a8234440d --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_text.rst.txt @@ -0,0 +1,113 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_text.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_text.py: + + +Demo text printing +=================== + +A example showing off elaborate text printing with matplotlib. + +.. GENERATED FROM PYTHON SOURCE LINES 7-49 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_text_001.png + :alt: plot text + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_text_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + + eqs = [] + eqs.append( + r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$" + ) + eqs.append( + r"$\frac{d\rho}{d t} + \rho \vec{v}\cdot\nabla\vec{v} = -\nabla p + \mu\nabla^2 \vec{v} + \rho \vec{g}$" + ) + eqs.append(r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$") + eqs.append(r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$") + eqs.append(r"$F_G = G\frac{m_1m_2}{r^2}$") + + plt.axes((0.025, 0.025, 0.95, 0.95)) + + rng = np.random.default_rng() + + for i in range(24): + index = rng.integers(0, len(eqs)) + eq = eqs[index] + size = np.random.uniform(12, 32) + x, y = np.random.uniform(0, 1, 2) + alpha = np.random.uniform(0.25, 0.75) + plt.text( + x, + y, + eq, + ha="center", + va="center", + color="#11557c", + alpha=alpha, + transform=plt.gca().transAxes, + fontsize=size, + clip_on=True, + ) + plt.xticks([]) + plt.yticks([]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.730 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_text.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_text.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_text.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_text.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/plot_ugly.rst.txt b/_sources/intro/matplotlib/auto_examples/plot_ugly.rst.txt new file mode 100644 index 000000000..b3a01d484 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/plot_ugly.rst.txt @@ -0,0 +1,92 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/plot_ugly.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_plot_ugly.py: + + +A example of plotting not quite right +====================================== + +An "ugly" example of plotting. + +.. GENERATED FROM PYTHON SOURCE LINES 7-28 + + + +.. image-sg:: /intro/matplotlib/auto_examples/images/sphx_glr_plot_ugly_001.png + :alt: plot ugly + :srcset: /intro/matplotlib/auto_examples/images/sphx_glr_plot_ugly_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + matplotlib.rc("grid", color="black", linestyle="-", linewidth=1) + + fig = plt.figure(figsize=(5, 4), dpi=72) + axes = fig.add_axes((0.01, 0.01, 0.98, 0.98), facecolor=".75") + X = np.linspace(0, 2, 40) + Y = np.sin(2 * np.pi * X) + plt.plot(X, Y, lw=0.05, c="b", antialiased=False) + + plt.xticks([]) + plt.yticks(np.arange(-1.0, 1.0, 0.2)) + plt.grid() + ax = plt.gca() + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.036 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_plot_ugly.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_ugly.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_ugly.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_ugly.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/pretty_plots/index.rst.txt b/_sources/intro/matplotlib/auto_examples/pretty_plots/index.rst.txt new file mode 100644 index 000000000..f2dfddf7d --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/pretty_plots/index.rst.txt @@ -0,0 +1,261 @@ + + +.. _sphx_glr_intro_matplotlib_auto_examples_pretty_plots: + + +Code generating the summary figures with a title +------------------------------------------------- + + + +.. raw:: html + +
+ +.. thumbnail-parent-div-open + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_plot3d_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_plot3d_ext.py` + +.. raw:: html + +
3D plotting vignette
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_polar_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_polar_ext.py` + +.. raw:: html + +
Plotting in polar, decorated
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_plot_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_plot_ext.py` + +.. raw:: html + +
Plot example vignette
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_multiplot_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_multiplot_ext.py` + +.. raw:: html + +
Multiple plots vignette
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_boxplot_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_boxplot_ext.py` + +.. raw:: html + +
Boxplot with matplotlib
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_scatter_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_scatter_ext.py` + +.. raw:: html + +
Plot scatter decorated
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_pie_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_pie_ext.py` + +.. raw:: html + +
Pie chart vignette
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_imshow_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_imshow_ext.py` + +.. raw:: html + +
Imshow demo
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_bar_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_bar_ext.py` + +.. raw:: html + +
Bar plot advanced
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_quiver_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_quiver_ext.py` + +.. raw:: html + +
Plotting quiver decorated
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_contour_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_contour_ext.py` + +.. raw:: html + +
Display the contours of a function
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_grid_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_grid_ext.py` + +.. raw:: html + +
Grid elaborate
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/matplotlib/auto_examples/pretty_plots/images/thumb/sphx_glr_plot_text_ext_thumb.png + :alt: + + :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_text_ext.py` + +.. raw:: html + +
Text printing decorated
+
+ + +.. thumbnail-parent-div-close + +.. raw:: html + +
+ + +.. toctree:: + :hidden: + + /intro/matplotlib/auto_examples/pretty_plots/plot_plot3d_ext + /intro/matplotlib/auto_examples/pretty_plots/plot_polar_ext + /intro/matplotlib/auto_examples/pretty_plots/plot_plot_ext + /intro/matplotlib/auto_examples/pretty_plots/plot_multiplot_ext + /intro/matplotlib/auto_examples/pretty_plots/plot_boxplot_ext + /intro/matplotlib/auto_examples/pretty_plots/plot_scatter_ext + /intro/matplotlib/auto_examples/pretty_plots/plot_pie_ext + /intro/matplotlib/auto_examples/pretty_plots/plot_imshow_ext + /intro/matplotlib/auto_examples/pretty_plots/plot_bar_ext + /intro/matplotlib/auto_examples/pretty_plots/plot_quiver_ext + /intro/matplotlib/auto_examples/pretty_plots/plot_contour_ext + /intro/matplotlib/auto_examples/pretty_plots/plot_grid_ext + /intro/matplotlib/auto_examples/pretty_plots/plot_text_ext + diff --git a/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_bar_ext.rst.txt b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_bar_ext.rst.txt new file mode 100644 index 000000000..92da8142f --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_bar_ext.rst.txt @@ -0,0 +1,126 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/pretty_plots/plot_bar_ext.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_bar_ext.py: + + +Bar plot advanced +================== + +An more elaborate bar plot example + +.. GENERATED FROM PYTHON SOURCE LINES 7-62 + + + +.. image-sg:: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_bar_ext_001.png + :alt: plot bar ext + :srcset: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_bar_ext_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + n = 16 + X = np.arange(n) + Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n) + Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n) + plt.bar(X, Y1, facecolor="#9999ff", edgecolor="white") + plt.bar(X, -Y2, facecolor="#ff9999", edgecolor="white") + plt.xlim(-0.5, n) + plt.xticks([]) + plt.ylim(-1, 1) + plt.yticks([]) + + + # Add a title and a box around it + from matplotlib.patches import FancyBboxPatch + + ax = plt.gca() + ax.add_patch( + FancyBboxPatch( + (-0.05, 0.87), + width=0.66, + height=0.165, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) + ) + + plt.text( + -0.05, + 1.02, + " Bar Plot: plt.bar(...)\n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=plt.gca().transAxes, + ) + + plt.text( + -0.05, + 1.01, + "\n\n Make a bar plot with rectangles ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=plt.gca().transAxes, + ) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.051 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_pretty_plots_plot_bar_ext.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_bar_ext.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_bar_ext.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_bar_ext.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_boxplot_ext.rst.txt b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_boxplot_ext.rst.txt new file mode 100644 index 000000000..16cecf8b4 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_boxplot_ext.rst.txt @@ -0,0 +1,129 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/pretty_plots/plot_boxplot_ext.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_boxplot_ext.py: + + +Boxplot with matplotlib +======================= + +An example of doing box plots with matplotlib + +.. GENERATED FROM PYTHON SOURCE LINES 8-66 + + + +.. image-sg:: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_boxplot_ext_001.png + :alt: plot boxplot ext + :srcset: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_boxplot_ext_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + + fig = plt.figure(figsize=(8, 5)) + axes = plt.subplot(111) + + n = 5 + Z = np.zeros((n, 4)) + X = np.linspace(0, 2, n) + rng = np.random.default_rng() + Y = rng.random((n, 4)) + plt.boxplot(Y) + + plt.xticks([]) + plt.yticks([]) + + + # Add a title and a box around it + from matplotlib.patches import FancyBboxPatch + + ax = plt.gca() + ax.add_patch( + FancyBboxPatch( + (-0.05, 0.87), + width=0.66, + height=0.165, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) + ) + + plt.text( + -0.05, + 1.02, + " Box Plot: plt.boxplot(...)\n ", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=axes.transAxes, + ) + + plt.text( + -0.04, + 0.98, + "\n Make a box and whisker plot ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=axes.transAxes, + ) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.044 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_pretty_plots_plot_boxplot_ext.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_boxplot_ext.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_boxplot_ext.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_boxplot_ext.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_contour_ext.rst.txt b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_contour_ext.rst.txt new file mode 100644 index 000000000..29053264d --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_contour_ext.rst.txt @@ -0,0 +1,143 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/pretty_plots/plot_contour_ext.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_contour_ext.py: + + +Display the contours of a function +=================================== + +An example demoing how to plot the contours of a function, with +additional layout tweaks. + +.. GENERATED FROM PYTHON SOURCE LINES 9-69 + + + +.. image-sg:: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_contour_ext_001.png + :alt: plot contour ext + :srcset: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_contour_ext_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + /home/runner/work/scientific-python-lectures/scientific-python-lectures/intro/matplotlib/examples/pretty_plots/plot_contour_ext.py:24: UserWarning: The following kwargs were not used by contour: 'linewidth' + C = plt.contour(X, Y, f(X, Y), 8, colors="black", linewidth=0.5) + + + + + + +| + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + + def f(x, y): + return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2) + + + n = 256 + x = np.linspace(-3, 3, n) + y = np.linspace(-3, 3, n) + X, Y = np.meshgrid(x, y) + + plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap="hot") + C = plt.contour(X, Y, f(X, Y), 8, colors="black", linewidth=0.5) + plt.clabel(C, inline=1, fontsize=10) + plt.xticks([]) + plt.yticks([]) + + + # Add a title and a box around it + from matplotlib.patches import FancyBboxPatch + + ax = plt.gca() + ax.add_patch( + FancyBboxPatch( + (-0.05, 0.87), + width=0.66, + height=0.165, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) + ) + + plt.text( + -0.05, + 1.02, + " Contour Plot: plt.contour(..)\n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=plt.gca().transAxes, + ) + + plt.text( + -0.05, + 1.01, + "\n\n Draw contour lines and filled contours ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=plt.gca().transAxes, + ) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.080 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_pretty_plots_plot_contour_ext.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_contour_ext.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_contour_ext.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_contour_ext.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_grid_ext.rst.txt b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_grid_ext.rst.txt new file mode 100644 index 000000000..e4aacaa89 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_grid_ext.rst.txt @@ -0,0 +1,139 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/pretty_plots/plot_grid_ext.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_grid_ext.py: + + +Grid elaborate +=============== + +An example displaying a grid on the axes and tweaking the layout. + +.. GENERATED FROM PYTHON SOURCE LINES 7-65 + + + +.. image-sg:: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_grid_ext_001.png + :alt: plot grid ext + :srcset: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_grid_ext_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + Text(-0.05, 1.01, '\n\n Draw ticks and grid ') + + + + + +| + +.. code-block:: Python + + + import matplotlib.pyplot as plt + from matplotlib.ticker import MultipleLocator + + fig = plt.figure(figsize=(8, 6), dpi=72, facecolor="white") + axes = plt.subplot(111) + axes.set_xlim(0, 4) + axes.set_ylim(0, 3) + + axes.xaxis.set_major_locator(MultipleLocator(1.0)) + axes.xaxis.set_minor_locator(MultipleLocator(0.1)) + axes.yaxis.set_major_locator(MultipleLocator(1.0)) + axes.yaxis.set_minor_locator(MultipleLocator(0.1)) + axes.grid(which="major", axis="x", linewidth=0.75, linestyle="-", color="0.75") + axes.grid(which="minor", axis="x", linewidth=0.25, linestyle="-", color="0.75") + axes.grid(which="major", axis="y", linewidth=0.75, linestyle="-", color="0.75") + axes.grid(which="minor", axis="y", linewidth=0.25, linestyle="-", color="0.75") + axes.set_xticklabels([]) + axes.set_yticklabels([]) + + + # Add a title and a box around it + from matplotlib.patches import FancyBboxPatch + + ax = plt.gca() + ax.add_patch( + FancyBboxPatch( + (-0.05, 0.87), + width=0.66, + height=0.165, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) + ) + + plt.text( + -0.05, + 1.02, + " Grid: plt.grid(...)\n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=axes.transAxes, + ) + + plt.text( + -0.05, + 1.01, + "\n\n Draw ticks and grid ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=axes.transAxes, + ) + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.107 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_pretty_plots_plot_grid_ext.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_grid_ext.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_grid_ext.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_grid_ext.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_imshow_ext.rst.txt b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_imshow_ext.rst.txt new file mode 100644 index 000000000..a48238086 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_imshow_ext.rst.txt @@ -0,0 +1,130 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/pretty_plots/plot_imshow_ext.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_imshow_ext.py: + + +Imshow demo +============ + +Demoing imshow + +.. GENERATED FROM PYTHON SOURCE LINES 7-66 + + + +.. image-sg:: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_imshow_ext_001.png + :alt: plot imshow ext + :srcset: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_imshow_ext_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + + def f(x, y): + return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2) + + + n = 10 + x = np.linspace(-3, 3, 8 * n) + y = np.linspace(-3, 3, 6 * n) + X, Y = np.meshgrid(x, y) + Z = f(X, Y) + plt.imshow(Z, interpolation="nearest", cmap="bone", origin="lower") + plt.xticks([]) + plt.yticks([]) + + + # Add a title and a box around it + from matplotlib.patches import FancyBboxPatch + + ax = plt.gca() + ax.add_patch( + FancyBboxPatch( + (-0.05, 0.87), + width=0.66, + height=0.165, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) + ) + + plt.text( + -0.05, + 1.02, + " Imshow: plt.imshow(...)\n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=plt.gca().transAxes, + ) + + plt.text( + -0.05, + 1.01, + "\n\n Display an image to current axes ", + horizontalalignment="left", + verticalalignment="top", + family="DejaVu Sans", + size="large", + transform=plt.gca().transAxes, + ) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.040 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_pretty_plots_plot_imshow_ext.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_imshow_ext.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_imshow_ext.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_imshow_ext.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_multiplot_ext.rst.txt b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_multiplot_ext.rst.txt new file mode 100644 index 000000000..b2f71273a --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_multiplot_ext.rst.txt @@ -0,0 +1,125 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/pretty_plots/plot_multiplot_ext.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_multiplot_ext.py: + + +Multiple plots vignette +======================== + +Demo multiple plots and style the figure. + +.. GENERATED FROM PYTHON SOURCE LINES 7-61 + + + +.. image-sg:: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_multiplot_ext_001.png + :alt: plot multiplot ext + :srcset: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_multiplot_ext_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import matplotlib.pyplot as plt + + ax = plt.subplot(2, 1, 1) + ax.set_xticklabels([]) + ax.set_yticklabels([]) + + + # Add a title and a box around it + from matplotlib.patches import FancyBboxPatch + + ax = plt.gca() + ax.add_patch( + FancyBboxPatch( + (-0.05, 0.72), + width=0.66, + height=0.34, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) + ) + + plt.text( + -0.05, + 1.02, + " Multiplot: plt.subplot(...)\n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=ax.transAxes, + ) + plt.text( + -0.05, + 1.01, + "\n\n Plot several plots at once ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=ax.transAxes, + ) + + ax = plt.subplot(2, 2, 3) + ax.set_xticklabels([]) + ax.set_yticklabels([]) + + ax = plt.subplot(2, 2, 4) + ax.set_xticklabels([]) + ax.set_yticklabels([]) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.081 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_pretty_plots_plot_multiplot_ext.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_multiplot_ext.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_multiplot_ext.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_multiplot_ext.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_pie_ext.rst.txt b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_pie_ext.rst.txt new file mode 100644 index 000000000..1b4ee5a91 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_pie_ext.rst.txt @@ -0,0 +1,129 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/pretty_plots/plot_pie_ext.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_pie_ext.py: + + +Pie chart vignette +=================== + +Demo pie chart with matplotlib and style the figure. + +.. GENERATED FROM PYTHON SOURCE LINES 7-65 + + + +.. image-sg:: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_pie_ext_001.png + :alt: plot pie ext + :srcset: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_pie_ext_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + n = 20 + X = np.ones(n) + X[-1] *= 2 + plt.pie(X, explode=X * 0.05, colors=[f"{i / float(n):f}" for i in range(n)]) + + fig = plt.gcf() + w, h = fig.get_figwidth(), fig.get_figheight() + r = h / float(w) + + plt.xlim(-1.5, 1.5) + plt.ylim(-1.5 * r, 1.5 * r) + plt.xticks([]) + plt.yticks([]) + + + # Add a title and a box around it + from matplotlib.patches import FancyBboxPatch + + ax = plt.gca() + ax.add_patch( + FancyBboxPatch( + (-0.05, 0.87), + width=0.66, + height=0.165, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) + ) + + plt.text( + -0.05, + 1.02, + " Pie Chart: plt.pie(...)\n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=plt.gca().transAxes, + ) + + plt.text( + -0.05, + 1.01, + "\n\n Make a pie chart of an array ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=plt.gca().transAxes, + ) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.058 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_pretty_plots_plot_pie_ext.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_pie_ext.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_pie_ext.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_pie_ext.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_plot3d_ext.rst.txt b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_plot3d_ext.rst.txt new file mode 100644 index 000000000..7588f4c06 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_plot3d_ext.rst.txt @@ -0,0 +1,113 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/pretty_plots/plot_plot3d_ext.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_plot3d_ext.py: + + +3D plotting vignette +===================== + +Demo 3D plotting with matplotlib and decorate the figure. + +.. GENERATED FROM PYTHON SOURCE LINES 7-49 + + + +.. image-sg:: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_plot3d_ext_001.png + :alt: plot plot3d ext + :srcset: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_plot3d_ext_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + from mpl_toolkits.mplot3d import Axes3D + + fig = plt.figure() + ax = Axes3D(fig) + X = np.arange(-4, 4, 0.25) + Y = np.arange(-4, 4, 0.25) + X, Y = np.meshgrid(X, Y) + R = np.sqrt(X**2 + Y**2) + Z = np.sin(R) + + ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap="hot") + ax.contourf(X, Y, Z, zdir="z", offset=-2, cmap="hot") + ax.set_zlim(-2, 2) + plt.xticks([]) + plt.yticks([]) + ax.set_zticks([]) + + ax.text2D( + 0.05, + 0.93, + " 3D plots \n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + bbox={"facecolor": "white", "alpha": 1.0}, + transform=plt.gca().transAxes, + ) + + ax.text2D( + 0.05, + 0.87, + " Plot 2D or 3D data", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=plt.gca().transAxes, + ) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.038 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_pretty_plots_plot_plot3d_ext.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_plot3d_ext.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_plot3d_ext.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_plot3d_ext.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_plot_ext.rst.txt b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_plot_ext.rst.txt new file mode 100644 index 000000000..8e8952458 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_plot_ext.rst.txt @@ -0,0 +1,125 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/pretty_plots/plot_plot_ext.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_plot_ext.py: + + +Plot example vignette +======================= + +An example of plots with matplotlib, and added annotations. + +.. GENERATED FROM PYTHON SOURCE LINES 7-61 + + + +.. image-sg:: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_plot_ext_001.png + :alt: plot plot ext + :srcset: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_plot_ext_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + n = 256 + X = np.linspace(0, 2, n) + Y = np.sin(2 * np.pi * X) + + plt.plot(X, Y, lw=2, color="violet") + plt.xlim(-0.2, 2.2) + plt.xticks([]) + plt.ylim(-1.2, 1.2) + plt.yticks([]) + + + # Add a title and a box around it + from matplotlib.patches import FancyBboxPatch + + ax = plt.gca() + ax.add_patch( + FancyBboxPatch( + (-0.05, 0.87), + width=0.66, + height=0.165, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) + ) + + plt.text( + -0.05, + 1.02, + " Regular Plot: plt.plot(...)\n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=plt.gca().transAxes, + ) + + plt.text( + -0.05, + 1.01, + "\n\n Plot lines and/or markers ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=plt.gca().transAxes, + ) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.031 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_pretty_plots_plot_plot_ext.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_plot_ext.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_plot_ext.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_plot_ext.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_polar_ext.rst.txt b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_polar_ext.rst.txt new file mode 100644 index 000000000..ad410fcac --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_polar_ext.rst.txt @@ -0,0 +1,118 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/pretty_plots/plot_polar_ext.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_polar_ext.py: + + +Plotting in polar, decorated +============================= + +An example showing how to plot in polar coordinate, and some +decorations. + +.. GENERATED FROM PYTHON SOURCE LINES 8-54 + + + +.. image-sg:: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_polar_ext_001.png + :alt: plot polar ext + :srcset: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_polar_ext_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + + import matplotlib + import matplotlib.pyplot as plt + + + plt.subplot(1, 1, 1, polar=True) + + N = 20 + theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N) + rng = np.random.default_rng() + radii = 10 * rng.random(N) + width = np.pi / 4 * rng.random(N) + bars = plt.bar(theta, radii, width=width, bottom=0.0) + jet = matplotlib.colormaps["jet"] + + for r, bar in zip(radii, bars, strict=True): + bar.set_facecolor(jet(r / 10.0)) + bar.set_alpha(0.5) + plt.gca().set_xticklabels([]) + plt.gca().set_yticklabels([]) + + + plt.text( + -0.2, + 1.02, + " Polar Axis \n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + bbox={"facecolor": "white", "alpha": 1.0}, + transform=plt.gca().transAxes, + ) + + plt.text( + -0.2, + 1.01, + "\n\n Plot anything using polar axis ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=plt.gca().transAxes, + ) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.110 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_pretty_plots_plot_polar_ext.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_polar_ext.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_polar_ext.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_polar_ext.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_quiver_ext.rst.txt b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_quiver_ext.rst.txt new file mode 100644 index 000000000..94999b6e5 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_quiver_ext.rst.txt @@ -0,0 +1,130 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/pretty_plots/plot_quiver_ext.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_quiver_ext.py: + + +Plotting quiver decorated +========================== + +An example showing quiver with decorations. + +.. GENERATED FROM PYTHON SOURCE LINES 7-66 + + + +.. image-sg:: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_quiver_ext_001.png + :alt: plot quiver ext + :srcset: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_quiver_ext_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + n = 8 + X, Y = np.mgrid[0:n, 0:n] + T = np.arctan2(Y - n / 2.0, X - n / 2.0) + R = 10 + np.sqrt((Y - n / 2.0) ** 2 + (X - n / 2.0) ** 2) + U, V = R * np.cos(T), R * np.sin(T) + + plt.quiver(X, Y, U, V, R, alpha=0.5) + plt.quiver(X, Y, U, V, edgecolor="k", facecolor="None", linewidth=0.5) + + plt.xlim(-1, n) + plt.xticks([]) + plt.ylim(-1, n) + plt.yticks([]) + + + # Add a title and a box around it + from matplotlib.patches import FancyBboxPatch + + ax = plt.gca() + ax.add_patch( + FancyBboxPatch( + (-0.05, 0.87), + width=0.66, + height=0.165, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) + ) + + plt.text( + -0.05, + 1.02, + " Quiver Plot: plt.quiver(...)\n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=plt.gca().transAxes, + ) + + plt.text( + -0.05, + 1.01, + "\n\n Plot a 2-D field of arrows ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=plt.gca().transAxes, + ) + + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.051 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_pretty_plots_plot_quiver_ext.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_quiver_ext.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_quiver_ext.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_quiver_ext.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_scatter_ext.rst.txt b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_scatter_ext.rst.txt new file mode 100644 index 000000000..fd575bf43 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_scatter_ext.rst.txt @@ -0,0 +1,128 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/pretty_plots/plot_scatter_ext.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_scatter_ext.py: + + +Plot scatter decorated +======================= + +An example showing the scatter function, with decorations. + +.. GENERATED FROM PYTHON SOURCE LINES 7-64 + + + +.. image-sg:: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_scatter_ext_001.png + :alt: plot scatter ext + :srcset: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_scatter_ext_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + n = 1024 + rng = np.random.default_rng() + X = rng.normal(0, 1, n) + Y = rng.normal(0, 1, n) + + T = np.arctan2(Y, X) + + plt.scatter(X, Y, s=75, c=T, alpha=0.5) + plt.xlim(-1.5, 1.5) + plt.xticks([]) + plt.ylim(-1.5, 1.5) + plt.yticks([]) + + + # Add a title and a box around it + from matplotlib.patches import FancyBboxPatch + + ax = plt.gca() + ax.add_patch( + FancyBboxPatch( + (-0.05, 0.87), + width=0.66, + height=0.165, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) + ) + + plt.text( + -0.05, + 1.02, + " Scatter Plot: plt.scatter(...)\n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=plt.gca().transAxes, + ) + + plt.text( + -0.05, + 1.01, + "\n\n Make a scatter plot of x versus y ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=plt.gca().transAxes, + ) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.062 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_pretty_plots_plot_scatter_ext.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_scatter_ext.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_scatter_ext.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_scatter_ext.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_text_ext.rst.txt b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_text_ext.rst.txt new file mode 100644 index 000000000..e78ffcb5c --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/pretty_plots/plot_text_ext.rst.txt @@ -0,0 +1,151 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/matplotlib/auto_examples/pretty_plots/plot_text_ext.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_text_ext.py: + + +Text printing decorated +======================= + +An example showing text printing and decorating the resulting figure. + +.. GENERATED FROM PYTHON SOURCE LINES 7-87 + + + +.. image-sg:: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_text_ext_001.png + :alt: plot text ext + :srcset: /intro/matplotlib/auto_examples/pretty_plots/images/sphx_glr_plot_text_ext_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + fig = plt.figure() + plt.xticks([]) + plt.yticks([]) + + eqs = [] + eqs.append( + r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$" + ) + eqs.append( + r"$\frac{d\rho}{d t} + \rho \vec{v}\cdot\nabla\vec{v} = -\nabla p + \mu\nabla^2 \vec{v} + \rho \vec{g}$" + ) + eqs.append(r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$") + eqs.append(r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$") + eqs.append(r"$F_G = G\frac{m_1m_2}{r^2}$") + + rng = np.random.default_rng() + + for i in range(24): + index = rng.integers(0, len(eqs)) + eq = eqs[index] + size = rng.uniform(12, 32) + x, y = rng.uniform(0, 1, 2) + alpha = rng.uniform(0.25, 0.75) + plt.text( + x, + y, + eq, + ha="center", + va="center", + color="#11557c", + alpha=alpha, + transform=plt.gca().transAxes, + fontsize=size, + clip_on=True, + ) + + + # Add a title and a box around it + from matplotlib.patches import FancyBboxPatch + + ax = plt.gca() + ax.add_patch( + FancyBboxPatch( + (-0.05, 0.87), + width=0.66, + height=0.165, + clip_on=False, + boxstyle="square,pad=0", + zorder=3, + facecolor="white", + alpha=1.0, + transform=plt.gca().transAxes, + ) + ) + + plt.text( + -0.05, + 1.02, + " Text: plt.text(...)\n", + horizontalalignment="left", + verticalalignment="top", + size="xx-large", + transform=plt.gca().transAxes, + ) + + plt.text( + -0.05, + 1.01, + "\n\n Draw any kind of text ", + horizontalalignment="left", + verticalalignment="top", + size="large", + transform=plt.gca().transAxes, + ) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.714 seconds) + + +.. _sphx_glr_download_intro_matplotlib_auto_examples_pretty_plots_plot_text_ext.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_text_ext.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_text_ext.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_text_ext.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/matplotlib/auto_examples/pretty_plots/sg_execution_times.rst.txt b/_sources/intro/matplotlib/auto_examples/pretty_plots/sg_execution_times.rst.txt new file mode 100644 index 000000000..b81b85d35 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/pretty_plots/sg_execution_times.rst.txt @@ -0,0 +1,73 @@ + +:orphan: + +.. _sphx_glr_intro_matplotlib_auto_examples_pretty_plots_sg_execution_times: + + +Computation times +================= +**00:01.467** total execution time for 13 files **from intro/matplotlib/auto_examples/pretty_plots**: + +.. container:: + + .. raw:: html + + + + + + + + .. list-table:: + :header-rows: 1 + :class: table table-striped sg-datatable + + * - Example + - Time + - Mem (MB) + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_text_ext.py` (``plot_text_ext.py``) + - 00:00.714 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_polar_ext.py` (``plot_polar_ext.py``) + - 00:00.110 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_grid_ext.py` (``plot_grid_ext.py``) + - 00:00.107 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_multiplot_ext.py` (``plot_multiplot_ext.py``) + - 00:00.081 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_contour_ext.py` (``plot_contour_ext.py``) + - 00:00.080 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_scatter_ext.py` (``plot_scatter_ext.py``) + - 00:00.062 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_pie_ext.py` (``plot_pie_ext.py``) + - 00:00.058 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_quiver_ext.py` (``plot_quiver_ext.py``) + - 00:00.051 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_bar_ext.py` (``plot_bar_ext.py``) + - 00:00.051 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_boxplot_ext.py` (``plot_boxplot_ext.py``) + - 00:00.044 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_imshow_ext.py` (``plot_imshow_ext.py``) + - 00:00.040 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_plot3d_ext.py` (``plot_plot3d_ext.py``) + - 00:00.038 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_plot_ext.py` (``plot_plot_ext.py``) + - 00:00.031 + - 0.0 diff --git a/_sources/intro/matplotlib/auto_examples/sg_execution_times.rst.txt b/_sources/intro/matplotlib/auto_examples/sg_execution_times.rst.txt new file mode 100644 index 000000000..a6f698519 --- /dev/null +++ b/_sources/intro/matplotlib/auto_examples/sg_execution_times.rst.txt @@ -0,0 +1,100 @@ + +:orphan: + +.. _sphx_glr_intro_matplotlib_auto_examples_sg_execution_times: + + +Computation times +================= +**00:02.112** total execution time for 22 files **from intro/matplotlib/auto_examples**: + +.. container:: + + .. raw:: html + + + + + + + + .. list-table:: + :header-rows: 1 + :class: table table-striped sg-datatable + + * - Example + - Time + - Mem (MB) + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_text.py` (``plot_text.py``) + - 00:00.730 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_imshow.py` (``plot_imshow.py``) + - 00:00.122 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_plot3d.py` (``plot_plot3d.py``) + - 00:00.106 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_grid.py` (``plot_grid.py``) + - 00:00.106 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_polar.py` (``plot_polar.py``) + - 00:00.096 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_bad.py` (``plot_bad.py``) + - 00:00.086 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_gridspec.py` (``plot_gridspec.py``) + - 00:00.086 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_contour.py` (``plot_contour.py``) + - 00:00.079 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_subplot-grid.py` (``plot_subplot-grid.py``) + - 00:00.072 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_scatter.py` (``plot_scatter.py``) + - 00:00.060 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_pie.py` (``plot_pie.py``) + - 00:00.059 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_axes-2.py` (``plot_axes-2.py``) + - 00:00.058 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_bar.py` (``plot_bar.py``) + - 00:00.056 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_good.py` (``plot_good.py``) + - 00:00.053 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_plot3d-2.py` (``plot_plot3d-2.py``) + - 00:00.053 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_subplot-horizontal.py` (``plot_subplot-horizontal.py``) + - 00:00.050 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_multiplot.py` (``plot_multiplot.py``) + - 00:00.049 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_axes.py` (``plot_axes.py``) + - 00:00.048 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_subplot-vertical.py` (``plot_subplot-vertical.py``) + - 00:00.041 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_ugly.py` (``plot_ugly.py``) + - 00:00.036 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_quiver.py` (``plot_quiver.py``) + - 00:00.034 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_plot.py` (``plot_plot.py``) + - 00:00.033 + - 0.0 diff --git a/_sources/intro/matplotlib/index.rst.txt b/_sources/intro/matplotlib/index.rst.txt new file mode 100644 index 000000000..57924ae8b --- /dev/null +++ b/_sources/intro/matplotlib/index.rst.txt @@ -0,0 +1,1262 @@ + +.. _matplotlib: + +.. currentmodule:: matplotlib.pyplot + +==================== +Matplotlib: plotting +==================== + +.. sidebar:: **Thanks** + + Many thanks to **Bill Wing** and **Christoph Deil** for review and + corrections. + +**Authors**: *Nicolas Rougier, Mike Müller, Gaël Varoquaux* + +.. contents:: Chapter contents + :local: + :depth: 1 + +Introduction +============ + +.. tip:: + + `Matplotlib `__ is probably the most + used Python package for 2D-graphics. It provides both a quick + way to visualize data from Python and publication-quality figures in + many formats. We are going to explore matplotlib in interactive mode + covering most common cases. + +IPython, Jupyter, and matplotlib modes +--------------------------------------- + +.. tip:: + + The `Jupyter `_ notebook and the + `IPython `_ enhanced interactive Python, are + tuned for the scientific-computing workflow in Python, + in combination with Matplotlib: + +For interactive matplotlib sessions, turn on the **matplotlib mode** + +:IPython console: + + When using the IPython console, use:: + + In [1]: %matplotlib + +:Jupyter notebook: + + In the notebook, insert, **at the beginning of the + notebook** the following `magic + `_:: + + %matplotlib inline + +pyplot +------ + +.. tip:: + + *pyplot* provides a procedural interface to the matplotlib object-oriented + plotting library. It is modeled closely after Matlab™. Therefore, the + majority of plotting commands in pyplot have Matlab™ analogs with similar + arguments. Important commands are explained with interactive examples. + +:: + + import matplotlib.pyplot as plt + +Simple plot +=========== + +.. tip:: + + In this section, we want to draw the cosine and sine functions on the same + plot. Starting from the default settings, we'll enrich the figure step by + step to make it nicer. + + First step is to get the data for the sine and cosine functions: + +:: + + import numpy as np + + X = np.linspace(-np.pi, np.pi, 256) + C, S = np.cos(X), np.sin(X) + + +``X`` is now a numpy array with 256 values ranging from :math:`-\pi` to :math:`+\pi` +(included). ``C`` is the cosine (256 values) and ``S`` is the sine (256 +values). + +To run the example, you can type them in an IPython interactive session:: + + $ ipython --matplotlib + +This brings us to the IPython prompt: :: + + IPython 0.13 -- An enhanced Interactive Python. + ? -> Introduction to IPython's features. + %magic -> Information about IPython's 'magic' % functions. + help -> Python's own help system. + object? -> Details about 'object'. ?object also works, ?? prints more. + +.. tip:: + + You can also download each of the examples and run it using regular + python, but you will lose interactive data manipulation:: + + $ python plot_exercise_1.py + + You can get source for each step by clicking on the corresponding figure. + + +Plotting with default settings +------------------------------- + +.. image:: auto_examples/exercises/images/sphx_glr_plot_exercise_1_001.png + :align: right + :scale: 35 + :target: auto_examples/exercises/plot_exercise_1.html + +.. hint:: Documentation + + * `plot tutorial `_ + * :func:`~plot()` command + +.. tip:: + + Matplotlib comes with a set of default settings that allow + customizing all kinds of properties. You can control the defaults of + almost every property in matplotlib: figure size and dpi, line width, + color and style, axes, axis and grid properties, text and font + properties and so on. + +|clear-floats| + +:: + + import numpy as np + import matplotlib.pyplot as plt + + X = np.linspace(-np.pi, np.pi, 256) + C, S = np.cos(X), np.sin(X) + + plt.plot(X, C) + plt.plot(X, S) + + plt.show() + + +Instantiating defaults +---------------------- + +.. image:: auto_examples/exercises/images/sphx_glr_plot_exercise_2_001.png + :align: right + :scale: 35 + :target: auto_examples/exercises/plot_exercise_2.html + +.. hint:: Documentation + + * `Customizing matplotlib `_ + +In the script below, we've instantiated (and commented) all the figure settings +that influence the appearance of the plot. + +.. tip:: + + The settings have been explicitly set to their default values, but + now you can interactively play with the values to explore their + affect (see `Line properties`_ and `Line styles`_ below). + +|clear-floats| + +:: + + import numpy as np + import matplotlib.pyplot as plt + + # Create a figure of size 8x6 inches, 80 dots per inch + plt.figure(figsize=(8, 6), dpi=80) + + # Create a new subplot from a grid of 1x1 + plt.subplot(1, 1, 1) + + X = np.linspace(-np.pi, np.pi, 256) + C, S = np.cos(X), np.sin(X) + + # Plot cosine with a blue continuous line of width 1 (pixels) + plt.plot(X, C, color="blue", linewidth=1.0, linestyle="-") + + # Plot sine with a green continuous line of width 1 (pixels) + plt.plot(X, S, color="green", linewidth=1.0, linestyle="-") + + # Set x limits + plt.xlim(-4.0, 4.0) + + # Set x ticks + plt.xticks(np.linspace(-4, 4, 9)) + + # Set y limits + plt.ylim(-1.0, 1.0) + + # Set y ticks + plt.yticks(np.linspace(-1, 1, 5)) + + # Save figure using 72 dots per inch + # plt.savefig("exercise_2.png", dpi=72) + + # Show result on screen + plt.show() + + +Changing colors and line widths +-------------------------------- + +.. image:: auto_examples/exercises/images/sphx_glr_plot_exercise_3_001.png + :align: right + :scale: 35 + :target: auto_examples/exercises/plot_exercise_3.html + +.. hint:: Documentation + + * `Controlling line properties `_ + * :class:`~matplotlib.lines.Line2D` API + +.. tip:: + + First step, we want to have the cosine in blue and the sine in red and a + slightly thicker line for both of them. We'll also slightly alter the figure + size to make it more horizontal. + +|clear-floats| + +:: + + ... + plt.figure(figsize=(10, 6), dpi=80) + plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") + plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") + ... + + +Setting limits +-------------- + +.. image:: auto_examples/exercises/images/sphx_glr_plot_exercise_4_001.png + :align: right + :scale: 35 + :target: auto_examples/exercises/plot_exercise_4.html + +.. hint:: Documentation + + * :func:`xlim()` command + * :func:`ylim()` command + +.. tip:: + + Current limits of the figure are a bit too tight and we want to make + some space in order to clearly see all data points. + +|clear-floats| + +:: + + ... + plt.xlim(X.min() * 1.1, X.max() * 1.1) + plt.ylim(C.min() * 1.1, C.max() * 1.1) + ... + + + +Setting ticks +------------- + +.. image:: auto_examples/exercises/images/sphx_glr_plot_exercise_5_001.png + :align: right + :scale: 35 + :target: auto_examples/exercises/plot_exercise_5.html + +.. hint:: Documentation + + * :func:`xticks()` command + * :func:`yticks()` command + * `Tick container `_ + * `Tick locating and formatting `_ + +.. tip:: + + Current ticks are not ideal because they do not show the interesting values + (:math:`\pm \pi`,:math:`\pm \pi`/2) for sine and cosine. We'll change them such that they show + only these values. + +|clear-floats| + +:: + + ... + plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi]) + plt.yticks([-1, 0, +1]) + ... + + + +Setting tick labels +------------------- + +.. image:: auto_examples/exercises/images/sphx_glr_plot_exercise_6_001.png + :align: right + :scale: 35 + :target: auto_examples/exercises/plot_exercise_6.html + + +.. hint:: Documentation + + * `Working with text `_ + * :func:`~xticks()` command + * :func:`~yticks()` command + * :meth:`~matplotlib.axes.Axes.set_xticklabels()` + * :meth:`~matplotlib.axes.Axes.set_yticklabels()` + + +.. tip:: + + Ticks are now properly placed but their label is not very explicit. + We could guess that 3.142 is :math:`\pi` but it would be better to make it + explicit. When we set tick values, we can also provide a + corresponding label in the second argument list. Note that we'll use + latex to allow for nice rendering of the label. + +|clear-floats| + +:: + + ... + plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], + [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) + + plt.yticks([-1, 0, +1], + [r'$-1$', r'$0$', r'$+1$']) + ... + + + +Moving spines +------------- + +.. image:: auto_examples/exercises/images/sphx_glr_plot_exercise_7_001.png + :align: right + :scale: 35 + :target: auto_examples/exercises/plot_exercise_7.html + + +.. hint:: Documentation + + * :mod:`~matplotlib.spines` API + * `Axis container `_ + * `Transformations tutorial `_ + +.. tip:: + + Spines are the lines connecting the axis tick marks and noting the + boundaries of the data area. They can be placed at arbitrary + positions and until now, they were on the border of the axis. We'll + change that since we want to have them in the middle. Since there are + four of them (top/bottom/left/right), we'll discard the top and right + by setting their color to none and we'll move the bottom and left + ones to coordinate 0 in data space coordinates. + +|clear-floats| + +:: + + ... + ax = plt.gca() # gca stands for 'get current axis' + ax.spines['right'].set_color('none') + ax.spines['top'].set_color('none') + ax.xaxis.set_ticks_position('bottom') + ax.spines['bottom'].set_position(('data',0)) + ax.yaxis.set_ticks_position('left') + ax.spines['left'].set_position(('data',0)) + ... + + + +Adding a legend +--------------- + +.. image:: auto_examples/exercises/images/sphx_glr_plot_exercise_8_001.png + :align: right + :scale: 35 + :target: auto_examples/exercises/plot_exercise_8.html + + +.. hint:: Documentation + + * `Legend guide `_ + * :func:`legend()` command + * :mod:`~matplotlib.legend` API + +.. tip:: + + Let's add a legend in the upper left corner. This only requires + adding the keyword argument label (that will be used in the legend + box) to the plot commands. + +|clear-floats| + +:: + + ... + plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine") + plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine") + + plt.legend(loc='upper left') + ... + + + +Annotate some points +-------------------- + +.. image:: auto_examples/exercises/images/sphx_glr_plot_exercise_9_001.png + :align: right + :scale: 35 + :target: auto_examples/exercises/plot_exercise_9.html + + +.. hint:: Documentation + + * `Annotating axis `_ + * :func:`annotate()` command + +.. tip:: + + Let's annotate some interesting points using the annotate command. We + chose the :math:`2\pi / 3` value and we want to annotate both the sine and the + cosine. We'll first draw a marker on the curve as well as a straight + dotted line. Then, we'll use the annotate command to display some + text with an arrow. + +|clear-floats| + +:: + + ... + + t = 2 * np.pi / 3 + plt.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5, linestyle="--") + plt.scatter([t, ], [np.cos(t), ], 50, color='blue') + + plt.annotate(r'$cos(\frac{2\pi}{3})=-\frac{1}{2}$', + xy=(t, np.cos(t)), xycoords='data', + xytext=(-90, -50), textcoords='offset points', fontsize=16, + arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) + + plt.plot([t, t],[0, np.sin(t)], color='red', linewidth=2.5, linestyle="--") + plt.scatter([t, ],[np.sin(t), ], 50, color='red') + + plt.annotate(r'$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$', + xy=(t, np.sin(t)), xycoords='data', + xytext=(+10, +30), textcoords='offset points', fontsize=16, + arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) + ... + + + +Devil is in the details +------------------------ + +.. image:: auto_examples/exercises/images/sphx_glr_plot_exercise_10_001.png + :align: right + :scale: 35 + :target: auto_examples/exercises/plot_exercise_10.html + +.. hint:: Documentation + + * :mod:`~matplotlib.artist` API + * :meth:`~matplotlib.text.Text.set_bbox()` method + +.. tip:: + + The tick labels are now hardly visible because of the blue and red + lines. We can make them bigger and we can also adjust their + properties such that they'll be rendered on a semi-transparent white + background. This will allow us to see both the data and the labels. + +|clear-floats| + +:: + + ... + for label in ax.get_xticklabels() + ax.get_yticklabels(): + label.set_fontsize(16) + label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65)) + ... + + + + +Figures, Subplots, Axes and Ticks +================================= + +A **"figure"** in matplotlib means the whole window in the user interface. +Within this figure there can be **"subplots"**. + +.. tip:: + + So far we have used implicit figure and axes creation. This is handy for + fast plots. We can have more control over the display using figure, + subplot, and axes explicitly. While subplot positions the plots in a + regular grid, axes allows free placement within the figure. Both can be + useful depending on your intention. We've already worked with figures and + subplots without explicitly calling them. When we call plot, matplotlib + calls :func:`gca` to get the current axes and gca in turn calls :func:`gcf` to + get the current figure. If there is none it calls :func:`figure` to make one, + strictly speaking, to make a ``subplot(111)``. Let's look at the details. + +Figures +------- + +.. tip:: + + A figure is the windows in the GUI that has "Figure #" as title. Figures + are numbered starting from 1 as opposed to the normal Python way starting + from 0. This is clearly MATLAB-style. There are several parameters that + determine what the figure looks like: + +============== ======================= ============================================ +Argument Default Description +============== ======================= ============================================ +``num`` ``1`` number of figure +``figsize`` ``figure.figsize`` figure size in inches (width, height) +``dpi`` ``figure.dpi`` resolution in dots per inch +``facecolor`` ``figure.facecolor`` color of the drawing background +``edgecolor`` ``figure.edgecolor`` color of edge around the drawing background +``frameon`` ``True`` draw figure frame or not +============== ======================= ============================================ + +.. tip:: + + The defaults can be specified in the resource file and will be used most of + the time. Only the number of the figure is frequently changed. + + As with other objects, you can set figure properties also setp or with the + set_something methods. + + When you work with the GUI you can close a figure by clicking on the x in + the upper right corner. But you can close a figure programmatically by + calling close. Depending on the argument it closes (1) the current figure + (no argument), (2) a specific figure (figure number or figure instance as + argument), or (3) all figures (``"all"`` as argument). + +:: + + plt.close(1) # Closes figure 1 + + +Subplots +-------- + +.. tip:: + + With subplot you can arrange plots in a regular grid. You need to specify + the number of rows and columns and the number of the plot. Note that the + `gridspec `_ command + is a more powerful alternative. + +.. avoid an ugly interplay between 'tip' and the images below: we want a + line-return + +|clear-floats| + +.. image:: auto_examples/images/sphx_glr_plot_subplot-horizontal_001.png + :scale: 25 + :target: auto_examples/plot_subplot-horizontal.html +.. image:: auto_examples/images/sphx_glr_plot_subplot-vertical_001.png + :scale: 25 + :target: auto_examples/plot_subplot-vertical.html +.. image:: auto_examples/images/sphx_glr_plot_subplot-grid_001.png + :scale: 25 + :target: auto_examples/plot_subplot-grid.html +.. image:: auto_examples/images/sphx_glr_plot_gridspec_001.png + :scale: 25 + :target: auto_examples/plot_gridspec.html + + +Axes +---- + +Axes are very similar to subplots but allow placement of plots at any location +in the figure. So if we want to put a smaller plot inside a bigger one we do +so with axes. + +.. image:: auto_examples/images/sphx_glr_plot_axes_001.png + :scale: 35 + :target: auto_examples/plot_axes.html +.. image:: auto_examples/images/sphx_glr_plot_axes-2_001.png + :scale: 35 + :target: auto_examples/plot_axes-2.html + + +Ticks +----- + +Well formatted ticks are an important part of publishing-ready +figures. Matplotlib provides a totally configurable system for ticks. There are +tick locators to specify where ticks should appear and tick formatters to give +ticks the appearance you want. Major and minor ticks can be located and +formatted independently from each other. Per default minor ticks are not shown, +i.e. there is only an empty list for them because it is as ``NullLocator`` (see +below). + +Tick Locators +............. + +Tick locators control the positions of the ticks. They are set as +follows:: + + ax = plt.gca() + ax.xaxis.set_major_locator(eval(locator)) + +There are several locators for different kind of requirements: + +.. raw:: latex + + ~ + +.. image:: auto_examples/options/images/sphx_glr_plot_ticks_001.png + :scale: 60 + :target: auto_examples/options/plot_ticks.html + +.. raw:: latex + + ~ + +All of these locators derive from the base class :class:`matplotlib.ticker.Locator`. +You can make your own locator deriving from it. Handling dates as ticks can be +especially tricky. Therefore, matplotlib provides special locators in +matplotlib.dates. + + +Other Types of Plots: examples and exercises +============================================= + +.. image:: auto_examples/pretty_plots/images/sphx_glr_plot_plot_ext_001.png + :scale: 39 + :target: `Regular Plots`_ +.. image:: auto_examples/pretty_plots/images/sphx_glr_plot_scatter_ext_001.png + :scale: 39 + :target: `Scatter Plots`_ +.. image:: auto_examples/pretty_plots/images/sphx_glr_plot_bar_ext_001.png + :scale: 39 + :target: `Bar Plots`_ +.. image:: auto_examples/pretty_plots/images/sphx_glr_plot_contour_ext_001.png + :scale: 39 + :target: `Contour Plots`_ +.. image:: auto_examples/pretty_plots/images/sphx_glr_plot_imshow_ext_001.png + :scale: 39 + :target: `Imshow`_ +.. image:: auto_examples/pretty_plots/images/sphx_glr_plot_quiver_ext_001.png + :scale: 39 + :target: `Quiver Plots`_ +.. image:: auto_examples/pretty_plots/images/sphx_glr_plot_pie_ext_001.png + :scale: 39 + :target: `Pie Charts`_ +.. image:: auto_examples/pretty_plots/images/sphx_glr_plot_grid_ext_001.png + :scale: 39 + :target: `Grids`_ +.. image:: auto_examples/pretty_plots/images/sphx_glr_plot_multiplot_ext_001.png + :scale: 39 + :target: `Multi Plots`_ +.. image:: auto_examples/pretty_plots/images/sphx_glr_plot_polar_ext_001.png + :scale: 39 + :target: `Polar Axis`_ +.. image:: auto_examples/pretty_plots/images/sphx_glr_plot_plot3d_ext_001.png + :scale: 39 + :target: `3D Plots`_ +.. image:: auto_examples/pretty_plots/images/sphx_glr_plot_text_ext_001.png + :scale: 39 + :target: `Text`_ + + +Regular Plots +------------- + +.. image:: auto_examples/images/sphx_glr_plot_plot_001.png + :align: right + :scale: 35 + :target: auto_examples/plot_plot.html + +Starting from the code below, try to reproduce the graphic taking +care of filled areas: + +.. hint:: + + You need to use the :func:`fill_between()` command. + + +:: + + n = 256 + X = np.linspace(-np.pi, np.pi, n) + Y = np.sin(2 * X) + + plt.plot(X, Y + 1, color='blue', alpha=1.00) + plt.plot(X, Y - 1, color='blue', alpha=1.00) + +Click on the figure for solution. + + +Scatter Plots +------------- + +.. image:: auto_examples/images/sphx_glr_plot_scatter_001.png + :align: right + :scale: 35 + :target: auto_examples/plot_scatter.html + +Starting from the code below, try to reproduce the graphic taking +care of marker size, color and transparency. + +.. hint:: + + Color is given by angle of (X,Y). + + +:: + + n = 1024 + rng = np.random.default_rng() + X = rng.normal(0,1,n) + Y = rng.normal(0,1,n) + + plt.scatter(X,Y) + +Click on figure for solution. + + +Bar Plots +--------- + +.. image:: auto_examples/images/sphx_glr_plot_bar_001.png + :align: right + :scale: 35 + :target: auto_examples/plot_bar.html + +Starting from the code below, try to reproduce the graphic by +adding labels for red bars. + +.. hint:: + + You need to take care of text alignment. + +|clear-floats| + +:: + + n = 12 + X = np.arange(n) + rng = np.random.default_rng() + Y1 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n) + Y2 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n) + + plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white') + plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white') + + for x, y in zip(X, Y1): + plt.text(x + 0.4, y + 0.05, '%.2f' % y, ha='center', va='bottom') + + plt.ylim(-1.25, +1.25) + +Click on figure for solution. + + +Contour Plots +------------- + +.. image:: auto_examples/images/sphx_glr_plot_contour_001.png + :align: right + :scale: 35 + :target: auto_examples/plot_contour.html + + +Starting from the code below, try to reproduce the graphic taking +care of the colormap (see `Colormaps`_ below). + +.. hint:: + + You need to use the :func:`clabel()` command. + +:: + + def f(x, y): + return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 -y ** 2) + + n = 256 + x = np.linspace(-3, 3, n) + y = np.linspace(-3, 3, n) + X, Y = np.meshgrid(x, y) + + plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap='jet') + C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5) + +Click on figure for solution. + + + +Imshow +------ + +.. image:: auto_examples/images/sphx_glr_plot_imshow_001.png + :align: right + :scale: 35 + :target: auto_examples/plot_imshow.html + + +Starting from the code below, try to reproduce the graphic taking +care of colormap, image interpolation and origin. + +.. hint:: + + You need to take care of the ``origin`` of the image in the imshow command and + use a :func:`colorbar()` + + +:: + + def f(x, y): + return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) + + n = 10 + x = np.linspace(-3, 3, 4 * n) + y = np.linspace(-3, 3, 3 * n) + X, Y = np.meshgrid(x, y) + plt.imshow(f(X, Y)) + +Click on the figure for the solution. + + +Pie Charts +---------- + +.. image:: auto_examples/images/sphx_glr_plot_pie_001.png + :align: right + :scale: 35 + :target: auto_examples/plot_pie.html + + +Starting from the code below, try to reproduce the graphic taking +care of colors and slices size. + +.. hint:: + + You need to modify Z. + +:: + + rng = np.random.default_rng() + Z = rng.uniform(0, 1, 20) + plt.pie(Z) + +Click on the figure for the solution. + + + +Quiver Plots +------------ + +.. image:: auto_examples/images/sphx_glr_plot_quiver_001.png + :align: right + :scale: 35 + :target: auto_examples/plot_quiver.html + + +Starting from the code below, try to reproduce the graphic taking +care of colors and orientations. + +.. hint:: + + You need to draw arrows twice. + +:: + + n = 8 + X, Y = np.mgrid[0:n, 0:n] + plt.quiver(X, Y) + +Click on figure for solution. + + +Grids +----- + +.. image:: auto_examples/images/sphx_glr_plot_grid_001.png + :align: right + :scale: 35 + :target: auto_examples/plot_grid.html + + +Starting from the code below, try to reproduce the graphic taking +care of line styles. + +:: + + axes = plt.gca() + axes.set_xlim(0, 4) + axes.set_ylim(0, 3) + axes.set_xticklabels([]) + axes.set_yticklabels([]) + + +Click on figure for solution. + + +Multi Plots +----------- + +.. image:: auto_examples/images/sphx_glr_plot_multiplot_001.png + :align: right + :scale: 35 + :target: auto_examples/plot_multiplot.html + +Starting from the code below, try to reproduce the graphic. + +.. hint:: + + You can use several subplots with different partition. + + +:: + + plt.subplot(2, 2, 1) + plt.subplot(2, 2, 3) + plt.subplot(2, 2, 4) + +Click on figure for solution. + + +Polar Axis +---------- + +.. image:: auto_examples/images/sphx_glr_plot_polar_001.png + :align: right + :scale: 35 + :target: auto_examples/plot_polar.html + + +.. hint:: + + You only need to modify the ``axes`` line + +Starting from the code below, try to reproduce the graphic. + + +:: + + plt.axes([0, 0, 1, 1]) + + N = 20 + theta = np.arange(0., 2 * np.pi, 2 * np.pi / N) + rng = np.random.default_rng() + radii = 10 * rng.random(N) + width = np.pi / 4 * rng.random(N) + bars = plt.bar(theta, radii, width=width, bottom=0.0) + + for r, bar in zip(radii, bars): + bar.set_facecolor(plt.cm.jet(r / 10.)) + bar.set_alpha(0.5) + +Click on figure for solution. + + +3D Plots +-------- + +.. image:: auto_examples/images/sphx_glr_plot_plot3d_001.png + :align: right + :scale: 35 + :target: auto_examples/plot_plot3d.html + +Starting from the code below, try to reproduce the graphic. + +.. hint:: + + You need to use :func:`contourf()` + + +:: + + from mpl_toolkits.mplot3d import Axes3D + + fig = plt.figure() + ax = Axes3D(fig) + X = np.arange(-4, 4, 0.25) + Y = np.arange(-4, 4, 0.25) + X, Y = np.meshgrid(X, Y) + R = np.sqrt(X**2 + Y**2) + Z = np.sin(R) + + ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot') + +Click on figure for solution. + +Text +---- + + +.. image:: auto_examples/images/sphx_glr_plot_text_001.png + :align: right + :scale: 35 + :target: auto_examples/plot_text.html + + +Try to do the same from scratch ! + +.. hint:: + + Have a look at the `matplotlib logo + `_. + + +Click on figure for solution. + +| + +____ + +| + +.. topic:: **Quick read** + + If you want to do a first quick pass through the Scientific Python Lectures + to learn the ecosystem, you can directly skip to the next chapter: + :ref:`scipy`. + + The remainder of this chapter is not necessary to follow the rest of + the intro part. But be sure to come back and finish this chapter later. + +Beyond this tutorial +==================== + +Matplotlib benefits from extensive documentation as well as a large +community of users and developers. Here are some links of interest: + +Tutorials +--------- + +.. hlist:: + + * `Pyplot tutorial `_ + + - Introduction + - Controlling line properties + - Working with multiple figures and axes + - Working with text + + * `Image tutorial `_ + + - Startup commands + - Importing image data into NumPy arrays + - Plotting NumPy arrays as images + + * `Text tutorial `_ + + - Text introduction + - Basic text commands + - Text properties and layout + - Writing mathematical expressions + - Text rendering With LaTeX + - Annotating text + + * `Artist tutorial `_ + + - Introduction + - Customizing your objects + - Object containers + - Figure container + - Axes container + - Axis containers + - Tick containers + + * `Path tutorial `_ + + - Introduction + - Bézier example + - Compound paths + + * `Transforms tutorial `_ + + - Introduction + - Data coordinates + - Axes coordinates + - Blended transformations + - Using offset transforms to create a shadow effect + - The transformation pipeline + + + +Matplotlib documentation +------------------------ + +.. hlist:: + + * `User guide `_ + + * `FAQ `_ + + - Installation + - Usage + - How-To + - Troubleshooting + - Environment Variables + + * `Screenshots `_ + + +Code documentation +------------------ + +The code is well documented and you can quickly access a specific command +from within a python session: + +:: + + >>> import matplotlib.pyplot as plt + >>> help(plt.plot) + Help on function plot in module matplotlib.pyplot: + + plot(*args: ...) -> 'list[Line2D]' + Plot y versus x as lines and/or markers. + + Call signatures:: + + plot([x], y, [fmt], *, data=None, **kwargs) + plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs) + ... + + +Galleries +--------- + +The `matplotlib gallery `_ is +also incredibly useful when you search how to render a given graphic. Each +example comes with its source. + + +Mailing lists +-------------- + +Finally, there is a `user mailing list +`_ where you can +ask for help and a `developers mailing list +`_ that is more +technical. + + +Quick references +================ + +Here is a set of tables that show main properties and styles. + +Line properties +---------------- + +.. list-table:: + :widths: 20 30 50 + :header-rows: 1 + + * - Property + - Description + - Appearance + + * - alpha (or a) + - alpha transparency on 0-1 scale + - .. image:: auto_examples/options/images/sphx_glr_plot_alpha_001.png + + * - antialiased + - True or False - use antialised rendering + - .. image:: auto_examples/options/images/sphx_glr_plot_aliased_001.png + .. image:: auto_examples/options/images/sphx_glr_plot_antialiased_001.png + + * - color (or c) + - matplotlib color arg + - .. image:: auto_examples/options/images/sphx_glr_plot_color_001.png + + * - linestyle (or ls) + - see `Line properties`_ + - + + * - linewidth (or lw) + - float, the line width in points + - .. image:: auto_examples/options/images/sphx_glr_plot_linewidth_001.png + + * - solid_capstyle + - Cap style for solid lines + - .. image:: auto_examples/options/images/sphx_glr_plot_solid_capstyle_001.png + + * - solid_joinstyle + - Join style for solid lines + - .. image:: auto_examples/options/images/sphx_glr_plot_solid_joinstyle_001.png + + * - dash_capstyle + - Cap style for dashes + - .. image:: auto_examples/options/images/sphx_glr_plot_dash_capstyle_001.png + + * - dash_joinstyle + - Join style for dashes + - .. image:: auto_examples/options/images/sphx_glr_plot_dash_joinstyle_001.png + + * - marker + - see `Markers`_ + - + + * - markeredgewidth (mew) + - line width around the marker symbol + - .. image:: auto_examples/options/images/sphx_glr_plot_mew_001.png + + * - markeredgecolor (mec) + - edge color if a marker is used + - .. image:: auto_examples/options/images/sphx_glr_plot_mec_001.png + + * - markerfacecolor (mfc) + - face color if a marker is used + - .. image:: auto_examples/options/images/sphx_glr_plot_mfc_001.png + + * - markersize (ms) + - size of the marker in points + - .. image:: auto_examples/options/images/sphx_glr_plot_ms_001.png + + + +Line styles +----------- + +.. image:: auto_examples/options/images/sphx_glr_plot_linestyles_001.png + +Markers +------- + +.. image:: auto_examples/options/images/sphx_glr_plot_markers_001.png + :scale: 90 + +Colormaps +--------- + +All colormaps can be reversed by appending ``_r``. For instance, ``gray_r`` is +the reverse of ``gray``. + +If you want to know more about colormaps, check the `documentation on Colormaps in matplotlib `_. + +.. image:: auto_examples/options/images/sphx_glr_plot_colormaps_001.png + :scale: 80 + + +Full code examples +================== + +.. include:: auto_examples/index.rst + :start-line: 1 diff --git a/_sources/intro/numpy/advanced_operations.rst.txt b/_sources/intro/numpy/advanced_operations.rst.txt new file mode 100644 index 000000000..3263a94eb --- /dev/null +++ b/_sources/intro/numpy/advanced_operations.rst.txt @@ -0,0 +1,220 @@ +.. For doctests + >>> import numpy as np + >>> # For doctest on headless environments + >>> import matplotlib + >>> matplotlib.use('Agg') + >>> import matplotlib.pyplot as plt + + + +.. currentmodule:: numpy + +Advanced operations +=================== + +.. contents:: Section contents + :local: + :depth: 1 + +Polynomials +----------- + +NumPy also contains polynomials in different bases: + +For example, :math:`3x^2 + 2x - 1`:: + + >>> p = np.poly1d([3, 2, -1]) + >>> p(0) + np.int64(-1) + >>> p.roots + array([-1. , 0.33333333]) + >>> p.order + 2 + +:: + + >>> x = np.linspace(0, 1, 20) + >>> rng = np.random.default_rng() + >>> y = np.cos(x) + 0.3*rng.random(20) + >>> p = np.poly1d(np.polyfit(x, y, 3)) + + >>> t = np.linspace(0, 1, 200) # use a larger number of points for smoother plotting + >>> plt.plot(x, y, 'o', t, p(t), '-') + [, ] + +.. image:: auto_examples/images/sphx_glr_plot_polyfit_001.png + :width: 50% + :target: auto_examples/plot_polyfit.html + :align: center + +See https://numpy.org/doc/stable/reference/routines.polynomials.poly1d.html +for more. + +More polynomials (with more bases) +................................... + +NumPy also has a more sophisticated polynomial interface, which supports +e.g. the Chebyshev basis. + +:math:`3x^2 + 2x - 1`:: + + >>> p = np.polynomial.Polynomial([-1, 2, 3]) # coefs in different order! + >>> p(0) + np.float64(-1.0) + >>> p.roots() + array([-1. , 0.33333333]) + >>> p.degree() # In general polynomials do not always expose 'order' + 2 + +Example using polynomials in Chebyshev basis, for polynomials in +range ``[-1, 1]``:: + + >>> x = np.linspace(-1, 1, 2000) + >>> rng = np.random.default_rng() + >>> y = np.cos(x) + 0.3*rng.random(2000) + >>> p = np.polynomial.Chebyshev.fit(x, y, 90) + + >>> plt.plot(x, y, 'r.') + [] + >>> plt.plot(x, p(x), 'k-', lw=3) + [] + +.. image:: auto_examples/images/sphx_glr_plot_chebyfit_001.png + :width: 50% + :target: auto_examples/plot_chebyfit.html + :align: center + +The Chebyshev polynomials have some advantages in interpolation. + +Loading data files +------------------- + +Text files +........... + +Example: :download:`populations.txt <../../data/populations.txt>`: + +.. include:: ../../data/populations.txt + :end-line: 5 + :literal: + +:: + + >>> data = np.loadtxt('data/populations.txt') + >>> data + array([[ 1900., 30000., 4000., 48300.], + [ 1901., 47200., 6100., 48200.], + [ 1902., 70200., 9800., 41500.], + ... + +:: + + >>> np.savetxt('pop2.txt', data) + >>> data2 = np.loadtxt('pop2.txt') + +.. note:: If you have a complicated text file, what you can try are: + + - ``np.genfromtxt`` + + - Using Python's I/O functions and e.g. regexps for parsing + (Python is quite well suited for this) + +.. topic:: Reminder: Navigating the filesystem with IPython + + .. ipython:: + + In [1]: pwd # show current directory + '/home/user/stuff/2011-numpy-tutorial' + In [2]: cd ex + '/home/user/stuff/2011-numpy-tutorial/ex' + In [3]: ls + populations.txt species.txt + +Images +....... + +Using Matplotlib:: + + >>> img = plt.imread('data/elephant.png') + >>> img.shape, img.dtype + ((200, 300, 3), dtype('float32')) + >>> plt.imshow(img) + + >>> plt.savefig('plot.png') + + >>> plt.imsave('red_elephant.png', img[:,:,0], cmap=plt.cm.gray) + +.. image:: auto_examples/images/sphx_glr_plot_elephant_001.png + :width: 50% + :target: auto_examples/plot_elephant.html + :align: center + +This saved only one channel (of RGB):: + + >>> plt.imshow(plt.imread('red_elephant.png')) + + +.. image:: auto_examples/images/sphx_glr_plot_elephant_002.png + :width: 50% + :target: auto_examples/plot_elephant.html + :align: center + +Other libraries:: + + >>> import imageio.v3 as iio + >>> iio.imwrite('tiny_elephant.png', (img[::6,::6] * 255).astype(np.uint8)) + >>> plt.imshow(plt.imread('tiny_elephant.png'), interpolation='nearest') + + +.. image:: auto_examples/images/sphx_glr_plot_elephant_003.png + :width: 50% + :target: auto_examples/plot_elephant.html + :align: center + + +NumPy's own format +................... + +NumPy has its own binary format, not portable but with efficient I/O:: + + >>> data = np.ones((3, 3)) + >>> np.save('pop.npy', data) + >>> data3 = np.load('pop.npy') + +Well-known (& more obscure) file formats +......................................... + +* HDF5: `h5py `__, `PyTables `__ +* NetCDF: ``scipy.io.netcdf_file``, `netcdf4-python `__, ... +* Matlab: ``scipy.io.loadmat``, ``scipy.io.savemat`` +* MatrixMarket: ``scipy.io.mmread``, ``scipy.io.mmwrite`` +* IDL: ``scipy.io.readsav`` + +... if somebody uses it, there's probably also a Python library for it. + + +.. topic:: Exercise: Text data files + :class: green + + Write a Python script that loads data from :download:`populations.txt + <../../data/populations.txt>`:: and drop the last column and the first + 5 rows. Save the smaller dataset to ``pop2.txt``. + + +.. loadtxt, savez, load, fromfile, tofile + +.. real life: point to HDF5, NetCDF, etc. + +.. EXE: use loadtxt to load a data file +.. EXE: use savez and load to save data in binary format +.. EXE: use tofile and fromfile to put and get binary data bytes in/from a file + follow-up: .view() +.. EXE: parsing text files -- Python can do this reasonably well natively! + throw in the mix some random text file to be parsed (eg. PPM) +.. EXE: advanced: read the data in a PPM file + + +.. topic:: NumPy internals + + If you are interested in the NumPy internals, there is a good discussion in + :ref:`advanced_numpy`. diff --git a/_sources/intro/numpy/array_object.rst.txt b/_sources/intro/numpy/array_object.rst.txt new file mode 100644 index 000000000..b9cdafabd --- /dev/null +++ b/_sources/intro/numpy/array_object.rst.txt @@ -0,0 +1,814 @@ +.. + >>> import numpy as np + >>> import matplotlib.pyplot as plt + + +.. currentmodule:: numpy + +The NumPy array object +====================== + +.. contents:: Section contents + :local: + :depth: 1 + +What are NumPy and NumPy arrays? +-------------------------------- + +NumPy arrays +............ + +:**Python** objects: + + - high-level number objects: integers, floating point + + - containers: lists (costless insertion and append), dictionaries + (fast lookup) + +:**NumPy** provides: + + - extension package to Python for multi-dimensional arrays + + - closer to hardware (efficiency) + + - designed for scientific computation (convenience) + + - Also known as *array oriented computing* + +| + +.. sourcecode:: pycon + + >>> import numpy as np + >>> a = np.array([0, 1, 2, 3]) + >>> a + array([0, 1, 2, 3]) + +.. tip:: + + For example, An array containing: + + * values of an experiment/simulation at discrete time steps + + * signal recorded by a measurement device, e.g. sound wave + + * pixels of an image, grey-level or colour + + * 3-D data measured at different X-Y-Z positions, e.g. MRI scan + + * ... + +**Why it is useful:** Memory-efficient container that provides fast numerical +operations. + +.. ipython:: + + In [1]: L = range(1000) + + In [2]: %timeit [i**2 for i in L] + 1000 loops, best of 3: 403 us per loop + + In [3]: a = np.arange(1000) + + In [4]: %timeit a**2 + 100000 loops, best of 3: 12.7 us per loop + + +.. extension package to Python to support multidimensional arrays + +.. diagram, import conventions + +.. scope of this tutorial: drill in features of array manipulation in + Python, and try to give some indication on how to get things done + in good style + +.. a fixed number of elements (cf. certain exceptions) +.. each element of same size and type +.. efficiency vs. Python lists + +NumPy Reference documentation +.............................. + +- On the web: https://numpy.org/doc/ + +- Interactive help: + + .. ipython:: + + In [5]: np.array? + String Form: + Docstring: + array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0, ... + + .. tip:: + + .. sourcecode:: pycon + + >>> help(np.array) + Help on built-in function array in module numpy: + + array(...) + array(object, dtype=None, ... + + +- Looking for something: + + .. ipython:: + + In [6]: np.con*? + np.concatenate + np.conj + np.conjugate + np.convolve + +Import conventions +.................. + +The recommended convention to import NumPy is: + +.. sourcecode:: pycon + + >>> import numpy as np + + +Creating arrays +--------------- + +Manual construction of arrays +.............................. + +* **1-D**: + + .. sourcecode:: pycon + + >>> a = np.array([0, 1, 2, 3]) + >>> a + array([0, 1, 2, 3]) + >>> a.ndim + 1 + >>> a.shape + (4,) + >>> len(a) + 4 + +* **2-D, 3-D, ...**: + + .. sourcecode:: pycon + + >>> b = np.array([[0, 1, 2], [3, 4, 5]]) # 2 x 3 array + >>> b + array([[0, 1, 2], + [3, 4, 5]]) + >>> b.ndim + 2 + >>> b.shape + (2, 3) + >>> len(b) # returns the size of the first dimension + 2 + + >>> c = np.array([[[1], [2]], [[3], [4]]]) + >>> c + array([[[1], + [2]], + + [[3], + [4]]]) + >>> c.shape + (2, 2, 1) + +.. topic:: **Exercise: Simple arrays** + :class: green + + * Create a simple two dimensional array. First, redo the examples + from above. And then create your own: how about odd numbers + counting backwards on the first row, and even numbers on the second? + * Use the functions :func:`len`, :func:`numpy.shape` on these arrays. + How do they relate to each other? And to the ``ndim`` attribute of + the arrays? + +Functions for creating arrays +.............................. + +.. tip:: + + In practice, we rarely enter items one by one... + +* Evenly spaced: + + .. sourcecode:: pycon + + >>> a = np.arange(10) # 0 .. n-1 (!) + >>> a + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + >>> b = np.arange(1, 9, 2) # start, end (exclusive), step + >>> b + array([1, 3, 5, 7]) + +* or by number of points: + + .. sourcecode:: pycon + + >>> c = np.linspace(0, 1, 6) # start, end, num-points + >>> c + array([0. , 0.2, 0.4, 0.6, 0.8, 1. ]) + >>> d = np.linspace(0, 1, 5, endpoint=False) + >>> d + array([0. , 0.2, 0.4, 0.6, 0.8]) + +* Common arrays: + + .. sourcecode:: pycon + + >>> a = np.ones((3, 3)) # reminder: (3, 3) is a tuple + >>> a + array([[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]]) + >>> b = np.zeros((2, 2)) + >>> b + array([[0., 0.], + [0., 0.]]) + >>> c = np.eye(3) + >>> c + array([[1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.]]) + >>> d = np.diag(np.array([1, 2, 3, 4])) + >>> d + array([[1, 0, 0, 0], + [0, 2, 0, 0], + [0, 0, 3, 0], + [0, 0, 0, 4]]) + +* :mod:`np.random`: random numbers (Mersenne Twister PRNG): + + .. sourcecode:: pycon + + >>> rng = np.random.default_rng(27446968) + >>> a = rng.random(4) # uniform in [0, 1] + >>> a + array([0.64613018, 0.48984931, 0.50851229, 0.22563948]) + + >>> b = rng.standard_normal(4) # Gaussian + >>> b + array([-0.38250769, -0.61536465, 0.98131732, 0.59353096]) + +.. topic:: **Exercise: Creating arrays using functions** + :class: green + + * Experiment with ``arange``, ``linspace``, ``ones``, ``zeros``, ``eye`` and + ``diag``. + * Create different kinds of arrays with random numbers. + * Try setting the seed before creating an array with random values. + * Look at the function ``np.empty``. What does it do? When might this be + useful? + +.. EXE: construct 1 2 3 4 5 +.. EXE: construct -5, -4, -3, -2, -1 +.. EXE: construct 2 4 6 8 +.. EXE: look what is in an empty() array +.. EXE: construct 15 equispaced numbers in range [0, 10] + +Basic data types +---------------- + +You may have noticed that, in some instances, array elements are displayed with +a trailing dot (e.g. ``2.`` vs ``2``). This is due to a difference in the +data-type used: + +.. sourcecode:: pycon + + >>> a = np.array([1, 2, 3]) + >>> a.dtype + dtype('int64') + + >>> b = np.array([1., 2., 3.]) + >>> b.dtype + dtype('float64') + +.. tip:: + + Different data-types allow us to store data more compactly in memory, + but most of the time we simply work with floating point numbers. + Note that, in the example above, NumPy auto-detects the data-type + from the input. + +----------------------------- + +You can explicitly specify which data-type you want: + +.. sourcecode:: pycon + + >>> c = np.array([1, 2, 3], dtype=float) + >>> c.dtype + dtype('float64') + + +The **default** data type is floating point: + +.. sourcecode:: pycon + + >>> a = np.ones((3, 3)) + >>> a.dtype + dtype('float64') + +There are also other types: + +:Complex: + + .. sourcecode:: pycon + + >>> d = np.array([1+2j, 3+4j, 5+6*1j]) + >>> d.dtype + dtype('complex128') + +:Bool: + + .. sourcecode:: pycon + + >>> e = np.array([True, False, False, True]) + >>> e.dtype + dtype('bool') + +:Strings: + + .. sourcecode:: pycon + + >>> f = np.array(['Bonjour', 'Hello', 'Hallo']) + >>> f.dtype # <--- strings containing max. 7 letters + dtype('>> %matplotlib # doctest: +SKIP + +Or, from the notebook, enable plots in the notebook: + +.. sourcecode:: pycon + + >>> %matplotlib inline # doctest: +SKIP + +The ``inline`` is important for the notebook, so that plots are displayed in +the notebook and not in a new window. + +*Matplotlib* is a 2D plotting package. We can import its functions as below: + +.. sourcecode:: pycon + + >>> import matplotlib.pyplot as plt # the tidy way + +And then use (note that you have to use ``show`` explicitly if you have not enabled interactive plots with ``%matplotlib``): + +.. sourcecode:: pycon + + >>> plt.plot(x, y) # line plot # doctest: +SKIP + >>> plt.show() # <-- shows the plot (not needed with interactive plots) # doctest: +SKIP + +Or, if you have enabled interactive plots with ``%matplotlib``: + +.. sourcecode:: pycon + + >>> plt.plot(x, y) # line plot # doctest: +SKIP + +* **1D plotting**: + +.. sourcecode:: pycon + + >>> x = np.linspace(0, 3, 20) + >>> y = np.linspace(0, 9, 20) + >>> plt.plot(x, y) # line plot + [] + >>> plt.plot(x, y, 'o') # dot plot + [] + +.. image:: auto_examples/images/sphx_glr_plot_basic1dplot_001.png + :width: 40% + :target: auto_examples/plot_basic1dplot.html + :align: center + +* **2D arrays** (such as images): + +.. sourcecode:: pycon + + >>> rng = np.random.default_rng(27446968) + >>> image = rng.random((30, 30)) + >>> plt.imshow(image, cmap=plt.cm.hot) + + >>> plt.colorbar() + + +.. image:: auto_examples/images/sphx_glr_plot_basic2dplot_001.png + :width: 50% + :target: auto_examples/plot_basic2dplot.html + :align: center + +.. seealso:: More in the: :ref:`matplotlib chapter ` + +.. topic:: **Exercise: Simple visualizations** + :class: green + + * Plot some simple arrays: a cosine as a function of time and a 2D + matrix. + * Try using the ``gray`` colormap on the 2D matrix. + + +Indexing and slicing +-------------------- + +The items of an array can be accessed and assigned to the same way as +other Python sequences (e.g. lists): + +.. sourcecode:: pycon + + >>> a = np.arange(10) + >>> a + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + >>> a[0], a[2], a[-1] + (np.int64(0), np.int64(2), np.int64(9)) + +.. warning:: + + Indices begin at 0, like other Python sequences (and C/C++). + In contrast, in Fortran or Matlab, indices begin at 1. + +The usual python idiom for reversing a sequence is supported: + +.. sourcecode:: pycon + + >>> a[::-1] + array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) + +For multidimensional arrays, indices are tuples of integers: + +.. sourcecode:: pycon + + >>> a = np.diag(np.arange(3)) + >>> a + array([[0, 0, 0], + [0, 1, 0], + [0, 0, 2]]) + >>> a[1, 1] + np.int64(1) + >>> a[2, 1] = 10 # third line, second column + >>> a + array([[ 0, 0, 0], + [ 0, 1, 0], + [ 0, 10, 2]]) + >>> a[1] + array([0, 1, 0]) + + +.. note:: + + * In 2D, the first dimension corresponds to **rows**, the second + to **columns**. + * for multidimensional ``a``, ``a[0]`` is interpreted by + taking all elements in the unspecified dimensions. + +**Slicing**: Arrays, like other Python sequences can also be sliced: + +.. sourcecode:: pycon + + >>> a = np.arange(10) + >>> a + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + >>> a[2:9:3] # [start:end:step] + array([2, 5, 8]) + +Note that the last index is not included! : + +.. sourcecode:: pycon + + >>> a[:4] + array([0, 1, 2, 3]) + +All three slice components are not required: by default, `start` is 0, +`end` is the last and `step` is 1: + +.. sourcecode:: pycon + + >>> a[1:3] + array([1, 2]) + >>> a[::2] + array([0, 2, 4, 6, 8]) + >>> a[3:] + array([3, 4, 5, 6, 7, 8, 9]) + +A small illustrated summary of NumPy indexing and slicing... + +.. only:: latex + + .. image:: ../../pyximages/numpy_indexing.pdf + :align: center + +.. only:: html + + .. image:: ../../pyximages/numpy_indexing.png + :align: center + :width: 70% + +You can also combine assignment and slicing: + +.. sourcecode:: pycon + + >>> a = np.arange(10) + >>> a[5:] = 10 + >>> a + array([ 0, 1, 2, 3, 4, 10, 10, 10, 10, 10]) + >>> b = np.arange(5) + >>> a[5:] = b[::-1] + >>> a + array([0, 1, 2, 3, 4, 4, 3, 2, 1, 0]) + +.. topic:: **Exercise: Indexing and slicing** + :class: green + + * Try the different flavours of slicing, using ``start``, ``end`` and + ``step``: starting from a linspace, try to obtain odd numbers + counting backwards, and even numbers counting forwards. + * Reproduce the slices in the diagram above. You may + use the following expression to create the array: + + .. sourcecode:: pycon + + >>> np.arange(6) + np.arange(0, 51, 10)[:, np.newaxis] + array([[ 0, 1, 2, 3, 4, 5], + [10, 11, 12, 13, 14, 15], + [20, 21, 22, 23, 24, 25], + [30, 31, 32, 33, 34, 35], + [40, 41, 42, 43, 44, 45], + [50, 51, 52, 53, 54, 55]]) + +.. topic:: **Exercise: Array creation** + :class: green + + Create the following arrays (with correct data types):: + + [[1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 2], + [1, 6, 1, 1]] + + [[0., 0., 0., 0., 0.], + [2., 0., 0., 0., 0.], + [0., 3., 0., 0., 0.], + [0., 0., 4., 0., 0.], + [0., 0., 0., 5., 0.], + [0., 0., 0., 0., 6.]] + + Par on course: 3 statements for each + + *Hint*: Individual array elements can be accessed similarly to a list, + e.g. ``a[1]`` or ``a[1, 2]``. + + *Hint*: Examine the docstring for ``diag``. + +.. topic:: Exercise: Tiling for array creation + :class: green + + Skim through the documentation for ``np.tile``, and use this function + to construct the array:: + + [[4, 3, 4, 3, 4, 3], + [2, 1, 2, 1, 2, 1], + [4, 3, 4, 3, 4, 3], + [2, 1, 2, 1, 2, 1]] + +Copies and views +---------------- + +A slicing operation creates a **view** on the original array, which is +just a way of accessing array data. Thus the original array is not +copied in memory. You can use ``np.may_share_memory()`` to check if two arrays +share the same memory block. Note however, that this uses heuristics and may +give you false positives. + +**When modifying the view, the original array is modified as well**: + +.. sourcecode:: pycon + + >>> a = np.arange(10) + >>> a + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + >>> b = a[::2] + >>> b + array([0, 2, 4, 6, 8]) + >>> np.may_share_memory(a, b) + True + >>> b[0] = 12 + >>> b + array([12, 2, 4, 6, 8]) + >>> a # (!) + array([12, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + + >>> a = np.arange(10) + >>> c = a[::2].copy() # force a copy + >>> c[0] = 12 + >>> a + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + + >>> np.may_share_memory(a, c) + False + + + +This behavior can be surprising at first sight... but it allows to save both +memory and time. + + +.. EXE: [1, 2, 3, 4, 5] -> [1, 2, 3] +.. EXE: [1, 2, 3, 4, 5] -> [4, 5] +.. EXE: [1, 2, 3, 4, 5] -> [1, 3, 5] +.. EXE: [1, 2, 3, 4, 5] -> [2, 4] +.. EXE: create an array [1, 1, 1, 1, 0, 0, 0] +.. EXE: create an array [0, 0, 0, 0, 1, 1, 1] +.. EXE: create an array [0, 1, 0, 1, 0, 1, 0] +.. EXE: create an array [1, 0, 1, 0, 1, 0, 1] +.. EXE: create an array [1, 0, 2, 0, 3, 0, 4] +.. CHA: archimedean sieve + +.. topic:: Worked example: Prime number sieve + :class: green + + .. image:: images/prime-sieve.png + + Compute prime numbers in 0--99, with a sieve + + * Construct a shape (100,) boolean array ``is_prime``, + filled with True in the beginning: + + .. sourcecode:: pycon + + >>> is_prime = np.ones((100,), dtype=bool) + + * Cross out 0 and 1 which are not primes: + + .. sourcecode:: pycon + + >>> is_prime[:2] = 0 + + * For each integer ``j`` starting from 2, cross out its higher multiples: + + .. sourcecode:: pycon + + >>> N_max = int(np.sqrt(len(is_prime) - 1)) + >>> for j in range(2, N_max + 1): + ... is_prime[2*j::j] = False + + * Skim through ``help(np.nonzero)``, and print the prime numbers + + * Follow-up: + + - Move the above code into a script file named ``prime_sieve.py`` + + - Run it to check it works + + - Use the optimization suggested in `the sieve of Eratosthenes + `_: + + 1. Skip ``j`` which are already known to not be primes + + 2. The first number to cross out is :math:`j^2` + +Fancy indexing +-------------- + +.. tip:: + + NumPy arrays can be indexed with slices, but also with boolean or + integer arrays (**masks**). This method is called *fancy indexing*. + It creates **copies not views**. + +Using boolean masks +................... + +.. sourcecode:: pycon + + >>> rng = np.random.default_rng(27446968) + >>> a = rng.integers(0, 21, 15) + >>> a + array([ 3, 13, 12, 10, 10, 10, 18, 4, 8, 5, 6, 11, 12, 17, 3]) + >>> (a % 3 == 0) + array([ True, False, True, False, False, False, True, False, False, + False, True, False, True, False, True]) + >>> mask = (a % 3 == 0) + >>> extract_from_a = a[mask] # or, a[a%3==0] + >>> extract_from_a # extract a sub-array with the mask + array([ 3, 12, 18, 6, 12, 3]) + +Indexing with a mask can be very useful to assign a new value to a sub-array: + +.. sourcecode:: pycon + + >>> a[a % 3 == 0] = -1 + >>> a + array([-1, 13, -1, 10, 10, 10, -1, 4, 8, 5, -1, 11, -1, 17, -1]) + + +Indexing with an array of integers +.................................. + +.. sourcecode:: pycon + + >>> a = np.arange(0, 100, 10) + >>> a + array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90]) + +Indexing can be done with an array of integers, where the same index is repeated +several time: + +.. sourcecode:: pycon + + >>> a[[2, 3, 2, 4, 2]] # note: [2, 3, 2, 4, 2] is a Python list + array([20, 30, 20, 40, 20]) + +New values can be assigned with this kind of indexing: + +.. sourcecode:: pycon + + >>> a[[9, 7]] = -100 + >>> a + array([ 0, 10, 20, 30, 40, 50, 60, -100, 80, -100]) + +.. tip:: + + When a new array is created by indexing with an array of integers, the + new array has the same shape as the array of integers: + + .. sourcecode:: pycon + + >>> a = np.arange(10) + >>> idx = np.array([[3, 4], [9, 7]]) + >>> idx.shape + (2, 2) + >>> a[idx] + array([[3, 4], + [9, 7]]) + + +____ + +The image below illustrates various fancy indexing applications + +.. only:: latex + + .. image:: ../../pyximages/numpy_fancy_indexing.pdf + :align: center + +.. only:: html + + .. image:: ../../pyximages/numpy_fancy_indexing.png + :align: center + :width: 80% + +.. topic:: **Exercise: Fancy indexing** + :class: green + + * Again, reproduce the fancy indexing shown in the diagram above. + * Use fancy indexing on the left and array creation on the right to assign + values into an array, for instance by setting parts of the array in + the diagram above to zero. + +.. We can even use fancy indexing and :ref:`broadcasting ` at +.. the same time: +.. +.. .. sourcecode:: pycon +.. +.. >>> a = np.arange(12).reshape(3,4) +.. >>> a +.. array([[ 0, 1, 2, 3], +.. [ 4, 5, 6, 7], +.. [ 8, 9, 10, 11]]) +.. >>> i = np.array([[0, 1], [1, 2]]) +.. >>> a[i, 2] # same as a[i, 2*np.ones((2, 2), dtype=int)] +.. array([[ 2, 6], +.. [ 6, 10]]) diff --git a/_sources/intro/numpy/auto_examples/index.rst.txt b/_sources/intro/numpy/auto_examples/index.rst.txt new file mode 100644 index 000000000..62359cb7f --- /dev/null +++ b/_sources/intro/numpy/auto_examples/index.rst.txt @@ -0,0 +1,205 @@ +:orphan: + +Full code examples for the numpy chapter +---------------------------------------- + + + +.. raw:: html + +
+ +.. thumbnail-parent-div-open + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/numpy/auto_examples/images/thumb/sphx_glr_plot_basic1dplot_thumb.png + :alt: + + :ref:`sphx_glr_intro_numpy_auto_examples_plot_basic1dplot.py` + +.. raw:: html + +
1D plotting
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/numpy/auto_examples/images/thumb/sphx_glr_plot_basic2dplot_thumb.png + :alt: + + :ref:`sphx_glr_intro_numpy_auto_examples_plot_basic2dplot.py` + +.. raw:: html + +
2D plotting
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/numpy/auto_examples/images/thumb/sphx_glr_plot_distances_thumb.png + :alt: + + :ref:`sphx_glr_intro_numpy_auto_examples_plot_distances.py` + +.. raw:: html + +
Distances exercise
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/numpy/auto_examples/images/thumb/sphx_glr_plot_polyfit_thumb.png + :alt: + + :ref:`sphx_glr_intro_numpy_auto_examples_plot_polyfit.py` + +.. raw:: html + +
Fitting to polynomial
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/numpy/auto_examples/images/thumb/sphx_glr_plot_chebyfit_thumb.png + :alt: + + :ref:`sphx_glr_intro_numpy_auto_examples_plot_chebyfit.py` + +.. raw:: html + +
Fitting in Chebyshev basis
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/numpy/auto_examples/images/thumb/sphx_glr_plot_populations_thumb.png + :alt: + + :ref:`sphx_glr_intro_numpy_auto_examples_plot_populations.py` + +.. raw:: html + +
Population exercise
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/numpy/auto_examples/images/thumb/sphx_glr_plot_elephant_thumb.png + :alt: + + :ref:`sphx_glr_intro_numpy_auto_examples_plot_elephant.py` + +.. raw:: html + +
Reading and writing an elephant
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/numpy/auto_examples/images/thumb/sphx_glr_plot_mandelbrot_thumb.png + :alt: + + :ref:`sphx_glr_intro_numpy_auto_examples_plot_mandelbrot.py` + +.. raw:: html + +
Mandelbrot set
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/numpy/auto_examples/images/thumb/sphx_glr_plot_randomwalk_thumb.png + :alt: + + :ref:`sphx_glr_intro_numpy_auto_examples_plot_randomwalk.py` + +.. raw:: html + +
Random walk exercise
+
+ + +.. thumbnail-parent-div-close + +.. raw:: html + +
+ + +.. toctree:: + :hidden: + + /intro/numpy/auto_examples/plot_basic1dplot + /intro/numpy/auto_examples/plot_basic2dplot + /intro/numpy/auto_examples/plot_distances + /intro/numpy/auto_examples/plot_polyfit + /intro/numpy/auto_examples/plot_chebyfit + /intro/numpy/auto_examples/plot_populations + /intro/numpy/auto_examples/plot_elephant + /intro/numpy/auto_examples/plot_mandelbrot + /intro/numpy/auto_examples/plot_randomwalk + + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-gallery + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download all examples in Python source code: auto_examples_python.zip ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download all examples in Jupyter notebooks: auto_examples_jupyter.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/numpy/auto_examples/plot_basic1dplot.rst.txt b/_sources/intro/numpy/auto_examples/plot_basic1dplot.rst.txt new file mode 100644 index 000000000..f2ca7244e --- /dev/null +++ b/_sources/intro/numpy/auto_examples/plot_basic1dplot.rst.txt @@ -0,0 +1,80 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/numpy/auto_examples/plot_basic1dplot.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_numpy_auto_examples_plot_basic1dplot.py: + + +1D plotting +=========== + +Plot a basic 1D figure + +.. GENERATED FROM PYTHON SOURCE LINES 8-17 + + + +.. image-sg:: /intro/numpy/auto_examples/images/sphx_glr_plot_basic1dplot_001.png + :alt: plot basic1dplot + :srcset: /intro/numpy/auto_examples/images/sphx_glr_plot_basic1dplot_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + x = np.linspace(0, 3, 20) + y = np.linspace(0, 9, 20) + plt.plot(x, y) + plt.plot(x, y, "o") + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.049 seconds) + + +.. _sphx_glr_download_intro_numpy_auto_examples_plot_basic1dplot.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_basic1dplot.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_basic1dplot.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_basic1dplot.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/numpy/auto_examples/plot_basic2dplot.rst.txt b/_sources/intro/numpy/auto_examples/plot_basic2dplot.rst.txt new file mode 100644 index 000000000..70018e203 --- /dev/null +++ b/_sources/intro/numpy/auto_examples/plot_basic2dplot.rst.txt @@ -0,0 +1,80 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/numpy/auto_examples/plot_basic2dplot.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_numpy_auto_examples_plot_basic2dplot.py: + + +2D plotting +=========== + +Plot a basic 2D figure + +.. GENERATED FROM PYTHON SOURCE LINES 8-17 + + + +.. image-sg:: /intro/numpy/auto_examples/images/sphx_glr_plot_basic2dplot_001.png + :alt: plot basic2dplot + :srcset: /intro/numpy/auto_examples/images/sphx_glr_plot_basic2dplot_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + rng = np.random.default_rng() + image = rng.random((30, 30)) + plt.imshow(image, cmap="hot") + plt.colorbar() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.075 seconds) + + +.. _sphx_glr_download_intro_numpy_auto_examples_plot_basic2dplot.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_basic2dplot.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_basic2dplot.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_basic2dplot.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/numpy/auto_examples/plot_chebyfit.rst.txt b/_sources/intro/numpy/auto_examples/plot_chebyfit.rst.txt new file mode 100644 index 000000000..3fdfe0c69 --- /dev/null +++ b/_sources/intro/numpy/auto_examples/plot_chebyfit.rst.txt @@ -0,0 +1,84 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/numpy/auto_examples/plot_chebyfit.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_numpy_auto_examples_plot_chebyfit.py: + + +Fitting in Chebyshev basis +========================== + +Plot noisy data and their polynomial fit in a Chebyshev basis + +.. GENERATED FROM PYTHON SOURCE LINES 8-21 + + + +.. image-sg:: /intro/numpy/auto_examples/images/sphx_glr_plot_chebyfit_001.png + :alt: plot chebyfit + :srcset: /intro/numpy/auto_examples/images/sphx_glr_plot_chebyfit_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + rng = np.random.default_rng(27446968) + + x = np.linspace(-1, 1, 2000) + y = np.cos(x) + 0.3 * rng.random(2000) + p = np.polynomial.Chebyshev.fit(x, y, 90) + + plt.plot(x, y, "r.") + plt.plot(x, p(x), "k-", lw=3) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.095 seconds) + + +.. _sphx_glr_download_intro_numpy_auto_examples_plot_chebyfit.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_chebyfit.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_chebyfit.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_chebyfit.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/numpy/auto_examples/plot_distances.rst.txt b/_sources/intro/numpy/auto_examples/plot_distances.rst.txt new file mode 100644 index 000000000..ece1d34d2 --- /dev/null +++ b/_sources/intro/numpy/auto_examples/plot_distances.rst.txt @@ -0,0 +1,80 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/numpy/auto_examples/plot_distances.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_numpy_auto_examples_plot_distances.py: + + +Distances exercise +================== + +Plot distances in a grid + +.. GENERATED FROM PYTHON SOURCE LINES 8-17 + + + +.. image-sg:: /intro/numpy/auto_examples/images/sphx_glr_plot_distances_001.png + :alt: plot distances + :srcset: /intro/numpy/auto_examples/images/sphx_glr_plot_distances_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + x, y = np.arange(5), np.arange(5)[:, np.newaxis] + distance = np.sqrt(x**2 + y**2) + plt.pcolor(distance) + plt.colorbar() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.069 seconds) + + +.. _sphx_glr_download_intro_numpy_auto_examples_plot_distances.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_distances.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_distances.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_distances.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/numpy/auto_examples/plot_elephant.rst.txt b/_sources/intro/numpy/auto_examples/plot_elephant.rst.txt new file mode 100644 index 000000000..de5058ef1 --- /dev/null +++ b/_sources/intro/numpy/auto_examples/plot_elephant.rst.txt @@ -0,0 +1,161 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/numpy/auto_examples/plot_elephant.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_numpy_auto_examples_plot_elephant.py: + + +Reading and writing an elephant +=============================== + +Read and write images + +.. GENERATED FROM PYTHON SOURCE LINES 8-12 + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 13-15 + +original figure +################################ + +.. GENERATED FROM PYTHON SOURCE LINES 15-20 + +.. code-block:: Python + + + plt.figure() + img = plt.imread("../../../data/elephant.png") + plt.imshow(img) + + + + +.. image-sg:: /intro/numpy/auto_examples/images/sphx_glr_plot_elephant_001.png + :alt: plot elephant + :srcset: /intro/numpy/auto_examples/images/sphx_glr_plot_elephant_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 21-23 + +red channel displayed in grey +################################ + +.. GENERATED FROM PYTHON SOURCE LINES 23-28 + +.. code-block:: Python + + + plt.figure() + img_red = img[:, :, 0] + plt.imshow(img_red, cmap="gray") + + + + +.. image-sg:: /intro/numpy/auto_examples/images/sphx_glr_plot_elephant_002.png + :alt: plot elephant + :srcset: /intro/numpy/auto_examples/images/sphx_glr_plot_elephant_002.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 29-31 + +lower resolution +################################ + +.. GENERATED FROM PYTHON SOURCE LINES 31-37 + +.. code-block:: Python + + + plt.figure() + img_tiny = img[::6, ::6] + plt.imshow(img_tiny, interpolation="nearest") + + plt.show() + + + +.. image-sg:: /intro/numpy/auto_examples/images/sphx_glr_plot_elephant_003.png + :alt: plot elephant + :srcset: /intro/numpy/auto_examples/images/sphx_glr_plot_elephant_003.png + :class: sphx-glr-single-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.256 seconds) + + +.. _sphx_glr_download_intro_numpy_auto_examples_plot_elephant.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_elephant.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_elephant.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_elephant.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/numpy/auto_examples/plot_mandelbrot.rst.txt b/_sources/intro/numpy/auto_examples/plot_mandelbrot.rst.txt new file mode 100644 index 000000000..326724e70 --- /dev/null +++ b/_sources/intro/numpy/auto_examples/plot_mandelbrot.rst.txt @@ -0,0 +1,105 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/numpy/auto_examples/plot_mandelbrot.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_numpy_auto_examples_plot_mandelbrot.py: + + +Mandelbrot set +============== + +Compute the Mandelbrot fractal and plot it + +.. GENERATED FROM PYTHON SOURCE LINES 8-42 + + + +.. image-sg:: /intro/numpy/auto_examples/images/sphx_glr_plot_mandelbrot_001.png + :alt: plot mandelbrot + :srcset: /intro/numpy/auto_examples/images/sphx_glr_plot_mandelbrot_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + from numpy import newaxis + import warnings + + + def compute_mandelbrot(N_max, some_threshold, nx, ny): + # A grid of c-values + x = np.linspace(-2, 1, nx) + y = np.linspace(-1.5, 1.5, ny) + + c = x[:, newaxis] + 1j * y[newaxis, :] + + # Mandelbrot iteration + + z = c + + # The code below overflows in many regions of the x-y grid, suppress + # warnings temporarily + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + for j in range(N_max): + z = z**2 + c + mandelbrot_set = abs(z) < some_threshold + + return mandelbrot_set + + + mandelbrot_set = compute_mandelbrot(50, 50.0, 601, 401) + + plt.imshow(mandelbrot_set.T, extent=(-2, 1, -1.5, 1.5)) + plt.gray() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.079 seconds) + + +.. _sphx_glr_download_intro_numpy_auto_examples_plot_mandelbrot.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_mandelbrot.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_mandelbrot.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_mandelbrot.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/numpy/auto_examples/plot_polyfit.rst.txt b/_sources/intro/numpy/auto_examples/plot_polyfit.rst.txt new file mode 100644 index 000000000..8374bff16 --- /dev/null +++ b/_sources/intro/numpy/auto_examples/plot_polyfit.rst.txt @@ -0,0 +1,84 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/numpy/auto_examples/plot_polyfit.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_numpy_auto_examples_plot_polyfit.py: + + +Fitting to polynomial +===================== + +Plot noisy data and their polynomial fit + +.. GENERATED FROM PYTHON SOURCE LINES 8-21 + + + +.. image-sg:: /intro/numpy/auto_examples/images/sphx_glr_plot_polyfit_001.png + :alt: plot polyfit + :srcset: /intro/numpy/auto_examples/images/sphx_glr_plot_polyfit_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + rng = np.random.default_rng(27446968) + + x = np.linspace(0, 1, 20) + y = np.cos(x) + 0.3 * rng.random(20) + p = np.poly1d(np.polyfit(x, y, 3)) + + t = np.linspace(0, 1, 200) + plt.plot(x, y, "o", t, p(t), "-") + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.048 seconds) + + +.. _sphx_glr_download_intro_numpy_auto_examples_plot_polyfit.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_polyfit.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_polyfit.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_polyfit.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/numpy/auto_examples/plot_populations.rst.txt b/_sources/intro/numpy/auto_examples/plot_populations.rst.txt new file mode 100644 index 000000000..9c4dddbe5 --- /dev/null +++ b/_sources/intro/numpy/auto_examples/plot_populations.rst.txt @@ -0,0 +1,82 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/numpy/auto_examples/plot_populations.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_numpy_auto_examples_plot_populations.py: + + +Population exercise +=================== + +Plot populations of hares, lynxes, and carrots + +.. GENERATED FROM PYTHON SOURCE LINES 8-19 + + + +.. image-sg:: /intro/numpy/auto_examples/images/sphx_glr_plot_populations_001.png + :alt: plot populations + :srcset: /intro/numpy/auto_examples/images/sphx_glr_plot_populations_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + data = np.loadtxt("../../../data/populations.txt") + year, hares, lynxes, carrots = data.T + + plt.axes((0.2, 0.1, 0.5, 0.8)) + plt.plot(year, hares, year, lynxes, year, carrots) + plt.legend(("Hare", "Lynx", "Carrot"), loc=(1.05, 0.5)) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.063 seconds) + + +.. _sphx_glr_download_intro_numpy_auto_examples_plot_populations.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_populations.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_populations.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_populations.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/numpy/auto_examples/plot_randomwalk.rst.txt b/_sources/intro/numpy/auto_examples/plot_randomwalk.rst.txt new file mode 100644 index 000000000..a5c4726e0 --- /dev/null +++ b/_sources/intro/numpy/auto_examples/plot_randomwalk.rst.txt @@ -0,0 +1,103 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/numpy/auto_examples/plot_randomwalk.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_numpy_auto_examples_plot_randomwalk.py: + + +Random walk exercise +==================== + +Plot distance as a function of time for a random walk +together with the theoretical result + +.. GENERATED FROM PYTHON SOURCE LINES 9-40 + + + +.. image-sg:: /intro/numpy/auto_examples/images/sphx_glr_plot_randomwalk_001.png + :alt: plot randomwalk + :srcset: /intro/numpy/auto_examples/images/sphx_glr_plot_randomwalk_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + # We create 1000 realizations with 200 steps each + n_stories = 1000 + t_max = 200 + + t = np.arange(t_max) + # Steps can be -1 or 1 (note that randint excludes the upper limit) + rng = np.random.default_rng() + steps = 2 * rng.integers(0, 1 + 1, (n_stories, t_max)) - 1 + + # The time evolution of the position is obtained by successively + # summing up individual steps. This is done for each of the + # realizations, i.e. along axis 1. + positions = np.cumsum(steps, axis=1) + + # Determine the time evolution of the mean square distance. + sq_distance = positions**2 + mean_sq_distance = np.mean(sq_distance, axis=0) + + # Plot the distance d from the origin as a function of time and + # compare with the theoretically expected result where d(t) + # grows as a square root of time t. + plt.figure(figsize=(4, 3)) + plt.plot(t, np.sqrt(mean_sq_distance), "g.", t, np.sqrt(t), "y-") + plt.xlabel(r"$t$") + plt.ylabel(r"$\sqrt{\langle (\delta x)^2 \rangle}$") + plt.tight_layout() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.077 seconds) + + +.. _sphx_glr_download_intro_numpy_auto_examples_plot_randomwalk.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_randomwalk.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_randomwalk.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_randomwalk.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/numpy/auto_examples/sg_execution_times.rst.txt b/_sources/intro/numpy/auto_examples/sg_execution_times.rst.txt new file mode 100644 index 000000000..eec72aa07 --- /dev/null +++ b/_sources/intro/numpy/auto_examples/sg_execution_times.rst.txt @@ -0,0 +1,61 @@ + +:orphan: + +.. _sphx_glr_intro_numpy_auto_examples_sg_execution_times: + + +Computation times +================= +**00:00.812** total execution time for 9 files **from intro/numpy/auto_examples**: + +.. container:: + + .. raw:: html + + + + + + + + .. list-table:: + :header-rows: 1 + :class: table table-striped sg-datatable + + * - Example + - Time + - Mem (MB) + * - :ref:`sphx_glr_intro_numpy_auto_examples_plot_elephant.py` (``plot_elephant.py``) + - 00:00.256 + - 0.0 + * - :ref:`sphx_glr_intro_numpy_auto_examples_plot_chebyfit.py` (``plot_chebyfit.py``) + - 00:00.095 + - 0.0 + * - :ref:`sphx_glr_intro_numpy_auto_examples_plot_mandelbrot.py` (``plot_mandelbrot.py``) + - 00:00.079 + - 0.0 + * - :ref:`sphx_glr_intro_numpy_auto_examples_plot_randomwalk.py` (``plot_randomwalk.py``) + - 00:00.077 + - 0.0 + * - :ref:`sphx_glr_intro_numpy_auto_examples_plot_basic2dplot.py` (``plot_basic2dplot.py``) + - 00:00.075 + - 0.0 + * - :ref:`sphx_glr_intro_numpy_auto_examples_plot_distances.py` (``plot_distances.py``) + - 00:00.069 + - 0.0 + * - :ref:`sphx_glr_intro_numpy_auto_examples_plot_populations.py` (``plot_populations.py``) + - 00:00.063 + - 0.0 + * - :ref:`sphx_glr_intro_numpy_auto_examples_plot_basic1dplot.py` (``plot_basic1dplot.py``) + - 00:00.049 + - 0.0 + * - :ref:`sphx_glr_intro_numpy_auto_examples_plot_polyfit.py` (``plot_polyfit.py``) + - 00:00.048 + - 0.0 diff --git a/_sources/intro/numpy/elaborate_arrays.rst.txt b/_sources/intro/numpy/elaborate_arrays.rst.txt new file mode 100644 index 000000000..d35230c13 --- /dev/null +++ b/_sources/intro/numpy/elaborate_arrays.rst.txt @@ -0,0 +1,252 @@ +.. For doctests + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + +.. currentmodule:: numpy + +More elaborate arrays +====================== + +.. contents:: Section contents + :local: + :depth: 1 + +More data types +--------------- + +Casting +........ + +"Bigger" type wins in mixed-type operations:: + + >>> np.array([1, 2, 3]) + 1.5 + array([2.5, 3.5, 4.5]) + +Assignment never changes the type! :: + + >>> a = np.array([1, 2, 3]) + >>> a.dtype + dtype('int64') + >>> a[0] = 1.9 # <-- float is truncated to integer + >>> a + array([1, 2, 3]) + +Forced casts:: + + >>> a = np.array([1.7, 1.2, 1.6]) + >>> b = a.astype(int) # <-- truncates to integer + >>> b + array([1, 1, 1]) + +Rounding:: + + >>> a = np.array([1.2, 1.5, 1.6, 2.5, 3.5, 4.5]) + >>> b = np.around(a) + >>> b # still floating-point + array([1., 2., 2., 2., 4., 4.]) + >>> c = np.around(a).astype(int) + >>> c + array([1, 2, 2, 2, 4, 4]) + +Different data type sizes +.......................... + +Integers (signed): + +=================== ============================================================== +:class:`int8` 8 bits +:class:`int16` 16 bits +:class:`int32` 32 bits (same as :class:`int` on 32-bit platform) +:class:`int64` 64 bits (same as :class:`int` on 64-bit platform) +=================== ============================================================== + +:: + + >>> np.array([1], dtype=int).dtype + dtype('int64') + >>> np.iinfo(np.int32).max, 2**31 - 1 + (2147483647, 2147483647) + + +Unsigned integers: + +=================== ============================================================== +:class:`uint8` 8 bits +:class:`uint16` 16 bits +:class:`uint32` 32 bits +:class:`uint64` 64 bits +=================== ============================================================== + +:: + + >>> np.iinfo(np.uint32).max, 2**32 - 1 + (4294967295, 4294967295) + + +Floating-point numbers: + +=================== ============================================================== +:class:`float16` 16 bits +:class:`float32` 32 bits +:class:`float64` 64 bits (same as :class:`float`) +:class:`float96` 96 bits, platform-dependent (same as :class:`np.longdouble`) +:class:`float128` 128 bits, platform-dependent (same as :class:`np.longdouble`) +=================== ============================================================== + +:: + + >>> np.finfo(np.float32).eps + np.float32(1.1920929e-07) + >>> np.finfo(np.float64).eps + np.float64(2.220446049250313e-16) + + >>> np.float32(1e-8) + np.float32(1) == 1 + np.True_ + >>> np.float64(1e-8) + np.float64(1) == 1 + np.False_ + +Complex floating-point numbers: + +=================== ============================================================== +:class:`complex64` two 32-bit floats +:class:`complex128` two 64-bit floats +:class:`complex192` two 96-bit floats, platform-dependent +:class:`complex256` two 128-bit floats, platform-dependent +=================== ============================================================== + +.. topic:: Smaller data types + + If you don't know you need special data types, then you probably don't. + + Comparison on using ``float32`` instead of ``float64``: + + - Half the size in memory and on disk + - Half the memory bandwidth required (may be a bit faster in some operations) + + .. ipython:: + + In [1]: a = np.zeros((int(1e6),), dtype=np.float64) + + In [2]: b = np.zeros((int(1e6),), dtype=np.float32) + + In [3]: %timeit a*a + 1000 loops, best of 3: 1.78 ms per loop + + In [4]: %timeit b*b + 1000 loops, best of 3: 1.07 ms per loop + + - But: bigger rounding errors --- sometimes in surprising places + (i.e., don't use them unless you really need them) + + +Structured data types +--------------------- + +=============== ==================== +``sensor_code`` (4-character string) +``position`` (float) +``value`` (float) +=============== ==================== + +:: + + >>> samples = np.zeros((6,), dtype=[('sensor_code', 'S4'), + ... ('position', float), ('value', float)]) + >>> samples.ndim + 1 + >>> samples.shape + (6,) + >>> samples.dtype.names + ('sensor_code', 'position', 'value') + >>> samples[:] = [('ALFA', 1, 0.37), ('BETA', 1, 0.11), ('TAU', 1, 0.13), + ... ('ALFA', 1.5, 0.37), ('ALFA', 3, 0.11), ('TAU', 1.2, 0.13)] + >>> samples + array([(b'ALFA', 1. , 0.37), (b'BETA', 1. , 0.11), (b'TAU', 1. , 0.13), + (b'ALFA', 1.5, 0.37), (b'ALFA', 3. , 0.11), (b'TAU', 1.2, 0.13)], + dtype=[('sensor_code', 'S4'), ('position', '>> samples['sensor_code'] + array([b'ALFA', b'BETA', b'TAU', b'ALFA', b'ALFA', b'TAU'], dtype='|S4') + >>> samples['value'] + array([0.37, 0.11, 0.13, 0.37, 0.11, 0.13]) + >>> samples[0] + np.void((b'ALFA', 1.0, 0.37), dtype=[('sensor_code', 'S4'), ('position', '>> samples[0]['sensor_code'] = 'TAU' + >>> samples[0] + np.void((b'TAU', 1.0, 0.37), dtype=[('sensor_code', 'S4'), ('position', '>> samples[['position', 'value']] + array([(1. , 0.37), (1. , 0.11), (1. , 0.13), (1.5, 0.37), + (3. , 0.11), (1.2, 0.13)], + dtype={'names': ['position', 'value'], 'formats': ['>> samples[samples['sensor_code'] == b'ALFA'] + array([(b'ALFA', 1.5, 0.37), (b'ALFA', 3. , 0.11)], + dtype=[('sensor_code', 'S4'), ('position', '`__ + and `here `__. + + +:class:`maskedarray`: dealing with (propagation of) missing data +------------------------------------------------------------------ + +* For floats one could use NaN's, but masks work for all types:: + + >>> x = np.ma.array([1, 2, 3, 4], mask=[0, 1, 0, 1]) + >>> x + masked_array(data=[1, --, 3, --], + mask=[False, True, False, True], + fill_value=999999) + + + >>> y = np.ma.array([1, 2, 3, 4], mask=[0, 1, 1, 1]) + >>> x + y + masked_array(data=[2, --, --, --], + mask=[False, True, True, True], + fill_value=999999) + + +* Masking versions of common functions:: + + >>> np.ma.sqrt([1, -1, 2, -2]) #doctest:+ELLIPSIS + masked_array(data=[1.0, --, 1.41421356237... --], + mask=[False, True, False, True], + fill_value=1e+20) + + + +.. note:: + + There are other useful :ref:`array siblings ` + + +_____ + +While it is off topic in a chapter on NumPy, let's take a moment to +recall good coding practice, which really do pay off in the long run: + +.. topic:: Good practices + + * Explicit variable names (no need of a comment to explain what is in + the variable) + + * Style: spaces after commas, around ``=``, etc. + + A certain number of rules for writing "beautiful" code (and, more + importantly, using the same conventions as everybody else!) are + given in the `Style Guide for Python Code + `_ and the `Docstring + Conventions `_ page (to + manage help strings). + + * Except some rare cases, variable names and comments in English. diff --git a/_sources/intro/numpy/exercises.rst.txt b/_sources/intro/numpy/exercises.rst.txt new file mode 100644 index 000000000..548a28420 --- /dev/null +++ b/_sources/intro/numpy/exercises.rst.txt @@ -0,0 +1,268 @@ +.. for doctests + >>> import matplotlib.pyplot as plt + +.. _numpy_exercises: + +Some exercises +============== + +Array manipulations +-------------------- + +1. Form the 2-D array (without typing it in explicitly):: + + [[1, 6, 11], + [2, 7, 12], + [3, 8, 13], + [4, 9, 14], + [5, 10, 15]] + + and generate a new array containing its 2nd and 4th rows. + +2. Divide each column of the array: + + .. sourcecode:: pycon + + >>> import numpy as np + >>> a = np.arange(25).reshape(5, 5) + + elementwise with the array ``b = np.array([1., 5, 10, 15, 20])``. + (Hint: ``np.newaxis``). + +3. Harder one: Generate a 10 x 3 array of random numbers (in range [0,1]). + For each row, pick the number closest to 0.5. + + - Use ``abs`` and ``argmin`` to find the column ``j`` closest for + each row. + + - Use fancy indexing to extract the numbers. (Hint: ``a[i,j]`` -- + the array ``i`` must contain the row numbers corresponding to stuff in + ``j``.) + + +Picture manipulation: Framing a Face +------------------------------------ + +Let's do some manipulations on NumPy arrays by starting with an image +of a raccoon. ``scipy`` provides a 2D array of this image with the +``scipy.datasets.face`` function:: + + + >>> import scipy as sp + >>> face = sp.datasets.face(gray=True) # 2D grayscale image + +Here are a few images we will be able to obtain with our manipulations: +use different colormaps, crop the image, change some parts of the image. + +.. image:: images/faces.png + :align: center + +* Let's use the imshow function of matplotlib to display the image. + + .. sourcecode:: pycon + + >>> import matplotlib.pyplot as plt + >>> face = sp.datasets.face(gray=True) + >>> plt.imshow(face) + + +* The face is displayed in false colors. A colormap must be + specified for it to be displayed in grey. + + .. sourcecode:: pycon + + >>> plt.imshow(face, cmap=plt.cm.gray) + + +* Create an array of the image with a narrower centering : for example, + remove 100 pixels from all the borders of the image. To check the result, + display this new array with ``imshow``. + + .. sourcecode:: pycon + + >>> crop_face = face[100:-100, 100:-100] + +* We will now frame the face with a black locket. For this, we + need to create a mask corresponding to the pixels we want to be + black. The center of the face is around (660, 330), so we defined + the mask by this condition ``(y-300)**2 + (x-660)**2`` + + .. sourcecode:: pycon + + >>> sy, sx = face.shape + >>> y, x = np.ogrid[0:sy, 0:sx] # x and y indices of pixels + >>> y.shape, x.shape + ((768, 1), (1, 1024)) + >>> centerx, centery = (660, 300) # center of the image + >>> mask = ((y - centery)**2 + (x - centerx)**2) > 230**2 # circle + + then we assign the value 0 to the pixels of the image corresponding + to the mask. The syntax is extremely simple and intuitive: + + .. sourcecode:: pycon + + >>> face[mask] = 0 + >>> plt.imshow(face) + + +* Follow-up: copy all instructions of this exercise in a script called + ``face_locket.py`` then execute this script in IPython with ``%run + face_locket.py``. + + Change the circle to an ellipsoid. + +Data statistics +---------------- + +The data in :download:`populations.txt <../../data/populations.txt>` +describes the populations of hares and lynxes (and carrots) in +northern Canada during 20 years: + +.. sourcecode:: pycon + + >>> data = np.loadtxt('data/populations.txt') + >>> year, hares, lynxes, carrots = data.T # trick: columns to variables + + >>> import matplotlib.pyplot as plt + >>> plt.axes([0.2, 0.1, 0.5, 0.8]) + + >>> plt.plot(year, hares, year, lynxes, year, carrots) + [, ...] + >>> plt.legend(('Hare', 'Lynx', 'Carrot'), loc=(1.05, 0.5)) + + +.. image:: auto_examples/images/sphx_glr_plot_populations_001.png + :width: 50% + :target: auto_examples/plot_populations.html + :align: center + +Computes and print, based on the data in ``populations.txt``... + +1. The mean and std of the populations of each species for the years + in the period. + +2. Which year each species had the largest population. + +3. Which species has the largest population for each year. + (Hint: ``argsort`` & fancy indexing of + ``np.array(['H', 'L', 'C'])``) + +4. Which years any of the populations is above 50000. + (Hint: comparisons and ``np.any``) + +5. The top 2 years for each species when they had the lowest + populations. (Hint: ``argsort``, fancy indexing) + +6. Compare (plot) the change in hare population (see + ``help(np.gradient)``) and the number of lynxes. Check correlation + (see ``help(np.corrcoef)``). + +... all without for-loops. + +Solution: :download:`Python source file ` + +Crude integral approximations +----------------------------- + +Write a function ``f(a, b, c)`` that returns :math:`a^b - c`. Form +a 24x12x6 array containing its values in parameter ranges ``[0,1] x +[0,1] x [0,1]``. + +Approximate the 3-d integral + +.. math:: \int_0^1\int_0^1\int_0^1(a^b-c)da\,db\,dc + +over this volume with the mean. The exact result is: :math:`\ln 2 - +\frac{1}{2}\approx0.1931\ldots` --- what is your relative error? + +(Hints: use elementwise operations and broadcasting. +You can make ``np.ogrid`` give a number of points in given range +with ``np.ogrid[0:1:20j]``.) + +**Reminder** Python functions:: + + def f(a, b, c): + return some_result + +Solution: :download:`Python source file ` + +Mandelbrot set +--------------- + +.. image:: auto_examples/images/sphx_glr_plot_mandelbrot_001.png + :width: 50% + :target: auto_examples/plot_mandelbrot.html + :align: center + +Write a script that computes the Mandelbrot fractal. The Mandelbrot +iteration:: + + N_max = 50 + some_threshold = 50 + + c = x + 1j*y + + z = 0 + for j in range(N_max): + z = z**2 + c + +Point (x, y) belongs to the Mandelbrot set if :math:`|z|` < +``some_threshold``. + +Do this computation by: + +.. For doctests + >>> mask = np.ones((3, 3)) + +1. Construct a grid of c = x + 1j*y values in range [-2, 1] x [-1.5, 1.5] + +2. Do the iteration + +3. Form the 2-d boolean mask indicating which points are in the set + +4. Save the result to an image with: + + .. sourcecode:: pycon + + >>> import matplotlib.pyplot as plt + >>> plt.imshow(mask.T, extent=[-2, 1, -1.5, 1.5]) + + >>> plt.gray() + >>> plt.savefig('mandelbrot.png') + +Solution: :download:`Python source file ` + +Markov chain +------------- + +.. image:: images/markov-chain.png + +Markov chain transition matrix ``P``, and probability distribution on +the states ``p``: + +1. ``0 <= P[i,j] <= 1``: probability to go from state ``i`` to state ``j`` + +2. Transition rule: :math:`p_{new} = P^T p_{old}` + +3. ``all(sum(P, axis=1) == 1)``, ``p.sum() == 1``: normalization + +Write a script that works with 5 states, and: + +- Constructs a random matrix, and normalizes each row so that it + is a transition matrix. + +- Starts from a random (normalized) probability distribution + ``p`` and takes 50 steps => ``p_50`` + +- Computes the stationary distribution: the eigenvector of ``P.T`` + with eigenvalue 1 (numerically: closest to 1) => ``p_stationary`` + +Remember to normalize the eigenvector --- I didn't... + +- Checks if ``p_50`` and ``p_stationary`` are equal to tolerance 1e-5 + +Toolbox: ``np.random``, ``@``, ``np.linalg.eig``, +reductions, ``abs()``, ``argmin``, comparisons, ``all``, +``np.linalg.norm``, etc. + +Solution: :download:`Python source file ` diff --git a/_sources/intro/numpy/gallery.rst.txt b/_sources/intro/numpy/gallery.rst.txt new file mode 100644 index 000000000..939efe548 --- /dev/null +++ b/_sources/intro/numpy/gallery.rst.txt @@ -0,0 +1,8 @@ +Full code examples +================== + +.. include the gallery. Skip the first line to avoid the "orphan" + declaration + +.. include:: auto_examples/index.rst + :start-line: 1 diff --git a/_sources/intro/numpy/index.rst.txt b/_sources/intro/numpy/index.rst.txt new file mode 100644 index 000000000..ee86ac103 --- /dev/null +++ b/_sources/intro/numpy/index.rst.txt @@ -0,0 +1,28 @@ +.. _numpy: + +*********************************************** +NumPy: creating and manipulating numerical data +*********************************************** + +**Authors**: *Emmanuelle Gouillart, Didrik Pinte, Gaël Varoquaux, and +Pauli Virtanen* + +.. .. contents:: Chapters contents + :local: + :depth: 4 + +This chapter gives an overview of NumPy, the core tool for performant +numerical computing with Python. + +____ + +.. include:: ../../includes/big_toc_css.rst + :start-line: 1 + +.. toctree:: + array_object.rst + operations.rst + elaborate_arrays.rst + advanced_operations.rst + exercises.rst + gallery.rst diff --git a/_sources/intro/numpy/operations.rst.txt b/_sources/intro/numpy/operations.rst.txt new file mode 100644 index 000000000..4e1853692 --- /dev/null +++ b/_sources/intro/numpy/operations.rst.txt @@ -0,0 +1,881 @@ + +.. For doctests + + >>> import numpy as np + >>> # For doctest on headless environments + >>> import matplotlib.pyplot as plt + +.. currentmodule:: numpy + +Numerical operations on arrays +============================== + +.. contents:: Section contents + :local: + :depth: 1 + + +Elementwise operations +---------------------- + +Basic operations +................ + +With scalars: + +.. sourcecode:: pycon + + >>> a = np.array([1, 2, 3, 4]) + >>> a + 1 + array([2, 3, 4, 5]) + >>> 2**a + array([ 2, 4, 8, 16]) + +All arithmetic operates elementwise: + +.. sourcecode:: pycon + + >>> b = np.ones(4) + 1 + >>> a - b + array([-1., 0., 1., 2.]) + >>> a * b + array([2., 4., 6., 8.]) + + >>> j = np.arange(5) + >>> 2**(j + 1) - j + array([ 2, 3, 6, 13, 28]) + +These operations are of course much faster than if you did them in pure python: + +.. sourcecode:: pycon + + >>> a = np.arange(10000) + >>> %timeit a + 1 # doctest: +SKIP + 10000 loops, best of 3: 24.3 us per loop + >>> l = range(10000) + >>> %timeit [i+1 for i in l] # doctest: +SKIP + 1000 loops, best of 3: 861 us per loop + + +.. warning:: **Array multiplication is not matrix multiplication:** + + .. sourcecode:: pycon + + >>> c = np.ones((3, 3)) + >>> c * c # NOT matrix multiplication! + array([[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]]) + +.. note:: **Matrix multiplication:** + + .. sourcecode:: pycon + + >>> c @ c + array([[3., 3., 3.], + [3., 3., 3.], + [3., 3., 3.]]) + +.. topic:: **Exercise: Elementwise operations** + :class: green + + * Try simple arithmetic elementwise operations: add even elements + with odd elements + * Time them against their pure python counterparts using ``%timeit``. + * Generate: + + * ``[2**0, 2**1, 2**2, 2**3, 2**4]`` + * ``a_j = 2^(3*j) - j`` + + +Other operations +................ + +**Comparisons:** + +.. sourcecode:: pycon + + >>> a = np.array([1, 2, 3, 4]) + >>> b = np.array([4, 2, 2, 4]) + >>> a == b + array([False, True, False, True]) + >>> a > b + array([False, False, True, False]) + +.. tip:: + + Array-wise comparisons: + + .. sourcecode:: pycon + + >>> a = np.array([1, 2, 3, 4]) + >>> b = np.array([4, 2, 2, 4]) + >>> c = np.array([1, 2, 3, 4]) + >>> np.array_equal(a, b) + False + >>> np.array_equal(a, c) + True + + +**Logical operations:** + +.. sourcecode:: pycon + + >>> a = np.array([1, 1, 0, 0], dtype=bool) + >>> b = np.array([1, 0, 1, 0], dtype=bool) + >>> np.logical_or(a, b) + array([ True, True, True, False]) + >>> np.logical_and(a, b) + array([ True, False, False, False]) + +**Transcendental functions:** + +.. sourcecode:: pycon + + >>> a = np.arange(5) + >>> np.sin(a) + array([ 0. , 0.84147098, 0.90929743, 0.14112001, -0.7568025 ]) + >>> np.exp(a) + array([ 1. , 2.71828183, 7.3890561 , 20.08553692, 54.59815003]) + >>> np.log(np.exp(a)) + array([0., 1., 2., 3., 4.]) + + +**Shape mismatches** + +.. sourcecode:: pycon + + >>> a = np.arange(4) + >>> a + np.array([1, 2]) + Traceback (most recent call last): + File "", line 1, in + ValueError: operands could not be broadcast together with shapes (4,) (2,) + +*Broadcasting?* We'll return to that :ref:`later `. + +**Transposition:** + +.. sourcecode:: pycon + + >>> a = np.triu(np.ones((3, 3)), 1) # see help(np.triu) + >>> a + array([[0., 1., 1.], + [0., 0., 1.], + [0., 0., 0.]]) + >>> a.T + array([[0., 0., 0.], + [1., 0., 0.], + [1., 1., 0.]]) + + +.. note:: **The transposition is a view** + + The transpose returns a *view* of the original array:: + + >>> a = np.arange(9).reshape(3, 3) + >>> a.T[0, 2] = 999 + >>> a.T + array([[ 0, 3, 999], + [ 1, 4, 7], + [ 2, 5, 8]]) + >>> a + array([[ 0, 1, 2], + [ 3, 4, 5], + [999, 7, 8]]) + +.. note:: **Linear algebra** + + The sub-module :mod:`numpy.linalg` implements basic linear algebra, such as + solving linear systems, singular value decomposition, etc. However, it is + not guaranteed to be compiled using efficient routines, and thus we + recommend the use of :mod:`scipy.linalg`, as detailed in section + :ref:`scipy_linalg` + +.. topic:: Exercise other operations + :class: green + + * Look at the help for ``np.allclose``. When might this be useful? + * Look at the help for ``np.triu`` and ``np.tril``. + + +Basic reductions +---------------- + +Computing sums +.............. + +.. sourcecode:: pycon + + >>> x = np.array([1, 2, 3, 4]) + >>> np.sum(x) + np.int64(10) + >>> x.sum() + np.int64(10) + +.. image:: images/reductions.png + :align: right + +Sum by rows and by columns: + +.. sourcecode:: pycon + + >>> x = np.array([[1, 1], [2, 2]]) + >>> x + array([[1, 1], + [2, 2]]) + >>> x.sum(axis=0) # columns (first dimension) + array([3, 3]) + >>> x[:, 0].sum(), x[:, 1].sum() + (np.int64(3), np.int64(3)) + >>> x.sum(axis=1) # rows (second dimension) + array([2, 4]) + >>> x[0, :].sum(), x[1, :].sum() + (np.int64(2), np.int64(4)) + +.. tip:: + + Same idea in higher dimensions: + + .. sourcecode:: pycon + + >>> rng = np.random.default_rng(27446968) + >>> x = rng.random((2, 2, 2)) + >>> x.sum(axis=2)[0, 1] + np.float64(0.73415...) + >>> x[0, 1, :].sum() + np.float64(0.73415...) + +Other reductions +................ + +--- works the same way (and take ``axis=``) + +**Extrema:** + +.. sourcecode:: pycon + + >>> x = np.array([1, 3, 2]) + >>> x.min() + np.int64(1) + >>> x.max() + np.int64(3) + + >>> x.argmin() # index of minimum + np.int64(0) + >>> x.argmax() # index of maximum + np.int64(1) + +**Logical operations:** + +.. sourcecode:: pycon + + >>> np.all([True, True, False]) + np.False_ + >>> np.any([True, True, False]) + np.True_ + +.. note:: + + Can be used for array comparisons: + + .. sourcecode:: pycon + + >>> a = np.zeros((100, 100)) + >>> np.any(a != 0) + np.False_ + >>> np.all(a == a) + np.True_ + + >>> a = np.array([1, 2, 3, 2]) + >>> b = np.array([2, 2, 3, 2]) + >>> c = np.array([6, 4, 4, 5]) + >>> ((a <= b) & (b <= c)).all() + np.True_ + +**Statistics:** + +.. sourcecode:: pycon + + >>> x = np.array([1, 2, 3, 1]) + >>> y = np.array([[1, 2, 3], [5, 6, 1]]) + >>> x.mean() + np.float64(1.75) + >>> np.median(x) + np.float64(1.5) + >>> np.median(y, axis=-1) # last axis + array([2., 5.]) + + >>> x.std() # full population standard dev. + np.float64(0.82915619758884995) + + +... and many more (best to learn as you go). + +.. topic:: **Exercise: Reductions** + :class: green + + * Given there is a ``sum``, what other function might you expect to see? + * What is the difference between ``sum`` and ``cumsum``? + + +.. topic:: Worked Example: diffusion using a random walk algorithm + + .. image:: random_walk.png + :align: center + + .. tip:: + + Let us consider a simple 1D random walk process: at each time step a + walker jumps right or left with equal probability. + + We are interested in finding the typical distance from the origin of a + random walker after ``t`` left or right jumps? We are going to + simulate many "walkers" to find this law, and we are going to do so + using array computing tricks: we are going to create a 2D array with + the "stories" (each walker has a story) in one direction, and the + time in the other: + + .. only:: latex + + .. image:: random_walk_schema.png + :align: center + + .. only:: html + + .. image:: random_walk_schema.png + :align: center + :width: 100% + + .. sourcecode:: pycon + + >>> n_stories = 1000 # number of walkers + >>> t_max = 200 # time during which we follow the walker + + We randomly choose all the steps 1 or -1 of the walk: + + .. sourcecode:: pycon + + >>> t = np.arange(t_max) + >>> rng = np.random.default_rng() + >>> steps = 2 * rng.integers(0, 1 + 1, (n_stories, t_max)) - 1 # +1 because the high value is exclusive + >>> np.unique(steps) # Verification: all steps are 1 or -1 + array([-1, 1]) + + We build the walks by summing steps along the time: + + .. sourcecode:: pycon + + >>> positions = np.cumsum(steps, axis=1) # axis = 1: dimension of time + >>> sq_distance = positions**2 + + We get the mean in the axis of the stories: + + .. sourcecode:: pycon + + >>> mean_sq_distance = np.mean(sq_distance, axis=0) + + Plot the results: + + .. sourcecode:: pycon + + >>> plt.figure(figsize=(4, 3)) +
+ >>> plt.plot(t, np.sqrt(mean_sq_distance), 'g.', t, np.sqrt(t), 'y-') + [, ] + >>> plt.xlabel(r"$t$") + Text(...'$t$') + >>> plt.ylabel(r"$\sqrt{\langle (\delta x)^2 \rangle}$") + Text(...'$\\sqrt{\\langle (\\delta x)^2 \\rangle}$') + >>> plt.tight_layout() # provide sufficient space for labels + + .. image:: auto_examples/images/sphx_glr_plot_randomwalk_001.png + :width: 50% + :target: auto_examples/plot_randomwalk.html + :align: center + + We find a well-known result in physics: the RMS distance grows as the + square root of the time! + + +.. arithmetic: sum/prod/mean/std + +.. extrema: min/max + +.. logical: all/any + +.. the axis argument + +.. EXE: verify if all elements in an array are equal to 1 +.. EXE: verify if any elements in an array are equal to 1 +.. EXE: load data with loadtxt from a file, and compute its basic statistics + +.. CHA: implement mean and std using only sum() + +.. _broadcasting: + +Broadcasting +------------ + +* Basic operations on ``numpy`` arrays (addition, etc.) are elementwise + +* This works on arrays of the same size. + + | **Nevertheless**, It's also possible to do operations on arrays of different + | sizes if *NumPy* can transform these arrays so that they all have + | the same size: this conversion is called **broadcasting**. + +The image below gives an example of broadcasting: + +.. only:: latex + + .. image:: images/numpy_broadcasting.png + :align: center + +.. only:: html + + .. image:: images/numpy_broadcasting.png + :align: center + :width: 100% + +Let's verify: + +.. sourcecode:: pycon + + >>> a = np.tile(np.arange(0, 40, 10), (3, 1)).T + >>> a + array([[ 0, 0, 0], + [10, 10, 10], + [20, 20, 20], + [30, 30, 30]]) + >>> b = np.array([0, 1, 2]) + >>> a + b + array([[ 0, 1, 2], + [10, 11, 12], + [20, 21, 22], + [30, 31, 32]]) + +We have already used broadcasting without knowing it!: + +.. sourcecode:: pycon + + >>> a = np.ones((4, 5)) + >>> a[0] = 2 # we assign an array of dimension 0 to an array of dimension 1 + >>> a + array([[2., 2., 2., 2., 2.], + [1., 1., 1., 1., 1.], + [1., 1., 1., 1., 1.], + [1., 1., 1., 1., 1.]]) + +A useful trick: + +.. sourcecode:: pycon + + >>> a = np.arange(0, 40, 10) + >>> a.shape + (4,) + >>> a = a[:, np.newaxis] # adds a new axis -> 2D array + >>> a.shape + (4, 1) + >>> a + array([[ 0], + [10], + [20], + [30]]) + >>> a + b + array([[ 0, 1, 2], + [10, 11, 12], + [20, 21, 22], + [30, 31, 32]]) + + +.. tip:: + + Broadcasting seems a bit magical, but it is actually quite natural to + use it when we want to solve a problem whose output data is an array + with more dimensions than input data. + +.. topic:: Worked Example: Broadcasting + :class: green + + Let's construct an array of distances (in miles) between cities of + Route 66: Chicago, Springfield, Saint-Louis, Tulsa, Oklahoma City, + Amarillo, Santa Fe, Albuquerque, Flagstaff and Los Angeles. + + .. sourcecode:: pycon + + >>> mileposts = np.array([0, 198, 303, 736, 871, 1175, 1475, 1544, + ... 1913, 2448]) + >>> distance_array = np.abs(mileposts - mileposts[:, np.newaxis]) + >>> distance_array + array([[ 0, 198, 303, 736, 871, 1175, 1475, 1544, 1913, 2448], + [ 198, 0, 105, 538, 673, 977, 1277, 1346, 1715, 2250], + [ 303, 105, 0, 433, 568, 872, 1172, 1241, 1610, 2145], + [ 736, 538, 433, 0, 135, 439, 739, 808, 1177, 1712], + [ 871, 673, 568, 135, 0, 304, 604, 673, 1042, 1577], + [1175, 977, 872, 439, 304, 0, 300, 369, 738, 1273], + [1475, 1277, 1172, 739, 604, 300, 0, 69, 438, 973], + [1544, 1346, 1241, 808, 673, 369, 69, 0, 369, 904], + [1913, 1715, 1610, 1177, 1042, 738, 438, 369, 0, 535], + [2448, 2250, 2145, 1712, 1577, 1273, 973, 904, 535, 0]]) + + + .. image:: images/route66.png + :align: center + :scale: 60 + +A lot of grid-based or network-based problems can also use +broadcasting. For instance, if we want to compute the distance from +the origin of points on a 5x5 grid, we can do + +.. sourcecode:: pycon + + >>> x, y = np.arange(5), np.arange(5)[:, np.newaxis] + >>> distance = np.sqrt(x ** 2 + y ** 2) + >>> distance + array([[0. , 1. , 2. , 3. , 4. ], + [1. , 1.41421356, 2.23606798, 3.16227766, 4.12310563], + [2. , 2.23606798, 2.82842712, 3.60555128, 4.47213595], + [3. , 3.16227766, 3.60555128, 4.24264069, 5. ], + [4. , 4.12310563, 4.47213595, 5. , 5.65685425]]) + +Or in color: + +.. sourcecode:: pycon + + >>> plt.pcolor(distance) + + >>> plt.colorbar() + + +.. image:: auto_examples/images/sphx_glr_plot_distances_001.png + :width: 50% + :target: auto_examples/plot_distances.html + :align: center + + +**Remark** : the :func:`numpy.ogrid` function allows to directly create vectors x +and y of the previous example, with two "significant dimensions": + +.. sourcecode:: pycon + + >>> x, y = np.ogrid[0:5, 0:5] + >>> x, y + (array([[0], + [1], + [2], + [3], + [4]]), array([[0, 1, 2, 3, 4]])) + >>> x.shape, y.shape + ((5, 1), (1, 5)) + >>> distance = np.sqrt(x ** 2 + y ** 2) + +.. tip:: + + So, ``np.ogrid`` is very useful as soon as we have to handle + computations on a grid. On the other hand, ``np.mgrid`` directly + provides matrices full of indices for cases where we can't (or don't + want to) benefit from broadcasting: + + .. sourcecode:: pycon + + >>> x, y = np.mgrid[0:4, 0:4] + >>> x + array([[0, 0, 0, 0], + [1, 1, 1, 1], + [2, 2, 2, 2], + [3, 3, 3, 3]]) + >>> y + array([[0, 1, 2, 3], + [0, 1, 2, 3], + [0, 1, 2, 3], + [0, 1, 2, 3]]) + +.. rules + +.. some usage examples: scalars, 1-d matrix products + +.. newaxis + +.. EXE: add 1-d array to a scalar +.. EXE: add 1-d array to a 2-d array +.. EXE: multiply matrix from the right with a diagonal array +.. CHA: constructing grids -- meshgrid using only newaxis + +.. seealso:: + + :ref:`broadcasting_advanced`: discussion of broadcasting in + the :ref:`advanced_numpy` chapter. + + +Array shape manipulation +------------------------ + +Flattening +.......... + +.. sourcecode:: pycon + + >>> a = np.array([[1, 2, 3], [4, 5, 6]]) + >>> a.ravel() + array([1, 2, 3, 4, 5, 6]) + >>> a.T + array([[1, 4], + [2, 5], + [3, 6]]) + >>> a.T.ravel() + array([1, 4, 2, 5, 3, 6]) + +Higher dimensions: last dimensions ravel out "first". + +Reshaping +......... + +The inverse operation to flattening: + +.. sourcecode:: pycon + + >>> a.shape + (2, 3) + >>> b = a.ravel() + >>> b = b.reshape((2, 3)) + >>> b + array([[1, 2, 3], + [4, 5, 6]]) + +Or, + +.. sourcecode:: pycon + + >>> a.reshape((2, -1)) # unspecified (-1) value is inferred + array([[1, 2, 3], + [4, 5, 6]]) + +.. warning:: + + ``ndarray.reshape`` **may** return a view (cf ``help(np.reshape)``)), + or copy + +.. tip:: + + .. sourcecode:: pycon + + >>> b[0, 0] = 99 + >>> a + array([[99, 2, 3], + [ 4, 5, 6]]) + + Beware: reshape may also return a copy!: + + .. sourcecode:: pycon + + >>> a = np.zeros((3, 2)) + >>> b = a.T.reshape(3*2) + >>> b[0] = 9 + >>> a + array([[0., 0.], + [0., 0.], + [0., 0.]]) + + To understand this you need to learn more about the memory layout of a NumPy array. + +Adding a dimension +.................. + +Indexing with the ``np.newaxis`` object allows us to add an axis to an array +(you have seen this already above in the broadcasting section): + +.. sourcecode:: pycon + + >>> z = np.array([1, 2, 3]) + >>> z + array([1, 2, 3]) + + >>> z[:, np.newaxis] + array([[1], + [2], + [3]]) + + >>> z[np.newaxis, :] + array([[1, 2, 3]]) + + + +Dimension shuffling +................... + +.. sourcecode:: pycon + + >>> a = np.arange(4*3*2).reshape(4, 3, 2) + >>> a.shape + (4, 3, 2) + >>> a[0, 2, 1] + np.int64(5) + >>> b = a.transpose(1, 2, 0) + >>> b.shape + (3, 2, 4) + >>> b[2, 1, 0] + np.int64(5) + +Also creates a view: + +.. sourcecode:: pycon + + >>> b[2, 1, 0] = -1 + >>> a[0, 2, 1] + np.int64(-1) + +Resizing +........ + +Size of an array can be changed with ``ndarray.resize``: + +.. sourcecode:: pycon + + >>> a = np.arange(4) + >>> a.resize((8,)) + >>> a + array([0, 1, 2, 3, 0, 0, 0, 0]) + +However, it must not be referred to somewhere else: + +.. sourcecode:: pycon + + >>> b = a + >>> a.resize((4,)) + Traceback (most recent call last): + File "", line 1, in + ValueError: cannot resize an array that references or is referenced + by another array in this way. + Use the np.resize function or refcheck=False + +.. seealso: ``help(np.tensordot)`` + +.. resizing: how to do it, and *when* is it possible (not always!) + +.. reshaping (demo using an image?) + +.. dimension shuffling + +.. when to use: some pre-made algorithm (e.g. in Fortran) accepts only + 1-D data, but you'd like to vectorize it + +.. EXE: load data incrementally from a file, by appending to a resizing array +.. EXE: vectorize a pre-made routine that only accepts 1-D data +.. EXE: manipulating matrix direct product spaces back and forth (give an example from physics -- spin index and orbital indices) +.. EXE: shuffling dimensions when writing a general vectorized function +.. CHA: the mathematical 'vec' operation + +.. topic:: **Exercise: Shape manipulations** + :class: green + + * Look at the docstring for ``reshape``, especially the notes section which + has some more information about copies and views. + * Use ``flatten`` as an alternative to ``ravel``. What is the difference? + (Hint: check which one returns a view and which a copy) + * Experiment with ``transpose`` for dimension shuffling. + +Sorting data +------------ + +Sorting along an axis: + +.. sourcecode:: pycon + + >>> a = np.array([[4, 3, 5], [1, 2, 1]]) + >>> b = np.sort(a, axis=1) + >>> b + array([[3, 4, 5], + [1, 1, 2]]) + +.. note:: Sorts each row separately! + +In-place sort: + +.. sourcecode:: pycon + + >>> a.sort(axis=1) + >>> a + array([[3, 4, 5], + [1, 1, 2]]) + +Sorting with fancy indexing: + +.. sourcecode:: pycon + + >>> a = np.array([4, 3, 1, 2]) + >>> j = np.argsort(a) + >>> j + array([2, 3, 1, 0]) + >>> a[j] + array([1, 2, 3, 4]) + +Finding minima and maxima: + +.. sourcecode:: pycon + + >>> a = np.array([4, 3, 1, 2]) + >>> j_max = np.argmax(a) + >>> j_min = np.argmin(a) + >>> j_max, j_min + (np.int64(0), np.int64(2)) + + +.. XXX: need a frame for summaries + + * Arithmetic etc. are elementwise operations + * Basic linear algebra, ``@`` + * Reductions: ``sum(axis=1)``, ``std()``, ``all()``, ``any()`` + * Broadcasting: ``a = np.arange(4); a[:,np.newaxis] + a[np.newaxis,:]`` + * Shape manipulation: ``a.ravel()``, ``a.reshape(2, 2)`` + * Fancy indexing: ``a[a > 3]``, ``a[[2, 3]]`` + * Sorting data: ``.sort()``, ``np.sort``, ``np.argsort``, ``np.argmax`` + +.. topic:: **Exercise: Sorting** + :class: green + + * Try both in-place and out-of-place sorting. + * Try creating arrays with different dtypes and sorting them. + * Use ``all`` or ``array_equal`` to check the results. + * Look at ``np.random.shuffle`` for a way to create sortable input quicker. + * Combine ``ravel``, ``sort`` and ``reshape``. + * Look at the ``axis`` keyword for ``sort`` and rewrite the previous + exercise. + +Summary +------- + +**What do you need to know to get started?** + +* Know how to create arrays : ``array``, ``arange``, ``ones``, + ``zeros``. + +* Know the shape of the array with ``array.shape``, then use slicing + to obtain different views of the array: ``array[::2]``, + etc. Adjust the shape of the array using ``reshape`` or flatten it + with ``ravel``. + +* Obtain a subset of the elements of an array and/or modify their values + with masks + + .. sourcecode:: pycon + + >>> a[a < 0] = 0 + +* Know miscellaneous operations on arrays, such as finding the mean or max + (``array.max()``, ``array.mean()``). No need to retain everything, but + have the reflex to search in the documentation (online docs, + ``help()``)!! + +* For advanced use: master the indexing with arrays of integers, as well as + broadcasting. Know more NumPy functions to handle various array + operations. + +.. topic:: **Quick read** + + If you want to do a first quick pass through the Scientific Python Lectures + to learn the ecosystem, you can directly skip to the next chapter: + :ref:`matplotlib`. + + The remainder of this chapter is not necessary to follow the rest of + the intro part. But be sure to come back and finish this chapter, as + well as to do some more :ref:`exercises `. diff --git a/_sources/intro/scipy/auto_examples/index.rst.txt b/_sources/intro/scipy/auto_examples/index.rst.txt new file mode 100644 index 000000000..20164bdc2 --- /dev/null +++ b/_sources/intro/scipy/auto_examples/index.rst.txt @@ -0,0 +1,442 @@ +:orphan: + +Full code examples for the SciPy chapter +---------------------------------------- + + + +.. raw:: html + +
+ +.. thumbnail-parent-div-open + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/images/thumb/sphx_glr_plot_optimize_example1_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_plot_optimize_example1.py` + +.. raw:: html + +
Finding the minimum of a smooth function
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/images/thumb/sphx_glr_plot_resample_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_plot_resample.py` + +.. raw:: html + +
Resample a signal with scipy.signal.resample
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/images/thumb/sphx_glr_plot_detrend_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_plot_detrend.py` + +.. raw:: html + +
Detrending a signal
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/images/thumb/sphx_glr_plot_solve_ivp_simple_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_plot_solve_ivp_simple.py` + +.. raw:: html + +
Integrating a simple ODE
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/images/thumb/sphx_glr_plot_normal_distribution_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_plot_normal_distribution.py` + +.. raw:: html + +
Normal distribution: histogram and PDF
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/images/thumb/sphx_glr_plot_solve_ivp_damped_spring_mass_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_plot_solve_ivp_damped_spring_mass.py` + +.. raw:: html + +
Integrate the Damped spring-mass oscillator
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/images/thumb/sphx_glr_plot_t_test_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_plot_t_test.py` + +.. raw:: html + +
Comparing 2 sets of samples from Gaussians
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/images/thumb/sphx_glr_plot_curve_fit_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_plot_curve_fit.py` + +.. raw:: html + +
Curve fitting
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/images/thumb/sphx_glr_plot_spectrogram_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_plot_spectrogram.py` + +.. raw:: html + +
Spectrogram, power spectral density
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/images/thumb/sphx_glr_plot_mathematical_morpho_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_plot_mathematical_morpho.py` + +.. raw:: html + +
Demo mathematical morphology
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/images/thumb/sphx_glr_plot_image_transform_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_plot_image_transform.py` + +.. raw:: html + +
Plot geometrical transformations on images
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/images/thumb/sphx_glr_plot_connect_measurements_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_plot_connect_measurements.py` + +.. raw:: html + +
Demo connected components
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/images/thumb/sphx_glr_plot_optimize_example2_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_plot_optimize_example2.py` + +.. raw:: html + +
Minima and roots of a function
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/images/thumb/sphx_glr_plot_image_filters_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_plot_image_filters.py` + +.. raw:: html + +
Plot filtering on images
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/images/thumb/sphx_glr_plot_2d_minimization_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_plot_2d_minimization.py` + +.. raw:: html + +
Optimization of a two-parameter function
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/images/thumb/sphx_glr_plot_fftpack_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_plot_fftpack.py` + +.. raw:: html + +
Plotting and manipulating FFTs for filtering
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/images/thumb/sphx_glr_plot_interpolation_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_plot_interpolation.py` + +.. raw:: html + +
A demo of 1D interpolation
+
+ + +.. thumbnail-parent-div-close + +.. raw:: html + +
+ + +.. toctree:: + :hidden: + + /intro/scipy/auto_examples/plot_optimize_example1 + /intro/scipy/auto_examples/plot_resample + /intro/scipy/auto_examples/plot_detrend + /intro/scipy/auto_examples/plot_solve_ivp_simple + /intro/scipy/auto_examples/plot_normal_distribution + /intro/scipy/auto_examples/plot_solve_ivp_damped_spring_mass + /intro/scipy/auto_examples/plot_t_test + /intro/scipy/auto_examples/plot_curve_fit + /intro/scipy/auto_examples/plot_spectrogram + /intro/scipy/auto_examples/plot_mathematical_morpho + /intro/scipy/auto_examples/plot_image_transform + /intro/scipy/auto_examples/plot_connect_measurements + /intro/scipy/auto_examples/plot_optimize_example2 + /intro/scipy/auto_examples/plot_image_filters + /intro/scipy/auto_examples/plot_2d_minimization + /intro/scipy/auto_examples/plot_fftpack + /intro/scipy/auto_examples/plot_interpolation + +Solutions of the exercises for SciPy +.................................... + + + +.. raw:: html + +
+ +.. thumbnail-parent-div-open + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/solutions/images/thumb/sphx_glr_plot_periodicity_finder_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_solutions_plot_periodicity_finder.py` + +.. raw:: html + +
Crude periodicity finding
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/solutions/images/thumb/sphx_glr_plot_curvefit_temperature_data_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_solutions_plot_curvefit_temperature_data.py` + +.. raw:: html + +
Curve fitting: temperature as a function of month of the year
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/solutions/images/thumb/sphx_glr_plot_image_blur_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_solutions_plot_image_blur.py` + +.. raw:: html + +
Simple image blur by convolution with a Gaussian kernel
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/solutions/images/thumb/sphx_glr_plot_fft_image_denoise_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_solutions_plot_fft_image_denoise.py` + +.. raw:: html + +
Image denoising by FFT
+
+ + +.. thumbnail-parent-div-close + +.. raw:: html + +
+ + +.. toctree:: + :hidden: + :includehidden: + + + /intro/scipy/auto_examples/solutions/index.rst + + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-gallery + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download all examples in Python source code: auto_examples_python.zip ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download all examples in Jupyter notebooks: auto_examples_jupyter.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/plot_2d_minimization.rst.txt b/_sources/intro/scipy/auto_examples/plot_2d_minimization.rst.txt new file mode 100644 index 000000000..744bed07b --- /dev/null +++ b/_sources/intro/scipy/auto_examples/plot_2d_minimization.rst.txt @@ -0,0 +1,204 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/auto_examples/plot_2d_minimization.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_auto_examples_plot_2d_minimization.py: + + +========================================= +Optimization of a two-parameter function +========================================= + +.. GENERATED FROM PYTHON SOURCE LINES 7-27 + +.. code-block:: Python + + + import numpy as np + + + # Define the function that we are interested in + def sixhump(x): + return ( + (4 - 2.1 * x[0] ** 2 + x[0] ** 4 / 3) * x[0] ** 2 + + x[0] * x[1] + + (-4 + 4 * x[1] ** 2) * x[1] ** 2 + ) + + + # Make a grid to evaluate the function (for plotting) + xlim = [-2, 2] + ylim = [-1, 1] + x = np.linspace(*xlim) # type: ignore[call-overload] + y = np.linspace(*ylim) # type: ignore[call-overload] + xg, yg = np.meshgrid(x, y) + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 28-31 + +A 2D image plot of the function +########################################################### + Simple visualization in 2D + +.. GENERATED FROM PYTHON SOURCE LINES 31-37 + +.. code-block:: Python + + import matplotlib.pyplot as plt + + plt.figure() + plt.imshow(sixhump([xg, yg]), extent=xlim + ylim, origin="lower") # type: ignore[arg-type] + plt.colorbar() + + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_2d_minimization_001.png + :alt: plot 2d minimization + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_2d_minimization_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 38-40 + +A 3D surface plot of the function +########################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 40-60 + +.. code-block:: Python + + from mpl_toolkits.mplot3d import Axes3D + + fig = plt.figure() + ax: Axes3D = fig.add_subplot(111, projection="3d") + surf = ax.plot_surface( + xg, + yg, + sixhump([xg, yg]), + rstride=1, + cstride=1, + cmap="viridis", + linewidth=0, + antialiased=False, + ) + + ax.set_xlabel("x") + ax.set_ylabel("y") + ax.set_zlabel("f(x, y)") + ax.set_title("Six-hump Camelback function") + + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_2d_minimization_002.png + :alt: Six-hump Camelback function + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_2d_minimization_002.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + Text(0.5, 1.0, 'Six-hump Camelback function') + + + +.. GENERATED FROM PYTHON SOURCE LINES 61-63 + +Find minima +########################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 63-80 + +.. code-block:: Python + + import scipy as sp + + # local minimization + res_local = sp.optimize.minimize(sixhump, x0=[0, 0]) + + # global minimization + res_global = sp.optimize.differential_evolution(sixhump, bounds=[xlim, ylim]) + + plt.figure() + # Show the function in 2D + plt.imshow(sixhump([xg, yg]), extent=xlim + ylim, origin="lower") # type: ignore[arg-type] + plt.colorbar() + # Mark the minima + plt.scatter(res_local.x[0], res_local.x[1], label="local minimizer") + plt.scatter(res_global.x[0], res_global.x[1], label="global minimizer") + plt.legend() + plt.show() + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_2d_minimization_003.png + :alt: plot 2d minimization + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_2d_minimization_003.png + :class: sphx-glr-single-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.324 seconds) + + +.. _sphx_glr_download_intro_scipy_auto_examples_plot_2d_minimization.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_2d_minimization.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_2d_minimization.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_2d_minimization.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/plot_connect_measurements.rst.txt b/_sources/intro/scipy/auto_examples/plot_connect_measurements.rst.txt new file mode 100644 index 000000000..d60cd206e --- /dev/null +++ b/_sources/intro/scipy/auto_examples/plot_connect_measurements.rst.txt @@ -0,0 +1,173 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/auto_examples/plot_connect_measurements.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_auto_examples_plot_connect_measurements.py: + + +============================= +Demo connected components +============================= + +Extracting and labeling connected components in a 2D array + +.. GENERATED FROM PYTHON SOURCE LINES 8-12 + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 13-14 + +Generate some binary data + +.. GENERATED FROM PYTHON SOURCE LINES 14-35 + +.. code-block:: Python + + x, y = np.indices((100, 100)) + sig = ( + np.sin(2 * np.pi * x / 50.0) + * np.sin(2 * np.pi * y / 50.0) + * (1 + x * y / 50.0**2) ** 2 + ) + mask = sig > 1 + + plt.figure(figsize=(7, 3.5)) + plt.subplot(1, 2, 1) + plt.imshow(sig) + plt.axis("off") + plt.title("sig") + + plt.subplot(1, 2, 2) + plt.imshow(mask, cmap="gray") + plt.axis("off") + plt.title("mask") + plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9) + + + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_connect_measurements_001.png + :alt: sig, mask + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_connect_measurements_001.png + :class: sphx-glr-single-img + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 36-37 + +Label connected components + +.. GENERATED FROM PYTHON SOURCE LINES 37-49 + +.. code-block:: Python + + import scipy as sp + + labels, nb = sp.ndimage.label(mask) + + plt.figure(figsize=(3.5, 3.5)) + plt.imshow(labels) + plt.title("label") + plt.axis("off") + + plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9) + + + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_connect_measurements_002.png + :alt: label + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_connect_measurements_002.png + :class: sphx-glr-single-img + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 50-51 + +Extract the 4th connected component, and crop the array around it + +.. GENERATED FROM PYTHON SOURCE LINES 51-60 + +.. code-block:: Python + + sl = sp.ndimage.find_objects(labels == 4) + plt.figure(figsize=(3.5, 3.5)) + plt.imshow(sig[sl[0]]) + plt.title("Cropped connected component") + plt.axis("off") + + plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9) + + plt.show() + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_connect_measurements_003.png + :alt: Cropped connected component + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_connect_measurements_003.png + :class: sphx-glr-single-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.114 seconds) + + +.. _sphx_glr_download_intro_scipy_auto_examples_plot_connect_measurements.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_connect_measurements.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_connect_measurements.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_connect_measurements.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/plot_curve_fit.rst.txt b/_sources/intro/scipy/auto_examples/plot_curve_fit.rst.txt new file mode 100644 index 000000000..565f49c33 --- /dev/null +++ b/_sources/intro/scipy/auto_examples/plot_curve_fit.rst.txt @@ -0,0 +1,160 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/auto_examples/plot_curve_fit.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_auto_examples_plot_curve_fit.py: + + +=============== +Curve fitting +=============== + +Demos a simple curve fitting + +.. GENERATED FROM PYTHON SOURCE LINES 10-11 + +First generate some data + +.. GENERATED FROM PYTHON SOURCE LINES 11-27 + +.. code-block:: Python + + import numpy as np + + # Seed the random number generator for reproducibility + rng = np.random.default_rng(27446968) + + x_data = np.linspace(-5, 5, num=50) + noise = 0.01 * np.cos(100 * x_data) + a, b = 2.9, 1.5 + y_data = a * np.cos(b * x_data) + noise + + # And plot it + import matplotlib.pyplot as plt + + plt.figure(figsize=(6, 4)) + plt.scatter(x_data, y_data) + + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_curve_fit_001.png + :alt: plot curve fit + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_curve_fit_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 28-29 + +Now fit a simple sine function to the data + +.. GENERATED FROM PYTHON SOURCE LINES 29-42 + +.. code-block:: Python + + import scipy as sp + + + def test_func(x, a, b, c): + return a * np.sin(b * x + c) + + + params, params_covariance = sp.optimize.curve_fit( + test_func, x_data, y_data, p0=[2, 1, 3] + ) + + print(params) + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + [2.900026 1.50012043 1.57079633] + + + + +.. GENERATED FROM PYTHON SOURCE LINES 43-44 + +And plot the resulting curve on the data + +.. GENERATED FROM PYTHON SOURCE LINES 44-52 + +.. code-block:: Python + + + plt.figure(figsize=(6, 4)) + plt.scatter(x_data, y_data, label="Data") + plt.plot(x_data, test_func(x_data, *params), label="Fitted function") + + plt.legend(loc="best") + + plt.show() + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_curve_fit_002.png + :alt: plot curve fit + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_curve_fit_002.png + :class: sphx-glr-single-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.114 seconds) + + +.. _sphx_glr_download_intro_scipy_auto_examples_plot_curve_fit.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_curve_fit.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_curve_fit.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_curve_fit.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/plot_detrend.rst.txt b/_sources/intro/scipy/auto_examples/plot_detrend.rst.txt new file mode 100644 index 000000000..0d5f988fb --- /dev/null +++ b/_sources/intro/scipy/auto_examples/plot_detrend.rst.txt @@ -0,0 +1,123 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/auto_examples/plot_detrend.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_auto_examples_plot_detrend.py: + + +=================== +Detrending a signal +=================== + +:func:`scipy.signal.detrend` removes a linear trend. + +.. GENERATED FROM PYTHON SOURCE LINES 10-11 + +Generate a random signal with a trend + +.. GENERATED FROM PYTHON SOURCE LINES 11-17 + +.. code-block:: Python + + import numpy as np + + t = np.linspace(0, 5, 100) + rng = np.random.default_rng() + x = t + rng.normal(size=100) + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 18-19 + +Detrend + +.. GENERATED FROM PYTHON SOURCE LINES 19-23 + +.. code-block:: Python + + import scipy as sp + + x_detrended = sp.signal.detrend(x) + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 24-25 + +Plot + +.. GENERATED FROM PYTHON SOURCE LINES 25-32 + +.. code-block:: Python + + import matplotlib.pyplot as plt + + plt.figure(figsize=(5, 4)) + plt.plot(t, x, label="x") + plt.plot(t, x_detrended, label="x_detrended") + plt.legend(loc="best") + plt.show() + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_detrend_001.png + :alt: plot detrend + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_detrend_001.png + :class: sphx-glr-single-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.055 seconds) + + +.. _sphx_glr_download_intro_scipy_auto_examples_plot_detrend.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_detrend.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_detrend.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_detrend.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/plot_fftpack.rst.txt b/_sources/intro/scipy/auto_examples/plot_fftpack.rst.txt new file mode 100644 index 000000000..7666ef2b5 --- /dev/null +++ b/_sources/intro/scipy/auto_examples/plot_fftpack.rst.txt @@ -0,0 +1,245 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/auto_examples/plot_fftpack.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_auto_examples_plot_fftpack.py: + + +============================================= +Plotting and manipulating FFTs for filtering +============================================= + +Plot the power of the FFT of a signal and inverse FFT back to reconstruct +a signal. + +This example demonstrate :func:`scipy.fft.fft`, +:func:`scipy.fft.fftfreq` and :func:`scipy.fft.ifft`. It +implements a basic filter that is very suboptimal, and should not be +used. + +.. GENERATED FROM PYTHON SOURCE LINES 15-20 + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 21-23 + +Generate the signal +########################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 23-36 + +.. code-block:: Python + + + # Seed the random number generator + rng = np.random.default_rng(27446968) + + time_step = 0.02 + period = 5.0 + + time_vec = np.arange(0, 20, time_step) + sig = np.sin(2 * np.pi / period * time_vec) + 0.5 * rng.normal(size=time_vec.size) + + plt.figure(figsize=(6, 5)) + plt.plot(time_vec, sig, label="Original signal") + + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_fftpack_001.png + :alt: plot fftpack + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_fftpack_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + [] + + + +.. GENERATED FROM PYTHON SOURCE LINES 37-39 + +Compute and plot the power +########################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 39-73 + +.. code-block:: Python + + + # The FFT of the signal + sig_fft = sp.fft.fft(sig) + + # And the power (sig_fft is of complex dtype) + power = np.abs(sig_fft) ** 2 + + # The corresponding frequencies + sample_freq = sp.fft.fftfreq(sig.size, d=time_step) + + # Plot the FFT power + plt.figure(figsize=(6, 5)) + plt.plot(sample_freq, power) + plt.xlabel("Frequency [Hz]") + plt.ylabel("plower") + + # Find the peak frequency: we can focus on only the positive frequencies + pos_mask = np.where(sample_freq > 0) + freqs = sample_freq[pos_mask] + peak_freq = freqs[power[pos_mask].argmax()] + + # Check that it does indeed correspond to the frequency that we generate + # the signal with + np.allclose(peak_freq, 1.0 / period) + + # An inner plot to show the peak frequency + axes = plt.axes((0.55, 0.3, 0.3, 0.5)) + plt.title("Peak frequency") + plt.plot(freqs[:8], power[pos_mask][:8]) + plt.setp(axes, yticks=[]) + + # scipy.signal.find_peaks_cwt can also be used for more advanced + # peak detection + + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_fftpack_002.png + :alt: Peak frequency + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_fftpack_002.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + [] + + + +.. GENERATED FROM PYTHON SOURCE LINES 74-79 + +Remove all the high frequencies +########################################################### + + We now remove all the high frequencies and transform back from + frequencies to signal. + +.. GENERATED FROM PYTHON SOURCE LINES 79-92 + +.. code-block:: Python + + + high_freq_fft = sig_fft.copy() + high_freq_fft[np.abs(sample_freq) > peak_freq] = 0 + filtered_sig = sp.fft.ifft(high_freq_fft) + + plt.figure(figsize=(6, 5)) + plt.plot(time_vec, sig, label="Original signal") + plt.plot(time_vec, filtered_sig, linewidth=3, label="Filtered signal") + plt.xlabel("Time [s]") + plt.ylabel("Amplitude") + + plt.legend(loc="best") + + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_fftpack_003.png + :alt: plot fftpack + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_fftpack_003.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + /opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages/matplotlib/cbook.py:1762: ComplexWarning: Casting complex values to real discards the imaginary part + return math.isfinite(val) + /opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages/matplotlib/cbook.py:1398: ComplexWarning: Casting complex values to real discards the imaginary part + return np.asarray(x, float) + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 93-97 + +**Note** This is actually a bad way of creating a filter: such brutal +cut-off in frequency space does not control distortion on the signal. + +Filters should be created using the SciPy filter design code + +.. GENERATED FROM PYTHON SOURCE LINES 98-99 + +.. code-block:: Python + + plt.show() + + + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.203 seconds) + + +.. _sphx_glr_download_intro_scipy_auto_examples_plot_fftpack.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_fftpack.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_fftpack.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_fftpack.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/plot_image_filters.rst.txt b/_sources/intro/scipy/auto_examples/plot_image_filters.rst.txt new file mode 100644 index 000000000..01d5e630d --- /dev/null +++ b/_sources/intro/scipy/auto_examples/plot_image_filters.rst.txt @@ -0,0 +1,115 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/auto_examples/plot_image_filters.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_auto_examples_plot_image_filters.py: + + +========================= +Plot filtering on images +========================= + +Demo filtering for denoising of images. + +.. GENERATED FROM PYTHON SOURCE LINES 8-51 + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_image_filters_001.png + :alt: noisy, Gaussian filter, median filter, Wiener filter + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_image_filters_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + # Load some data + import scipy as sp + + face = sp.datasets.face(gray=True) + face = face[:512, -512:] # crop out square on right + + # Apply a variety of filters + import matplotlib.pyplot as plt + + import numpy as np + + noisy_face = np.copy(face).astype(float) + rng = np.random.default_rng() + noisy_face += face.std() * 0.5 * rng.standard_normal(face.shape) + blurred_face = sp.ndimage.gaussian_filter(noisy_face, sigma=3) + median_face = sp.ndimage.median_filter(noisy_face, size=5) + wiener_face = sp.signal.wiener(noisy_face, (5, 5)) + + plt.figure(figsize=(12, 3.5)) + plt.subplot(141) + plt.imshow(noisy_face, cmap="gray") + plt.axis("off") + plt.title("noisy") + + plt.subplot(142) + plt.imshow(blurred_face, cmap="gray") + plt.axis("off") + plt.title("Gaussian filter") + + plt.subplot(143) + plt.imshow(median_face, cmap="gray") + plt.axis("off") + plt.title("median filter") + + plt.subplot(144) + plt.imshow(wiener_face, cmap="gray") + plt.title("Wiener filter") + plt.axis("off") + + plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.458 seconds) + + +.. _sphx_glr_download_intro_scipy_auto_examples_plot_image_filters.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_image_filters.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_image_filters.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_image_filters.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/plot_image_transform.rst.txt b/_sources/intro/scipy/auto_examples/plot_image_transform.rst.txt new file mode 100644 index 000000000..86637977d --- /dev/null +++ b/_sources/intro/scipy/auto_examples/plot_image_transform.rst.txt @@ -0,0 +1,122 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/auto_examples/plot_image_transform.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_auto_examples_plot_image_transform.py: + + +============================================ +Plot geometrical transformations on images +============================================ + +Demo geometrical transformations of images. + +.. GENERATED FROM PYTHON SOURCE LINES 8-48 + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_image_transform_001.png + :alt: plot image transform + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_image_transform_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + Downloading file 'face.dat' from 'https://raw.githubusercontent.com/scipy/dataset-face/main/face.dat' to '/home/runner/.cache/scipy-data'. + + + + + + +| + +.. code-block:: Python + + + # Load some data + import scipy as sp + + face = sp.datasets.face(gray=True) + + # Apply a variety of transformations + import matplotlib.pyplot as plt + + shifted_face = sp.ndimage.shift(face, (50, 50)) + shifted_face2 = sp.ndimage.shift(face, (50, 50), mode="nearest") + rotated_face = sp.ndimage.rotate(face, 30) + cropped_face = face[50:-50, 50:-50] + zoomed_face = sp.ndimage.zoom(face, 2) + zoomed_face.shape + + plt.figure(figsize=(15, 3)) + plt.subplot(151) + plt.imshow(shifted_face, cmap="gray") + plt.axis("off") + + plt.subplot(152) + plt.imshow(shifted_face2, cmap="gray") + plt.axis("off") + + plt.subplot(153) + plt.imshow(rotated_face, cmap="gray") + plt.axis("off") + + plt.subplot(154) + plt.imshow(cropped_face, cmap="gray") + plt.axis("off") + + plt.subplot(155) + plt.imshow(zoomed_face, cmap="gray") + plt.axis("off") + + plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.975 seconds) + + +.. _sphx_glr_download_intro_scipy_auto_examples_plot_image_transform.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_image_transform.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_image_transform.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_image_transform.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/plot_interpolation.rst.txt b/_sources/intro/scipy/auto_examples/plot_interpolation.rst.txt new file mode 100644 index 000000000..b1e5cde25 --- /dev/null +++ b/_sources/intro/scipy/auto_examples/plot_interpolation.rst.txt @@ -0,0 +1,137 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/auto_examples/plot_interpolation.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_auto_examples_plot_interpolation.py: + + +============================ +A demo of 1D interpolation +============================ + +.. GENERATED FROM PYTHON SOURCE LINES 7-55 + + + +.. rst-class:: sphx-glr-horizontal + + + * + + .. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_interpolation_001.png + :alt: plot interpolation + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_interpolation_001.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_interpolation_002.png + :alt: plot interpolation + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_interpolation_002.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_interpolation_003.png + :alt: plot interpolation + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_interpolation_003.png + :class: sphx-glr-multi-img + + + + + +.. code-block:: Python + + + # Generate data + import numpy as np + + rng = np.random.default_rng(27446968) + measured_time = np.linspace(0, 2 * np.pi, 20) + function = np.sin(measured_time) + noise = rng.normal(loc=0, scale=0.1, size=20) + measurements = function + noise + + # Smooth the curve and interpolate at new times + import scipy as sp + + smoothing_spline = sp.interpolate.make_smoothing_spline(measured_time, measurements) + interpolation_time = np.linspace(0, 2 * np.pi, 200) + smooth_results = smoothing_spline(interpolation_time) + + # Plot the data, the interpolant, and the original function + import matplotlib.pyplot as plt + + plt.figure(figsize=(6, 4)) + plt.plot(measured_time, measurements, ".", ms=6, label="measurements") + plt.plot(interpolation_time, smooth_results, label="smoothing spline") + plt.plot(interpolation_time, np.sin(interpolation_time), "--", label="underlying curve") + plt.legend() + plt.show() + + # Fit the data exactly + interp_spline = sp.interpolate.make_interp_spline(measured_time, function) + interp_results = interp_spline(interpolation_time) + + # Plot the data, the interpolant, and the original function + plt.figure(figsize=(6, 4)) + plt.plot(measured_time, function, ".", ms=6, label="measurements") + plt.plot(interpolation_time, interp_results, label="interpolating spline") + plt.plot(interpolation_time, np.sin(interpolation_time), "--", label="underlying curve") + plt.legend() + plt.show() + + # Plot interpolant, its derivative, and its antiderivative + plt.figure(figsize=(6, 4)) + t = interpolation_time + plt.plot(t, interp_spline(t), label="spline") + plt.plot(t, interp_spline.derivative()(t), label="derivative") + plt.plot(t, interp_spline.antiderivative()(t) - 1, label="antiderivative") + + plt.legend() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.202 seconds) + + +.. _sphx_glr_download_intro_scipy_auto_examples_plot_interpolation.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_interpolation.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_interpolation.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_interpolation.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/plot_mathematical_morpho.rst.txt b/_sources/intro/scipy/auto_examples/plot_mathematical_morpho.rst.txt new file mode 100644 index 000000000..afa9ea003 --- /dev/null +++ b/_sources/intro/scipy/auto_examples/plot_mathematical_morpho.rst.txt @@ -0,0 +1,115 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/auto_examples/plot_mathematical_morpho.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_auto_examples_plot_mathematical_morpho.py: + + +============================= +Demo mathematical morphology +============================= + +A basic demo of binary opening and closing. + +.. GENERATED FROM PYTHON SOURCE LINES 8-51 + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_mathematical_morpho_001.png + :alt: a, mask, opened_mask, closed_mask + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_mathematical_morpho_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + # Generate some binary data + import numpy as np + + np.random.seed(0) + a = np.zeros((50, 50)) + a[10:-10, 10:-10] = 1 + a += 0.25 * np.random.standard_normal(a.shape) + mask = a >= 0.5 + + # Apply mathematical morphology + import scipy as sp + + opened_mask = sp.ndimage.binary_opening(mask) + closed_mask = sp.ndimage.binary_closing(opened_mask) + + # Plot + import matplotlib.pyplot as plt + + plt.figure(figsize=(12, 3.5)) + plt.subplot(141) + plt.imshow(a, cmap="gray") + plt.axis("off") + plt.title("a") + + plt.subplot(142) + plt.imshow(mask, cmap="gray") + plt.axis("off") + plt.title("mask") + + plt.subplot(143) + plt.imshow(opened_mask, cmap="gray") + plt.axis("off") + plt.title("opened_mask") + + plt.subplot(144) + plt.imshow(closed_mask, cmap="gray") + plt.title("closed_mask") + plt.axis("off") + + plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.098 seconds) + + +.. _sphx_glr_download_intro_scipy_auto_examples_plot_mathematical_morpho.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_mathematical_morpho.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_mathematical_morpho.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_mathematical_morpho.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/plot_normal_distribution.rst.txt b/_sources/intro/scipy/auto_examples/plot_normal_distribution.rst.txt new file mode 100644 index 000000000..cb1bf08e8 --- /dev/null +++ b/_sources/intro/scipy/auto_examples/plot_normal_distribution.rst.txt @@ -0,0 +1,91 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/auto_examples/plot_normal_distribution.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_auto_examples_plot_normal_distribution.py: + + +======================================= +Normal distribution: histogram and PDF +======================================= + +Explore the normal distribution: a histogram built from samples and the +PDF (probability density function). + +.. GENERATED FROM PYTHON SOURCE LINES 9-27 + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_normal_distribution_001.png + :alt: plot normal distribution + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_normal_distribution_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + dist = sp.stats.norm(loc=0, scale=1) # standard normal distribution + sample = dist.rvs(size=100000) # "random variate sample" + plt.hist( + sample, + bins=51, # group the observations into 50 bins + density=True, # normalize the frequencies + label="normalized histogram", + ) + + x = np.linspace(-5, 5) # possible values of the random variable + plt.plot(x, dist.pdf(x), label="PDF") + plt.legend() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.101 seconds) + + +.. _sphx_glr_download_intro_scipy_auto_examples_plot_normal_distribution.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_normal_distribution.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_normal_distribution.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_normal_distribution.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/plot_optimize_example1.rst.txt b/_sources/intro/scipy/auto_examples/plot_optimize_example1.rst.txt new file mode 100644 index 000000000..5f8079c44 --- /dev/null +++ b/_sources/intro/scipy/auto_examples/plot_optimize_example1.rst.txt @@ -0,0 +1,138 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/auto_examples/plot_optimize_example1.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_auto_examples_plot_optimize_example1.py: + + +========================================= +Finding the minimum of a smooth function +========================================= + +Demos various methods to find the minimum of a function. + +.. GENERATED FROM PYTHON SOURCE LINES 8-20 + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + + def f(x): + return x**2 + 10 * np.sin(x) + + + x = np.arange(-5, 5, 0.1) + plt.plot(x, f(x)) + + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_optimize_example1_001.png + :alt: plot optimize example1 + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_optimize_example1_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + [] + + + +.. GENERATED FROM PYTHON SOURCE LINES 21-22 + +Now find the minimum with a few methods + +.. GENERATED FROM PYTHON SOURCE LINES 22-27 + +.. code-block:: Python + + import scipy as sp + + # The default (Nelder Mead) + print(sp.optimize.minimize(f, x0=0)) + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + message: Optimization terminated successfully. + success: True + status: 0 + fun: -7.945823375615215 + x: [-1.306e+00] + nit: 5 + jac: [-1.192e-06] + hess_inv: [[ 8.589e-02]] + nfev: 12 + njev: 6 + + + + +.. GENERATED FROM PYTHON SOURCE LINES 28-30 + +.. code-block:: Python + + + plt.show() + + + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.048 seconds) + + +.. _sphx_glr_download_intro_scipy_auto_examples_plot_optimize_example1.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_optimize_example1.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_optimize_example1.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_optimize_example1.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/plot_optimize_example2.rst.txt b/_sources/intro/scipy/auto_examples/plot_optimize_example2.rst.txt new file mode 100644 index 000000000..2a4b9fca6 --- /dev/null +++ b/_sources/intro/scipy/auto_examples/plot_optimize_example2.rst.txt @@ -0,0 +1,190 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/auto_examples/plot_optimize_example2.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_auto_examples_plot_optimize_example2.py: + + +=============================== +Minima and roots of a function +=============================== + +Demos finding minima and roots of a function. + +.. GENERATED FROM PYTHON SOURCE LINES 10-12 + +Define the function +########################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 12-22 + +.. code-block:: Python + + + import numpy as np + + x = np.arange(-10, 10, 0.1) + + + def f(x): + return x**2 + 10 * np.sin(x) + + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 23-25 + +Find minima +########################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 25-37 + +.. code-block:: Python + + + import scipy as sp + + # Global optimization + grid = (-10, 10, 0.1) + xmin_global = sp.optimize.brute(f, (grid,)) + print(f"Global minima found {xmin_global}") + + # Constrain optimization + xmin_local = sp.optimize.fminbound(f, 0, 10) + print(f"Local minimum found {xmin_local}") + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + Global minima found [-1.30641113] + Local minimum found 3.8374671194983834 + + + + +.. GENERATED FROM PYTHON SOURCE LINES 38-40 + +Root finding +########################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 40-46 + +.. code-block:: Python + + + root = sp.optimize.root(f, 1) # our initial guess is 1 + print(f"First root found {root.x}") + root2 = sp.optimize.root(f, -2.5) + print(f"Second root found {root2.x}") + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + First root found [0.] + Second root found [-2.47948183] + + + + +.. GENERATED FROM PYTHON SOURCE LINES 47-49 + +Plot function, minima, and roots +########################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 49-72 + +.. code-block:: Python + + + import matplotlib.pyplot as plt + + fig = plt.figure(figsize=(6, 4)) + ax = fig.add_subplot(111) + + # Plot the function + ax.plot(x, f(x), "b-", label="f(x)") + + # Plot the minima + xmins = np.array([xmin_global[0], xmin_local]) + ax.plot(xmins, f(xmins), "go", label="Minima") + + # Plot the roots + roots = np.array([root.x, root2.x]) + ax.plot(roots, f(roots), "kv", label="Roots") + + # Decorate the figure + ax.legend(loc="best") + ax.set_xlabel("x") + ax.set_ylabel("f(x)") + ax.axhline(0, color="gray") + plt.show() + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_optimize_example2_001.png + :alt: plot optimize example2 + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_optimize_example2_001.png + :class: sphx-glr-single-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.070 seconds) + + +.. _sphx_glr_download_intro_scipy_auto_examples_plot_optimize_example2.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_optimize_example2.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_optimize_example2.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_optimize_example2.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/plot_resample.rst.txt b/_sources/intro/scipy/auto_examples/plot_resample.rst.txt new file mode 100644 index 000000000..f10923752 --- /dev/null +++ b/_sources/intro/scipy/auto_examples/plot_resample.rst.txt @@ -0,0 +1,122 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/auto_examples/plot_resample.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_auto_examples_plot_resample.py: + + +Resample a signal with scipy.signal.resample +============================================= + +:func:`scipy.signal.resample` uses FFT to resample a 1D signal. + +.. GENERATED FROM PYTHON SOURCE LINES 9-10 + +Generate a signal with 100 data point + +.. GENERATED FROM PYTHON SOURCE LINES 10-15 + +.. code-block:: Python + + import numpy as np + + t = np.linspace(0, 5, 100) + x = np.sin(t) + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 16-17 + +Downsample it by a factor of 4 + +.. GENERATED FROM PYTHON SOURCE LINES 17-21 + +.. code-block:: Python + + import scipy as sp + + x_resampled = sp.signal.resample(x, 25) + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 22-23 + +Plot + +.. GENERATED FROM PYTHON SOURCE LINES 23-31 + +.. code-block:: Python + + import matplotlib.pyplot as plt + + plt.figure(figsize=(5, 4)) + plt.plot(t, x, label="Original signal") + plt.plot(t[::4], x_resampled, "ko", label="Resampled signal") + + plt.legend(loc="best") + plt.show() + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_resample_001.png + :alt: plot resample + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_resample_001.png + :class: sphx-glr-single-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.246 seconds) + + +.. _sphx_glr_download_intro_scipy_auto_examples_plot_resample.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_resample.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_resample.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_resample.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/plot_solve_ivp_damped_spring_mass.rst.txt b/_sources/intro/scipy/auto_examples/plot_solve_ivp_damped_spring_mass.rst.txt new file mode 100644 index 000000000..adfb65eae --- /dev/null +++ b/_sources/intro/scipy/auto_examples/plot_solve_ivp_damped_spring_mass.rst.txt @@ -0,0 +1,99 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/auto_examples/plot_solve_ivp_damped_spring_mass.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_auto_examples_plot_solve_ivp_damped_spring_mass.py: + + +============================================ +Integrate the Damped spring-mass oscillator +============================================ + +.. GENERATED FROM PYTHON SOURCE LINES 8-37 + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_solve_ivp_damped_spring_mass_001.png + :alt: plot solve ivp damped spring mass + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_solve_ivp_damped_spring_mass_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + m = 0.5 # kg + k = 4 # N/m + c = 0.4 # N s/m + + zeta = c / (2 * m * np.sqrt(k / m)) + omega = np.sqrt(k / m) + + + def f(t, z, zeta, omega): + return (z[1], -zeta * omega * z[1] - omega**2 * z[0]) + + + t_span = (0, 10) + t_eval = np.linspace(*t_span, 100) + z0 = [1, 0] + res = sp.integrate.solve_ivp( + f, t_span, z0, t_eval=t_eval, args=(zeta, omega), method="LSODA" + ) + + plt.figure(figsize=(4, 3)) + plt.plot(res.t, res.y[0], label="y") + plt.plot(res.t, res.y[1], label="dy/dt") + plt.legend(loc="best") + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.052 seconds) + + +.. _sphx_glr_download_intro_scipy_auto_examples_plot_solve_ivp_damped_spring_mass.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_solve_ivp_damped_spring_mass.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_solve_ivp_damped_spring_mass.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_solve_ivp_damped_spring_mass.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/plot_solve_ivp_simple.rst.txt b/_sources/intro/scipy/auto_examples/plot_solve_ivp_simple.rst.txt new file mode 100644 index 000000000..9fe861e62 --- /dev/null +++ b/_sources/intro/scipy/auto_examples/plot_solve_ivp_simple.rst.txt @@ -0,0 +1,97 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/auto_examples/plot_solve_ivp_simple.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_auto_examples_plot_solve_ivp_simple.py: + + +========================= +Integrating a simple ODE +========================= + +Solve the ODE dy/dt = -2y between t = 0..4, with the initial condition +y(t=0) = 1. + +.. GENERATED FROM PYTHON SOURCE LINES 9-33 + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_solve_ivp_simple_001.png + :alt: Solution of Initial Value Problem + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_solve_ivp_simple_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + + def f(t, y): + return -2 * y + + + t_span = (0, 4) # time interval + t_eval = np.linspace(*t_span) # times at which to evaluate `y` + y0 = [ + 1, + ] # initial state + res = sp.integrate.solve_ivp(f, t_span=t_span, y0=y0, t_eval=t_eval) + + plt.figure(figsize=(4, 3)) + plt.plot(res.t, res.y[0]) + plt.xlabel("t") + plt.ylabel("y") + plt.title("Solution of Initial Value Problem") + plt.tight_layout() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.080 seconds) + + +.. _sphx_glr_download_intro_scipy_auto_examples_plot_solve_ivp_simple.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_solve_ivp_simple.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_solve_ivp_simple.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_solve_ivp_simple.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/plot_spectrogram.rst.txt b/_sources/intro/scipy/auto_examples/plot_spectrogram.rst.txt new file mode 100644 index 000000000..ecd25ac8e --- /dev/null +++ b/_sources/intro/scipy/auto_examples/plot_spectrogram.rst.txt @@ -0,0 +1,193 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/auto_examples/plot_spectrogram.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_auto_examples_plot_spectrogram.py: + + +====================================== +Spectrogram, power spectral density +====================================== + +Demo spectrogram and power spectral density on a frequency chirp. + +.. GENERATED FROM PYTHON SOURCE LINES 8-12 + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 13-15 + +Generate a chirp signal +########################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 15-28 + +.. code-block:: Python + + + # Seed the random number generator + np.random.seed(0) + + time_step = 0.01 + time_vec = np.arange(0, 70, time_step) + + # A signal with a small frequency chirp + sig = np.sin(0.5 * np.pi * time_vec * (1 + 0.1 * time_vec)) + + plt.figure(figsize=(8, 5)) + plt.plot(time_vec, sig) + + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_spectrogram_001.png + :alt: plot spectrogram + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_spectrogram_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + [] + + + +.. GENERATED FROM PYTHON SOURCE LINES 29-33 + +Compute and plot the spectrogram +########################################################### + + The spectrum of the signal on consecutive time windows + +.. GENERATED FROM PYTHON SOURCE LINES 33-46 + +.. code-block:: Python + + + import scipy as sp + + freqs, times, spectrogram = sp.signal.spectrogram(sig) + + plt.figure(figsize=(5, 4)) + plt.imshow(spectrogram, aspect="auto", cmap="hot_r", origin="lower") + plt.title("Spectrogram") + plt.ylabel("Frequency band") + plt.xlabel("Time window") + plt.tight_layout() + + + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_spectrogram_002.png + :alt: Spectrogram + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_spectrogram_002.png + :class: sphx-glr-single-img + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 47-51 + +Compute and plot the power spectral density (PSD) +########################################################### + + The power of the signal per frequency band + +.. GENERATED FROM PYTHON SOURCE LINES 51-61 + +.. code-block:: Python + + + freqs, psd = sp.signal.welch(sig) + + plt.figure(figsize=(5, 4)) + plt.semilogx(freqs, psd) + plt.title("PSD: power spectral density") + plt.xlabel("Frequency") + plt.ylabel("Power") + plt.tight_layout() + + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_spectrogram_003.png + :alt: PSD: power spectral density + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_spectrogram_003.png + :class: sphx-glr-single-img + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 62-64 + +.. code-block:: Python + + + plt.show() + + + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.350 seconds) + + +.. _sphx_glr_download_intro_scipy_auto_examples_plot_spectrogram.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_spectrogram.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_spectrogram.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_spectrogram.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/plot_t_test.rst.txt b/_sources/intro/scipy/auto_examples/plot_t_test.rst.txt new file mode 100644 index 000000000..a09d4a20c --- /dev/null +++ b/_sources/intro/scipy/auto_examples/plot_t_test.rst.txt @@ -0,0 +1,89 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/auto_examples/plot_t_test.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_auto_examples_plot_t_test.py: + + +========================================== +Comparing 2 sets of samples from Gaussians +========================================== + +.. GENERATED FROM PYTHON SOURCE LINES 7-26 + + + +.. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_t_test_001.png + :alt: plot t test + :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_t_test_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + # Generates 2 sets of observations + rng = np.random.default_rng(27446968) + samples1 = rng.normal(0, size=1000) + samples2 = rng.normal(1, size=1000) + + # Compute a histogram of the sample + bins = np.linspace(-4, 4, 30) + histogram1, bins = np.histogram(samples1, bins=bins, density=True) + histogram2, bins = np.histogram(samples2, bins=bins, density=True) + + plt.figure(figsize=(6, 4)) + plt.hist(samples1, bins=bins, density=True, label="Samples 1") # type: ignore[arg-type] + plt.hist(samples2, bins=bins, density=True, label="Samples 2") # type: ignore[arg-type] + plt.legend(loc="best") + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.104 seconds) + + +.. _sphx_glr_download_intro_scipy_auto_examples_plot_t_test.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_t_test.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_t_test.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_t_test.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/sg_execution_times.rst.txt b/_sources/intro/scipy/auto_examples/sg_execution_times.rst.txt new file mode 100644 index 000000000..4e995a0f9 --- /dev/null +++ b/_sources/intro/scipy/auto_examples/sg_execution_times.rst.txt @@ -0,0 +1,85 @@ + +:orphan: + +.. _sphx_glr_intro_scipy_auto_examples_sg_execution_times: + + +Computation times +================= +**00:03.592** total execution time for 17 files **from intro/scipy/auto_examples**: + +.. container:: + + .. raw:: html + + + + + + + + .. list-table:: + :header-rows: 1 + :class: table table-striped sg-datatable + + * - Example + - Time + - Mem (MB) + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_image_transform.py` (``plot_image_transform.py``) + - 00:00.975 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_image_filters.py` (``plot_image_filters.py``) + - 00:00.458 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_spectrogram.py` (``plot_spectrogram.py``) + - 00:00.350 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_2d_minimization.py` (``plot_2d_minimization.py``) + - 00:00.324 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_resample.py` (``plot_resample.py``) + - 00:00.246 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_fftpack.py` (``plot_fftpack.py``) + - 00:00.203 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_interpolation.py` (``plot_interpolation.py``) + - 00:00.202 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_connect_measurements.py` (``plot_connect_measurements.py``) + - 00:00.114 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_curve_fit.py` (``plot_curve_fit.py``) + - 00:00.114 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_t_test.py` (``plot_t_test.py``) + - 00:00.104 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_normal_distribution.py` (``plot_normal_distribution.py``) + - 00:00.101 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_mathematical_morpho.py` (``plot_mathematical_morpho.py``) + - 00:00.098 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_solve_ivp_simple.py` (``plot_solve_ivp_simple.py``) + - 00:00.080 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_optimize_example2.py` (``plot_optimize_example2.py``) + - 00:00.070 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_detrend.py` (``plot_detrend.py``) + - 00:00.055 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_solve_ivp_damped_spring_mass.py` (``plot_solve_ivp_damped_spring_mass.py``) + - 00:00.052 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_optimize_example1.py` (``plot_optimize_example1.py``) + - 00:00.048 + - 0.0 diff --git a/_sources/intro/scipy/auto_examples/solutions/index.rst.txt b/_sources/intro/scipy/auto_examples/solutions/index.rst.txt new file mode 100644 index 000000000..3aaa18485 --- /dev/null +++ b/_sources/intro/scipy/auto_examples/solutions/index.rst.txt @@ -0,0 +1,98 @@ + + +.. _sphx_glr_intro_scipy_auto_examples_solutions: + +Solutions of the exercises for SciPy +.................................... + + + +.. raw:: html + +
+ +.. thumbnail-parent-div-open + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/solutions/images/thumb/sphx_glr_plot_periodicity_finder_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_solutions_plot_periodicity_finder.py` + +.. raw:: html + +
Crude periodicity finding
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/solutions/images/thumb/sphx_glr_plot_curvefit_temperature_data_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_solutions_plot_curvefit_temperature_data.py` + +.. raw:: html + +
Curve fitting: temperature as a function of month of the year
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/solutions/images/thumb/sphx_glr_plot_image_blur_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_solutions_plot_image_blur.py` + +.. raw:: html + +
Simple image blur by convolution with a Gaussian kernel
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/auto_examples/solutions/images/thumb/sphx_glr_plot_fft_image_denoise_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_auto_examples_solutions_plot_fft_image_denoise.py` + +.. raw:: html + +
Image denoising by FFT
+
+ + +.. thumbnail-parent-div-close + +.. raw:: html + +
+ + +.. toctree:: + :hidden: + + /intro/scipy/auto_examples/solutions/plot_periodicity_finder + /intro/scipy/auto_examples/solutions/plot_curvefit_temperature_data + /intro/scipy/auto_examples/solutions/plot_image_blur + /intro/scipy/auto_examples/solutions/plot_fft_image_denoise + diff --git a/_sources/intro/scipy/auto_examples/solutions/plot_curvefit_temperature_data.rst.txt b/_sources/intro/scipy/auto_examples/solutions/plot_curvefit_temperature_data.rst.txt new file mode 100644 index 000000000..f9febdcae --- /dev/null +++ b/_sources/intro/scipy/auto_examples/solutions/plot_curvefit_temperature_data.rst.txt @@ -0,0 +1,159 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/auto_examples/solutions/plot_curvefit_temperature_data.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_auto_examples_solutions_plot_curvefit_temperature_data.py: + + +============================================================== +Curve fitting: temperature as a function of month of the year +============================================================== + +We have the min and max temperatures in Alaska for each months of the +year. We would like to find a function to describe this yearly evolution. + +For this, we will fit a periodic function. + +.. GENERATED FROM PYTHON SOURCE LINES 13-15 + +The data +########################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 15-28 + +.. code-block:: Python + + import numpy as np + + temp_max = np.array([17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18]) + temp_min = np.array([-62, -59, -56, -46, -32, -18, -9, -13, -25, -46, -52, -58]) + + import matplotlib.pyplot as plt + + months = np.arange(12) + plt.plot(months, temp_max, "ro") + plt.plot(months, temp_min, "bo") + plt.xlabel("Month") + plt.ylabel("Min and max temperature") + + + + +.. image-sg:: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_curvefit_temperature_data_001.png + :alt: plot curvefit temperature data + :srcset: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_curvefit_temperature_data_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + Text(35.472222222222214, 0.5, 'Min and max temperature') + + + +.. GENERATED FROM PYTHON SOURCE LINES 29-31 + +Fitting it to a periodic function +########################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 31-42 + +.. code-block:: Python + + + import scipy as sp + + + def yearly_temps(times, avg, ampl, time_offset): + return avg + ampl * np.cos((times + time_offset) * 2 * np.pi / times.max()) + + + res_max, cov_max = sp.optimize.curve_fit(yearly_temps, months, temp_max, [20, 10, 0]) + res_min, cov_min = sp.optimize.curve_fit(yearly_temps, months, temp_min, [-40, 20, 0]) + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 43-45 + +Plotting the fit +########################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 45-57 + +.. code-block:: Python + + + days = np.linspace(0, 12, num=365) + + plt.figure() + plt.plot(months, temp_max, "ro") + plt.plot(days, yearly_temps(days, *res_max), "r-") + plt.plot(months, temp_min, "bo") + plt.plot(days, yearly_temps(days, *res_min), "b-") + plt.xlabel("Month") + plt.ylabel(r"Temperature ($^\circ$C)") + + plt.show() + + + +.. image-sg:: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_curvefit_temperature_data_002.png + :alt: plot curvefit temperature data + :srcset: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_curvefit_temperature_data_002.png + :class: sphx-glr-single-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.108 seconds) + + +.. _sphx_glr_download_intro_scipy_auto_examples_solutions_plot_curvefit_temperature_data.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_curvefit_temperature_data.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_curvefit_temperature_data.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_curvefit_temperature_data.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/solutions/plot_fft_image_denoise.rst.txt b/_sources/intro/scipy/auto_examples/solutions/plot_fft_image_denoise.rst.txt new file mode 100644 index 000000000..98e03bf0c --- /dev/null +++ b/_sources/intro/scipy/auto_examples/solutions/plot_fft_image_denoise.rst.txt @@ -0,0 +1,272 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/auto_examples/solutions/plot_fft_image_denoise.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_auto_examples_solutions_plot_fft_image_denoise.py: + + +====================== +Image denoising by FFT +====================== + +Denoise an image (:download:`../../../../data/moonlanding.png`) by +implementing a blur with an FFT. + +Implements, via FFT, the following convolution: + +.. math:: + + f_1(t) = \int dt'\, K(t-t') f_0(t') + +.. math:: + + \tilde{f}_1(\omega) = \tilde{K}(\omega) \tilde{f}_0(\omega) + +.. GENERATED FROM PYTHON SOURCE LINES 22-24 + +Read and plot the image +########################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 24-34 + +.. code-block:: Python + + import numpy as np + import matplotlib.pyplot as plt + + im = plt.imread("../../../../data/moonlanding.png").astype(float) + + plt.figure() + plt.imshow(im, "gray") + plt.title("Original image") + + + + + +.. image-sg:: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_fft_image_denoise_001.png + :alt: Original image + :srcset: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_fft_image_denoise_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + Text(0.5, 1.0, 'Original image') + + + +.. GENERATED FROM PYTHON SOURCE LINES 35-37 + +Compute the 2d FFT of the input image +########################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 37-56 + +.. code-block:: Python + + import scipy as sp + + im_fft = sp.fft.fft2(im) + + # Show the results + + + def plot_spectrum(im_fft): + from matplotlib.colors import LogNorm + + # A logarithmic colormap + plt.imshow(np.abs(im_fft), norm=LogNorm(vmin=5)) + plt.colorbar() + + + plt.figure() + plot_spectrum(im_fft) + plt.title("Fourier transform") + + + + +.. image-sg:: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_fft_image_denoise_002.png + :alt: Fourier transform + :srcset: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_fft_image_denoise_002.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + Text(0.5, 1.0, 'Fourier transform') + + + +.. GENERATED FROM PYTHON SOURCE LINES 57-59 + +Filter in FFT +########################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 59-85 + +.. code-block:: Python + + + # In the lines following, we'll make a copy of the original spectrum and + # truncate coefficients. + + # Define the fraction of coefficients (in each direction) we keep + keep_fraction = 0.1 + + # Call ff a copy of the original transform. NumPy arrays have a copy + # method for this purpose. + im_fft2 = im_fft.copy() + + # Set r and c to be the number of rows and columns of the array. + r, c = im_fft2.shape + + # Set to zero all rows with indices between r*keep_fraction and + # r*(1-keep_fraction): + im_fft2[int(r * keep_fraction) : int(r * (1 - keep_fraction))] = 0 + + # Similarly with the columns: + im_fft2[:, int(c * keep_fraction) : int(c * (1 - keep_fraction))] = 0 + + plt.figure() + plot_spectrum(im_fft2) + plt.title("Filtered Spectrum") + + + + + +.. image-sg:: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_fft_image_denoise_003.png + :alt: Filtered Spectrum + :srcset: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_fft_image_denoise_003.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + Text(0.5, 1.0, 'Filtered Spectrum') + + + +.. GENERATED FROM PYTHON SOURCE LINES 86-88 + +Reconstruct the final image +########################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 88-98 + +.. code-block:: Python + + + # Reconstruct the denoised image from the filtered spectrum, keep only the + # real part for display. + im_new = sp.fft.ifft2(im_fft2).real + + plt.figure() + plt.imshow(im_new, "gray") + plt.title("Reconstructed Image") + + + + + +.. image-sg:: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_fft_image_denoise_004.png + :alt: Reconstructed Image + :srcset: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_fft_image_denoise_004.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + Text(0.5, 1.0, 'Reconstructed Image') + + + +.. GENERATED FROM PYTHON SOURCE LINES 99-104 + +Easier and better: :func:`scipy.ndimage.gaussian_filter` +########################################################### + + Implementing filtering directly with FFTs is tricky and time consuming. + We can use the Gaussian filter from :mod:`scipy.ndimage` + +.. GENERATED FROM PYTHON SOURCE LINES 104-112 + +.. code-block:: Python + + + im_blur = sp.ndimage.gaussian_filter(im, 4) + + plt.figure() + plt.imshow(im_blur, "gray") + plt.title("Blurred image") + + plt.show() + + + +.. image-sg:: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_fft_image_denoise_005.png + :alt: Blurred image + :srcset: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_fft_image_denoise_005.png + :class: sphx-glr-single-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.782 seconds) + + +.. _sphx_glr_download_intro_scipy_auto_examples_solutions_plot_fft_image_denoise.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_fft_image_denoise.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_fft_image_denoise.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_fft_image_denoise.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/solutions/plot_image_blur.rst.txt b/_sources/intro/scipy/auto_examples/solutions/plot_image_blur.rst.txt new file mode 100644 index 000000000..9e9a47f55 --- /dev/null +++ b/_sources/intro/scipy/auto_examples/solutions/plot_image_blur.rst.txt @@ -0,0 +1,246 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/auto_examples/solutions/plot_image_blur.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_auto_examples_solutions_plot_image_blur.py: + + +======================================================= +Simple image blur by convolution with a Gaussian kernel +======================================================= + +Blur an an image (:download:`../../../../data/elephant.png`) using a +Gaussian kernel. + +Convolution is easy to perform with FFT: convolving two signals boils +down to multiplying their FFTs (and performing an inverse FFT). + +.. GENERATED FROM PYTHON SOURCE LINES 13-18 + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 19-21 + +The original image +#################################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 21-27 + +.. code-block:: Python + + + # read image + img = plt.imread("../../../../data/elephant.png") + plt.figure() + plt.imshow(img) + + + + +.. image-sg:: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_image_blur_001.png + :alt: plot image blur + :srcset: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_image_blur_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 28-30 + +Prepare an Gaussian convolution kernel +#################################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 30-39 + +.. code-block:: Python + + + # First a 1-D Gaussian + t = np.linspace(-10, 10, 30) + bump = np.exp(-0.1 * t**2) + bump /= np.trapezoid(bump) # normalize the integral to 1 + + # make a 2-D kernel out of it + kernel = bump[:, np.newaxis] * bump[np.newaxis, :] + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 40-42 + +Implement convolution via FFT +#################################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 42-60 + +.. code-block:: Python + + + # Padded fourier transform, with the same shape as the image + # We use :func:`scipy.fft.fft2` to have a 2D FFT + kernel_ft = sp.fft.fft2(kernel, s=img.shape[:2], axes=(0, 1)) + + # convolve + img_ft = sp.fft.fft2(img, axes=(0, 1)) + # the 'newaxis' is to match to color direction + img2_ft = kernel_ft[:, :, np.newaxis] * img_ft + img2 = sp.fft.ifft2(img2_ft, axes=(0, 1)).real + + # clip values to range + img2 = np.clip(img2, 0, 1) + + # plot output + plt.figure() + plt.imshow(img2) + + + + +.. image-sg:: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_image_blur_002.png + :alt: plot image blur + :srcset: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_image_blur_002.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 61-67 + +Further exercise (only if you are familiar with this stuff): + +A "wrapped border" appears in the upper left and top edges of the +image. This is because the padding is not done correctly, and does +not take the kernel size into account (so the convolution "flows out +of bounds of the image"). Try to remove this artifact. + +.. GENERATED FROM PYTHON SOURCE LINES 70-76 + +A function to do it: :func:`scipy.signal.fftconvolve` +#################################################################### + + The above exercise was only for didactic reasons: there exists a + function in scipy that will do this for us, and probably do a better + job: :func:`scipy.signal.fftconvolve` + +.. GENERATED FROM PYTHON SOURCE LINES 76-83 + +.. code-block:: Python + + + # mode='same' is there to enforce the same output shape as input arrays + # (ie avoid border effects) + img3 = sp.signal.fftconvolve(img, kernel[:, :, np.newaxis], mode="same") + plt.figure() + plt.imshow(img3) + + + + +.. image-sg:: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_image_blur_003.png + :alt: plot image blur + :srcset: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_image_blur_003.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 84-87 + +Note that we still have a decay to zero at the border of the image. +Using :func:`scipy.ndimage.gaussian_filter` would get rid of this +artifact + +.. GENERATED FROM PYTHON SOURCE LINES 87-90 + +.. code-block:: Python + + + + plt.show() + + + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.321 seconds) + + +.. _sphx_glr_download_intro_scipy_auto_examples_solutions_plot_image_blur.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_image_blur.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_image_blur.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_image_blur.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/solutions/plot_periodicity_finder.rst.txt b/_sources/intro/scipy/auto_examples/solutions/plot_periodicity_finder.rst.txt new file mode 100644 index 000000000..d4de4dd32 --- /dev/null +++ b/_sources/intro/scipy/auto_examples/solutions/plot_periodicity_finder.rst.txt @@ -0,0 +1,164 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/auto_examples/solutions/plot_periodicity_finder.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_auto_examples_solutions_plot_periodicity_finder.py: + + +========================== +Crude periodicity finding +========================== + +Discover the periods in evolution of animal populations +(:download:`../../../../data/populations.txt`) + +.. GENERATED FROM PYTHON SOURCE LINES 11-13 + +Load the data +########################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 13-20 + +.. code-block:: Python + + + import numpy as np + + data = np.loadtxt("../../../../data/populations.txt") + years = data[:, 0] + populations = data[:, 1:] + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 21-23 + +Plot the data +########################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 23-32 + +.. code-block:: Python + + + import matplotlib.pyplot as plt + + plt.figure() + plt.plot(years, populations * 1e-3) + plt.xlabel("Year") + plt.ylabel(r"Population number ($\cdot10^3$)") + plt.legend(["hare", "lynx", "carrot"], loc=1) + + + + +.. image-sg:: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_periodicity_finder_001.png + :alt: plot periodicity finder + :srcset: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_periodicity_finder_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 33-35 + +Plot its periods +########################################################### + +.. GENERATED FROM PYTHON SOURCE LINES 35-49 + +.. code-block:: Python + + import scipy as sp + + ft_populations = sp.fft.fft(populations, axis=0) + frequencies = sp.fft.fftfreq(populations.shape[0], years[1] - years[0]) + periods = 1 / frequencies + + plt.figure() + plt.plot(periods, abs(ft_populations) * 1e-3, "o") + plt.xlim(0, 22) + plt.xlabel("Period") + plt.ylabel(r"Power ($\cdot10^3$)") + + plt.show() + + + + +.. image-sg:: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_periodicity_finder_002.png + :alt: plot periodicity finder + :srcset: /intro/scipy/auto_examples/solutions/images/sphx_glr_plot_periodicity_finder_002.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + /home/runner/work/scientific-python-lectures/scientific-python-lectures/intro/scipy/examples/solutions/plot_periodicity_finder.py:39: RuntimeWarning: divide by zero encountered in divide + periods = 1 / frequencies + + + + +.. GENERATED FROM PYTHON SOURCE LINES 50-53 + +There's probably a period of around 10 years (obvious from the +plot), but for this crude a method, there's not enough data to say +much more. + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.141 seconds) + + +.. _sphx_glr_download_intro_scipy_auto_examples_solutions_plot_periodicity_finder.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_periodicity_finder.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_periodicity_finder.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_periodicity_finder.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/auto_examples/solutions/sg_execution_times.rst.txt b/_sources/intro/scipy/auto_examples/solutions/sg_execution_times.rst.txt new file mode 100644 index 000000000..4dbdda718 --- /dev/null +++ b/_sources/intro/scipy/auto_examples/solutions/sg_execution_times.rst.txt @@ -0,0 +1,46 @@ + +:orphan: + +.. _sphx_glr_intro_scipy_auto_examples_solutions_sg_execution_times: + + +Computation times +================= +**00:01.353** total execution time for 4 files **from intro/scipy/auto_examples/solutions**: + +.. container:: + + .. raw:: html + + + + + + + + .. list-table:: + :header-rows: 1 + :class: table table-striped sg-datatable + + * - Example + - Time + - Mem (MB) + * - :ref:`sphx_glr_intro_scipy_auto_examples_solutions_plot_fft_image_denoise.py` (``plot_fft_image_denoise.py``) + - 00:00.782 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_solutions_plot_image_blur.py` (``plot_image_blur.py``) + - 00:00.321 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_solutions_plot_periodicity_finder.py` (``plot_periodicity_finder.py``) + - 00:00.141 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_solutions_plot_curvefit_temperature_data.py` (``plot_curvefit_temperature_data.py``) + - 00:00.108 + - 0.0 diff --git a/_sources/intro/scipy/image_processing/image_processing.rst.txt b/_sources/intro/scipy/image_processing/image_processing.rst.txt new file mode 100644 index 000000000..a8af7ffbd --- /dev/null +++ b/_sources/intro/scipy/image_processing/image_processing.rst.txt @@ -0,0 +1,301 @@ +:orphan: + +.. for doctests + >>> import matplotlib.pyplot as plt + +:mod:`scipy.ndimage` provides manipulation of n-dimensional arrays as +images. + +Geometrical transformations on images +....................................... + +Changing orientation, resolution, .. :: + + >>> import scipy as sp + + >>> # Load an image + >>> face = sp.datasets.face(gray=True) + + >>> # Shift, rotate and zoom it + >>> shifted_face = sp.ndimage.shift(face, (50, 50)) + >>> shifted_face2 = sp.ndimage.shift(face, (50, 50), mode='nearest') + >>> rotated_face = sp.ndimage.rotate(face, 30) + >>> cropped_face = face[50:-50, 50:-50] + >>> zoomed_face = sp.ndimage.zoom(face, 2) + >>> zoomed_face.shape + (1536, 2048) + +.. image:: /intro/scipy/auto_examples/images/sphx_glr_plot_image_transform_001.png + :target: auto_examples/plot_image_transform.html + :scale: 70 + :align: center + + +:: + + >>> plt.subplot(151) + + + >>> plt.imshow(shifted_face, cmap=plt.cm.gray) + + + >>> plt.axis('off') + (np.float64(-0.5), np.float64(1023.5), np.float64(767.5), np.float64(-0.5)) + + >>> # etc. + + +Image filtering +................... + +Generate a noisy face:: + + >>> import scipy as sp + >>> face = sp.datasets.face(gray=True) + >>> face = face[:512, -512:] # crop out square on right + >>> import numpy as np + >>> noisy_face = np.copy(face).astype(float) + >>> rng = np.random.default_rng() + >>> noisy_face += face.std() * 0.5 * rng.standard_normal(face.shape) + +Apply a variety of filters on it:: + + >>> blurred_face = sp.ndimage.gaussian_filter(noisy_face, sigma=3) + >>> median_face = sp.ndimage.median_filter(noisy_face, size=5) + >>> wiener_face = sp.signal.wiener(noisy_face, (5, 5)) + +.. image:: /intro/scipy/auto_examples/images/sphx_glr_plot_image_filters_001.png + :target: auto_examples/plot_image_filters.html + :scale: 70 + :align: center + + +Other filters in :mod:`scipy.ndimage.filters` and :mod:`scipy.signal` +can be applied to images. + +.. topic:: Exercise + :class: green + + Compare histograms for the different filtered images. + +Mathematical morphology +........................ + +.. tip:: + + `Mathematical morphology + `_ stems from set + theory. It characterizes and transforms geometrical structures. Binary + (black and white) images, in particular, can be transformed using this + theory: the sets to be transformed are the sets of neighboring + non-zero-valued pixels. The theory was also extended to gray-valued + images. + +.. image:: /intro/scipy/image_processing/morpho_mat.png + :align: center + +Mathematical-morphology operations use a *structuring element* +in order to modify geometrical structures. + +Let us first generate a structuring element:: + + >>> el = sp.ndimage.generate_binary_structure(2, 1) + >>> el + array([[False, True, False], + [...True, True, True], + [False, True, False]]) + >>> el.astype(int) + array([[0, 1, 0], + [1, 1, 1], + [0, 1, 0]]) + +* **Erosion** :func:`scipy.ndimage.binary_erosion` :: + + >>> a = np.zeros((7, 7), dtype=int) + >>> a[1:6, 2:5] = 1 + >>> a + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> sp.ndimage.binary_erosion(a).astype(a.dtype) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> # Erosion removes objects smaller than the structure + >>> sp.ndimage.binary_erosion(a, structure=np.ones((5,5))).astype(a.dtype) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + +* **Dilation** :func:`scipy.ndimage.binary_dilation` :: + + >>> a = np.zeros((5, 5)) + >>> a[2, 2] = 1 + >>> a + array([[0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0.], + [0., 0., 1., 0., 0.], + [0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0.]]) + >>> sp.ndimage.binary_dilation(a).astype(a.dtype) + array([[0., 0., 0., 0., 0.], + [0., 0., 1., 0., 0.], + [0., 1., 1., 1., 0.], + [0., 0., 1., 0., 0.], + [0., 0., 0., 0., 0.]]) + +* **Opening** :func:`scipy.ndimage.binary_opening` :: + + >>> a = np.zeros((5, 5), dtype=int) + >>> a[1:4, 1:4] = 1 + >>> a[4, 4] = 1 + >>> a + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 1]]) + >>> # Opening removes small objects + >>> sp.ndimage.binary_opening(a, structure=np.ones((3, 3))).astype(int) + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]]) + >>> # Opening can also smooth corners + >>> sp.ndimage.binary_opening(a).astype(int) + array([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 1, 1, 1, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]]) + +* **Closing:** :func:`scipy.ndimage.binary_closing` + +.. topic:: Exercise + :class: green + + Check that opening amounts to eroding, then dilating. + +An opening operation removes small structures, while a closing operation +fills small holes. Such operations can therefore be used to "clean" an +image. :: + + >>> a = np.zeros((50, 50)) + >>> a[10:-10, 10:-10] = 1 + >>> rng = np.random.default_rng() + >>> a += 0.25 * rng.standard_normal(a.shape) + >>> mask = a>=0.5 + >>> opened_mask = sp.ndimage.binary_opening(mask) + >>> closed_mask = sp.ndimage.binary_closing(opened_mask) + +.. image:: /intro/scipy/auto_examples/images/sphx_glr_plot_mathematical_morpho_001.png + :target: auto_examples/plot_mathematical_morpho.html + :scale: 70 + :align: center + + +.. topic:: Exercise + :class: green + + Check that the area of the reconstructed square is smaller + than the area of the initial square. (The opposite would occur if the + closing step was performed *before* the opening). + +For *gray-valued* images, eroding (resp. dilating) amounts to replacing +a pixel by the minimal (resp. maximal) value among pixels covered by the +structuring element centered on the pixel of interest. :: + + >>> a = np.zeros((7, 7), dtype=int) + >>> a[1:6, 1:6] = 3 + >>> a[4, 4] = 2; a[2, 3] = 1 + >>> a + array([[0, 0, 0, 0, 0, 0, 0], + [0, 3, 3, 3, 3, 3, 0], + [0, 3, 3, 1, 3, 3, 0], + [0, 3, 3, 3, 3, 3, 0], + [0, 3, 3, 3, 2, 3, 0], + [0, 3, 3, 3, 3, 3, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> sp.ndimage.grey_erosion(a, size=(3, 3)) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 3, 2, 2, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + + +Connected components and measurements on images +................................................ + +Let us first generate a nice synthetic binary image. :: + + >>> x, y = np.indices((100, 100)) + >>> sig = np.sin(2*np.pi*x/50.) * np.sin(2*np.pi*y/50.) * (1+x*y/50.**2)**2 + >>> mask = sig > 1 + +.. image:: /intro/scipy/auto_examples/images/sphx_glr_plot_connect_measurements_001.png + :target: auto_examples/plot_connect_measurements.html + :scale: 60 + :align: center + +.. image:: /intro/scipy/auto_examples/images/sphx_glr_plot_connect_measurements_002.png + :target: auto_examples/plot_connect_measurements.html + :scale: 60 + :align: right + +:func:`scipy.ndimage.label` assigns a different label to each connected +component:: + + >>> labels, nb = sp.ndimage.label(mask) + >>> nb + 8 + +.. raw:: html + +
+ + +Now compute measurements on each connected component:: + + >>> areas = sp.ndimage.sum(mask, labels, range(1, labels.max()+1)) + >>> areas # The number of pixels in each connected component + array([190., 45., 424., 278., 459., 190., 549., 424.]) + >>> maxima = sp.ndimage.maximum(sig, labels, range(1, labels.max()+1)) + >>> maxima # The maximum signal in each connected component + array([ 1.80238238, 1.13527605, 5.51954079, 2.49611818, 6.71673619, + 1.80238238, 16.76547217, 5.51954079]) + +.. image:: /intro/scipy/auto_examples/images/sphx_glr_plot_connect_measurements_003.png + :target: auto_examples/plot_connect_measurements.html + :scale: 60 + :align: right + + +Extract the 4th connected component, and crop the array around it:: + + >>> sp.ndimage.find_objects(labels)[3] + (slice(30, 48, None), slice(30, 48, None)) + >>> sl = sp.ndimage.find_objects(labels)[3] + >>> import matplotlib.pyplot as plt + >>> plt.imshow(sig[sl]) + + + + +See the summary exercise on :ref:`summary_exercise_image_processing` for a more +advanced example. diff --git a/_sources/intro/scipy/index.rst.txt b/_sources/intro/scipy/index.rst.txt new file mode 100644 index 000000000..4b802437c --- /dev/null +++ b/_sources/intro/scipy/index.rst.txt @@ -0,0 +1,1147 @@ +.. for doctests + >>> import matplotlib.pyplot as plt + >>> import numpy as np + +.. _scipy: + +SciPy : high-level scientific computing +======================================= + +**Authors**: *Gaël Varoquaux, Adrien Chauve, Andre Espaze, Emmanuelle Gouillart, Ralf Gommers* + + +.. topic:: Scipy + + The :mod:`scipy` package contains various toolboxes dedicated to common + issues in scientific computing. Its different submodules correspond + to different applications, such as interpolation, integration, + optimization, image processing, statistics, special functions, etc. + +.. tip:: + + :mod:`scipy` can be compared to other standard scientific-computing + libraries, such as the GSL (GNU Scientific Library for C and C++), + or Matlab's toolboxes. ``scipy`` is the core package for scientific + routines in Python; it is meant to operate efficiently on ``numpy`` + arrays, so that NumPy and SciPy work hand in hand. + + Before implementing a routine, it is worth checking if the desired + data processing is not already implemented in SciPy. As + non-professional programmers, scientists often tend to **re-invent the + wheel**, which leads to buggy, non-optimal, difficult-to-share and + unmaintainable code. By contrast, ``SciPy``'s routines are optimized + and tested, and should therefore be used when possible. + + +.. contents:: Chapters contents + :local: + :depth: 1 + + +.. warning:: + + This tutorial is far from an introduction to numerical computing. + As enumerating the different submodules and functions in SciPy would + be very boring, we concentrate instead on a few examples to give a + general idea of how to use ``scipy`` for scientific computing. + +:mod:`scipy` is composed of task-specific sub-modules: + +=========================== ========================================== +:mod:`scipy.cluster` Vector quantization / Kmeans +:mod:`scipy.constants` Physical and mathematical constants +:mod:`scipy.fft` Fourier transform +:mod:`scipy.integrate` Integration routines +:mod:`scipy.interpolate` Interpolation +:mod:`scipy.io` Data input and output +:mod:`scipy.linalg` Linear algebra routines +:mod:`scipy.ndimage` n-dimensional image package +:mod:`scipy.odr` Orthogonal distance regression +:mod:`scipy.optimize` Optimization +:mod:`scipy.signal` Signal processing +:mod:`scipy.sparse` Sparse matrices +:mod:`scipy.spatial` Spatial data structures and algorithms +:mod:`scipy.special` Any special mathematical functions +:mod:`scipy.stats` Statistics +=========================== ========================================== + +.. tip:: + + They all depend on :mod:`numpy`, but are mostly independent of each + other. The standard way of importing NumPy and these SciPy modules + is:: + + >>> import numpy as np + >>> import scipy as sp + + +File input/output: :mod:`scipy.io` +---------------------------------- +:mod:`scipy.io` contains functions for loading and saving data in +several common formats including Matlab, IDL, Matrix Market, and +Harwell-Boeing. + +**Matlab files**: Loading and saving:: + + >>> import scipy as sp + >>> a = np.ones((3, 3)) + >>> sp.io.savemat('file.mat', {'a': a}) # savemat expects a dictionary + >>> data = sp.io.loadmat('file.mat') + >>> data['a'] + array([[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]]) + +.. warning:: **Python / Matlab mismatch**: The Matlab file format does not support 1D arrays. + + :: + + >>> a = np.ones(3) + >>> a + array([1., 1., 1.]) + >>> a.shape + (3,) + >>> sp.io.savemat('file.mat', {'a': a}) + >>> a2 = sp.io.loadmat('file.mat')['a'] + >>> a2 + array([[1., 1., 1.]]) + >>> a2.shape + (1, 3) + + Notice that the original array was a one-dimensional array, whereas the + saved and reloaded array is a two-dimensional array with a single row. + + For other formats, see the :mod:`scipy.io` documentation. + +.. seealso:: + + * Load text files: :func:`numpy.loadtxt`/:func:`numpy.savetxt` + + * Clever loading of text/csv files: + :func:`numpy.genfromtxt` + + * Fast and efficient, but NumPy-specific, binary format: + :func:`numpy.save`/:func:`numpy.load` + + * Basic input/output of images in Matplotlib: + :func:`matplotlib.pyplot.imread`/:func:`matplotlib.pyplot.imsave` + + * More advanced input/output of images: :mod:`imageio` + +Special functions: :mod:`scipy.special` +--------------------------------------- + +"Special" functions are functions commonly used in science and mathematics that +are not considered to be "elementary" functions. Examples include + + * the gamma function, :func:`scipy.special.gamma`, + * the error function, :func:`scipy.special.erf`, + * Bessel functions, such as :func:`scipy.special.jv` + (Bessel function of the first kind), and + * elliptic functions, such as :func:`scipy.special.ellipj` + (Jacobi elliptic functions). + +Other special functions are combinations of familiar elementary functions, +but they offer better accuracy or robustness than their naive implementations +would. + +Most of these function are computed elementwise and follow standard +NumPy broadcasting rules when the input arrays have different shapes. +For example, :func:`scipy.special.xlog1py` is mathematically equivalent +to :math:`x\log(1 + y)`. + + >>> import scipy as sp + >>> x = np.asarray([1, 2]) + >>> y = np.asarray([[3], [4], [5]]) + >>> res = sp.special.xlog1py(x, y) + >>> res.shape + (3, 2) + >>> ref = x * np.log(1 + y) + >>> np.allclose(res, ref) + True + +However, :func:`scipy.special.xlog1py` is numerically favorable for small :math:`y`, +when explicit addition of ``1`` would lead to loss of precision due to floating +point truncation error. + + >>> x = 2.5 + >>> y = 1e-18 + >>> x * np.log(1 + y) + np.float64(0.0) + >>> sp.special.xlog1py(x, y) + np.float64(2.5e-18) + +Many special functions also have "logarithmized" variants. For instance, +the gamma function :math:`\Gamma(\cdot)` is related to the factorial +function by :math:`n! = \Gamma(n + 1)`, but it extends the domain from the +positive integers to the complex plane. + + >>> x = np.arange(10) + >>> np.allclose(sp.special.gamma(x + 1), sp.special.factorial(x)) + True + >>> sp.special.gamma(5) < sp.special.gamma(5.5) < sp.special.gamma(6) + np.True_ + +The factorial function grows quickly, and so the gamma function overflows +for moderate values of the argument. However, sometimes only the logarithm +of the gamma function is needed. In such cases, we can compute the logarithm +of the gamma function directly using :func:`scipy.special.gammaln`. + + >>> x = [5, 50, 500] + >>> np.log(sp.special.gamma(x)) + array([ 3.17805383, 144.56574395, inf]) + >>> sp.special.gammaln(x) + array([ 3.17805383, 144.56574395, 2605.11585036]) + +Such functions can often be used when the intermediate components of a +calculation would overflow or underflow, but the final result would not. +For example, suppose we wish to compute the ratio +:math:`\Gamma(500)/\Gamma(499)`. + + >>> a = sp.special.gamma(500) + >>> b = sp.special.gamma(499) + >>> a, b + (np.float64(inf), np.float64(inf)) + +Both the numerator and denominator overflow, so performing :math:`a / b` will +not return the result we seek. However, the magnitude of the result should +be moderate, so the use of logarithms comes to mind. Combining the identities +:math:`\log(a/b) = \log(a) - \log(b)` and :math:`\exp(\log(x)) = x`, +we get: + + >>> log_a = sp.special.gammaln(500) + >>> log_b = sp.special.gammaln(499) + >>> log_res = log_a - log_b + >>> res = np.exp(log_res) + >>> res + np.float64(499.0000000...) + +Similarly, suppose we wish to compute the difference +:math:`\log(\Gamma(500) - \Gamma(499))`. For this, we use +:func:`scipy.special.logsumexp`, which computes +:math:`\log(\exp(x) + \exp(y))` using a numerical trick that avoids overflow. + + >>> res = sp.special.logsumexp([log_a, log_b], + ... b=[1, -1]) # weights the terms of the sum + >>> res + np.float64(2605.113844343...) + +For more information about these and many other special functions, see +the documentation of :mod:`scipy.special`. + +.. _scipy_linalg: + +Linear algebra operations: :mod:`scipy.linalg` +---------------------------------------------- + +:mod:`scipy.linalg` provides a Python interface to efficient, compiled +implementations of standard linear algebra operations: the BLAS (Basic +Linear Algebra Subroutines) and LAPACK (Linear Algebra PACKage) libraries. + +For example, the :func:`scipy.linalg.det` function computes the determinant +of a square matrix:: + + >>> import scipy as sp + >>> arr = np.array([[1, 2], + ... [3, 4]]) + >>> sp.linalg.det(arr) + np.float64(-2.0) + +Mathematically, the solution of a linear system :math:`Ax = b` is :math:`x = A^{-1}b`, +but explicit inversion of a matrix is numerically unstable and should be avoided. +Instead, use :func:`scipy.linalg.solve`:: + + >>> A = np.array([[1, 2], + ... [2, 3]]) + >>> b = np.array([14, 23]) + >>> x = sp.linalg.solve(A, b) + >>> x + array([4., 5.]) + >>> np.allclose(A @ x, b) + True + +Linear systems with special structure can often be solved more efficiently +than more general systems. For example, systems with triangular matrices +can be solved using :func:`scipy.linalg.solve_triangular`:: + + >>> A_upper = np.triu(A) + >>> A_upper + array([[1, 2], + [0, 3]]) + >>> np.allclose(sp.linalg.solve_triangular(A_upper, b, lower=False), + ... sp.linalg.solve(A_upper, b)) + True + +:mod:`scipy.linalg` also features matrix factorizations/decompositions +such as the singular value decomposition. + + >>> A = np.array([[1, 2], + ... [2, 3]]) + >>> U, s, Vh = sp.linalg.svd(A) + >>> s # singular values + array([4.23606798, 0.23606798]) + +The original matrix can be recovered by matrix multiplication of the +factors:: + + >>> S = np.diag(s) # convert to diagonal matrix before matrix multiplication + >>> A2 = U @ S @ Vh + >>> np.allclose(A2, A) + True + >>> A3 = (U * s) @ Vh # more efficient: use array math broadcasting rules! + >>> np.allclose(A3, A) + True + +Many other decompositions (e.g. LU, Cholesky, QR), solvers for structured +linear systems (e.g. triangular, circulant), eigenvalue problem algorithms, +matrix functions (e.g. matrix exponential), and routines for special matrix +creation (e.g. block diagonal, toeplitz) are available in :mod:`scipy.linalg`. + + +.. _intro_scipy_interpolate: + +Interpolation: :mod:`scipy.interpolate` +--------------------------------------- + +:mod:`scipy.interpolate` is used for fitting a function -- an "interpolant" -- +to experimental or computed data. Once fit, the interpolant can be used to +approximate the underlying function at intermediate points; it can also be used +to compute the integral, derivative, or inverse of the function. + +Some kinds of interpolants, known as "smoothing splines", are designed to +generate smooth curves from noisy data. For example, suppose we have +the following data:: + + >>> rng = np.random.default_rng(27446968) + >>> measured_time = np.linspace(0, 2*np.pi, 20) + >>> function = np.sin(measured_time) + >>> noise = rng.normal(loc=0, scale=0.1, size=20) + >>> measurements = function + noise + + +:func:`scipy.interpolate.make_smoothing_spline` can be used to form a curve +similar to the underlying sine function. + + >>> smoothing_spline = sp.interpolate.make_smoothing_spline(measured_time, measurements) + >>> interpolation_time = np.linspace(0, 2*np.pi, 200) + >>> smooth_results = smoothing_spline(interpolation_time) + +.. image:: auto_examples/images/sphx_glr_plot_interpolation_001.png + :target: auto_examples/plot_interpolation.html + :scale: 60 + :align: right + +On the other hand, if the data are not noisy, it may be desirable to pass +exactly through each point. + + >>> interp_spline = sp.interpolate.make_interp_spline(measured_time, function) + >>> interp_results = interp_spline(interpolation_time) + +.. image:: auto_examples/images/sphx_glr_plot_interpolation_002.png + :target: auto_examples/plot_interpolation.html + :scale: 60 + :align: right + +The ``derivative`` and ``antiderivative`` methods of the result object can be used +for differentiation and integration. For the latter, the constant of integration is +assumed to be zero, but we can "wrap" the antiderivative to include a nonzero +constant of integration. + + >>> d_interp_spline = interp_spline.derivative() + >>> d_interp_results = d_interp_spline(interpolation_time) + >>> i_interp_spline = lambda t: interp_spline.antiderivative()(t) - 1 + >>> i_interp_results = i_interp_spline(interpolation_time) + +.. image:: auto_examples/images/sphx_glr_plot_interpolation_003.png + :target: auto_examples/plot_interpolation.html + :scale: 60 + :align: right + +For functions that are monotonic on an interval (e.g. :math:`\sin` from :math:`\pi/2` +to :math:`3\pi/2`), we can reverse the arguments of ``make_interp_spline`` to +interpolate the inverse function. Because the first argument is expected to be +monotonically *increasing*, we also reverse the order of elements in the arrays +with :func:`numpy.flip`. + + >>> i = (measured_time > np.pi/2) & (measured_time < 3*np.pi/2) + >>> inverse_spline = sp.interpolate.make_interp_spline(np.flip(function[i]), + ... np.flip(measured_time[i])) + >>> inverse_spline(0) + array(3.14159265) + +See the summary exercise on :ref:`summary_exercise_stat_interp` for a more +advanced spline interpolation example, and read the +`SciPy interpolation tutorial `__ +and the :mod:`scipy.interpolate` documentation for much more information. + +Optimization and fit: :mod:`scipy.optimize` +------------------------------------------- + +:mod:`scipy.optimize` provides algorithms for root finding, curve fitting, +and more general optimization. + +Root Finding +............ + +:func:`scipy.optimize.root_scalar` attempts to find a root of a specified +scalar-valued function (i.e., an argument at which the function value is zero). +Like many :mod:`scipy.optimize` functions, the function needs an initial +guess of the solution, which the algorithm will refine until it converges or +recognizes failure. We also provide the derivative to improve the rate of +convergence. + + >>> def f(x): + ... return (x-1)*(x-2) + >>> def df(x): + ... return 2*x - 3 + >>> x0 = 0 # guess + >>> res = sp.optimize.root_scalar(f, x0=x0, fprime=df) + >>> res + converged: True + flag: converged + function_calls: 12 + iterations: 6 + root: 1.0 + method: newton + +.. warning:: + + None of the functions in :mod:`scipy.optimize` that accept a guess are + guaranteed to converge for all possible guesses! (For example, try + ``x0=1.5`` in the example above, where the derivative of the function is + exactly zero.) If this occurs, try a different guess, adjust the options + (like providing a ``bracket`` as shown below), or consider whether SciPy + offers a more appropriate method for the problem. + +Note that only one the root at ``1.0`` is found. By inspection, we can tell +that there is a second root at ``2.0``. We can direct the function toward a +particular root by changing the guess or by passing a bracket that contains +only the root we seek. + + >>> res = sp.optimize.root_scalar(f, bracket=(1.5, 10)) + >>> res.root + 2.0 + +For multivariate problems, use :func:`scipy.optimize.root`. + + >>> def f(x): + ... # intersection of unit circle and line from origin + ... return [x[0]**2 + x[1]**2 - 1, + ... x[1] - x[0]] + >>> res = sp.optimize.root(f, x0=[0, 0]) + >>> np.allclose(f(res.x), 0, atol=1e-10) + True + >>> np.allclose(res.x, np.sqrt(2)/2) + True + +Over-constrained problems can be solved in the least-squares +sense using :func:`scipy.optimize.root` with ``method='lm'`` +(Levenberg-Marquardt). + + >>> def f(x): + ... # intersection of unit circle, line from origin, and parabola + ... return [x[0]**2 + x[1]**2 - 1, + ... x[1] - x[0], + ... x[1] - x[0]**2] + >>> res = sp.optimize.root(f, x0=[1, 1], method='lm') + >>> res.success + True + >>> res.x + array([0.76096066, 0.66017736]) + +See the documentation of :func:`scipy.optimize.root_scalar` +and :func:`scipy.optimize.root` for a variety of other solution +algorithms and options. + +Curve fitting +............. + +.. image:: auto_examples/images/sphx_glr_plot_curve_fit_001.png + :target: auto_examples/plot_curve_fit.html + :align: right + :scale: 50 + +Suppose we have data that is sinusoidal but noisy:: + + >>> x = np.linspace(-5, 5, num=50) # 50 values between -5 and 5 + >>> noise = 0.01 * np.cos(100 * x) + >>> a, b = 2.9, 1.5 + >>> y = a * np.cos(b * x) + noise + +We can approximate the underlying amplitude, frequency, and phase +from the data by least squares curve fitting. To begin, we write +a function that accepts the independent variable as the first +argument and all parameters to fit as separate arguments:: + + >>> def f(x, a, b, c): + ... return a * np.sin(b * x + c) + +.. image:: auto_examples/images/sphx_glr_plot_curve_fit_002.png + :target: auto_examples/plot_curve_fit.html + :align: right + :scale: 50 + +We then use :func:`scipy.optimize.curve_fit` to find :math:`a` and :math:`b`:: + + >>> params, _ = sp.optimize.curve_fit(f, x, y, p0=[2, 1, 3]) + >>> params + array([2.900026 , 1.50012043, 1.57079633]) + >>> ref = [a, b, np.pi/2] # what we'd expect + >>> np.allclose(params, ref, rtol=1e-3) + True + +.. raw:: html + +
+ +.. topic:: Exercise: Curve fitting of temperature data + :class: green + + The temperature extremes in Alaska for each month, starting in January, are + given by (in degrees Celsius):: + + max: 17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18 + min: -62, -59, -56, -46, -32, -18, -9, -13, -25, -46, -52, -58 + + 1. Plot these temperature extremes. + 2. Define a function that can describe min and max temperatures. + Hint: this function has to have a period of 1 year. + Hint: include a time offset. + 3. Fit this function to the data with :func:`scipy.optimize.curve_fit`. + 4. Plot the result. Is the fit reasonable? If not, why? + 5. Is the time offset for min and max temperatures the same within the fit + accuracy? + + :ref:`solution ` + + +Optimization +............ + +.. image:: auto_examples/images/sphx_glr_plot_optimize_example1_001.png + :target: auto_examples/plot_optimize_example1.html + :align: right + :scale: 50 + +Suppose we wish to minimize the scalar-valued function of a single +variable :math:`f(x) = x^2 + 10 \sin(x)`:: + + >>> def f(x): + ... return x**2 + 10*np.sin(x) + >>> x = np.arange(-5, 5, 0.1) + >>> plt.plot(x, f(x)) + [] + >>> plt.show() + +We can see that the function has a local minimizer near :math:`x = 3.8` +and a global minimizer near :math:`x = -1.3`, but +the precise values cannot be determined from the plot. + +The most appropriate function for this purpose is +:func:`scipy.optimize.minimize_scalar`. +Since we know the approximate locations of the minima, we will provide +bounds that restrict the search to the vicinity of the global minimum. + + >>> res = sp.optimize.minimize_scalar(f, bounds=(-2, -1)) + >>> res + message: Solution found. + success: True + status: 0 + fun: -7.9458233756... + x: -1.306440997... + nit: 8 + nfev: 8 + >>> res.fun == f(res.x) + np.True_ + +If we did not already know the approximate location of the global minimum, +we could use one of SciPy's global minimizers, such as +:func:`scipy.optimize.differential_evolution`. We are required to pass +``bounds``, but they do not need to be tight. + + >>> bounds=[(-5, 5)] # list of lower, upper bound for each variable + >>> res = sp.optimize.differential_evolution(f, bounds=bounds) + >>> res # doctest:+SKIP + message: Optimization terminated successfully. + success: True + fun: -7.9458233756... + x: [-1.306e+00] + nit: 6 + nfev: 111 + jac: [ 9.948e-06] + +For multivariate optimization, a good choice for many problems is +:func:`scipy.optimize.minimize`. +Suppose we wish to find the minimum of a quadratic function of two +variables, :math:`f(x_0, x_1) = (x_0-1)^2 + (x_1-2)^2`. + + >>> def f(x): + ... return (x[0] - 1)**2 + (x[1] - 2)**2 + +Like :func:`scipy.optimize.root`, :func:`scipy.optimize.minimize` +requires a guess ``x0``. (Note that this is the initial value of +*both* variables rather than the value of the variable we happened to +label :math:`x_0`.) + + >>> res = sp.optimize.minimize(f, x0=[0, 0]) + >>> res + message: Optimization terminated successfully. + success: True + status: 0 + fun: 1.70578...e-16 + x: [ 1.000e+00 2.000e+00] + nit: 2 + jac: [ 3.219e-09 -8.462e-09] + hess_inv: [[ 9.000e-01 -2.000e-01] + [-2.000e-01 6.000e-01]] + nfev: 9 + njev: 3 + +.. sidebar:: **Maximization?** + + Is :func:`scipy.optimize.minimize` restricted to the solution of + minimization problems? Nope! To solve a maximization problem, + simply minimize the *negative* of the original objective function. + +This barely scratches the surface of SciPy's optimization features, which +include mixed integer linear programming, constrained nonlinear programming, +and the solution of assignment problems. For much more information, see the +documentation of :mod:`scipy.optimize` and the advanced chapter +:ref:`mathematical_optimization`. + +.. topic:: Exercise: 2-D minimization + :class: green + + .. image:: auto_examples/images/sphx_glr_plot_2d_minimization_002.png + :target: auto_examples/plot_2d_minimization.html + :align: right + :scale: 50 + + The six-hump camelback function + + .. math:: f(x, y) = (4 - 2.1x^2 + \frac{x^4}{3})x^2 + xy + (4y^2 - 4)y^2 + + has multiple local minima. Find a global minimum (there is more than one, + each with the same value of the objective function) and at least one other + local minimum. + + Hints: + + - Variables can be restricted to :math:`-2 < x < 2` and :math:`-1 < y < 1`. + - :func:`numpy.meshgrid` and :func:`matplotlib.pyplot.imshow` can help + with visualization. + - Try minimizing with :func:`scipy.optimize.minimize` with an initial + guess of :math:`(x, y) = (0, 0)`. Does it find the global minimum, or + converge to a local minimum? What about other initial guesses? + - Try minimizing with :func:`scipy.optimize.differential_evolution`. + + :ref:`solution ` + +See the summary exercise on :ref:`summary_exercise_optimize` for another, more +advanced example. + + +Statistics and random numbers: :mod:`scipy.stats` +------------------------------------------------- + +.. Comment to make doctest pass + >>> np.random.seed(0) + + +:mod:`scipy.stats` contains fundamental tools for statistics in Python. + +Statistical Distributions +......................... + +Consider a random variable distributed according to the standard normal. +We draw a sample consisting of 100000 observations from the random variable. +The normalized histogram of the sample is an estimator of the random +variable's probability density function (PDF):: + + >>> dist = sp.stats.norm(loc=0, scale=1) # standard normal distribution + >>> sample = dist.rvs(size=100000) # "random variate sample" + >>> plt.hist(sample, bins=50, density=True, label='normalized histogram') # doctest: +SKIP + >>> x = np.linspace(-5, 5) + >>> plt.plot(x, dist.pdf(x), label='PDF') + [] + >>> plt.legend() + + +.. image:: auto_examples/images/sphx_glr_plot_normal_distribution_001.png + :target: auto_examples/plot_normal_distribution.html + :scale: 70 + +.. sidebar:: **Distribution objects and frozen distributions** + + Each of the 100+ :mod:`scipy.stats` distribution families is represented by an + *object* with a `__call__` method. Here, we call the :class:`scipy.stats.norm` + object to specify its location and scale, and it returns a *frozen* + distribution: a particular element of a distribution family with all + parameters fixed. The frozen distribution object has methods to compute + essential functions of the particular distribution. + +Suppose we knew that the sample had been drawn from a distribution belonging +to the family of normal distributions, but we did not know the particular +distribution's location (mean) and scale (standard deviation). We perform +maximum likelihood estimation of the unknown parameters using the +distribution family's ``fit`` method:: + + >>> loc, scale = sp.stats.norm.fit(sample) + >>> loc + np.float64(0.0015767005...) + >>> scale + np.float64(0.9973396878...) + +Since we know the true parameters of the distribution from which the +sample was drawn, we are not surprised that these estimates are similar. + +.. topic:: Exercise: Probability distributions + :class: green + + Generate 1000 random variates from a gamma distribution with a shape + parameter of 1. *Hint: the shape parameter is passed as the first + argument when freezing the distribution*. Plot the histogram of the + sample, and overlay the distribution's PDF. Estimate the shape parameter + from the sample using the ``fit`` method. + + Extra: the distributions have many useful methods. Explore them + using tab completion. Plot the cumulative density function of the + distribution, and compute the variance. + +Sample Statistics and Hypothesis Tests +...................................... + +The sample mean is an estimator of the mean of the distribution from which +the sample was drawn:: + + >>> np.mean(sample) + np.float64(0.001576700508...) + +NumPy includes some of the most fundamental sample statistics (e.g. +:func:`numpy.mean`, :func:`numpy.var`, :func:`numpy.percentile`); +:mod:`scipy.stats` includes many more. For instance, the geometric mean +is a common measure of central tendency for data that tends to be +distributed over many orders of magnitude. + + >>> sp.stats.gmean(2**sample) + np.float64(1.0010934829...) + +SciPy also includes a variety of hypothesis tests that produce a +sample statistic and a p-value. For instance, suppose we wish to +test the null hypothesis that ``sample`` was drawn from a normal +distribution:: + + >>> res = sp.stats.normaltest(sample) + >>> res.statistic + np.float64(5.20841759...) + >>> res.pvalue + np.float64(0.07396163283...) + +Here, ``statistic`` is a sample statistic that tends to be high for +samples that are drawn from non-normal distributions. ``pvalue`` is +the probability of observing such a high value of the statistic for +a sample that *has* been drawn from a normal distribution. If the +p-value is unusually small, this may be taken as evidence that +``sample`` was *not* drawn from the normal distribution. Our statistic +and p-value are moderate, so the test is inconclusive. + +There are many other features of :mod:`scipy.stats`, including circular +statistics, quasi-Monte Carlo methods, and resampling methods. +For much more information, see the documentation of :mod:`scipy.stats` +and the advanced chapter :ref:`statistics `. + +Numerical integration: :mod:`scipy.integrate` +--------------------------------------------- + +Quadrature +.......... + +Suppose we wish to compute the definite integral +:math:`\int_0^{\pi / 2} \sin(t) dt` numerically. :func:`scipy.integrate.quad` +chooses one of several adaptive techniques depending on the parameters, and +is therefore the recommended first choice for integration of function of a single variable:: + + >>> integral, error_estimate = sp.integrate.quad(np.sin, 0, np.pi/2) + >>> np.allclose(integral, 1) # numerical result ~ analytical result + True + >>> abs(integral - 1) < error_estimate # actual error < estimated error + True + +Other functions for *numerical quadrature*, including integration of +multivariate functions and approximating integrals from samples, are available +in :mod:`scipy.integrate`. + +Initial Value Problems +...................... + +:mod:`scipy.integrate` also features routines for integrating `Ordinary +Differential Equations (ODE) +`__. +For example, :func:`scipy.integrate.solve_ivp` integrates ODEs of the form: + +.. math:: + + \frac{dy}{dt} = f(t, y(t)) + +from an initial time :math:`t_0` and initial state :math:`y(t=t_0)=t_0` to a final +time :math:`t_f` or until an event occurs (e.g. a specified state is reached). + +As an introduction, consider the initial value problem given by +:math:`\frac{dy}{dt} = -2 y` and the initial condition :math:`y(t=0) = 1` on +the interval :math:`t = 0 \dots 4`. We begin by defining a callable that +computes :math:`f(t, y(t))` given the current time and state. + + >>> def f(t, y): + ... return -2 * y + +Then, to compute ``y`` as a function of time:: + + >>> t_span = (0, 4) # time interval + >>> t_eval = np.linspace(*t_span) # times at which to evaluate `y` + >>> y0 = [1,] # initial state + >>> res = sp.integrate.solve_ivp(f, t_span=t_span, y0=y0, t_eval=t_eval) + +and plot the result:: + + >>> plt.plot(res.t, res.y[0]) + [] + >>> plt.xlabel('t') + Text(0.5, ..., 't') + >>> plt.ylabel('y') + Text(..., 0.5, 'y') + >>> plt.title('Solution of Initial Value Problem') + Text(0.5, 1.0, 'Solution of Initial Value Problem') + +.. image:: auto_examples/images/sphx_glr_plot_solve_ivp_simple_001.png + :target: auto_examples/plot_solve_ivp_simple.html + :scale: 70 + :align: right + +Let us integrate a more complex ODE: a `damped +spring-mass oscillator +`__. +The position of a mass attached to a spring obeys the 2nd order ODE +:math:`\ddot{y} + 2 \zeta \omega_0 \dot{y} + \omega_0^2 y = 0` with natural frequency +:math:`\omega_0 = \sqrt{k/m}`, damping ratio :math:`\zeta = c/(2 m \omega_0)`, +spring constant :math:`k`, mass :math:`m`, and damping coefficient :math:`c`. + +Before using :func:`scipy.integrate.solve_ivp`, the 2nd order ODE +needs to be transformed into a system of first-order ODEs. Note that + +.. math:: + + \frac{dy}{dt} = \dot{y} + \frac{d\dot{y}}{dt} = \ddot{y} = -(2 \zeta \omega_0 \dot{y} + \omega_0^2 y) + +If we define :math:`z = [z_0, z_1]` where :math:`z_0 = y` and :math:`z_1 = \dot{y}`, +then the first order equation: + +.. math:: + + \frac{dz}{dt} = + \begin{bmatrix} + \frac{dz_0}{dt} \\ + \frac{dz_1}{dt} + \end{bmatrix} = + \begin{bmatrix} + z_1 \\ + -(2 \zeta \omega_0 z_1 + \omega_0^2 z_0) + \end{bmatrix} + +is equivalent to the original second order equation. + +We set:: + + >>> m = 0.5 # kg + >>> k = 4 # N/m + >>> c = 0.4 # N s/m + >>> zeta = c / (2 * m * np.sqrt(k/m)) + >>> omega = np.sqrt(k / m) + +and define the function that computes :math:`\dot{z} = f(t, z(t))`:: + + >>> def f(t, z, zeta, omega): + ... return (z[1], -2.0 * zeta * omega * z[1] - omega**2 * z[0]) + +.. image:: auto_examples/images/sphx_glr_plot_solve_ivp_damped_spring_mass_001.png + :target: auto_examples/plot_solve_ivp_damped_spring_mass.html + :scale: 70 + :align: right + +Integration of the system follows:: + + >>> t_span = (0, 10) + >>> t_eval = np.linspace(*t_span, 100) + >>> z0 = [1, 0] + >>> res = sp.integrate.solve_ivp(f, t_span, z0, t_eval=t_eval, + ... args=(zeta, omega), method='LSODA') + +.. tip:: + + With the option `method='LSODA'`, :func:`scipy.integrate.solve_ivp` uses the LSODA + (Livermore Solver for Ordinary Differential equations with Automatic method switching + for stiff and non-stiff problems). See the `ODEPACK Fortran library`_ for more details. + +.. _`ODEPACK Fortran library` : https://people.sc.fsu.edu/~jburkardt/f77_src/odepack/odepack.html + +.. seealso:: **Partial Differental Equations** + + There is no Partial Differential Equations (PDE) solver in SciPy. + Some Python packages for solving PDE's are available, such as fipy_ + or SfePy_. + +.. _fipy: https://www.ctcms.nist.gov/fipy/ +.. _SfePy: https://sfepy.org/doc/ + +Fast Fourier transforms: :mod:`scipy.fft` +--------------------------------------------- + +The :mod:`scipy.fft` module computes fast Fourier transforms (FFTs) +and offers utilities to handle them. Some important functions are: + +* :func:`scipy.fft.fft` to compute the FFT + +* :func:`scipy.fft.fftfreq` to generate the sampling frequencies + +* :func:`scipy.fft.ifft` to compute the inverse FFT, from frequency + space to signal space + +| + +As an illustration, a (noisy) input signal (``sig``), and its FFT:: + + >>> sig_fft = sp.fft.fft(sig) # doctest:+SKIP + >>> freqs = sp.fft.fftfreq(sig.size, d=time_step) # doctest:+SKIP + + +.. |signal_fig| image:: auto_examples/images/sphx_glr_plot_fftpack_001.png + :target: auto_examples/plot_fftpack.html + :scale: 60 + +.. |fft_fig| image:: auto_examples/images/sphx_glr_plot_fftpack_002.png + :target: auto_examples/plot_fftpack.html + :scale: 60 + +===================== ===================== +|signal_fig| |fft_fig| +===================== ===================== +**Signal** **FFT** +===================== ===================== + +As the signal comes from a real-valued function, the Fourier transform is +symmetric. + +The peak signal frequency can be found with ``freqs[power.argmax()]`` + +.. image:: auto_examples/images/sphx_glr_plot_fftpack_003.png + :target: auto_examples/plot_fftpack.html + :scale: 60 + :align: right + + +Setting the Fourier component above this frequency to zero and inverting +the FFT with :func:`scipy.fft.ifft`, gives a filtered signal. + +.. note:: + + The code of this example can be found :ref:`here ` + +.. topic:: `numpy.fft` + + NumPy also has an implementation of FFT (:mod:`numpy.fft`). However, + the SciPy one + should be preferred, as it uses more efficient underlying implementations. + +| + +**Fully worked examples:** + +.. |periodicity_finding| image:: auto_examples/solutions/images/sphx_glr_plot_periodicity_finder_001.png + :scale: 50 + :target: auto_examples/solutions/plot_periodicity_finder.html + +.. |image_blur| image:: auto_examples/solutions/images/sphx_glr_plot_image_blur_002.png + :scale: 50 + :target: auto_examples/solutions/plot_image_blur.html + +=================================================================================================================== =================================================================================================================== +Crude periodicity finding (:ref:`link `) Gaussian image blur (:ref:`link `) +=================================================================================================================== =================================================================================================================== +|periodicity_finding| |image_blur| +=================================================================================================================== =================================================================================================================== + +| + +.. topic:: Exercise: Denoise moon landing image + :class: green + + .. image:: ../../data/moonlanding.png + :scale: 70 + + 1. Examine the provided image :download:`moonlanding.png + <../../data/moonlanding.png>`, which is heavily contaminated with periodic + noise. In this exercise, we aim to clean up the noise using the + Fast Fourier Transform. + + 2. Load the image using :func:`matplotlib.pyplot.imread`. + + 3. Find and use the 2-D FFT function in :mod:`scipy.fft`, and plot the + spectrum (Fourier transform of) the image. Do you have any trouble + visualising the spectrum? If so, why? + + 4. The spectrum consists of high and low frequency components. The noise is + contained in the high-frequency part of the spectrum, so set some of + those components to zero (use array slicing). + + 5. Apply the inverse Fourier transform to see the resulting image. + + :ref:`Solution ` + +| + + +Signal processing: :mod:`scipy.signal` +-------------------------------------- + +.. tip:: + + :mod:`scipy.signal` is for typical signal processing: 1D, + regularly-sampled signals. + +.. image:: auto_examples/images/sphx_glr_plot_resample_001.png + :target: auto_examples/plot_resample.html + :scale: 65 + :align: right + + +**Resampling** :func:`scipy.signal.resample`: resample a signal to `n` +points using FFT. :: + + >>> t = np.linspace(0, 5, 100) + >>> x = np.sin(t) + + >>> x_resampled = sp.signal.resample(x, 25) + + >>> plt.plot(t, x) + [] + >>> plt.plot(t[::4], x_resampled, 'ko') + [] + +.. tip:: + + Notice how on the side of the window the resampling is less accurate + and has a rippling effect. + + This resampling is different from the :ref:`interpolation + ` provided by :mod:`scipy.interpolate` as it + only applies to regularly sampled data. + + +.. image:: auto_examples/images/sphx_glr_plot_detrend_001.png + :target: auto_examples/plot_detrend.html + :scale: 65 + :align: right + +**Detrending** :func:`scipy.signal.detrend`: remove linear trend from signal:: + + >>> t = np.linspace(0, 5, 100) + >>> rng = np.random.default_rng() + >>> x = t + rng.normal(size=100) + + >>> x_detrended = sp.signal.detrend(x) + + >>> plt.plot(t, x) + [] + >>> plt.plot(t, x_detrended) + [] + +.. raw:: html + +
+ +**Filtering**: +For non-linear filtering, :mod:`scipy.signal` has filtering (median +filter :func:`scipy.signal.medfilt`, Wiener :func:`scipy.signal.wiener`), +but we will discuss this in the image section. + +.. tip:: + + :mod:`scipy.signal` also has a full-blown set of tools for the design + of linear filter (finite and infinite response filters), but this is + out of the scope of this tutorial. + + +**Spectral analysis**: +:func:`scipy.signal.spectrogram` compute a spectrogram --frequency +spectrums over consecutive time windows--, while +:func:`scipy.signal.welch` comptes a power spectrum density (PSD). + +.. |chirp_fig| image:: auto_examples/images/sphx_glr_plot_spectrogram_001.png + :target: auto_examples/plot_spectrogram.html + :scale: 45 + +.. |spectrogram_fig| image:: auto_examples/images/sphx_glr_plot_spectrogram_002.png + :target: auto_examples/plot_spectrogram.html + :scale: 45 + +.. |psd_fig| image:: auto_examples/images/sphx_glr_plot_spectrogram_003.png + :target: auto_examples/plot_spectrogram.html + :scale: 45 + +|chirp_fig| |spectrogram_fig| |psd_fig| + +Image manipulation: :mod:`scipy.ndimage` +----------------------------------------- + +.. include:: image_processing/image_processing.rst + :start-line: 1 + + +Summary exercises on scientific computing +----------------------------------------- + +The summary exercises use mainly NumPy, SciPy and Matplotlib. They provide some +real-life examples of scientific computing with Python. Now that the basics of +working with NumPy and SciPy have been introduced, the interested user is +invited to try these exercises. + +.. only:: html + + **Exercises:** + +.. toctree:: + :maxdepth: 1 + + summary-exercises/stats-interpolate.rst + summary-exercises/optimize-fit.rst + summary-exercises/image-processing.rst + +.. only:: html + + **Proposed solutions:** + +.. toctree:: + :maxdepth: 1 + + summary-exercises/answers_image_processing.rst + +.. include the gallery. Skip the first line to avoid the "orphan" + declaration + +.. include:: auto_examples/index.rst + :start-line: 1 + + +.. seealso:: **References to go further** + + * Some chapters of the `advanced `__ and the + `packages and applications `__ parts of the SciPy + lectures + + * The `SciPy cookbook `__ + +.. compile solutions, but don't list them explicitly +.. toctree:: + :hidden: + + solutions.rst diff --git a/_sources/intro/scipy/solutions.rst.txt b/_sources/intro/scipy/solutions.rst.txt new file mode 100644 index 000000000..43ec0b4a7 --- /dev/null +++ b/_sources/intro/scipy/solutions.rst.txt @@ -0,0 +1,105 @@ +=========== +Solutions +=========== + + +.. _pi_wallis: + +The Pi Wallis Solution +---------------------- + +Compute the decimals of Pi using the Wallis formula: + +.. literalinclude:: solutions/pi_wallis.py + +.. _quick_sort: + +The Quicksort Solution +---------------------- + +Implement the quicksort algorithm, as defined by wikipedia: + +:: + + function quicksort(array) + var list less, greater + if length(array) ≤ 1 + return array + select and remove a pivot value pivot from array + for each x in array + if x ≤ pivot then append x to less + else append x to greater + return concatenate(quicksort(less), pivot, quicksort(greater)) + +.. literalinclude:: solutions/quick_sort.py + +.. _fibonacci: + +Fibonacci sequence +------------------ + +Write a function that displays the ``n`` first terms of the Fibonacci +sequence, defined by: + +* ``u_0 = 1; u_1 = 1`` +* ``u_(n+2) = u_(n+1) + u_n`` + +:: + + >>> def fib(n): + ... """Display the n first terms of Fibonacci sequence""" + ... a, b = 0, 1 + ... i = 0 + ... while i < n: + ... print(b) + ... a, b = b, a+b + ... i +=1 + ... + >>> fib(10) + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 55 + +.. _dir_sort: + +The Directory Listing Solution +------------------------------ + +Implement a script that takes a directory name as argument, and +returns the list of '.py' files, sorted by name length. + +**Hint:** try to understand the docstring of list.sort + +.. literalinclude:: solutions/dir_sort.py + +.. _data_file: + +The Data File I/O Solution +-------------------------- + +Write a function that will load the column of numbers in ``data.txt`` +and calculate the min, max and sum values. + +Data file: + +.. literalinclude:: solutions/data.txt + +Solution: + +.. literalinclude:: solutions/data_file.py + +.. _path_site: + +The PYTHONPATH Search Solution +------------------------------ + +Write a program to search your PYTHONPATH for the module ``site.py``. + +.. literalinclude:: solutions/path_site.py diff --git a/_sources/intro/scipy/summary-exercises/answers_image_processing.rst.txt b/_sources/intro/scipy/summary-exercises/answers_image_processing.rst.txt new file mode 100644 index 000000000..f95a440d7 --- /dev/null +++ b/_sources/intro/scipy/summary-exercises/answers_image_processing.rst.txt @@ -0,0 +1,79 @@ + +.. only:: html + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> import scipy as sp + +.. _image-answers: + +Example of solution for the image processing exercise: unmolten grains in glass +=============================================================================== + + +.. image:: ../image_processing/MV_HFV_012.jpg + :align: center + +1. Open the image file MV_HFV_012.jpg and display it. Browse through the + keyword arguments in the docstring of ``imshow`` to display the image + with the "right" orientation (origin in the bottom left corner, and not + the upper left corner as for standard arrays). :: + + >>> dat = plt.imread('data/MV_HFV_012.jpg') + +2. Crop the image to remove the lower panel with measure information. :: + + >>> dat = dat[:-60] + +3. Slightly filter the image with a median filter in order to refine its + histogram. Check how the histogram changes. :: + + >>> filtdat = sp.ndimage.median_filter(dat, size=(7,7)) + >>> hi_dat = np.histogram(dat, bins=np.arange(256)) + >>> hi_filtdat = np.histogram(filtdat, bins=np.arange(256)) + + .. image:: ../image_processing/exo_histos.png + :align: center + +4. Using the histogram of the filtered image, determine thresholds that + allow to define masks for sand pixels, glass pixels and bubble pixels. + Other option (homework): write a function that determines automatically + the thresholds from the minima of the histogram. :: + + >>> void = filtdat <= 50 + >>> sand = np.logical_and(filtdat > 50, filtdat <= 114) + >>> glass = filtdat > 114 + +5. Display an image in which the three phases are colored with three + different colors. :: + + >>> phases = void.astype(int) + 2*glass.astype(int) + 3*sand.astype(int) + + .. image:: ../image_processing/three_phases.png + :align: center + +6. Use mathematical morphology to clean the different phases. :: + + >>> sand_op = sp.ndimage.binary_opening(sand, iterations=2) + +7. Attribute labels to all bubbles and sand grains, and remove from the + sand mask grains that are smaller than 10 pixels. To do so, use + ``sp.ndimage.sum`` or ``np.bincount`` to compute the grain sizes. :: + + >>> sand_labels, sand_nb = sp.ndimage.label(sand_op) + >>> sand_areas = np.array(sp.ndimage.sum(sand_op, sand_labels, np.arange(sand_labels.max()+1))) + >>> mask = sand_areas > 100 + >>> remove_small_sand = mask[sand_labels.ravel()].reshape(sand_labels.shape) + + .. image:: ../image_processing/sands.png + :align: center + + +8. Compute the mean size of bubbles. :: + + >>> bubbles_labels, bubbles_nb = sp.ndimage.label(void) + >>> bubbles_areas = np.bincount(bubbles_labels.ravel())[1:] + >>> mean_bubble_size = bubbles_areas.mean() + >>> median_bubble_size = np.median(bubbles_areas) + >>> mean_bubble_size, median_bubble_size + (np.float64(1699.875), np.float64(65.0)) diff --git a/_sources/intro/scipy/summary-exercises/auto_examples/index.rst.txt b/_sources/intro/scipy/summary-exercises/auto_examples/index.rst.txt new file mode 100644 index 000000000..9d834b30d --- /dev/null +++ b/_sources/intro/scipy/summary-exercises/auto_examples/index.rst.txt @@ -0,0 +1,169 @@ +:orphan: + +Examples for the summary excercices +==================================== + + + +.. raw:: html + +
+ +.. thumbnail-parent-div-open + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/summary-exercises/auto_examples/images/thumb/sphx_glr_plot_optimize_lidar_complex_data_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_optimize_lidar_complex_data.py` + +.. raw:: html + +
The lidar system, data (2 of 2 datasets)
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/summary-exercises/auto_examples/images/thumb/sphx_glr_plot_optimize_lidar_data_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_optimize_lidar_data.py` + +.. raw:: html + +
The lidar system, data (1 of 2 datasets)
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/summary-exercises/auto_examples/images/thumb/sphx_glr_plot_sprog_annual_maxima_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_sprog_annual_maxima.py` + +.. raw:: html + +
The Gumbell distribution, results
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/summary-exercises/auto_examples/images/thumb/sphx_glr_plot_optimize_lidar_data_fit_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_optimize_lidar_data_fit.py` + +.. raw:: html + +
The lidar system, data and fit (1 of 2 datasets)
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/summary-exercises/auto_examples/images/thumb/sphx_glr_plot_optimize_lidar_complex_data_fit_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_optimize_lidar_complex_data_fit.py` + +.. raw:: html + +
The lidar system, data and fit (2 of 2 datasets)
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/summary-exercises/auto_examples/images/thumb/sphx_glr_plot_cumulative_wind_speed_prediction_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_cumulative_wind_speed_prediction.py` + +.. raw:: html + +
Cumulative wind speed prediction
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /intro/scipy/summary-exercises/auto_examples/images/thumb/sphx_glr_plot_gumbell_wind_speed_prediction_thumb.png + :alt: + + :ref:`sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_gumbell_wind_speed_prediction.py` + +.. raw:: html + +
The Gumbell distribution
+
+ + +.. thumbnail-parent-div-close + +.. raw:: html + +
+ + +.. toctree:: + :hidden: + + /intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_complex_data + /intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_data + /intro/scipy/summary-exercises/auto_examples/plot_sprog_annual_maxima + /intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_data_fit + /intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_complex_data_fit + /intro/scipy/summary-exercises/auto_examples/plot_cumulative_wind_speed_prediction + /intro/scipy/summary-exercises/auto_examples/plot_gumbell_wind_speed_prediction + + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-gallery + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download all examples in Python source code: auto_examples_python.zip ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download all examples in Jupyter notebooks: auto_examples_jupyter.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/summary-exercises/auto_examples/plot_cumulative_wind_speed_prediction.rst.txt b/_sources/intro/scipy/summary-exercises/auto_examples/plot_cumulative_wind_speed_prediction.rst.txt new file mode 100644 index 000000000..e248c94bd --- /dev/null +++ b/_sources/intro/scipy/summary-exercises/auto_examples/plot_cumulative_wind_speed_prediction.rst.txt @@ -0,0 +1,107 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/summary-exercises/auto_examples/plot_cumulative_wind_speed_prediction.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_cumulative_wind_speed_prediction.py: + + +Cumulative wind speed prediction +================================ + +Generate the image cumulative-wind-speed-prediction.png +for the interpolate section of scipy.rst. + +.. GENERATED FROM PYTHON SOURCE LINES 8-33 + + + +.. image-sg:: /intro/scipy/summary-exercises/auto_examples/images/sphx_glr_plot_cumulative_wind_speed_prediction_001.png + :alt: plot cumulative wind speed prediction + :srcset: /intro/scipy/summary-exercises/auto_examples/images/sphx_glr_plot_cumulative_wind_speed_prediction_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + Text(42.722222222222214, 0.5, 'Cumulative probability') + + + + + +| + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + max_speeds = np.load("max-speeds.npy") + years_nb = max_speeds.shape[0] + + cprob = (np.arange(years_nb, dtype=np.float32) + 1) / (years_nb + 1) + sorted_max_speeds = np.sort(max_speeds) + speed_spline = sp.interpolate.UnivariateSpline(cprob, sorted_max_speeds) + nprob = np.linspace(0, 1, 100) + fitted_max_speeds = speed_spline(nprob) + + fifty_prob = 1.0 - 0.02 + fifty_wind = speed_spline(fifty_prob) + + plt.figure() + plt.plot(sorted_max_speeds, cprob, "o") + plt.plot(fitted_max_speeds, nprob, "g--") + plt.plot([fifty_wind], [fifty_prob], "o", ms=8.0, mfc="y", mec="y") + plt.text(30, 0.05, rf"$V_{{50}} = {fifty_wind:.2f} \, m/s$") + plt.plot([fifty_wind, fifty_wind], [plt.axis()[2], fifty_prob], "k--") + plt.xlabel("Annual wind speed maxima [$m/s$]") + plt.ylabel("Cumulative probability") + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.077 seconds) + + +.. _sphx_glr_download_intro_scipy_summary-exercises_auto_examples_plot_cumulative_wind_speed_prediction.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_cumulative_wind_speed_prediction.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_cumulative_wind_speed_prediction.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_cumulative_wind_speed_prediction.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/summary-exercises/auto_examples/plot_gumbell_wind_speed_prediction.rst.txt b/_sources/intro/scipy/summary-exercises/auto_examples/plot_gumbell_wind_speed_prediction.rst.txt new file mode 100644 index 000000000..5b48ee829 --- /dev/null +++ b/_sources/intro/scipy/summary-exercises/auto_examples/plot_gumbell_wind_speed_prediction.rst.txt @@ -0,0 +1,104 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/summary-exercises/auto_examples/plot_gumbell_wind_speed_prediction.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_gumbell_wind_speed_prediction.py: + + +The Gumbell distribution +========================= + +Generate the exercise results on the Gumbell distribution + +.. GENERATED FROM PYTHON SOURCE LINES 7-40 + + + +.. image-sg:: /intro/scipy/summary-exercises/auto_examples/images/sphx_glr_plot_gumbell_wind_speed_prediction_001.png + :alt: plot gumbell wind speed prediction + :srcset: /intro/scipy/summary-exercises/auto_examples/images/sphx_glr_plot_gumbell_wind_speed_prediction_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import scipy as sp + import matplotlib.pyplot as plt + + + def gumbell_dist(arr): + return -np.log(-np.log(arr)) + + + years_nb = 21 + wspeeds = np.load("sprog-windspeeds.npy") + max_speeds = np.array([arr.max() for arr in np.array_split(wspeeds, years_nb)]) + sorted_max_speeds = np.sort(max_speeds) + + cprob = (np.arange(years_nb, dtype=np.float32) + 1) / (years_nb + 1) + gprob = gumbell_dist(cprob) + speed_spline = sp.interpolate.UnivariateSpline(gprob, sorted_max_speeds, k=1) + nprob = gumbell_dist(np.linspace(1e-3, 1 - 1e-3, 100)) + fitted_max_speeds = speed_spline(nprob) + + fifty_prob = gumbell_dist(49.0 / 50.0) + fifty_wind = speed_spline(fifty_prob) + + plt.figure() + plt.plot(sorted_max_speeds, gprob, "o") + plt.plot(fitted_max_speeds, nprob, "g--") + plt.plot([fifty_wind], [fifty_prob], "o", ms=8.0, mfc="y", mec="y") + plt.plot([fifty_wind, fifty_wind], [plt.axis()[2], fifty_prob], "k--") + plt.text(35, -1, rf"$V_{{50}} = {fifty_wind:.2f} \, m/s$") + plt.xlabel("Annual wind speed maxima [$m/s$]") + plt.ylabel("Gumbell cumulative probability") + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.068 seconds) + + +.. _sphx_glr_download_intro_scipy_summary-exercises_auto_examples_plot_gumbell_wind_speed_prediction.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_gumbell_wind_speed_prediction.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_gumbell_wind_speed_prediction.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_gumbell_wind_speed_prediction.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_complex_data.rst.txt b/_sources/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_complex_data.rst.txt new file mode 100644 index 000000000..9b3ed1cea --- /dev/null +++ b/_sources/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_complex_data.rst.txt @@ -0,0 +1,84 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_complex_data.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_optimize_lidar_complex_data.py: + + +The lidar system, data (2 of 2 datasets) +======================================== + +Generate a chart of more complex data recorded by the lidar system + +.. GENERATED FROM PYTHON SOURCE LINES 7-20 + + + +.. image-sg:: /intro/scipy/summary-exercises/auto_examples/images/sphx_glr_plot_optimize_lidar_complex_data_001.png + :alt: plot optimize lidar complex data + :srcset: /intro/scipy/summary-exercises/auto_examples/images/sphx_glr_plot_optimize_lidar_complex_data_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + waveform_2 = np.load("waveform_2.npy") + + t = np.arange(len(waveform_2)) + + fig, ax = plt.subplots(figsize=(8, 6)) + plt.plot(t, waveform_2) + plt.xlabel("Time [ns]") + plt.ylabel("Amplitude [bins]") + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.082 seconds) + + +.. _sphx_glr_download_intro_scipy_summary-exercises_auto_examples_plot_optimize_lidar_complex_data.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_optimize_lidar_complex_data.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_optimize_lidar_complex_data.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_optimize_lidar_complex_data.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_complex_data_fit.rst.txt b/_sources/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_complex_data_fit.rst.txt new file mode 100644 index 000000000..4d71d527a --- /dev/null +++ b/_sources/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_complex_data_fit.rst.txt @@ -0,0 +1,102 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_complex_data_fit.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_optimize_lidar_complex_data_fit.py: + + +The lidar system, data and fit (2 of 2 datasets) +================================================ + +Generate a chart of the data fitted by Gaussian curve + +.. GENERATED FROM PYTHON SOURCE LINES 7-38 + + + +.. image-sg:: /intro/scipy/summary-exercises/auto_examples/images/sphx_glr_plot_optimize_lidar_complex_data_fit_001.png + :alt: plot optimize lidar complex data fit + :srcset: /intro/scipy/summary-exercises/auto_examples/images/sphx_glr_plot_optimize_lidar_complex_data_fit_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + import scipy as sp + + + def model(t, coeffs): + return ( + coeffs[0] + + coeffs[1] * np.exp(-(((t - coeffs[2]) / coeffs[3]) ** 2)) + + coeffs[4] * np.exp(-(((t - coeffs[5]) / coeffs[6]) ** 2)) + + coeffs[7] * np.exp(-(((t - coeffs[8]) / coeffs[9]) ** 2)) + ) + + + def residuals(coeffs, y, t): + return y - model(t, coeffs) + + + waveform_2 = np.load("waveform_2.npy") + t = np.arange(len(waveform_2)) + + x0 = np.array([3, 30, 20, 1, 12, 25, 1, 8, 28, 1], dtype=float) + x, flag = sp.optimize.leastsq(residuals, x0, args=(waveform_2, t)) + + fig, ax = plt.subplots(figsize=(8, 6)) + plt.plot(t, waveform_2, t, model(t, x)) + plt.xlabel("Time [ns]") + plt.ylabel("Amplitude [bins]") + plt.legend(["Waveform", "Model"]) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.077 seconds) + + +.. _sphx_glr_download_intro_scipy_summary-exercises_auto_examples_plot_optimize_lidar_complex_data_fit.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_optimize_lidar_complex_data_fit.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_optimize_lidar_complex_data_fit.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_optimize_lidar_complex_data_fit.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_data.rst.txt b/_sources/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_data.rst.txt new file mode 100644 index 000000000..78b6661b9 --- /dev/null +++ b/_sources/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_data.rst.txt @@ -0,0 +1,84 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_data.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_optimize_lidar_data.py: + + +The lidar system, data (1 of 2 datasets) +======================================== + +Generate a chart of the data recorded by the lidar system + +.. GENERATED FROM PYTHON SOURCE LINES 7-20 + + + +.. image-sg:: /intro/scipy/summary-exercises/auto_examples/images/sphx_glr_plot_optimize_lidar_data_001.png + :alt: plot optimize lidar data + :srcset: /intro/scipy/summary-exercises/auto_examples/images/sphx_glr_plot_optimize_lidar_data_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + waveform_1 = np.load("waveform_1.npy") + + t = np.arange(len(waveform_1)) + + fig, ax = plt.subplots(figsize=(8, 6)) + plt.plot(t, waveform_1) + plt.xlabel("Time [ns]") + plt.ylabel("Amplitude [bins]") + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.066 seconds) + + +.. _sphx_glr_download_intro_scipy_summary-exercises_auto_examples_plot_optimize_lidar_data.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_optimize_lidar_data.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_optimize_lidar_data.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_optimize_lidar_data.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_data_fit.rst.txt b/_sources/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_data_fit.rst.txt new file mode 100644 index 000000000..e9ddee11b --- /dev/null +++ b/_sources/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_data_fit.rst.txt @@ -0,0 +1,109 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_data_fit.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_optimize_lidar_data_fit.py: + + +The lidar system, data and fit (1 of 2 datasets) +================================================ + +Generate a chart of the data fitted by Gaussian curve + +.. GENERATED FROM PYTHON SOURCE LINES 7-35 + + + +.. image-sg:: /intro/scipy/summary-exercises/auto_examples/images/sphx_glr_plot_optimize_lidar_data_fit_001.png + :alt: plot optimize lidar data fit + :srcset: /intro/scipy/summary-exercises/auto_examples/images/sphx_glr_plot_optimize_lidar_data_fit_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + [ 2.70363341 27.82020742 15.47924562 3.05636228] + + + + + + +| + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + import scipy as sp + + + def model(t, coeffs): + return coeffs[0] + coeffs[1] * np.exp(-(((t - coeffs[2]) / coeffs[3]) ** 2)) + + + def residuals(coeffs, y, t): + return y - model(t, coeffs) + + + waveform_1 = np.load("waveform_1.npy") + t = np.arange(len(waveform_1)) + + x0 = np.array([3, 30, 15, 1], dtype=float) + x, flag = sp.optimize.leastsq(residuals, x0, args=(waveform_1, t)) + + print(x) + + fig, ax = plt.subplots(figsize=(8, 6)) + plt.plot(t, waveform_1, t, model(t, x)) + plt.xlabel("Time [ns]") + plt.ylabel("Amplitude [bins]") + plt.legend(["Waveform", "Model"]) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.296 seconds) + + +.. _sphx_glr_download_intro_scipy_summary-exercises_auto_examples_plot_optimize_lidar_data_fit.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_optimize_lidar_data_fit.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_optimize_lidar_data_fit.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_optimize_lidar_data_fit.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/summary-exercises/auto_examples/plot_sprog_annual_maxima.rst.txt b/_sources/intro/scipy/summary-exercises/auto_examples/plot_sprog_annual_maxima.rst.txt new file mode 100644 index 000000000..0ddbb5227 --- /dev/null +++ b/_sources/intro/scipy/summary-exercises/auto_examples/plot_sprog_annual_maxima.rst.txt @@ -0,0 +1,94 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "intro/scipy/summary-exercises/auto_examples/plot_sprog_annual_maxima.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_sprog_annual_maxima.py: + + +The Gumbell distribution, results +================================= + +Generate the exercise results on the Gumbell distribution + +.. GENERATED FROM PYTHON SOURCE LINES 7-20 + + + +.. image-sg:: /intro/scipy/summary-exercises/auto_examples/images/sphx_glr_plot_sprog_annual_maxima_001.png + :alt: plot sprog annual maxima + :srcset: /intro/scipy/summary-exercises/auto_examples/images/sphx_glr_plot_sprog_annual_maxima_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + Text(47.097222222222214, 0.5, 'Annual wind speed maxima [$m/s$]') + + + + + +| + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + years_nb = 21 + wspeeds = np.load("sprog-windspeeds.npy") + max_speeds = np.array([arr.max() for arr in np.array_split(wspeeds, years_nb)]) + + plt.figure() + plt.bar(np.arange(years_nb) + 1, max_speeds) + plt.axis("tight") + plt.xlabel("Year") + plt.ylabel("Annual wind speed maxima [$m/s$]") + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.240 seconds) + + +.. _sphx_glr_download_intro_scipy_summary-exercises_auto_examples_plot_sprog_annual_maxima.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_sprog_annual_maxima.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_sprog_annual_maxima.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_sprog_annual_maxima.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/intro/scipy/summary-exercises/auto_examples/sg_execution_times.rst.txt b/_sources/intro/scipy/summary-exercises/auto_examples/sg_execution_times.rst.txt new file mode 100644 index 000000000..4b36f2056 --- /dev/null +++ b/_sources/intro/scipy/summary-exercises/auto_examples/sg_execution_times.rst.txt @@ -0,0 +1,55 @@ + +:orphan: + +.. _sphx_glr_intro_scipy_summary-exercises_auto_examples_sg_execution_times: + + +Computation times +================= +**00:00.907** total execution time for 7 files **from intro/scipy/summary-exercises/auto_examples**: + +.. container:: + + .. raw:: html + + + + + + + + .. list-table:: + :header-rows: 1 + :class: table table-striped sg-datatable + + * - Example + - Time + - Mem (MB) + * - :ref:`sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_optimize_lidar_data_fit.py` (``plot_optimize_lidar_data_fit.py``) + - 00:00.296 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_sprog_annual_maxima.py` (``plot_sprog_annual_maxima.py``) + - 00:00.240 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_optimize_lidar_complex_data.py` (``plot_optimize_lidar_complex_data.py``) + - 00:00.082 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_optimize_lidar_complex_data_fit.py` (``plot_optimize_lidar_complex_data_fit.py``) + - 00:00.077 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_cumulative_wind_speed_prediction.py` (``plot_cumulative_wind_speed_prediction.py``) + - 00:00.077 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_gumbell_wind_speed_prediction.py` (``plot_gumbell_wind_speed_prediction.py``) + - 00:00.068 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_optimize_lidar_data.py` (``plot_optimize_lidar_data.py``) + - 00:00.066 + - 0.0 diff --git a/_sources/intro/scipy/summary-exercises/image-processing.rst.txt b/_sources/intro/scipy/summary-exercises/image-processing.rst.txt new file mode 100644 index 000000000..899b2e635 --- /dev/null +++ b/_sources/intro/scipy/summary-exercises/image-processing.rst.txt @@ -0,0 +1,41 @@ +.. _summary_exercise_image_processing: + +Image processing application: counting bubbles and unmolten grains +------------------------------------------------------------------ + +.. image:: ../image_processing/MV_HFV_012.jpg + :align: center + +.. only:: latex + +Statement of the problem +.......................... + +1. Open the image file MV_HFV_012.jpg and display it. Browse through the keyword arguments + in the docstring of ``imshow`` to display the image with the "right" orientation (origin + in the bottom left corner, and not the upper left corner as for standard arrays). + + This Scanning Element Microscopy image shows a glass sample (light gray matrix) with some + bubbles (on black) and unmolten sand grains (dark gray). We wish to determine the + fraction of the sample covered by these three phases, and to estimate the typical size of + sand grains and bubbles, their sizes, etc. + +2. Crop the image to remove the lower panel with measure information. + +3. Slightly filter the image with a median filter in order to refine its + histogram. Check how the histogram changes. + +4. Using the histogram of the filtered image, determine thresholds that allow to define + masks for sand pixels, glass pixels and bubble pixels. Other option (homework): write a + function that determines automatically the thresholds from the minima of the histogram. + +5. Display an image in which the three phases are colored with three + different colors. + +6. Use mathematical morphology to clean the different phases. + +7. Attribute labels to all bubbles and sand grains, and remove from the sand mask grains + that are smaller than 10 pixels. To do so, use ``ndimage.sum`` or ``np.bincount`` to + compute the grain sizes. + +8. Compute the mean size of bubbles. diff --git a/_sources/intro/scipy/summary-exercises/optimize-fit.rst.txt b/_sources/intro/scipy/summary-exercises/optimize-fit.rst.txt new file mode 100644 index 000000000..cc9e3ea59 --- /dev/null +++ b/_sources/intro/scipy/summary-exercises/optimize-fit.rst.txt @@ -0,0 +1,178 @@ +.. for doctests + >>> import matplotlib.pyplot as plt + + + +.. _summary_exercise_optimize: + +Non linear least squares curve fitting: application to point extraction in topographical lidar data +--------------------------------------------------------------------------------------------------- + +The goal of this exercise is to fit a model to some data. The data used in this tutorial are lidar data and are described in details in the following introductory paragraph. If you're impatient and want to practice now, please skip it and go directly to :ref:`first_step`. + + +Introduction +~~~~~~~~~~~~ + +Lidars systems are optical rangefinders that analyze property of scattered light +to measure distances. Most of them emit a short light impulsion towards a target +and record the reflected signal. This signal is then processed to extract the +distance between the lidar system and the target. + +Topographical lidar systems are such systems embedded in airborne +platforms. They measure distances between the platform and the Earth, so as to +deliver information on the Earth's topography (see [#mallet]_ for more details). + +.. [#mallet] Mallet, C. and Bretar, F. Full-Waveform Topographic Lidar: State-of-the-Art. *ISPRS Journal of Photogrammetry and Remote Sensing* 64(1), pp.1-16, January 2009 http://dx.doi.org/10.1016/j.isprsjprs.2008.09.007 + +In this tutorial, the goal is to analyze the waveform recorded by the lidar +system [#data]_. Such a signal contains peaks whose center and amplitude permit to +compute the position and some characteristics of the hit target. When the +footprint of the laser beam is around 1m on the Earth surface, the beam can hit +multiple targets during the two-way propagation (for example the ground and the +top of a tree or building). The sum of the contributions of each target hit by +the laser beam then produces a complex signal with multiple peaks, each one +containing information about one target. + +One state of the art method to extract information from these data is to +decompose them in a sum of Gaussian functions where each function represents the +contribution of a target hit by the laser beam. + +Therefore, we use the :mod:`scipy.optimize` module to fit a waveform to one +or a sum of Gaussian functions. + +.. _first_step: + +Loading and visualization +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Load the first waveform using:: + + >>> import numpy as np + >>> waveform_1 = np.load('intro/scipy/summary-exercises/examples/waveform_1.npy') + +and visualize it:: + + >>> import matplotlib.pyplot as plt + >>> t = np.arange(len(waveform_1)) + >>> plt.plot(t, waveform_1) #doctest: +ELLIPSIS + [] + >>> plt.show() + +As shown below, this waveform is a 80-bin-length signal with a single peak +with an amplitude of approximately 30 in the 15 nanosecond bin. Additionally, the +base level of noise is approximately 3. These values can be used in the initial solution. + +.. figure:: auto_examples/images/sphx_glr_plot_optimize_lidar_data_001.png + :align: center + :target: auto_examples/plot_optimize_lidar_data.html + + +Fitting a waveform with a simple Gaussian model +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The signal is very simple and can be modeled as a single Gaussian function and +an offset corresponding to the background noise. To fit the signal with the +function, we must: + +* define the model +* propose an initial solution +* call ``scipy.optimize.leastsq`` + + +Model +^^^^^ + +A Gaussian function defined by + +.. math:: + B + A \exp\left\{-\left(\frac{t-\mu}{\sigma}\right)^2\right\} + +can be defined in python by:: + + >>> def model(t, coeffs): + ... return coeffs[0] + coeffs[1] * np.exp( - ((t-coeffs[2])/coeffs[3])**2 ) + +where + +* ``coeffs[0]`` is :math:`B` (noise) +* ``coeffs[1]`` is :math:`A` (amplitude) +* ``coeffs[2]`` is :math:`\mu` (center) +* ``coeffs[3]`` is :math:`\sigma` (width) + + +Initial solution +^^^^^^^^^^^^^^^^ + +One possible initial solution that we determine by inspection is:: + + >>> x0 = np.array([3, 30, 15, 1], dtype=float) + +Fit +^^^ + +``scipy.optimize.leastsq`` minimizes the sum of squares of the function given as +an argument. Basically, the function to minimize is the residuals (the +difference between the data and the model):: + + >>> def residuals(coeffs, y, t): + ... return y - model(t, coeffs) + +So let's get our solution by calling :func:`scipy.optimize.leastsq` with the +following arguments: + +* the function to minimize +* an initial solution +* the additional arguments to pass to the function + +:: + + >>> import scipy as sp + >>> t = np.arange(len(waveform_1)) + >>> x, flag = sp.optimize.leastsq(residuals, x0, args=(waveform_1, t)) + >>> x + array([ 2.70363, 27.82020, 15.47924, 3.05636]) + +And visualize the solution: + +.. literalinclude:: examples/plot_optimize_lidar_data_fit.py + :lines: 29- + +.. figure:: auto_examples/images/sphx_glr_plot_optimize_lidar_data_fit_001.png + :align: center + :target: auto_examples/plot_optimize_lidar_data_fit.html + + +*Remark:* from scipy v0.8 and above, you should rather use :func:`scipy.optimize.curve_fit` which takes the model and the data as arguments, so you don't need to define the residuals any more. + + + +Going further +~~~~~~~~~~~~~ + +* Try with a more complex waveform (for instance ``waveform_2.npy``) + that contains three significant peaks. You must adapt the model which is + now a sum of Gaussian functions instead of only one Gaussian peak. + +.. figure:: auto_examples/images/sphx_glr_plot_optimize_lidar_complex_data_001.png + :align: center + :target: auto_examples/plot_optimize_lidar_complex_data.html + + +* In some cases, writing an explicit function to compute the Jacobian is faster + than letting ``leastsq`` estimate it numerically. Create a function to compute + the Jacobian of the residuals and use it as an input for ``leastsq``. + +* When we want to detect very small peaks in the signal, or when the initial + guess is too far from a good solution, the result given by the algorithm is + often not satisfying. Adding constraints to the parameters of the model + enables to overcome such limitations. An example of *a priori* knowledge we can + add is the sign of our variables (which are all positive). + +* See the `solution `_. + +* Further exercise: compare the result of :func:`scipy.optimize.leastsq` and what you can + get with :func:`scipy.optimize.fmin_slsqp` when adding boundary constraints. + + +.. [#data] The data used for this tutorial are part of the demonstration data available for the `FullAnalyze software `_ and were kindly provided by the GIS DRAIX. diff --git a/_sources/intro/scipy/summary-exercises/stats-interpolate.rst.txt b/_sources/intro/scipy/summary-exercises/stats-interpolate.rst.txt new file mode 100644 index 000000000..cb531c8c3 --- /dev/null +++ b/_sources/intro/scipy/summary-exercises/stats-interpolate.rst.txt @@ -0,0 +1,137 @@ +.. _summary_exercise_stat_interp: + +Maximum wind speed prediction at the Sprogø station +--------------------------------------------------- +The exercise goal is to predict the maximum wind speed occurring every +50 years even if no measure exists for such a period. The available +data are only measured over 21 years at the Sprogø meteorological +station located in Denmark. First, the statistical steps will be given +and then illustrated with functions from the scipy.interpolate module. +At the end the interested readers are invited to compute results from +raw data and in a slightly different approach. + +Statistical approach +~~~~~~~~~~~~~~~~~~~~ +The annual maxima are supposed to fit a normal probability density +function. However such function is not going to be estimated because +it gives a probability from a wind speed maxima. Finding the maximum wind +speed occurring every 50 years requires the opposite approach, the result +needs to be found from a defined probability. That is the quantile function +role and the exercise goal will be to find it. In the current model, +it is supposed that the maximum wind speed occurring every 50 years is +defined as the upper 2% quantile. + +By definition, the quantile function is the inverse of the cumulative +distribution function. The latter describes the probability distribution +of an annual maxima. In the exercise, the cumulative probability ``p_i`` +for a given year ``i`` is defined as ``p_i = i/(N+1)`` with ``N = 21``, +the number of measured years. Thus it will be possible to calculate +the cumulative probability of every measured wind speed maxima. +From those experimental points, the scipy.interpolate module will be +very useful for fitting the quantile function. Finally the 50 years +maxima is going to be evaluated from the cumulative probability +of the 2% quantile. + +Computing the cumulative probabilities +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +The annual wind speeds maxima have already been computed and saved in +the NumPy format in the file :download:`examples/max-speeds.npy`, thus they will be loaded +by using NumPy:: + + >>> import numpy as np + >>> max_speeds = np.load('intro/scipy/summary-exercises/examples/max-speeds.npy') + >>> years_nb = max_speeds.shape[0] + +Following the cumulative probability definition ``p_i`` from the previous +section, the corresponding values will be:: + + >>> cprob = (np.arange(years_nb, dtype=np.float32) + 1)/(years_nb + 1) + +and they are assumed to fit the given wind speeds:: + + >>> sorted_max_speeds = np.sort(max_speeds) + + +Prediction with UnivariateSpline +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +In this section the quantile function will be estimated by using the +``UnivariateSpline`` class which can represent a spline from points. The +default behavior is to build a spline of degree 3 and points can +have different weights according to their reliability. Variants are +``InterpolatedUnivariateSpline`` and ``LSQUnivariateSpline`` on which +errors checking is going to change. In case a 2D spline is wanted, +the ``BivariateSpline`` class family is provided. All those classes +for 1D and 2D splines use the FITPACK Fortran subroutines, that's why a +lower library access is available through the ``splrep`` and ``splev`` +functions for respectively representing and evaluating a spline. +Moreover interpolation functions without the use of FITPACK parameters +are also provided for simpler use. + +For the Sprogø maxima wind speeds, the ``UnivariateSpline`` will be +used because a spline of degree 3 seems to correctly fit the data:: + + >>> import scipy as sp + >>> quantile_func = sp.interpolate.UnivariateSpline(cprob, sorted_max_speeds) + +The quantile function is now going to be evaluated from the full range +of probabilities:: + + >>> nprob = np.linspace(0, 1, 100) + >>> fitted_max_speeds = quantile_func(nprob) + +In the current model, the maximum wind speed occurring every 50 years is +defined as the upper 2% quantile. As a result, the cumulative probability +value will be:: + + >>> fifty_prob = 1. - 0.02 + + +So the storm wind speed occurring every 50 years can be guessed by:: + + >>> fifty_wind = quantile_func(fifty_prob) + >>> fifty_wind + array(32.97989825...) + +The results are now gathered on a Matplotlib figure: + +.. figure:: auto_examples/images/sphx_glr_plot_cumulative_wind_speed_prediction_001.png + :align: center + + Solution: :download:`Python source file ` + + +Exercise with the Gumbell distribution +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +The interested readers are now invited to make an exercise by using the wind +speeds measured over 21 years. The measurement period is around 90 minutes (the +original period was around 10 minutes but the file size has been reduced for +making the exercise setup easier). The data are stored in NumPy format inside +the file :download:`examples/sprog-windspeeds.npy`. Do not look at +the source code for the plots +until you have completed the exercise. + +* The first step will be to find the annual maxima by using NumPy + and plot them as a matplotlib bar figure. + +.. figure:: auto_examples/images/sphx_glr_plot_sprog_annual_maxima_001.png + :align: center + + Solution: :download:`Python source file ` + + + +* The second step will be to use the Gumbell distribution on cumulative + probabilities ``p_i`` defined as ``-log( -log(p_i) )`` for fitting + a linear quantile function (remember that you can define the degree + of the ``UnivariateSpline``). Plotting the annual maxima versus the + Gumbell distribution should give you the following figure. + +.. figure:: auto_examples/images/sphx_glr_plot_gumbell_wind_speed_prediction_001.png + :align: center + + Solution: :download:`Python source file ` + + + +* The last step will be to find 34.23 m/s for the maximum wind speed + occurring every 50 years. diff --git a/_sources/packages/index.rst.txt b/_sources/packages/index.rst.txt new file mode 100644 index 000000000..420817638 --- /dev/null +++ b/_sources/packages/index.rst.txt @@ -0,0 +1,23 @@ +.. _applications_part: + +Packages and applications +========================== + +This part of the *Scientific Python Lectures* is dedicated to various +scientific packages useful for extended needs. + +| + + +.. include:: ../includes/big_toc_css.rst + :start-line: 1 + +.. rst-class:: tune + + .. toctree:: + :maxdepth: 3 + + statistics/index.rst + sympy.rst + scikit-image/index.rst + scikit-learn/index.rst diff --git a/_sources/packages/scikit-image/auto_examples/index.rst.txt b/_sources/packages/scikit-image/auto_examples/index.rst.txt new file mode 100644 index 000000000..8413fb4bc --- /dev/null +++ b/_sources/packages/scikit-image/auto_examples/index.rst.txt @@ -0,0 +1,241 @@ +:orphan: + +Examples for the scikit-image chapter +====================================== + + + +.. raw:: html + +
+ +.. thumbnail-parent-div-open + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-image/auto_examples/images/thumb/sphx_glr_plot_check_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_check.py` + +.. raw:: html + +
Creating an image
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-image/auto_examples/images/thumb/sphx_glr_plot_camera_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_camera.py` + +.. raw:: html + +
Displaying a simple image
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-image/auto_examples/images/thumb/sphx_glr_plot_camera_uint_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_camera_uint.py` + +.. raw:: html + +
Integers can overflow
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-image/auto_examples/images/thumb/sphx_glr_plot_equalize_hist_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_equalize_hist.py` + +.. raw:: html + +
Equalizing the histogram of an image
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-image/auto_examples/images/thumb/sphx_glr_plot_sobel_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_sobel.py` + +.. raw:: html + +
Computing horizontal gradients with the Sobel filter
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-image/auto_examples/images/thumb/sphx_glr_plot_boundaries_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_boundaries.py` + +.. raw:: html + +
Segmentation contours
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-image/auto_examples/images/thumb/sphx_glr_plot_threshold_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_threshold.py` + +.. raw:: html + +
Otsu thresholding
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-image/auto_examples/images/thumb/sphx_glr_plot_features_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_features.py` + +.. raw:: html + +
Affine transform
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-image/auto_examples/images/thumb/sphx_glr_plot_labels_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_labels.py` + +.. raw:: html + +
Labelling connected components of an image
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-image/auto_examples/images/thumb/sphx_glr_plot_filter_coins_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_filter_coins.py` + +.. raw:: html + +
Various denoising filters
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-image/auto_examples/images/thumb/sphx_glr_plot_segmentations_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_segmentations.py` + +.. raw:: html + +
Watershed and random walker for segmentation
+
+ + +.. thumbnail-parent-div-close + +.. raw:: html + +
+ + +.. toctree:: + :hidden: + + /packages/scikit-image/auto_examples/plot_check + /packages/scikit-image/auto_examples/plot_camera + /packages/scikit-image/auto_examples/plot_camera_uint + /packages/scikit-image/auto_examples/plot_equalize_hist + /packages/scikit-image/auto_examples/plot_sobel + /packages/scikit-image/auto_examples/plot_boundaries + /packages/scikit-image/auto_examples/plot_threshold + /packages/scikit-image/auto_examples/plot_features + /packages/scikit-image/auto_examples/plot_labels + /packages/scikit-image/auto_examples/plot_filter_coins + /packages/scikit-image/auto_examples/plot_segmentations + + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-gallery + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download all examples in Python source code: auto_examples_python.zip ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download all examples in Jupyter notebooks: auto_examples_jupyter.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-image/auto_examples/plot_boundaries.rst.txt b/_sources/packages/scikit-image/auto_examples/plot_boundaries.rst.txt new file mode 100644 index 000000000..c10233ef0 --- /dev/null +++ b/_sources/packages/scikit-image/auto_examples/plot_boundaries.rst.txt @@ -0,0 +1,93 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-image/auto_examples/plot_boundaries.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-image_auto_examples_plot_boundaries.py: + + +Segmentation contours +===================== + +Visualize segmentation contours on original grayscale image. + +.. GENERATED FROM PYTHON SOURCE LINES 7-29 + + + +.. image-sg:: /packages/scikit-image/auto_examples/images/sphx_glr_plot_boundaries_001.png + :alt: plot boundaries + :srcset: /packages/scikit-image/auto_examples/images/sphx_glr_plot_boundaries_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + from skimage import data, segmentation + from skimage import filters + import matplotlib.pyplot as plt + import numpy as np + + coins = data.coins() + mask = coins > filters.threshold_otsu(coins) + clean_border = segmentation.clear_border(mask).astype(int) + + coins_edges = segmentation.mark_boundaries(coins, clean_border) + + plt.figure(figsize=(8, 3.5)) + plt.subplot(121) + plt.imshow(clean_border, cmap="gray") + plt.axis("off") + plt.subplot(122) + plt.imshow(coins_edges) + plt.axis("off") + + plt.tight_layout() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.099 seconds) + + +.. _sphx_glr_download_packages_scikit-image_auto_examples_plot_boundaries.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_boundaries.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_boundaries.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_boundaries.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-image/auto_examples/plot_camera.rst.txt b/_sources/packages/scikit-image/auto_examples/plot_camera.rst.txt new file mode 100644 index 000000000..ccae61004 --- /dev/null +++ b/_sources/packages/scikit-image/auto_examples/plot_camera.rst.txt @@ -0,0 +1,84 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-image/auto_examples/plot_camera.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-image_auto_examples_plot_camera.py: + + +Displaying a simple image +========================= + +Load and display an image + +.. GENERATED FROM PYTHON SOURCE LINES 7-20 + + + +.. image-sg:: /packages/scikit-image/auto_examples/images/sphx_glr_plot_camera_001.png + :alt: plot camera + :srcset: /packages/scikit-image/auto_examples/images/sphx_glr_plot_camera_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import matplotlib.pyplot as plt + from skimage import data + + camera = data.camera() + + + plt.figure(figsize=(4, 4)) + plt.imshow(camera, cmap="gray", interpolation="nearest") + plt.axis("off") + + plt.tight_layout() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.073 seconds) + + +.. _sphx_glr_download_packages_scikit-image_auto_examples_plot_camera.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_camera.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_camera.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_camera.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-image/auto_examples/plot_camera_uint.rst.txt b/_sources/packages/scikit-image/auto_examples/plot_camera_uint.rst.txt new file mode 100644 index 000000000..4b0cf6330 --- /dev/null +++ b/_sources/packages/scikit-image/auto_examples/plot_camera_uint.rst.txt @@ -0,0 +1,88 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-image/auto_examples/plot_camera_uint.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-image_auto_examples_plot_camera_uint.py: + + +Integers can overflow +====================== + +An illustration of overflow problem arising when working with integers + +.. GENERATED FROM PYTHON SOURCE LINES 7-24 + + + +.. image-sg:: /packages/scikit-image/auto_examples/images/sphx_glr_plot_camera_uint_001.png + :alt: plot camera uint + :srcset: /packages/scikit-image/auto_examples/images/sphx_glr_plot_camera_uint_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import matplotlib.pyplot as plt + from skimage import data + + camera = data.camera() + camera_multiply = 3 * camera + + plt.figure(figsize=(8, 4)) + plt.subplot(121) + plt.imshow(camera, cmap="gray", interpolation="nearest") + plt.axis("off") + plt.subplot(122) + plt.imshow(camera_multiply, cmap="gray", interpolation="nearest") + plt.axis("off") + + plt.tight_layout() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.116 seconds) + + +.. _sphx_glr_download_packages_scikit-image_auto_examples_plot_camera_uint.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_camera_uint.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_camera_uint.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_camera_uint.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-image/auto_examples/plot_check.rst.txt b/_sources/packages/scikit-image/auto_examples/plot_check.rst.txt new file mode 100644 index 000000000..1036c7036 --- /dev/null +++ b/_sources/packages/scikit-image/auto_examples/plot_check.rst.txt @@ -0,0 +1,82 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-image/auto_examples/plot_check.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-image_auto_examples_plot_check.py: + + +Creating an image +================== + +How to create an image with basic NumPy commands : ``np.zeros``, slicing... + +This examples show how to create a simple checkerboard. + +.. GENERATED FROM PYTHON SOURCE LINES 9-18 + + + +.. image-sg:: /packages/scikit-image/auto_examples/images/sphx_glr_plot_check_001.png + :alt: plot check + :srcset: /packages/scikit-image/auto_examples/images/sphx_glr_plot_check_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + check = np.zeros((8, 8)) + check[::2, 1::2] = 1 + check[1::2, ::2] = 1 + plt.matshow(check, cmap="gray") + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.059 seconds) + + +.. _sphx_glr_download_packages_scikit-image_auto_examples_plot_check.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_check.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_check.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_check.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-image/auto_examples/plot_equalize_hist.rst.txt b/_sources/packages/scikit-image/auto_examples/plot_equalize_hist.rst.txt new file mode 100644 index 000000000..cec3f904f --- /dev/null +++ b/_sources/packages/scikit-image/auto_examples/plot_equalize_hist.rst.txt @@ -0,0 +1,88 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-image/auto_examples/plot_equalize_hist.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-image_auto_examples_plot_equalize_hist.py: + + +Equalizing the histogram of an image +===================================== + +Histogram equalizing makes images have a uniform histogram. + +.. GENERATED FROM PYTHON SOURCE LINES 7-24 + + + +.. image-sg:: /packages/scikit-image/auto_examples/images/sphx_glr_plot_equalize_hist_001.png + :alt: plot equalize hist + :srcset: /packages/scikit-image/auto_examples/images/sphx_glr_plot_equalize_hist_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + from skimage import data, exposure + import matplotlib.pyplot as plt + + camera = data.camera() + camera_equalized = exposure.equalize_hist(camera) + + plt.figure(figsize=(7, 3)) + + plt.subplot(121) + plt.imshow(camera, cmap="gray", interpolation="nearest") + plt.axis("off") + plt.subplot(122) + plt.imshow(camera_equalized, cmap="gray", interpolation="nearest") + plt.axis("off") + plt.tight_layout() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.089 seconds) + + +.. _sphx_glr_download_packages_scikit-image_auto_examples_plot_equalize_hist.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_equalize_hist.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_equalize_hist.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_equalize_hist.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-image/auto_examples/plot_features.rst.txt b/_sources/packages/scikit-image/auto_examples/plot_features.rst.txt new file mode 100644 index 000000000..bb9dbbf67 --- /dev/null +++ b/_sources/packages/scikit-image/auto_examples/plot_features.rst.txt @@ -0,0 +1,91 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-image/auto_examples/plot_features.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-image_auto_examples_plot_features.py: + + +Affine transform +================= + +Warping and affine transforms of images. + +.. GENERATED FROM PYTHON SOURCE LINES 7-27 + + + +.. image-sg:: /packages/scikit-image/auto_examples/images/sphx_glr_plot_features_001.png + :alt: plot features + :srcset: /packages/scikit-image/auto_examples/images/sphx_glr_plot_features_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import matplotlib.pyplot as plt + + from skimage import data + from skimage.feature import corner_harris, corner_subpix, corner_peaks + from skimage.transform import warp, AffineTransform + + + tform = AffineTransform(scale=(1.3, 1.1), rotation=1, shear=0.7, translation=(210, 50)) + image = warp(data.checkerboard(), tform.inverse, output_shape=(350, 350)) + + coords = corner_peaks(corner_harris(image), min_distance=5) + coords_subpix = corner_subpix(image, coords, window_size=13) + + plt.gray() + plt.imshow(image, interpolation="nearest") + plt.plot(coords_subpix[:, 1], coords_subpix[:, 0], "+r", markersize=15, mew=5) + plt.plot(coords[:, 1], coords[:, 0], ".b", markersize=7) + plt.axis("off") + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 5.704 seconds) + + +.. _sphx_glr_download_packages_scikit-image_auto_examples_plot_features.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_features.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_features.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_features.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-image/auto_examples/plot_filter_coins.rst.txt b/_sources/packages/scikit-image/auto_examples/plot_filter_coins.rst.txt new file mode 100644 index 000000000..50e44e9d3 --- /dev/null +++ b/_sources/packages/scikit-image/auto_examples/plot_filter_coins.rst.txt @@ -0,0 +1,102 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-image/auto_examples/plot_filter_coins.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-image_auto_examples_plot_filter_coins.py: + + +Various denoising filters +========================= + +This example compares several denoising filters available in scikit-image: +a Gaussian filter, a median filter, and total variation denoising. + +.. GENERATED FROM PYTHON SOURCE LINES 8-38 + + + +.. image-sg:: /packages/scikit-image/auto_examples/images/sphx_glr_plot_filter_coins_001.png + :alt: Image, Gaussian filter, Median filter, TV filter + :srcset: /packages/scikit-image/auto_examples/images/sphx_glr_plot_filter_coins_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + from skimage import data + from skimage import filters + from skimage import restoration + + coins = data.coins() + gaussian_filter_coins = filters.gaussian(coins, sigma=2) + med_filter_coins = filters.median(coins, np.ones((3, 3))) + tv_filter_coins = restoration.denoise_tv_chambolle(coins, weight=0.1) + + plt.figure(figsize=(16, 4)) + plt.subplot(141) + plt.imshow(coins[10:80, 300:370], cmap="gray", interpolation="nearest") + plt.axis("off") + plt.title("Image") + plt.subplot(142) + plt.imshow(gaussian_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest") + plt.axis("off") + plt.title("Gaussian filter") + plt.subplot(143) + plt.imshow(med_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest") + plt.axis("off") + plt.title("Median filter") + plt.subplot(144) + plt.imshow(tv_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest") + plt.axis("off") + plt.title("TV filter") + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.154 seconds) + + +.. _sphx_glr_download_packages_scikit-image_auto_examples_plot_filter_coins.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_filter_coins.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_filter_coins.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_filter_coins.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-image/auto_examples/plot_labels.rst.txt b/_sources/packages/scikit-image/auto_examples/plot_labels.rst.txt new file mode 100644 index 000000000..95fa64846 --- /dev/null +++ b/_sources/packages/scikit-image/auto_examples/plot_labels.rst.txt @@ -0,0 +1,103 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-image/auto_examples/plot_labels.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-image_auto_examples_plot_labels.py: + + +Labelling connected components of an image +=========================================== + +This example shows how to label connected components of a binary image, using +the dedicated skimage.measure.label function. + +.. GENERATED FROM PYTHON SOURCE LINES 8-39 + + + +.. image-sg:: /packages/scikit-image/auto_examples/images/sphx_glr_plot_labels_001.png + :alt: plot labels + :srcset: /packages/scikit-image/auto_examples/images/sphx_glr_plot_labels_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + from skimage import measure + from skimage import filters + import matplotlib.pyplot as plt + import numpy as np + + n = 12 + l = 256 + rng = np.random.default_rng(27446968) + im = np.zeros((l, l)) + points = l * rng.random((2, n**2)) + im[(points[0]).astype(int), (points[1]).astype(int)] = 1 + im = filters.gaussian(im, sigma=l / (4.0 * n)) + blobs = im > 0.7 * im.mean() + + all_labels = measure.label(blobs) + blobs_labels = measure.label(blobs, background=0) + + plt.figure(figsize=(9, 3.5)) + plt.subplot(131) + plt.imshow(blobs, cmap="gray") + plt.axis("off") + plt.subplot(132) + plt.imshow(all_labels, cmap="nipy_spectral") + plt.axis("off") + plt.subplot(133) + plt.imshow(blobs_labels, cmap="nipy_spectral") + plt.axis("off") + + plt.tight_layout() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.074 seconds) + + +.. _sphx_glr_download_packages_scikit-image_auto_examples_plot_labels.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_labels.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_labels.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_labels.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-image/auto_examples/plot_segmentations.rst.txt b/_sources/packages/scikit-image/auto_examples/plot_segmentations.rst.txt new file mode 100644 index 000000000..15e80ad56 --- /dev/null +++ b/_sources/packages/scikit-image/auto_examples/plot_segmentations.rst.txt @@ -0,0 +1,125 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-image/auto_examples/plot_segmentations.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-image_auto_examples_plot_segmentations.py: + + +Watershed and random walker for segmentation +============================================ + +This example compares two segmentation methods in order to separate two +connected disks: the watershed algorithm, and the random walker algorithm. + +Both segmentation methods require seeds, that are pixels belonging +unambigusouly to a reagion. Here, local maxima of the distance map to the +background are used as seeds. + +.. GENERATED FROM PYTHON SOURCE LINES 12-61 + + + +.. image-sg:: /packages/scikit-image/auto_examples/images/sphx_glr_plot_segmentations_001.png + :alt: image, distance map, watershed segmentation, random walker segmentation + :srcset: /packages/scikit-image/auto_examples/images/sphx_glr_plot_segmentations_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + from skimage.segmentation import watershed + from skimage.feature import peak_local_max + from skimage import measure + from skimage.segmentation import random_walker + import matplotlib.pyplot as plt + import scipy as sp + + # Generate an initial image with two overlapping circles + x, y = np.indices((80, 80)) + x1, y1, x2, y2 = 28, 28, 44, 52 + r1, r2 = 16, 20 + mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1**2 + mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2**2 + image = np.logical_or(mask_circle1, mask_circle2) + # Now we want to separate the two objects in image + # Generate the markers as local maxima of the distance + # to the background + distance = sp.ndimage.distance_transform_edt(image) + peak_idx = peak_local_max(distance, footprint=np.ones((3, 3)), labels=image) + peak_mask = np.zeros_like(distance, dtype=bool) + peak_mask[tuple(peak_idx.T)] = True + markers = measure.label(peak_mask) + labels_ws = watershed(-distance, markers, mask=image) + + markers[~image] = -1 + labels_rw = random_walker(image, markers) + + plt.figure(figsize=(12, 3.5)) + plt.subplot(141) + plt.imshow(image, cmap="gray", interpolation="nearest") + plt.axis("off") + plt.title("image") + plt.subplot(142) + plt.imshow(-distance, interpolation="nearest") + plt.axis("off") + plt.title("distance map") + plt.subplot(143) + plt.imshow(labels_ws, cmap="nipy_spectral", interpolation="nearest") + plt.axis("off") + plt.title("watershed segmentation") + plt.subplot(144) + plt.imshow(labels_rw, cmap="nipy_spectral", interpolation="nearest") + plt.axis("off") + plt.title("random walker segmentation") + + plt.tight_layout() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.164 seconds) + + +.. _sphx_glr_download_packages_scikit-image_auto_examples_plot_segmentations.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_segmentations.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_segmentations.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_segmentations.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-image/auto_examples/plot_sobel.rst.txt b/_sources/packages/scikit-image/auto_examples/plot_sobel.rst.txt new file mode 100644 index 000000000..1aefd9b93 --- /dev/null +++ b/_sources/packages/scikit-image/auto_examples/plot_sobel.rst.txt @@ -0,0 +1,90 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-image/auto_examples/plot_sobel.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-image_auto_examples_plot_sobel.py: + + +Computing horizontal gradients with the Sobel filter +===================================================== + +This example illustrates the use of the horizontal Sobel filter, to compute +horizontal gradients. + +.. GENERATED FROM PYTHON SOURCE LINES 8-26 + + + +.. image-sg:: /packages/scikit-image/auto_examples/images/sphx_glr_plot_sobel_001.png + :alt: plot sobel + :srcset: /packages/scikit-image/auto_examples/images/sphx_glr_plot_sobel_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + from skimage import data + from skimage import filters + import matplotlib.pyplot as plt + + text = data.text() + hsobel_text = filters.sobel_h(text) + + plt.figure(figsize=(12, 3)) + + plt.subplot(121) + plt.imshow(text, cmap="gray", interpolation="nearest") + plt.axis("off") + plt.subplot(122) + plt.imshow(hsobel_text, cmap="nipy_spectral", interpolation="nearest") + plt.axis("off") + plt.tight_layout() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.099 seconds) + + +.. _sphx_glr_download_packages_scikit-image_auto_examples_plot_sobel.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_sobel.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_sobel.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_sobel.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-image/auto_examples/plot_threshold.rst.txt b/_sources/packages/scikit-image/auto_examples/plot_threshold.rst.txt new file mode 100644 index 000000000..2c0e02132 --- /dev/null +++ b/_sources/packages/scikit-image/auto_examples/plot_threshold.rst.txt @@ -0,0 +1,95 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-image/auto_examples/plot_threshold.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-image_auto_examples_plot_threshold.py: + + +Otsu thresholding +================== + +This example illustrates automatic Otsu thresholding. + +.. GENERATED FROM PYTHON SOURCE LINES 7-31 + + + +.. image-sg:: /packages/scikit-image/auto_examples/images/sphx_glr_plot_threshold_001.png + :alt: plot threshold + :srcset: /packages/scikit-image/auto_examples/images/sphx_glr_plot_threshold_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import matplotlib.pyplot as plt + from skimage import data + from skimage import filters + from skimage import exposure + + camera = data.camera() + val = filters.threshold_otsu(camera) + + hist, bins_center = exposure.histogram(camera) + + plt.figure(figsize=(9, 4)) + plt.subplot(131) + plt.imshow(camera, cmap="gray", interpolation="nearest") + plt.axis("off") + plt.subplot(132) + plt.imshow(camera < val, cmap="gray", interpolation="nearest") + plt.axis("off") + plt.subplot(133) + plt.plot(bins_center, hist, lw=2) + plt.axvline(val, color="k", ls="--") + + plt.tight_layout() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.116 seconds) + + +.. _sphx_glr_download_packages_scikit-image_auto_examples_plot_threshold.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_threshold.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_threshold.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_threshold.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-image/auto_examples/sg_execution_times.rst.txt b/_sources/packages/scikit-image/auto_examples/sg_execution_times.rst.txt new file mode 100644 index 000000000..9448abd5d --- /dev/null +++ b/_sources/packages/scikit-image/auto_examples/sg_execution_times.rst.txt @@ -0,0 +1,67 @@ + +:orphan: + +.. _sphx_glr_packages_scikit-image_auto_examples_sg_execution_times: + + +Computation times +================= +**00:06.747** total execution time for 11 files **from packages/scikit-image/auto_examples**: + +.. container:: + + .. raw:: html + + + + + + + + .. list-table:: + :header-rows: 1 + :class: table table-striped sg-datatable + + * - Example + - Time + - Mem (MB) + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_features.py` (``plot_features.py``) + - 00:05.704 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_segmentations.py` (``plot_segmentations.py``) + - 00:00.164 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_filter_coins.py` (``plot_filter_coins.py``) + - 00:00.154 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_camera_uint.py` (``plot_camera_uint.py``) + - 00:00.116 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_threshold.py` (``plot_threshold.py``) + - 00:00.116 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_boundaries.py` (``plot_boundaries.py``) + - 00:00.099 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_sobel.py` (``plot_sobel.py``) + - 00:00.099 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_equalize_hist.py` (``plot_equalize_hist.py``) + - 00:00.089 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_labels.py` (``plot_labels.py``) + - 00:00.074 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_camera.py` (``plot_camera.py``) + - 00:00.073 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_check.py` (``plot_check.py``) + - 00:00.059 + - 0.0 diff --git a/_sources/packages/scikit-image/index.rst.txt b/_sources/packages/scikit-image/index.rst.txt new file mode 100644 index 000000000..d7b5e7a3e --- /dev/null +++ b/_sources/packages/scikit-image/index.rst.txt @@ -0,0 +1,781 @@ +.. for doctests + >>> import numpy as np + >>> import scipy as sp + >>> import matplotlib.pyplot as plt + +.. _scikit_image: + +================================== +``scikit-image``: image processing +================================== + +.. currentmodule:: skimage + + +**Author**: *Emmanuelle Gouillart* + +`scikit-image `_ is a Python package dedicated +to image processing, using NumPy arrays as image objects. +This chapter describes how to use ``scikit-image`` for various image +processing tasks, and how it relates to other scientific Python +modules such as NumPy and SciPy. + +.. seealso:: + + For basic image manipulation, such as image cropping or simple + filtering, a large number of simple operations can be realized with + NumPy and SciPy only. See :ref:`basic_image`. + + Note that you should be familiar with the content of the previous + chapter before reading the current one, as basic operations such as + masking and labeling are a prerequisite. + +.. contents:: Chapters contents + :local: + :depth: 2 + + +Introduction and concepts +========================= + +Images are NumPy's arrays ``np.ndarray`` + +:image: + + ``np.ndarray`` + +:pixels: + + array values: ``a[2, 3]`` + +:channels: + + array dimensions + +:image encoding: + + ``dtype`` (``np.uint8``, ``np.uint16``, ``np.float``) + +:filters: + + functions (``numpy``, ``skimage``, ``scipy``) + + +:: + + >>> import numpy as np + >>> check = np.zeros((8, 8)) + >>> check[::2, 1::2] = 1 + >>> check[1::2, ::2] = 1 + >>> import matplotlib.pyplot as plt + >>> plt.imshow(check, cmap='gray', interpolation='nearest') + + + +.. image:: auto_examples/images/sphx_glr_plot_check_001.png + :scale: 60 + :target: auto_examples/plot_check.html + :align: center + +``scikit-image`` and the scientific Python ecosystem +---------------------------------------------------- + +``scikit-image`` is packaged in both ``pip`` and ``conda``-based +Python installations, as well as in most Linux distributions. Other +Python packages for image processing & visualization that operate on +NumPy arrays include: + +:mod:`scipy.ndimage` + For N-dimensional arrays. Basic filtering, + mathematical morphology, regions properties + +`Mahotas `_ + With a focus on high-speed implementations. + +`Napari `_ + A fast, interactive, multi-dimensional image viewer built in Qt. + +Some powerful C++ image processing libraries also have Python bindings: + +`OpenCV `_ + A highly optimized computer vision library with a focus on real-time + applications. + +`ITK `_ + The Insight ToolKit, especially useful for registration and + working with 3D images. + +To varying degrees, these tend to be less Pythonic and NumPy-friendly. + +What is included in scikit-image +-------------------------------- + +* Website: https://scikit-image.org/ + +* Gallery of examples: + https://scikit-image.org/docs/stable/auto_examples/ + +The library contains predominantly image processing algorithms, but +also utility functions to ease data handling and processing. +It contains the following submodules: + +:mod:`color` + Color space conversion. + +:mod:`data` + Test images and example data. + +:mod:`draw` + Drawing primitives (lines, text, etc.) that operate on NumPy + arrays. + +:mod:`exposure` + Image intensity adjustment, e.g., histogram equalization, etc. + +:mod:`feature` + Feature detection and extraction, e.g., texture analysis corners, etc. + +:mod:`filters` + Sharpening, edge finding, rank filters, thresholding, etc. + +:mod:`graph` + Graph-theoretic operations, e.g., shortest paths. + +:mod:`io` + Reading, saving, and displaying images and video. + +:mod:`measure` + Measurement of image properties, e.g., region properties and contours. + +:mod:`metrics` + Metrics corresponding to images, e.g. distance metrics, similarity, etc. + +:mod:`morphology` + Morphological operations, e.g., opening or skeletonization. + +:mod:`restoration` + Restoration algorithms, e.g., deconvolution algorithms, denoising, etc. + +:mod:`segmentation` + Partitioning an image into multiple regions. + +:mod:`transform` + Geometric and other transforms, e.g., rotation or the Radon transform. + +:mod:`util` + Generic utilities. + +.. TODO Edit this section with a more refined discussion of the various + package features. + +Importing +========= + +We import ``scikit-image`` using the convention:: + + >>> import skimage as ski + +Most functionality lives in subpackages, e.g.:: + + >>> image = ski.data.cat() + +You can list all submodules with:: + + >>> for m in dir(ski): print(m) + __version__ + color + data + draw + exposure + feature + filters + future + graph + io + measure + metrics + morphology + registration + restoration + segmentation + transform + util + +Most ``scikit-image`` functions take NumPy ``ndarrays`` as arguments :: + + >>> camera = ski.data.camera() + >>> camera.dtype + dtype('uint8') + >>> camera.shape + (512, 512) + >>> filtered_camera = ski.filters.gaussian(camera, sigma=1) + >>> type(filtered_camera) + + +Example data +============ + +To start off, we need example images to work with. +The library ships with a few of these: + +:mod:`skimage.data` :: + + >>> image = ski.data.cat() + >>> image.shape + (300, 451, 3) + +Input/output, data types and colorspaces +======================================== + +I/O: :mod:`skimage.io` + +Save an image to disk: :func:`skimage.io.imsave` :: + + >>> ski.io.imsave("cat.png", image) + +Reading from files: :func:`skimage.io.imread` :: + + >>> cat = ski.io.imread("cat.png") + +.. image:: auto_examples/images/sphx_glr_plot_camera_001.png + :width: 50% + :target: auto_examples/plot_camera.html + :align: center + +This works with many data formats supported by the +`ImageIO `__ library. + +Loading also works with URLs:: + + >>> logo = ski.io.imread('https://scikit-image.org/_static/img/logo.png') + +Data types +----------- + + +.. image:: auto_examples/images/sphx_glr_plot_camera_uint_001.png + :align: right + :width: 50% + :target: auto_examples/plot_camera_uint.html + +Image ndarrays can be represented either by integers (signed or unsigned) or +floats. + +Careful with overflows with integer data types + +:: + + >>> camera = ski.data.camera() + >>> camera.dtype + dtype('uint8') + >>> camera_multiply = 3 * camera + +Different integer sizes are possible: 8-, 16- or 32-bytes, signed or +unsigned. + +.. warning:: + + An important (if questionable) ``skimage`` **convention**: float images + are supposed to lie in [-1, 1] (in order to have comparable contrast for + all float images) :: + + >>> camera_float = ski.util.img_as_float(camera) + >>> camera.max(), camera_float.max() + (np.uint8(255), np.float64(1.0)) + +Some image processing routines need to work with float arrays, and may +hence output an array with a different type and the data range from the +input array :: + + >>> camera_sobel = ski.filters.sobel(camera) + >>> camera_sobel.max() + np.float64(0.644...) + + +Utility functions are provided in :mod:`skimage` to convert both the +dtype and the data range, following skimage's conventions: +``util.img_as_float``, ``util.img_as_ubyte``, etc. + +See the `user guide +`_ for +more details. + +Colorspaces +------------ + +Color images are of shape (N, M, 3) or (N, M, 4) (when an alpha channel +encodes transparency) :: + + >>> face = sp.datasets.face() + >>> face.shape + (768, 1024, 3) + + +Routines converting between different colorspaces (RGB, HSV, LAB etc.) +are available in :mod:`skimage.color` : ``color.rgb2hsv``, ``color.lab2rgb``, +etc. Check the docstring for the expected dtype (and data range) of input +images. + +.. topic:: 3D images + + Most functions of ``skimage`` can take 3D images as input arguments. + Check the docstring to know if a function can be used on 3D images + (for example MRI or CT images). + + + +.. topic:: Exercise + :class: green + + Open a color image on your disk as a NumPy array. + + Find a skimage function computing the histogram of an image and + plot the histogram of each color channel + + Convert the image to grayscale and plot its histogram. + +Image preprocessing / enhancement +================================== + +Goals: denoising, feature (edges) extraction, ... + + +Local filters +-------------- + +Local filters replace the value of pixels by a function of the +values of neighboring pixels. The function can be linear or non-linear. + +Neighbourhood: square (choose size), disk, or more complicated +*structuring element*. + +.. image:: ../../advanced/image_processing/kernels.png + :width: 80% + :align: center + +Example : horizontal Sobel filter :: + + >>> text = ski.data.text() + >>> hsobel_text = ski.filters.sobel_h(text) + + +Uses the following linear kernel for computing horizontal gradients:: + + 1 2 1 + 0 0 0 + -1 -2 -1 + +.. image:: auto_examples/images/sphx_glr_plot_sobel_001.png + :width: 70% + :target: auto_examples/plot_sobel.html + :align: center + + +Non-local filters +----------------- + +Non-local filters use a large region of the image (or all the image) to +transform the value of one pixel:: + + >>> camera = ski.data.camera() + >>> camera_equalized = ski.exposure.equalize_hist(camera) + +Enhances contrast in large almost uniform regions. + +.. image:: auto_examples/images/sphx_glr_plot_equalize_hist_001.png + :width: 70% + :target: auto_examples/plot_equalize_hist.html + :align: center + +Mathematical morphology +----------------------- + +See `wikipedia `_ +for an introduction on mathematical morphology. + +Probe an image with a simple shape (a **structuring element**), and +modify this image according to how the shape locally fits or misses the +image. + +Default structuring element: 4-connectivity of a pixel :: + + >>> # Import structuring elements to make them more easily accessible + >>> from skimage.morphology import disk, diamond + + >>> diamond(1) + array([[0, 1, 0], + [1, 1, 1], + [0, 1, 0]], dtype=uint8) + + +.. image:: ../../advanced/image_processing/diamond_kernel.png + :align: center + +**Erosion** = minimum filter. Replace the value of a pixel by the minimal value covered by the structuring element.:: + + >>> a = np.zeros((7,7), dtype=np.uint8) + >>> a[1:6, 2:5] = 1 + >>> a + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + >>> ski.morphology.binary_erosion(a, diamond(1)).astype(np.uint8) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + >>> #Erosion removes objects smaller than the structure + >>> ski.morphology.binary_erosion(a, diamond(2)).astype(np.uint8) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + +**Dilation**: maximum filter:: + + >>> a = np.zeros((5, 5)) + >>> a[2, 2] = 1 + >>> a + array([[0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0.], + [0., 0., 1., 0., 0.], + [0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0.]]) + >>> ski.morphology.binary_dilation(a, diamond(1)).astype(np.uint8) + array([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 1, 1, 1, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]], dtype=uint8) + +**Opening**: erosion + dilation:: + + >>> a = np.zeros((5,5), dtype=int) + >>> a[1:4, 1:4] = 1; a[4, 4] = 1 + >>> a + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 1]]) + >>> ski.morphology.binary_opening(a, diamond(1)).astype(np.uint8) + array([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 1, 1, 1, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]], dtype=uint8) + +Opening removes small objects and smoothes corners. + +.. topic:: Grayscale mathematical morphology + + Mathematical morphology operations are also available for + (non-binary) grayscale images (int or float type). Erosion and dilation + correspond to minimum (resp. maximum) filters. + +Higher-level mathematical morphology are available: tophat, +skeletonization, etc. + +.. seealso:: + + Basic mathematical morphology is also implemented in + :mod:`scipy.ndimage.morphology`. The ``scipy.ndimage`` implementation + works on arbitrary-dimensional arrays. + +--------------------- + +.. topic:: Example of filters comparison: image denoising + + :: + + >>> coins = ski.data.coins() + >>> coins_zoom = coins[10:80, 300:370] + >>> median_coins = ski.filters.median( + ... coins_zoom, disk(1) + ... ) + >>> tv_coins = ski.restoration.denoise_tv_chambolle( + ... coins_zoom, weight=0.1 + ... ) + >>> gaussian_coins = ski.filters.gaussian(coins, sigma=2) + + .. image:: auto_examples/images/sphx_glr_plot_filter_coins_001.png + :width: 99% + :target: auto_examples/plot_filter_coins.html + +Image segmentation +=================== + +Image segmentation is the attribution of different labels to different +regions of the image, for example in order to extract the pixels of an +object of interest. + +Binary segmentation: foreground + background +--------------------------------------------- + +Histogram-based method: **Otsu thresholding** +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. tip:: + + The `Otsu method `_ is a + simple heuristic to find a threshold to separate the foreground from + the background. + +.. sidebar:: Earlier scikit-image versions + + :mod:`skimage.filters` is called :mod:`skimage.filter` in earlier + versions of scikit-image + +:: + + camera = ski.data.camera() + val = ski.filters.threshold_otsu(camera) + mask = camera < val + +.. image:: auto_examples/images/sphx_glr_plot_threshold_001.png + :width: 70% + :target: auto_examples/plot_threshold.html + :align: center + +Labeling connected components of a discrete image +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. tip:: + + Once you have separated foreground objects, it is use to separate them + from each other. For this, we can assign a different integer labels to + each one. + +Synthetic data:: + + >>> n = 20 + >>> l = 256 + >>> im = np.zeros((l, l)) + >>> rng = np.random.default_rng() + >>> points = l * rng.random((2, n ** 2)) + >>> im[(points[0]).astype(int), (points[1]).astype(int)] = 1 + >>> im = ski.filters.gaussian(im, sigma=l / (4. * n)) + >>> blobs = im > im.mean() + +Label all connected components:: + + >>> all_labels = ski.measure.label(blobs) + +Label only foreground connected components:: + + >>> blobs_labels = ski.measure.label(blobs, background=0) + + +.. image:: auto_examples/images/sphx_glr_plot_labels_001.png + :width: 90% + :target: auto_examples/plot_labels.html + :align: center + +.. seealso:: + + :func:`scipy.ndimage.find_objects` is useful to return slices on + object in an image. + +Marker based methods +--------------------------------------------- + +If you have markers inside a set of regions, you can use these to segment +the regions. + +*Watershed* segmentation +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The Watershed (:func:`skimage.segmentation.watershed`) is a region-growing +approach that fills "basins" in the image :: + + >>> # Generate an initial image with two overlapping circles + >>> x, y = np.indices((80, 80)) + >>> x1, y1, x2, y2 = 28, 28, 44, 52 + >>> r1, r2 = 16, 20 + >>> mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1 ** 2 + >>> mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2 ** 2 + >>> image = np.logical_or(mask_circle1, mask_circle2) + >>> # Now we want to separate the two objects in image + >>> # Generate the markers as local maxima of the distance + >>> # to the background + >>> import scipy as sp + >>> distance = sp.ndimage.distance_transform_edt(image) + >>> peak_idx = ski.feature.peak_local_max( + ... distance, footprint=np.ones((3, 3)), labels=image + ... ) + >>> peak_mask = np.zeros_like(distance, dtype=bool) + >>> peak_mask[tuple(peak_idx.T)] = True + >>> markers = ski.morphology.label(peak_mask) + >>> labels_ws = ski.segmentation.watershed( + ... -distance, markers, mask=image + ... ) + +*Random walker* segmentation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The random walker algorithm (:func:`skimage.segmentation.random_walker`) +is similar to the Watershed, but with a more "probabilistic" approach. It +is based on the idea of the diffusion of labels in the image:: + + >>> # Transform markers image so that 0-valued pixels are to + >>> # be labelled, and -1-valued pixels represent background + >>> markers[~image] = -1 + >>> labels_rw = ski.segmentation.random_walker(image, markers) + +.. image:: auto_examples/images/sphx_glr_plot_segmentations_001.png + :width: 90% + :target: auto_examples/plot_segmentations.html + :align: center + + +.. topic:: Postprocessing label images + + ``skimage`` provides several utility functions that can be used on + label images (ie images where different discrete values identify + different regions). Functions names are often self-explaining: + :func:`skimage.segmentation.clear_border`, + :func:`skimage.segmentation.relabel_from_one`, + :func:`skimage.morphology.remove_small_objects`, etc. + + +.. topic:: Exercise + :class: green + + * Load the ``coins`` image from the ``data`` submodule. + + * Separate the coins from the background by testing several + segmentation methods: Otsu thresholding, adaptive thresholding, and + watershed or random walker segmentation. + + * If necessary, use a postprocessing function to improve the coins / + background segmentation. + + +Measuring regions' properties +============================== + +Example: compute the size and perimeter of the two segmented regions:: + + >>> properties = ski.measure.regionprops(labels_rw) + >>> [float(prop.area) for prop in properties] + [770.0, 1168.0] + >>> [prop.perimeter for prop in properties] + [np.float64(100.91...), np.float64(126.81...)] + +.. seealso:: + + for some properties, functions are available as well in + :mod:`scipy.ndimage.measurements` with a different API (a list is + returned). + + +.. topic:: Exercise (continued) + :class: green + + * Use the binary image of the coins and background from the previous + exercise. + + * Compute an image of labels for the different coins. + + * Compute the size and eccentricity of all coins. + +Data visualization and interaction +=================================== + +Meaningful visualizations are useful when testing a given processing +pipeline. + +Some image processing operations:: + + >>> coins = ski.data.coins() + >>> mask = coins > ski.filters.threshold_otsu(coins) + >>> clean_border = ski.segmentation.clear_border(mask) + +Visualize binary result:: + + >>> plt.figure() +
+ >>> plt.imshow(clean_border, cmap='gray') + + +Visualize contour :: + + >>> plt.figure() +
+ >>> plt.imshow(coins, cmap='gray') + + >>> plt.contour(clean_border, [0.5]) + + +Use ``skimage`` dedicated utility function:: + + >>> coins_edges = ski.segmentation.mark_boundaries( + ... coins, clean_border.astype(int) + ... ) + +.. image:: auto_examples/images/sphx_glr_plot_boundaries_001.png + :width: 90% + :target: auto_examples/plot_boundaries.html + :align: center + +Feature extraction for computer vision +======================================= + +Geometric or textural descriptor can be extracted from images in order to + +* classify parts of the image (e.g. sky vs. buildings) + +* match parts of different images (e.g. for object detection) + +* and many other applications of + `Computer Vision `_ + +Example: detecting corners using Harris detector :: + + tform = ski.transform.AffineTransform( + scale=(1.3, 1.1), rotation=1, shear=0.7, + translation=(210, 50) + ) + image = ski.transform.warp( + data.checkerboard(), tform.inverse, output_shape=(350, 350) + ) + + coords = ski.feature.corner_peaks( + ski.feature.corner_harris(image), min_distance=5 + ) + coords_subpix = ski.feature.corner_subpix( + image, coords, window_size=13 + ) + +.. image:: auto_examples/images/sphx_glr_plot_features_001.png + :width: 90% + :target: auto_examples/plot_features.html + :align: center + +(this example is taken from the `plot_corner +`_ +example in scikit-image) + +Points of interest such as corners can then be used to match objects in +different images, as described in the `plot_matching +`_ +example of scikit-image. + +Full code examples +================== + +.. include the gallery. Skip the first line to avoid the "orphan" + declaration + +.. include:: auto_examples/index.rst + :start-line: 1 diff --git a/_sources/packages/scikit-learn/auto_examples/index.rst.txt b/_sources/packages/scikit-learn/auto_examples/index.rst.txt new file mode 100644 index 000000000..2180fffb8 --- /dev/null +++ b/_sources/packages/scikit-learn/auto_examples/index.rst.txt @@ -0,0 +1,349 @@ +:orphan: + +Examples for the scikit-learn chapter +====================================== + + + +.. raw:: html + +
+ +.. thumbnail-parent-div-open + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-learn/auto_examples/images/thumb/sphx_glr_plot_pca_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_pca.py` + +.. raw:: html + +
Demo PCA in 2D
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-learn/auto_examples/images/thumb/sphx_glr_plot_measuring_performance_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_measuring_performance.py` + +.. raw:: html + +
Measuring Decision Tree performance
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-learn/auto_examples/images/thumb/sphx_glr_plot_linear_regression_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_linear_regression.py` + +.. raw:: html + +
A simple linear regression
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-learn/auto_examples/images/thumb/sphx_glr_plot_iris_scatter_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_iris_scatter.py` + +.. raw:: html + +
Plot 2D views of the iris dataset
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-learn/auto_examples/images/thumb/sphx_glr_plot_tsne_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_tsne.py` + +.. raw:: html + +
tSNE to visualize digits
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-learn/auto_examples/images/thumb/sphx_glr_plot_linear_model_cv_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_linear_model_cv.py` + +.. raw:: html + +
Use the RidgeCV and LassoCV to set the regularization parameter
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-learn/auto_examples/images/thumb/sphx_glr_plot_variance_linear_regr_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_variance_linear_regr.py` + +.. raw:: html + +
Plot variance and regularization in linear models
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-learn/auto_examples/images/thumb/sphx_glr_plot_separator_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_separator.py` + +.. raw:: html + +
Simple picture of the formal problem of machine learning
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-learn/auto_examples/images/thumb/sphx_glr_plot_compare_classifiers_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_compare_classifiers.py` + +.. raw:: html + +
Compare classifiers on the digits data
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-learn/auto_examples/images/thumb/sphx_glr_plot_polynomial_regression_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_polynomial_regression.py` + +.. raw:: html + +
Plot fitting a 9th order polynomial
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-learn/auto_examples/images/thumb/sphx_glr_plot_california_prediction_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_california_prediction.py` + +.. raw:: html + +
A simple regression analysis on the California housing data
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-learn/auto_examples/images/thumb/sphx_glr_plot_iris_knn_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_iris_knn.py` + +.. raw:: html + +
Nearest-neighbor prediction on iris
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-learn/auto_examples/images/thumb/sphx_glr_plot_digits_simple_classif_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_digits_simple_classif.py` + +.. raw:: html + +
Simple visualization and classification of the digits dataset
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-learn/auto_examples/images/thumb/sphx_glr_plot_eigenfaces_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_eigenfaces.py` + +.. raw:: html + +
The eigenfaces example: chaining PCA and SVMs
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-learn/auto_examples/images/thumb/sphx_glr_plot_svm_non_linear_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_svm_non_linear.py` + +.. raw:: html + +
Example of linear and non-linear models
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-learn/auto_examples/images/thumb/sphx_glr_plot_bias_variance_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_bias_variance.py` + +.. raw:: html + +
Bias and variance of polynomial fit
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/scikit-learn/auto_examples/images/thumb/sphx_glr_plot_ML_flow_chart_thumb.png + :alt: + + :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_ML_flow_chart.py` + +.. raw:: html + +
Tutorial Diagrams
+
+ + +.. thumbnail-parent-div-close + +.. raw:: html + +
+ + +.. toctree:: + :hidden: + + /packages/scikit-learn/auto_examples/plot_pca + /packages/scikit-learn/auto_examples/plot_measuring_performance + /packages/scikit-learn/auto_examples/plot_linear_regression + /packages/scikit-learn/auto_examples/plot_iris_scatter + /packages/scikit-learn/auto_examples/plot_tsne + /packages/scikit-learn/auto_examples/plot_linear_model_cv + /packages/scikit-learn/auto_examples/plot_variance_linear_regr + /packages/scikit-learn/auto_examples/plot_separator + /packages/scikit-learn/auto_examples/plot_compare_classifiers + /packages/scikit-learn/auto_examples/plot_polynomial_regression + /packages/scikit-learn/auto_examples/plot_california_prediction + /packages/scikit-learn/auto_examples/plot_iris_knn + /packages/scikit-learn/auto_examples/plot_digits_simple_classif + /packages/scikit-learn/auto_examples/plot_eigenfaces + /packages/scikit-learn/auto_examples/plot_svm_non_linear + /packages/scikit-learn/auto_examples/plot_bias_variance + /packages/scikit-learn/auto_examples/plot_ML_flow_chart + + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-gallery + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download all examples in Python source code: auto_examples_python.zip ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download all examples in Jupyter notebooks: auto_examples_jupyter.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-learn/auto_examples/plot_ML_flow_chart.rst.txt b/_sources/packages/scikit-learn/auto_examples/plot_ML_flow_chart.rst.txt new file mode 100644 index 000000000..8f08588bc --- /dev/null +++ b/_sources/packages/scikit-learn/auto_examples/plot_ML_flow_chart.rst.txt @@ -0,0 +1,250 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-learn/auto_examples/plot_ML_flow_chart.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-learn_auto_examples_plot_ML_flow_chart.py: + + +Tutorial Diagrams +----------------- + +This script plots the flow-charts used in the scikit-learn tutorials. + +.. GENERATED FROM PYTHON SOURCE LINES 7-167 + + + +.. rst-class:: sphx-glr-horizontal + + + * + + .. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_ML_flow_chart_001.png + :alt: plot ML flow chart + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_ML_flow_chart_001.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_ML_flow_chart_002.png + :alt: plot ML flow chart + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_ML_flow_chart_002.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_ML_flow_chart_003.png + :alt: plot ML flow chart + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_ML_flow_chart_003.png + :class: sphx-glr-multi-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + from matplotlib.patches import Circle, Rectangle, Polygon, Arrow, FancyArrow + + + def create_base(box_bg="#CCCCCC", arrow1="#88CCFF", arrow2="#88FF88", supervised=True): + fig = plt.figure(figsize=(9, 6), facecolor="w") + ax = plt.axes((0, 0, 1, 1), xticks=[], yticks=[], frameon=False) + ax.set_xlim(0, 9) + ax.set_ylim(0, 6) + + patches = [ + Rectangle((0.3, 3.6), 1.5, 1.8, zorder=1, fc=box_bg), + Rectangle((0.5, 3.8), 1.5, 1.8, zorder=2, fc=box_bg), + Rectangle((0.7, 4.0), 1.5, 1.8, zorder=3, fc=box_bg), + Rectangle((2.9, 3.6), 0.2, 1.8, fc=box_bg), + Rectangle((3.1, 3.8), 0.2, 1.8, fc=box_bg), + Rectangle((3.3, 4.0), 0.2, 1.8, fc=box_bg), + Rectangle((0.3, 0.2), 1.5, 1.8, fc=box_bg), + Rectangle((2.9, 0.2), 0.2, 1.8, fc=box_bg), + Circle((5.5, 3.5), 1.0, fc=box_bg), + Polygon([[5.5, 1.7], [6.1, 1.1], [5.5, 0.5], [4.9, 1.1]], fc=box_bg), + FancyArrow( + 2.3, 4.6, 0.35, 0, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2 + ), + FancyArrow( + 3.75, 4.2, 0.5, -0.2, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2 + ), + FancyArrow( + 5.5, 2.4, 0, -0.4, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2 + ), + FancyArrow( + 2.0, 1.1, 0.5, 0, fc=arrow2, width=0.25, head_width=0.5, head_length=0.2 + ), + FancyArrow( + 3.3, 1.1, 1.3, 0, fc=arrow2, width=0.25, head_width=0.5, head_length=0.2 + ), + FancyArrow( + 6.2, 1.1, 0.8, 0, fc=arrow2, width=0.25, head_width=0.5, head_length=0.2 + ), + ] + + if supervised: + patches += [ + Rectangle((0.3, 2.4), 1.5, 0.5, zorder=1, fc=box_bg), + Rectangle((0.5, 2.6), 1.5, 0.5, zorder=2, fc=box_bg), + Rectangle((0.7, 2.8), 1.5, 0.5, zorder=3, fc=box_bg), + FancyArrow( + 2.3, 2.9, 2.0, 0, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2 + ), + Rectangle((7.3, 0.85), 1.5, 0.5, fc=box_bg), + ] + else: + patches += [Rectangle((7.3, 0.2), 1.5, 1.8, fc=box_bg)] + + for p in patches: + ax.add_patch(p) + + plt.text( + 1.45, + 4.9, + "Training\nText,\nDocuments,\nImages,\netc.", + ha="center", + va="center", + fontsize=14, + ) + + plt.text(3.6, 4.9, "Feature\nVectors", ha="left", va="center", fontsize=14) + + plt.text( + 5.5, 3.5, "Machine\nLearning\nAlgorithm", ha="center", va="center", fontsize=14 + ) + + plt.text( + 1.05, + 1.1, + "New Text,\nDocument,\nImage,\netc.", + ha="center", + va="center", + fontsize=14, + ) + + plt.text(3.3, 1.7, "Feature\nVector", ha="left", va="center", fontsize=14) + + plt.text(5.5, 1.1, "Predictive\nModel", ha="center", va="center", fontsize=12) + + if supervised: + plt.text(1.45, 3.05, "Labels", ha="center", va="center", fontsize=14) + + plt.text(8.05, 1.1, "Expected\nLabel", ha="center", va="center", fontsize=14) + plt.text( + 8.8, 5.8, "Supervised Learning Model", ha="right", va="top", fontsize=18 + ) + + else: + plt.text( + 8.05, + 1.1, + "Likelihood\nor Cluster ID\nor Better\nRepresentation", + ha="center", + va="center", + fontsize=12, + ) + plt.text( + 8.8, 5.8, "Unsupervised Learning Model", ha="right", va="top", fontsize=18 + ) + + + def plot_supervised_chart(annotate=False): + create_base(supervised=True) + if annotate: + fontdict = {"color": "r", "weight": "bold", "size": 14} + plt.text( + 1.9, + 4.55, + "X = vec.fit_transform(input)", + fontdict=fontdict, + rotation=20, + ha="left", + va="bottom", + ) + plt.text( + 3.7, + 3.2, + "clf.fit(X, y)", + fontdict=fontdict, + rotation=20, + ha="left", + va="bottom", + ) + plt.text( + 1.7, + 1.5, + "X_new = vec.transform(input)", + fontdict=fontdict, + rotation=20, + ha="left", + va="bottom", + ) + plt.text( + 6.1, + 1.5, + "y_new = clf.predict(X_new)", + fontdict=fontdict, + rotation=20, + ha="left", + va="bottom", + ) + + + def plot_unsupervised_chart(): + create_base(supervised=False) + + + if __name__ == "__main__": + plot_supervised_chart(False) + plot_supervised_chart(True) + plot_unsupervised_chart() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.214 seconds) + + +.. _sphx_glr_download_packages_scikit-learn_auto_examples_plot_ML_flow_chart.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_ML_flow_chart.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_ML_flow_chart.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_ML_flow_chart.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-learn/auto_examples/plot_bias_variance.rst.txt b/_sources/packages/scikit-learn/auto_examples/plot_bias_variance.rst.txt new file mode 100644 index 000000000..ddf527145 --- /dev/null +++ b/_sources/packages/scikit-learn/auto_examples/plot_bias_variance.rst.txt @@ -0,0 +1,315 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-learn/auto_examples/plot_bias_variance.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-learn_auto_examples_plot_bias_variance.py: + + +==================================== +Bias and variance of polynomial fit +==================================== + +Demo overfitting, underfitting, and validation and learning curves with +polynomial regression. + +Fit polynomes of different degrees to a dataset: for too small a degree, +the model *underfits*, while for too large a degree, it overfits. + +.. GENERATED FROM PYTHON SOURCE LINES 13-23 + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + + def generating_func(x, rng=None, error=0.5): + rng = np.random.default_rng(rng) + return rng.normal(10 - 1.0 / (x + 0.1), error) + + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 24-25 + +A polynomial regression + +.. GENERATED FROM PYTHON SOURCE LINES 25-29 + +.. code-block:: Python + + from sklearn.pipeline import make_pipeline + from sklearn.linear_model import LinearRegression + from sklearn.preprocessing import PolynomialFeatures + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 30-31 + +A simple figure to illustrate the problem + +.. GENERATED FROM PYTHON SOURCE LINES 31-63 + +.. code-block:: Python + + + n_samples = 8 + + rng = np.random.default_rng(27446968) + x = 10 ** np.linspace(-2, 0, n_samples) + y = generating_func(x, rng=rng) + + x_test = np.linspace(-0.2, 1.2, 1000) + + titles = ["d = 1 (under-fit; high bias)", "d = 2", "d = 6 (over-fit; high variance)"] + degrees = [1, 2, 6] + + fig = plt.figure(figsize=(9, 3.5)) + fig.subplots_adjust(left=0.06, right=0.98, bottom=0.15, top=0.85, wspace=0.05) + + for i, d in enumerate(degrees): + ax = fig.add_subplot(131 + i, xticks=[], yticks=[]) + ax.scatter(x, y, marker="x", c="k", s=50) + + model = make_pipeline(PolynomialFeatures(d), LinearRegression()) + model.fit(x[:, np.newaxis], y) + ax.plot(x_test, model.predict(x_test[:, np.newaxis]), "-b") + + ax.set_xlim(-0.2, 1.2) + ax.set_ylim(0, 12) + ax.set_xlabel("house size") + if i == 0: + ax.set_ylabel("price") + + ax.set_title(titles[i]) + + + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_bias_variance_001.png + :alt: d = 1 (under-fit; high bias), d = 2, d = 6 (over-fit; high variance) + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_bias_variance_001.png + :class: sphx-glr-single-img + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 64-65 + +Generate a larger dataset + +.. GENERATED FROM PYTHON SOURCE LINES 65-85 + +.. code-block:: Python + + from sklearn.model_selection import train_test_split + + n_samples = 200 + test_size = 0.4 + error = 1.0 + + # randomly sample the data + x = rng.random(n_samples) + y = generating_func(x, rng=rng, error=error) + + # split into training, validation, and testing sets. + x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=test_size) + + # show the training and validation sets + plt.figure(figsize=(6, 4)) + plt.scatter(x_train, y_train, color="red", label="Training set") + plt.scatter(x_test, y_test, color="blue", label="Test set") + plt.title("The data") + plt.legend(loc="best") + + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_bias_variance_002.png + :alt: The data + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_bias_variance_002.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 86-87 + +Plot a validation curve + +.. GENERATED FROM PYTHON SOURCE LINES 87-115 + +.. code-block:: Python + + from sklearn.model_selection import validation_curve + + degrees = list(range(1, 21)) + + model = make_pipeline(PolynomialFeatures(), LinearRegression()) + + # The parameter to vary is the "degrees" on the pipeline step + # "polynomialfeatures" + train_scores, validation_scores = validation_curve( + model, + x[:, np.newaxis], + y, + param_name="polynomialfeatures__degree", + param_range=degrees, + ) + + # Plot the mean train error and validation error across folds + plt.figure(figsize=(6, 4)) + plt.plot(degrees, validation_scores.mean(axis=1), lw=2, label="cross-validation") + plt.plot(degrees, train_scores.mean(axis=1), lw=2, label="training") + + plt.legend(loc="best") + plt.xlabel("degree of fit") + plt.ylabel("explained variance") + plt.title("Validation curve") + plt.tight_layout() + + + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_bias_variance_003.png + :alt: Validation curve + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_bias_variance_003.png + :class: sphx-glr-single-img + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 116-120 + +Learning curves +########################################################### + + Plot train and test error with an increasing number of samples + +.. GENERATED FROM PYTHON SOURCE LINES 120-147 + +.. code-block:: Python + + + # A learning curve for d=1, 5, 15 + for d in [1, 5, 15]: + model = make_pipeline(PolynomialFeatures(degree=d), LinearRegression()) + + from sklearn.model_selection import learning_curve + + train_sizes, train_scores, validation_scores = learning_curve( + model, x[:, np.newaxis], y, train_sizes=np.logspace(-1, 0, 20) + ) + + # Plot the mean train error and validation error across folds + plt.figure(figsize=(6, 4)) + plt.plot( + train_sizes, validation_scores.mean(axis=1), lw=2, label="cross-validation" + ) + plt.plot(train_sizes, train_scores.mean(axis=1), lw=2, label="training") + plt.ylim(ymin=-0.1, ymax=1) + + plt.legend(loc="best") + plt.xlabel("number of train samples") + plt.ylabel("explained variance") + plt.title("Learning curve (degree=%i)" % d) + plt.tight_layout() + + + plt.show() + + + +.. rst-class:: sphx-glr-horizontal + + + * + + .. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_bias_variance_004.png + :alt: Learning curve (degree=1) + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_bias_variance_004.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_bias_variance_005.png + :alt: Learning curve (degree=5) + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_bias_variance_005.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_bias_variance_006.png + :alt: Learning curve (degree=15) + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_bias_variance_006.png + :class: sphx-glr-multi-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 1.391 seconds) + + +.. _sphx_glr_download_packages_scikit-learn_auto_examples_plot_bias_variance.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_bias_variance.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_bias_variance.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_bias_variance.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-learn/auto_examples/plot_california_prediction.rst.txt b/_sources/packages/scikit-learn/auto_examples/plot_california_prediction.rst.txt new file mode 100644 index 000000000..1b993dcc5 --- /dev/null +++ b/_sources/packages/scikit-learn/auto_examples/plot_california_prediction.rst.txt @@ -0,0 +1,287 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-learn/auto_examples/plot_california_prediction.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-learn_auto_examples_plot_california_prediction.py: + + +A simple regression analysis on the California housing data +=========================================================== + +Here we perform a simple regression analysis on the California housing +data, exploring two types of regressors. + +.. GENERATED FROM PYTHON SOURCE LINES 9-14 + +.. code-block:: Python + + + from sklearn.datasets import fetch_california_housing + + data = fetch_california_housing(as_frame=True) + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 15-16 + +Print a histogram of the quantity to predict: price + +.. GENERATED FROM PYTHON SOURCE LINES 16-24 + +.. code-block:: Python + + import matplotlib.pyplot as plt + + plt.figure(figsize=(4, 3)) + plt.hist(data.target) + plt.xlabel("price ($100k)") + plt.ylabel("count") + plt.tight_layout() + + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_001.png + :alt: plot california prediction + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_001.png + :class: sphx-glr-single-img + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 25-26 + +Print the join histogram for each feature + +.. GENERATED FROM PYTHON SOURCE LINES 26-35 + +.. code-block:: Python + + + for index, feature_name in enumerate(data.feature_names): + plt.figure(figsize=(4, 3)) + plt.scatter(data.data[feature_name], data.target) + plt.ylabel("Price", size=15) + plt.xlabel(feature_name, size=15) + plt.tight_layout() + + + + + +.. rst-class:: sphx-glr-horizontal + + + * + + .. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_002.png + :alt: plot california prediction + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_002.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_003.png + :alt: plot california prediction + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_003.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_004.png + :alt: plot california prediction + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_004.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_005.png + :alt: plot california prediction + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_005.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_006.png + :alt: plot california prediction + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_006.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_007.png + :alt: plot california prediction + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_007.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_008.png + :alt: plot california prediction + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_008.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_009.png + :alt: plot california prediction + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_009.png + :class: sphx-glr-multi-img + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 36-37 + +Simple prediction + +.. GENERATED FROM PYTHON SOURCE LINES 37-58 + +.. code-block:: Python + + + from sklearn.model_selection import train_test_split + + X_train, X_test, y_train, y_test = train_test_split(data.data, data.target) + + from sklearn.linear_model import LinearRegression + + clf = LinearRegression() + clf.fit(X_train, y_train) + predicted = clf.predict(X_test) + expected = y_test + + plt.figure(figsize=(4, 3)) + plt.scatter(expected, predicted) + plt.plot([0, 8], [0, 8], "--k") + plt.axis("tight") + plt.xlabel("True price ($100k)") + plt.ylabel("Predicted price ($100k)") + plt.tight_layout() + + + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_010.png + :alt: plot california prediction + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_010.png + :class: sphx-glr-single-img + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 59-60 + +Prediction with gradient boosted tree + +.. GENERATED FROM PYTHON SOURCE LINES 60-77 + +.. code-block:: Python + + + from sklearn.ensemble import GradientBoostingRegressor + + clf = GradientBoostingRegressor() + clf.fit(X_train, y_train) + + predicted = clf.predict(X_test) + expected = y_test + + plt.figure(figsize=(4, 3)) + plt.scatter(expected, predicted) + plt.plot([0, 5], [0, 5], "--k") + plt.axis("tight") + plt.xlabel("True price ($100k)") + plt.ylabel("Predicted price ($100k)") + plt.tight_layout() + + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_011.png + :alt: plot california prediction + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_california_prediction_011.png + :class: sphx-glr-single-img + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 78-79 + +Print the error rate + +.. GENERATED FROM PYTHON SOURCE LINES 79-84 + +.. code-block:: Python + + import numpy as np + + print(f"RMS: {np.sqrt(np.mean((predicted - expected) ** 2))!r} ") + + plt.show() + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + RMS: np.float64(0.5314909993118918) + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 4.717 seconds) + + +.. _sphx_glr_download_packages_scikit-learn_auto_examples_plot_california_prediction.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_california_prediction.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_california_prediction.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_california_prediction.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-learn/auto_examples/plot_compare_classifiers.rst.txt b/_sources/packages/scikit-learn/auto_examples/plot_compare_classifiers.rst.txt new file mode 100644 index 000000000..5586095fa --- /dev/null +++ b/_sources/packages/scikit-learn/auto_examples/plot_compare_classifiers.rst.txt @@ -0,0 +1,132 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-learn/auto_examples/plot_compare_classifiers.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-learn_auto_examples_plot_compare_classifiers.py: + + +Compare classifiers on the digits data +======================================= + +Compare the performance of a variety of classifiers on a test set for the +digits data. + +.. GENERATED FROM PYTHON SOURCE LINES 8-45 + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + LinearSVC: 0.9344942114287969 + GaussianNB: 0.8332741681010102 + KNeighborsClassifier: 0.9804562804949924 + ------------------ + /opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages/sklearn/svm/_base.py:1235: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations. + warnings.warn( + LinearSVC(loss='hinge'): 0.9294570108037394 + LinearSVC(loss='squared_hinge'): 0.9344942114287969 + ------------------- + KNeighbors(n_neighbors=1): 0.9913675218842191 + KNeighbors(n_neighbors=2): 0.9848442068835102 + KNeighbors(n_neighbors=3): 0.9867753449543099 + KNeighbors(n_neighbors=4): 0.9803719053818863 + KNeighbors(n_neighbors=5): 0.9804562804949924 + KNeighbors(n_neighbors=6): 0.9757924194139573 + KNeighbors(n_neighbors=7): 0.9780645792142071 + KNeighbors(n_neighbors=8): 0.9780645792142071 + KNeighbors(n_neighbors=9): 0.9780645792142071 + KNeighbors(n_neighbors=10): 0.9755550897728812 + + + + + + +| + +.. code-block:: Python + + + from sklearn import model_selection, datasets, metrics + from sklearn.svm import LinearSVC + from sklearn.naive_bayes import GaussianNB + from sklearn.neighbors import KNeighborsClassifier + + digits = datasets.load_digits() + X = digits.data + y = digits.target + X_train, X_test, y_train, y_test = model_selection.train_test_split( + X, y, test_size=0.25, random_state=0 + ) + + for Model in [LinearSVC, GaussianNB, KNeighborsClassifier]: + clf = Model().fit(X_train, y_train) + y_pred = clf.predict(X_test) + print(f"{Model.__name__}: {metrics.f1_score(y_test, y_pred, average='macro')}") + + print("------------------") + + # test SVC loss + for loss in ["hinge", "squared_hinge"]: + clf = LinearSVC(loss=loss).fit(X_train, y_train) + y_pred = clf.predict(X_test) + print( + f"LinearSVC(loss='{loss}'): {metrics.f1_score(y_test, y_pred, average='macro')}" + ) + + print("-------------------") + + # test the number of neighbors + for n_neighbors in range(1, 11): + clf = KNeighborsClassifier(n_neighbors=n_neighbors).fit(X_train, y_train) + y_pred = clf.predict(X_test) + print( + f"KNeighbors(n_neighbors={n_neighbors}): {metrics.f1_score(y_test, y_pred, average='macro')}" + ) + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.258 seconds) + + +.. _sphx_glr_download_packages_scikit-learn_auto_examples_plot_compare_classifiers.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_compare_classifiers.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_compare_classifiers.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_compare_classifiers.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-learn/auto_examples/plot_digits_simple_classif.rst.txt b/_sources/packages/scikit-learn/auto_examples/plot_digits_simple_classif.rst.txt new file mode 100644 index 000000000..2bc74f664 --- /dev/null +++ b/_sources/packages/scikit-learn/auto_examples/plot_digits_simple_classif.rst.txt @@ -0,0 +1,342 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-learn/auto_examples/plot_digits_simple_classif.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-learn_auto_examples_plot_digits_simple_classif.py: + + +Simple visualization and classification of the digits dataset +============================================================= + +Plot the first few samples of the digits dataset and a 2D representation +built using PCA, then do a simple classification + +.. GENERATED FROM PYTHON SOURCE LINES 8-13 + +.. code-block:: Python + + + from sklearn.datasets import load_digits + + digits = load_digits() + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 14-18 + +Plot the data: images of digits +------------------------------- + +Each data in a 8x8 image + +.. GENERATED FROM PYTHON SOURCE LINES 18-30 + +.. code-block:: Python + + import matplotlib.pyplot as plt + + fig = plt.figure(figsize=(6, 6)) # figure size in inches + fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05) + + for i in range(64): + ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[]) + ax.imshow(digits.images[i], cmap="binary", interpolation="nearest") + # label the image with the target value + ax.text(0, 7, str(digits.target[i])) + + + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_digits_simple_classif_001.png + :alt: plot digits simple classif + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_digits_simple_classif_001.png + :class: sphx-glr-single-img + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 31-33 + +Plot a projection on the 2 first principal axis +------------------------------------------------ + +.. GENERATED FROM PYTHON SOURCE LINES 33-44 + +.. code-block:: Python + + + plt.figure() + + from sklearn.decomposition import PCA + + pca = PCA(n_components=2) + proj = pca.fit_transform(digits.data) + plt.scatter(proj[:, 0], proj[:, 1], c=digits.target, cmap="Paired") + plt.colorbar() + + + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_digits_simple_classif_002.png + :alt: plot digits simple classif + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_digits_simple_classif_002.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 45-47 + +Classify with Gaussian naive Bayes +---------------------------------- + +.. GENERATED FROM PYTHON SOURCE LINES 47-78 + +.. code-block:: Python + + + from sklearn.naive_bayes import GaussianNB + from sklearn.model_selection import train_test_split + + # split the data into training and validation sets + X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target) + + # train the model + clf = GaussianNB() + clf.fit(X_train, y_train) + + # use the model to predict the labels of the test data + predicted = clf.predict(X_test) + expected = y_test + + # Plot the prediction + fig = plt.figure(figsize=(6, 6)) # figure size in inches + fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05) + + # plot the digits: each image is 8x8 pixels + for i in range(64): + ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[]) + ax.imshow(X_test.reshape(-1, 8, 8)[i], cmap="binary", interpolation="nearest") + + # label the image with the target value + if predicted[i] == expected[i]: + ax.text(0, 7, str(predicted[i]), color="green") + else: + ax.text(0, 7, str(predicted[i]), color="red") + + + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_digits_simple_classif_003.png + :alt: plot digits simple classif + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_digits_simple_classif_003.png + :class: sphx-glr-single-img + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 79-83 + +Quantify the performance +------------------------ + +First print the number of correct matches + +.. GENERATED FROM PYTHON SOURCE LINES 83-85 + +.. code-block:: Python + + matches = predicted == expected + print(matches.sum()) + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + 395 + + + + +.. GENERATED FROM PYTHON SOURCE LINES 86-87 + +The total number of data points + +.. GENERATED FROM PYTHON SOURCE LINES 87-88 + +.. code-block:: Python + + print(len(matches)) + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + 450 + + + + +.. GENERATED FROM PYTHON SOURCE LINES 89-90 + +And now, the ration of correct predictions + +.. GENERATED FROM PYTHON SOURCE LINES 90-92 + +.. code-block:: Python + + matches.sum() / float(len(matches)) + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + np.float64(0.8777777777777778) + + + +.. GENERATED FROM PYTHON SOURCE LINES 93-94 + +Print the classification report + +.. GENERATED FROM PYTHON SOURCE LINES 94-98 + +.. code-block:: Python + + from sklearn import metrics + + print(metrics.classification_report(expected, predicted)) + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + precision recall f1-score support + + 0 0.97 0.95 0.96 37 + 1 0.83 0.85 0.84 41 + 2 0.89 0.84 0.86 49 + 3 0.93 0.83 0.88 47 + 4 0.93 0.90 0.92 42 + 5 0.89 0.95 0.92 42 + 6 0.98 0.97 0.97 60 + 7 0.81 0.98 0.88 47 + 8 0.65 0.87 0.75 39 + 9 0.97 0.63 0.76 46 + + accuracy 0.88 450 + macro avg 0.89 0.88 0.87 450 + weighted avg 0.89 0.88 0.88 450 + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 99-100 + +Print the confusion matrix + +.. GENERATED FROM PYTHON SOURCE LINES 100-103 + +.. code-block:: Python + + print(metrics.confusion_matrix(expected, predicted)) + + plt.show() + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + [[35 0 0 0 1 0 0 1 0 0] + [ 0 35 0 0 0 0 1 1 4 0] + [ 0 1 41 0 0 0 0 0 7 0] + [ 0 0 2 39 0 1 0 2 2 1] + [ 0 1 0 0 38 0 0 2 1 0] + [ 0 0 0 0 1 40 0 1 0 0] + [ 0 0 1 0 1 0 58 0 0 0] + [ 0 0 0 0 0 1 0 46 0 0] + [ 0 2 0 1 0 1 0 1 34 0] + [ 1 3 2 2 0 2 0 3 4 29]] + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 1.749 seconds) + + +.. _sphx_glr_download_packages_scikit-learn_auto_examples_plot_digits_simple_classif.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_digits_simple_classif.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_digits_simple_classif.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_digits_simple_classif.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-learn/auto_examples/plot_eigenfaces.rst.txt b/_sources/packages/scikit-learn/auto_examples/plot_eigenfaces.rst.txt new file mode 100644 index 000000000..12fb5cef8 --- /dev/null +++ b/_sources/packages/scikit-learn/auto_examples/plot_eigenfaces.rst.txt @@ -0,0 +1,1374 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-learn/auto_examples/plot_eigenfaces.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-learn_auto_examples_plot_eigenfaces.py: + + +The eigenfaces example: chaining PCA and SVMs +============================================= + +The goal of this example is to show how an unsupervised method and a +supervised one can be chained for better prediction. It starts with a +didactic but lengthy way of doing things, and finishes with the +idiomatic approach to pipelining in scikit-learn. + +Here we'll take a look at a simple facial recognition example. Ideally, +we would use a dataset consisting of a subset of the `Labeled Faces in +the Wild `__ data that is available +with :func:`sklearn.datasets.fetch_lfw_people`. However, this is a +relatively large download (~200MB) so we will do the tutorial on a +simpler, less rich dataset. Feel free to explore the LFW dataset. + +.. GENERATED FROM PYTHON SOURCE LINES 17-23 + +.. code-block:: Python + + + from sklearn import datasets + + faces = datasets.fetch_olivetti_faces() + faces.data.shape + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + downloading Olivetti faces from https://ndownloader.figshare.com/files/5976027 to /home/runner/scikit_learn_data + + (400, 4096) + + + +.. GENERATED FROM PYTHON SOURCE LINES 24-25 + +Let's visualize these faces to see what we're working with + +.. GENERATED FROM PYTHON SOURCE LINES 25-34 + +.. code-block:: Python + + + import matplotlib.pyplot as plt + + fig = plt.figure(figsize=(8, 6)) + # plot several images + for i in range(15): + ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[]) + ax.imshow(faces.images[i], cmap="bone") + + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_eigenfaces_001.png + :alt: plot eigenfaces + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_eigenfaces_001.png + :class: sphx-glr-single-img + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 35-49 + +.. tip:: + + Note is that these faces have already been localized and scaled to a + common size. This is an important preprocessing piece for facial + recognition, and is a process that can require a large collection of + training data. This can be done in scikit-learn, but the challenge is + gathering a sufficient amount of training data for the algorithm to work. + Fortunately, this piece is common enough that it has been done. One good + resource is + `OpenCV `__, + the *Open Computer Vision Library*. + +We'll perform a Support Vector classification of the images. We'll do a +typical train-test split on the images: + +.. GENERATED FROM PYTHON SOURCE LINES 49-58 + +.. code-block:: Python + + + from sklearn.model_selection import train_test_split + + X_train, X_test, y_train, y_test = train_test_split( + faces.data, faces.target, random_state=0 + ) + + print(X_train.shape, X_test.shape) + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + (300, 4096) (100, 4096) + + + + +.. GENERATED FROM PYTHON SOURCE LINES 59-65 + +Preprocessing: Principal Component Analysis +------------------------------------------- + +1850 dimensions is a lot for SVM. We can use PCA to reduce these 1850 +features to a manageable size, while maintaining most of the information +in the dataset. + +.. GENERATED FROM PYTHON SOURCE LINES 65-71 + +.. code-block:: Python + + + from sklearn import decomposition + + pca = decomposition.PCA(n_components=150, whiten=True) + pca.fit(X_train) + + + + + + +.. raw:: html + +
+
PCA(n_components=150, whiten=True)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
+
+
+
+ +.. GENERATED FROM PYTHON SOURCE LINES 72-74 + +One interesting part of PCA is that it computes the "mean" face, which +can be interesting to examine: + +.. GENERATED FROM PYTHON SOURCE LINES 74-77 + +.. code-block:: Python + + + plt.imshow(pca.mean_.reshape(faces.images[0].shape), cmap="bone") + + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_eigenfaces_002.png + :alt: plot eigenfaces + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_eigenfaces_002.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 78-80 + +The principal components measure deviations about this mean along +orthogonal axes. + +.. GENERATED FROM PYTHON SOURCE LINES 80-83 + +.. code-block:: Python + + + print(pca.components_.shape) + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + (150, 4096) + + + + +.. GENERATED FROM PYTHON SOURCE LINES 84-85 + +It is also interesting to visualize these principal components: + +.. GENERATED FROM PYTHON SOURCE LINES 85-91 + +.. code-block:: Python + + + fig = plt.figure(figsize=(16, 6)) + for i in range(30): + ax = fig.add_subplot(3, 10, i + 1, xticks=[], yticks=[]) + ax.imshow(pca.components_[i].reshape(faces.images[0].shape), cmap="bone") + + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_eigenfaces_003.png + :alt: plot eigenfaces + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_eigenfaces_003.png + :class: sphx-glr-single-img + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 92-99 + +The components ("eigenfaces") are ordered by their importance from +top-left to bottom-right. We see that the first few components seem to +primarily take care of lighting conditions; the remaining components +pull out certain identifying features: the nose, eyes, eyebrows, etc. + +With this projection computed, we can now project our original training +and test data onto the PCA basis: + +.. GENERATED FROM PYTHON SOURCE LINES 99-103 + +.. code-block:: Python + + + X_train_pca = pca.transform(X_train) + X_test_pca = pca.transform(X_test) + print(X_train_pca.shape) + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + (300, 150) + + + + +.. GENERATED FROM PYTHON SOURCE LINES 104-106 + +.. code-block:: Python + + print(X_test_pca.shape) + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + (100, 150) + + + + +.. GENERATED FROM PYTHON SOURCE LINES 107-116 + +These projected components correspond to factors in a linear combination +of component images such that the combination approaches the original +face. + +Doing the Learning: Support Vector Machines +------------------------------------------- + +Now we'll perform support-vector-machine classification on this reduced +dataset: + +.. GENERATED FROM PYTHON SOURCE LINES 116-122 + +.. code-block:: Python + + + from sklearn import svm + + clf = svm.SVC(C=5.0, gamma=0.001) + clf.fit(X_train_pca, y_train) + + + + + + +.. raw:: html + +
+
SVC(C=5.0, gamma=0.001)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
+
+
+
+ +.. GENERATED FROM PYTHON SOURCE LINES 123-126 + +Finally, we can evaluate how well this classification did. First, we +might plot a few of the test-cases with the labels learned from the +training set: + +.. GENERATED FROM PYTHON SOURCE LINES 126-137 + +.. code-block:: Python + + + import numpy as np + + fig = plt.figure(figsize=(8, 6)) + for i in range(15): + ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[]) + ax.imshow(X_test[i].reshape(faces.images[0].shape), cmap="bone") + y_pred = clf.predict(X_test_pca[i, np.newaxis])[0] + color = "black" if y_pred == y_test[i] else "red" + ax.set_title(y_pred, fontsize="small", color=color) + + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_eigenfaces_004.png + :alt: 13, 30, 34, 19, 24, 6, 15, 26, 14, 21, 3, 13, 11, 34, 1 + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_eigenfaces_004.png + :class: sphx-glr-single-img + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 138-147 + +The classifier is correct on an impressive number of images given the +simplicity of its learning model! Using a linear classifier on 150 +features derived from the pixel-level data, the algorithm correctly +identifies a large number of the people in the images. + +Again, we can quantify this effectiveness using one of several measures +from :mod:`sklearn.metrics`. First we can do the classification +report, which shows the precision, recall and other measures of the +"goodness" of the classification: + +.. GENERATED FROM PYTHON SOURCE LINES 147-153 + +.. code-block:: Python + + + from sklearn import metrics + + y_pred = clf.predict(X_test_pca) + print(metrics.classification_report(y_test, y_pred)) + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + precision recall f1-score support + + 0 1.00 0.50 0.67 6 + 1 1.00 1.00 1.00 4 + 2 0.50 1.00 0.67 2 + 3 1.00 1.00 1.00 1 + 4 0.33 1.00 0.50 1 + 5 1.00 1.00 1.00 5 + 6 1.00 1.00 1.00 4 + 7 1.00 0.67 0.80 3 + 9 1.00 1.00 1.00 1 + 10 1.00 1.00 1.00 4 + 11 1.00 1.00 1.00 1 + 12 0.67 1.00 0.80 2 + 13 1.00 1.00 1.00 3 + 14 1.00 1.00 1.00 5 + 15 1.00 1.00 1.00 3 + 17 1.00 1.00 1.00 6 + 19 1.00 1.00 1.00 4 + 20 1.00 1.00 1.00 1 + 21 1.00 1.00 1.00 1 + 22 1.00 1.00 1.00 2 + 23 1.00 1.00 1.00 1 + 24 1.00 1.00 1.00 2 + 25 1.00 0.50 0.67 2 + 26 1.00 0.75 0.86 4 + 27 1.00 1.00 1.00 1 + 28 0.67 1.00 0.80 2 + 29 1.00 1.00 1.00 3 + 30 1.00 1.00 1.00 4 + 31 1.00 1.00 1.00 3 + 32 1.00 1.00 1.00 3 + 33 1.00 1.00 1.00 2 + 34 1.00 1.00 1.00 3 + 35 1.00 1.00 1.00 1 + 36 1.00 1.00 1.00 3 + 37 1.00 1.00 1.00 3 + 38 1.00 1.00 1.00 1 + 39 1.00 1.00 1.00 3 + + accuracy 0.94 100 + macro avg 0.95 0.96 0.94 100 + weighted avg 0.97 0.94 0.94 100 + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 154-158 + +Another interesting metric is the *confusion matrix*, which indicates +how often any two items are mixed-up. The confusion matrix of a perfect +classifier would only have nonzero entries on the diagonal, with zeros +on the off-diagonal: + +.. GENERATED FROM PYTHON SOURCE LINES 158-161 + +.. code-block:: Python + + + print(metrics.confusion_matrix(y_test, y_pred)) + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + [[3 0 0 ... 0 0 0] + [0 4 0 ... 0 0 0] + [0 0 2 ... 0 0 0] + ... + [0 0 0 ... 3 0 0] + [0 0 0 ... 0 1 0] + [0 0 0 ... 0 0 3]] + + + + +.. GENERATED FROM PYTHON SOURCE LINES 162-171 + +Pipelining +---------- + +Above we used PCA as a pre-processing step before applying our support +vector machine classifier. Plugging the output of one estimator directly +into the input of a second estimator is a commonly used pattern; for +this reason scikit-learn provides a ``Pipeline`` object which automates +this process. The above problem can be re-expressed as a pipeline as +follows: + +.. GENERATED FROM PYTHON SOURCE LINES 171-187 + +.. code-block:: Python + + + from sklearn.pipeline import Pipeline + + clf = Pipeline( + [ + ("pca", decomposition.PCA(n_components=150, whiten=True)), + ("svm", svm.LinearSVC(C=1.0)), + ] + ) + + clf.fit(X_train, y_train) + + y_pred = clf.predict(X_test) + print(metrics.confusion_matrix(y_pred, y_test)) + plt.show() + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + [[4 0 0 ... 0 0 0] + [0 4 0 ... 0 0 0] + [0 0 1 ... 0 0 0] + ... + [1 0 0 ... 3 0 0] + [0 0 0 ... 0 1 0] + [0 0 0 ... 0 0 3]] + + + + +.. GENERATED FROM PYTHON SOURCE LINES 188-197 + +A Note on Facial Recognition +---------------------------- + +Here we have used PCA "eigenfaces" as a pre-processing step for facial +recognition. The reason we chose this is because PCA is a +broadly-applicable technique, which can be useful for a wide array of +data types. Research in the field of facial recognition in particular, +however, has shown that other more specific feature extraction methods +are can be much more effective. + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 4.145 seconds) + + +.. _sphx_glr_download_packages_scikit-learn_auto_examples_plot_eigenfaces.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_eigenfaces.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_eigenfaces.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_eigenfaces.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-learn/auto_examples/plot_iris_knn.rst.txt b/_sources/packages/scikit-learn/auto_examples/plot_iris_knn.rst.txt new file mode 100644 index 000000000..05a20ff90 --- /dev/null +++ b/_sources/packages/scikit-learn/auto_examples/plot_iris_knn.rst.txt @@ -0,0 +1,165 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-learn/auto_examples/plot_iris_knn.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-learn_auto_examples_plot_iris_knn.py: + + +Nearest-neighbor prediction on iris +==================================== + +Plot the decision boundary of nearest neighbor decision on iris, first +with a single nearest neighbor, and then using 3 nearest neighbors. + +.. GENERATED FROM PYTHON SOURCE LINES 8-32 + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + from sklearn import neighbors, datasets + from matplotlib.colors import ListedColormap + + # Create color maps for 3-class classification problem, as with iris + cmap_light = ListedColormap(["#FFAAAA", "#AAFFAA", "#AAAAFF"]) + cmap_bold = ListedColormap(["#FF0000", "#00FF00", "#0000FF"]) + + iris = datasets.load_iris() + X = iris.data[:, :2] # we only take the first two features. We could + # avoid this ugly slicing by using a two-dim dataset + y = iris.target + + knn = neighbors.KNeighborsClassifier(n_neighbors=1) + knn.fit(X, y) + + x_min, x_max = X[:, 0].min() - 0.1, X[:, 0].max() + 0.1 + y_min, y_max = X[:, 1].min() - 0.1, X[:, 1].max() + 0.1 + xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100), np.linspace(y_min, y_max, 100)) + Z = knn.predict(np.c_[xx.ravel(), yy.ravel()]) + + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 33-34 + +Put the result into a color plot + +.. GENERATED FROM PYTHON SOURCE LINES 34-45 + +.. code-block:: Python + + Z = Z.reshape(xx.shape) + plt.figure() + plt.pcolormesh(xx, yy, Z, cmap=cmap_light) + + # Plot also the training points + plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold) + plt.xlabel("sepal length (cm)") + plt.ylabel("sepal width (cm)") + plt.axis("tight") + + + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_iris_knn_001.png + :alt: plot iris knn + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_iris_knn_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + (np.float64(4.180808080808081), np.float64(8.019191919191918), np.float64(1.8868686868686868), np.float64(4.513131313131313)) + + + +.. GENERATED FROM PYTHON SOURCE LINES 46-47 + +And now, redo the analysis with 3 neighbors + +.. GENERATED FROM PYTHON SOURCE LINES 47-64 + +.. code-block:: Python + + knn = neighbors.KNeighborsClassifier(n_neighbors=3) + knn.fit(X, y) + + Z = knn.predict(np.c_[xx.ravel(), yy.ravel()]) + + # Put the result into a color plot + Z = Z.reshape(xx.shape) + plt.figure() + plt.pcolormesh(xx, yy, Z, cmap=cmap_light) + + # Plot also the training points + plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold) + plt.xlabel("sepal length (cm)") + plt.ylabel("sepal width (cm)") + plt.axis("tight") + + plt.show() + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_iris_knn_002.png + :alt: plot iris knn + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_iris_knn_002.png + :class: sphx-glr-single-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.795 seconds) + + +.. _sphx_glr_download_packages_scikit-learn_auto_examples_plot_iris_knn.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_iris_knn.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_iris_knn.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_iris_knn.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-learn/auto_examples/plot_iris_scatter.rst.txt b/_sources/packages/scikit-learn/auto_examples/plot_iris_scatter.rst.txt new file mode 100644 index 000000000..9226ad592 --- /dev/null +++ b/_sources/packages/scikit-learn/auto_examples/plot_iris_scatter.rst.txt @@ -0,0 +1,98 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-learn/auto_examples/plot_iris_scatter.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-learn_auto_examples_plot_iris_scatter.py: + + +Plot 2D views of the iris dataset +================================= + +Plot a simple scatter plot of 2 features of the iris dataset. + +Note that more elaborate visualization of this dataset is detailed +in the :ref:`statistics` chapter. + +.. GENERATED FROM PYTHON SOURCE LINES 10-34 + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_iris_scatter_001.png + :alt: plot iris scatter + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_iris_scatter_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + # Load the data + from sklearn.datasets import load_iris + + iris = load_iris() + + from matplotlib import ticker + import matplotlib.pyplot as plt + + # The indices of the features that we are plotting + x_index = 0 + y_index = 1 + + # this formatter will label the colorbar with the correct target names + formatter = ticker.FuncFormatter(lambda i, *args: iris.target_names[int(i)]) + + plt.figure(figsize=(5, 4)) + plt.scatter(iris.data[:, x_index], iris.data[:, y_index], c=iris.target) + plt.colorbar(ticks=[0, 1, 2], format=formatter) + plt.xlabel(iris.feature_names[x_index]) + plt.ylabel(iris.feature_names[y_index]) + + plt.tight_layout() + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.093 seconds) + + +.. _sphx_glr_download_packages_scikit-learn_auto_examples_plot_iris_scatter.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_iris_scatter.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_iris_scatter.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_iris_scatter.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-learn/auto_examples/plot_linear_model_cv.rst.txt b/_sources/packages/scikit-learn/auto_examples/plot_linear_model_cv.rst.txt new file mode 100644 index 000000000..3e3a8c14b --- /dev/null +++ b/_sources/packages/scikit-learn/auto_examples/plot_linear_model_cv.rst.txt @@ -0,0 +1,147 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-learn/auto_examples/plot_linear_model_cv.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-learn_auto_examples_plot_linear_model_cv.py: + + +================================================================ +Use the RidgeCV and LassoCV to set the regularization parameter +================================================================ + +.. GENERATED FROM PYTHON SOURCE LINES 10-11 + +Load the diabetes dataset + +.. GENERATED FROM PYTHON SOURCE LINES 11-17 + +.. code-block:: Python + + from sklearn.datasets import load_diabetes + + data = load_diabetes() + X, y = data.data, data.target + print(X.shape) + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + (442, 10) + + + + +.. GENERATED FROM PYTHON SOURCE LINES 18-19 + +Compute the cross-validation score with the default hyper-parameters + +.. GENERATED FROM PYTHON SOURCE LINES 19-26 + +.. code-block:: Python + + from sklearn.model_selection import cross_val_score + from sklearn.linear_model import Ridge, Lasso + + for Model in [Ridge, Lasso]: + model = Model() + print(f"{Model.__name__}: {cross_val_score(model, X, y).mean()}") + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + Ridge: 0.410174971340889 + Lasso: 0.3375593674654274 + + + + +.. GENERATED FROM PYTHON SOURCE LINES 27-29 + +We compute the cross-validation score as a function of alpha, the +strength of the regularization for Lasso and Ridge + +.. GENERATED FROM PYTHON SOURCE LINES 29-45 + +.. code-block:: Python + + import numpy as np + import matplotlib.pyplot as plt + + alphas = np.logspace(-3, -1, 30) + + plt.figure(figsize=(5, 3)) + + for Model in [Lasso, Ridge]: + scores = [cross_val_score(Model(alpha), X, y, cv=3).mean() for alpha in alphas] + plt.plot(alphas, scores, label=Model.__name__) + + plt.legend(loc="lower left") + plt.xlabel("alpha") + plt.ylabel("cross validation score") + plt.tight_layout() + plt.show() + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_linear_model_cv_001.png + :alt: plot linear model cv + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_linear_model_cv_001.png + :class: sphx-glr-single-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.391 seconds) + + +.. _sphx_glr_download_packages_scikit-learn_auto_examples_plot_linear_model_cv.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_linear_model_cv.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_linear_model_cv.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_linear_model_cv.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-learn/auto_examples/plot_linear_regression.rst.txt b/_sources/packages/scikit-learn/auto_examples/plot_linear_regression.rst.txt new file mode 100644 index 000000000..6017b51ae --- /dev/null +++ b/_sources/packages/scikit-learn/auto_examples/plot_linear_regression.rst.txt @@ -0,0 +1,102 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-learn/auto_examples/plot_linear_regression.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-learn_auto_examples_plot_linear_regression.py: + + +A simple linear regression +=========================== + +.. GENERATED FROM PYTHON SOURCE LINES 6-39 + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_linear_regression_001.png + :alt: plot linear regression + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_linear_regression_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + from sklearn.linear_model import LinearRegression + + # x from 0 to 30 + rng = np.random.default_rng() + x = 30 * rng.random((20, 1)) + + # y = a*x + b with noise + y = 0.5 * x + 1.0 + rng.normal(size=x.shape) + + # create a linear regression model + model = LinearRegression() + model.fit(x, y) + + # predict y from the data + x_new = np.linspace(0, 30, 100) + y_new = model.predict(x_new[:, np.newaxis]) + + # plot the results + plt.figure(figsize=(4, 3)) + ax = plt.axes() + ax.scatter(x, y) + ax.plot(x_new, y_new) + + ax.set_xlabel("x") + ax.set_ylabel("y") + + ax.axis("tight") + + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.047 seconds) + + +.. _sphx_glr_download_packages_scikit-learn_auto_examples_plot_linear_regression.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_linear_regression.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_linear_regression.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_linear_regression.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-learn/auto_examples/plot_measuring_performance.rst.txt b/_sources/packages/scikit-learn/auto_examples/plot_measuring_performance.rst.txt new file mode 100644 index 000000000..208cf7069 --- /dev/null +++ b/_sources/packages/scikit-learn/auto_examples/plot_measuring_performance.rst.txt @@ -0,0 +1,137 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-learn/auto_examples/plot_measuring_performance.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-learn_auto_examples_plot_measuring_performance.py: + + +Measuring Decision Tree performance +==================================== + +Demonstrates overfit when testing on train set. + +.. GENERATED FROM PYTHON SOURCE LINES 9-10 + +Get the data + +.. GENERATED FROM PYTHON SOURCE LINES 10-15 + +.. code-block:: Python + + + from sklearn.datasets import fetch_california_housing + + data = fetch_california_housing(as_frame=True) + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 16-17 + +Train and test a model + +.. GENERATED FROM PYTHON SOURCE LINES 17-24 + +.. code-block:: Python + + from sklearn.tree import DecisionTreeRegressor + + clf = DecisionTreeRegressor().fit(data.data, data.target) + + predicted = clf.predict(data.data) + expected = data.target + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 25-26 + +Plot predicted as a function of expected + +.. GENERATED FROM PYTHON SOURCE LINES 26-37 + +.. code-block:: Python + + + import matplotlib.pyplot as plt + + plt.figure(figsize=(4, 3)) + plt.scatter(expected, predicted) + plt.plot([0, 5], [0, 5], "--k") + plt.axis("tight") + plt.xlabel("True price ($100k)") + plt.ylabel("Predicted price ($100k)") + plt.tight_layout() + + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_measuring_performance_001.png + :alt: plot measuring performance + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_measuring_performance_001.png + :class: sphx-glr-single-img + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 38-44 + +Pretty much no errors! + +This is too good to be true: we are testing the model on the train +data, which is not a measure of generalization. + +**The results are not valid** + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 1.300 seconds) + + +.. _sphx_glr_download_packages_scikit-learn_auto_examples_plot_measuring_performance.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_measuring_performance.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_measuring_performance.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_measuring_performance.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-learn/auto_examples/plot_pca.rst.txt b/_sources/packages/scikit-learn/auto_examples/plot_pca.rst.txt new file mode 100644 index 000000000..9021418ec --- /dev/null +++ b/_sources/packages/scikit-learn/auto_examples/plot_pca.rst.txt @@ -0,0 +1,551 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-learn/auto_examples/plot_pca.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-learn_auto_examples_plot_pca.py: + + +=============== +Demo PCA in 2D +=============== + +.. GENERATED FROM PYTHON SOURCE LINES 9-10 + +Load the iris data + +.. GENERATED FROM PYTHON SOURCE LINES 10-16 + +.. code-block:: Python + + from sklearn import datasets + + iris = datasets.load_iris() + X = iris.data + y = iris.target + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 17-18 + +Fit a PCA + +.. GENERATED FROM PYTHON SOURCE LINES 18-23 + +.. code-block:: Python + + from sklearn.decomposition import PCA + + pca = PCA(n_components=2, whiten=True) + pca.fit(X) + + + + + + +.. raw:: html + +
+
PCA(n_components=2, whiten=True)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
+
+
+
+ +.. GENERATED FROM PYTHON SOURCE LINES 24-25 + +Project the data in 2D + +.. GENERATED FROM PYTHON SOURCE LINES 25-27 + +.. code-block:: Python + + X_pca = pca.transform(X) + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 28-29 + +Visualize the data + +.. GENERATED FROM PYTHON SOURCE LINES 29-38 + +.. code-block:: Python + + target_ids = range(len(iris.target_names)) + + import matplotlib.pyplot as plt + + plt.figure(figsize=(6, 5)) + for i, c, label in zip(target_ids, "rgbcmykw", iris.target_names, strict=False): + plt.scatter(X_pca[y == i, 0], X_pca[y == i, 1], c=c, label=label) + plt.legend() + plt.show() + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_pca_001.png + :alt: plot pca + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_pca_001.png + :class: sphx-glr-single-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.099 seconds) + + +.. _sphx_glr_download_packages_scikit-learn_auto_examples_plot_pca.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_pca.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_pca.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_pca.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-learn/auto_examples/plot_polynomial_regression.rst.txt b/_sources/packages/scikit-learn/auto_examples/plot_polynomial_regression.rst.txt new file mode 100644 index 000000000..55467cc9f --- /dev/null +++ b/_sources/packages/scikit-learn/auto_examples/plot_polynomial_regression.rst.txt @@ -0,0 +1,191 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-learn/auto_examples/plot_polynomial_regression.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-learn_auto_examples_plot_polynomial_regression.py: + + +Plot fitting a 9th order polynomial +==================================== + +Fits data generated from a 9th order polynomial with model of 4th order +and 9th order polynomials, to demonstrate that often simpler models are +to be preferred + +.. GENERATED FROM PYTHON SOURCE LINES 9-29 + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + from matplotlib.colors import ListedColormap + + from sklearn import linear_model + + # Create color maps for 3-class classification problem, as with iris + cmap_light = ListedColormap(["#FFAAAA", "#AAFFAA", "#AAAAFF"]) + cmap_bold = ListedColormap(["#FF0000", "#00FF00", "#0000FF"]) + + + rng = np.random.default_rng(27446968) + x = 2 * rng.random(100) - 1 + + f = lambda t: 1.2 * t**2 + 0.1 * t**3 - 0.4 * t**5 - 0.5 * t**9 + y = f(x) + 0.4 * rng.normal(size=100) + + x_test = np.linspace(-1, 1, 100) + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 30-31 + +The data + +.. GENERATED FROM PYTHON SOURCE LINES 31-34 + +.. code-block:: Python + + plt.figure(figsize=(6, 4)) + plt.scatter(x, y, s=4) + + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_polynomial_regression_001.png + :alt: plot polynomial regression + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_polynomial_regression_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 35-38 + +Fitting 4th and 9th order polynomials + +For this we need to engineer features: the n_th powers of x: + +.. GENERATED FROM PYTHON SOURCE LINES 38-57 + +.. code-block:: Python + + plt.figure(figsize=(6, 4)) + plt.scatter(x, y, s=4) + + X = np.array([x**i for i in range(5)]).T + X_test = np.array([x_test**i for i in range(5)]).T + regr = linear_model.LinearRegression() + regr.fit(X, y) + plt.plot(x_test, regr.predict(X_test), label="4th order") + + X = np.array([x**i for i in range(10)]).T + X_test = np.array([x_test**i for i in range(10)]).T + regr = linear_model.LinearRegression() + regr.fit(X, y) + plt.plot(x_test, regr.predict(X_test), label="9th order") + + plt.legend(loc="best") + plt.axis("tight") + plt.title("Fitting a 4th and a 9th order polynomial") + + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_polynomial_regression_002.png + :alt: Fitting a 4th and a 9th order polynomial + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_polynomial_regression_002.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + Text(0.5, 1.0, 'Fitting a 4th and a 9th order polynomial') + + + +.. GENERATED FROM PYTHON SOURCE LINES 58-59 + +Ground truth + +.. GENERATED FROM PYTHON SOURCE LINES 59-66 + +.. code-block:: Python + + plt.figure(figsize=(6, 4)) + plt.scatter(x, y, s=4) + plt.plot(x_test, f(x_test), label="truth") + plt.axis("tight") + plt.title("Ground truth (9th order polynomial)") + + plt.show() + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_polynomial_regression_003.png + :alt: Ground truth (9th order polynomial) + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_polynomial_regression_003.png + :class: sphx-glr-single-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.175 seconds) + + +.. _sphx_glr_download_packages_scikit-learn_auto_examples_plot_polynomial_regression.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_polynomial_regression.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_polynomial_regression.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_polynomial_regression.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-learn/auto_examples/plot_separator.rst.txt b/_sources/packages/scikit-learn/auto_examples/plot_separator.rst.txt new file mode 100644 index 000000000..322ae3fc3 --- /dev/null +++ b/_sources/packages/scikit-learn/auto_examples/plot_separator.rst.txt @@ -0,0 +1,108 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-learn/auto_examples/plot_separator.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-learn_auto_examples_plot_separator.py: + + +Simple picture of the formal problem of machine learning +========================================================= + +This example generates simple synthetic data ploints and shows a +separating hyperplane on them. + +.. GENERATED FROM PYTHON SOURCE LINES 8-44 + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_separator_001.png + :alt: plot separator + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_separator_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + from sklearn.linear_model import SGDClassifier + from sklearn.datasets import make_blobs + + # we create 50 separable synthetic points + X, Y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.60) + + # fit the model + clf = SGDClassifier(loss="hinge", alpha=0.01, fit_intercept=True) + clf.fit(X, Y) + + # plot the line, the points, and the nearest vectors to the plane + xx = np.linspace(-1, 5, 10) + yy = np.linspace(-1, 5, 10) + + X1, X2 = np.meshgrid(xx, yy) + Z = np.empty(X1.shape) + for (i, j), val in np.ndenumerate(X1): + x1 = val + x2 = X2[i, j] + p = clf.decision_function([[x1, x2]]) + Z[i, j] = p[0] + + plt.figure(figsize=(4, 3)) + ax = plt.axes() + ax.contour( + X1, X2, Z, [-1.0, 0.0, 1.0], colors="k", linestyles=["dashed", "solid", "dashed"] + ) + ax.scatter(X[:, 0], X[:, 1], c=Y, cmap="Paired") + + ax.axis("tight") + + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.051 seconds) + + +.. _sphx_glr_download_packages_scikit-learn_auto_examples_plot_separator.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_separator.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_separator.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_separator.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-learn/auto_examples/plot_svm_non_linear.rst.txt b/_sources/packages/scikit-learn/auto_examples/plot_svm_non_linear.rst.txt new file mode 100644 index 000000000..d7bcf3136 --- /dev/null +++ b/_sources/packages/scikit-learn/auto_examples/plot_svm_non_linear.rst.txt @@ -0,0 +1,226 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-learn/auto_examples/plot_svm_non_linear.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-learn_auto_examples_plot_svm_non_linear.py: + + +Example of linear and non-linear models +======================================== + +This is an example plot from the tutorial which accompanies an explanation +of the support vector machine GUI. + +.. GENERATED FROM PYTHON SOURCE LINES 8-17 + +.. code-block:: Python + + + import numpy as np + import matplotlib.pyplot as plt + + from sklearn import svm + + + rng = np.random.default_rng(27446968) + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 18-19 + +data that is linearly separable + +.. GENERATED FROM PYTHON SOURCE LINES 19-65 + +.. code-block:: Python + + + + def linear_model(rseed=42, n_samples=30): + "Generate data according to a linear model" + np.random.seed(rseed) + + data = np.random.normal(0, 10, (n_samples, 2)) + data[: n_samples // 2] -= 15 + data[n_samples // 2 :] += 15 + + labels = np.ones(n_samples) + labels[: n_samples // 2] = -1 + + return data, labels + + + X, y = linear_model() + clf = svm.SVC(kernel="linear") + clf.fit(X, y) + + plt.figure(figsize=(6, 4)) + ax = plt.subplot(111, xticks=[], yticks=[]) + ax.scatter(X[:, 0], X[:, 1], c=y, cmap="bone") + + ax.scatter( + clf.support_vectors_[:, 0], + clf.support_vectors_[:, 1], + s=80, + edgecolors="k", + facecolors="none", + ) + + delta = 1 + y_min, y_max = -50, 50 + x_min, x_max = -50, 50 + x = np.arange(x_min, x_max + delta, delta) + y = np.arange(y_min, y_max + delta, delta) + X1, X2 = np.meshgrid(x, y) + Z = clf.decision_function(np.c_[X1.ravel(), X2.ravel()]) + Z = Z.reshape(X1.shape) + + ax.contour( + X1, X2, Z, [-1.0, 0.0, 1.0], colors="k", linestyles=["dashed", "solid", "dashed"] + ) + + + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_svm_non_linear_001.png + :alt: plot svm non linear + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_svm_non_linear_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 66-67 + +data with a non-linear separation + +.. GENERATED FROM PYTHON SOURCE LINES 67-125 + +.. code-block:: Python + + + + def nonlinear_model(rseed=27446968, n_samples=30): + rng = np.random.default_rng(rseed) + + radius = 40 * rng.random(n_samples) + far_pts = radius > 20 + radius[far_pts] *= 1.2 + radius[~far_pts] *= 1.1 + + theta = rng.random(n_samples) * np.pi * 2 + + data = np.empty((n_samples, 2)) + data[:, 0] = radius * np.cos(theta) + data[:, 1] = radius * np.sin(theta) + + labels = np.ones(n_samples) + labels[far_pts] = -1 + + return data, labels + + + X, y = nonlinear_model() + clf = svm.SVC(kernel="rbf", gamma=0.001, coef0=0, degree=3) + clf.fit(X, y) + + plt.figure(figsize=(6, 4)) + ax = plt.subplot(1, 1, 1, xticks=[], yticks=[]) + ax.scatter(X[:, 0], X[:, 1], c=y, cmap="bone", zorder=2) + + ax.scatter( + clf.support_vectors_[:, 0], + clf.support_vectors_[:, 1], + s=80, + edgecolors="k", + facecolors="none", + ) + + delta = 1 + y_min, y_max = -50, 50 + x_min, x_max = -50, 50 + x = np.arange(x_min, x_max + delta, delta) + y = np.arange(y_min, y_max + delta, delta) + X1, X2 = np.meshgrid(x, y) + Z = clf.decision_function(np.c_[X1.ravel(), X2.ravel()]) + Z = Z.reshape(X1.shape) + + ax.contour( + X1, + X2, + Z, + [-1.0, 0.0, 1.0], + colors="k", + linestyles=["dashed", "solid", "dashed"], + zorder=1, + ) + + plt.show() + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_svm_non_linear_002.png + :alt: plot svm non linear + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_svm_non_linear_002.png + :class: sphx-glr-single-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.068 seconds) + + +.. _sphx_glr_download_packages_scikit-learn_auto_examples_plot_svm_non_linear.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_svm_non_linear.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_svm_non_linear.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_svm_non_linear.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-learn/auto_examples/plot_tsne.rst.txt b/_sources/packages/scikit-learn/auto_examples/plot_tsne.rst.txt new file mode 100644 index 000000000..2ab644a42 --- /dev/null +++ b/_sources/packages/scikit-learn/auto_examples/plot_tsne.rst.txt @@ -0,0 +1,148 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-learn/auto_examples/plot_tsne.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-learn_auto_examples_plot_tsne.py: + + +========================== +tSNE to visualize digits +========================== + +Here we use :class:`sklearn.manifold.TSNE` to visualize the digits +datasets. Indeed, the digits are vectors in a 8*8 = 64 dimensional space. +We want to project them in 2D for visualization. tSNE is often a good +solution, as it groups and separates data points based on their local +relationship. + +.. GENERATED FROM PYTHON SOURCE LINES 15-16 + +Load the iris data + +.. GENERATED FROM PYTHON SOURCE LINES 16-23 + +.. code-block:: Python + + from sklearn import datasets + + digits = datasets.load_digits() + # Take the first 500 data points: it's hard to see 1500 points + X = digits.data[:500] + y = digits.target[:500] + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 24-25 + +Fit and transform with a TSNE + +.. GENERATED FROM PYTHON SOURCE LINES 25-29 + +.. code-block:: Python + + from sklearn.manifold import TSNE + + tsne = TSNE(n_components=2, random_state=0) + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 30-31 + +Project the data in 2D + +.. GENERATED FROM PYTHON SOURCE LINES 31-33 + +.. code-block:: Python + + X_2d = tsne.fit_transform(X) + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 34-35 + +Visualize the data + +.. GENERATED FROM PYTHON SOURCE LINES 35-45 + +.. code-block:: Python + + target_ids = range(len(digits.target_names)) + + import matplotlib.pyplot as plt + + plt.figure(figsize=(6, 5)) + colors = "r", "g", "b", "c", "m", "y", "k", "w", "orange", "purple" + for i, c, label in zip(target_ids, colors, digits.target_names, strict=True): + plt.scatter(X_2d[y == i, 0], X_2d[y == i, 1], c=c, label=label) + plt.legend() + plt.show() + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_tsne_001.png + :alt: plot tsne + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_tsne_001.png + :class: sphx-glr-single-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 1.216 seconds) + + +.. _sphx_glr_download_packages_scikit-learn_auto_examples_plot_tsne.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_tsne.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_tsne.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_tsne.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-learn/auto_examples/plot_variance_linear_regr.rst.txt b/_sources/packages/scikit-learn/auto_examples/plot_variance_linear_regr.rst.txt new file mode 100644 index 000000000..c45f683ba --- /dev/null +++ b/_sources/packages/scikit-learn/auto_examples/plot_variance_linear_regr.rst.txt @@ -0,0 +1,189 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/scikit-learn/auto_examples/plot_variance_linear_regr.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_scikit-learn_auto_examples_plot_variance_linear_regr.py: + + +================================================== +Plot variance and regularization in linear models +================================================== + +.. GENERATED FROM PYTHON SOURCE LINES 8-16 + +.. code-block:: Python + + + import numpy as np + + # Smaller figures + import matplotlib.pyplot as plt + + plt.rcParams["figure.figsize"] = (3, 2) + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 17-18 + +We consider the situation where we have only 2 data point + +.. GENERATED FROM PYTHON SOURCE LINES 18-22 + +.. code-block:: Python + + X = np.c_[0.5, 1].T + y = [0.5, 1] + X_test = np.c_[0, 2].T + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 23-24 + +Without noise, as linear regression fits the data perfectly + +.. GENERATED FROM PYTHON SOURCE LINES 24-31 + +.. code-block:: Python + + from sklearn import linear_model + + regr = linear_model.LinearRegression() + regr.fit(X, y) + plt.plot(X, y, "o") + plt.plot(X_test, regr.predict(X_test)) + + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_variance_linear_regr_001.png + :alt: plot variance linear regr + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_variance_linear_regr_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + [] + + + +.. GENERATED FROM PYTHON SOURCE LINES 32-33 + +In real life situation, we have noise (e.g. measurement noise) in our data: + +.. GENERATED FROM PYTHON SOURCE LINES 33-40 + +.. code-block:: Python + + rng = np.random.default_rng(27446968) + for _ in range(6): + noisy_X = X + np.random.normal(loc=0, scale=0.1, size=X.shape) + plt.plot(noisy_X, y, "o") + regr.fit(noisy_X, y) + plt.plot(X_test, regr.predict(X_test)) + + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_variance_linear_regr_002.png + :alt: plot variance linear regr + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_variance_linear_regr_002.png + :class: sphx-glr-single-img + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 41-49 + +As we can see, our linear model captures and amplifies the noise in the +data. It displays a lot of variance. + +We can use another linear estimator that uses regularization, the +:class:`~sklearn.linear_model.Ridge` estimator. This estimator +regularizes the coefficients by shrinking them to zero, under the +assumption that very high correlations are often spurious. The alpha +parameter controls the amount of shrinkage used. + +.. GENERATED FROM PYTHON SOURCE LINES 49-59 + +.. code-block:: Python + + + regr = linear_model.Ridge(alpha=0.1) + np.random.seed(0) + for _ in range(6): + noisy_X = X + np.random.normal(loc=0, scale=0.1, size=X.shape) + plt.plot(noisy_X, y, "o") + regr.fit(noisy_X, y) + plt.plot(X_test, regr.predict(X_test)) + + plt.show() + + + +.. image-sg:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_variance_linear_regr_003.png + :alt: plot variance linear regr + :srcset: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_variance_linear_regr_003.png + :class: sphx-glr-single-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.107 seconds) + + +.. _sphx_glr_download_packages_scikit-learn_auto_examples_plot_variance_linear_regr.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_variance_linear_regr.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_variance_linear_regr.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_variance_linear_regr.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/scikit-learn/auto_examples/sg_execution_times.rst.txt b/_sources/packages/scikit-learn/auto_examples/sg_execution_times.rst.txt new file mode 100644 index 000000000..e6b7827e8 --- /dev/null +++ b/_sources/packages/scikit-learn/auto_examples/sg_execution_times.rst.txt @@ -0,0 +1,85 @@ + +:orphan: + +.. _sphx_glr_packages_scikit-learn_auto_examples_sg_execution_times: + + +Computation times +================= +**00:16.816** total execution time for 17 files **from packages/scikit-learn/auto_examples**: + +.. container:: + + .. raw:: html + + + + + + + + .. list-table:: + :header-rows: 1 + :class: table table-striped sg-datatable + + * - Example + - Time + - Mem (MB) + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_california_prediction.py` (``plot_california_prediction.py``) + - 00:04.717 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_eigenfaces.py` (``plot_eigenfaces.py``) + - 00:04.145 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_digits_simple_classif.py` (``plot_digits_simple_classif.py``) + - 00:01.749 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_bias_variance.py` (``plot_bias_variance.py``) + - 00:01.391 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_measuring_performance.py` (``plot_measuring_performance.py``) + - 00:01.300 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_tsne.py` (``plot_tsne.py``) + - 00:01.216 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_iris_knn.py` (``plot_iris_knn.py``) + - 00:00.795 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_linear_model_cv.py` (``plot_linear_model_cv.py``) + - 00:00.391 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_compare_classifiers.py` (``plot_compare_classifiers.py``) + - 00:00.258 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_ML_flow_chart.py` (``plot_ML_flow_chart.py``) + - 00:00.214 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_polynomial_regression.py` (``plot_polynomial_regression.py``) + - 00:00.175 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_variance_linear_regr.py` (``plot_variance_linear_regr.py``) + - 00:00.107 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_pca.py` (``plot_pca.py``) + - 00:00.099 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_iris_scatter.py` (``plot_iris_scatter.py``) + - 00:00.093 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_svm_non_linear.py` (``plot_svm_non_linear.py``) + - 00:00.068 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_separator.py` (``plot_separator.py``) + - 00:00.051 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_linear_regression.py` (``plot_linear_regression.py``) + - 00:00.047 + - 0.0 diff --git a/_sources/packages/scikit-learn/index.rst.txt b/_sources/packages/scikit-learn/index.rst.txt new file mode 100644 index 000000000..526438cd0 --- /dev/null +++ b/_sources/packages/scikit-learn/index.rst.txt @@ -0,0 +1,1756 @@ +.. _scikit-learn_chapter: + +======================================== +scikit-learn: machine learning in Python +======================================== + +**Authors**: *Gael Varoquaux* + +.. image:: images/scikit-learn-logo.png + :scale: 40 + :align: right + +.. topic:: Prerequisites + + .. rst-class:: horizontal + + * :ref:`numpy ` + * :ref:`scipy ` + * :ref:`matplotlib (optional) ` + * :ref:`ipython (the enhancements come handy) ` + +.. sidebar:: **Acknowledgements** + + This chapter is adapted from `a tutorial + `__ given by Gaël + Varoquaux, Jake Vanderplas, Olivier Grisel. + +.. seealso:: **Data science in Python** + + * The :ref:`statistics` chapter may also be of interest + for readers looking into machine learning. + + * The `documentation of scikit-learn `_ is + very complete and didactic. + +.. contents:: Chapters contents + :local: + :depth: 1 + +.. For doctests + >>> import numpy as np + >>> # For doctest on headless environments + >>> import matplotlib.pyplot as plt + +.. currentmodule:: sklearn + +Introduction: problem settings +============================== + +What is machine learning? +------------------------- + +.. tip:: + + Machine Learning is about building programs with **tunable + parameters** that are adjusted automatically so as to improve their + behavior by **adapting to previously seen data.** + + Machine Learning can be considered a subfield of **Artificial + Intelligence** since those algorithms can be seen as building blocks + to make computers learn to behave more intelligently by somehow + **generalizing** rather that just storing and retrieving data items + like a database system would do. + +.. figure:: auto_examples/images/sphx_glr_plot_separator_001.png + :align: right + :target: auto_examples/plot_separator.html + :width: 350 + + A classification problem + +We'll take a look at two very simple machine learning tasks here. The +first is a **classification** task: the figure shows a collection of +two-dimensional data, colored according to two different class labels. A +classification algorithm may be used to draw a dividing boundary between +the two clusters of points: + +By drawing this separating line, we have learned a model which can +**generalize** to new data: if you were to drop another point onto the +plane which is unlabeled, this algorithm could now **predict** whether +it's a blue or a red point. + +.. raw:: html + +
+ +.. figure:: auto_examples/images/sphx_glr_plot_linear_regression_001.png + :align: right + :target: auto_examples/plot_linear_regression.html + :width: 350 + + A regression problem + +| + +The next simple task we'll look at is a **regression** task: a simple +best-fit line to a set of data. + +Again, this is an example of fitting a model to data, but our focus here +is that the model can make generalizations about new data. The model has +been **learned** from the training data, and can be used to predict the +result of test data: here, we might be given an x-value, and the model +would allow us to predict the y value. + +Data in scikit-learn +-------------------- + +The data matrix +~~~~~~~~~~~~~~~ + +Machine learning algorithms implemented in scikit-learn expect data +to be stored in a **two-dimensional array or matrix**. The arrays can be +either ``numpy`` arrays, or in some cases ``scipy.sparse`` matrices. The +size of the array is expected to be ``[n_samples, n_features]`` + +- **n\_samples:** The number of samples: each sample is an item to + process (e.g. classify). A sample can be a document, a picture, a + sound, a video, an astronomical object, a row in database or CSV + file, or whatever you can describe with a fixed set of quantitative + traits. +- **n\_features:** The number of features or distinct traits that can + be used to describe each item in a quantitative manner. Features are + generally real-valued, but may be boolean or discrete-valued in some + cases. + +.. tip:: + + The number of features must be fixed in advance. However it can be + very high dimensional (e.g. millions of features) with most of them + being zeros for a given sample. This is a case where ``scipy.sparse`` + matrices can be useful, in that they are much more memory-efficient + than NumPy arrays. + +A Simple Example: the Iris Dataset +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The application problem +....................... + +As an example of a simple dataset, let us a look at the +iris data stored by scikit-learn. Suppose we want to recognize species of +irises. The data consists of measurements of +three different species of irises: + +.. |setosa_picture| image:: images/iris_setosa.jpg + +.. |versicolor_picture| image:: images/iris_versicolor.jpg + +.. |virginica_picture| image:: images/iris_virginica.jpg + +===================== ===================== ===================== +|setosa_picture| |versicolor_picture| |virginica_picture| +===================== ===================== ===================== +Setosa Iris Versicolor Iris Virginica Iris +===================== ===================== ===================== + + +.. topic:: **Quick Question:** + :class: green + + **If we want to design an algorithm to recognize iris species, what + might the data be?** + + Remember: we need a 2D array of size ``[n_samples x n_features]``. + + - What would the ``n_samples`` refer to? + + - What might the ``n_features`` refer to? + +Remember that there must be a **fixed** number of features for each +sample, and feature number ``i`` must be a similar kind of quantity for +each sample. + +Loading the Iris Data with Scikit-learn +....................................... + +Scikit-learn has a very straightforward set of data on these iris +species. The data consist of the following: + +- Features in the Iris dataset: + + .. rst-class:: horizontal + + * sepal length (cm) + * sepal width (cm) + * petal length (cm) + * petal width (cm) + +- Target classes to predict: + + .. rst-class:: horizontal + + * Setosa + * Versicolour + * Virginica + +:mod:`scikit-learn` embeds a copy of the iris CSV file along with a +function to load it into NumPy arrays:: + + >>> from sklearn.datasets import load_iris + >>> iris = load_iris() + +.. note:: + + **Import sklearn** Note that scikit-learn is imported as :mod:`sklearn` + +The features of each sample flower are stored in the ``data`` attribute +of the dataset:: + + >>> print(iris.data.shape) + (150, 4) + >>> n_samples, n_features = iris.data.shape + >>> print(n_samples) + 150 + >>> print(n_features) + 4 + >>> print(iris.data[0]) + [5.1 3.5 1.4 0.2] + +The information about the class of each sample is stored in the +``target`` attribute of the dataset:: + + >>> print(iris.target.shape) + (150,) + >>> print(iris.target) + [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 + 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 + 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 + 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 + 2 2] + +The names of the classes are stored in the last attribute, namely +``target_names``:: + + >>> print(iris.target_names) + ['setosa' 'versicolor' 'virginica'] + +This data is four-dimensional, but we can visualize two of the +dimensions at a time using a scatter plot: + +.. image:: auto_examples/images/sphx_glr_plot_iris_scatter_001.png + :align: left + :target: auto_examples/plot_iris_scatter.html + +.. topic:: **Exercise**: + :class: green + + Can you choose 2 features to find a plot where it is easier to + separate the different classes of irises? + + **Hint**: click on the figure above to see the code that generates it, + and modify this code. + + +Basic principles of machine learning with scikit-learn +====================================================== + +Introducing the scikit-learn estimator object +---------------------------------------------- + +Every algorithm is exposed in scikit-learn via an ''Estimator'' object. +For instance a linear regression is: :class:`sklearn.linear_model.LinearRegression` :: + + >>> from sklearn.linear_model import LinearRegression + +**Estimator parameters**: All the parameters of an estimator can be set +when it is instantiated:: + + >>> model = LinearRegression(n_jobs=1) + >>> print(model) + LinearRegression(n_jobs=1) + +Fitting on data +~~~~~~~~~~~~~~~ + +Let's create some simple data with :ref:`numpy `:: + + >>> import numpy as np + >>> x = np.array([0, 1, 2]) + >>> y = np.array([0, 1, 2]) + + >>> X = x[:, np.newaxis] # The input data for sklearn is 2D: (samples == 3 x features == 1) + >>> X + array([[0], + [1], + [2]]) + + >>> model.fit(X, y) + LinearRegression(n_jobs=1) + +**Estimated parameters**: When data is fitted with an estimator, +parameters are estimated from the data at hand. All the estimated +parameters are attributes of the estimator object ending by an +underscore:: + + >>> model.coef_ + array([1.]) + +Supervised Learning: Classification and regression +-------------------------------------------------- + +In **Supervised Learning**, we have a dataset consisting of both +features and labels. The task is to construct an estimator which is able +to predict the label of an object given the set of features. A +relatively simple example is predicting the species of iris given a set +of measurements of its flower. This is a relatively simple task. Some +more complicated examples are: + +- given a multicolor image of an object through a telescope, determine + whether that object is a star, a quasar, or a galaxy. +- given a photograph of a person, identify the person in the photo. +- given a list of movies a person has watched and their personal rating + of the movie, recommend a list of movies they would like (So-called + *recommender systems*: a famous example is the `Netflix + Prize `__). + +.. tip:: + + What these tasks have in common is that there is one or more unknown + quantities associated with the object which needs to be determined from + other observed quantities. + +Supervised learning is further broken down into two categories, +**classification** and **regression**. In classification, the label is +discrete, while in regression, the label is continuous. For example, in +astronomy, the task of determining whether an object is a star, a +galaxy, or a quasar is a classification problem: the label is from three +distinct categories. On the other hand, we might wish to estimate the +age of an object based on such observations: this would be a regression +problem, because the label (age) is a continuous quantity. + +**Classification**: K nearest neighbors (kNN) is one of the simplest +learning strategies: given a new, unknown observation, look up in your +reference database which ones have the closest features and assign the +predominant class. Let's try it out on our iris classification problem:: + + from sklearn import neighbors, datasets + iris = datasets.load_iris() + X, y = iris.data, iris.target + knn = neighbors.KNeighborsClassifier(n_neighbors=1) + knn.fit(X, y) + # What kind of iris has 3cm x 5cm sepal and 4cm x 2cm petal? + print(iris.target_names[knn.predict([[3, 5, 4, 2]])]) + + +.. figure:: auto_examples/images/sphx_glr_plot_iris_knn_001.png + :align: center + :target: auto_examples/plot_iris_knn.html + + A plot of the sepal space and the prediction of the KNN + +**Regression**: The simplest possible regression setting is the linear +regression one: + +.. literalinclude:: examples/plot_linear_regression.py + :start-after: import matplotlib.pyplot as plt + :end-before: plot the results + +.. figure:: auto_examples/images/sphx_glr_plot_linear_regression_001.png + :align: center + :target: auto_examples/plot_linear_regression.html + + A plot of a simple linear regression. + +A recap on Scikit-learn's estimator interface +--------------------------------------------- + +Scikit-learn strives to have a uniform interface across all methods, and +we’ll see examples of these below. Given a scikit-learn *estimator* +object named ``model``, the following methods are available: + +:In **all Estimators**: + + - ``model.fit()`` : fit training data. For supervised learning + applications, this accepts two arguments: the data ``X`` and the + labels ``y`` (e.g. ``model.fit(X, y)``). For unsupervised learning + applications, this accepts only a single argument, the data ``X`` + (e.g. ``model.fit(X)``). + +:In **supervised estimators**: + + - ``model.predict()`` : given a trained model, predict the label of a + new set of data. This method accepts one argument, the new data + ``X_new`` (e.g. ``model.predict(X_new)``), and returns the learned + label for each object in the array. + - ``model.predict_proba()`` : For classification problems, some + estimators also provide this method, which returns the probability + that a new observation has each categorical label. In this case, the + label with the highest probability is returned by + ``model.predict()``. + - ``model.score()`` : for classification or regression problems, most + (all?) estimators implement a score method. Scores are between 0 and + 1, with a larger score indicating a better fit. + +:In **unsupervised estimators**: + + - ``model.transform()`` : given an unsupervised model, transform new + data into the new basis. This also accepts one argument ``X_new``, + and returns the new representation of the data based on the + unsupervised model. + - ``model.fit_transform()`` : some estimators implement this method, + which more efficiently performs a fit and a transform on the same + input data. + +Regularization: what it is and why it is necessary +-------------------------------------------------- + +Preferring simpler models +~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Train errors** Suppose you are using a 1-nearest neighbor estimator. +How many errors do you expect on your train set? + +- Train set error is not a good measurement of prediction performance. + You need to leave out a test set. +- In general, we should accept errors on the train set. + +**An example of regularization** The core idea behind regularization is +that we are going to prefer models that are simpler, for a certain +definition of ''simpler'', even if they lead to more errors on the train +set. + +As an example, let's generate with a 9th order polynomial, with noise: + +.. figure:: auto_examples/images/sphx_glr_plot_polynomial_regression_001.png + :align: center + :scale: 90 + :target: auto_examples/plot_polynomial_regression.html + +And now, let's fit a 4th order and a 9th order polynomial to the data. + +.. figure:: auto_examples/images/sphx_glr_plot_polynomial_regression_002.png + :align: center + :scale: 90 + :target: auto_examples/plot_polynomial_regression.html + +With your naked eyes, which model do you prefer, the 4th order one, or +the 9th order one? + +Let's look at the ground truth: + +.. figure:: auto_examples/images/sphx_glr_plot_polynomial_regression_003.png + :align: center + :scale: 90 + :target: auto_examples/plot_polynomial_regression.html + +.. tip:: + + Regularization is ubiquitous in machine learning. Most scikit-learn + estimators have a parameter to tune the amount of regularization. For + instance, with k-NN, it is 'k', the number of nearest neighbors used to + make the decision. k=1 amounts to no regularization: 0 error on the + training set, whereas large k will push toward smoother decision + boundaries in the feature space. + +Simple versus complex models for classification +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. |linear| image:: auto_examples/images/sphx_glr_plot_svm_non_linear_001.png + :width: 400 + :target: auto_examples/plot_svm_non_linear.html + +.. |nonlinear| image:: auto_examples/images/sphx_glr_plot_svm_non_linear_002.png + :width: 400 + :target: auto_examples/plot_svm_non_linear.html + +========================== ========================== +|linear| |nonlinear| +========================== ========================== +A linear separation A non-linear separation +========================== ========================== + +.. tip:: + + For classification models, the decision boundary, that separates the + class expresses the complexity of the model. For instance, a linear + model, that makes a decision based on a linear combination of + features, is more complex than a non-linear one. + + +Supervised Learning: Classification of Handwritten Digits +========================================================= + +The nature of the data +----------------------- + +.. sidebar:: Code and notebook + + Python code and Jupyter notebook for this section are found + :ref:`here ` + + +In this section we'll apply scikit-learn to the classification of +handwritten digits. This will go a bit beyond the iris classification we +saw before: we'll discuss some of the metrics which can be used in +evaluating the effectiveness of a classification model. :: + + >>> from sklearn.datasets import load_digits + >>> digits = load_digits() + +.. image:: auto_examples/images/sphx_glr_plot_digits_simple_classif_001.png + :target: auto_examples/plot_digits_simple_classif.html + :align: center + +Let us visualize the data and remind us what we're looking at (click on +the figure for the full code):: + + # plot the digits: each image is 8x8 pixels + for i in range(64): + ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[]) + ax.imshow(digits.images[i], cmap=plt.cm.binary, interpolation='nearest') + +Visualizing the Data on its principal components +------------------------------------------------- + +A good first-step for many problems is to visualize the data using a +*Dimensionality Reduction* technique. We'll start with the most +straightforward one, `Principal Component Analysis (PCA) +`_. + +PCA seeks orthogonal linear combinations of the features which show the +greatest variance, and as such, can help give you a good idea of the +structure of the data set. :: + + >>> from sklearn.decomposition import PCA + >>> pca = PCA(n_components=2) + >>> proj = pca.fit_transform(digits.data) + >>> plt.scatter(proj[:, 0], proj[:, 1], c=digits.target) + + >>> plt.colorbar() + + +.. image:: auto_examples/images/sphx_glr_plot_digits_simple_classif_002.png + :align: center + :target: auto_examples/plot_digits_simple_classif.html + +.. topic:: **Question** + :class: green + + Given these projections of the data, which numbers do you think a + classifier might have trouble distinguishing? + +Gaussian Naive Bayes Classification +----------------------------------- + +For most classification problems, it's nice to have a simple, fast +method to provide a quick baseline classification. If the simple +and fast method is sufficient, then we don't have to waste CPU cycles on +more complex models. If not, we can use the results of the simple method +to give us clues about our data. + +One good method to keep in mind is Gaussian Naive Bayes +(:class:`sklearn.naive_bayes.GaussianNB`). + +.. sidebar:: Old scikit-learn versions + + :func:`~sklearn.model_selection.train_test_split` is imported from + ``sklearn.cross_validation`` + +.. tip:: + + Gaussian Naive Bayes fits a Gaussian distribution to each training label + independently on each feature, and uses this to quickly give a rough + classification. It is generally not sufficiently accurate for real-world + data, but can perform surprisingly well, for instance on text data. + +:: + + >>> from sklearn.naive_bayes import GaussianNB + >>> from sklearn.model_selection import train_test_split + + >>> # split the data into training and validation sets + >>> X_train, X_test, y_train, y_test = train_test_split( + ... digits.data, digits.target, random_state=42) + + >>> # train the model + >>> clf = GaussianNB() + >>> clf.fit(X_train, y_train) + GaussianNB() + + >>> # use the model to predict the labels of the test data + >>> predicted = clf.predict(X_test) + >>> expected = y_test + >>> print(predicted) + [6 9 3 7 2 2 5 8 5 2 1 1 7 0 4 8 3 7 8 8 4 3 9 7 5 6 3 5 6 3...] + >>> print(expected) + [6 9 3 7 2 1 5 2 5 2 1 9 4 0 4 2 3 7 8 8 4 3 9 7 5 6 3 5 6 3...] + +As above, we plot the digits with the predicted labels to get an idea of +how well the classification is working. + +.. image:: auto_examples/images/sphx_glr_plot_digits_simple_classif_003.png + :align: center + :target: auto_examples/plot_digits_simple_classif.html + + +.. topic:: **Question** + :class: green + + Why did we split the data into training and validation sets? + +Quantitative Measurement of Performance +--------------------------------------- + +We'd like to measure the performance of our estimator without having to +resort to plotting examples. A simple method might be to simply compare +the number of matches:: + + >>> matches = (predicted == expected) + >>> print(matches.sum()) + 385 + >>> print(len(matches)) + 450 + >>> matches.sum() / float(len(matches)) + np.float64(0.8555...) + +We see that more than 80% of the 450 predictions match the input. But +there are other more sophisticated metrics that can be used to judge the +performance of a classifier: several are available in the +:mod:`sklearn.metrics` submodule. + +One of the most useful metrics is the ``classification_report``, which +combines several measures and prints a table with the results:: + + >>> from sklearn import metrics + >>> print(metrics.classification_report(expected, predicted)) + precision recall f1-score support + + 0 1.00 0.95 0.98 43 + 1 0.85 0.78 0.82 37 + 2 0.85 0.61 0.71 38 + 3 0.97 0.83 0.89 46 + 4 0.98 0.84 0.90 55 + 5 0.90 0.95 0.93 59 + 6 0.90 0.96 0.92 45 + 7 0.71 0.98 0.82 41 + 8 0.60 0.89 0.72 38 + 9 0.90 0.73 0.80 48 + + accuracy 0.86 450 + macro avg 0.87 0.85 0.85 450 + weighted avg 0.88 0.86 0.86 450 + + + +Another enlightening metric for this sort of multi-label classification +is a *confusion matrix*: it helps us visualize which labels are being +interchanged in the classification errors:: + + >>> print(metrics.confusion_matrix(expected, predicted)) + [[41 0 0 0 0 1 0 1 0 0] + [ 0 29 2 0 0 0 0 0 4 2] + [ 0 2 23 0 0 0 1 0 12 0] + [ 0 0 1 38 0 1 0 0 5 1] + [ 0 0 0 0 46 0 2 7 0 0] + [ 0 0 0 0 0 56 1 1 0 1] + [ 0 0 0 0 1 1 43 0 0 0] + [ 0 0 0 0 0 1 0 40 0 0] + [ 0 2 0 0 0 0 0 2 34 0] + [ 0 1 1 1 0 2 1 5 2 35]] + +We see here that in particular, the numbers 1, 2, 3, and 9 are often +being labeled 8. + + +Supervised Learning: Regression of Housing Data +=============================================== + +Here we'll do a short example of a regression problem: learning a +continuous value from a set of features. + +A quick look at the data +------------------------- + +.. sidebar:: Code and notebook + + Python code and Jupyter notebook for this section are found + :ref:`here ` + + + +We'll use the California house prices set, available in scikit-learn. +This records measurements of 8 attributes of housing markets in +California, as well as the median price. The question is: can you predict +the price of a new market given its attributes?:: + + >>> from sklearn.datasets import fetch_california_housing + >>> data = fetch_california_housing(as_frame=True) + >>> print(data.data.shape) + (20640, 8) + >>> print(data.target.shape) + (20640,) + +We can see that there are just over 20000 data points. + +The ``DESCR`` variable has a long description of the dataset:: + + >>> print(data.DESCR) + .. _california_housing_dataset: + + California Housing dataset + -------------------------- + + **Data Set Characteristics:** + + :Number of Instances: 20640 + + :Number of Attributes: 8 numeric, predictive attributes and the target + + :Attribute Information: + - MedInc median income in block group + - HouseAge median house age in block group + - AveRooms average number of rooms per household + - AveBedrms average number of bedrooms per household + - Population block group population + - AveOccup average number of household members + - Latitude block group latitude + - Longitude block group longitude + + :Missing Attribute Values: None + + This dataset was obtained from the StatLib repository. + https://www.dcc.fc.up.pt/~ltorgo/Regression/cal_housing.html + + The target variable is the median house value for California districts, + expressed in hundreds of thousands of dollars ($100,000). + + This dataset was derived from the 1990 U.S. census, using one row per census + block group. A block group is the smallest geographical unit for which the U.S. + Census Bureau publishes sample data (a block group typically has a population + of 600 to 3,000 people). + + A household is a group of people residing within a home. Since the average + number of rooms and bedrooms in this dataset are provided per household, these + columns may take surprisingly large values for block groups with few households + and many empty houses, such as vacation resorts. + + It can be downloaded/loaded using the + :func:`sklearn.datasets.fetch_california_housing` function. + + .. rubric:: References + + - Pace, R. Kelley and Ronald Barry, Sparse Spatial Autoregressions, + Statistics and Probability Letters, 33 (1997) 291-297 + + +It often helps to quickly visualize pieces of the data using histograms, +scatter plots, or other plot types. With matplotlib, let us show a +histogram of the target values: the median price in each neighborhood:: + + >>> plt.hist(data.target) + (array([... + +.. image:: auto_examples/images/sphx_glr_plot_california_prediction_001.png + :align: center + :target: auto_examples/plot_california_prediction.html + :scale: 70 + + + +Let's have a quick look to see if some features are more relevant than +others for our problem:: + + >>> for index, feature_name in enumerate(data.feature_names): + ... plt.figure() + ... plt.scatter(data.data[feature_name], data.target) +
>> from sklearn.model_selection import train_test_split + >>> X_train, X_test, y_train, y_test = train_test_split(data.data, data.target) + >>> from sklearn.linear_model import LinearRegression + >>> clf = LinearRegression() + >>> clf.fit(X_train, y_train) + LinearRegression() + >>> predicted = clf.predict(X_test) + >>> expected = y_test + >>> print("RMS: %s" % np.sqrt(np.mean((predicted - expected) ** 2))) + RMS: 0.7... + +.. image:: auto_examples/images/sphx_glr_plot_california_prediction_010.png + :align: right + :target: auto_examples/plot_california_prediction.html + +We can plot the error: expected as a function of predicted:: + + >>> plt.scatter(expected, predicted) + + +.. tip:: + + The prediction at least correlates with the true price, though there are + clearly some biases. We could imagine evaluating the performance of the + regressor by, say, computing the RMS residuals between the true and + predicted price. There are some subtleties in this, however, which we'll + cover in a later section. + +.. topic:: **Exercise: Gradient Boosting Tree Regression** + :class: green + + There are many other types of regressors available in scikit-learn: + we'll try a more powerful one here. + + **Use the GradientBoostingRegressor class to fit the housing data**. + + **hint** You can copy and paste some of the above code, replacing + :class:`~sklearn.linear_model.LinearRegression` with + :class:`~sklearn.ensemble.GradientBoostingRegressor`:: + + from sklearn.ensemble import GradientBoostingRegressor + # Instantiate the model, fit the results, and scatter in vs. out + + **Solution** The solution is found in :ref:`the code of this chapter ` + + + +Measuring prediction performance +================================ + +A quick test on the K-neighbors classifier +------------------------------------------ + +Here we'll continue to look at the digits data, but we'll switch to the +K-Neighbors classifier. The K-neighbors classifier is an instance-based +classifier. The K-neighbors classifier predicts the label of +an unknown point based on the labels of the *K* nearest points in the +parameter space. :: + + >>> # Get the data + >>> from sklearn.datasets import load_digits + >>> digits = load_digits() + >>> X = digits.data + >>> y = digits.target + + >>> # Instantiate and train the classifier + >>> from sklearn.neighbors import KNeighborsClassifier + >>> clf = KNeighborsClassifier(n_neighbors=1) + >>> clf.fit(X, y) + KNeighborsClassifier(...) + + >>> # Check the results using metrics + >>> from sklearn import metrics + >>> y_pred = clf.predict(X) + + >>> print(metrics.confusion_matrix(y_pred, y)) + [[178 0 0 0 0 0 0 0 0 0] + [ 0 182 0 0 0 0 0 0 0 0] + [ 0 0 177 0 0 0 0 0 0 0] + [ 0 0 0 183 0 0 0 0 0 0] + [ 0 0 0 0 181 0 0 0 0 0] + [ 0 0 0 0 0 182 0 0 0 0] + [ 0 0 0 0 0 0 181 0 0 0] + [ 0 0 0 0 0 0 0 179 0 0] + [ 0 0 0 0 0 0 0 0 174 0] + [ 0 0 0 0 0 0 0 0 0 180]] + +Apparently, we've found a perfect classifier! But this is misleading for +the reasons we saw before: the classifier essentially "memorizes" all the +samples it has already seen. To really test how well this algorithm +does, we need to try some samples it *hasn't* yet seen. + +This problem also occurs with regression models. In the following we +fit an other instance-based model named "decision tree" to the California +Housing price dataset we introduced previously:: + + >>> from sklearn.datasets import fetch_california_housing + >>> from sklearn.tree import DecisionTreeRegressor + + >>> data = fetch_california_housing(as_frame=True) + >>> clf = DecisionTreeRegressor().fit(data.data, data.target) + >>> predicted = clf.predict(data.data) + >>> expected = data.target + + >>> plt.scatter(expected, predicted) + + >>> plt.plot([0, 50], [0, 50], '--k') + [>> from sklearn import model_selection + >>> X = digits.data + >>> y = digits.target + + >>> X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, + ... test_size=0.25, random_state=0) + + >>> print("%r, %r, %r" % (X.shape, X_train.shape, X_test.shape)) + (1797, 64), (1347, 64), (450, 64) + +Now we train on the training data, and test on the testing data:: + + >>> clf = KNeighborsClassifier(n_neighbors=1).fit(X_train, y_train) + >>> y_pred = clf.predict(X_test) + + >>> print(metrics.confusion_matrix(y_test, y_pred)) + [[37 0 0 0 0 0 0 0 0 0] + [ 0 43 0 0 0 0 0 0 0 0] + [ 0 0 43 1 0 0 0 0 0 0] + [ 0 0 0 45 0 0 0 0 0 0] + [ 0 0 0 0 38 0 0 0 0 0] + [ 0 0 0 0 0 47 0 0 0 1] + [ 0 0 0 0 0 0 52 0 0 0] + [ 0 0 0 0 0 0 0 48 0 0] + [ 0 0 0 0 0 0 0 0 48 0] + [ 0 0 0 1 0 1 0 0 0 45]] + >>> print(metrics.classification_report(y_test, y_pred)) + precision recall f1-score support + + 0 1.00 1.00 1.00 37 + 1 1.00 1.00 1.00 43 + 2 1.00 0.98 0.99 44 + 3 0.96 1.00 0.98 45 + 4 1.00 1.00 1.00 38 + 5 0.98 0.98 0.98 48 + 6 1.00 1.00 1.00 52 + 7 1.00 1.00 1.00 48 + 8 1.00 1.00 1.00 48 + 9 0.98 0.96 0.97 47 + + accuracy 0.99 450 + macro avg 0.99 0.99 0.99 450 + weighted avg 0.99 0.99 0.99 450 + + +The averaged f1-score is often used as a convenient measure of the +overall performance of an algorithm. It appears in the bottom row +of the classification report; it can also be accessed directly:: + + >>> metrics.f1_score(y_test, y_pred, average="macro") + np.float64(0.991367...) + +The over-fitting we saw previously can be quantified by computing the +f1-score on the training data itself:: + + >>> metrics.f1_score(y_train, clf.predict(X_train), average="macro") + np.float64(1.0) + +.. note:: + + **Regression metrics** In the case of regression models, we + need to use different metrics, such as explained variance. + +Model Selection via Validation +------------------------------ + +.. tip:: + + We have applied Gaussian Naives, support vectors machines, and + K-nearest neighbors classifiers to the digits dataset. Now that we + have these validation tools in place, we can ask quantitatively which + of the three estimators works best for this dataset. + +* With the default hyper-parameters for each estimator, which gives the + best f1 score on the **validation set**? Recall that hyperparameters + are the parameters set when you instantiate the classifier: for + example, the ``n_neighbors`` in ``clf = + KNeighborsClassifier(n_neighbors=1)`` :: + + >>> from sklearn.naive_bayes import GaussianNB + >>> from sklearn.neighbors import KNeighborsClassifier + >>> from sklearn.svm import LinearSVC + + >>> X = digits.data + >>> y = digits.target + >>> X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, + ... test_size=0.25, random_state=0) + + >>> for Model in [GaussianNB(), KNeighborsClassifier(), LinearSVC(dual=False)]: + ... clf = Model.fit(X_train, y_train) + ... y_pred = clf.predict(X_test) + ... print('%s: %s' % + ... (Model.__class__.__name__, metrics.f1_score(y_test, y_pred, average="macro"))) + GaussianNB: 0.8... + KNeighborsClassifier: 0.9... + LinearSVC: 0.9... + +* For each classifier, which value for the hyperparameters gives the best + results for the digits data? For :class:`~sklearn.svm.LinearSVC`, use + ``loss='l2'`` and ``loss='l1'``. For + :class:`~sklearn.neighbors.KNeighborsClassifier` we use + ``n_neighbors`` between 1 and 10. Note that + :class:`~sklearn.naive_bayes.GaussianNB` does not have any adjustable + hyperparameters. :: + + LinearSVC(loss='l1'): 0.930570687535 + LinearSVC(loss='l2'): 0.933068826918 + ------------------- + KNeighbors(n_neighbors=1): 0.991367521884 + KNeighbors(n_neighbors=2): 0.984844206884 + KNeighbors(n_neighbors=3): 0.986775344954 + KNeighbors(n_neighbors=4): 0.980371905382 + KNeighbors(n_neighbors=5): 0.980456280495 + KNeighbors(n_neighbors=6): 0.975792419414 + KNeighbors(n_neighbors=7): 0.978064579214 + KNeighbors(n_neighbors=8): 0.978064579214 + KNeighbors(n_neighbors=9): 0.978064579214 + KNeighbors(n_neighbors=10): 0.975555089773 + + **Solution:** :ref:`code source ` + + +Cross-validation +---------------- + +Cross-validation consists in repeatedly splitting the data in pairs of +train and test sets, called 'folds'. Scikit-learn comes with a function +to automatically compute score on all these folds. Here we do +:class:`~sklearn.model_selection.KFold` with k=5. :: + + >>> clf = KNeighborsClassifier() + >>> from sklearn.model_selection import cross_val_score + >>> cross_val_score(clf, X, y, cv=5) #doctest: +ELLIPSIS + array([0.947..., 0.955..., 0.966..., 0.980..., 0.963... ]) + +We can use different splitting strategies, such as random splitting:: + + >>> from sklearn.model_selection import ShuffleSplit + >>> cv = ShuffleSplit(n_splits=5) + >>> cross_val_score(clf, X, y, cv=cv) + array([...]) + +.. tip:: + + There exists `many different cross-validation strategies + `_ + in scikit-learn. They are often useful to take in account non iid + datasets. + +Hyperparameter optimization with cross-validation +------------------------------------------------- + +Consider regularized linear models, such as *Ridge Regression*, which +uses l2 regularization, and *Lasso Regression*, which uses l1 +regularization. Choosing their regularization parameter is important. + +Let us set these parameters on the Diabetes dataset, a simple regression +problem. The diabetes data consists of 10 physiological variables (age, +sex, weight, blood pressure) measure on 442 patients, and an indication +of disease progression after one year:: + + >>> from sklearn.datasets import load_diabetes + >>> data = load_diabetes() + >>> X, y = data.data, data.target + >>> print(X.shape) + (442, 10) + +With the default hyper-parameters: we compute the cross-validation score:: + + >>> from sklearn.linear_model import Ridge, Lasso + + >>> for Model in [Ridge, Lasso]: + ... model = Model() + ... print('%s: %s' % (Model.__name__, cross_val_score(model, X, y).mean())) + Ridge: 0.4... + Lasso: 0.3... + +Basic Hyperparameter Optimization +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +We compute the cross-validation score as a function of alpha, the +strength of the regularization for :class:`~sklearn.linear_model.Lasso` +and :class:`~sklearn.linear_model.Ridge`. We choose 20 values of alpha +between 0.0001 and 1:: + + >>> alphas = np.logspace(-3, -1, 30) + + >>> for Model in [Lasso, Ridge]: + ... scores = [cross_val_score(Model(alpha), X, y, cv=3).mean() + ... for alpha in alphas] + ... plt.plot(alphas, scores, label=Model.__name__) + [>> from sklearn.model_selection import GridSearchCV + >>> for Model in [Ridge, Lasso]: + ... gscv = GridSearchCV(Model(), dict(alpha=alphas), cv=3).fit(X, y) + ... print('%s: %s' % (Model.__name__, gscv.best_params_)) + Ridge: {'alpha': np.float64(0.06210169418915616)} + Lasso: {'alpha': np.float64(0.01268961003167922)} + +Built-in Hyperparameter Search +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +For some models within scikit-learn, cross-validation can be performed +more efficiently on large datasets. In this case, a cross-validated +version of the particular model is included. The cross-validated +versions of :class:`~sklearn.linear_model.Ridge` and +:class:`~sklearn.linear_model.Lasso` are +:class:`~sklearn.linear_model.RidgeCV` and +:class:`~sklearn.linear_model.LassoCV`, respectively. Parameter search +on these estimators can be performed as follows:: + + >>> from sklearn.linear_model import RidgeCV, LassoCV + >>> for Model in [RidgeCV, LassoCV]: + ... model = Model(alphas=alphas, cv=3).fit(X, y) + ... print('%s: %s' % (Model.__name__, model.alpha_)) + RidgeCV: 0.0621016941892 + LassoCV: 0.0126896100317 + +We see that the results match those returned by GridSearchCV + +Nested cross-validation +~~~~~~~~~~~~~~~~~~~~~~~ + +How do we measure the performance of these estimators? We have used data +to set the hyperparameters, so we need to test on actually new data. We +can do this by running :func:`~sklearn.model_selection.cross_val_score` +on our CV objects. Here there are 2 cross-validation loops going on, this +is called *'nested cross validation'*:: + + for Model in [RidgeCV, LassoCV]: + scores = cross_val_score(Model(alphas=alphas, cv=3), X, y, cv=3) + print(Model.__name__, np.mean(scores)) + + +.. note:: + + Note that these results do not match the best results of our curves + above, and :class:`~sklearn.linear_model.LassoCV` seems to + under-perform :class:`~sklearn.linear_model.RidgeCV`. The reason is + that setting the hyper-parameter is harder for Lasso, thus the + estimation error on this hyper-parameter is larger. + +Unsupervised Learning: Dimensionality Reduction and Visualization +================================================================= + +Unsupervised learning is applied on X without y: data without labels. A +typical use case is to find hidden structure in the data. + +Dimensionality Reduction: PCA +----------------------------- + +Dimensionality reduction derives a set of new artificial features smaller +than the original feature set. Here we'll use `Principal Component +Analysis (PCA) +`__, a +dimensionality reduction that strives to retain most of the variance of +the original data. We'll use :class:`sklearn.decomposition.PCA` on the +iris dataset:: + + >>> X = iris.data + >>> y = iris.target + +.. tip:: + + :class:`~sklearn.decomposition.PCA` computes linear combinations of + the original features using a truncated Singular Value Decomposition + of the matrix X, to project the data onto a base of the top singular + vectors. + +:: + + >>> from sklearn.decomposition import PCA + >>> pca = PCA(n_components=2, whiten=True) + >>> pca.fit(X) + PCA(n_components=2, whiten=True) + +Once fitted, :class:`~sklearn.decomposition.PCA` exposes the singular +vectors in the ``components_`` attribute:: + + >>> pca.components_ + array([[ 0.3..., -0.08..., 0.85..., 0.3...], + [ 0.6..., 0.7..., -0.1..., -0.07...]]) + +Other attributes are available as well:: + + >>> pca.explained_variance_ratio_ + array([0.92..., 0.053...]) + +Let us project the iris dataset along those first two dimensions::: + + >>> X_pca = pca.transform(X) + >>> X_pca.shape + (150, 2) + +:class:`~sklearn.decomposition.PCA` ``normalizes`` and ``whitens`` the data, which means that the data +is now centered on both components with unit variance:: + + >>> X_pca.mean(axis=0) + array([...e-15, ...e-15]) + >>> X_pca.std(axis=0, ddof=1) + array([1., 1.]) + +Furthermore, the samples components do no longer carry any linear +correlation:: + + >>> np.corrcoef(X_pca.T) # doctest: +SKIP + array([[1.00000000e+00, 0.0], + [0.0, 1.00000000e+00]]) + +With a number of retained components 2 or 3, PCA is useful to visualize +the dataset:: + + >>> target_ids = range(len(iris.target_names)) + >>> for i, c, label in zip(target_ids, 'rgbcmykw', iris.target_names): + ... plt.scatter(X_pca[y == i, 0], X_pca[y == i, 1], + ... c=c, label=label) + >> # Take the first 500 data points: it's hard to see 1500 points + >>> X = digits.data[:500] + >>> y = digits.target[:500] + + >>> # Fit and transform with a TSNE + >>> from sklearn.manifold import TSNE + >>> tsne = TSNE(n_components=2, learning_rate='auto', init='random', random_state=0) + >>> X_2d = tsne.fit_transform(X) + + >>> # Visualize the data + >>> plt.scatter(X_2d[:, 0], X_2d[:, 1], c=y) + + + +.. image:: auto_examples/images/sphx_glr_plot_tsne_001.png + :align: left + :target: auto_examples/plot_tsne.html + :scale: 70 + + +.. topic:: fit_transform + + As :class:`~sklearn.manifold.TSNE` cannot be applied to new data, we + need to use its `fit_transform` method. + +| + +:class:`sklearn.manifold.TSNE` separates quite well the different classes +of digits even though it had no access to the class information. + +.. raw:: html + +
+ + +.. topic:: Exercise: Other dimension reduction of digits + :class: green + + :mod:`sklearn.manifold` has many other non-linear embeddings. Try + them out on the digits dataset. Could you judge their quality without + knowing the labels ``y``? :: + + >>> from sklearn.datasets import load_digits + >>> digits = load_digits() + >>> # ... + +Parameter selection, Validation, and Testing +============================================ + +Hyperparameters, Over-fitting, and Under-fitting +------------------------------------------------ + +.. seealso:: + + This section is adapted from `Andrew Ng's excellent + Coursera course `__ + +The issues associated with validation and cross-validation are some of +the most important aspects of the practice of machine learning. +Selecting the optimal model for your data is vital, and is a piece of +the problem that is not often appreciated by machine learning +practitioners. + +The central question is: **If our estimator is underperforming, how +should we move forward?** + +- Use simpler or more complicated model? +- Add more features to each observed data point? +- Add more training samples? + +The answer is often counter-intuitive. In particular, **Sometimes using +a more complicated model will give worse results.** Also, **Sometimes +adding training data will not improve your results.** The ability to +determine what steps will improve your model is what separates the +successful machine learning practitioners from the unsuccessful. + +Bias-variance trade-off: illustration on a simple regression problem +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. sidebar:: Code and notebook + + Python code and Jupyter notebook for this section are found + :ref:`here + ` + + +Let us start with a simple 1D regression problem. This +will help us to easily visualize the data and the model, and the results +generalize easily to higher-dimensional datasets. We'll explore a simple +**linear regression** problem, with :mod:`sklearn.linear_model`. + + +.. include:: auto_examples/plot_variance_linear_regr.rst + :start-after: We consider the situation where we have only 2 data point + :end-before: **Total running time of the script:** + + +As we can see, the estimator displays much less variance. However it +systematically under-estimates the coefficient. It displays a biased +behavior. + +This is a typical example of **bias/variance tradeof**: non-regularized +estimator are not biased, but they can display a lot of variance. +Highly-regularized models have little variance, but high bias. This bias +is not necessarily a bad thing: what matters is choosing the +tradeoff between bias and variance that leads to the best prediction +performance. For a specific dataset there is a sweet spot corresponding +to the highest complexity that the data can support, depending on the +amount of noise and of observations available. + +Visualizing the Bias/Variance Tradeoff +-------------------------------------- + +.. tip:: + + Given a particular dataset and a model (e.g. a polynomial), we'd like to + understand whether bias (underfit) or variance limits prediction, and how + to tune the *hyperparameter* (here ``d``, the degree of the polynomial) + to give the best fit. + +On a given data, let us fit a simple polynomial regression model with +varying degrees: + +.. image:: auto_examples/images/sphx_glr_plot_bias_variance_001.png + :align: center + :target: auto_examples/plot_bias_variance.html + +.. tip:: + + In the above figure, we see fits for three different values of ``d``. + For ``d = 1``, the data is under-fit. This means that the model is too + simplistic: no straight line will ever be a good fit to this data. In + this case, we say that the model suffers from high bias. The model + itself is biased, and this will be reflected in the fact that the data + is poorly fit. At the other extreme, for ``d = 6`` the data is over-fit. + This means that the model has too many free parameters (6 in this case) + which can be adjusted to perfectly fit the training data. If we add a + new point to this plot, though, chances are it will be very far from the + curve representing the degree-6 fit. In this case, we say that the model + suffers from high variance. The reason for the term "high variance" is + that if any of the input points are varied slightly, it could result in + a very different model. + + In the middle, for ``d = 2``, we have found a good mid-point. It fits + the data fairly well, and does not suffer from the bias and variance + problems seen in the figures on either side. What we would like is a way + to quantitatively identify bias and variance, and optimize the + metaparameters (in this case, the polynomial degree d) in order to + determine the best algorithm. + +.. topic:: Polynomial regression with scikit-learn + + A polynomial regression is built by pipelining + :class:`~sklearn.preprocessing.PolynomialFeatures` + and a :class:`~sklearn.linear_model.LinearRegression`:: + + >>> from sklearn.pipeline import make_pipeline + >>> from sklearn.preprocessing import PolynomialFeatures + >>> from sklearn.linear_model import LinearRegression + >>> model = make_pipeline(PolynomialFeatures(degree=2), LinearRegression()) + + +Validation Curves +~~~~~~~~~~~~~~~~~ + +Let us create a dataset like in the example above:: + + >>> def generating_func(x, rng, err=0.5): + ... return rng.normal(10 - 1. / (x + 0.1), err) + + >>> # randomly sample more data + >>> rng = np.random.default_rng(27446968) + >>> x = rng.random(size=200) + >>> y = generating_func(x, err=1., rng=rng) + +.. image:: auto_examples/images/sphx_glr_plot_bias_variance_002.png + :align: right + :target: auto_examples/plot_bias_variance.html + :scale: 60 + +Central to quantify bias and variance of a model is to apply it on *test +data*, sampled from the same distribution as the train, but that will +capture independent noise:: + + >>> xtrain, xtest, ytrain, ytest = train_test_split(x, y, test_size=0.4) + + +.. raw:: html + +
+ +**Validation curve** A validation curve consists in varying a model parameter +that controls its complexity (here the degree of the +polynomial) and measures both error of the model on training data, and on +test data (*eg* with cross-validation). The model parameter is then +adjusted so that the test error is minimized: + +We use :func:`sklearn.model_selection.validation_curve` to compute train +and test error, and plot it:: + + >>> from sklearn.model_selection import validation_curve + + >>> degrees = np.arange(1, 21) + + >>> model = make_pipeline(PolynomialFeatures(), LinearRegression()) + + >>> # Vary the "degrees" on the pipeline step "polynomialfeatures" + >>> train_scores, validation_scores = validation_curve( + ... model, x[:, np.newaxis], y, + ... param_name='polynomialfeatures__degree', + ... param_range=degrees) + + >>> # Plot the mean train score and validation score across folds + >>> plt.plot(degrees, validation_scores.mean(axis=1), label='cross-validation') + [] + >>> plt.plot(degrees, train_scores.mean(axis=1), label='training') + [] + >>> plt.legend(loc='best') + + +.. image:: auto_examples/images/sphx_glr_plot_bias_variance_003.png + :align: left + :target: auto_examples/plot_bias_variance.html + :scale: 60 + + +This figure shows why validation is important. On the left side of the +plot, we have very low-degree polynomial, which under-fit the data. This +leads to a low explained variance for both the training set and the +validation set. On the far right side of the plot, we have a very high +degree polynomial, which over-fits the data. This can be seen in the fact +that the training explained variance is very high, while on the +validation set, it is low. Choosing ``d`` around 4 or 5 gets us the best +tradeoff. + +.. tip:: + + The astute reader will realize that something is amiss here: in the + above plot, ``d = 4`` gives the best results. But in the previous plot, + we found that ``d = 6`` vastly over-fits the data. What’s going on here? + The difference is the **number of training points** used. In the + previous example, there were only eight training points. In this + example, we have 100. As a general rule of thumb, the more training + points used, the more complicated model can be used. But how can you + determine for a given model whether more training points will be + helpful? A useful diagnostic for this are learning curves. + +Learning Curves +~~~~~~~~~~~~~~~ + +A learning curve shows the training and validation score as a +function of the number of training points. Note that when we train on a +subset of the training data, the training score is computed using +this subset, not the full training set. This curve gives a +quantitative view into how beneficial it will be to add training +samples. + +.. topic:: **Questions:** + :class: green + + - As the number of training samples are increased, what do you expect + to see for the training score? For the validation score? + - Would you expect the training score to be higher or lower than the + validation score? Would you ever expect this to change? + + +:mod:`scikit-learn` provides +:func:`sklearn.model_selection.learning_curve`:: + + >>> from sklearn.model_selection import learning_curve + >>> train_sizes, train_scores, validation_scores = learning_curve( + ... model, x[:, np.newaxis], y, train_sizes=np.logspace(-1, 0, 20)) + + >>> # Plot the mean train score and validation score across folds + >>> plt.plot(train_sizes, validation_scores.mean(axis=1), label='cross-validation') + [] + >>> plt.plot(train_sizes, train_scores.mean(axis=1), label='training') + [] + + +.. figure:: auto_examples/images/sphx_glr_plot_bias_variance_004.png + :align: left + :target: auto_examples/plot_bias_variance.html + :scale: 60 + + For a ``degree=1`` model + +Note that the validation score *generally increases* with a growing +training set, while the training score *generally decreases* with a +growing training set. As the training size +increases, they will converge to a single value. + +From the above discussion, we know that ``d = 1`` is a high-bias +estimator which under-fits the data. This is indicated by the fact that +both the training and validation scores are low. When confronted +with this type of learning curve, we can expect that adding more +training data will not help: both lines converge to a +relatively low score. + +|clear-floats| + +**When the learning curves have converged to a low score, we have a +high bias model.** + +A high-bias model can be improved by: + +- Using a more sophisticated model (i.e. in this case, increase ``d``) +- Gather more features for each sample. +- Decrease regularization in a regularized model. + +Increasing the number of samples, however, does not improve a high-bias +model. + +Now let's look at a high-variance (i.e. over-fit) model: + +.. figure:: auto_examples/images/sphx_glr_plot_bias_variance_006.png + :align: left + :target: auto_examples/plot_bias_variance.html + :scale: 60 + + For a ``degree=15`` model + + +Here we show the learning curve for ``d = 15``. From the above +discussion, we know that ``d = 15`` is a **high-variance** estimator +which **over-fits** the data. This is indicated by the fact that the +training score is much higher than the validation score. As we add more +samples to this training set, the training score will continue to +decrease, while the cross-validation error will continue to increase, until they +meet in the middle. + +|clear-floats| + +**Learning curves that have not yet converged with the full training +set indicate a high-variance, over-fit model.** + +A high-variance model can be improved by: + +- Gathering more training samples. +- Using a less-sophisticated model (i.e. in this case, make ``d`` + smaller) +- Increasing regularization. + +In particular, gathering more features for each sample will not help the +results. + +Summary on model selection +-------------------------- + +We’ve seen above that an under-performing algorithm can be due to two +possible situations: high bias (under-fitting) and high variance +(over-fitting). In order to evaluate our algorithm, we set aside a +portion of our training data for cross-validation. Using the technique +of learning curves, we can train on progressively larger subsets of the +data, evaluating the training error and cross-validation error to +determine whether our algorithm has high variance or high bias. But what +do we do with this information? + +High Bias +~~~~~~~~~ + +If a model shows high **bias**, the following actions might help: + +- **Add more features**. In our example of predicting home prices, it + may be helpful to make use of information such as the neighborhood + the house is in, the year the house was built, the size of the lot, + etc. Adding these features to the training and test sets can improve + a high-bias estimator +- **Use a more sophisticated model**. Adding complexity to the model + can help improve on bias. For a polynomial fit, this can be + accomplished by increasing the degree d. Each learning technique has + its own methods of adding complexity. +- **Use fewer samples**. Though this will not improve the + classification, a high-bias algorithm can attain nearly the same + error with a smaller training sample. For algorithms which are + computationally expensive, reducing the training sample size can lead + to very large improvements in speed. +- **Decrease regularization**. Regularization is a technique used to + impose simplicity in some machine learning models, by adding a + penalty term that depends on the characteristics of the parameters. + If a model has high bias, decreasing the effect of regularization can + lead to better results. + +High Variance +~~~~~~~~~~~~~ + +If a model shows **high variance**, the following actions might +help: + +- **Use fewer features**. Using a feature selection technique may be + useful, and decrease the over-fitting of the estimator. +- **Use a simpler model**. Model complexity and over-fitting go + hand-in-hand. +- **Use more training samples**. Adding training samples can reduce the + effect of over-fitting, and lead to improvements in a high variance + estimator. +- **Increase Regularization**. Regularization is designed to prevent + over-fitting. In a high-variance model, increasing regularization can + lead to better results. + +These choices become very important in real-world situations. For +example, due to limited telescope time, astronomers must seek a balance +between observing a large number of objects, and observing a large +number of features for each object. Determining which is more important +for a particular learning task can inform the observing strategy that +the astronomer employs. + +A last word of caution: separate validation and test set +-------------------------------------------------------- + +Using validation schemes to determine hyper-parameters means that we are +fitting the hyper-parameters to the particular validation set. In the +same way that parameters can be over-fit to the training set, +hyperparameters can be over-fit to the validation set. Because of this, +the validation error tends to under-predict the classification error of +new data. + +For this reason, it is recommended to split the data into three sets: + +- The **training set**, used to train the model (usually ~60% of the + data) +- The **validation set**, used to validate the model (usually ~20% of + the data) +- The **test set**, used to evaluate the expected error of the + validated model (usually ~20% of the data) + +Many machine learning practitioners do not separate test set and +validation set. But if your goal is to gauge the error of a model on +unknown data, using an independent test set is vital. + +| + +.. include:: auto_examples/index.rst + :start-line: 1 + +.. seealso:: **Going further** + + * The `documentation of scikit-learn `__ is + very complete and didactic. + + * `Introduction to Machine Learning with Python + `_, + by Sarah Guido, Andreas Müller + (`notebooks available here `_). diff --git a/_sources/packages/statistics/auto_examples/index.rst.txt b/_sources/packages/statistics/auto_examples/index.rst.txt new file mode 100644 index 000000000..c889dee6f --- /dev/null +++ b/_sources/packages/statistics/auto_examples/index.rst.txt @@ -0,0 +1,231 @@ +:orphan: + +Full code for the figures +========================== + +Code examples for the statistics chapter. + + + +.. raw:: html + +
+ +.. thumbnail-parent-div-open + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/statistics/auto_examples/images/thumb/sphx_glr_plot_paired_boxplots_thumb.png + :alt: + + :ref:`sphx_glr_packages_statistics_auto_examples_plot_paired_boxplots.py` + +.. raw:: html + +
Boxplots and paired differences
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/statistics/auto_examples/images/thumb/sphx_glr_plot_pandas_thumb.png + :alt: + + :ref:`sphx_glr_packages_statistics_auto_examples_plot_pandas.py` + +.. raw:: html + +
Plotting simple quantities of a pandas dataframe
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/statistics/auto_examples/images/thumb/sphx_glr_plot_iris_analysis_thumb.png + :alt: + + :ref:`sphx_glr_packages_statistics_auto_examples_plot_iris_analysis.py` + +.. raw:: html + +
Analysis of Iris petal and sepal sizes
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/statistics/auto_examples/images/thumb/sphx_glr_plot_regression_thumb.png + :alt: + + :ref:`sphx_glr_packages_statistics_auto_examples_plot_regression.py` + +.. raw:: html + +
Simple Regression
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/statistics/auto_examples/images/thumb/sphx_glr_plot_regression_3d_thumb.png + :alt: + + :ref:`sphx_glr_packages_statistics_auto_examples_plot_regression_3d.py` + +.. raw:: html + +
Multiple Regression
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/statistics/auto_examples/images/thumb/sphx_glr_plot_wage_education_gender_thumb.png + :alt: + + :ref:`sphx_glr_packages_statistics_auto_examples_plot_wage_education_gender.py` + +.. raw:: html + +
Test for an education/gender interaction in wages
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/statistics/auto_examples/images/thumb/sphx_glr_plot_wage_data_thumb.png + :alt: + + :ref:`sphx_glr_packages_statistics_auto_examples_plot_wage_data.py` + +.. raw:: html + +
Visualizing factors influencing wages
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/statistics/auto_examples/images/thumb/sphx_glr_plot_airfare_thumb.png + :alt: + + :ref:`sphx_glr_packages_statistics_auto_examples_plot_airfare.py` + +.. raw:: html + +
Air fares before and after 9/11
+
+ + +.. thumbnail-parent-div-close + +.. raw:: html + +
+ + +.. toctree:: + :hidden: + + /packages/statistics/auto_examples/plot_paired_boxplots + /packages/statistics/auto_examples/plot_pandas + /packages/statistics/auto_examples/plot_iris_analysis + /packages/statistics/auto_examples/plot_regression + /packages/statistics/auto_examples/plot_regression_3d + /packages/statistics/auto_examples/plot_wage_education_gender + /packages/statistics/auto_examples/plot_wage_data + /packages/statistics/auto_examples/plot_airfare + +Solutions to this chapter's exercises +====================================== + + + +.. raw:: html + +
+ +.. thumbnail-parent-div-open + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/statistics/auto_examples/solutions/images/thumb/sphx_glr_plot_brain_size_thumb.png + :alt: + + :ref:`sphx_glr_packages_statistics_auto_examples_solutions_plot_brain_size.py` + +.. raw:: html + +
Relating Gender and IQ
+
+ + +.. thumbnail-parent-div-close + +.. raw:: html + +
+ + +.. toctree:: + :hidden: + :includehidden: + + + /packages/statistics/auto_examples/solutions/index.rst + + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-gallery + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download all examples in Python source code: auto_examples_python.zip ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download all examples in Jupyter notebooks: auto_examples_jupyter.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/statistics/auto_examples/plot_airfare.rst.txt b/_sources/packages/statistics/auto_examples/plot_airfare.rst.txt new file mode 100644 index 000000000..9817fa8f0 --- /dev/null +++ b/_sources/packages/statistics/auto_examples/plot_airfare.rst.txt @@ -0,0 +1,425 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/statistics/auto_examples/plot_airfare.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_statistics_auto_examples_plot_airfare.py: + + +Air fares before and after 9/11 +===================================== + +This is a business-intelligence (BI) like application. + +What is interesting here is that we may want to study fares as a function +of the year, paired accordingly to the trips, or forgetting the year, +only as a function of the trip endpoints. + +Using statsmodels' linear models, we find that both with an OLS (ordinary +least square) and a robust fit, the intercept and the slope are +significantly non-zero: the air fares have decreased between 2000 and +2001, and their dependence on distance travelled has also decreased + +.. GENERATED FROM PYTHON SOURCE LINES 17-21 + +.. code-block:: Python + + + # Standard library imports + import os + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 22-23 + +Load the data + +.. GENERATED FROM PYTHON SOURCE LINES 23-61 + +.. code-block:: Python + + import pandas + import requests + + if not os.path.exists("airfares.txt"): + # Download the file if it is not present + r = requests.get( + "https://users.stat.ufl.edu/~winner/data/airq4.dat", + verify=False, # Wouldn't normally do this, but this site's certificate + # is not yet distributed + ) + with open("airfares.txt", "wb") as f: + f.write(r.content) + + # As a separator, ' +' is a regular expression that means 'one of more + # space' + data = pandas.read_csv( + "airfares.txt", + delim_whitespace=True, + header=0, + names=[ + "city1", + "city2", + "pop1", + "pop2", + "dist", + "fare_2000", + "nb_passengers_2000", + "fare_2001", + "nb_passengers_2001", + ], + ) + + # we log-transform the number of passengers + import numpy as np + + data["nb_passengers_2000"] = np.log10(data["nb_passengers_2000"]) + data["nb_passengers_2001"] = np.log10(data["nb_passengers_2001"]) + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + /home/runner/work/scientific-python-lectures/scientific-python-lectures/packages/statistics/examples/plot_airfare.py:38: FutureWarning: The 'delim_whitespace' keyword in pd.read_csv is deprecated and will be removed in a future version. Use ``sep='\s+'`` instead + data = pandas.read_csv( + + + + +.. GENERATED FROM PYTHON SOURCE LINES 62-63 + +Make a dataframe with the year as an attribute, instead of separate columns + +.. GENERATED FROM PYTHON SOURCE LINES 63-93 + +.. code-block:: Python + + + # This involves a small danse in which we separate the dataframes in 2, + # one for year 2000, and one for 2001, before concatenating again. + + # Make an index of each flight + data_flat = data.reset_index() + + data_2000 = data_flat[ + ["city1", "city2", "pop1", "pop2", "dist", "fare_2000", "nb_passengers_2000"] + ] + # Rename the columns + data_2000.columns = pandas.Index( + ["city1", "city2", "pop1", "pop2", "dist", "fare", "nb_passengers"] + ) + # Add a column with the year + data_2000.insert(0, "year", 2000) + + data_2001 = data_flat[ + ["city1", "city2", "pop1", "pop2", "dist", "fare_2001", "nb_passengers_2001"] + ] + # Rename the columns + data_2001.columns = pandas.Index( + ["city1", "city2", "pop1", "pop2", "dist", "fare", "nb_passengers"] + ) + # Add a column with the year + data_2001.insert(0, "year", 2001) + + data_flat = pandas.concat([data_2000, data_2001]) + + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 94-95 + +Plot scatter matrices highlighting different aspects + +.. GENERATED FROM PYTHON SOURCE LINES 95-112 + +.. code-block:: Python + + + import seaborn + + seaborn.pairplot( + data_flat, vars=["fare", "dist", "nb_passengers"], kind="reg", markers="." + ) + + # A second plot, to show the effect of the year (ie the 9/11 effect) + seaborn.pairplot( + data_flat, + vars=["fare", "dist", "nb_passengers"], + kind="reg", + hue="year", + markers=".", + ) + + + + + +.. rst-class:: sphx-glr-horizontal + + + * + + .. image-sg:: /packages/statistics/auto_examples/images/sphx_glr_plot_airfare_001.png + :alt: plot airfare + :srcset: /packages/statistics/auto_examples/images/sphx_glr_plot_airfare_001.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /packages/statistics/auto_examples/images/sphx_glr_plot_airfare_002.png + :alt: plot airfare + :srcset: /packages/statistics/auto_examples/images/sphx_glr_plot_airfare_002.png + :class: sphx-glr-multi-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 113-114 + +Plot the difference in fare + +.. GENERATED FROM PYTHON SOURCE LINES 114-128 + +.. code-block:: Python + + + import matplotlib.pyplot as plt + + plt.figure(figsize=(5, 2)) + seaborn.boxplot(data.fare_2001 - data.fare_2000) + plt.title("Fare: 2001 - 2000") + plt.subplots_adjust() + + plt.figure(figsize=(5, 2)) + seaborn.boxplot(data.nb_passengers_2001 - data.nb_passengers_2000) + plt.title("NB passengers: 2001 - 2000") + plt.subplots_adjust() + + + + + +.. rst-class:: sphx-glr-horizontal + + + * + + .. image-sg:: /packages/statistics/auto_examples/images/sphx_glr_plot_airfare_003.png + :alt: Fare: 2001 - 2000 + :srcset: /packages/statistics/auto_examples/images/sphx_glr_plot_airfare_003.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /packages/statistics/auto_examples/images/sphx_glr_plot_airfare_004.png + :alt: NB passengers: 2001 - 2000 + :srcset: /packages/statistics/auto_examples/images/sphx_glr_plot_airfare_004.png + :class: sphx-glr-multi-img + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 129-131 + +Statistical testing: dependence of fare on distance and number of +passengers + +.. GENERATED FROM PYTHON SOURCE LINES 131-141 + +.. code-block:: Python + + import statsmodels.formula.api as sm + + result = sm.ols(formula="fare ~ 1 + dist + nb_passengers", data=data_flat).fit() + print(result.summary()) + + # Using a robust fit + result = sm.rlm(formula="fare ~ 1 + dist + nb_passengers", data=data_flat).fit() + print(result.summary()) + + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + OLS Regression Results + ============================================================================== + Dep. Variable: fare R-squared: 0.275 + Model: OLS Adj. R-squared: 0.275 + Method: Least Squares F-statistic: 1585. + Date: Sun, 06 Oct 2024 Prob (F-statistic): 0.00 + Time: 19:11:35 Log-Likelihood: -45532. + No. Observations: 8352 AIC: 9.107e+04 + Df Residuals: 8349 BIC: 9.109e+04 + Df Model: 2 + Covariance Type: nonrobust + ================================================================================= + coef std err t P>|t| [0.025 0.975] + --------------------------------------------------------------------------------- + Intercept 211.2428 2.466 85.669 0.000 206.409 216.076 + dist 0.0484 0.001 48.149 0.000 0.046 0.050 + nb_passengers -32.8925 1.127 -29.191 0.000 -35.101 -30.684 + ============================================================================== + Omnibus: 604.051 Durbin-Watson: 1.446 + Prob(Omnibus): 0.000 Jarque-Bera (JB): 740.733 + Skew: 0.710 Prob(JB): 1.42e-161 + Kurtosis: 3.338 Cond. No. 5.23e+03 + ============================================================================== + + Notes: + [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. + [2] The condition number is large, 5.23e+03. This might indicate that there are + strong multicollinearity or other numerical problems. + Robust linear Model Regression Results + ============================================================================== + Dep. Variable: fare No. Observations: 8352 + Model: RLM Df Residuals: 8349 + Method: IRLS Df Model: 2 + Norm: HuberT + Scale Est.: mad + Cov Type: H1 + Date: Sun, 06 Oct 2024 + Time: 19:11:35 + No. Iterations: 12 + ================================================================================= + coef std err z P>|z| [0.025 0.975] + --------------------------------------------------------------------------------- + Intercept 215.0848 2.448 87.856 0.000 210.287 219.883 + dist 0.0460 0.001 46.166 0.000 0.044 0.048 + nb_passengers -35.2686 1.119 -31.526 0.000 -37.461 -33.076 + ================================================================================= + + If the model instance has been used for another fit with different fit parameters, then the fit options might not be the correct ones anymore . + + + + +.. GENERATED FROM PYTHON SOURCE LINES 142-143 + +Statistical testing: regression of fare on distance: 2001/2000 difference + +.. GENERATED FROM PYTHON SOURCE LINES 143-152 + +.. code-block:: Python + + + result = sm.ols(formula="fare_2001 - fare_2000 ~ 1 + dist", data=data).fit() + print(result.summary()) + + # Plot the corresponding regression + data["fare_difference"] = data["fare_2001"] - data["fare_2000"] + seaborn.lmplot(x="dist", y="fare_difference", data=data) + + plt.show() + + + +.. image-sg:: /packages/statistics/auto_examples/images/sphx_glr_plot_airfare_005.png + :alt: plot airfare + :srcset: /packages/statistics/auto_examples/images/sphx_glr_plot_airfare_005.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + OLS Regression Results + ============================================================================== + Dep. Variable: fare_2001 R-squared: 0.159 + Model: OLS Adj. R-squared: 0.159 + Method: Least Squares F-statistic: 791.7 + Date: Sun, 06 Oct 2024 Prob (F-statistic): 1.20e-159 + Time: 19:11:35 Log-Likelihood: -22640. + No. Observations: 4176 AIC: 4.528e+04 + Df Residuals: 4174 BIC: 4.530e+04 + Df Model: 1 + Covariance Type: nonrobust + ============================================================================== + coef std err t P>|t| [0.025 0.975] + ------------------------------------------------------------------------------ + Intercept 148.0279 1.673 88.480 0.000 144.748 151.308 + dist 0.0388 0.001 28.136 0.000 0.036 0.041 + ============================================================================== + Omnibus: 136.558 Durbin-Watson: 1.544 + Prob(Omnibus): 0.000 Jarque-Bera (JB): 149.624 + Skew: 0.462 Prob(JB): 3.23e-33 + Kurtosis: 2.920 Cond. No. 2.40e+03 + ============================================================================== + + Notes: + [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. + [2] The condition number is large, 2.4e+03. This might indicate that there are + strong multicollinearity or other numerical problems. + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 7.718 seconds) + + +.. _sphx_glr_download_packages_statistics_auto_examples_plot_airfare.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_airfare.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_airfare.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_airfare.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/statistics/auto_examples/plot_iris_analysis.rst.txt b/_sources/packages/statistics/auto_examples/plot_iris_analysis.rst.txt new file mode 100644 index 000000000..0f12a32eb --- /dev/null +++ b/_sources/packages/statistics/auto_examples/plot_iris_analysis.rst.txt @@ -0,0 +1,180 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/statistics/auto_examples/plot_iris_analysis.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_statistics_auto_examples_plot_iris_analysis.py: + + +Analysis of Iris petal and sepal sizes +======================================= + +Illustrate an analysis on a real dataset: + +- Visualizing the data to formulate intuitions +- Fitting of a linear model +- Hypothesis test of the effect of a categorical variable in the presence + of a continuous confound + +.. GENERATED FROM PYTHON SOURCE LINES 13-24 + +.. code-block:: Python + + + import matplotlib.pyplot as plt + + import pandas + from pandas import plotting + + from statsmodels.formula.api import ols + + # Load the data + data = pandas.read_csv("iris.csv") + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 25-26 + +Plot a scatter matrix + +.. GENERATED FROM PYTHON SOURCE LINES 26-36 + +.. code-block:: Python + + + # Express the names as categories + categories = pandas.Categorical(data["name"]) + + # The parameter 'c' is passed to plt.scatter and will control the color + plotting.scatter_matrix(data, c=categories.codes, marker="o") + + fig = plt.gcf() + fig.suptitle("blue: setosa, green: versicolor, red: virginica", size=13) + + + + +.. image-sg:: /packages/statistics/auto_examples/images/sphx_glr_plot_iris_analysis_001.png + :alt: blue: setosa, green: versicolor, red: virginica + :srcset: /packages/statistics/auto_examples/images/sphx_glr_plot_iris_analysis_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + Text(0.5, 0.98, 'blue: setosa, green: versicolor, red: virginica') + + + +.. GENERATED FROM PYTHON SOURCE LINES 37-38 + +Statistical analysis + +.. GENERATED FROM PYTHON SOURCE LINES 38-51 + +.. code-block:: Python + + + # Let us try to explain the sepal length as a function of the petal + # width and the category of iris + + model = ols("sepal_width ~ name + petal_length", data).fit() + print(model.summary()) + + # Now formulate a "contrast", to test if the offset for versicolor and + # virginica are identical + + print("Testing the difference between effect of versicolor and virginica") + print(model.f_test([0, 1, -1, 0])) + plt.show() + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + OLS Regression Results + ============================================================================== + Dep. Variable: sepal_width R-squared: 0.478 + Model: OLS Adj. R-squared: 0.468 + Method: Least Squares F-statistic: 44.63 + Date: Sun, 06 Oct 2024 Prob (F-statistic): 1.58e-20 + Time: 19:11:16 Log-Likelihood: -38.185 + No. Observations: 150 AIC: 84.37 + Df Residuals: 146 BIC: 96.41 + Df Model: 3 + Covariance Type: nonrobust + ====================================================================================== + coef std err t P>|t| [0.025 0.975] + -------------------------------------------------------------------------------------- + Intercept 2.9813 0.099 29.989 0.000 2.785 3.178 + name[T.versicolor] -1.4821 0.181 -8.190 0.000 -1.840 -1.124 + name[T.virginica] -1.6635 0.256 -6.502 0.000 -2.169 -1.158 + petal_length 0.2983 0.061 4.920 0.000 0.178 0.418 + ============================================================================== + Omnibus: 2.868 Durbin-Watson: 1.753 + Prob(Omnibus): 0.238 Jarque-Bera (JB): 2.885 + Skew: -0.082 Prob(JB): 0.236 + Kurtosis: 3.659 Cond. No. 54.0 + ============================================================================== + + Notes: + [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. + Testing the difference between effect of versicolor and virginica + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.427 seconds) + + +.. _sphx_glr_download_packages_statistics_auto_examples_plot_iris_analysis.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_iris_analysis.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_iris_analysis.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_iris_analysis.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/statistics/auto_examples/plot_paired_boxplots.rst.txt b/_sources/packages/statistics/auto_examples/plot_paired_boxplots.rst.txt new file mode 100644 index 000000000..e64f72257 --- /dev/null +++ b/_sources/packages/statistics/auto_examples/plot_paired_boxplots.rst.txt @@ -0,0 +1,104 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/statistics/auto_examples/plot_paired_boxplots.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_statistics_auto_examples_plot_paired_boxplots.py: + + +Boxplots and paired differences +================================================= + +Plot boxplots for FSIQ, PIQ, and the paired difference between the two: +while the spread (error bars) for FSIQ and PIQ are very large, there is a +systematic (common) effect due to the subjects. This effect is cancelled +out in the difference and the spread of the difference ("paired" by +subject) is much smaller than the spread of the individual measures. + +.. GENERATED FROM PYTHON SOURCE LINES 12-29 + + + +.. rst-class:: sphx-glr-horizontal + + + * + + .. image-sg:: /packages/statistics/auto_examples/images/sphx_glr_plot_paired_boxplots_001.png + :alt: plot paired boxplots + :srcset: /packages/statistics/auto_examples/images/sphx_glr_plot_paired_boxplots_001.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /packages/statistics/auto_examples/images/sphx_glr_plot_paired_boxplots_002.png + :alt: plot paired boxplots + :srcset: /packages/statistics/auto_examples/images/sphx_glr_plot_paired_boxplots_002.png + :class: sphx-glr-multi-img + + + + + +.. code-block:: Python + + + import pandas + + import matplotlib.pyplot as plt + + data = pandas.read_csv("brain_size.csv", sep=";", na_values=".") + + # Box plot of FSIQ and PIQ (different measures od IQ) + plt.figure(figsize=(4, 3)) + data.boxplot(column=["FSIQ", "PIQ"]) + + # Boxplot of the difference + plt.figure(figsize=(4, 3)) + plt.boxplot(data["FSIQ"] - data["PIQ"]) + plt.xticks((1,), ("FSIQ - PIQ",)) + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.072 seconds) + + +.. _sphx_glr_download_packages_statistics_auto_examples_plot_paired_boxplots.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_paired_boxplots.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_paired_boxplots.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_paired_boxplots.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/statistics/auto_examples/plot_pandas.rst.txt b/_sources/packages/statistics/auto_examples/plot_pandas.rst.txt new file mode 100644 index 000000000..051c1525d --- /dev/null +++ b/_sources/packages/statistics/auto_examples/plot_pandas.rst.txt @@ -0,0 +1,113 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/statistics/auto_examples/plot_pandas.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_statistics_auto_examples_plot_pandas.py: + + +Plotting simple quantities of a pandas dataframe +================================================= + +This example loads from a CSV file data with mixed numerical and +categorical entries, and plots a few quantities, separately for females +and males, thanks to the pandas integrated plotting tool (that uses +matplotlib behind the scene). + +See http://pandas.pydata.org/pandas-docs/stable/visualization.html + +.. GENERATED FROM PYTHON SOURCE LINES 12-30 + + + +.. rst-class:: sphx-glr-horizontal + + + * + + .. image-sg:: /packages/statistics/auto_examples/images/sphx_glr_plot_pandas_001.png + :alt: Female, Male + :srcset: /packages/statistics/auto_examples/images/sphx_glr_plot_pandas_001.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /packages/statistics/auto_examples/images/sphx_glr_plot_pandas_002.png + :alt: plot pandas + :srcset: /packages/statistics/auto_examples/images/sphx_glr_plot_pandas_002.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /packages/statistics/auto_examples/images/sphx_glr_plot_pandas_003.png + :alt: plot pandas + :srcset: /packages/statistics/auto_examples/images/sphx_glr_plot_pandas_003.png + :class: sphx-glr-multi-img + + + + + +.. code-block:: Python + + + import pandas + + data = pandas.read_csv("brain_size.csv", sep=";", na_values=".") + + # Box plots of different columns for each gender + groupby_gender = data.groupby("Gender") + groupby_gender.boxplot(column=["FSIQ", "VIQ", "PIQ"]) + + from pandas import plotting + + # Scatter matrices for different columns + plotting.scatter_matrix(data[["Weight", "Height", "MRI_Count"]]) + plotting.scatter_matrix(data[["PIQ", "VIQ", "FSIQ"]]) + + import matplotlib.pyplot as plt + + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.536 seconds) + + +.. _sphx_glr_download_packages_statistics_auto_examples_plot_pandas.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_pandas.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_pandas.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_pandas.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/statistics/auto_examples/plot_regression.rst.txt b/_sources/packages/statistics/auto_examples/plot_regression.rst.txt new file mode 100644 index 000000000..a5f164f81 --- /dev/null +++ b/_sources/packages/statistics/auto_examples/plot_regression.rst.txt @@ -0,0 +1,213 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/statistics/auto_examples/plot_regression.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_statistics_auto_examples_plot_regression.py: + + +Simple Regression +==================== + +Fit a simple linear regression using 'statsmodels', compute corresponding +p-values. + +.. GENERATED FROM PYTHON SOURCE LINES 8-21 + +.. code-block:: Python + + + # Original author: Thomas Haslwanter + + import numpy as np + import matplotlib.pyplot as plt + import pandas + + # For statistics. Requires statsmodels 5.0 or more + from statsmodels.formula.api import ols + + # Analysis of Variance (ANOVA) on linear models + from statsmodels.stats.anova import anova_lm + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 22-23 + +Generate and show the data + +.. GENERATED FROM PYTHON SOURCE LINES 23-34 + +.. code-block:: Python + + x = np.linspace(-5, 5, 20) + + # To get reproducible values, provide a seed value + rng = np.random.default_rng(27446968) + + y = -5 + 3 * x + 4 * np.random.normal(size=x.shape) + + # Plot the data + plt.figure(figsize=(5, 4)) + plt.plot(x, y, "o") + + + + +.. image-sg:: /packages/statistics/auto_examples/images/sphx_glr_plot_regression_001.png + :alt: plot regression + :srcset: /packages/statistics/auto_examples/images/sphx_glr_plot_regression_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + [] + + + +.. GENERATED FROM PYTHON SOURCE LINES 35-37 + +Multilinear regression model, calculating fit, P-values, confidence +intervals etc. + +.. GENERATED FROM PYTHON SOURCE LINES 37-54 + +.. code-block:: Python + + + # Convert the data into a Pandas DataFrame to use the formulas framework + # in statsmodels + data = pandas.DataFrame({"x": x, "y": y}) + + # Fit the model + model = ols("y ~ x", data).fit() + + # Print the summary + print(model.summary()) + + # Perform analysis of variance on fitted linear model + anova_results = anova_lm(model) + + print("\nANOVA results") + print(anova_results) + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + OLS Regression Results + ============================================================================== + Dep. Variable: y R-squared: 0.845 + Model: OLS Adj. R-squared: 0.836 + Method: Least Squares F-statistic: 97.76 + Date: Sun, 06 Oct 2024 Prob (F-statistic): 1.06e-08 + Time: 19:11:17 Log-Likelihood: -53.560 + No. Observations: 20 AIC: 111.1 + Df Residuals: 18 BIC: 113.1 + Df Model: 1 + Covariance Type: nonrobust + ============================================================================== + coef std err t P>|t| [0.025 0.975] + ------------------------------------------------------------------------------ + Intercept -4.1877 0.830 -5.044 0.000 -5.932 -2.444 + x 2.7046 0.274 9.887 0.000 2.130 3.279 + ============================================================================== + Omnibus: 1.871 Durbin-Watson: 1.930 + Prob(Omnibus): 0.392 Jarque-Bera (JB): 0.597 + Skew: 0.337 Prob(JB): 0.742 + Kurtosis: 3.512 Cond. No. 3.03 + ============================================================================== + + Notes: + [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. + + ANOVA results + df sum_sq mean_sq F PR(>F) + x 1.0 1347.476043 1347.476043 97.760281 1.062847e-08 + Residual 18.0 248.102486 13.783471 NaN NaN + + + + +.. GENERATED FROM PYTHON SOURCE LINES 55-56 + +Plot the fitted model + +.. GENERATED FROM PYTHON SOURCE LINES 56-64 + +.. code-block:: Python + + + # Retrieve the parameter estimates + offset, coef = model._results.params + plt.plot(x, x * coef + offset) + plt.xlabel("x") + plt.ylabel("y") + + plt.show() + + + +.. image-sg:: /packages/statistics/auto_examples/images/sphx_glr_plot_regression_002.png + :alt: plot regression + :srcset: /packages/statistics/auto_examples/images/sphx_glr_plot_regression_002.png + :class: sphx-glr-single-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.107 seconds) + + +.. _sphx_glr_download_packages_statistics_auto_examples_plot_regression.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_regression.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_regression.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_regression.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/statistics/auto_examples/plot_regression_3d.rst.txt b/_sources/packages/statistics/auto_examples/plot_regression_3d.rst.txt new file mode 100644 index 000000000..7034a7ebb --- /dev/null +++ b/_sources/packages/statistics/auto_examples/plot_regression_3d.rst.txt @@ -0,0 +1,213 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/statistics/auto_examples/plot_regression_3d.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_statistics_auto_examples_plot_regression_3d.py: + + +Multiple Regression +==================== + +Calculate using 'statsmodels' just the best fit, or all the corresponding +statistical parameters. + +Also shows how to make 3d plots. + +.. GENERATED FROM PYTHON SOURCE LINES 10-26 + +.. code-block:: Python + + + # Original author: Thomas Haslwanter + + import numpy as np + import matplotlib.pyplot as plt + import pandas + + # For 3d plots. This import is necessary to have 3D plotting below + from mpl_toolkits.mplot3d import Axes3D + + # For statistics. Requires statsmodels 5.0 or more + from statsmodels.formula.api import ols + + # Analysis of Variance (ANOVA) on linear models + from statsmodels.stats.anova import anova_lm + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 27-28 + +Generate and show the data + +.. GENERATED FROM PYTHON SOURCE LINES 28-46 + +.. code-block:: Python + + x = np.linspace(-5, 5, 21) + # We generate a 2D grid + X, Y = np.meshgrid(x, x) + + # To get reproducible values, provide a seed value + rng = np.random.default_rng(27446968) + + # Z is the elevation of this 2D grid + Z = -5 + 3 * X - 0.5 * Y + 8 * np.random.normal(size=X.shape) + + # Plot the data + ax: Axes3D = plt.figure().add_subplot(projection="3d") + surf = ax.plot_surface(X, Y, Z, cmap="coolwarm", rstride=1, cstride=1) + ax.view_init(20, -120) + ax.set_xlabel("X") + ax.set_ylabel("Y") + ax.set_zlabel("Z") + + + + +.. image-sg:: /packages/statistics/auto_examples/images/sphx_glr_plot_regression_3d_001.png + :alt: plot regression 3d + :srcset: /packages/statistics/auto_examples/images/sphx_glr_plot_regression_3d_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + Text(-0.10764513121260137, 0.009865032686848034, 'Z') + + + +.. GENERATED FROM PYTHON SOURCE LINES 47-49 + +Multilinear regression model, calculating fit, P-values, confidence +intervals etc. + +.. GENERATED FROM PYTHON SOURCE LINES 49-77 + +.. code-block:: Python + + + # Convert the data into a Pandas DataFrame to use the formulas framework + # in statsmodels + + # First we need to flatten the data: it's 2D layout is not relevant. + X = X.flatten() + Y = Y.flatten() + Z = Z.flatten() + + data = pandas.DataFrame({"x": X, "y": Y, "z": Z}) + + # Fit the model + model = ols("z ~ x + y", data).fit() + + # Print the summary + print(model.summary()) + + print("\nRetrieving manually the parameter estimates:") + print(model._results.params) + # should be array([-4.99754526, 3.00250049, -0.50514907]) + + # Perform analysis of variance on fitted linear model + anova_results = anova_lm(model) + + print("\nANOVA results") + print(anova_results) + + plt.show() + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + OLS Regression Results + ============================================================================== + Dep. Variable: z R-squared: 0.579 + Model: OLS Adj. R-squared: 0.577 + Method: Least Squares F-statistic: 300.7 + Date: Sun, 06 Oct 2024 Prob (F-statistic): 6.43e-83 + Time: 19:11:17 Log-Likelihood: -1552.0 + No. Observations: 441 AIC: 3110. + Df Residuals: 438 BIC: 3122. + Df Model: 2 + Covariance Type: nonrobust + ============================================================================== + coef std err t P>|t| [0.025 0.975] + ------------------------------------------------------------------------------ + Intercept -4.4332 0.390 -11.358 0.000 -5.200 -3.666 + x 3.0861 0.129 23.940 0.000 2.833 3.340 + y -0.6856 0.129 -5.318 0.000 -0.939 -0.432 + ============================================================================== + Omnibus: 0.560 Durbin-Watson: 1.967 + Prob(Omnibus): 0.756 Jarque-Bera (JB): 0.651 + Skew: -0.077 Prob(JB): 0.722 + Kurtosis: 2.893 Cond. No. 3.03 + ============================================================================== + + Notes: + [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. + + Retrieving manually the parameter estimates: + [-4.43322435 3.08614608 -0.68556194] + + ANOVA results + df sum_sq mean_sq F PR(>F) + x 1.0 38501.973182 38501.973182 573.111646 1.365553e-81 + y 1.0 1899.955512 1899.955512 28.281320 1.676135e-07 + Residual 438.0 29425.094352 67.180581 NaN NaN + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.093 seconds) + + +.. _sphx_glr_download_packages_statistics_auto_examples_plot_regression_3d.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_regression_3d.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_regression_3d.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_regression_3d.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/statistics/auto_examples/plot_wage_data.rst.txt b/_sources/packages/statistics/auto_examples/plot_wage_data.rst.txt new file mode 100644 index 000000000..13852da56 --- /dev/null +++ b/_sources/packages/statistics/auto_examples/plot_wage_data.rst.txt @@ -0,0 +1,224 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/statistics/auto_examples/plot_wage_data.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_statistics_auto_examples_plot_wage_data.py: + + +Visualizing factors influencing wages +===================================== + +This example uses seaborn to quickly plot various factors relating wages, +experience, and education. + +Seaborn (https://seaborn.pydata.org) is a library that combines +visualization and statistical fits to show trends in data. + +Note that importing seaborn changes the matplotlib style to have an +"excel-like" feeling. This changes affect other matplotlib figures. To +restore defaults once this example is run, we would need to call +plt.rcdefaults(). + +.. GENERATED FROM PYTHON SOURCE LINES 16-22 + +.. code-block:: Python + + + # Standard library imports + import os + + import matplotlib.pyplot as plt + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 23-24 + +Load the data + +.. GENERATED FROM PYTHON SOURCE LINES 24-61 + +.. code-block:: Python + + import pandas + import requests + + if not os.path.exists("wages.txt"): + # Download the file if it is not present + r = requests.get("http://lib.stat.cmu.edu/datasets/CPS_85_Wages") + with open("wages.txt", "wb") as f: + f.write(r.content) + + # Give names to the columns + names = [ + "EDUCATION: Number of years of education", + "SOUTH: 1=Person lives in South, 0=Person lives elsewhere", + "SEX: 1=Female, 0=Male", + "EXPERIENCE: Number of years of work experience", + "UNION: 1=Union member, 0=Not union member", + "WAGE: Wage (dollars per hour)", + "AGE: years", + "RACE: 1=Other, 2=Hispanic, 3=White", + "OCCUPATION: 1=Management, 2=Sales, 3=Clerical, 4=Service, 5=Professional, 6=Other", + "SECTOR: 0=Other, 1=Manufacturing, 2=Construction", + "MARR: 0=Unmarried, 1=Married", + ] + + short_names = [n.split(":")[0] for n in names] + + data = pandas.read_csv( + "wages.txt", skiprows=27, skipfooter=6, sep=None, header=None, engine="python" + ) + data.columns = pandas.Index(short_names) + + # Log-transform the wages, because they typically are increased with + # multiplicative factors + import numpy as np + + data["WAGE"] = np.log10(data["WAGE"]) + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 62-63 + +Plot scatter matrices highlighting different aspects + +.. GENERATED FROM PYTHON SOURCE LINES 63-78 + +.. code-block:: Python + + + import seaborn + + seaborn.pairplot(data, vars=["WAGE", "AGE", "EDUCATION"], kind="reg") + + seaborn.pairplot(data, vars=["WAGE", "AGE", "EDUCATION"], kind="reg", hue="SEX") + plt.suptitle("Effect of gender: 1=Female, 0=Male") + + seaborn.pairplot(data, vars=["WAGE", "AGE", "EDUCATION"], kind="reg", hue="RACE") + plt.suptitle("Effect of race: 1=Other, 2=Hispanic, 3=White") + + seaborn.pairplot(data, vars=["WAGE", "AGE", "EDUCATION"], kind="reg", hue="UNION") + plt.suptitle("Effect of union: 1=Union member, 0=Not union member") + + + + + +.. rst-class:: sphx-glr-horizontal + + + * + + .. image-sg:: /packages/statistics/auto_examples/images/sphx_glr_plot_wage_data_001.png + :alt: plot wage data + :srcset: /packages/statistics/auto_examples/images/sphx_glr_plot_wage_data_001.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /packages/statistics/auto_examples/images/sphx_glr_plot_wage_data_002.png + :alt: Effect of gender: 1=Female, 0=Male + :srcset: /packages/statistics/auto_examples/images/sphx_glr_plot_wage_data_002.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /packages/statistics/auto_examples/images/sphx_glr_plot_wage_data_003.png + :alt: Effect of race: 1=Other, 2=Hispanic, 3=White + :srcset: /packages/statistics/auto_examples/images/sphx_glr_plot_wage_data_003.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /packages/statistics/auto_examples/images/sphx_glr_plot_wage_data_004.png + :alt: Effect of union: 1=Union member, 0=Not union member + :srcset: /packages/statistics/auto_examples/images/sphx_glr_plot_wage_data_004.png + :class: sphx-glr-multi-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + Text(0.5, 0.98, 'Effect of union: 1=Union member, 0=Not union member') + + + +.. GENERATED FROM PYTHON SOURCE LINES 79-80 + +Plot a simple regression + +.. GENERATED FROM PYTHON SOURCE LINES 80-84 + +.. code-block:: Python + + + seaborn.lmplot(y="WAGE", x="EDUCATION", data=data) + + plt.show() + + + +.. image-sg:: /packages/statistics/auto_examples/images/sphx_glr_plot_wage_data_005.png + :alt: plot wage data + :srcset: /packages/statistics/auto_examples/images/sphx_glr_plot_wage_data_005.png + :class: sphx-glr-single-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 9.494 seconds) + + +.. _sphx_glr_download_packages_statistics_auto_examples_plot_wage_data.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_wage_data.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_wage_data.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_wage_data.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/statistics/auto_examples/plot_wage_education_gender.rst.txt b/_sources/packages/statistics/auto_examples/plot_wage_education_gender.rst.txt new file mode 100644 index 000000000..d1918b4c7 --- /dev/null +++ b/_sources/packages/statistics/auto_examples/plot_wage_education_gender.rst.txt @@ -0,0 +1,284 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/statistics/auto_examples/plot_wage_education_gender.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_statistics_auto_examples_plot_wage_education_gender.py: + + +Test for an education/gender interaction in wages +================================================== + +Wages depend mostly on education. Here we investigate how this dependence +is related to gender: not only does gender create an offset in wages, it +also seems that wages increase more with education for males than +females. + +Does our data support this last hypothesis? We will test this using +statsmodels' formulas +(http://statsmodels.sourceforge.net/stable/example_formulas.html). + +.. GENERATED FROM PYTHON SOURCE LINES 17-18 + +Load and massage the data + +.. GENERATED FROM PYTHON SOURCE LINES 18-53 + +.. code-block:: Python + + import pandas + + import urllib.request + import os + + if not os.path.exists("wages.txt"): + # Download the file if it is not present + url = "http://lib.stat.cmu.edu/datasets/CPS_85_Wages" + with urllib.request.urlopen(url) as r, open("wages.txt", "wb") as f: + f.write(r.read()) + + # EDUCATION: Number of years of education + # SEX: 1=Female, 0=Male + # WAGE: Wage (dollars per hour) + data = pandas.read_csv( + "wages.txt", + skiprows=27, + skipfooter=6, + sep=None, + header=None, + names=["education", "gender", "wage"], + usecols=[0, 2, 5], + ) + + # Convert genders to strings (this is particularly useful so that the + # statsmodels formulas detects that gender is a categorical variable) + import numpy as np + + data["gender"] = np.choose(data.gender, ["male", "female"]) + + # Log-transform the wages, because they typically are increased with + # multiplicative factors + data["wage"] = np.log10(data["wage"]) + + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + /home/runner/work/scientific-python-lectures/scientific-python-lectures/packages/statistics/examples/plot_wage_education_gender.py:32: ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support skipfooter; you can avoid this warning by specifying engine='python'. + data = pandas.read_csv( + + + + +.. GENERATED FROM PYTHON SOURCE LINES 54-55 + +simple plotting + +.. GENERATED FROM PYTHON SOURCE LINES 55-61 + +.. code-block:: Python + + import seaborn + + # Plot 2 linear fits for male and female. + seaborn.lmplot(y="wage", x="education", hue="gender", data=data) + + + + + +.. image-sg:: /packages/statistics/auto_examples/images/sphx_glr_plot_wage_education_gender_001.png + :alt: plot wage education gender + :srcset: /packages/statistics/auto_examples/images/sphx_glr_plot_wage_education_gender_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 62-63 + +statistical analysis + +.. GENERATED FROM PYTHON SOURCE LINES 63-72 + +.. code-block:: Python + + import statsmodels.formula.api as sm + + # Note that this model is not the plot displayed above: it is one + # joined model for male and female, not separate models for male and + # female. The reason is that a single model enables statistical testing + result = sm.ols(formula="wage ~ education + gender", data=data).fit() + print(result.summary()) + + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + OLS Regression Results + ============================================================================== + Dep. Variable: wage R-squared: 0.193 + Model: OLS Adj. R-squared: 0.190 + Method: Least Squares F-statistic: 63.42 + Date: Sun, 06 Oct 2024 Prob (F-statistic): 2.01e-25 + Time: 19:11:18 Log-Likelihood: 86.654 + No. Observations: 534 AIC: -167.3 + Df Residuals: 531 BIC: -154.5 + Df Model: 2 + Covariance Type: nonrobust + ================================================================================== + coef std err t P>|t| [0.025 0.975] + ---------------------------------------------------------------------------------- + Intercept 0.4053 0.046 8.732 0.000 0.314 0.496 + gender[T.male] 0.1008 0.018 5.625 0.000 0.066 0.136 + education 0.0334 0.003 9.768 0.000 0.027 0.040 + ============================================================================== + Omnibus: 4.675 Durbin-Watson: 1.792 + Prob(Omnibus): 0.097 Jarque-Bera (JB): 4.876 + Skew: -0.147 Prob(JB): 0.0873 + Kurtosis: 3.365 Cond. No. 69.7 + ============================================================================== + + Notes: + [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. + + + + +.. GENERATED FROM PYTHON SOURCE LINES 73-77 + +The plots above highlight that there is not only a different offset in +wage but also a different slope + +We need to model this using an interaction + +.. GENERATED FROM PYTHON SOURCE LINES 77-83 + +.. code-block:: Python + + result = sm.ols( + formula="wage ~ education + gender + education * gender", data=data + ).fit() + print(result.summary()) + + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + OLS Regression Results + ============================================================================== + Dep. Variable: wage R-squared: 0.198 + Model: OLS Adj. R-squared: 0.194 + Method: Least Squares F-statistic: 43.72 + Date: Sun, 06 Oct 2024 Prob (F-statistic): 2.94e-25 + Time: 19:11:18 Log-Likelihood: 88.503 + No. Observations: 534 AIC: -169.0 + Df Residuals: 530 BIC: -151.9 + Df Model: 3 + Covariance Type: nonrobust + ============================================================================================ + coef std err t P>|t| [0.025 0.975] + -------------------------------------------------------------------------------------------- + Intercept 0.2998 0.072 4.173 0.000 0.159 0.441 + gender[T.male] 0.2750 0.093 2.972 0.003 0.093 0.457 + education 0.0415 0.005 7.647 0.000 0.031 0.052 + education:gender[T.male] -0.0134 0.007 -1.919 0.056 -0.027 0.000 + ============================================================================== + Omnibus: 4.838 Durbin-Watson: 1.825 + Prob(Omnibus): 0.089 Jarque-Bera (JB): 5.000 + Skew: -0.156 Prob(JB): 0.0821 + Kurtosis: 3.356 Cond. No. 194. + ============================================================================== + + Notes: + [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. + + + + +.. GENERATED FROM PYTHON SOURCE LINES 84-87 + +Looking at the p-value of the interaction of gender and education, the +data does not support the hypothesis that education benefits males +more than female (p-value > 0.05). + +.. GENERATED FROM PYTHON SOURCE LINES 87-92 + +.. code-block:: Python + + + + import matplotlib.pyplot as plt + + plt.show() + + + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.520 seconds) + + +.. _sphx_glr_download_packages_statistics_auto_examples_plot_wage_education_gender.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_wage_education_gender.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_wage_education_gender.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_wage_education_gender.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/statistics/auto_examples/sg_execution_times.rst.txt b/_sources/packages/statistics/auto_examples/sg_execution_times.rst.txt new file mode 100644 index 000000000..6b43b254e --- /dev/null +++ b/_sources/packages/statistics/auto_examples/sg_execution_times.rst.txt @@ -0,0 +1,58 @@ + +:orphan: + +.. _sphx_glr_packages_statistics_auto_examples_sg_execution_times: + + +Computation times +================= +**00:18.966** total execution time for 8 files **from packages/statistics/auto_examples**: + +.. container:: + + .. raw:: html + + + + + + + + .. list-table:: + :header-rows: 1 + :class: table table-striped sg-datatable + + * - Example + - Time + - Mem (MB) + * - :ref:`sphx_glr_packages_statistics_auto_examples_plot_wage_data.py` (``plot_wage_data.py``) + - 00:09.494 + - 0.0 + * - :ref:`sphx_glr_packages_statistics_auto_examples_plot_airfare.py` (``plot_airfare.py``) + - 00:07.718 + - 0.0 + * - :ref:`sphx_glr_packages_statistics_auto_examples_plot_pandas.py` (``plot_pandas.py``) + - 00:00.536 + - 0.0 + * - :ref:`sphx_glr_packages_statistics_auto_examples_plot_wage_education_gender.py` (``plot_wage_education_gender.py``) + - 00:00.520 + - 0.0 + * - :ref:`sphx_glr_packages_statistics_auto_examples_plot_iris_analysis.py` (``plot_iris_analysis.py``) + - 00:00.427 + - 0.0 + * - :ref:`sphx_glr_packages_statistics_auto_examples_plot_regression.py` (``plot_regression.py``) + - 00:00.107 + - 0.0 + * - :ref:`sphx_glr_packages_statistics_auto_examples_plot_regression_3d.py` (``plot_regression_3d.py``) + - 00:00.093 + - 0.0 + * - :ref:`sphx_glr_packages_statistics_auto_examples_plot_paired_boxplots.py` (``plot_paired_boxplots.py``) + - 00:00.072 + - 0.0 diff --git a/_sources/packages/statistics/auto_examples/solutions/index.rst.txt b/_sources/packages/statistics/auto_examples/solutions/index.rst.txt new file mode 100644 index 000000000..cd8a5b4b6 --- /dev/null +++ b/_sources/packages/statistics/auto_examples/solutions/index.rst.txt @@ -0,0 +1,44 @@ + + +.. _sphx_glr_packages_statistics_auto_examples_solutions: + +Solutions to this chapter's exercises +====================================== + + + +.. raw:: html + +
+ +.. thumbnail-parent-div-open + +.. raw:: html + +
+ +.. only:: html + + .. image:: /packages/statistics/auto_examples/solutions/images/thumb/sphx_glr_plot_brain_size_thumb.png + :alt: + + :ref:`sphx_glr_packages_statistics_auto_examples_solutions_plot_brain_size.py` + +.. raw:: html + +
Relating Gender and IQ
+
+ + +.. thumbnail-parent-div-close + +.. raw:: html + +
+ + +.. toctree:: + :hidden: + + /packages/statistics/auto_examples/solutions/plot_brain_size + diff --git a/_sources/packages/statistics/auto_examples/solutions/plot_brain_size.rst.txt b/_sources/packages/statistics/auto_examples/solutions/plot_brain_size.rst.txt new file mode 100644 index 000000000..886bf1157 --- /dev/null +++ b/_sources/packages/statistics/auto_examples/solutions/plot_brain_size.rst.txt @@ -0,0 +1,168 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "packages/statistics/auto_examples/solutions/plot_brain_size.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code. + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_packages_statistics_auto_examples_solutions_plot_brain_size.py: + + +Relating Gender and IQ +======================= + +Going back to the brain size + IQ data, test if the VIQ of male and +female are different after removing the effect of brain size, height and +weight. + +Notice that here 'Gender' is a categorical value. As it is a non-float +data type, statsmodels is able to automatically infer this. + +.. GENERATED FROM PYTHON SOURCE LINES 13-28 + +.. code-block:: Python + + + import pandas + from statsmodels.formula.api import ols + + data = pandas.read_csv("../brain_size.csv", sep=";", na_values=".") + + model = ols("VIQ ~ Gender + MRI_Count + Height", data).fit() + print(model.summary()) + + # Here, we don't need to define a contrast, as we are testing a single + # coefficient of our model, and not a combination of coefficients. + # However, defining a contrast, which would then be a 'unit contrast', + # will give us the same results + print(model.f_test([0, 1, 0, 0])) + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + OLS Regression Results + ============================================================================== + Dep. Variable: VIQ R-squared: 0.246 + Model: OLS Adj. R-squared: 0.181 + Method: Least Squares F-statistic: 3.809 + Date: Sun, 06 Oct 2024 Prob (F-statistic): 0.0184 + Time: 19:11:35 Log-Likelihood: -172.34 + No. Observations: 39 AIC: 352.7 + Df Residuals: 35 BIC: 359.3 + Df Model: 3 + Covariance Type: nonrobust + ================================================================================== + coef std err t P>|t| [0.025 0.975] + ---------------------------------------------------------------------------------- + Intercept 166.6258 88.824 1.876 0.069 -13.696 346.948 + Gender[T.Male] 8.8524 10.710 0.827 0.414 -12.890 30.595 + MRI_Count 0.0002 6.46e-05 2.615 0.013 3.78e-05 0.000 + Height -3.0837 1.276 -2.417 0.021 -5.674 -0.494 + ============================================================================== + Omnibus: 7.373 Durbin-Watson: 2.109 + Prob(Omnibus): 0.025 Jarque-Bera (JB): 2.252 + Skew: 0.005 Prob(JB): 0.324 + Kurtosis: 1.823 Cond. No. 2.40e+07 + ============================================================================== + + Notes: + [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. + [2] The condition number is large, 2.4e+07. This might indicate that there are + strong multicollinearity or other numerical problems. + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 29-31 + +Here we plot a scatter matrix to get intuitions on our results. +This goes beyond what was asked in the exercise + +.. GENERATED FROM PYTHON SOURCE LINES 31-57 + +.. code-block:: Python + + + # This plotting is useful to get an intuitions on the relationships between + # our different variables + + from pandas import plotting + import matplotlib.pyplot as plt + + # Fill in the missing values for Height for plotting + data["Height"] = data["Height"].ffill() + + # The parameter 'c' is passed to plt.scatter and will control the color + # The same holds for parameters 'marker', 'alpha' and 'cmap', that + # control respectively the type of marker used, their transparency and + # the colormap + plotting.scatter_matrix( + data[["VIQ", "MRI_Count", "Height"]], + c=(data["Gender"] == "Female"), + marker="o", + alpha=1, + cmap="winter", + ) + + fig = plt.gcf() + fig.suptitle("blue: male, green: female", size=13) + + plt.show() + + + +.. image-sg:: /packages/statistics/auto_examples/solutions/images/sphx_glr_plot_brain_size_001.png + :alt: blue: male, green: female + :srcset: /packages/statistics/auto_examples/solutions/images/sphx_glr_plot_brain_size_001.png + :class: sphx-glr-single-img + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** (0 minutes 0.236 seconds) + + +.. _sphx_glr_download_packages_statistics_auto_examples_solutions_plot_brain_size.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_brain_size.ipynb ` + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_brain_size.py ` + + .. container:: sphx-glr-download sphx-glr-download-zip + + :download:`Download zipped: plot_brain_size.zip ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/_sources/packages/statistics/auto_examples/solutions/sg_execution_times.rst.txt b/_sources/packages/statistics/auto_examples/solutions/sg_execution_times.rst.txt new file mode 100644 index 000000000..24f01e0ac --- /dev/null +++ b/_sources/packages/statistics/auto_examples/solutions/sg_execution_times.rst.txt @@ -0,0 +1,37 @@ + +:orphan: + +.. _sphx_glr_packages_statistics_auto_examples_solutions_sg_execution_times: + + +Computation times +================= +**00:00.236** total execution time for 1 file **from packages/statistics/auto_examples/solutions**: + +.. container:: + + .. raw:: html + + + + + + + + .. list-table:: + :header-rows: 1 + :class: table table-striped sg-datatable + + * - Example + - Time + - Mem (MB) + * - :ref:`sphx_glr_packages_statistics_auto_examples_solutions_plot_brain_size.py` (``plot_brain_size.py``) + - 00:00.236 + - 0.0 diff --git a/_sources/packages/statistics/index.rst.txt b/_sources/packages/statistics/index.rst.txt new file mode 100644 index 000000000..41966c2e7 --- /dev/null +++ b/_sources/packages/statistics/index.rst.txt @@ -0,0 +1,910 @@ +.. for doctests + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> import pandas + >>> pandas.options.display.width = 0 + +.. also switch current directory from the root directory (where the tests + are run) to be able to load the data + >>> import os + >>> os.chdir('packages/statistics') + + +.. _statistics: + +===================== +Statistics in Python +===================== + +**Author**: *Gaël Varoquaux* + +.. topic:: **Requirements** + + * Standard scientific Python environment (NumPy, SciPy, matplotlib) + + * `Pandas `__ + + * `Statsmodels `__ + + * `Seaborn `__ + + To install Python and these dependencies, we recommend that you + download `Anaconda Python `_ or, + preferably, use the package manager if you are under Ubuntu or other linux. + +.. seealso:: + + * **Bayesian statistics in Python**: + This chapter does not cover tools for Bayesian statistics. Of + particular interest for Bayesian modelling is `PyMC + `_, which implements a probabilistic + programming language in Python. + + * **Read a statistics book**: + The `Think stats `_ book is + available as free PDF or in print and is a great introduction to + statistics. + + +| + +.. tip:: + + **Why Python for statistics?** + + R is a language dedicated to statistics. Python is a general-purpose + language with statistics modules. R has more statistical analysis + features than Python, and specialized syntaxes. However, when it + comes to building complex analysis pipelines that mix statistics with + e.g. image analysis, text mining, or control of a physical + experiment, the richness of Python is an invaluable asset. + + +.. contents:: Contents + :local: + :depth: 2 + +.. tip:: + + In this document, the Python inputs are represented with the sign + ">>>". + + | + + **Disclaimer: Gender questions** + + Some of the examples of this tutorial are chosen around gender + questions. The reason is that on such questions controlling the truth + of a claim actually matters to many people. + + +Data representation and interaction +==================================== + +Data as a table +---------------- + +The setting that we consider for statistical analysis is that of multiple +*observations* or *samples* described by a set of different *attributes* +or *features*. The data can than be seen as a 2D table, or matrix, with +columns giving the different attributes of the data, and rows the +observations. For instance, the data contained in +:download:`examples/brain_size.csv`: + +.. include:: examples/brain_size.csv + :literal: + :end-line: 6 + + +The pandas data-frame +------------------------ + +.. tip:: + + We will store and manipulate this data in a + :class:`pandas.DataFrame`, from the `pandas + `__ module. It is the Python equivalent of + the spreadsheet table. It is different from a 2D ``numpy`` array as it + has named columns, can contain a mixture of different data types by + column, and has elaborate selection and pivotal mechanisms. + +Creating dataframes: reading data files or converting arrays +............................................................ + +.. sidebar:: **Separator** + + It is a CSV file, but the separator is ";" + +**Reading from a CSV file:** Using the above CSV file that gives +observations of brain size and weight and IQ (Willerman et al. 1991), the +data are a mixture of numerical and categorical values:: + + >>> import pandas + >>> data = pandas.read_csv('examples/brain_size.csv', sep=';', na_values=".") + >>> data + Unnamed: 0 Gender FSIQ VIQ PIQ Weight Height MRI_Count + 0 1 Female 133 132 124 118.0 64.5 816932 + 1 2 Male 140 150 124 NaN 72.5 1001121 + 2 3 Male 139 123 150 143.0 73.3 1038437 + 3 4 Male 133 129 128 172.0 68.8 965353 + 4 5 Female 137 132 134 147.0 65.0 951545 + ... + +.. warning:: **Missing values** + + The weight of the second individual is missing in the CSV file. If we + don't specify the missing value (NA = not available) marker, we will + not be able to do statistical analysis. + +| + +**Creating from arrays**: A :class:`pandas.DataFrame` can also be seen +as a dictionary of 1D 'series', eg arrays or lists. If we have 3 +``numpy`` arrays:: + + >>> import numpy as np + >>> t = np.linspace(-6, 6, 20) + >>> sin_t = np.sin(t) + >>> cos_t = np.cos(t) + +We can expose them as a :class:`pandas.DataFrame`:: + + >>> pandas.DataFrame({'t': t, 'sin': sin_t, 'cos': cos_t}) + t sin cos + 0 -6.000000 0.279415 0.960170 + 1 -5.368421 0.792419 0.609977 + 2 -4.736842 0.999701 0.024451 + 3 -4.105263 0.821291 -0.570509 + 4 -3.473684 0.326021 -0.945363 + 5 -2.842105 -0.295030 -0.955488 + 6 -2.210526 -0.802257 -0.596979 + 7 -1.578947 -0.999967 -0.008151 + 8 -0.947368 -0.811882 0.583822 + ... + +| + +**Other inputs**: `pandas `__ can input data from +SQL, excel files, or other formats. See the `pandas documentation +`__. + +| + +Manipulating data +.................. + +`data` is a :class:`pandas.DataFrame`, that resembles R's dataframe:: + + >>> data.shape # 40 rows and 8 columns + (40, 8) + + >>> data.columns # It has columns + Index(['Unnamed: 0', 'Gender', 'FSIQ', 'VIQ', 'PIQ', 'Weight', 'Height', + 'MRI_Count'], + dtype='object') + + >>> print(data['Gender']) # Columns can be addressed by name + 0 Female + 1 Male + 2 Male + 3 Male + 4 Female + ... + + >>> # Simpler selector + >>> data[data['Gender'] == 'Female']['VIQ'].mean() + np.float64(109.45) + +.. note:: For a quick view on a large dataframe, use its `describe` + method: :meth:`pandas.DataFrame.describe`. + +| + +**groupby**: splitting a dataframe on values of categorical variables:: + + >>> groupby_gender = data.groupby('Gender') + >>> for gender, value in groupby_gender['VIQ']: + ... print((gender, value.mean())) + ('Female', np.float64(109.45)) + ('Male', np.float64(115.25)) + + +`groupby_gender` is a powerful object that exposes many +operations on the resulting group of dataframes:: + + >>> groupby_gender.mean() + Unnamed: 0 FSIQ VIQ PIQ Weight Height MRI_Count + Gender + Female 19.65 111.9 109.45 110.45 137.200000 65.765000 862654.6 + Male 21.35 115.0 115.25 111.60 166.444444 71.431579 954855.4 + + +.. tip:: + + Use tab-completion on `groupby_gender` to find more. Other common + grouping functions are median, count (useful for checking to see the + amount of missing values in different subsets) or sum. Groupby + evaluation is lazy, no work is done until an aggregation function is + applied. + + +| + +.. image:: auto_examples/images/sphx_glr_plot_pandas_001.png + :target: auto_examples/plot_pandas.html + :align: right + :scale: 42 + + +.. topic:: **Exercise** + :class: green + + * What is the mean value for VIQ for the full population? + * How many males/females were included in this study? + + **Hint** use 'tab completion' to find out the methods that can be + called, instead of 'mean' in the above example. + + * What is the average value of MRI counts expressed in log units, for + males and females? + +.. note:: + + `groupby_gender.boxplot` is used for the plots above (see `this + example `_). + +| + +Plotting data +.............. + +.. currentmodule:: pandas + +Pandas comes with some plotting tools (:mod:`pandas.plotting`, using +matplotlib behind the scene) to display statistics of the data in +dataframes: + +**Scatter matrices**:: + + >>> from pandas import plotting + >>> plotting.scatter_matrix(data[['Weight', 'Height', 'MRI_Count']]) + array([[, + , + ], + [, + , + ], + [, + , + ]], dtype=object) + +.. image:: auto_examples/images/sphx_glr_plot_pandas_002.png + :target: auto_examples/plot_pandas.html + :scale: 70 + :align: center + +:: + + >>> plotting.scatter_matrix(data[['PIQ', 'VIQ', 'FSIQ']]) + array([[, + , + ], + [, + , + ], + [, + , + ]], dtype=object) + +.. sidebar:: **Two populations** + + The IQ metrics are bimodal, as if there are 2 sub-populations. + +.. image:: auto_examples/images/sphx_glr_plot_pandas_003.png + :target: auto_examples/plot_pandas.html + :scale: 70 + :align: center + +.. topic:: **Exercise** + :class: green + + Plot the scatter matrix for males only, and for females only. Do you + think that the 2 sub-populations correspond to gender? + + +Hypothesis testing: comparing two groups +========================================== + +For simple `statistical tests +`_, we will +use the :mod:`scipy.stats` sub-module of `SciPy +`_:: + + >>> import scipy as sp + +.. seealso:: + + SciPy is a vast library. For a quick summary to the whole library, see + the :ref:`scipy ` chapter. + + +Student's t-test: the simplest statistical test +------------------------------------------------ + +One-sample tests: testing the value of a population mean +........................................................ + +.. image:: two_sided.png + :scale: 50 + :align: right + +:func:`scipy.stats.ttest_1samp` tests the null hypothesis that the mean +of the population underlying the data is equal to a given value. It returns +the `T statistic `_, +and the `p-value `_ (see the +function's help):: + + >>> sp.stats.ttest_1samp(data['VIQ'], 0) + TtestResult(statistic=np.float64(30.088099970...), pvalue=np.float64(1.32891964...e-28), df=np.int64(39)) + +The p-value of :math:`10^-28` indicates that such an extreme value of the statistic +is unlikely to be observed under the null hypothesis. This may be taken as +evidence that the null hypothesis is false and that the population mean IQ +(VIQ measure) is not 0. + +Technically, the p-value of the t-test is derived under the assumption that +the means of samples drawn from the population are normally distributed. +This condition is exactly satisfied when the population itself is normally +distributed; however, due to the central limit theorem, the condition is +nearly true for reasonably large samples drawn from populations that follow +a variety of non-normal distributions. + +Nonetheless, if we are concerned that violation of the normality assumptions +will affect the conclusions of the test, we can use a `Wilcoxon signed-rank test +`_, which relaxes +this assumption at the expense of test power:: + + >>> sp.stats.wilcoxon(data['VIQ']) + WilcoxonResult(statistic=np.float64(0.0), pvalue=np.float64(1.8189894...e-12)) + +Two-sample t-test: testing for difference across populations +............................................................ + +We have seen above that the mean VIQ in the male and female samples +were different. To test whether this difference is significant (and +suggests that there is a difference in population means), we perform +a two-sample t-test using :func:`scipy.stats.ttest_ind`:: + + >>> female_viq = data[data['Gender'] == 'Female']['VIQ'] + >>> male_viq = data[data['Gender'] == 'Male']['VIQ'] + >>> sp.stats.ttest_ind(female_viq, male_viq) + TtestResult(statistic=np.float64(-0.77261617232...), pvalue=np.float64(0.4445287677858...), df=np.float64(38.0)) + +The corresponding non-parametric test is the `Mann–Whitney U +test `_, +:func:`scipy.stats.mannwhitneyu`. + + >>> sp.stats.mannwhitneyu(female_viq, male_viq) + MannwhitneyuResult(statistic=np.float64(164.5), pvalue=np.float64(0.34228868687...)) + +Paired tests: repeated measurements on the same individuals +----------------------------------------------------------- + +.. image:: auto_examples/images/sphx_glr_plot_paired_boxplots_001.png + :target: auto_examples/plot_pandas.html + :scale: 70 + :align: right + +PIQ, VIQ, and FSIQ give three measures of IQ. Let us test whether FISQ +and PIQ are significantly different. We can use an "independent sample" test:: + + >>> sp.stats.ttest_ind(data['FSIQ'], data['PIQ']) + TtestResult(statistic=np.float64(0.46563759638...), pvalue=np.float64(0.64277250...), df=np.float64(78.0)) + +The problem with this approach is that it ignores an important relationship +between observations: FSIQ and PIQ are measured on the same individuals. +Thus, the variance due to inter-subject variability is confounding, reducing +the power of the test. This variability can be removed using a "paired test" +or `"repeated measures test" +`_:: + + >>> sp.stats.ttest_rel(data['FSIQ'], data['PIQ']) + TtestResult(statistic=np.float64(1.784201940...), pvalue=np.float64(0.082172638183...), df=np.int64(39)) + +.. image:: auto_examples/images/sphx_glr_plot_paired_boxplots_002.png + :target: auto_examples/plot_pandas.html + :scale: 60 + :align: right + +This is equivalent to a one-sample test on the differences between paired +observations:: + + >>> sp.stats.ttest_1samp(data['FSIQ'] - data['PIQ'], 0) + TtestResult(statistic=np.float64(1.784201940...), pvalue=np.float64(0.082172638...), df=np.int64(39)) + +Accordingly, we can perform a nonparametric version of the test with +``wilcoxon``. + + >>> sp.stats.wilcoxon(data['FSIQ'], data['PIQ'], method="approx") + WilcoxonResult(statistic=np.float64(274.5), pvalue=np.float64(0.106594927135...)) + +.. topic:: **Exercise** + :class: green + + * Test the difference between weights in males and females. + + * Use non parametric statistics to test the difference between VIQ in + males and females. + + **Conclusion**: we find that the data does not support the hypothesis + that males and females have different VIQ. + +| + +Linear models, multiple factors, and analysis of variance +========================================================== + +"formulas" to specify statistical models in Python +-------------------------------------------------- + +A simple linear regression +........................... + +.. image:: auto_examples/images/sphx_glr_plot_regression_001.png + :target: auto_examples/plot_regression.html + :scale: 60 + :align: right + +Given two set of observations, `x` and `y`, we want to test the +hypothesis that `y` is a linear function of `x`. In other terms: + + :math:`y = x * \textit{coef} + \textit{intercept} + e` + +where `e` is observation noise. We will use the `statsmodels +`_ module to: + +#. Fit a linear model. We will use the simplest strategy, `ordinary least + squares `_ (OLS). + +#. Test that `coef` is non zero. + +| + +First, we generate simulated data according to the model:: + + >>> import numpy as np + >>> x = np.linspace(-5, 5, 20) + >>> rng = np.random.default_rng(27446968) + >>> # normal distributed noise + >>> y = -5 + 3*x + 4 * rng.normal(size=x.shape) + >>> # Create a data frame containing all the relevant variables + >>> data = pandas.DataFrame({'x': x, 'y': y}) + + +.. sidebar:: **"formulas" for statistics in Python** + + `See the statsmodels documentation + `_ + +| + +Then we specify an OLS model and fit it:: + + >>> from statsmodels.formula.api import ols + >>> model = ols("y ~ x", data).fit() + +We can inspect the various statistics derived from the fit:: + + >>> print(model.summary()) # doctest: +REPORT_UDIFF + OLS Regression Results + ============================================================================== + Dep. Variable: y R-squared: 0.901 + Model: OLS Adj. R-squared: 0.896 + Method: Least Squares F-statistic: 164.5 + Date: ... Prob (F-statistic): 1.72e-10 + Time: ... Log-Likelihood: -51.758 + No. Observations: 20 AIC: 107.5 + Df Residuals: 18 BIC: 109.5 + Df Model: 1 + Covariance Type: nonrobust + ============================================================================== + coef std err t P>|t| [0.025 0.975] + ------------------------------------------------------------------------------ + Intercept -4.2948 0.759 -5.661 0.000 -5.889 -2.701 + x 3.2060 0.250 12.825 0.000 2.681 3.731 + ============================================================================== + Omnibus: 1.218 Durbin-Watson: 1.796 + Prob(Omnibus): 0.544 Jarque-Bera (JB): 0.999 + Skew: 0.503 Prob(JB): 0.607 + Kurtosis: 2.568 Cond. No. 3.03 + ============================================================================== + + Notes: + [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. + +.. topic:: Terminology: + + Statsmodels uses a statistical terminology: the `y` variable in + statsmodels is called 'endogenous' while the `x` variable is called + exogenous. This is discussed in more detail `here + `_. + + To simplify, `y` (endogenous) is the value you are trying to predict, + while `x` (exogenous) represents the features you are using to make + the prediction. + + +.. topic:: **Exercise** + :class: green + + Retrieve the estimated parameters from the model above. **Hint**: + use tab-completion to find the relevant attribute. + +| + +Categorical variables: comparing groups or multiple categories +............................................................... + +Let us go back the data on brain size:: + + >>> data = pandas.read_csv('examples/brain_size.csv', sep=';', na_values=".") + +We can write a comparison between IQ of male and female using a linear +model:: + + >>> model = ols("VIQ ~ Gender + 1", data).fit() + >>> print(model.summary()) # doctest: +REPORT_UDIFF + OLS Regression Results + ============================================================================== + Dep. Variable: VIQ R-squared: 0.015 + Model: OLS Adj. R-squared: -0.010 + Method: Least Squares F-statistic: 0.5969 + Date: ... Prob (F-statistic): 0.445 + Time: ... Log-Likelihood: -182.42 + No. Observations: 40 AIC: 368.8 + Df Residuals: 38 BIC: 372.2 + Df Model: 1 + Covariance Type: nonrobust + ================================================================================== + coef std err t P>|t| [0.025 0.975] + ---------------------------------------------------------------------------------- + Intercept 109.4500 5.308 20.619 0.000 98.704 120.196 + Gender[T.Male] 5.8000 7.507 0.773 0.445 -9.397 20.997 + ============================================================================== + Omnibus: 26.188 Durbin-Watson: 1.709 + Prob(Omnibus): 0.000 Jarque-Bera (JB): 3.703 + Skew: 0.010 Prob(JB): 0.157 + Kurtosis: 1.510 Cond. No. 2.62 + ============================================================================== + + Notes: + [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. + +.. topic:: **Tips on specifying model** + + **Forcing categorical**: the 'Gender' is automatically detected as a + categorical variable, and thus each of its different values are + treated as different entities. + + An integer column can be forced to be treated as categorical using:: + + >>> model = ols('VIQ ~ C(Gender)', data).fit() + + **Intercept**: We can remove the intercept using `- 1` in the formula, + or force the use of an intercept using `+ 1`. + + .. tip:: + + By default, statsmodels treats a categorical variable with K possible + values as K-1 'dummy' boolean variables (the last level being + absorbed into the intercept term). This is almost always a good + default choice - however, it is possible to specify different + encodings for categorical variables + (https://www.statsmodels.org/devel/contrasts.html). + + +| + +.. topic:: **Link to t-tests between different FSIQ and PIQ** + + To compare different types of IQ, we need to create a "long-form" + table, listing IQs, where the type of IQ is indicated by a + categorical variable:: + + >>> data_fisq = pandas.DataFrame({'iq': data['FSIQ'], 'type': 'fsiq'}) + >>> data_piq = pandas.DataFrame({'iq': data['PIQ'], 'type': 'piq'}) + >>> data_long = pandas.concat((data_fisq, data_piq)) + >>> print(data_long) + iq type + 0 133 fsiq + 1 140 fsiq + 2 139 fsiq + 3 133 fsiq + 4 137 fsiq + ... ... ... + 35 128 piq + 36 124 piq + 37 94 piq + 38 74 piq + 39 89 piq + + [80 rows x 2 columns] + + >>> model = ols("iq ~ type", data_long).fit() + >>> print(model.summary()) # doctest: +REPORT_UDIFF + OLS Regression Results + ... + ==========================... + coef std err t P>|t| [0.025 0.975] + ------------------------------------------... + Intercept 113.4500 3.683 30.807 0.000 106.119 120.781 + type[T.piq] -2.4250 5.208 -0.466 0.643 -12.793 7.943 + ... + + We can see that we retrieve the same values for t-test and + corresponding p-values for the effect of the type of iq than the + previous t-test:: + + >>> sp.stats.ttest_ind(data['FSIQ'], data['PIQ']) + TtestResult(statistic=np.float64(0.46563759638...), pvalue=np.float64(0.64277250...), df=np.float64(78.0)) + + +Multiple Regression: including multiple factors +------------------------------------------------- + +.. image:: auto_examples/images/sphx_glr_plot_regression_3d_001.png + :target: auto_examples/plot_regression_3d.html + :scale: 45 + :align: right + +| + +Consider a linear model explaining a variable `z` (the dependent +variable) with 2 variables `x` and `y`: + + :math:`z = x \, c_1 + y \, c_2 + i + e` + +Such a model can be seen in 3D as fitting a plane to a cloud of (`x`, +`y`, `z`) points. + +| +| + +**Example: the iris data** (:download:`examples/iris.csv`) + +.. tip:: + + Sepal and petal size tend to be related: bigger flowers are bigger! + But is there in addition a systematic effect of species? + +.. image:: auto_examples/images/sphx_glr_plot_iris_analysis_001.png + :target: auto_examples/plot_iris_analysis_1.html + :scale: 80 + :align: center + +:: + + >>> data = pandas.read_csv('examples/iris.csv') + >>> model = ols('sepal_width ~ name + petal_length', data).fit() + >>> print(model.summary()) # doctest: +REPORT_UDIFF + OLS Regression Results + ==========================... + Dep. Variable: sepal_width R-squared: 0.478 + Model: OLS Adj. R-squared: 0.468 + Method: Least Squares F-statistic: 44.63 + Date: ... Prob (F-statistic): 1.58e-20 + Time: ... Log-Likelihood: -38.185 + No. Observations: 150 AIC: 84.37 + Df Residuals: 146 BIC: 96.41 + Df Model: 3 + Covariance Type: nonrobust + ==========================... + coef std err t P>|t| [0.025 0.975] + ------------------------------------------... + Intercept 2.9813 0.099 29.989 0.000 2.785 3.178 + name[T.versicolor] -1.4821 0.181 -8.190 0.000 -1.840 -1.124 + name[T.virginica] -1.6635 0.256 -6.502 0.000 -2.169 -1.158 + petal_length 0.2983 0.061 4.920 0.000 0.178 0.418 + ==========================... + Omnibus: 2.868 Durbin-Watson: 1.753 + Prob(Omnibus): 0.238 Jarque-Bera (JB): 2.885 + Skew: -0.082 Prob(JB): 0.236 + Kurtosis: 3.659 Cond. No. 54.0 + ==========================... + + Notes: + [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. + +| + +Post-hoc hypothesis testing: analysis of variance (ANOVA) +---------------------------------------------------------- + +In the above iris example, we wish to test if the petal length is +different between versicolor and virginica, after removing the effect of +sepal width. This can be formulated as testing the difference between the +coefficient associated to versicolor and virginica in the linear model +estimated above (it is an Analysis of Variance, `ANOVA +`_). For this, we +write a **vector of 'contrast'** on the parameters estimated: we want to +test ``"name[T.versicolor] - name[T.virginica]"``, with an `F-test +`_:: + + >>> print(model.f_test([0, 1, -1, 0])) + + +Is this difference significant? + +| + + +.. topic:: **Exercise** + :class: green + + Going back to the brain size + IQ data, test if the VIQ of male and + female are different after removing the effect of brain size, height + and weight. + +| + +More visualization: seaborn for statistical exploration +======================================================= + +`Seaborn `_ combines +simple statistical fits with plotting on pandas dataframes. + +Let us consider a data giving wages and many other personal information +on 500 individuals (`Berndt, ER. The Practice of Econometrics. 1991. NY: +Addison-Wesley `_). + +.. tip:: + + The full code loading and plotting of the wages data is found in + `corresponding example `_. + +:: + + >>> print(data) # doctest: +SKIP + EDUCATION SOUTH SEX EXPERIENCE UNION WAGE AGE RACE \ + 0 8 0 1 21 0 0.707570 35 2 + 1 9 0 1 42 0 0.694605 57 3 + 2 12 0 0 1 0 0.824126 19 3 + 3 12 0 0 4 0 0.602060 22 3 + ... + +Pairplot: scatter matrices +-------------------------- + +We can easily have an intuition on the interactions between continuous +variables using :func:`seaborn.pairplot` to display a scatter matrix:: + + >>> import seaborn + >>> seaborn.pairplot(data, vars=['WAGE', 'AGE', 'EDUCATION'], + ... kind='reg') # doctest: +SKIP + + +.. image:: auto_examples/images/sphx_glr_plot_wage_data_001.png + :target: auto_examples/plot_wage_data.html + :align: center + :scale: 60 + +Categorical variables can be plotted as the hue:: + + >>> seaborn.pairplot(data, vars=['WAGE', 'AGE', 'EDUCATION'], + ... kind='reg', hue='SEX') # doctest: +SKIP + + +.. image:: auto_examples/images/sphx_glr_plot_wage_data_002.png + :target: auto_examples/plot_wage_data.html + :align: center + :scale: 60 + +.. topic:: **Look and feel and matplotlib settings** + + Seaborn changes the default of matplotlib figures to achieve a more + "modern", "excel-like" look. It does that upon import. You can reset + the default using:: + + >>> import matplotlib.pyplot as plt + >>> plt.rcdefaults() + + .. tip:: + + To switch back to seaborn settings, or understand better styling in + seaborn, see the `relevant section of the seaborn documentation + `_. + + +lmplot: plotting a univariate regression +----------------------------------------- + +.. image:: auto_examples/images/sphx_glr_plot_wage_data_005.png + :target: auto_examples/plot_wage_data.html + :align: right + :scale: 60 + +A regression capturing the relation between one variable and another, eg +wage, and education, can be plotted using :func:`seaborn.lmplot`:: + + >>> seaborn.lmplot(y='WAGE', x='EDUCATION', data=data) # doctest: +SKIP + +.. raw:: html + +
+ +.. topic:: **Robust regression** + + .. tip:: + + Given that, in the above plot, there seems to be a couple of data + points that are outside of the main cloud to the right, they might be + outliers, not representative of the population, but driving the + regression. + + To compute a regression that is less sensitive to outliers, one must + use a `robust model + `_. This is done in + seaborn using ``robust=True`` in the plotting functions, or in + statsmodels by replacing the use of the OLS by a "Robust Linear + Model", :func:`statsmodels.formula.api.rlm`. + + +Testing for interactions +========================= + +.. image:: auto_examples/images/sphx_glr_plot_wage_education_gender_001.png + :target: auto_examples/plot_wage_education_gender.html + :align: center + :scale: 70 + +Do wages increase more with education for males than females? + +.. tip:: + + The plot above is made of two different fits. We need to formulate a + single model that tests for a variance of slope across the two + populations. This is done via an `"interaction" + `_. + + +:: + + >>> result = sm.ols(formula='wage ~ education + gender + education * gender', + ... data=data).fit() # doctest: +SKIP + >>> print(result.summary()) # doctest: +SKIP + ... + coef std err t P>|t| [0.025 0.975] + ------------------------------------------------------------------------------ + Intercept 0.2998 0.072 4.173 0.000 0.159 0.441 + gender[T.male] 0.2750 0.093 2.972 0.003 0.093 0.457 + education 0.0415 0.005 7.647 0.000 0.031 0.052 + education:gender[T.male] -0.0134 0.007 -1.919 0.056 -0.027 0.000 + ==========================... + ... + +Can we conclude that education benefits males more than females? + +| + +.. topic:: **Take home messages** + + * Hypothesis testing and p-values give you the **significance** of an + effect / difference. + + * **Formulas** (with categorical variables) enable you to express rich + links in your data. + + * **Visualizing** your data and fitting simple models give insight into the + data. + + * **Conditionning** (adding factors that can explain all or part of + the variation) is an important modeling aspect that changes the + interpretation. + +| + +.. include the gallery. Skip the first line to avoid the "orphan" + declaration + +.. include:: auto_examples/index.rst + :start-line: 1 diff --git a/_sources/packages/sympy.rst.txt b/_sources/packages/sympy.rst.txt new file mode 100644 index 000000000..8f1db841e --- /dev/null +++ b/_sources/packages/sympy.rst.txt @@ -0,0 +1,466 @@ + +.. TODO: bench and fit in 1:30 + +.. _sympy: + +====================================== +Sympy : Symbolic Mathematics in Python +====================================== + +**Author**: *Fabian Pedregosa* + +.. topic:: Objectives + + 1. Evaluate expressions with arbitrary precision. + 2. Perform algebraic manipulations on symbolic expressions. + 3. Perform basic calculus tasks (limits, differentiation and + integration) with symbolic expressions. + 4. Solve polynomial and transcendental equations. + 5. Solve some differential equations. + +.. role:: input(strong) + +**What is SymPy?** SymPy is a Python library for symbolic mathematics. It +aims to be an alternative to systems such as Mathematica or Maple while keeping +the code as simple as possible and easily +extensible. SymPy is written entirely in Python and does not require any +external libraries. + +Sympy documentation and packages for installation can be found on +https://www.sympy.org/ + +.. contents:: Chapters contents + :local: + :depth: 4 + + +First Steps with SymPy +====================== + + +Using SymPy as a calculator +--------------------------- + +SymPy defines three numerical types: ``Real``, ``Rational`` and ``Integer``. + +The Rational class represents a rational number as a pair of two +Integers: the numerator and the denominator, so ``Rational(1, 2)`` +represents 1/2, ``Rational(5, 2)`` 5/2 and so on:: + + >>> import sympy as sym + >>> a = sym.Rational(1, 2) + + >>> a + 1/2 + + >>> a*2 + 1 + +SymPy uses mpmath in the background, which makes it possible to +perform computations using arbitrary-precision arithmetic. That +way, some special constants, like :math:`e`, :math:`pi`, :math:`oo` (Infinity), +are treated as +symbols and can be evaluated with arbitrary precision:: + + >>> sym.pi**2 + pi**2 + + >>> sym.pi.evalf() + 3.14159265358979 + + >>> (sym.pi + sym.exp(1)).evalf() + 5.85987448204884 + +as you see, ``evalf`` evaluates the expression to a floating-point number. + +There is also a class representing mathematical infinity, called +``oo``:: + + >>> sym.oo > 99999 + True + >>> sym.oo + 1 + oo + + +.. topic:: **Exercises** + :class: green + + 1. Calculate :math:`\sqrt{2}` with 100 decimals. + 2. Calculate :math:`1/2 + 1/3` in rational arithmetic. + + +Symbols +------- + +In contrast to other Computer Algebra Systems, in SymPy you have to declare +symbolic variables explicitly:: + + >>> x = sym.Symbol('x') + >>> y = sym.Symbol('y') + +Then you can manipulate them:: + + >>> x + y + x - y + 2*x + + >>> (x + y) ** 2 + (x + y)**2 + +Symbols can now be manipulated using some of python operators: ``+``, ``-``, +``*``, ``**`` (arithmetic), ``&``, ``|``, ``~``, ``>>``, ``<<`` (boolean). + + +.. topic:: **Printing** + + Sympy allows for control of the display of the output. From here we use the + following setting for printing:: + + >>> sym.init_printing(use_unicode=False, wrap_line=True) + + + +Algebraic manipulations +======================= + +SymPy is capable of performing powerful algebraic manipulations. We'll +take a look into some of the most frequently used: expand and simplify. + +Expand +------ + +Use this to expand an algebraic expression. It will try to denest +powers and multiplications:: + + >>> sym.expand((x + y) ** 3) + 3 2 2 3 + x + 3*x *y + 3*x*y + y + >>> 3 * x * y ** 2 + 3 * y * x ** 2 + x ** 3 + y ** 3 + 3 2 2 3 + x + 3*x *y + 3*x*y + y + + +Further options can be given in form on keywords:: + + >>> sym.expand(x + y, complex=True) + re(x) + re(y) + I*im(x) + I*im(y) + >>> sym.I * sym.im(x) + sym.I * sym.im(y) + sym.re(x) + sym.re(y) + re(x) + re(y) + I*im(x) + I*im(y) + + >>> sym.expand(sym.cos(x + y), trig=True) + -sin(x)*sin(y) + cos(x)*cos(y) + >>> sym.cos(x) * sym.cos(y) - sym.sin(x) * sym.sin(y) + -sin(x)*sin(y) + cos(x)*cos(y) + +Simplify +-------- + +Use simplify if you would like to transform an expression into a +simpler form:: + + >>> sym.simplify((x + x * y) / x) + y + 1 + + +Simplification is a somewhat vague term, and more precises +alternatives to simplify exists: ``powsimp`` (simplification of +exponents), ``trigsimp`` (for trigonometric expressions) , ``logcombine``, +``radsimp``, together. + +.. topic:: **Exercises** + :class: green + + 1. Calculate the expanded form of :math:`(x+y)^6`. + 2. Simplify the trigonometric expression :math:`\sin(x) / \cos(x)` + + +Calculus +======== + +Limits +------ + +Limits are easy to use in SymPy, they follow the syntax ``limit(function, +variable, point)``, so to compute the limit of :math:`f(x)` as +:math:`x \rightarrow 0`, you would issue ``limit(f, x, 0)``:: + + >>> sym.limit(sym.sin(x) / x, x, 0) + 1 + +you can also calculate the limit at infinity:: + + >>> sym.limit(x, x, sym.oo) + oo + + >>> sym.limit(1 / x, x, sym.oo) + 0 + + >>> sym.limit(x ** x, x, 0) + 1 + + +.. index:: differentiation, diff + +Differentiation +--------------- + +You can differentiate any SymPy expression using ``diff(func, +var)``. Examples:: + + >>> sym.diff(sym.sin(x), x) + cos(x) + >>> sym.diff(sym.sin(2 * x), x) + 2*cos(2*x) + + >>> sym.diff(sym.tan(x), x) + 2 + tan (x) + 1 + +You can check that it is correct by:: + + >>> sym.limit((sym.tan(x + y) - sym.tan(x)) / y, y, 0) + 1 + ------- + 2 + cos (x) + +Which is equivalent since + +.. math:: \sec(x) = \frac{1}{\cos(x)} and \sec^2(x) = \tan^2(x) + 1. + +You can check this as well:: + + >>> sym.trigsimp(sym.diff(sym.tan(x), x)) + 1 + ------- + 2 + cos (x) + +Higher derivatives can be calculated using the ``diff(func, var, n)`` method:: + + >>> sym.diff(sym.sin(2 * x), x, 1) + 2*cos(2*x) + + >>> sym.diff(sym.sin(2 * x), x, 2) + -4*sin(2*x) + + >>> sym.diff(sym.sin(2 * x), x, 3) + -8*cos(2*x) + + +Series expansion +---------------- + +SymPy also knows how to compute the Taylor series of an expression at +a point. Use ``series(expr, var)``:: + + >>> sym.series(sym.cos(x), x) + 2 4 + x x / 6\ + 1 - -- + -- + O\x / + 2 24 + >>> sym.series(1/sym.cos(x), x) + 2 4 + x 5*x / 6\ + 1 + -- + ---- + O\x / + 2 24 + + +.. topic:: **Exercises** + :class: green + + 1. Calculate :math:`\lim_{x\rightarrow 0} \sin(x)/x` + 2. Calculate the derivative of :math:`log(x)` for :math:`x`. + +.. index:: integration + +Integration +----------- + +SymPy has support for indefinite and definite integration of transcendental +elementary and special functions via ``integrate()`` facility, which uses +the powerful extended Risch-Norman algorithm and some heuristics and pattern +matching. You can integrate elementary functions:: + + >>> sym.integrate(6 * x ** 5, x) + 6 + x + >>> sym.integrate(sym.sin(x), x) + -cos(x) + >>> sym.integrate(sym.log(x), x) + x*log(x) - x + >>> sym.integrate(2 * x + sym.sinh(x), x) + 2 + x + cosh(x) + +Also special functions are handled easily:: + + >>> sym.integrate(sym.exp(-x ** 2) * sym.erf(x), x) + ____ 2 + \/ pi *erf (x) + -------------- + 4 + +It is possible to compute definite integral:: + + >>> sym.integrate(x**3, (x, -1, 1)) + 0 + >>> sym.integrate(sym.sin(x), (x, 0, sym.pi / 2)) + 1 + >>> sym.integrate(sym.cos(x), (x, -sym.pi / 2, sym.pi / 2)) + 2 + +Also improper integrals are supported as well:: + + >>> sym.integrate(sym.exp(-x), (x, 0, sym.oo)) + 1 + >>> sym.integrate(sym.exp(-x ** 2), (x, -sym.oo, sym.oo)) + ____ + \/ pi + + +.. index:: equations; algebraic, solve + + +Equation solving +================ + +SymPy is able to solve algebraic equations, in one and several +variables using :func:`~sympy.solveset`:: + + >>> sym.solveset(x ** 4 - 1, x) + {-1, 1, -I, I} + +As you can see it takes as first argument an expression that is +supposed to be equaled to 0. It also has (limited) support for transcendental +equations:: + + >>> sym.solveset(sym.exp(x) + 1, x) + {I*(2*n*pi + pi) | n in Integers} + +.. topic:: **Systems of linear equations** + + Sympy is able to solve a large part of + polynomial equations, and is also capable of solving multiple + equations with respect to multiple variables giving a tuple as second + argument. To do this you use the :func:`~sympy.solve` command:: + + >>> solution = sym.solve((x + 5 * y - 2, -3 * x + 6 * y - 15), (x, y)) + >>> solution[x], solution[y] + (-3, 1) + +Another alternative in the case of polynomial equations is +`factor`. `factor` returns the polynomial factorized into irreducible +terms, and is capable of computing the factorization over various +domains:: + + >>> f = x ** 4 - 3 * x ** 2 + 1 + >>> sym.factor(f) + / 2 \ / 2 \ + \x - x - 1/*\x + x - 1/ + + >>> sym.factor(f, modulus=5) + 2 2 + (x - 2) *(x + 2) + +SymPy is also able to solve boolean equations, that is, to decide if a +certain boolean expression is satisfiable or not. For this, we use the +function satisfiable:: + + >>> sym.satisfiable(x & y) + {x: True, y: True} + +This tells us that ``(x & y)`` is True whenever ``x`` and ``y`` are both True. +If an expression cannot be true, i.e. no values of its arguments can make +the expression True, it will return False:: + + >>> sym.satisfiable(x & ~x) + False + + + +.. topic:: **Exercises** + :class: green + + 1. Solve the system of equations :math:`x + y = 2`, :math:`2\cdot x + y = 0` + 2. Are there boolean values ``x``, ``y`` that make ``(~x | y) & (~y | x)`` true? + + +Linear Algebra +============== + +.. index:: Matrix + +Matrices +-------- + +Matrices are created as instances from the Matrix class:: + + >>> sym.Matrix([[1, 0], [0, 1]]) + [1 0] + [ ] + [0 1] + +unlike a NumPy array, you can also put Symbols in it:: + + >>> x, y = sym.symbols('x, y') + >>> A = sym.Matrix([[1, x], [y, 1]]) + >>> A + [1 x] + [ ] + [y 1] + + >>> A**2 + [x*y + 1 2*x ] + [ ] + [ 2*y x*y + 1] + + +.. index:: equations; differential, diff, dsolve + +Differential Equations +---------------------- + +SymPy is capable of solving (some) Ordinary Differential. +To solve differential equations, use dsolve. First, create +an undefined function by passing cls=Function to the symbols function:: + + >>> f, g = sym.symbols('f g', cls=sym.Function) + +f and g are now undefined functions. We can call f(x), and it will represent +an unknown function:: + + >>> f(x) + f(x) + + >>> f(x).diff(x, x) + f(x) + 2 + d + f(x) + ---(f(x)) + 2 + dx + + >>> sym.dsolve(f(x).diff(x, x) + f(x), f(x)) + f(x) = C1*sin(x) + C2*cos(x) + + +Keyword arguments can be given to this function in order to help if +find the best possible resolution system. For example, if you know +that it is a separable equations, you can use keyword ``hint='separable'`` +to force dsolve to resolve it as a separable equation:: + + >>> sym.dsolve(sym.sin(x) * sym.cos(f(x)) + sym.cos(x) * sym.sin(f(x)) * f(x).diff(x), f(x), hint='separable') + / C1 \ / C1 \ + [f(x) = - acos|------| + 2*pi, f(x) = acos|------|] + \cos(x)/ \cos(x)/ + + + +.. topic:: **Exercises** + :class: green + + 1. Solve the Bernoulli differential equation + + .. math:: + x \frac{d f(x)}{x} + f(x) - f(x)^2=0 + + 2. Solve the same equation using ``hint='Bernoulli'``. What do you observe ? diff --git a/_sources/preface.rst.txt b/_sources/preface.rst.txt new file mode 100644 index 000000000..e3754f411 --- /dev/null +++ b/_sources/preface.rst.txt @@ -0,0 +1,60 @@ +==================================== +About the Scientific Python Lectures +==================================== + +.. contents:: + :local: + :depth: 1 + +.. Hack to have multi-column layout in authors list + +*Release:* |release| + +.. image:: https://zenodo.org/badge/doi/10.5281/zenodo.594102.svg + :target: http://dx.doi.org/10.5281/zenodo.594102 + + +.. raw:: html + + + + + +.. include:: AUTHORS.rst + +.. include:: CHANGES.rst + +.. include:: LICENSE.rst + +.. include:: CONTRIBUTING.rst diff --git a/_sources/sg_execution_times.rst.txt b/_sources/sg_execution_times.rst.txt new file mode 100644 index 000000000..67d044dda --- /dev/null +++ b/_sources/sg_execution_times.rst.txt @@ -0,0 +1,553 @@ + +:orphan: + +.. _sphx_glr_sg_execution_times: + + +Computation times +================= +**01:11.364** total execution time for 173 files **from all galleries**: + +.. container:: + + .. raw:: html + + + + + + + + .. list-table:: + :header-rows: 1 + :class: table table-striped sg-datatable + + * - Example + - Time + - Mem (MB) + * - :ref:`sphx_glr_packages_statistics_auto_examples_plot_wage_data.py` (``packages/statistics/examples/plot_wage_data.py``) + - 00:09.494 + - 0.0 + * - :ref:`sphx_glr_packages_statistics_auto_examples_plot_airfare.py` (``packages/statistics/examples/plot_airfare.py``) + - 00:07.718 + - 0.0 + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_gradient_descent.py` (``advanced/mathematical_optimization/examples/plot_gradient_descent.py``) + - 00:06.858 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_features.py` (``packages/scikit-image/examples/plot_features.py``) + - 00:05.704 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_california_prediction.py` (``packages/scikit-learn/examples/plot_california_prediction.py``) + - 00:04.717 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_eigenfaces.py` (``packages/scikit-learn/examples/plot_eigenfaces.py``) + - 00:04.145 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_colormaps.py` (``intro/matplotlib/examples/options/plot_colormaps.py``) + - 00:01.807 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_digits_simple_classif.py` (``packages/scikit-learn/examples/plot_digits_simple_classif.py``) + - 00:01.749 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_bias_variance.py` (``packages/scikit-learn/examples/plot_bias_variance.py``) + - 00:01.391 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_measuring_performance.py` (``packages/scikit-learn/examples/plot_measuring_performance.py``) + - 00:01.300 + - 0.0 + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_exercise_ill_conditioned.py` (``advanced/mathematical_optimization/examples/plot_exercise_ill_conditioned.py``) + - 00:01.296 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_tsne.py` (``packages/scikit-learn/examples/plot_tsne.py``) + - 00:01.216 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_image_transform.py` (``intro/scipy/examples/plot_image_transform.py``) + - 00:00.975 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_ticks.py` (``intro/matplotlib/examples/options/plot_ticks.py``) + - 00:00.923 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_iris_knn.py` (``packages/scikit-learn/examples/plot_iris_knn.py``) + - 00:00.795 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_solutions_plot_fft_image_denoise.py` (``intro/scipy/examples/solutions/plot_fft_image_denoise.py``) + - 00:00.782 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_GMM.py` (``advanced/image_processing/examples/plot_GMM.py``) + - 00:00.780 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_text.py` (``intro/matplotlib/examples/plot_text.py``) + - 00:00.730 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_text_ext.py` (``intro/matplotlib/examples/pretty_plots/plot_text_ext.py``) + - 00:00.714 + - 0.0 + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_compare_optimizers.py` (``advanced/mathematical_optimization/examples/plot_compare_optimizers.py``) + - 00:00.569 + - 0.0 + * - :ref:`sphx_glr_packages_statistics_auto_examples_plot_pandas.py` (``packages/statistics/examples/plot_pandas.py``) + - 00:00.536 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_face.py` (``advanced/image_processing/examples/plot_face.py``) + - 00:00.533 + - 0.0 + * - :ref:`sphx_glr_packages_statistics_auto_examples_plot_wage_education_gender.py` (``packages/statistics/examples/plot_wage_education_gender.py``) + - 00:00.520 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_geom_face.py` (``advanced/image_processing/examples/plot_geom_face.py``) + - 00:00.468 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_image_filters.py` (``intro/scipy/examples/plot_image_filters.py``) + - 00:00.458 + - 0.0 + * - :ref:`sphx_glr_packages_statistics_auto_examples_plot_iris_analysis.py` (``packages/statistics/examples/plot_iris_analysis.py``) + - 00:00.427 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_sharpen.py` (``advanced/image_processing/examples/plot_sharpen.py``) + - 00:00.419 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_linear_model_cv.py` (``packages/scikit-learn/examples/plot_linear_model_cv.py``) + - 00:00.391 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_spectrogram.py` (``intro/scipy/examples/plot_spectrogram.py``) + - 00:00.350 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_display_face.py` (``advanced/image_processing/examples/plot_display_face.py``) + - 00:00.341 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_2d_minimization.py` (``intro/scipy/examples/plot_2d_minimization.py``) + - 00:00.324 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_solutions_plot_image_blur.py` (``intro/scipy/examples/solutions/plot_image_blur.py``) + - 00:00.321 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_optimize_lidar_data_fit.py` (``intro/scipy/summary-exercises/examples/plot_optimize_lidar_data_fit.py``) + - 00:00.296 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_blur.py` (``advanced/image_processing/examples/plot_blur.py``) + - 00:00.282 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_compare_classifiers.py` (``packages/scikit-learn/examples/plot_compare_classifiers.py``) + - 00:00.258 + - 0.0 + * - :ref:`sphx_glr_intro_numpy_auto_examples_plot_elephant.py` (``intro/numpy/examples/plot_elephant.py``) + - 00:00.256 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_granulo.py` (``advanced/image_processing/examples/plot_granulo.py``) + - 00:00.250 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_resample.py` (``intro/scipy/examples/plot_resample.py``) + - 00:00.246 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_sprog_annual_maxima.py` (``intro/scipy/summary-exercises/examples/plot_sprog_annual_maxima.py``) + - 00:00.240 + - 0.0 + * - :ref:`sphx_glr_packages_statistics_auto_examples_solutions_plot_brain_size.py` (``packages/statistics/examples/solutions/plot_brain_size.py``) + - 00:00.236 + - 0.0 + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_1d_optim.py` (``advanced/mathematical_optimization/examples/plot_1d_optim.py``) + - 00:00.231 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_face_tv_denoise.py` (``advanced/image_processing/examples/plot_face_tv_denoise.py``) + - 00:00.215 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_ML_flow_chart.py` (``packages/scikit-learn/examples/plot_ML_flow_chart.py``) + - 00:00.214 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_fftpack.py` (``intro/scipy/examples/plot_fftpack.py``) + - 00:00.203 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_find_edges.py` (``advanced/image_processing/examples/plot_find_edges.py``) + - 00:00.203 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_interpolation.py` (``intro/scipy/examples/plot_interpolation.py``) + - 00:00.202 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_face_denoise.py` (``advanced/image_processing/examples/plot_face_denoise.py``) + - 00:00.201 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_block_mean.py` (``advanced/image_processing/examples/plot_block_mean.py``) + - 00:00.190 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_spectral_clustering.py` (``advanced/image_processing/examples/plot_spectral_clustering.py``) + - 00:00.182 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_radial_mean.py` (``advanced/image_processing/examples/plot_radial_mean.py``) + - 00:00.176 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_polynomial_regression.py` (``packages/scikit-learn/examples/plot_polynomial_regression.py``) + - 00:00.175 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_segmentations.py` (``packages/scikit-image/examples/plot_segmentations.py``) + - 00:00.164 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_numpy_array.py` (``advanced/image_processing/examples/plot_numpy_array.py``) + - 00:00.162 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_interpolation_face.py` (``advanced/image_processing/examples/plot_interpolation_face.py``) + - 00:00.157 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_filter_coins.py` (``packages/scikit-image/examples/plot_filter_coins.py``) + - 00:00.154 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_solutions_plot_periodicity_finder.py` (``intro/scipy/examples/solutions/plot_periodicity_finder.py``) + - 00:00.141 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_denoising.py` (``advanced/image_processing/examples/plot_denoising.py``) + - 00:00.131 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_imshow.py` (``intro/matplotlib/examples/plot_imshow.py``) + - 00:00.122 + - 0.0 + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_exercise_flat_minimum.py` (``advanced/mathematical_optimization/examples/plot_exercise_flat_minimum.py``) + - 00:00.117 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_camera_uint.py` (``packages/scikit-image/examples/plot_camera_uint.py``) + - 00:00.116 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_threshold.py` (``packages/scikit-image/examples/plot_threshold.py``) + - 00:00.116 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_connect_measurements.py` (``intro/scipy/examples/plot_connect_measurements.py``) + - 00:00.114 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_curve_fit.py` (``intro/scipy/examples/plot_curve_fit.py``) + - 00:00.114 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_histo_segmentation.py` (``advanced/image_processing/examples/plot_histo_segmentation.py``) + - 00:00.110 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_polar_ext.py` (``intro/matplotlib/examples/pretty_plots/plot_polar_ext.py``) + - 00:00.110 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_solutions_plot_curvefit_temperature_data.py` (``intro/scipy/examples/solutions/plot_curvefit_temperature_data.py``) + - 00:00.108 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_grid_ext.py` (``intro/matplotlib/examples/pretty_plots/plot_grid_ext.py``) + - 00:00.107 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_variance_linear_regr.py` (``packages/scikit-learn/examples/plot_variance_linear_regr.py``) + - 00:00.107 + - 0.0 + * - :ref:`sphx_glr_packages_statistics_auto_examples_plot_regression.py` (``packages/statistics/examples/plot_regression.py``) + - 00:00.107 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_plot3d.py` (``intro/matplotlib/examples/plot_plot3d.py``) + - 00:00.106 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_grid.py` (``intro/matplotlib/examples/plot_grid.py``) + - 00:00.106 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_9.py` (``intro/matplotlib/examples/exercises/plot_exercise_9.py``) + - 00:00.104 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_t_test.py` (``intro/scipy/examples/plot_t_test.py``) + - 00:00.104 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_10.py` (``intro/matplotlib/examples/exercises/plot_exercise_10.py``) + - 00:00.102 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_normal_distribution.py` (``intro/scipy/examples/plot_normal_distribution.py``) + - 00:00.101 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_boundaries.py` (``packages/scikit-image/examples/plot_boundaries.py``) + - 00:00.099 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_sobel.py` (``packages/scikit-image/examples/plot_sobel.py``) + - 00:00.099 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_pca.py` (``packages/scikit-learn/examples/plot_pca.py``) + - 00:00.099 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_mathematical_morpho.py` (``intro/scipy/examples/plot_mathematical_morpho.py``) + - 00:00.098 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_polar.py` (``intro/matplotlib/examples/plot_polar.py``) + - 00:00.096 + - 0.0 + * - :ref:`sphx_glr_intro_numpy_auto_examples_plot_chebyfit.py` (``intro/numpy/examples/plot_chebyfit.py``) + - 00:00.095 + - 0.0 + * - :ref:`sphx_glr_packages_statistics_auto_examples_plot_regression_3d.py` (``packages/statistics/examples/plot_regression_3d.py``) + - 00:00.093 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_iris_scatter.py` (``packages/scikit-learn/examples/plot_iris_scatter.py``) + - 00:00.093 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_equalize_hist.py` (``packages/scikit-image/examples/plot_equalize_hist.py``) + - 00:00.089 + - 0.0 + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_constraints.py` (``advanced/mathematical_optimization/examples/plot_constraints.py``) + - 00:00.089 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_clean_morpho.py` (``advanced/image_processing/examples/plot_clean_morpho.py``) + - 00:00.087 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_bad.py` (``intro/matplotlib/examples/plot_bad.py``) + - 00:00.086 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_gridspec.py` (``intro/matplotlib/examples/plot_gridspec.py``) + - 00:00.086 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_optimize_lidar_complex_data.py` (``intro/scipy/summary-exercises/examples/plot_optimize_lidar_complex_data.py``) + - 00:00.082 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_multiplot_ext.py` (``intro/matplotlib/examples/pretty_plots/plot_multiplot_ext.py``) + - 00:00.081 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_synthetic_data.py` (``advanced/image_processing/examples/plot_synthetic_data.py``) + - 00:00.081 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_contour_ext.py` (``intro/matplotlib/examples/pretty_plots/plot_contour_ext.py``) + - 00:00.080 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_solve_ivp_simple.py` (``intro/scipy/examples/plot_solve_ivp_simple.py``) + - 00:00.080 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_contour.py` (``intro/matplotlib/examples/plot_contour.py``) + - 00:00.079 + - 0.0 + * - :ref:`sphx_glr_intro_numpy_auto_examples_plot_mandelbrot.py` (``intro/numpy/examples/plot_mandelbrot.py``) + - 00:00.079 + - 0.0 + * - :ref:`sphx_glr_intro_numpy_auto_examples_plot_randomwalk.py` (``intro/numpy/examples/plot_randomwalk.py``) + - 00:00.077 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_optimize_lidar_complex_data_fit.py` (``intro/scipy/summary-exercises/examples/plot_optimize_lidar_complex_data_fit.py``) + - 00:00.077 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_cumulative_wind_speed_prediction.py` (``intro/scipy/summary-exercises/examples/plot_cumulative_wind_speed_prediction.py``) + - 00:00.077 + - 0.0 + * - :ref:`sphx_glr_intro_numpy_auto_examples_plot_basic2dplot.py` (``intro/numpy/examples/plot_basic2dplot.py``) + - 00:00.075 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_labels.py` (``packages/scikit-image/examples/plot_labels.py``) + - 00:00.074 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_markers.py` (``intro/matplotlib/examples/options/plot_markers.py``) + - 00:00.073 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_camera.py` (``packages/scikit-image/examples/plot_camera.py``) + - 00:00.073 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_subplot-grid.py` (``intro/matplotlib/examples/plot_subplot-grid.py``) + - 00:00.072 + - 0.0 + * - :ref:`sphx_glr_packages_statistics_auto_examples_plot_paired_boxplots.py` (``packages/statistics/examples/plot_paired_boxplots.py``) + - 00:00.072 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_optimize_example2.py` (``intro/scipy/examples/plot_optimize_example2.py``) + - 00:00.070 + - 0.0 + * - :ref:`sphx_glr_intro_numpy_auto_examples_plot_distances.py` (``intro/numpy/examples/plot_distances.py``) + - 00:00.069 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_svm_non_linear.py` (``packages/scikit-learn/examples/plot_svm_non_linear.py``) + - 00:00.068 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_gumbell_wind_speed_prediction.py` (``intro/scipy/summary-exercises/examples/plot_gumbell_wind_speed_prediction.py``) + - 00:00.068 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_summary-exercises_auto_examples_plot_optimize_lidar_data.py` (``intro/scipy/summary-exercises/examples/plot_optimize_lidar_data.py``) + - 00:00.066 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_watershed_segmentation.py` (``advanced/image_processing/examples/plot_watershed_segmentation.py``) + - 00:00.064 + - 0.0 + * - :ref:`sphx_glr_intro_numpy_auto_examples_plot_populations.py` (``intro/numpy/examples/plot_populations.py``) + - 00:00.063 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_scatter_ext.py` (``intro/matplotlib/examples/pretty_plots/plot_scatter_ext.py``) + - 00:00.062 + - 0.0 + * - :ref:`sphx_glr_advanced_advanced_numpy_auto_examples_plot_maskedstats.py` (``advanced/advanced_numpy/examples/plots/plot_maskedstats.py``) + - 00:00.062 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_8.py` (``intro/matplotlib/examples/exercises/plot_exercise_8.py``) + - 00:00.061 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_greyscale_dilation.py` (``advanced/image_processing/examples/plot_greyscale_dilation.py``) + - 00:00.060 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_scatter.py` (``intro/matplotlib/examples/plot_scatter.py``) + - 00:00.060 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-image_auto_examples_plot_check.py` (``packages/scikit-image/examples/plot_check.py``) + - 00:00.059 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_pie.py` (``intro/matplotlib/examples/plot_pie.py``) + - 00:00.059 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_1.py` (``intro/matplotlib/examples/exercises/plot_exercise_1.py``) + - 00:00.059 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_pie_ext.py` (``intro/matplotlib/examples/pretty_plots/plot_pie_ext.py``) + - 00:00.058 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_axes-2.py` (``intro/matplotlib/examples/plot_axes-2.py``) + - 00:00.058 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_4.py` (``intro/matplotlib/examples/exercises/plot_exercise_4.py``) + - 00:00.056 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_bar.py` (``intro/matplotlib/examples/plot_bar.py``) + - 00:00.056 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_7.py` (``intro/matplotlib/examples/exercises/plot_exercise_7.py``) + - 00:00.055 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_detrend.py` (``intro/scipy/examples/plot_detrend.py``) + - 00:00.055 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_good.py` (``intro/matplotlib/examples/plot_good.py``) + - 00:00.053 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_plot3d-2.py` (``intro/matplotlib/examples/plot_plot3d-2.py``) + - 00:00.053 + - 0.0 + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_curve_fitting.py` (``advanced/mathematical_optimization/examples/plot_curve_fitting.py``) + - 00:00.053 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_solve_ivp_damped_spring_mass.py` (``intro/scipy/examples/plot_solve_ivp_damped_spring_mass.py``) + - 00:00.052 + - 0.0 + * - :ref:`sphx_glr_guide_auto_examples_plot_simple.py` (``guide/examples/plot_simple.py``) + - 00:00.052 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_separator.py` (``packages/scikit-learn/examples/plot_separator.py``) + - 00:00.051 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_2.py` (``intro/matplotlib/examples/exercises/plot_exercise_2.py``) + - 00:00.051 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_quiver_ext.py` (``intro/matplotlib/examples/pretty_plots/plot_quiver_ext.py``) + - 00:00.051 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_bar_ext.py` (``intro/matplotlib/examples/pretty_plots/plot_bar_ext.py``) + - 00:00.051 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_subplot-horizontal.py` (``intro/matplotlib/examples/plot_subplot-horizontal.py``) + - 00:00.050 + - 0.0 + * - :ref:`sphx_glr_intro_numpy_auto_examples_plot_basic1dplot.py` (``intro/numpy/examples/plot_basic1dplot.py``) + - 00:00.049 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_6.py` (``intro/matplotlib/examples/exercises/plot_exercise_6.py``) + - 00:00.049 + - 0.0 + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_non_bounds_constraints.py` (``advanced/mathematical_optimization/examples/plot_non_bounds_constraints.py``) + - 00:00.049 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_multiplot.py` (``intro/matplotlib/examples/plot_multiplot.py``) + - 00:00.049 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_axes.py` (``intro/matplotlib/examples/plot_axes.py``) + - 00:00.048 + - 0.0 + * - :ref:`sphx_glr_intro_scipy_auto_examples_plot_optimize_example1.py` (``intro/scipy/examples/plot_optimize_example1.py``) + - 00:00.048 + - 0.0 + * - :ref:`sphx_glr_intro_numpy_auto_examples_plot_polyfit.py` (``intro/numpy/examples/plot_polyfit.py``) + - 00:00.048 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_3.py` (``intro/matplotlib/examples/exercises/plot_exercise_3.py``) + - 00:00.048 + - 0.0 + * - :ref:`sphx_glr_packages_scikit-learn_auto_examples_plot_linear_regression.py` (``packages/scikit-learn/examples/plot_linear_regression.py``) + - 00:00.047 + - 0.0 + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_convex.py` (``advanced/mathematical_optimization/examples/plot_convex.py``) + - 00:00.047 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_propagation.py` (``advanced/image_processing/examples/plot_propagation.py``) + - 00:00.045 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_linestyles.py` (``intro/matplotlib/examples/options/plot_linestyles.py``) + - 00:00.044 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_measure_data.py` (``advanced/image_processing/examples/plot_measure_data.py``) + - 00:00.044 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_boxplot_ext.py` (``intro/matplotlib/examples/pretty_plots/plot_boxplot_ext.py``) + - 00:00.044 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_subplot-vertical.py` (``intro/matplotlib/examples/plot_subplot-vertical.py``) + - 00:00.041 + - 0.0 + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_smooth.py` (``advanced/mathematical_optimization/examples/plot_smooth.py``) + - 00:00.041 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_imshow_ext.py` (``intro/matplotlib/examples/pretty_plots/plot_imshow_ext.py``) + - 00:00.040 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_exercises_plot_exercise_5.py` (``intro/matplotlib/examples/exercises/plot_exercise_5.py``) + - 00:00.039 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_plot3d_ext.py` (``intro/matplotlib/examples/pretty_plots/plot_plot3d_ext.py``) + - 00:00.038 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_ugly.py` (``intro/matplotlib/examples/plot_ugly.py``) + - 00:00.036 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_quiver.py` (``intro/matplotlib/examples/plot_quiver.py``) + - 00:00.034 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_plot_plot.py` (``intro/matplotlib/examples/plot_plot.py``) + - 00:00.033 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_pretty_plots_plot_plot_ext.py` (``intro/matplotlib/examples/pretty_plots/plot_plot_ext.py``) + - 00:00.031 + - 0.0 + * - :ref:`sphx_glr_advanced_image_processing_auto_examples_plot_find_object.py` (``advanced/image_processing/examples/plot_find_object.py``) + - 00:00.020 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_linewidth.py` (``intro/matplotlib/examples/options/plot_linewidth.py``) + - 00:00.020 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_alpha.py` (``intro/matplotlib/examples/options/plot_alpha.py``) + - 00:00.019 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_color.py` (``intro/matplotlib/examples/options/plot_color.py``) + - 00:00.018 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_mec.py` (``intro/matplotlib/examples/options/plot_mec.py``) + - 00:00.017 + - 0.0 + * - :ref:`sphx_glr_advanced_mathematical_optimization_auto_examples_plot_noisy.py` (``advanced/mathematical_optimization/examples/plot_noisy.py``) + - 00:00.017 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_mfc.py` (``intro/matplotlib/examples/options/plot_mfc.py``) + - 00:00.017 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_ms.py` (``intro/matplotlib/examples/options/plot_ms.py``) + - 00:00.017 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_mew.py` (``intro/matplotlib/examples/options/plot_mew.py``) + - 00:00.017 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_solid_joinstyle.py` (``intro/matplotlib/examples/options/plot_solid_joinstyle.py``) + - 00:00.014 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_dash_joinstyle.py` (``intro/matplotlib/examples/options/plot_dash_joinstyle.py``) + - 00:00.014 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_dash_capstyle.py` (``intro/matplotlib/examples/options/plot_dash_capstyle.py``) + - 00:00.014 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_solid_capstyle.py` (``intro/matplotlib/examples/options/plot_solid_capstyle.py``) + - 00:00.013 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_antialiased.py` (``intro/matplotlib/examples/options/plot_antialiased.py``) + - 00:00.013 + - 0.0 + * - :ref:`sphx_glr_intro_matplotlib_auto_examples_options_plot_aliased.py` (``intro/matplotlib/examples/options/plot_aliased.py``) + - 00:00.012 + - 0.0 diff --git a/_static/basic.css b/_static/basic.css new file mode 100644 index 000000000..f316efcb4 --- /dev/null +++ b/_static/basic.css @@ -0,0 +1,925 @@ +/* + * basic.css + * ~~~~~~~~~ + * + * Sphinx stylesheet -- basic theme. + * + * :copyright: Copyright 2007-2024 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/* -- main layout ----------------------------------------------------------- */ + +div.clearer { + clear: both; +} + +div.section::after { + display: block; + content: ''; + clear: left; +} + +/* -- relbar ---------------------------------------------------------------- */ + +div.related { + width: 100%; + font-size: 90%; +} + +div.related h3 { + display: none; +} + +div.related ul { + margin: 0; + padding: 0 0 0 10px; + list-style: none; +} + +div.related li { + display: inline; +} + +div.related li.right { + float: right; + margin-right: 5px; +} + +/* -- sidebar --------------------------------------------------------------- */ + +div.sphinxsidebarwrapper { + padding: 10px 5px 0 10px; +} + +div.sphinxsidebar { + float: left; + width: 230px; + margin-left: -100%; + font-size: 90%; + word-wrap: break-word; + overflow-wrap : break-word; +} + +div.sphinxsidebar ul { + list-style: none; +} + +div.sphinxsidebar ul ul, +div.sphinxsidebar ul.want-points { + margin-left: 20px; + list-style: square; +} + +div.sphinxsidebar ul ul { + margin-top: 0; + margin-bottom: 0; +} + +div.sphinxsidebar form { + margin-top: 10px; +} + +div.sphinxsidebar input { + border: 1px solid #98dbcc; + font-family: sans-serif; + font-size: 1em; +} + +div.sphinxsidebar #searchbox form.search { + overflow: hidden; +} + +div.sphinxsidebar #searchbox input[type="text"] { + float: left; + width: 80%; + padding: 0.25em; + box-sizing: border-box; +} + +div.sphinxsidebar #searchbox input[type="submit"] { + float: left; + width: 20%; + border-left: none; + padding: 0.25em; + box-sizing: border-box; +} + + +img { + border: 0; + max-width: 100%; +} + +/* -- search page ----------------------------------------------------------- */ + +ul.search { + margin: 10px 0 0 20px; + padding: 0; +} + +ul.search li { + padding: 5px 0 5px 20px; + background-image: url(file.png); + background-repeat: no-repeat; + background-position: 0 7px; +} + +ul.search li a { + font-weight: bold; +} + +ul.search li p.context { + color: #888; + margin: 2px 0 0 30px; + text-align: left; +} + +ul.keywordmatches li.goodmatch a { + font-weight: bold; +} + +/* -- index page ------------------------------------------------------------ */ + +table.contentstable { + width: 90%; + margin-left: auto; + margin-right: auto; +} + +table.contentstable p.biglink { + line-height: 150%; +} + +a.biglink { + font-size: 1.3em; +} + +span.linkdescr { + font-style: italic; + padding-top: 5px; + font-size: 90%; +} + +/* -- general index --------------------------------------------------------- */ + +table.indextable { + width: 100%; +} + +table.indextable td { + text-align: left; + vertical-align: top; +} + +table.indextable ul { + margin-top: 0; + margin-bottom: 0; + list-style-type: none; +} + +table.indextable > tbody > tr > td > ul { + padding-left: 0em; +} + +table.indextable tr.pcap { + height: 10px; +} + +table.indextable tr.cap { + margin-top: 10px; + background-color: #f2f2f2; +} + +img.toggler { + margin-right: 3px; + margin-top: 3px; + cursor: pointer; +} + +div.modindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +div.genindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +/* -- domain module index --------------------------------------------------- */ + +table.modindextable td { + padding: 2px; + border-collapse: collapse; +} + +/* -- general body styles --------------------------------------------------- */ + +div.body { + min-width: 360px; + max-width: 800px; +} + +div.body p, div.body dd, div.body li, div.body blockquote { + -moz-hyphens: auto; + -ms-hyphens: auto; + -webkit-hyphens: auto; + hyphens: auto; +} + +a.headerlink { + visibility: hidden; +} + +a:visited { + color: #551A8B; +} + +h1:hover > a.headerlink, +h2:hover > a.headerlink, +h3:hover > a.headerlink, +h4:hover > a.headerlink, +h5:hover > a.headerlink, +h6:hover > a.headerlink, +dt:hover > a.headerlink, +caption:hover > a.headerlink, +p.caption:hover > a.headerlink, +div.code-block-caption:hover > a.headerlink { + visibility: visible; +} + +div.body p.caption { + text-align: inherit; +} + +div.body td { + text-align: left; +} + +.first { + margin-top: 0 !important; +} + +p.rubric { + margin-top: 30px; + font-weight: bold; +} + +img.align-left, figure.align-left, .figure.align-left, object.align-left { + clear: left; + float: left; + margin-right: 1em; +} + +img.align-right, figure.align-right, .figure.align-right, object.align-right { + clear: right; + float: right; + margin-left: 1em; +} + +img.align-center, figure.align-center, .figure.align-center, object.align-center { + display: block; + margin-left: auto; + margin-right: auto; +} + +img.align-default, figure.align-default, .figure.align-default { + display: block; + margin-left: auto; + margin-right: auto; +} + +.align-left { + text-align: left; +} + +.align-center { + text-align: center; +} + +.align-default { + text-align: center; +} + +.align-right { + text-align: right; +} + +/* -- sidebars -------------------------------------------------------------- */ + +div.sidebar, +aside.sidebar { + margin: 0 0 0.5em 1em; + border: 1px solid #ddb; + padding: 7px; + background-color: #ffe; + width: 40%; + float: right; + clear: right; + overflow-x: auto; +} + +p.sidebar-title { + font-weight: bold; +} + +nav.contents, +aside.topic, +div.admonition, div.topic, blockquote { + clear: left; +} + +/* -- topics ---------------------------------------------------------------- */ + +nav.contents, +aside.topic, +div.topic { + border: 1px solid #ccc; + padding: 7px; + margin: 10px 0 10px 0; +} + +p.topic-title { + font-size: 1.1em; + font-weight: bold; + margin-top: 10px; +} + +/* -- admonitions ----------------------------------------------------------- */ + +div.admonition { + margin-top: 10px; + margin-bottom: 10px; + padding: 7px; +} + +div.admonition dt { + font-weight: bold; +} + +p.admonition-title { + margin: 0px 10px 5px 0px; + font-weight: bold; +} + +div.body p.centered { + text-align: center; + margin-top: 25px; +} + +/* -- content of sidebars/topics/admonitions -------------------------------- */ + +div.sidebar > :last-child, +aside.sidebar > :last-child, +nav.contents > :last-child, +aside.topic > :last-child, +div.topic > :last-child, +div.admonition > :last-child { + margin-bottom: 0; +} + +div.sidebar::after, +aside.sidebar::after, +nav.contents::after, +aside.topic::after, +div.topic::after, +div.admonition::after, +blockquote::after { + display: block; + content: ''; + clear: both; +} + +/* -- tables ---------------------------------------------------------------- */ + +table.docutils { + margin-top: 10px; + margin-bottom: 10px; + border: 0; + border-collapse: collapse; +} + +table.align-center { + margin-left: auto; + margin-right: auto; +} + +table.align-default { + margin-left: auto; + margin-right: auto; +} + +table caption span.caption-number { + font-style: italic; +} + +table caption span.caption-text { +} + +table.docutils td, table.docutils th { + padding: 1px 8px 1px 5px; + border-top: 0; + border-left: 0; + border-right: 0; + border-bottom: 1px solid #aaa; +} + +th { + text-align: left; + padding-right: 5px; +} + +table.citation { + border-left: solid 1px gray; + margin-left: 1px; +} + +table.citation td { + border-bottom: none; +} + +th > :first-child, +td > :first-child { + margin-top: 0px; +} + +th > :last-child, +td > :last-child { + margin-bottom: 0px; +} + +/* -- figures --------------------------------------------------------------- */ + +div.figure, figure { + margin: 0.5em; + padding: 0.5em; +} + +div.figure p.caption, figcaption { + padding: 0.3em; +} + +div.figure p.caption span.caption-number, +figcaption span.caption-number { + font-style: italic; +} + +div.figure p.caption span.caption-text, +figcaption span.caption-text { +} + +/* -- field list styles ----------------------------------------------------- */ + +table.field-list td, table.field-list th { + border: 0 !important; +} + +.field-list ul { + margin: 0; + padding-left: 1em; +} + +.field-list p { + margin: 0; +} + +.field-name { + -moz-hyphens: manual; + -ms-hyphens: manual; + -webkit-hyphens: manual; + hyphens: manual; +} + +/* -- hlist styles ---------------------------------------------------------- */ + +table.hlist { + margin: 1em 0; +} + +table.hlist td { + vertical-align: top; +} + +/* -- object description styles --------------------------------------------- */ + +.sig { + font-family: 'Consolas', 'Menlo', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace; +} + +.sig-name, code.descname { + background-color: transparent; + font-weight: bold; +} + +.sig-name { + font-size: 1.1em; +} + +code.descname { + font-size: 1.2em; +} + +.sig-prename, code.descclassname { + background-color: transparent; +} + +.optional { + font-size: 1.3em; +} + +.sig-paren { + font-size: larger; +} + +.sig-param.n { + font-style: italic; +} + +/* C++ specific styling */ + +.sig-inline.c-texpr, +.sig-inline.cpp-texpr { + font-family: unset; +} + +.sig.c .k, .sig.c .kt, +.sig.cpp .k, .sig.cpp .kt { + color: #0033B3; +} + +.sig.c .m, +.sig.cpp .m { + color: #1750EB; +} + +.sig.c .s, .sig.c .sc, +.sig.cpp .s, .sig.cpp .sc { + color: #067D17; +} + + +/* -- other body styles ----------------------------------------------------- */ + +ol.arabic { + list-style: decimal; +} + +ol.loweralpha { + list-style: lower-alpha; +} + +ol.upperalpha { + list-style: upper-alpha; +} + +ol.lowerroman { + list-style: lower-roman; +} + +ol.upperroman { + list-style: upper-roman; +} + +:not(li) > ol > li:first-child > :first-child, +:not(li) > ul > li:first-child > :first-child { + margin-top: 0px; +} + +:not(li) > ol > li:last-child > :last-child, +:not(li) > ul > li:last-child > :last-child { + margin-bottom: 0px; +} + +ol.simple ol p, +ol.simple ul p, +ul.simple ol p, +ul.simple ul p { + margin-top: 0; +} + +ol.simple > li:not(:first-child) > p, +ul.simple > li:not(:first-child) > p { + margin-top: 0; +} + +ol.simple p, +ul.simple p { + margin-bottom: 0; +} + +aside.footnote > span, +div.citation > span { + float: left; +} +aside.footnote > span:last-of-type, +div.citation > span:last-of-type { + padding-right: 0.5em; +} +aside.footnote > p { + margin-left: 2em; +} +div.citation > p { + margin-left: 4em; +} +aside.footnote > p:last-of-type, +div.citation > p:last-of-type { + margin-bottom: 0em; +} +aside.footnote > p:last-of-type:after, +div.citation > p:last-of-type:after { + content: ""; + clear: both; +} + +dl.field-list { + display: grid; + grid-template-columns: fit-content(30%) auto; +} + +dl.field-list > dt { + font-weight: bold; + word-break: break-word; + padding-left: 0.5em; + padding-right: 5px; +} + +dl.field-list > dd { + padding-left: 0.5em; + margin-top: 0em; + margin-left: 0em; + margin-bottom: 0em; +} + +dl { + margin-bottom: 15px; +} + +dd > :first-child { + margin-top: 0px; +} + +dd ul, dd table { + margin-bottom: 10px; +} + +dd { + margin-top: 3px; + margin-bottom: 10px; + margin-left: 30px; +} + +.sig dd { + margin-top: 0px; + margin-bottom: 0px; +} + +.sig dl { + margin-top: 0px; + margin-bottom: 0px; +} + +dl > dd:last-child, +dl > dd:last-child > :last-child { + margin-bottom: 0; +} + +dt:target, span.highlighted { + background-color: #fbe54e; +} + +rect.highlighted { + fill: #fbe54e; +} + +dl.glossary dt { + font-weight: bold; + font-size: 1.1em; +} + +.versionmodified { + font-style: italic; +} + +.system-message { + background-color: #fda; + padding: 5px; + border: 3px solid red; +} + +.footnote:target { + background-color: #ffa; +} + +.line-block { + display: block; + margin-top: 1em; + margin-bottom: 1em; +} + +.line-block .line-block { + margin-top: 0; + margin-bottom: 0; + margin-left: 1.5em; +} + +.guilabel, .menuselection { + font-family: sans-serif; +} + +.accelerator { + text-decoration: underline; +} + +.classifier { + font-style: oblique; +} + +.classifier:before { + font-style: normal; + margin: 0 0.5em; + content: ":"; + display: inline-block; +} + +abbr, acronym { + border-bottom: dotted 1px; + cursor: help; +} + +.translated { + background-color: rgba(207, 255, 207, 0.2) +} + +.untranslated { + background-color: rgba(255, 207, 207, 0.2) +} + +/* -- code displays --------------------------------------------------------- */ + +pre { + overflow: auto; + overflow-y: hidden; /* fixes display issues on Chrome browsers */ +} + +pre, div[class*="highlight-"] { + clear: both; +} + +span.pre { + -moz-hyphens: none; + -ms-hyphens: none; + -webkit-hyphens: none; + hyphens: none; + white-space: nowrap; +} + +div[class*="highlight-"] { + margin: 1em 0; +} + +td.linenos pre { + border: 0; + background-color: transparent; + color: #aaa; +} + +table.highlighttable { + display: block; +} + +table.highlighttable tbody { + display: block; +} + +table.highlighttable tr { + display: flex; +} + +table.highlighttable td { + margin: 0; + padding: 0; +} + +table.highlighttable td.linenos { + padding-right: 0.5em; +} + +table.highlighttable td.code { + flex: 1; + overflow: hidden; +} + +.highlight .hll { + display: block; +} + +div.highlight pre, +table.highlighttable pre { + margin: 0; +} + +div.code-block-caption + div { + margin-top: 0; +} + +div.code-block-caption { + margin-top: 1em; + padding: 2px 5px; + font-size: small; +} + +div.code-block-caption code { + background-color: transparent; +} + +table.highlighttable td.linenos, +span.linenos, +div.highlight span.gp { /* gp: Generic.Prompt */ + user-select: none; + -webkit-user-select: text; /* Safari fallback only */ + -webkit-user-select: none; /* Chrome/Safari */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* IE10+ */ +} + +div.code-block-caption span.caption-number { + padding: 0.1em 0.3em; + font-style: italic; +} + +div.code-block-caption span.caption-text { +} + +div.literal-block-wrapper { + margin: 1em 0; +} + +code.xref, a code { + background-color: transparent; + font-weight: bold; +} + +h1 code, h2 code, h3 code, h4 code, h5 code, h6 code { + background-color: transparent; +} + +.viewcode-link { + float: right; +} + +.viewcode-back { + float: right; + font-family: sans-serif; +} + +div.viewcode-block:target { + margin: -1px -10px; + padding: 0 10px; +} + +/* -- math display ---------------------------------------------------------- */ + +img.math { + vertical-align: middle; +} + +div.body div.math p { + text-align: center; +} + +span.eqno { + float: right; +} + +span.eqno a.headerlink { + position: absolute; + z-index: 1; +} + +div.math:hover a.headerlink { + visibility: visible; +} + +/* -- printout stylesheet --------------------------------------------------- */ + +@media print { + div.document, + div.documentwrapper, + div.bodywrapper { + margin: 0 !important; + width: 100%; + } + + div.sphinxsidebar, + div.related, + div.footer, + #top-link { + display: none; + } +} \ No newline at end of file diff --git a/_static/binder_badge_logo.svg b/_static/binder_badge_logo.svg new file mode 100644 index 000000000..327f6b639 --- /dev/null +++ b/_static/binder_badge_logo.svg @@ -0,0 +1 @@ + launchlaunchbinderbinder \ No newline at end of file diff --git a/_static/broken_example.png b/_static/broken_example.png new file mode 100644 index 000000000..4fea24e7d Binary files /dev/null and b/_static/broken_example.png differ diff --git a/_static/check-solid.svg b/_static/check-solid.svg new file mode 100644 index 000000000..92fad4b5c --- /dev/null +++ b/_static/check-solid.svg @@ -0,0 +1,4 @@ + + + + diff --git a/_static/classic.css b/_static/classic.css new file mode 100644 index 000000000..d0ac21e43 --- /dev/null +++ b/_static/classic.css @@ -0,0 +1,269 @@ +/* + * classic.css_t + * ~~~~~~~~~~~~~ + * + * Sphinx stylesheet -- classic theme. + * + * :copyright: Copyright 2007-2024 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +@import url("basic.css"); + +/* -- page layout ----------------------------------------------------------- */ + +html { + /* CSS hack for macOS's scrollbar (see #1125) */ + background-color: #FFFFFF; +} + +body { + font-family: sans-serif; + font-size: 100%; + background-color: #000000; + color: #000; + margin: 0; + padding: 0; +} + +div.document { + display: flex; + background-color: #1c4e63; +} + +div.documentwrapper { + float: left; + width: 100%; +} + +div.bodywrapper { + margin: 0 0 0 230px; +} + +div.body { + background-color: #ffffff; + color: #000000; + padding: 0 20px 30px 20px; +} + +div.footer { + color: #ffffff; + width: 100%; + padding: 9px 0 9px 0; + text-align: center; + font-size: 75%; +} + +div.footer a { + color: #ffffff; + text-decoration: underline; +} + +div.related { + background-color: #000000; + line-height: 30px; + color: #ffffff; +} + +div.related a { + color: #ffffff; +} + +div.sphinxsidebar { +} + +div.sphinxsidebar h3 { + font-family: 'Trebuchet MS', sans-serif; + color: #ffffff; + font-size: 1.4em; + font-weight: normal; + margin: 0; + padding: 0; +} + +div.sphinxsidebar h3 a { + color: #ffffff; +} + +div.sphinxsidebar h4 { + font-family: 'Trebuchet MS', sans-serif; + color: #ffffff; + font-size: 1.3em; + font-weight: normal; + margin: 5px 0 0 0; + padding: 0; +} + +div.sphinxsidebar p { + color: #ffffff; +} + +div.sphinxsidebar p.topless { + margin: 5px 10px 10px 10px; +} + +div.sphinxsidebar ul { + margin: 10px; + padding: 0; + color: #ffffff; +} + +div.sphinxsidebar a { + color: #98dbcc; +} + +div.sphinxsidebar input { + border: 1px solid #98dbcc; + font-family: sans-serif; + font-size: 1em; +} + + + +/* -- hyperlink styles ------------------------------------------------------ */ + +a { + color: #355f7c; + text-decoration: none; +} + +a:visited { + color: #551a8b; + text-decoration: none; +} + +a:hover { + text-decoration: underline; +} + + + +/* -- body styles ----------------------------------------------------------- */ + +div.body h1, +div.body h2, +div.body h3, +div.body h4, +div.body h5, +div.body h6 { + font-family: 'Trebuchet MS', sans-serif; + background-color: #f2f2f2; + font-weight: normal; + color: #20435c; + border-bottom: 1px solid #ccc; + margin: 20px -20px 10px -20px; + padding: 3px 0 3px 10px; +} + +div.body h1 { margin-top: 0; font-size: 200%; } +div.body h2 { font-size: 160%; } +div.body h3 { font-size: 140%; } +div.body h4 { font-size: 120%; } +div.body h5 { font-size: 110%; } +div.body h6 { font-size: 100%; } + +a.headerlink { + color: #c60f0f; + font-size: 0.8em; + padding: 0 4px 0 4px; + text-decoration: none; +} + +a.headerlink:hover { + background-color: #c60f0f; + color: white; +} + +div.body p, div.body dd, div.body li, div.body blockquote { + text-align: justify; + line-height: 130%; +} + +div.admonition p.admonition-title + p { + display: inline; +} + +div.admonition p { + margin-bottom: 5px; +} + +div.admonition pre { + margin-bottom: 5px; +} + +div.admonition ul, div.admonition ol { + margin-bottom: 5px; +} + +div.note { + background-color: #eee; + border: 1px solid #ccc; +} + +div.seealso { + background-color: #ffc; + border: 1px solid #ff6; +} + +nav.contents, +aside.topic, +div.topic { + background-color: #eee; +} + +div.warning { + background-color: #ffe4e4; + border: 1px solid #f66; +} + +p.admonition-title { + display: inline; +} + +p.admonition-title:after { + content: ":"; +} + +pre { + padding: 5px; + background-color: unset; + color: unset; + line-height: 120%; + border: 1px solid #ac9; + border-left: none; + border-right: none; +} + +code { + background-color: #ecf0f3; + padding: 0 1px 0 1px; + font-size: 0.95em; +} + +th, dl.field-list > dt { + background-color: #ede; +} + +.warning code { + background: #efc2c2; +} + +.note code { + background: #d6d6d6; +} + +.viewcode-back { + font-family: sans-serif; +} + +div.viewcode-block:target { + background-color: #f4debf; + border-top: 1px solid #ac9; + border-bottom: 1px solid #ac9; +} + +div.code-block-caption { + color: #efefef; + background-color: #1c4e63; +} \ No newline at end of file diff --git a/_static/clipboard.min.js b/_static/clipboard.min.js new file mode 100644 index 000000000..54b3c4638 --- /dev/null +++ b/_static/clipboard.min.js @@ -0,0 +1,7 @@ +/*! + * clipboard.js v2.0.8 + * https://clipboardjs.com/ + * + * Licensed MIT © Zeno Rocha + */ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.ClipboardJS=e():t.ClipboardJS=e()}(this,function(){return n={686:function(t,e,n){"use strict";n.d(e,{default:function(){return o}});var e=n(279),i=n.n(e),e=n(370),u=n.n(e),e=n(817),c=n.n(e);function a(t){try{return document.execCommand(t)}catch(t){return}}var f=function(t){t=c()(t);return a("cut"),t};var l=function(t){var e,n,o,r=1 + + + + diff --git a/_static/copybutton.css b/_static/copybutton.css new file mode 100644 index 000000000..f1916ec7d --- /dev/null +++ b/_static/copybutton.css @@ -0,0 +1,94 @@ +/* Copy buttons */ +button.copybtn { + position: absolute; + display: flex; + top: .3em; + right: .3em; + width: 1.7em; + height: 1.7em; + opacity: 0; + transition: opacity 0.3s, border .3s, background-color .3s; + user-select: none; + padding: 0; + border: none; + outline: none; + border-radius: 0.4em; + /* The colors that GitHub uses */ + border: #1b1f2426 1px solid; + background-color: #f6f8fa; + color: #57606a; +} + +button.copybtn.success { + border-color: #22863a; + color: #22863a; +} + +button.copybtn svg { + stroke: currentColor; + width: 1.5em; + height: 1.5em; + padding: 0.1em; +} + +div.highlight { + position: relative; +} + +/* Show the copybutton */ +.highlight:hover button.copybtn, button.copybtn.success { + opacity: 1; +} + +.highlight button.copybtn:hover { + background-color: rgb(235, 235, 235); +} + +.highlight button.copybtn:active { + background-color: rgb(187, 187, 187); +} + +/** + * A minimal CSS-only tooltip copied from: + * https://codepen.io/mildrenben/pen/rVBrpK + * + * To use, write HTML like the following: + * + *

Short

+ */ + .o-tooltip--left { + position: relative; + } + + .o-tooltip--left:after { + opacity: 0; + visibility: hidden; + position: absolute; + content: attr(data-tooltip); + padding: .2em; + font-size: .8em; + left: -.2em; + background: grey; + color: white; + white-space: nowrap; + z-index: 2; + border-radius: 2px; + transform: translateX(-102%) translateY(0); + transition: opacity 0.2s cubic-bezier(0.64, 0.09, 0.08, 1), transform 0.2s cubic-bezier(0.64, 0.09, 0.08, 1); +} + +.o-tooltip--left:hover:after { + display: block; + opacity: 1; + visibility: visible; + transform: translateX(-100%) translateY(0); + transition: opacity 0.2s cubic-bezier(0.64, 0.09, 0.08, 1), transform 0.2s cubic-bezier(0.64, 0.09, 0.08, 1); + transition-delay: .5s; +} + +/* By default the copy button shouldn't show up when printing a page */ +@media print { + button.copybtn { + display: none; + } +} diff --git a/_static/copybutton.js b/_static/copybutton.js new file mode 100644 index 000000000..d53be9783 --- /dev/null +++ b/_static/copybutton.js @@ -0,0 +1,248 @@ +// Localization support +const messages = { + 'en': { + 'copy': 'Copy', + 'copy_to_clipboard': 'Copy to clipboard', + 'copy_success': 'Copied!', + 'copy_failure': 'Failed to copy', + }, + 'es' : { + 'copy': 'Copiar', + 'copy_to_clipboard': 'Copiar al portapapeles', + 'copy_success': '¡Copiado!', + 'copy_failure': 'Error al copiar', + }, + 'de' : { + 'copy': 'Kopieren', + 'copy_to_clipboard': 'In die Zwischenablage kopieren', + 'copy_success': 'Kopiert!', + 'copy_failure': 'Fehler beim Kopieren', + }, + 'fr' : { + 'copy': 'Copier', + 'copy_to_clipboard': 'Copier dans le presse-papier', + 'copy_success': 'Copié !', + 'copy_failure': 'Échec de la copie', + }, + 'ru': { + 'copy': 'Скопировать', + 'copy_to_clipboard': 'Скопировать в буфер', + 'copy_success': 'Скопировано!', + 'copy_failure': 'Не удалось скопировать', + }, + 'zh-CN': { + 'copy': '复制', + 'copy_to_clipboard': '复制到剪贴板', + 'copy_success': '复制成功!', + 'copy_failure': '复制失败', + }, + 'it' : { + 'copy': 'Copiare', + 'copy_to_clipboard': 'Copiato negli appunti', + 'copy_success': 'Copiato!', + 'copy_failure': 'Errore durante la copia', + } +} + +let locale = 'en' +if( document.documentElement.lang !== undefined + && messages[document.documentElement.lang] !== undefined ) { + locale = document.documentElement.lang +} + +let doc_url_root = DOCUMENTATION_OPTIONS.URL_ROOT; +if (doc_url_root == '#') { + doc_url_root = ''; +} + +/** + * SVG files for our copy buttons + */ +let iconCheck = ` + ${messages[locale]['copy_success']} + + +` + +// If the user specified their own SVG use that, otherwise use the default +let iconCopy = ``; +if (!iconCopy) { + iconCopy = ` + ${messages[locale]['copy_to_clipboard']} + + + +` +} + +/** + * Set up copy/paste for code blocks + */ + +const runWhenDOMLoaded = cb => { + if (document.readyState != 'loading') { + cb() + } else if (document.addEventListener) { + document.addEventListener('DOMContentLoaded', cb) + } else { + document.attachEvent('onreadystatechange', function() { + if (document.readyState == 'complete') cb() + }) + } +} + +const codeCellId = index => `codecell${index}` + +// Clears selected text since ClipboardJS will select the text when copying +const clearSelection = () => { + if (window.getSelection) { + window.getSelection().removeAllRanges() + } else if (document.selection) { + document.selection.empty() + } +} + +// Changes tooltip text for a moment, then changes it back +// We want the timeout of our `success` class to be a bit shorter than the +// tooltip and icon change, so that we can hide the icon before changing back. +var timeoutIcon = 2000; +var timeoutSuccessClass = 1500; + +const temporarilyChangeTooltip = (el, oldText, newText) => { + el.setAttribute('data-tooltip', newText) + el.classList.add('success') + // Remove success a little bit sooner than we change the tooltip + // So that we can use CSS to hide the copybutton first + setTimeout(() => el.classList.remove('success'), timeoutSuccessClass) + setTimeout(() => el.setAttribute('data-tooltip', oldText), timeoutIcon) +} + +// Changes the copy button icon for two seconds, then changes it back +const temporarilyChangeIcon = (el) => { + el.innerHTML = iconCheck; + setTimeout(() => {el.innerHTML = iconCopy}, timeoutIcon) +} + +const addCopyButtonToCodeCells = () => { + // If ClipboardJS hasn't loaded, wait a bit and try again. This + // happens because we load ClipboardJS asynchronously. + if (window.ClipboardJS === undefined) { + setTimeout(addCopyButtonToCodeCells, 250) + return + } + + // Add copybuttons to all of our code cells + const COPYBUTTON_SELECTOR = 'div.highlight pre'; + const codeCells = document.querySelectorAll(COPYBUTTON_SELECTOR) + codeCells.forEach((codeCell, index) => { + const id = codeCellId(index) + codeCell.setAttribute('id', id) + + const clipboardButton = id => + `` + codeCell.insertAdjacentHTML('afterend', clipboardButton(id)) + }) + +function escapeRegExp(string) { + return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string +} + +/** + * Removes excluded text from a Node. + * + * @param {Node} target Node to filter. + * @param {string} exclude CSS selector of nodes to exclude. + * @returns {DOMString} Text from `target` with text removed. + */ +function filterText(target, exclude) { + const clone = target.cloneNode(true); // clone as to not modify the live DOM + if (exclude) { + // remove excluded nodes + clone.querySelectorAll(exclude).forEach(node => node.remove()); + } + return clone.innerText; +} + +// Callback when a copy button is clicked. Will be passed the node that was clicked +// should then grab the text and replace pieces of text that shouldn't be used in output +function formatCopyText(textContent, copybuttonPromptText, isRegexp = false, onlyCopyPromptLines = true, removePrompts = true, copyEmptyLines = true, lineContinuationChar = "", hereDocDelim = "") { + var regexp; + var match; + + // Do we check for line continuation characters and "HERE-documents"? + var useLineCont = !!lineContinuationChar + var useHereDoc = !!hereDocDelim + + // create regexp to capture prompt and remaining line + if (isRegexp) { + regexp = new RegExp('^(' + copybuttonPromptText + ')(.*)') + } else { + regexp = new RegExp('^(' + escapeRegExp(copybuttonPromptText) + ')(.*)') + } + + const outputLines = []; + var promptFound = false; + var gotLineCont = false; + var gotHereDoc = false; + const lineGotPrompt = []; + for (const line of textContent.split('\n')) { + match = line.match(regexp) + if (match || gotLineCont || gotHereDoc) { + promptFound = regexp.test(line) + lineGotPrompt.push(promptFound) + if (removePrompts && promptFound) { + outputLines.push(match[2]) + } else { + outputLines.push(line) + } + gotLineCont = line.endsWith(lineContinuationChar) & useLineCont + if (line.includes(hereDocDelim) & useHereDoc) + gotHereDoc = !gotHereDoc + } else if (!onlyCopyPromptLines) { + outputLines.push(line) + } else if (copyEmptyLines && line.trim() === '') { + outputLines.push(line) + } + } + + // If no lines with the prompt were found then just use original lines + if (lineGotPrompt.some(v => v === true)) { + textContent = outputLines.join('\n'); + } + + // Remove a trailing newline to avoid auto-running when pasting + if (textContent.endsWith("\n")) { + textContent = textContent.slice(0, -1) + } + return textContent +} + + +var copyTargetText = (trigger) => { + var target = document.querySelector(trigger.attributes['data-clipboard-target'].value); + + // get filtered text + let exclude = '.linenos'; + + let text = filterText(target, exclude); + return formatCopyText(text, '>>> |\\.\\.\\. |\\$ |In \\[\\d*\\]: | {2,5}\\.\\.\\.: | {5,8}: ', true, true, true, false, '', '') +} + + // Initialize with a callback so we can modify the text before copy + const clipboard = new ClipboardJS('.copybtn', {text: copyTargetText}) + + // Update UI with error/success messages + clipboard.on('success', event => { + clearSelection() + temporarilyChangeTooltip(event.trigger, messages[locale]['copy'], messages[locale]['copy_success']) + temporarilyChangeIcon(event.trigger) + }) + + clipboard.on('error', event => { + temporarilyChangeTooltip(event.trigger, messages[locale]['copy'], messages[locale]['copy_failure']) + }) +} + +runWhenDOMLoaded(addCopyButtonToCodeCells) \ No newline at end of file diff --git a/_static/copybutton_funcs.js b/_static/copybutton_funcs.js new file mode 100644 index 000000000..dbe1aaad7 --- /dev/null +++ b/_static/copybutton_funcs.js @@ -0,0 +1,73 @@ +function escapeRegExp(string) { + return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string +} + +/** + * Removes excluded text from a Node. + * + * @param {Node} target Node to filter. + * @param {string} exclude CSS selector of nodes to exclude. + * @returns {DOMString} Text from `target` with text removed. + */ +export function filterText(target, exclude) { + const clone = target.cloneNode(true); // clone as to not modify the live DOM + if (exclude) { + // remove excluded nodes + clone.querySelectorAll(exclude).forEach(node => node.remove()); + } + return clone.innerText; +} + +// Callback when a copy button is clicked. Will be passed the node that was clicked +// should then grab the text and replace pieces of text that shouldn't be used in output +export function formatCopyText(textContent, copybuttonPromptText, isRegexp = false, onlyCopyPromptLines = true, removePrompts = true, copyEmptyLines = true, lineContinuationChar = "", hereDocDelim = "") { + var regexp; + var match; + + // Do we check for line continuation characters and "HERE-documents"? + var useLineCont = !!lineContinuationChar + var useHereDoc = !!hereDocDelim + + // create regexp to capture prompt and remaining line + if (isRegexp) { + regexp = new RegExp('^(' + copybuttonPromptText + ')(.*)') + } else { + regexp = new RegExp('^(' + escapeRegExp(copybuttonPromptText) + ')(.*)') + } + + const outputLines = []; + var promptFound = false; + var gotLineCont = false; + var gotHereDoc = false; + const lineGotPrompt = []; + for (const line of textContent.split('\n')) { + match = line.match(regexp) + if (match || gotLineCont || gotHereDoc) { + promptFound = regexp.test(line) + lineGotPrompt.push(promptFound) + if (removePrompts && promptFound) { + outputLines.push(match[2]) + } else { + outputLines.push(line) + } + gotLineCont = line.endsWith(lineContinuationChar) & useLineCont + if (line.includes(hereDocDelim) & useHereDoc) + gotHereDoc = !gotHereDoc + } else if (!onlyCopyPromptLines) { + outputLines.push(line) + } else if (copyEmptyLines && line.trim() === '') { + outputLines.push(line) + } + } + + // If no lines with the prompt were found then just use original lines + if (lineGotPrompt.some(v => v === true)) { + textContent = outputLines.join('\n'); + } + + // Remove a trailing newline to avoid auto-running when pasting + if (textContent.endsWith("\n")) { + textContent = textContent.slice(0, -1) + } + return textContent +} diff --git a/_static/default.css b/_static/default.css new file mode 100644 index 000000000..81b936363 --- /dev/null +++ b/_static/default.css @@ -0,0 +1 @@ +@import url("classic.css"); diff --git a/_static/doctools.js b/_static/doctools.js new file mode 100644 index 000000000..4d67807d1 --- /dev/null +++ b/_static/doctools.js @@ -0,0 +1,156 @@ +/* + * doctools.js + * ~~~~~~~~~~~ + * + * Base JavaScript utilities for all Sphinx HTML documentation. + * + * :copyright: Copyright 2007-2024 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ +"use strict"; + +const BLACKLISTED_KEY_CONTROL_ELEMENTS = new Set([ + "TEXTAREA", + "INPUT", + "SELECT", + "BUTTON", +]); + +const _ready = (callback) => { + if (document.readyState !== "loading") { + callback(); + } else { + document.addEventListener("DOMContentLoaded", callback); + } +}; + +/** + * Small JavaScript module for the documentation. + */ +const Documentation = { + init: () => { + Documentation.initDomainIndexTable(); + Documentation.initOnKeyListeners(); + }, + + /** + * i18n support + */ + TRANSLATIONS: {}, + PLURAL_EXPR: (n) => (n === 1 ? 0 : 1), + LOCALE: "unknown", + + // gettext and ngettext don't access this so that the functions + // can safely bound to a different name (_ = Documentation.gettext) + gettext: (string) => { + const translated = Documentation.TRANSLATIONS[string]; + switch (typeof translated) { + case "undefined": + return string; // no translation + case "string": + return translated; // translation exists + default: + return translated[0]; // (singular, plural) translation tuple exists + } + }, + + ngettext: (singular, plural, n) => { + const translated = Documentation.TRANSLATIONS[singular]; + if (typeof translated !== "undefined") + return translated[Documentation.PLURAL_EXPR(n)]; + return n === 1 ? singular : plural; + }, + + addTranslations: (catalog) => { + Object.assign(Documentation.TRANSLATIONS, catalog.messages); + Documentation.PLURAL_EXPR = new Function( + "n", + `return (${catalog.plural_expr})` + ); + Documentation.LOCALE = catalog.locale; + }, + + /** + * helper function to focus on search bar + */ + focusSearchBar: () => { + document.querySelectorAll("input[name=q]")[0]?.focus(); + }, + + /** + * Initialise the domain index toggle buttons + */ + initDomainIndexTable: () => { + const toggler = (el) => { + const idNumber = el.id.substr(7); + const toggledRows = document.querySelectorAll(`tr.cg-${idNumber}`); + if (el.src.substr(-9) === "minus.png") { + el.src = `${el.src.substr(0, el.src.length - 9)}plus.png`; + toggledRows.forEach((el) => (el.style.display = "none")); + } else { + el.src = `${el.src.substr(0, el.src.length - 8)}minus.png`; + toggledRows.forEach((el) => (el.style.display = "")); + } + }; + + const togglerElements = document.querySelectorAll("img.toggler"); + togglerElements.forEach((el) => + el.addEventListener("click", (event) => toggler(event.currentTarget)) + ); + togglerElements.forEach((el) => (el.style.display = "")); + if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) togglerElements.forEach(toggler); + }, + + initOnKeyListeners: () => { + // only install a listener if it is really needed + if ( + !DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS && + !DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS + ) + return; + + document.addEventListener("keydown", (event) => { + // bail for input elements + if (BLACKLISTED_KEY_CONTROL_ELEMENTS.has(document.activeElement.tagName)) return; + // bail with special keys + if (event.altKey || event.ctrlKey || event.metaKey) return; + + if (!event.shiftKey) { + switch (event.key) { + case "ArrowLeft": + if (!DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) break; + + const prevLink = document.querySelector('link[rel="prev"]'); + if (prevLink && prevLink.href) { + window.location.href = prevLink.href; + event.preventDefault(); + } + break; + case "ArrowRight": + if (!DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) break; + + const nextLink = document.querySelector('link[rel="next"]'); + if (nextLink && nextLink.href) { + window.location.href = nextLink.href; + event.preventDefault(); + } + break; + } + } + + // some keyboard layouts may need Shift to get / + switch (event.key) { + case "/": + if (!DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS) break; + Documentation.focusSearchBar(); + event.preventDefault(); + } + }); + }, +}; + +// quick alias for translations +const _ = Documentation.gettext; + +_ready(Documentation.init); diff --git a/_static/documentation_options.js b/_static/documentation_options.js new file mode 100644 index 000000000..44a74bb3c --- /dev/null +++ b/_static/documentation_options.js @@ -0,0 +1,13 @@ +const DOCUMENTATION_OPTIONS = { + VERSION: '2024.2rc0.dev0', + LANGUAGE: 'en', + COLLAPSE_INDEX: false, + BUILDER: 'html', + FILE_SUFFIX: '.html', + LINK_SUFFIX: '.html', + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt', + NAVIGATION_WITH_KEYS: false, + SHOW_SEARCH_SUMMARY: true, + ENABLE_SEARCH_SHORTCUTS: true, +}; \ No newline at end of file diff --git a/_static/favicon.ico b/_static/favicon.ico new file mode 100644 index 000000000..4198a1acf Binary files /dev/null and b/_static/favicon.ico differ diff --git a/_static/file.png b/_static/file.png new file mode 100644 index 000000000..a858a410e Binary files /dev/null and b/_static/file.png differ diff --git a/_static/foldable_toc.css b/_static/foldable_toc.css new file mode 100644 index 000000000..3599fdc11 --- /dev/null +++ b/_static/foldable_toc.css @@ -0,0 +1,99 @@ +div.bodywrapper blockquote { + margin: 0 ; +} + +div.toctree-wrapper ul { + margin: 0 ; + padding-left: 0px ; +} + +div.tune li, div.tune ul { + transition-duration: 0.2s; +} + +div.tune li.toctree-l1 { + padding: 5px 0 0; + list-style-type: none; + font-size: 150% ; + font-family: Arial, sans-serif; + background-color: #f2f2f2; + font-weight: normal; + color: #20435c; + margin-left: 0; + margin-bottom: 1.2em; + font-weight: bold; + } + +div.tune li.toctree-l1 a { + padding: 0 0 0 10px ; + color: #314F64 ; +} + +div.tune li.toctree-l2 { + padding: 0.25em 0 0.25em 0 ; + list-style-type: none; + background-color: #FFFFFF; + font-size: 85% ; + font-weight: normal; +} + +div.tune li.toctree-l2 ul { + padding-left: 40px ; +} + + +div.tune li.toctree-l2:before { + content: attr(data-content) ; + font-size: 85% ; + color: #777 ; + display: inline-block; + width: 10px; +} + +div.tune li.toctree-l3 { + font-size: 75% ; + list-style-type: square; + font-weight: normal; +} + +div.tune li.toctree-l4 { + font-size: 85% ; + list-style-type: circle; + font-weight: normal; +} + +div.preface li.toctree-l1 { + font-weight: bold; + background-color: transparent; + margin-bottom: 0; + margin-left: 0; + margin-top: 10px; + display: inline; +} + +div.preface li.toctree-l2 { + background-color: transparent; + margin-bottom: 0; + margin-left: 1.5em; + display: inline; +} + +div.sidebar { + width: 25ex ; +} + +@media only screen and (max-width: 1080px) and (-webkit-min-device-pixel-ratio: 2.5), (max-width: 70ex) { + div.sidebar { + width: 79%; + padding-left: 5%; + font-size: 80%; + margin-left: auto; + margin-right: 1px; + } +} + +@media (max-width: 1324px) { + div.sphinxsidebar { + display: none; + } +} diff --git a/_static/foldable_toc.js b/_static/foldable_toc.js new file mode 100644 index 000000000..715be2c75 --- /dev/null +++ b/_static/foldable_toc.js @@ -0,0 +1,40 @@ +// Function to make the index toctree foldable +$(function () { + $('.toctree-l2') + .click(function(event){ + if (event.target.tagName.toLowerCase() != "a") { + if ($(this).children('ul').length > 0) { + $(this).attr('data-content', + (!$(this).children('ul').is(':hidden')) ? '\u25ba' : '\u25bc'); + $(this).children('ul').toggle(); + } + return true; //Makes links clickable + } + }) + .mousedown(function(event){ return false; }) //Firefox highlighting fix + .children('ul').hide(); + // Initialize the values + $('li.toctree-l2:not(:has(ul))').attr('data-content', '-'); + $('li.toctree-l2:has(ul)').attr('data-content', '\u25ba'); + $('li.toctree-l2:has(ul)').css('cursor', 'pointer'); + + $('.toctree-l2').hover( + function () { + if ($(this).children('ul').length > 0) { + $(this).css('background-color', '#D0D0D0').children('ul').css('background-color', '#F0F0F0'); + $(this).attr('data-content', + (!$(this).children('ul').is(':hidden')) ? '\u25bc' : '\u25ba'); + } + else { + $(this).css('background-color', '#F9F9F9'); + } + }, + function () { + $(this).css('background-color', 'white').children('ul').css('background-color', 'white'); + if ($(this).children('ul').length > 0) { + $(this).attr('data-content', + (!$(this).children('ul').is(':hidden')) ? '\u25bc' : '\u25ba'); + } + } + ); +}); diff --git a/_static/jupyterlite_badge_logo.svg b/_static/jupyterlite_badge_logo.svg new file mode 100644 index 000000000..5de36d7fd --- /dev/null +++ b/_static/jupyterlite_badge_logo.svg @@ -0,0 +1,3 @@ + + +launchlaunchlitelite \ No newline at end of file diff --git a/_static/language_data.js b/_static/language_data.js new file mode 100644 index 000000000..367b8ed81 --- /dev/null +++ b/_static/language_data.js @@ -0,0 +1,199 @@ +/* + * language_data.js + * ~~~~~~~~~~~~~~~~ + * + * This script contains the language-specific data used by searchtools.js, + * namely the list of stopwords, stemmer, scorer and splitter. + * + * :copyright: Copyright 2007-2024 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +var stopwords = ["a", "and", "are", "as", "at", "be", "but", "by", "for", "if", "in", "into", "is", "it", "near", "no", "not", "of", "on", "or", "such", "that", "the", "their", "then", "there", "these", "they", "this", "to", "was", "will", "with"]; + + +/* Non-minified version is copied as a separate JS file, if available */ + +/** + * Porter Stemmer + */ +var Stemmer = function() { + + var step2list = { + ational: 'ate', + tional: 'tion', + enci: 'ence', + anci: 'ance', + izer: 'ize', + bli: 'ble', + alli: 'al', + entli: 'ent', + eli: 'e', + ousli: 'ous', + ization: 'ize', + ation: 'ate', + ator: 'ate', + alism: 'al', + iveness: 'ive', + fulness: 'ful', + ousness: 'ous', + aliti: 'al', + iviti: 'ive', + biliti: 'ble', + logi: 'log' + }; + + var step3list = { + icate: 'ic', + ative: '', + alize: 'al', + iciti: 'ic', + ical: 'ic', + ful: '', + ness: '' + }; + + var c = "[^aeiou]"; // consonant + var v = "[aeiouy]"; // vowel + var C = c + "[^aeiouy]*"; // consonant sequence + var V = v + "[aeiou]*"; // vowel sequence + + var mgr0 = "^(" + C + ")?" + V + C; // [C]VC... is m>0 + var meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$"; // [C]VC[V] is m=1 + var mgr1 = "^(" + C + ")?" + V + C + V + C; // [C]VCVC... is m>1 + var s_v = "^(" + C + ")?" + v; // vowel in stem + + this.stemWord = function (w) { + var stem; + var suffix; + var firstch; + var origword = w; + + if (w.length < 3) + return w; + + var re; + var re2; + var re3; + var re4; + + firstch = w.substr(0,1); + if (firstch == "y") + w = firstch.toUpperCase() + w.substr(1); + + // Step 1a + re = /^(.+?)(ss|i)es$/; + re2 = /^(.+?)([^s])s$/; + + if (re.test(w)) + w = w.replace(re,"$1$2"); + else if (re2.test(w)) + w = w.replace(re2,"$1$2"); + + // Step 1b + re = /^(.+?)eed$/; + re2 = /^(.+?)(ed|ing)$/; + if (re.test(w)) { + var fp = re.exec(w); + re = new RegExp(mgr0); + if (re.test(fp[1])) { + re = /.$/; + w = w.replace(re,""); + } + } + else if (re2.test(w)) { + var fp = re2.exec(w); + stem = fp[1]; + re2 = new RegExp(s_v); + if (re2.test(stem)) { + w = stem; + re2 = /(at|bl|iz)$/; + re3 = new RegExp("([^aeiouylsz])\\1$"); + re4 = new RegExp("^" + C + v + "[^aeiouwxy]$"); + if (re2.test(w)) + w = w + "e"; + else if (re3.test(w)) { + re = /.$/; + w = w.replace(re,""); + } + else if (re4.test(w)) + w = w + "e"; + } + } + + // Step 1c + re = /^(.+?)y$/; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + re = new RegExp(s_v); + if (re.test(stem)) + w = stem + "i"; + } + + // Step 2 + re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + suffix = fp[2]; + re = new RegExp(mgr0); + if (re.test(stem)) + w = stem + step2list[suffix]; + } + + // Step 3 + re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + suffix = fp[2]; + re = new RegExp(mgr0); + if (re.test(stem)) + w = stem + step3list[suffix]; + } + + // Step 4 + re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/; + re2 = /^(.+?)(s|t)(ion)$/; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + re = new RegExp(mgr1); + if (re.test(stem)) + w = stem; + } + else if (re2.test(w)) { + var fp = re2.exec(w); + stem = fp[1] + fp[2]; + re2 = new RegExp(mgr1); + if (re2.test(stem)) + w = stem; + } + + // Step 5 + re = /^(.+?)e$/; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + re = new RegExp(mgr1); + re2 = new RegExp(meq1); + re3 = new RegExp("^" + C + v + "[^aeiouwxy]$"); + if (re.test(stem) || (re2.test(stem) && !(re3.test(stem)))) + w = stem; + } + re = /ll$/; + re2 = new RegExp(mgr1); + if (re.test(w) && re2.test(w)) { + re = /.$/; + w = w.replace(re,""); + } + + // and turn initial Y back to y + if (firstch == "y") + w = firstch.toLowerCase() + w.substr(1); + return w; + } +} + diff --git a/_static/minus.png b/_static/minus.png new file mode 100644 index 000000000..d96755fda Binary files /dev/null and b/_static/minus.png differ diff --git a/_static/nature.css b/_static/nature.css new file mode 100644 index 000000000..41ebe3f3b --- /dev/null +++ b/_static/nature.css @@ -0,0 +1,1003 @@ +/* + * nature.css_t + * ~~~~~~~~~~~~ + * + * Sphinx stylesheet -- nature theme. + * + * :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ +@import url("basic.css"); +@import url("default.css"); + +body { + font-size: .9em; + line-height: 1.45; + color: #333332; + background-color: white; + -webkit-margin-before: 1em; + -webkit-margin-after: 1em; + -webkit-margin-start: 0px; + -webkit-margin-end: 0px; + margin: 0 0; + font-family: sans-serif; +} + +/**** For mobile device: increase font size on small devices ****/ +@media only screen and (-webkit-min-device-pixel-ratio: 1.5), + only screen and (-o-min-device-pixel-ratio: 15/10), + only screen and (min-resolution: 140dpi) +{ + /* High DPI devices */ + body { + font-size: 150%; + } +} + +/**** End font sizes ****/ + +div.body { + color: #333332; + padding: 0 10px 30px 10px; +} + +div.body li { + line-height: 1.45; +} + +li.horizontal { + display: inline-block; +} + +ul.horizontal li { + display: inline-block; +} + +ul.horizontal li:before { + content: "\2022"; + margin-right: .5ex; + margin-left: 1.5ex; +} + +/* On a horizontal table, if the list item has only one paragraph + child, render that child inline instead of as a paragraph */ +ul.horizontal li p:first-child:nth-last-child(1) { + display: inline-block; +} + +div.body p { + line-height: 1.45; +} + +ul, menu, dir { + display: block; + list-style-type: disc; + -webkit-margin-before: 1em; + -webkit-margin-after: 1em; + -webkit-margin-start: 0px; + -webkit-margin-end: 0px; + -webkit-padding-start: 40px; +} + +/************************ Header *****************************/ + +div.related li { + display: inline-block; +} + +div.related a { + border-radius: 6px; + color: white; + display: inline-block; + border: none; +} + +div.related li.left { + margin-right: .5ex; + position: absolute; + left: -.8ex; + top: .2ex; +} + +/* Give a button-like feeling to the next/previous links */ +div.related li.right a { + font-weight: bold; + border-width: 1px; + /*border: solid; + border-width: 1px;*/ + border-color: #777; + padding: 0px 8px; + background-color: #333; + background-image: linear-gradient(#444, #111); + box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); +} + +div.related a:hover { + background-image: linear-gradient(#777, #444); + text-decoration: none; +} + +div.related li.right a:hover { + background-image: linear-gradient(#666, #333); +} + + +div.related ul { + margin-left: .8ex; +} + +div.related li.left img { + padding: 0ex; +} + +div.related { + background-color: #555; + background-image: linear-gradient(#555, #333); + color: #777; + padding: 2px 0; + border: #777 solid; + border-width: 1px 0px 2px 0px; +} + +div.related li.edit_on_github a { + font-weight: normal; + margin-right: 1em; + color: #DDD; +} + +div.related li.edit_on_github span.tooltip { + display: none; + z-index: 100; +} + +div.related li.edit_on_github:hover span.tooltip { + display: block; + color: white; + position: absolute; + right: 120px; + top: 37px; + padding: 2px 10px; + background-color: #222; + border-radius: 6px; +} + +@media (max-width: 840px) { + li.edit_on_github a { + display: none; + } +} + +@media only screen and (-webkit-min-device-pixel-ratio: 1.5), + only screen and (-o-min-device-pixel-ratio: 15/10), + only screen and (min-resolution: 140dpi) +{ + /* High DPI devices */ + div.related { + font-size: 120%; + padding-top: 1pt; + padding-bottom: 1pt; + line-height: 1.3; + } + + li.edit_on_github a { + display: none; + } +} + + +@media only screen and (max-width: 1080px) and (-webkit-min-device-pixel-ratio: 2.5), + only screen and (max-width: 1080px) and (-o-min-device-pixel-ratio: 25/10), + only screen and (max-width: 1080px) and (min-resolution: 250dpi) +{ + /* High DPI small screen devices, typically mobile phones */ + div.related { + font-size: 140%; + padding-top: 3pt; + padding-bottom: 3pt; + } + + li.edit_on_github a { + display: none; + } + + div.related li.left { + display: none; + } +} + + +/* Hide the footer */ +div.footer { + display: none; +} + +span.hiddenlink { + display: none; + z-index: 100; + background-color: rgb(355, 253, 242); + position: absolute; + left: 4px; + top: 20px; + width: 20ex; + padding: 3px; + border: 1px solid #888; + color: black; + line-height: 100%; +} + +li.left:hover span.hiddenlink { + display: block; +} + +li.transparent:hover span.hiddenlink { + display: none; +} + +/* -- page layout ----------------------------------------------------------- */ + +/* Restrict the width of the body, to avoid very long lines */ +div.body { + max-width: 90ex; + margin-left: auto; + margin-right: auto; + /*border: solid; + border-width: 0px 1px 0px 1px; + border-color: rgb(204, 204, 204);*/ +} + +@media only screen and (max-width: 1080px) and (-webkit-min-device-pixel-ratio: 2.5), + only screen and (max-width: 1080px) and (-o-min-device-pixel-ratio: 25/10), + only screen and (max-width: 1080px) and (min-resolution: 250dpi) +{ + /* Necessary for good layout on Android phones */ + div.body { + max-width: 102ex; + } + + ol.arabic { + padding-left: 5.9ex; + } +} + +/********** The general sidebar **************/ + +div.sphinxsidebarwrapper { + padding: 0px; +} + +div.sphinxsidebar { + width: 300px; + float: none; + position: fixed; + margin-left: 10px; + margin-top: 10px; +} + +div.sphinxsidebarwrapper { + background-color: #F7F7F7; + border: solid 1px #EEE; + padding: 10px 3px 3px 10px; +} + +div.sidebartoc:empty { + display: none +} + +div.sphinxsidebar p { + display: none; +} + +div.sphinxsidebar a { + color: #393333; +} + +div.sphinxsidebar h3 { + color: #393333; + font-size: 110%; +} + +div.sphinxsidebar h3 a { + color: #393333; + font-weight: 600; +} + +img.sidebarlogo { + max-width: 105%; + width: 105%; + margin-top: -10px; + margin-left: -13%; +} + +@media (max-width: 70ex), + only screen and (-webkit-min-device-pixel-ratio: 2.5) +{ + div.sphinxsidebar { + display: none !important; + } + + div.bodywrapper { + margin: 0px; + } +} + +@media (max-width: 1324px) { + div.sphinxsidebar { + margin-top: 0px; + width: 2em; + min-width: 20px; + } + + div.sphinxsidebar:before { + content: "☰"; + display: inline-block; + font-size: 1.5rem; + margin-left: 1.1ex; + margin-top: 1rem; + color: rgba(0, 0, 0, .3); + } + + div.bodywrapper { + margin: 0px; + } + + div.sphinxsidebarwrapper { + display: none; + } + + div.sphinxsidebar:hover { + width: 300px; + z-index: 1000; + } + + div.sphinxsidebar:hover div.sphinxsidebarwrapper { + display: block; + box-shadow: 10px 10px 5px #888888; + } +} + +div.sphinxsidebar ul { + margin: 0px 5px 15px 0px; + font-size: 110%; + padding-left: 2ex; + text-indent: -2.5ex; +} + +div.sphinxsidebar ul ul { + padding-left: 4ex; + text-indent: -4ex; + font-size: 90%; + list-style: none; + margin: 0.5ex 0px 0px -1.7ex; +} + +div.sphinxsidebar ul li a { + +} + +div.sphinxsidebar ul li:only-child a { + display: none; /* Hide level 1 if there is only 1 */ +} + +div.sphinxsidebar ul ul li a, div.sphinxsidebar ul li:only-child ul a { + display: inline; +} + +div.sphinxsidebar ul ul ul { + display: none; /* Hide 3 level down in the contents */ +} + +div.sphinxsidebarwrapper ul ul li.active a { + font-weight: bold; +} + +div.sphinxsidebarwrapper ul ul li.active ul { + display: block; /* Show the active level 3 */ + margin: 0.1ex 0px 0.5ex -2ex; +} + +div.sphinxsidebarwrapper ul ul li.active ul a{ + font-weight: normal; +} + +div.sphinxsidebarwrapper ul ul li.active ul li.active a{ + font-weight: bold; +} + + +div.sphinxsidebarwrapper ul ul li.active ul ul { + display: none; /* Always hide 4 level down */ +} + +/*********************************************/ + + +div.document { + background-color: white; + border: none; +} + +/* bold section titles */ +div.body h1, div.body h2 { + font-weight: bold; +} + +/* more spacing for visual air */ +div.body h1, div.body h2, div.body h3, div.body h4, div.body h5, div.body +h6 { + margin: 20px 0px 20px -20px; + padding: 3px 0px 3px 5px; +} + +/* When the margins disappear */ +@media (max-width: 110ex) { + div.body h1, div.body h2, div.body h3, div.body h4, div.body h5, div.body + h6 { + padding-left: 8px; + } +} + +@media (max-width: 100ex) { + div.body h1, div.body h2, div.body h3, div.body h4, div.body h5, div.body + h6 { + padding-left: 13px; + } +} + +div.body h2 { + margin-top: 65px; +} + +div.body h1 div.section:first-of-kind h2 { + /* Less vertical space for an h2 right after an h1 */ + margin-top: 55px; +} + +/* "div.body > div.section" selects the div.section that is an immediate + * child of div.body */ +div.body > div.section, div.body > div.section > div.section { + /* Necessary to add vertical space after float */ + display: flow-root; +} + + +div.body h3 { + margin-top: 45px; +} + +div.body h2 div.section:first-of-kind h3, div.body hr { + margin-top: 39px; +} + +div.body h4 { + background-color: #FAFAFA; +} + +div.body h1 a.toc-backref:visited, +div.body h1 a.toc-backref, +div.body h2 a.toc-backref:visited, +div.body h2 a.toc-backref, +div.body h3 a.toc-backref:visited, +div.body h3 a.toc-backref, +div.body h4 a.toc-backref:visited, +div.body h4 a.toc-backref { + color: #20435c; +} + +a.headerlink:after { + content: "🔗"; + margin-left: -1.1ex; +} + +h1:hover a.headerlink, h2:hover a.headerlink, +h3:hover a.headerlink, h4:hover a.headerlink { + visibility: hidden; + display: inline-block; +} + +a.headerlink { + display: inline-block; +} + +h1:hover a.headerlink:after, h2:hover a.headerlink:after, +h3:hover a.headerlink:after, h4:hover a.headerlink:after { + visibility: visible; +} + + +a.headerlink { + color: #8a0d0d; + float: right; + font-weight: normal; +} + +a.headerlink:hover { + color: #f21515; +} + +div.body hr.docutils { + border-style: solid; + color: gray; +} + +/* clear both after section titles */ +div.body h1, div.body h2, div.body h3, div.body h4, hr { + clear: both; +} + +/* Page title should have a lot of space */ +div.body h1 { + text-align: center; + font-size: 200%; + border: none; + background-color: transparent; + padding: 10px; +} +/* pre */ +div.body pre { + font-weight: 500; + font-family: "Droid Sans Mono", "Liberation Mono", Courier, monospace; + color: black; + margin-top: 3px; + /* The following lines ensure that no horizontal scrolling is + * necessary to see code lines */ + overflow: visible; + text-overflow: ellipsis; + background-color: hsl(210, 100%, 98%); + border-color: #B8BEC3; + /* Break words to avoid too long lines */ + -webkit-hyphens: auto; + -moz-hyphens: auto; + -ms-hyphens: auto; + hyphens: auto; +} + +div.highlight-default { + /* Useful when a float overlays part of the code block */ + display: flow-root; +} + +div.highlight { + /* To anchor the copybutton */ + position: relative; +} + +div.highlight pre a { + color: #111; + text-decoration:underline; +} + +div.highlight pre { + /* Hack to have indented line wraps */ + white-space: pre-wrap; + padding-left: 3.6em; + text-indent: -3.5em; +} + +/* Hack to have indented line wraps */ +div.highlight pre div.newline { + margin-right: -4.5em; + padding-left: 1em; + display: inline-block; + visibility: hidden; +} + +/* Disable the above hack on android phone, as font scaling breaks it */ +@media only screen and (-webkit-min-device-pixel-ratio: 1.5), + only screen and (-o-min-device-pixel-ratio: 15/10), + only screen and (min-resolution: 140dpi) + { + div.highlight pre { + padding-left: 0pt; + text-indent: 0pt; + } + + div.highlight pre div.newline { + margin-right: 0pt; + padding-left: 0pt; + } +} + +/* On non text-highlighted code, break all words */ +div.body pre { + word-break: break-all; +} + +div.body pre span { + word-break: normal; +} + +/* Line wrap after "()[]" (that are set in a span.p by pygment) and + * '.,=' (that are set in a span.o by pygment) */ +div.body pre span.o:after, div.body pre span.p:after{ + -ms-word-break: break-all; + word-break: break-all; + + /* Non standard for webkit */ + word-break: break-word; + +-webkit-hyphens: auto; + -moz-hyphens: auto; + -ms-hyphens: auto; + hyphens: auto; + + content: ""; + display: inline-block; +} + + +/* On *results* of commands (tagged as "go") force word wrapping */ +div.highlight pre span.go { + word-break: break-word; +} + + +div.highlight:hover span.copybutton { + background-color: #3F556B; +} + +div.highlight:hover span.copybutton:hover { + background-color: #20252B; +} + + +@media (min-width: 1060px) { + div.highlight:hover span.copybutton:after{ + background: #3F556B; + border-radius: 5px; + color: white; + content: attr(title); + left: 110%; + padding: 5px 15px; + position: absolute; + z-index: 98; + width: 140px; + top: -10px; + } +} + +div.body p { + margin-bottom : .3em; + margin-top : .7em; +} + +div.body ul, div.body ol, div.body blockquote { + margin-top : .3em; +} + +div.body a.reference.external { + overflow-wrap: break-word; +} + +div.body img { + /* Required for clean overlap in left or right align */ + position: relative; + z-index: 10; + /* Avoid being larger than the page (for small-screen devices) */ + max-width: 100%; +} + +/* Center figures that are larger than 100% of the figure */ +div.body a.image-reference div.figure { + margin-left: -200px; + margin-right: -200px; + text-align: center; + } + +/* alternating colors in table rows */ +table.docutils tr:nth-child(even) { + background-color: #F3F3FF; +} +table.docutils tr:nth-child(odd) { + background-color: #FFFFEE; +} + +table.docutils tr { + border-style: solid none solid none; + border-width: 1px 0 1px 0; + border-color: #AAAAAA; +} + +table.docutils { + margin-bottom: 10px; +} + +table.field-list { + width: 100%; +} + +/* Replicate coloring for definition lists */ +/* Sphinx now uses these instead of tables for field lists */ +/* https://www.sphinx-doc.org/en/master/usage/restructuredtext/field-lists.html */ +dl.field-list { + border-top: solid 1px #AAAAAA; +} +dt.field-odd { + border-bottom: solid 1px #AAAAAA; + padding: 0.3em; +} +dt.field-even { + border-bottom: solid 1px #AAAAAA; + padding: 0.3em; +} +dd.field-odd { + background-color: #FFFFEE; + border-bottom: solid 1px #AAAAAA; + padding-right: 0.75em; + padding-bottom: 0.3em; +} +dd.field-even { + background-color: #F3F3FF; + border-bottom: solid 1px #AAAAAA; + padding-right: 0.75em; + padding-bottom: 0.3em; +} + +/* Boxes */ +aside.topic, div.admonition { + border-radius: 4px 4px 4px 4px; + display: flow-root; +} + +div.sidebar { + padding-top: 2px; + width: initial; + max-width: 40%; +} + +aside.topic { + background-color: #F9F9F9; + margin-top: 15px; + padding-top: 3px; +} + +div.seealso { + margin-top: 15px; + margin-bottom: 20px; +} + +/* special colors for exercises */ +div.green { + background-color: #e4ffe4; + border: 1px solid #6f6; +} + + +/* Content div */ +nav.contents { + background-color: #FFFFF6; + border-color: #c0ac5c; +} + +nav.contents li { + list-style-type: none; + font-size: 110% ; + font-weight: bold; +} + +@media (max-width: 70ex) { + nav.contents ul { + padding-left: 2.5ex; + } +} + +nav.contents p { + margin-bottom : 0px; + margin-top : 0px; +} + +nav.contents ul { + margin-bottom : 4px; + margin-top : 0px; +} + +nav.contents li li { + list-style-type: none; + list-style-type: square; + font-size: 90% ; + font-weight: normal; +} + +div.body p.topic-title, div.body p.sidebar-title { + margin-bottom: 3px; +} + +/* toctree */ +div.toctree-wrapper ul { + padding-left: 4px; +} + +li.toctree-l1 { + padding: 0 0 0.5em 0 ; + list-style-type: none; + font-size: 110% ; + font-weight: bold; + } + +li.toctree-l1 ul { + padding-left: 40px ; +} + +li.toctree-l2 { + font-size: 80% ; + list-style-type: square; + font-weight: normal; + } + + +li.toctree-l3 { + font-size: 90% ; + list-style-type: circle; + font-weight: normal; + } + +table.hlist td { + width: 50%; + vertical-align: top; +} + + +table.hlist ul { + margin-top: 0em; +} + + +/************************ Admonitions ************************/ + +div.admonition p { + text-align: left; + margin: 0; + padding: 0; +} +div.admonition ul { + padding-top: 0px; + margin-top: 0px; +} +div.admonition .first { + font-weight: bold; +} + +/* hint */ +div.hint { + line-height: 1.5em; + margin: 0; + padding: 3px 5px; + width: 260px; + border: 1px solid #cccccc; + background-color: #FFD; +} + +div.tip { + font-size: 95%; + padding: 2ex; + border: 1px solid; + background: #EEFFEE; +} + +.div.tip p.admonition-title { + display: none; +} + +div.collapsed { + color: #CCC; + font-size: 90% ; +} + +div.collapsed > :not(.summary) { + display: none !important; +} + +div.collapsed p.summary { + display: inline; +} + +p.summary > img { + padding-right: 5px; +} + +.transparent img { + opacity: .5; +} + +.collapsed a { + color: #CCC; +} + +div.tip p.summary { + display: inline; +} + +/* sidebar */ +div.sidebar ul { + padding-top: 0px; + margin-top: 0px; + margin-bottom: 7px; +} +div.sidebar .first { + margin-bottom: 5px; +} + +div.sidebar { + margin-right: 2px; + z-index: 50; +} + +/* Stop highlight blocks from clearing divs, so that we + can float result images next to code snippets. */ + +pre, div[class*="highlight-"] { + clear: none; +} + +/* Suppress floats on small screens */ +@media only screen and (max-width: 1080px) and (-webkit-min-device-pixel-ratio: 2.5), (max-width: 70ex) { + div.sidebar { + float: none; + width: 95%; + padding-top: 8px; + } +} + +@media only screen and (max-width: 1080px) and (-webkit-min-device-pixel-ratio: 2.5), (max-width: 60ex) { + img.align-right { + float: none; + } + + img.align-left { + float: none; + } +} + +/* Warnings: replace the admonition name by a warning sign */ +div.warning .first { + display: none; + /*overflow: hidden;*/ + margin-right: -2ex; + margin-left: -2ex; + height: auto; +} + +div.warning:before { + content: "🚨"; + margin-right: .5ex; + text-rendering: auto; +} + +/************* Code examples *****************/ +ul.horizontal img { + max-width: 100% ; +} + +/* Disable as it prevents "font boosting", used by chrome to set font + * size on small devices such as phones */ +/*div.max-height pre { + overflow-y: scroll; + overflow-x: scroll; + max-height: 30em; +}*/ + +/************* For sphinx-gallery ************/ +p.sphx-glr-script-out, div.body p.sphx-glr-script-out { + margin-left: -2.3em; + margin-top: -1em; +} + +div.sphx-glr-script-out div.highlight { + margin-left: 0em; +} + +/* Undo clever wrapping of code in sphinx output */ +div.sphx-glr-script-out div.highlight pre div.newline { + margin-right: 0em; + padding-left: 0em; +} + +div.sphx-glr-script-out div.highlight pre { + text-indent: 0em; +} +.gp, .go { + -webkit-user-select: none; /* Chrome, Opera, Safari */ + -moz-user-select: none; /* Firefox 2+ */ + -ms-user-select: none; /* IE 10+ */ + user-select: none; /* Standard syntax */ +} \ No newline at end of file diff --git a/_static/no_image.png b/_static/no_image.png new file mode 100644 index 000000000..8c2d48d5d Binary files /dev/null and b/_static/no_image.png differ diff --git a/_static/plus.png b/_static/plus.png new file mode 100644 index 000000000..7107cec93 Binary files /dev/null and b/_static/plus.png differ diff --git a/_static/pygments.css b/_static/pygments.css new file mode 100644 index 000000000..0d49244ed --- /dev/null +++ b/_static/pygments.css @@ -0,0 +1,75 @@ +pre { line-height: 125%; } +td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; } +span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; } +td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; } +span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; } +.highlight .hll { background-color: #ffffcc } +.highlight { background: #eeffcc; } +.highlight .c { color: #408090; font-style: italic } /* Comment */ +.highlight .err { border: 1px solid #FF0000 } /* Error */ +.highlight .k { color: #007020; font-weight: bold } /* Keyword */ +.highlight .o { color: #666666 } /* Operator */ +.highlight .ch { color: #408090; font-style: italic } /* Comment.Hashbang */ +.highlight .cm { color: #408090; font-style: italic } /* Comment.Multiline */ +.highlight .cp { color: #007020 } /* Comment.Preproc */ +.highlight .cpf { color: #408090; font-style: italic } /* Comment.PreprocFile */ +.highlight .c1 { color: #408090; font-style: italic } /* Comment.Single */ +.highlight .cs { color: #408090; background-color: #fff0f0 } /* Comment.Special */ +.highlight .gd { color: #A00000 } /* Generic.Deleted */ +.highlight .ge { font-style: italic } /* Generic.Emph */ +.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */ +.highlight .gr { color: #FF0000 } /* Generic.Error */ +.highlight .gh { color: #000080; font-weight: bold } /* Generic.Heading */ +.highlight .gi { color: #00A000 } /* Generic.Inserted */ +.highlight .go { color: #333333 } /* Generic.Output */ +.highlight .gp { color: #c65d09; font-weight: bold } /* Generic.Prompt */ +.highlight .gs { font-weight: bold } /* Generic.Strong */ +.highlight .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ +.highlight .gt { color: #0044DD } /* Generic.Traceback */ +.highlight .kc { color: #007020; font-weight: bold } /* Keyword.Constant */ +.highlight .kd { color: #007020; font-weight: bold } /* Keyword.Declaration */ +.highlight .kn { color: #007020; font-weight: bold } /* Keyword.Namespace */ +.highlight .kp { color: #007020 } /* Keyword.Pseudo */ +.highlight .kr { color: #007020; font-weight: bold } /* Keyword.Reserved */ +.highlight .kt { color: #902000 } /* Keyword.Type */ +.highlight .m { color: #208050 } /* Literal.Number */ +.highlight .s { color: #4070a0 } /* Literal.String */ +.highlight .na { color: #4070a0 } /* Name.Attribute */ +.highlight .nb { color: #007020 } /* Name.Builtin */ +.highlight .nc { color: #0e84b5; font-weight: bold } /* Name.Class */ +.highlight .no { color: #60add5 } /* Name.Constant */ +.highlight .nd { color: #555555; font-weight: bold } /* Name.Decorator */ +.highlight .ni { color: #d55537; font-weight: bold } /* Name.Entity */ +.highlight .ne { color: #007020 } /* Name.Exception */ +.highlight .nf { color: #06287e } /* Name.Function */ +.highlight .nl { color: #002070; font-weight: bold } /* Name.Label */ +.highlight .nn { color: #0e84b5; font-weight: bold } /* Name.Namespace */ +.highlight .nt { color: #062873; font-weight: bold } /* Name.Tag */ +.highlight .nv { color: #bb60d5 } /* Name.Variable */ +.highlight .ow { color: #007020; font-weight: bold } /* Operator.Word */ +.highlight .w { color: #bbbbbb } /* Text.Whitespace */ +.highlight .mb { color: #208050 } /* Literal.Number.Bin */ +.highlight .mf { color: #208050 } /* Literal.Number.Float */ +.highlight .mh { color: #208050 } /* Literal.Number.Hex */ +.highlight .mi { color: #208050 } /* Literal.Number.Integer */ +.highlight .mo { color: #208050 } /* Literal.Number.Oct */ +.highlight .sa { color: #4070a0 } /* Literal.String.Affix */ +.highlight .sb { color: #4070a0 } /* Literal.String.Backtick */ +.highlight .sc { color: #4070a0 } /* Literal.String.Char */ +.highlight .dl { color: #4070a0 } /* Literal.String.Delimiter */ +.highlight .sd { color: #4070a0; font-style: italic } /* Literal.String.Doc */ +.highlight .s2 { color: #4070a0 } /* Literal.String.Double */ +.highlight .se { color: #4070a0; font-weight: bold } /* Literal.String.Escape */ +.highlight .sh { color: #4070a0 } /* Literal.String.Heredoc */ +.highlight .si { color: #70a0d0; font-style: italic } /* Literal.String.Interpol */ +.highlight .sx { color: #c65d09 } /* Literal.String.Other */ +.highlight .sr { color: #235388 } /* Literal.String.Regex */ +.highlight .s1 { color: #4070a0 } /* Literal.String.Single */ +.highlight .ss { color: #517918 } /* Literal.String.Symbol */ +.highlight .bp { color: #007020 } /* Name.Builtin.Pseudo */ +.highlight .fm { color: #06287e } /* Name.Function.Magic */ +.highlight .vc { color: #bb60d5 } /* Name.Variable.Class */ +.highlight .vg { color: #bb60d5 } /* Name.Variable.Global */ +.highlight .vi { color: #bb60d5 } /* Name.Variable.Instance */ +.highlight .vm { color: #bb60d5 } /* Name.Variable.Magic */ +.highlight .il { color: #208050 } /* Literal.Number.Integer.Long */ \ No newline at end of file diff --git a/_static/scroll_highlight_toc.js b/_static/scroll_highlight_toc.js new file mode 100644 index 000000000..e403339b4 --- /dev/null +++ b/_static/scroll_highlight_toc.js @@ -0,0 +1,31 @@ +// Highlight the table of content as we scroll + +$( document ).ready(function () { + sections = {}, + i = 0, + url = document.URL.replace(/#.*$/, ""), + current_section = 0; + + // Grab positions of our sections + $('.headerlink').each(function(){ + sections[this.href.replace(url, '')] = $(this).offset().top - 50; + }); + + $(window).scroll(function(event) { + var pos = $(window).scrollTop(); + + // Highlight the current section + $('a.internal').parent().removeClass('active'); + for(i in sections){ + if(sections[i] > pos){ + break; + }; + if($('a.internal[href$="' + i + '"]').is(':visible')){ + current_section = i; + }; + } + $('a.internal[href$="' + current_section + '"]').parent().addClass('active'); + $('a.internal[href$="' + current_section + '"]').parent().parent().parent().addClass('active'); + $('a.internal[href$="' + current_section + '"]').parent().parent().parent().parent().parent().addClass('active'); + }); +}); diff --git a/_static/searchtools.js b/_static/searchtools.js new file mode 100644 index 000000000..b08d58c9b --- /dev/null +++ b/_static/searchtools.js @@ -0,0 +1,620 @@ +/* + * searchtools.js + * ~~~~~~~~~~~~~~~~ + * + * Sphinx JavaScript utilities for the full-text search. + * + * :copyright: Copyright 2007-2024 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ +"use strict"; + +/** + * Simple result scoring code. + */ +if (typeof Scorer === "undefined") { + var Scorer = { + // Implement the following function to further tweak the score for each result + // The function takes a result array [docname, title, anchor, descr, score, filename] + // and returns the new score. + /* + score: result => { + const [docname, title, anchor, descr, score, filename] = result + return score + }, + */ + + // query matches the full name of an object + objNameMatch: 11, + // or matches in the last dotted part of the object name + objPartialMatch: 6, + // Additive scores depending on the priority of the object + objPrio: { + 0: 15, // used to be importantResults + 1: 5, // used to be objectResults + 2: -5, // used to be unimportantResults + }, + // Used when the priority is not in the mapping. + objPrioDefault: 0, + + // query found in title + title: 15, + partialTitle: 7, + // query found in terms + term: 5, + partialTerm: 2, + }; +} + +const _removeChildren = (element) => { + while (element && element.lastChild) element.removeChild(element.lastChild); +}; + +/** + * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping + */ +const _escapeRegExp = (string) => + string.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string + +const _displayItem = (item, searchTerms, highlightTerms) => { + const docBuilder = DOCUMENTATION_OPTIONS.BUILDER; + const docFileSuffix = DOCUMENTATION_OPTIONS.FILE_SUFFIX; + const docLinkSuffix = DOCUMENTATION_OPTIONS.LINK_SUFFIX; + const showSearchSummary = DOCUMENTATION_OPTIONS.SHOW_SEARCH_SUMMARY; + const contentRoot = document.documentElement.dataset.content_root; + + const [docName, title, anchor, descr, score, _filename] = item; + + let listItem = document.createElement("li"); + let requestUrl; + let linkUrl; + if (docBuilder === "dirhtml") { + // dirhtml builder + let dirname = docName + "/"; + if (dirname.match(/\/index\/$/)) + dirname = dirname.substring(0, dirname.length - 6); + else if (dirname === "index/") dirname = ""; + requestUrl = contentRoot + dirname; + linkUrl = requestUrl; + } else { + // normal html builders + requestUrl = contentRoot + docName + docFileSuffix; + linkUrl = docName + docLinkSuffix; + } + let linkEl = listItem.appendChild(document.createElement("a")); + linkEl.href = linkUrl + anchor; + linkEl.dataset.score = score; + linkEl.innerHTML = title; + if (descr) { + listItem.appendChild(document.createElement("span")).innerHTML = + " (" + descr + ")"; + // highlight search terms in the description + if (SPHINX_HIGHLIGHT_ENABLED) // set in sphinx_highlight.js + highlightTerms.forEach((term) => _highlightText(listItem, term, "highlighted")); + } + else if (showSearchSummary) + fetch(requestUrl) + .then((responseData) => responseData.text()) + .then((data) => { + if (data) + listItem.appendChild( + Search.makeSearchSummary(data, searchTerms, anchor) + ); + // highlight search terms in the summary + if (SPHINX_HIGHLIGHT_ENABLED) // set in sphinx_highlight.js + highlightTerms.forEach((term) => _highlightText(listItem, term, "highlighted")); + }); + Search.output.appendChild(listItem); +}; +const _finishSearch = (resultCount) => { + Search.stopPulse(); + Search.title.innerText = _("Search Results"); + if (!resultCount) + Search.status.innerText = Documentation.gettext( + "Your search did not match any documents. Please make sure that all words are spelled correctly and that you've selected enough categories." + ); + else + Search.status.innerText = _( + "Search finished, found ${resultCount} page(s) matching the search query." + ).replace('${resultCount}', resultCount); +}; +const _displayNextItem = ( + results, + resultCount, + searchTerms, + highlightTerms, +) => { + // results left, load the summary and display it + // this is intended to be dynamic (don't sub resultsCount) + if (results.length) { + _displayItem(results.pop(), searchTerms, highlightTerms); + setTimeout( + () => _displayNextItem(results, resultCount, searchTerms, highlightTerms), + 5 + ); + } + // search finished, update title and status message + else _finishSearch(resultCount); +}; +// Helper function used by query() to order search results. +// Each input is an array of [docname, title, anchor, descr, score, filename]. +// Order the results by score (in opposite order of appearance, since the +// `_displayNextItem` function uses pop() to retrieve items) and then alphabetically. +const _orderResultsByScoreThenName = (a, b) => { + const leftScore = a[4]; + const rightScore = b[4]; + if (leftScore === rightScore) { + // same score: sort alphabetically + const leftTitle = a[1].toLowerCase(); + const rightTitle = b[1].toLowerCase(); + if (leftTitle === rightTitle) return 0; + return leftTitle > rightTitle ? -1 : 1; // inverted is intentional + } + return leftScore > rightScore ? 1 : -1; +}; + +/** + * Default splitQuery function. Can be overridden in ``sphinx.search`` with a + * custom function per language. + * + * The regular expression works by splitting the string on consecutive characters + * that are not Unicode letters, numbers, underscores, or emoji characters. + * This is the same as ``\W+`` in Python, preserving the surrogate pair area. + */ +if (typeof splitQuery === "undefined") { + var splitQuery = (query) => query + .split(/[^\p{Letter}\p{Number}_\p{Emoji_Presentation}]+/gu) + .filter(term => term) // remove remaining empty strings +} + +/** + * Search Module + */ +const Search = { + _index: null, + _queued_query: null, + _pulse_status: -1, + + htmlToText: (htmlString, anchor) => { + const htmlElement = new DOMParser().parseFromString(htmlString, 'text/html'); + for (const removalQuery of [".headerlink", "script", "style"]) { + htmlElement.querySelectorAll(removalQuery).forEach((el) => { el.remove() }); + } + if (anchor) { + const anchorContent = htmlElement.querySelector(`[role="main"] ${anchor}`); + if (anchorContent) return anchorContent.textContent; + + console.warn( + `Anchored content block not found. Sphinx search tries to obtain it via DOM query '[role=main] ${anchor}'. Check your theme or template.` + ); + } + + // if anchor not specified or not found, fall back to main content + const docContent = htmlElement.querySelector('[role="main"]'); + if (docContent) return docContent.textContent; + + console.warn( + "Content block not found. Sphinx search tries to obtain it via DOM query '[role=main]'. Check your theme or template." + ); + return ""; + }, + + init: () => { + const query = new URLSearchParams(window.location.search).get("q"); + document + .querySelectorAll('input[name="q"]') + .forEach((el) => (el.value = query)); + if (query) Search.performSearch(query); + }, + + loadIndex: (url) => + (document.body.appendChild(document.createElement("script")).src = url), + + setIndex: (index) => { + Search._index = index; + if (Search._queued_query !== null) { + const query = Search._queued_query; + Search._queued_query = null; + Search.query(query); + } + }, + + hasIndex: () => Search._index !== null, + + deferQuery: (query) => (Search._queued_query = query), + + stopPulse: () => (Search._pulse_status = -1), + + startPulse: () => { + if (Search._pulse_status >= 0) return; + + const pulse = () => { + Search._pulse_status = (Search._pulse_status + 1) % 4; + Search.dots.innerText = ".".repeat(Search._pulse_status); + if (Search._pulse_status >= 0) window.setTimeout(pulse, 500); + }; + pulse(); + }, + + /** + * perform a search for something (or wait until index is loaded) + */ + performSearch: (query) => { + // create the required interface elements + const searchText = document.createElement("h2"); + searchText.textContent = _("Searching"); + const searchSummary = document.createElement("p"); + searchSummary.classList.add("search-summary"); + searchSummary.innerText = ""; + const searchList = document.createElement("ul"); + searchList.classList.add("search"); + + const out = document.getElementById("search-results"); + Search.title = out.appendChild(searchText); + Search.dots = Search.title.appendChild(document.createElement("span")); + Search.status = out.appendChild(searchSummary); + Search.output = out.appendChild(searchList); + + const searchProgress = document.getElementById("search-progress"); + // Some themes don't use the search progress node + if (searchProgress) { + searchProgress.innerText = _("Preparing search..."); + } + Search.startPulse(); + + // index already loaded, the browser was quick! + if (Search.hasIndex()) Search.query(query); + else Search.deferQuery(query); + }, + + _parseQuery: (query) => { + // stem the search terms and add them to the correct list + const stemmer = new Stemmer(); + const searchTerms = new Set(); + const excludedTerms = new Set(); + const highlightTerms = new Set(); + const objectTerms = new Set(splitQuery(query.toLowerCase().trim())); + splitQuery(query.trim()).forEach((queryTerm) => { + const queryTermLower = queryTerm.toLowerCase(); + + // maybe skip this "word" + // stopwords array is from language_data.js + if ( + stopwords.indexOf(queryTermLower) !== -1 || + queryTerm.match(/^\d+$/) + ) + return; + + // stem the word + let word = stemmer.stemWord(queryTermLower); + // select the correct list + if (word[0] === "-") excludedTerms.add(word.substr(1)); + else { + searchTerms.add(word); + highlightTerms.add(queryTermLower); + } + }); + + if (SPHINX_HIGHLIGHT_ENABLED) { // set in sphinx_highlight.js + localStorage.setItem("sphinx_highlight_terms", [...highlightTerms].join(" ")) + } + + // console.debug("SEARCH: searching for:"); + // console.info("required: ", [...searchTerms]); + // console.info("excluded: ", [...excludedTerms]); + + return [query, searchTerms, excludedTerms, highlightTerms, objectTerms]; + }, + + /** + * execute search (requires search index to be loaded) + */ + _performSearch: (query, searchTerms, excludedTerms, highlightTerms, objectTerms) => { + const filenames = Search._index.filenames; + const docNames = Search._index.docnames; + const titles = Search._index.titles; + const allTitles = Search._index.alltitles; + const indexEntries = Search._index.indexentries; + + // Collect multiple result groups to be sorted separately and then ordered. + // Each is an array of [docname, title, anchor, descr, score, filename]. + const normalResults = []; + const nonMainIndexResults = []; + + _removeChildren(document.getElementById("search-progress")); + + const queryLower = query.toLowerCase().trim(); + for (const [title, foundTitles] of Object.entries(allTitles)) { + if (title.toLowerCase().trim().includes(queryLower) && (queryLower.length >= title.length/2)) { + for (const [file, id] of foundTitles) { + const score = Math.round(Scorer.title * queryLower.length / title.length); + const boost = titles[file] === title ? 1 : 0; // add a boost for document titles + normalResults.push([ + docNames[file], + titles[file] !== title ? `${titles[file]} > ${title}` : title, + id !== null ? "#" + id : "", + null, + score + boost, + filenames[file], + ]); + } + } + } + + // search for explicit entries in index directives + for (const [entry, foundEntries] of Object.entries(indexEntries)) { + if (entry.includes(queryLower) && (queryLower.length >= entry.length/2)) { + for (const [file, id, isMain] of foundEntries) { + const score = Math.round(100 * queryLower.length / entry.length); + const result = [ + docNames[file], + titles[file], + id ? "#" + id : "", + null, + score, + filenames[file], + ]; + if (isMain) { + normalResults.push(result); + } else { + nonMainIndexResults.push(result); + } + } + } + } + + // lookup as object + objectTerms.forEach((term) => + normalResults.push(...Search.performObjectSearch(term, objectTerms)) + ); + + // lookup as search terms in fulltext + normalResults.push(...Search.performTermsSearch(searchTerms, excludedTerms)); + + // let the scorer override scores with a custom scoring function + if (Scorer.score) { + normalResults.forEach((item) => (item[4] = Scorer.score(item))); + nonMainIndexResults.forEach((item) => (item[4] = Scorer.score(item))); + } + + // Sort each group of results by score and then alphabetically by name. + normalResults.sort(_orderResultsByScoreThenName); + nonMainIndexResults.sort(_orderResultsByScoreThenName); + + // Combine the result groups in (reverse) order. + // Non-main index entries are typically arbitrary cross-references, + // so display them after other results. + let results = [...nonMainIndexResults, ...normalResults]; + + // remove duplicate search results + // note the reversing of results, so that in the case of duplicates, the highest-scoring entry is kept + let seen = new Set(); + results = results.reverse().reduce((acc, result) => { + let resultStr = result.slice(0, 4).concat([result[5]]).map(v => String(v)).join(','); + if (!seen.has(resultStr)) { + acc.push(result); + seen.add(resultStr); + } + return acc; + }, []); + + return results.reverse(); + }, + + query: (query) => { + const [searchQuery, searchTerms, excludedTerms, highlightTerms, objectTerms] = Search._parseQuery(query); + const results = Search._performSearch(searchQuery, searchTerms, excludedTerms, highlightTerms, objectTerms); + + // for debugging + //Search.lastresults = results.slice(); // a copy + // console.info("search results:", Search.lastresults); + + // print the results + _displayNextItem(results, results.length, searchTerms, highlightTerms); + }, + + /** + * search for object names + */ + performObjectSearch: (object, objectTerms) => { + const filenames = Search._index.filenames; + const docNames = Search._index.docnames; + const objects = Search._index.objects; + const objNames = Search._index.objnames; + const titles = Search._index.titles; + + const results = []; + + const objectSearchCallback = (prefix, match) => { + const name = match[4] + const fullname = (prefix ? prefix + "." : "") + name; + const fullnameLower = fullname.toLowerCase(); + if (fullnameLower.indexOf(object) < 0) return; + + let score = 0; + const parts = fullnameLower.split("."); + + // check for different match types: exact matches of full name or + // "last name" (i.e. last dotted part) + if (fullnameLower === object || parts.slice(-1)[0] === object) + score += Scorer.objNameMatch; + else if (parts.slice(-1)[0].indexOf(object) > -1) + score += Scorer.objPartialMatch; // matches in last name + + const objName = objNames[match[1]][2]; + const title = titles[match[0]]; + + // If more than one term searched for, we require other words to be + // found in the name/title/description + const otherTerms = new Set(objectTerms); + otherTerms.delete(object); + if (otherTerms.size > 0) { + const haystack = `${prefix} ${name} ${objName} ${title}`.toLowerCase(); + if ( + [...otherTerms].some((otherTerm) => haystack.indexOf(otherTerm) < 0) + ) + return; + } + + let anchor = match[3]; + if (anchor === "") anchor = fullname; + else if (anchor === "-") anchor = objNames[match[1]][1] + "-" + fullname; + + const descr = objName + _(", in ") + title; + + // add custom score for some objects according to scorer + if (Scorer.objPrio.hasOwnProperty(match[2])) + score += Scorer.objPrio[match[2]]; + else score += Scorer.objPrioDefault; + + results.push([ + docNames[match[0]], + fullname, + "#" + anchor, + descr, + score, + filenames[match[0]], + ]); + }; + Object.keys(objects).forEach((prefix) => + objects[prefix].forEach((array) => + objectSearchCallback(prefix, array) + ) + ); + return results; + }, + + /** + * search for full-text terms in the index + */ + performTermsSearch: (searchTerms, excludedTerms) => { + // prepare search + const terms = Search._index.terms; + const titleTerms = Search._index.titleterms; + const filenames = Search._index.filenames; + const docNames = Search._index.docnames; + const titles = Search._index.titles; + + const scoreMap = new Map(); + const fileMap = new Map(); + + // perform the search on the required terms + searchTerms.forEach((word) => { + const files = []; + const arr = [ + { files: terms[word], score: Scorer.term }, + { files: titleTerms[word], score: Scorer.title }, + ]; + // add support for partial matches + if (word.length > 2) { + const escapedWord = _escapeRegExp(word); + if (!terms.hasOwnProperty(word)) { + Object.keys(terms).forEach((term) => { + if (term.match(escapedWord)) + arr.push({ files: terms[term], score: Scorer.partialTerm }); + }); + } + if (!titleTerms.hasOwnProperty(word)) { + Object.keys(titleTerms).forEach((term) => { + if (term.match(escapedWord)) + arr.push({ files: titleTerms[term], score: Scorer.partialTitle }); + }); + } + } + + // no match but word was a required one + if (arr.every((record) => record.files === undefined)) return; + + // found search word in contents + arr.forEach((record) => { + if (record.files === undefined) return; + + let recordFiles = record.files; + if (recordFiles.length === undefined) recordFiles = [recordFiles]; + files.push(...recordFiles); + + // set score for the word in each file + recordFiles.forEach((file) => { + if (!scoreMap.has(file)) scoreMap.set(file, {}); + scoreMap.get(file)[word] = record.score; + }); + }); + + // create the mapping + files.forEach((file) => { + if (!fileMap.has(file)) fileMap.set(file, [word]); + else if (fileMap.get(file).indexOf(word) === -1) fileMap.get(file).push(word); + }); + }); + + // now check if the files don't contain excluded terms + const results = []; + for (const [file, wordList] of fileMap) { + // check if all requirements are matched + + // as search terms with length < 3 are discarded + const filteredTermCount = [...searchTerms].filter( + (term) => term.length > 2 + ).length; + if ( + wordList.length !== searchTerms.size && + wordList.length !== filteredTermCount + ) + continue; + + // ensure that none of the excluded terms is in the search result + if ( + [...excludedTerms].some( + (term) => + terms[term] === file || + titleTerms[term] === file || + (terms[term] || []).includes(file) || + (titleTerms[term] || []).includes(file) + ) + ) + break; + + // select one (max) score for the file. + const score = Math.max(...wordList.map((w) => scoreMap.get(file)[w])); + // add result to the result list + results.push([ + docNames[file], + titles[file], + "", + null, + score, + filenames[file], + ]); + } + return results; + }, + + /** + * helper function to return a node containing the + * search summary for a given text. keywords is a list + * of stemmed words. + */ + makeSearchSummary: (htmlText, keywords, anchor) => { + const text = Search.htmlToText(htmlText, anchor); + if (text === "") return null; + + const textLower = text.toLowerCase(); + const actualStartPosition = [...keywords] + .map((k) => textLower.indexOf(k.toLowerCase())) + .filter((i) => i > -1) + .slice(-1)[0]; + const startWithContext = Math.max(actualStartPosition - 120, 0); + + const top = startWithContext === 0 ? "" : "..."; + const tail = startWithContext + 240 < text.length ? "..." : ""; + + let summary = document.createElement("p"); + summary.classList.add("context"); + summary.textContent = top + text.substr(startWithContext, 240).trim() + tail; + + return summary; + }, +}; + +_ready(Search.init); diff --git a/_static/sg_gallery-binder.css b/_static/sg_gallery-binder.css new file mode 100644 index 000000000..420005d22 --- /dev/null +++ b/_static/sg_gallery-binder.css @@ -0,0 +1,11 @@ +/* CSS for binder integration */ + +div.binder-badge { + margin: 1em auto; + vertical-align: middle; +} + +div.lite-badge { + margin: 1em auto; + vertical-align: middle; +} diff --git a/_static/sg_gallery-dataframe.css b/_static/sg_gallery-dataframe.css new file mode 100644 index 000000000..fac74c43b --- /dev/null +++ b/_static/sg_gallery-dataframe.css @@ -0,0 +1,47 @@ +/* Pandas dataframe css */ +/* Taken from: https://github.com/spatialaudio/nbsphinx/blob/fb3ba670fc1ba5f54d4c487573dbc1b4ecf7e9ff/src/nbsphinx.py#L587-L619 */ +html[data-theme="light"] { + --sg-text-color: #000; + --sg-tr-odd-color: #f5f5f5; + --sg-tr-hover-color: rgba(66, 165, 245, 0.2); +} +html[data-theme="dark"] { + --sg-text-color: #fff; + --sg-tr-odd-color: #373737; + --sg-tr-hover-color: rgba(30, 81, 122, 0.2); +} + +table.dataframe { + border: none !important; + border-collapse: collapse; + border-spacing: 0; + border-color: transparent; + color: var(--sg-text-color); + font-size: 12px; + table-layout: fixed; + width: auto; +} +table.dataframe thead { + border-bottom: 1px solid var(--sg-text-color); + vertical-align: bottom; +} +table.dataframe tr, +table.dataframe th, +table.dataframe td { + text-align: right; + vertical-align: middle; + padding: 0.5em 0.5em; + line-height: normal; + white-space: normal; + max-width: none; + border: none; +} +table.dataframe th { + font-weight: bold; +} +table.dataframe tbody tr:nth-child(odd) { + background: var(--sg-tr-odd-color); +} +table.dataframe tbody tr:hover { + background: var(--sg-tr-hover-color); +} diff --git a/_static/sg_gallery-rendered-html.css b/_static/sg_gallery-rendered-html.css new file mode 100644 index 000000000..93dc2ffb0 --- /dev/null +++ b/_static/sg_gallery-rendered-html.css @@ -0,0 +1,224 @@ +/* Adapted from notebook/static/style/style.min.css */ +html[data-theme="light"] { + --sg-text-color: #000; + --sg-background-color: #ffffff; + --sg-code-background-color: #eff0f1; + --sg-tr-hover-color: rgba(66, 165, 245, 0.2); + --sg-tr-odd-color: #f5f5f5; +} +html[data-theme="dark"] { + --sg-text-color: #fff; + --sg-background-color: #121212; + --sg-code-background-color: #2f2f30; + --sg-tr-hover-color: rgba(66, 165, 245, 0.2); + --sg-tr-odd-color: #1f1f1f; +} + +.rendered_html { + color: var(--sg-text-color); + /* any extras will just be numbers: */ +} +.rendered_html em { + font-style: italic; +} +.rendered_html strong { + font-weight: bold; +} +.rendered_html u { + text-decoration: underline; +} +.rendered_html :link { + text-decoration: underline; +} +.rendered_html :visited { + text-decoration: underline; +} +.rendered_html h1 { + font-size: 185.7%; + margin: 1.08em 0 0 0; + font-weight: bold; + line-height: 1.0; +} +.rendered_html h2 { + font-size: 157.1%; + margin: 1.27em 0 0 0; + font-weight: bold; + line-height: 1.0; +} +.rendered_html h3 { + font-size: 128.6%; + margin: 1.55em 0 0 0; + font-weight: bold; + line-height: 1.0; +} +.rendered_html h4 { + font-size: 100%; + margin: 2em 0 0 0; + font-weight: bold; + line-height: 1.0; +} +.rendered_html h5 { + font-size: 100%; + margin: 2em 0 0 0; + font-weight: bold; + line-height: 1.0; + font-style: italic; +} +.rendered_html h6 { + font-size: 100%; + margin: 2em 0 0 0; + font-weight: bold; + line-height: 1.0; + font-style: italic; +} +.rendered_html h1:first-child { + margin-top: 0.538em; +} +.rendered_html h2:first-child { + margin-top: 0.636em; +} +.rendered_html h3:first-child { + margin-top: 0.777em; +} +.rendered_html h4:first-child { + margin-top: 1em; +} +.rendered_html h5:first-child { + margin-top: 1em; +} +.rendered_html h6:first-child { + margin-top: 1em; +} +.rendered_html ul:not(.list-inline), +.rendered_html ol:not(.list-inline) { + padding-left: 2em; +} +.rendered_html ul { + list-style: disc; +} +.rendered_html ul ul { + list-style: square; + margin-top: 0; +} +.rendered_html ul ul ul { + list-style: circle; +} +.rendered_html ol { + list-style: decimal; +} +.rendered_html ol ol { + list-style: upper-alpha; + margin-top: 0; +} +.rendered_html ol ol ol { + list-style: lower-alpha; +} +.rendered_html ol ol ol ol { + list-style: lower-roman; +} +.rendered_html ol ol ol ol ol { + list-style: decimal; +} +.rendered_html * + ul { + margin-top: 1em; +} +.rendered_html * + ol { + margin-top: 1em; +} +.rendered_html hr { + color: var(--sg-text-color); + background-color: var(--sg-text-color); +} +.rendered_html pre { + margin: 1em 2em; + padding: 0px; + background-color: var(--sg-background-color); +} +.rendered_html code { + background-color: var(--sg-code-background-color); +} +.rendered_html p code { + padding: 1px 5px; +} +.rendered_html pre code { + background-color: var(--sg-background-color); +} +.rendered_html pre, +.rendered_html code { + border: 0; + color: var(--sg-text-color); + font-size: 100%; +} +.rendered_html blockquote { + margin: 1em 2em; +} +.rendered_html table { + margin-left: auto; + margin-right: auto; + border: none; + border-collapse: collapse; + border-spacing: 0; + color: var(--sg-text-color); + font-size: 12px; + table-layout: fixed; +} +.rendered_html thead { + border-bottom: 1px solid var(--sg-text-color); + vertical-align: bottom; +} +.rendered_html tr, +.rendered_html th, +.rendered_html td { + text-align: right; + vertical-align: middle; + padding: 0.5em 0.5em; + line-height: normal; + white-space: normal; + max-width: none; + border: none; +} +.rendered_html th { + font-weight: bold; +} +.rendered_html tbody tr:nth-child(odd) { + background: var(--sg-tr-odd-color); +} +.rendered_html tbody tr:hover { + color: var(--sg-text-color); + background: var(--sg-tr-hover-color); +} +.rendered_html * + table { + margin-top: 1em; +} +.rendered_html p { + text-align: left; +} +.rendered_html * + p { + margin-top: 1em; +} +.rendered_html img { + display: block; + margin-left: auto; + margin-right: auto; +} +.rendered_html * + img { + margin-top: 1em; +} +.rendered_html img, +.rendered_html svg { + max-width: 100%; + height: auto; +} +.rendered_html img.unconfined, +.rendered_html svg.unconfined { + max-width: none; +} +.rendered_html .alert { + margin-bottom: initial; +} +.rendered_html * + .alert { + margin-top: 1em; +} +[dir="rtl"] .rendered_html p { + text-align: right; +} diff --git a/_static/sg_gallery.css b/_static/sg_gallery.css new file mode 100644 index 000000000..9bcd33c8a --- /dev/null +++ b/_static/sg_gallery.css @@ -0,0 +1,367 @@ +/* +Sphinx-Gallery has compatible CSS to fix default sphinx themes +Tested for Sphinx 1.3.1 for all themes: default, alabaster, sphinxdoc, +scrolls, agogo, traditional, nature, haiku, pyramid +Tested for Read the Docs theme 0.1.7 */ + +/* Define light colors */ +:root, html[data-theme="light"], body[data-theme="light"]{ + --sg-tooltip-foreground: black; + --sg-tooltip-background: rgba(250, 250, 250, 0.9); + --sg-tooltip-border: #ccc transparent; + --sg-thumb-box-shadow-color: #6c757d40; + --sg-thumb-hover-border: #0069d9; + --sg-script-out: #888; + --sg-script-pre: #fafae2; + --sg-pytb-foreground: #000; + --sg-pytb-background: #ffe4e4; + --sg-pytb-border-color: #f66; + --sg-download-a-background-color: #ffc; + --sg-download-a-background-image: linear-gradient(to bottom, #ffc, #d5d57e); + --sg-download-a-border-color: 1px solid #c2c22d; + --sg-download-a-color: #000; + --sg-download-a-hover-background-color: #d5d57e; + --sg-download-a-hover-box-shadow-1: rgba(255, 255, 255, 0.1); + --sg-download-a-hover-box-shadow-2: rgba(0, 0, 0, 0.25); +} +@media(prefers-color-scheme: light) { + :root[data-theme="auto"], html[data-theme="auto"], body[data-theme="auto"] { + --sg-tooltip-foreground: black; + --sg-tooltip-background: rgba(250, 250, 250, 0.9); + --sg-tooltip-border: #ccc transparent; + --sg-thumb-box-shadow-color: #6c757d40; + --sg-thumb-hover-border: #0069d9; + --sg-script-out: #888; + --sg-script-pre: #fafae2; + --sg-pytb-foreground: #000; + --sg-pytb-background: #ffe4e4; + --sg-pytb-border-color: #f66; + --sg-download-a-background-color: #ffc; + --sg-download-a-background-image: linear-gradient(to bottom, #ffc, #d5d57e); + --sg-download-a-border-color: 1px solid #c2c22d; + --sg-download-a-color: #000; + --sg-download-a-hover-background-color: #d5d57e; + --sg-download-a-hover-box-shadow-1: rgba(255, 255, 255, 0.1); + --sg-download-a-hover-box-shadow-2: rgba(0, 0, 0, 0.25); + } +} + +html[data-theme="dark"], body[data-theme="dark"] { + --sg-tooltip-foreground: white; + --sg-tooltip-background: rgba(10, 10, 10, 0.9); + --sg-tooltip-border: #333 transparent; + --sg-thumb-box-shadow-color: #79848d40; + --sg-thumb-hover-border: #003975; + --sg-script-out: rgb(179, 179, 179); + --sg-script-pre: #2e2e22; + --sg-pytb-foreground: #fff; + --sg-pytb-background: #1b1717; + --sg-pytb-border-color: #622; + --sg-download-a-background-color: #443; + --sg-download-a-background-image: linear-gradient(to bottom, #443, #221); + --sg-download-a-border-color: 1px solid #3a3a0d; + --sg-download-a-color: #fff; + --sg-download-a-hover-background-color: #616135; + --sg-download-a-hover-box-shadow-1: rgba(0, 0, 0, 0.1); + --sg-download-a-hover-box-shadow-2: rgba(255, 255, 255, 0.25); +} +@media(prefers-color-scheme: dark){ + html[data-theme="auto"], body[data-theme="auto"] { + --sg-tooltip-foreground: white; + --sg-tooltip-background: rgba(10, 10, 10, 0.9); + --sg-tooltip-border: #333 transparent; + --sg-thumb-box-shadow-color: #79848d40; + --sg-thumb-hover-border: #003975; + --sg-script-out: rgb(179, 179, 179); + --sg-script-pre: #2e2e22; + --sg-pytb-foreground: #fff; + --sg-pytb-background: #1b1717; + --sg-pytb-border-color: #622; + --sg-download-a-background-color: #443; + --sg-download-a-background-image: linear-gradient(to bottom, #443, #221); + --sg-download-a-border-color: 1px solid #3a3a0d; + --sg-download-a-color: #fff; + --sg-download-a-hover-background-color: #616135; + --sg-download-a-hover-box-shadow-1: rgba(0, 0, 0, 0.1); + --sg-download-a-hover-box-shadow-2: rgba(255, 255, 255, 0.25); + } +} + +.sphx-glr-thumbnails { + width: 100%; + margin: 0px 0px 20px 0px; + + /* align thumbnails on a grid */ + justify-content: space-between; + display: grid; + /* each grid column should be at least 160px (this will determine + the actual number of columns) and then take as much of the + remaining width as possible */ + grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); + gap: 15px; +} +.sphx-glr-thumbnails .toctree-wrapper { + /* hide empty toctree divs added to the DOM + by sphinx even though the toctree is hidden + (they would fill grid places with empty divs) */ + display: none; +} +.sphx-glr-thumbcontainer { + background: transparent; + -moz-border-radius: 5px; + -webkit-border-radius: 5px; + border-radius: 5px; + box-shadow: 0 0 10px var(--sg-thumb-box-shadow-color); + + /* useful to absolutely position link in div */ + position: relative; + + /* thumbnail width should include padding and borders + and take all available space */ + box-sizing: border-box; + width: 100%; + padding: 10px; + border: 1px solid transparent; + + /* align content in thumbnail */ + display: flex; + flex-direction: column; + align-items: center; + gap: 7px; +} +.sphx-glr-thumbcontainer p { + position: absolute; + top: 0; + left: 0; +} +.sphx-glr-thumbcontainer p, +.sphx-glr-thumbcontainer p a { + /* link should cover the whole thumbnail div */ + width: 100%; + height: 100%; +} +.sphx-glr-thumbcontainer p a span { + /* text within link should be masked + (we are just interested in the href) */ + display: none; +} +.sphx-glr-thumbcontainer:hover { + border: 1px solid; + border-color: var(--sg-thumb-hover-border); + cursor: pointer; +} +.sphx-glr-thumbcontainer a.internal { + bottom: 0; + display: block; + left: 0; + box-sizing: border-box; + padding: 150px 10px 0; + position: absolute; + right: 0; + top: 0; +} +/* Next one is to avoid Sphinx traditional theme to cover all the +thumbnail with its default link Background color */ +.sphx-glr-thumbcontainer a.internal:hover { + background-color: transparent; +} + +.sphx-glr-thumbcontainer p { + margin: 0 0 0.1em 0; +} +.sphx-glr-thumbcontainer .figure { + margin: 10px; + width: 160px; +} +.sphx-glr-thumbcontainer img { + display: inline; + max-height: 112px; + max-width: 160px; +} + +.sphx-glr-thumbcontainer[tooltip]::before { + content: ""; + position: absolute; + pointer-events: none; + top: 0; + left: 0; + width: 100%; + height: 100%; + z-index: 97; + background-color: var(--sg-tooltip-background); + backdrop-filter: blur(3px); + opacity: 0; + transition: opacity 0.3s; +} + +.sphx-glr-thumbcontainer[tooltip]:hover::before { + opacity: 1; +} + +.sphx-glr-thumbcontainer[tooltip]:hover::after { + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + color: var(--sg-tooltip-foreground); + content: attr(tooltip); + padding: 10px 10px 5px; + z-index: 98; + width: 100%; + max-height: 100%; + position: absolute; + pointer-events: none; + top: 0; + box-sizing: border-box; + overflow: hidden; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 6; +} + +.sphx-glr-script-out { + color: var(--sg-script-out); + display: flex; + gap: 0.5em; +} +.sphx-glr-script-out::before { + content: "Out:"; + /* These numbers come from the pre style in the pydata sphinx theme. This + * turns out to match perfectly on the rtd theme, but be a bit too low for + * the pydata sphinx theme. As I could not find a dimension to use that was + * scaled the same way, I just picked one option that worked pretty close for + * both. */ + line-height: 1.4; + padding-top: 10px; +} +.sphx-glr-script-out .highlight { + background-color: transparent; + /* These options make the div expand... */ + flex-grow: 1; + /* ... but also keep it from overflowing its flex container. */ + overflow: auto; +} +.sphx-glr-script-out .highlight pre { + background-color: var(--sg-script-pre); + border: 0; + max-height: 30em; + overflow: auto; + padding-left: 1ex; + /* This margin is necessary in the pydata sphinx theme because pre has a box + * shadow which would be clipped by the overflow:auto in the parent div + * above. */ + margin: 2px; + word-break: break-word; +} +.sphx-glr-script-out + p { + margin-top: 1.8em; +} +blockquote.sphx-glr-script-out { + margin-left: 0pt; +} +.sphx-glr-script-out.highlight-pytb .highlight pre { + color: var(--sg-pytb-foreground); + background-color: var(--sg-pytb-background); + border: 1px solid var(--sg-pytb-border-color); + margin-top: 10px; + padding: 7px; +} + +div.sphx-glr-footer { + text-align: center; +} + +div.sphx-glr-download { + margin: 1em auto; + vertical-align: middle; +} + +div.sphx-glr-download a { + background-color: var(--sg-download-a-background-color); + background-image: var(--sg-download-a-background-image); + border-radius: 4px; + border: 1px solid var(--sg-download-a-border-color); + color: var(--sg-download-a-color); + display: inline-block; + font-weight: bold; + padding: 1ex; + text-align: center; +} + +div.sphx-glr-download code.download { + display: inline-block; + white-space: normal; + word-break: normal; + overflow-wrap: break-word; + /* border and background are given by the enclosing 'a' */ + border: none; + background: none; +} + +div.sphx-glr-download a:hover { + box-shadow: inset 0 1px 0 var(--sg-download-a-hover-box-shadow-1), 0 1px 5px var(--sg-download-a-hover-box-shadow-2); + text-decoration: none; + background-image: none; + background-color: var(--sg-download-a-hover-background-color); +} + +div.sphx-glr-sidebar-item img { + max-height: 20px; +} + +.sphx-glr-example-title:target::before { + display: block; + content: ""; + margin-top: -50px; + height: 50px; + visibility: hidden; +} + +ul.sphx-glr-horizontal { + list-style: none; + padding: 0; +} +ul.sphx-glr-horizontal li { + display: inline; +} +ul.sphx-glr-horizontal img { + height: auto !important; +} + +.sphx-glr-single-img { + margin: auto; + display: block; + max-width: 100%; +} + +.sphx-glr-multi-img { + max-width: 42%; + height: auto; +} + +div.sphx-glr-animation { + margin: auto; + display: block; + max-width: 100%; +} +div.sphx-glr-animation .animation { + display: block; +} + +p.sphx-glr-signature a.reference.external { + -moz-border-radius: 5px; + -webkit-border-radius: 5px; + border-radius: 5px; + padding: 3px; + font-size: 75%; + text-align: right; + margin-left: auto; + display: table; +} + +.sphx-glr-clear { + clear: both; +} + +a.sphx-glr-backref-instance { + text-decoration: none; +} diff --git a/_static/sidebar.js b/_static/sidebar.js new file mode 100644 index 000000000..f28c20689 --- /dev/null +++ b/_static/sidebar.js @@ -0,0 +1,70 @@ +/* + * sidebar.js + * ~~~~~~~~~~ + * + * This script makes the Sphinx sidebar collapsible. + * + * .sphinxsidebar contains .sphinxsidebarwrapper. This script adds + * in .sphixsidebar, after .sphinxsidebarwrapper, the #sidebarbutton + * used to collapse and expand the sidebar. + * + * When the sidebar is collapsed the .sphinxsidebarwrapper is hidden + * and the width of the sidebar and the margin-left of the document + * are decreased. When the sidebar is expanded the opposite happens. + * This script saves a per-browser/per-session cookie used to + * remember the position of the sidebar among the pages. + * Once the browser is closed the cookie is deleted and the position + * reset to the default (expanded). + * + * :copyright: Copyright 2007-2024 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +const initialiseSidebar = () => { + + + + + // global elements used by the functions. + const bodyWrapper = document.getElementsByClassName("bodywrapper")[0] + const sidebar = document.getElementsByClassName("sphinxsidebar")[0] + const sidebarWrapper = document.getElementsByClassName('sphinxsidebarwrapper')[0] + const sidebarButton = document.getElementById("sidebarbutton") + const sidebarArrow = sidebarButton.querySelector('span') + + // for some reason, the document has no sidebar; do not run into errors + if (typeof sidebar === "undefined") return; + + const flipArrow = element => element.innerText = (element.innerText === "»") ? "«" : "»" + + const collapse_sidebar = () => { + bodyWrapper.style.marginLeft = ".8em"; + sidebar.style.width = ".8em" + sidebarWrapper.style.display = "none" + flipArrow(sidebarArrow) + sidebarButton.title = _('Expand sidebar') + window.localStorage.setItem("sidebar", "collapsed") + } + + const expand_sidebar = () => { + bodyWrapper.style.marginLeft = "" + sidebar.style.removeProperty("width") + sidebarWrapper.style.display = "" + flipArrow(sidebarArrow) + sidebarButton.title = _('Collapse sidebar') + window.localStorage.setItem("sidebar", "expanded") + } + + sidebarButton.addEventListener("click", () => { + (sidebarWrapper.style.display === "none") ? expand_sidebar() : collapse_sidebar() + }) + + if (!window.localStorage.getItem("sidebar")) return + const value = window.localStorage.getItem("sidebar") + if (value === "collapsed") collapse_sidebar(); + else if (value === "expanded") expand_sidebar(); +} + +if (document.readyState !== "loading") initialiseSidebar() +else document.addEventListener("DOMContentLoaded", initialiseSidebar) \ No newline at end of file diff --git a/_static/sphinx_highlight.js b/_static/sphinx_highlight.js new file mode 100644 index 000000000..8a96c69a1 --- /dev/null +++ b/_static/sphinx_highlight.js @@ -0,0 +1,154 @@ +/* Highlighting utilities for Sphinx HTML documentation. */ +"use strict"; + +const SPHINX_HIGHLIGHT_ENABLED = true + +/** + * highlight a given string on a node by wrapping it in + * span elements with the given class name. + */ +const _highlight = (node, addItems, text, className) => { + if (node.nodeType === Node.TEXT_NODE) { + const val = node.nodeValue; + const parent = node.parentNode; + const pos = val.toLowerCase().indexOf(text); + if ( + pos >= 0 && + !parent.classList.contains(className) && + !parent.classList.contains("nohighlight") + ) { + let span; + + const closestNode = parent.closest("body, svg, foreignObject"); + const isInSVG = closestNode && closestNode.matches("svg"); + if (isInSVG) { + span = document.createElementNS("http://www.w3.org/2000/svg", "tspan"); + } else { + span = document.createElement("span"); + span.classList.add(className); + } + + span.appendChild(document.createTextNode(val.substr(pos, text.length))); + const rest = document.createTextNode(val.substr(pos + text.length)); + parent.insertBefore( + span, + parent.insertBefore( + rest, + node.nextSibling + ) + ); + node.nodeValue = val.substr(0, pos); + /* There may be more occurrences of search term in this node. So call this + * function recursively on the remaining fragment. + */ + _highlight(rest, addItems, text, className); + + if (isInSVG) { + const rect = document.createElementNS( + "http://www.w3.org/2000/svg", + "rect" + ); + const bbox = parent.getBBox(); + rect.x.baseVal.value = bbox.x; + rect.y.baseVal.value = bbox.y; + rect.width.baseVal.value = bbox.width; + rect.height.baseVal.value = bbox.height; + rect.setAttribute("class", className); + addItems.push({ parent: parent, target: rect }); + } + } + } else if (node.matches && !node.matches("button, select, textarea")) { + node.childNodes.forEach((el) => _highlight(el, addItems, text, className)); + } +}; +const _highlightText = (thisNode, text, className) => { + let addItems = []; + _highlight(thisNode, addItems, text, className); + addItems.forEach((obj) => + obj.parent.insertAdjacentElement("beforebegin", obj.target) + ); +}; + +/** + * Small JavaScript module for the documentation. + */ +const SphinxHighlight = { + + /** + * highlight the search words provided in localstorage in the text + */ + highlightSearchWords: () => { + if (!SPHINX_HIGHLIGHT_ENABLED) return; // bail if no highlight + + // get and clear terms from localstorage + const url = new URL(window.location); + const highlight = + localStorage.getItem("sphinx_highlight_terms") + || url.searchParams.get("highlight") + || ""; + localStorage.removeItem("sphinx_highlight_terms") + url.searchParams.delete("highlight"); + window.history.replaceState({}, "", url); + + // get individual terms from highlight string + const terms = highlight.toLowerCase().split(/\s+/).filter(x => x); + if (terms.length === 0) return; // nothing to do + + // There should never be more than one element matching "div.body" + const divBody = document.querySelectorAll("div.body"); + const body = divBody.length ? divBody[0] : document.querySelector("body"); + window.setTimeout(() => { + terms.forEach((term) => _highlightText(body, term, "highlighted")); + }, 10); + + const searchBox = document.getElementById("searchbox"); + if (searchBox === null) return; + searchBox.appendChild( + document + .createRange() + .createContextualFragment( + '" + ) + ); + }, + + /** + * helper function to hide the search marks again + */ + hideSearchWords: () => { + document + .querySelectorAll("#searchbox .highlight-link") + .forEach((el) => el.remove()); + document + .querySelectorAll("span.highlighted") + .forEach((el) => el.classList.remove("highlighted")); + localStorage.removeItem("sphinx_highlight_terms") + }, + + initEscapeListener: () => { + // only install a listener if it is really needed + if (!DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS) return; + + document.addEventListener("keydown", (event) => { + // bail for input elements + if (BLACKLISTED_KEY_CONTROL_ELEMENTS.has(document.activeElement.tagName)) return; + // bail with special keys + if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return; + if (DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS && (event.key === "Escape")) { + SphinxHighlight.hideSearchWords(); + event.preventDefault(); + } + }); + }, +}; + +_ready(() => { + /* Do not call highlightSearchWords() when we are on the search page. + * It will highlight words from the *previous* search query. + */ + if (typeof Search === "undefined") SphinxHighlight.highlightSearchWords(); + SphinxHighlight.initEscapeListener(); +}); diff --git a/about.html b/about.html new file mode 100644 index 000000000..66954fd38 --- /dev/null +++ b/about.html @@ -0,0 +1,200 @@ + + + + + + + + 4. About the Scientific Python Lectures — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +

+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/advanced_numpy/auto_examples/index.html b/advanced/advanced_numpy/auto_examples/index.html new file mode 100644 index 000000000..40c333671 --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/index.html @@ -0,0 +1,189 @@ + + + + + + + + Examples for the advanced NumPy chapter — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ + + + \ No newline at end of file diff --git a/advanced/advanced_numpy/auto_examples/plot_maskedstats.html b/advanced/advanced_numpy/auto_examples/plot_maskedstats.html new file mode 100644 index 000000000..10dde58c1 --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/plot_maskedstats.html @@ -0,0 +1,207 @@ + + + + + + + + Example: Masked statistics — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Example: Masked statistics

+

Plot a masked statistics

+plot maskedstats
import numpy as np
+
import matplotlib.pyplot as plt +
+
data = np.loadtxt("../../../../data/populations.txt") +
populations = np.ma.masked_array(data[:, 1:]) # type: ignore[var-annotated] +
year = data[:, 0] +
+
bad_years = ((year >= 1903) & (year <= 1910)) | ((year >= 1917) & (year <= 1918)) +
populations[bad_years, 0] = np.ma.masked +
populations[bad_years, 1] = np.ma.masked +
+
plt.plot(year, populations, "o-") +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.062 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/advanced_numpy/auto_examples/sg_execution_times.html b/advanced/advanced_numpy/auto_examples/sg_execution_times.html new file mode 100644 index 000000000..af8a9d59c --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/sg_execution_times.html @@ -0,0 +1,206 @@ + + + + + + + + Computation times — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Computation times

+

00:00.062 total execution time for 1 file from advanced/advanced_numpy/auto_examples:

+
+ + + + + +++++ + + + + + + + + + + + + +

Example

Time

Mem (MB)

Example: Masked statistics (plot_maskedstats.py)

00:00.062

0.0

+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/advanced_numpy/index.html b/advanced/advanced_numpy/index.html new file mode 100644 index 000000000..7aa1295a7 --- /dev/null +++ b/advanced/advanced_numpy/index.html @@ -0,0 +1,2169 @@ + + + + + + + + 2.2. Advanced NumPy — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

2.2. Advanced NumPy

+

Author: Pauli Virtanen

+

NumPy is at the base of Python’s scientific stack of tools. Its purpose +to implement efficient operations on many items in a block of memory. +Understanding how it works in detail helps in making efficient use of its +flexibility, taking useful shortcuts.

+

This section covers:

+
    +
  • Anatomy of NumPy arrays, and its consequences. Tips and +tricks.

  • +
  • Universal functions: what, why, and what to do if you want +a new one.

  • +
  • Integration with other tools: NumPy offers several ways to +wrap any data in an ndarray, without unnecessary copies.

  • +
  • Recently added features, and what’s in them: PEP +3118 buffers, generalized ufuncs, …

  • +
+ + +
+

Tip

+

In this section, NumPy will be imported as follows:

+
>>> import numpy as np
+
+
+
+
+

2.2.1. Life of ndarray

+
+

2.2.1.1. It’s…

+

ndarray =

+
+

block of memory + indexing scheme + data type descriptor

+
    +
  • raw data

  • +
  • how to locate an element

  • +
  • how to interpret an element

  • +
+
+../../_images/threefundamental.png +
typedef struct PyArrayObject {
+
PyObject_HEAD +
+
/* Block of memory */ +
char *data; +
+
/* Data type descriptor */ +
PyArray_Descr *descr; +
+
/* Indexing scheme */ +
int nd; +
npy_intp *dimensions; +
npy_intp *strides; +
+
/* Other stuff */ +
PyObject *base; +
int flags; +
PyObject *weakreflist; +
} PyArrayObject; +
+
+
+
+

2.2.1.2. Block of memory

+
>>> x = np.array([1, 2, 3], dtype=np.int32)
+
>>> x.data +
<... at ...> +
>>> bytes(x.data) +
b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00' +
+
+

Memory address of the data:

+
>>> x.__array_interface__['data'][0] 
+
64803824 +
+
+

The whole __array_interface__:

+
>>> x.__array_interface__
+
{'data': (..., False), 'strides': None, 'descr': [('', '<i4')], 'typestr': '<i4', 'shape': (3,), 'version': 3} +
+
+

Reminder: two ndarrays may share the same memory:

+
>>> x = np.array([1, 2, 3, 4])
+
>>> y = x[:-1] +
>>> x[0] = 9 +
>>> y +
array([9, 2, 3]) +
+
+

Memory does not need to be owned by an ndarray:

+
>>> x = b'1234'
+
+
+

x is a string (in Python 3 a bytes), we can represent its data as an +array of ints:

+
>>> y = np.frombuffer(x, dtype=np.int8)
+
>>> y.data +
<... at ...> +
>>> y.base is x +
True +
+
>>> y.flags +
C_CONTIGUOUS : True +
F_CONTIGUOUS : True +
OWNDATA : False +
WRITEABLE : False +
ALIGNED : True +
WRITEBACKIFCOPY : False +
+
+

The owndata and writeable flags indicate status of the memory +block.

+
+

See also

+

array interface

+
+
+
+

2.2.1.3. Data types

+
+

The descriptor

+

dtype describes a single item in the array:

+ ++++ + + + + + + + + + + + + + + + + + +

type

scalar type of the data, one of:

+

int8, int16, float64, et al. (fixed size)

+

str, unicode, void (flexible size)

+

itemsize

size of the data block

byteorder

byte order: big-endian > / little-endian < / not applicable |

fields

sub-dtypes, if it’s a structured data type

shape

shape of the array, if it’s a sub-array

+
>>> np.dtype(int).type
+
<class 'numpy.int64'> +
>>> np.dtype(int).itemsize +
8 +
>>> np.dtype(int).byteorder +
'=' +
+
+
+
+

Example: reading .wav files

+

The .wav file header:

+ ++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

chunk_id

"RIFF"

chunk_size

4-byte unsigned little-endian integer

format

"WAVE"

fmt_id

"fmt "

fmt_size

4-byte unsigned little-endian integer

audio_fmt

2-byte unsigned little-endian integer

num_channels

2-byte unsigned little-endian integer

sample_rate

4-byte unsigned little-endian integer

byte_rate

4-byte unsigned little-endian integer

block_align

2-byte unsigned little-endian integer

bits_per_sample

2-byte unsigned little-endian integer

data_id

"data"

data_size

4-byte unsigned little-endian integer

+
    +
  • 44-byte block of raw data (in the beginning of the file)

  • +
  • … followed by data_size bytes of actual sound data.

  • +
+

The .wav file header as a NumPy structured data type:

+
>>> wav_header_dtype = np.dtype([
+
... ("chunk_id", (bytes, 4)), # flexible-sized scalar type, item size 4 +
... ("chunk_size", "<u4"), # little-endian unsigned 32-bit integer +
... ("format", "S4"), # 4-byte string +
... ("fmt_id", "S4"), +
... ("fmt_size", "<u4"), +
... ("audio_fmt", "<u2"), # +
... ("num_channels", "<u2"), # .. more of the same ... +
... ("sample_rate", "<u4"), # +
... ("byte_rate", "<u4"), +
... ("block_align", "<u2"), +
... ("bits_per_sample", "<u2"), +
... ("data_id", ("S1", (2, 2))), # sub-array, just for fun! +
... ("data_size", "u4"), +
... # +
... # the sound data itself cannot be represented here: +
... # it does not have a fixed size +
... ]) +
+
+
+

See also

+

wavreader.py

+
+
>>> wav_header_dtype['format']
+
dtype('S4') +
>>> wav_header_dtype.fields +
mappingproxy({'chunk_id': (dtype('S4'), 0), 'chunk_size': (dtype('uint32'), 4), 'format': (dtype('S4'), 8), 'fmt_id': (dtype('S4'), 12), 'fmt_size': (dtype('uint32'), 16), 'audio_fmt': (dtype('uint16'), 20), 'num_channels': (dtype('uint16'), 22), 'sample_rate': (dtype('uint32'), 24), 'byte_rate': (dtype('uint32'), 28), 'block_align': (dtype('uint16'), 32), 'bits_per_sample': (dtype('uint16'), 34), 'data_id': (dtype(('S1', (2, 2))), 36), 'data_size': (dtype('uint32'), 40)}) +
>>> wav_header_dtype.fields['format'] +
(dtype('S4'), 8) +
+
+
    +
  • The first element is the sub-dtype in the structured data, corresponding +to the name format

  • +
  • The second one is its offset (in bytes) from the beginning of the item

  • +
+ +
>>> f = open('data/test.wav', 'r')
+
>>> wav_header = np.fromfile(f, dtype=wav_header_dtype, count=1) +
>>> f.close() +
>>> print(wav_header) +
[ ('RIFF', 17402L, 'WAVE', 'fmt ', 16L, 1, 1, 16000L, 32000L, 2, 16, [['d', 'a'], ['t', 'a']], 17366L)] +
>>> wav_header['sample_rate'] +
array([16000], dtype=uint32) +
+
+

Let’s try accessing the sub-array:

+
>>> wav_header['data_id']  
+
array([[['d', 'a'], +
['t', 'a']]], +
dtype='|S1') +
>>> wav_header.shape +
(1,) +
>>> wav_header['data_id'].shape +
(1, 2, 2) +
+
+

When accessing sub-arrays, the dimensions get added to the end!

+
+

Note

+

There are existing modules such as wavfile, audiolab, +etc. for loading sound data…

+
+
+
+

Casting and re-interpretation/views

+

casting

+
+
    +
  • on assignment

  • +
  • on array construction

  • +
  • on arithmetic

  • +
  • etc.

  • +
  • and manually: .astype(dtype)

  • +
+
+

data re-interpretation

+
+
    +
  • manually: .view(dtype)

  • +
+
+
+
Casting
+
    +
  • Casting in arithmetic, in nutshell:

    +
      +
    • only type (not value!) of operands matters

    • +
    • largest “safe” type able to represent both is picked

    • +
    • scalars can “lose” to arrays in some situations

    • +
    +
  • +
  • Casting in general copies data:

    +
    >>> x = np.array([1, 2, 3, 4], dtype=float)
    +
    >>> x +
    array([1., 2., 3., 4.]) +
    >>> y = x.astype(np.int8) +
    >>> y +
    array([1, 2, 3, 4], dtype=int8) +
    >>> y + 1 +
    array([2, 3, 4, 5], dtype=int8) +
    >>> y + 256 +
    Traceback (most recent call last): +
    File "<stdin>", line 1, in <module> +
    OverflowError: Python integer 256 out of bounds for int8 +
    >>> y + 256.0 +
    array([257., 258., 259., 260.]) +
    >>> y + np.array([256], dtype=np.int32) +
    array([257, 258, 259, 260], dtype=int32) +
    +
    +
  • +
  • Casting on setitem: dtype of the array is not changed on item assignment:

    +
    >>> y[:] = y + 1.5
    +
    >>> y +
    array([2, 3, 4, 5], dtype=int8) +
    +
    +
  • +
+
+

Note

+

Exact rules: see NumPy documentation

+
+
+
+
Re-interpretation / viewing
+
    +
  • Data block in memory (4 bytes)

    + +++++++++ + + + + + + + + + + +

    0x01

    ||

    0x02

    ||

    0x03

    ||

    0x04

    +
      +
    • 4 of uint8, OR,

    • +
    • 4 of int8, OR,

    • +
    • 2 of int16, OR,

    • +
    • 1 of int32, OR,

    • +
    • 1 of float32, OR,

    • +
    • +
    +

    How to switch from one to another?

    +
  • +
+
    +
  1. Switch the dtype:

    +
    >>> x = np.array([1, 2, 3, 4], dtype=np.uint8)
    +
    >>> x.dtype = "<i2" +
    >>> x +
    array([ 513, 1027], dtype=int16) +
    >>> 0x0201, 0x0403 +
    (513, 1027) +
    +
    +
  2. +
+
+
+++++++ + + + + + + + + +

0x01

0x02

||

0x03

0x04

+
+
+

Note

+

little-endian: least significant byte is on the left in memory

+
+
+
+
    +
  1. Create a new view of type uint32, shorthand i4:

    +
    >>> y = x.view("<i4")
    +
    >>> y +
    array([67305985], dtype=int32) +
    >>> 0x04030201 +
    67305985 +
    +
    +
  2. +
+
+
++++++ + + + + + + + +

0x01

0x02

0x03

0x04

+
+
+

Note

+
    +
  • .view() makes views, does not copy (or alter) the memory block

  • +
  • only changes the dtype (and adjusts array shape):

    +
    >>> x[1] = 5
    +
    >>> y +
    array([328193], dtype=int32) +
    >>> y.base is x +
    True +
    +
    +
  • +
+
+

Mini-exercise: data re-interpretation

+
+

See also

+

view-colors.py

+
+

You have RGBA data in an array:

+
>>> x = np.zeros((10, 10, 4), dtype=np.int8)
+
>>> x[:, :, 0] = 1 +
>>> x[:, :, 1] = 2 +
>>> x[:, :, 2] = 3 +
>>> x[:, :, 3] = 4 +
+
+

where the last three dimensions are the R, B, and G, and alpha channels.

+

How to make a (10, 10) structured array with field names ‘r’, ‘g’, ‘b’, ‘a’ +without copying data?

+
>>> y = ...                     
+
+
>>> assert (y['r'] == 1).all() +
>>> assert (y['g'] == 2).all() +
>>> assert (y['b'] == 3).all() +
>>> assert (y['a'] == 4).all() +
+
+

Solution

+
+
... +
+
+

Warning

+

Another two arrays, each occupying exactly 4 bytes of memory:

+
>>> x = np.array([[1, 3], [2, 4]], dtype=np.uint8)
+
>>> x +
array([[1, 3], +
[2, 4]], dtype=uint8) +
>>> y = x.transpose() +
>>> y +
array([[1, 2], +
[3, 4]], dtype=uint8) +
+
+

We view the elements of x (1 byte each) as int16 (2 bytes each):

+
>>> x.view(np.int16)
+
array([[ 769], +
[1026]], dtype=int16) +
+
+

What is happening here? Take a look at the bytes stored in memory +by x:

+
>>> x.tobytes()
+
b'\x01\x03\x02\x04' +
+
+

The \x stands for heXadecimal, so what we are seeing is:

+
0x01 0x03 0x02 0x04
+
+
+

We ask NumPy to interpret these bytes as elements of dtype +int16—each of which occupies two bytes in memory. Therefore, +0x01 0x03 becomes the first uint16 and 0x02 0x04 the +second.

+

You may then expect to see 0x0103 (259, when converting from +hexadecimal to decimal) as the first result. But your computer +likely stores most significant bytes first, and as such reads the +number as 0x0301 or 769 (go on and type 0x0301 into your Python +terminal to verify).

+

We can do the same on a copy of y (why doesn’t it work on y +directly?):

+
>>> y.copy().view(np.int16)
+
array([[ 513], +
[1027]], dtype=int16) +
+
+

Can you explain these numbers, 513 and 1027, as well as the output +shape of the resulting array?

+
+
+
+
+
+

2.2.1.4. Indexing scheme: strides

+
+

Main point

+

The question:

+
>>> x = np.array([[1, 2, 3],
+
... [4, 5, 6], +
... [7, 8, 9]], dtype=np.int8) +
>>> x.tobytes('A') +
b'\x01\x02\x03\x04\x05\x06\x07\x08\t' +
+
At which byte in ``x.data`` does the item ``x[1, 2]`` begin? +
+
+

The answer (in NumPy)

+
+
    +
  • strides: the number of bytes to jump to find the next element

  • +
  • 1 stride per dimension

  • +
+
+
>>> x.strides
+
(3, 1) +
>>> byte_offset = 3 * 1 + 1 * 2 # to find x[1, 2] +
>>> x.flat[byte_offset] +
np.int8(6) +
>>> x[1, 2] +
np.int8(6) +
+
+

simple, flexible

+
+
C and Fortran order
+
+

Note

+

The Python built-in bytes returns bytes in C-order by default +which can cause confusion when trying to inspect memory layout. We use +numpy.ndarray.tobytes() with order=A instead, which preserves +the C or F ordering of the bytes in memory.

+
+
>>> x = np.array([[1, 2, 3],
+
... [4, 5, 6]], dtype=np.int16, order='C') +
>>> x.strides +
(6, 2) +
>>> x.tobytes('A') +
b'\x01\x00\x02\x00\x03\x00\x04\x00\x05\x00\x06\x00' +
+
+
    +
  • Need to jump 6 bytes to find the next row

  • +
  • Need to jump 2 bytes to find the next column

  • +
+
>>> y = np.array(x, order='F')
+
>>> y.strides +
(2, 4) +
>>> y.tobytes('A') +
b'\x01\x00\x04\x00\x02\x00\x05\x00\x03\x00\x06\x00' +
+
+
    +
  • Need to jump 2 bytes to find the next row

  • +
  • Need to jump 4 bytes to find the next column

  • +
+
    +
  • Similarly to higher dimensions:

    +
      +
    • C: last dimensions vary fastest (= smaller strides)

    • +
    • F: first dimensions vary fastest

    • +
    +
    +

    \mathrm{shape} &= (d_1, d_2, ..., d_n)
+\\
+\mathrm{strides} &= (s_1, s_2, ..., s_n)
+\\
+s_j^C &= d_{j+1} d_{j+2} ... d_{n} \times \mathrm{itemsize}
+\\
+s_j^F &= d_{1} d_{2} ... d_{j-1} \times \mathrm{itemsize}

    +
  • +
+
+

Note

+

Now we can understand the behavior of .view():

+
>>> y = np.array([[1, 3], [2, 4]], dtype=np.uint8).transpose()
+
>>> x = y.copy() +
+
+

Transposition does not affect the memory layout of the data, only strides

+
>>> x.strides
+
(2, 1) +
>>> y.strides +
(1, 2) +
+
+
>>> x.tobytes('A')
+
b'\x01\x02\x03\x04' +
>>> y.tobytes('A') +
b'\x01\x03\x02\x04' +
+
+
    +
  • the results are different when interpreted as 2 of int16

  • +
  • .copy() creates new arrays in the C order (by default)

  • +
+
+
+

Note

+

In-place operations with views

+

Prior to NumPy version 1.13, in-place operations with views could result in +incorrect results for large arrays. +Since version 1.13, +NumPy includes checks for memory overlap to +guarantee that results are consistent with the non in-place version +(e.g. a = a + a.T produces the same result as a += a.T). +Note however that this may result in the data being copied (as if using +a += a.T.copy()), ultimately resulting in more memory being used than +might otherwise be expected for in-place operations!

+
+
+
+
Slicing with integers
+
    +
  • Everything can be represented by changing only shape, strides, +and possibly adjusting the data pointer!

  • +
  • Never makes copies of the data

  • +
+
>>> x = np.array([1, 2, 3, 4, 5, 6], dtype=np.int32)
+
>>> y = x[::-1] +
>>> y +
array([6, 5, 4, 3, 2, 1], dtype=int32) +
>>> y.strides +
(-4,) +
+
>>> y = x[2:] +
>>> y.__array_interface__['data'][0] - x.__array_interface__['data'][0] +
8 +
+
>>> x = np.zeros((10, 10, 10), dtype=float) +
>>> x.strides +
(800, 80, 8) +
>>> x[::2,::3,::4].strides +
(1600, 240, 32) +
+
+
    +
  • Similarly, transposes never make copies (it just swaps strides):

    +
    >>> x = np.zeros((10, 10, 10), dtype=float)
    +
    >>> x.strides +
    (800, 80, 8) +
    >>> x.T.strides +
    (8, 80, 800) +
    +
    +
  • +
+

But: not all reshaping operations can be represented by playing with +strides:

+
>>> a = np.arange(6, dtype=np.int8).reshape(3, 2)
+
>>> b = a.T +
>>> b.strides +
(1, 2) +
+
+

So far, so good. However:

+
>>> bytes(a.data)
+
b'\x00\x01\x02\x03\x04\x05' +
>>> b +
array([[0, 2, 4], +
[1, 3, 5]], dtype=int8) +
>>> c = b.reshape(3*2) +
>>> c +
array([0, 2, 4, 1, 3, 5], dtype=int8) +
+
+

Here, there is no way to represent the array c given one stride +and the block of memory for a. Therefore, the reshape +operation needs to make a copy here.

+
+
+
+

Example: fake dimensions with strides

+

Stride manipulation

+
>>> from numpy.lib.stride_tricks import as_strided
+
>>> help(as_strided) +
Help on function as_strided in module numpy.lib.stride_tricks: +
... +
+
+
+

Warning

+

as_strided does not check that you stay inside the memory +block bounds…

+
+
>>> x = np.array([1, 2, 3, 4], dtype=np.int16)
+
>>> as_strided(x, strides=(2*2, ), shape=(2, )) +
array([1, 3], dtype=int16) +
>>> x[::2] +
array([1, 3], dtype=int16) +
+
+
+

See also

+

stride-fakedims.py

+
+

Exercise

+
+
array([1, 2, 3, 4], dtype=np.int8)
+
+
-> array([[1, 2, 3, 4], +
[1, 2, 3, 4], +
[1, 2, 3, 4]], dtype=np.int8) +
+
+

using only as_strided.:

+
Hint: byte_offset = stride[0]*index[0] + stride[1]*index[1] + ...
+
+
+
+

Spoiler

+
+
... +
+
+
+

Broadcasting

+
    +
  • Doing something useful with it: outer product +of [1, 2, 3, 4] and [5, 6, 7]

  • +
+
>>> x = np.array([1, 2, 3, 4], dtype=np.int16)
+
>>> x2 = as_strided(x, strides=(0, 1*2), shape=(3, 4)) +
>>> x2 +
array([[1, 2, 3, 4], +
[1, 2, 3, 4], +
[1, 2, 3, 4]], dtype=int16) +
+
+
>>> y = np.array([5, 6, 7], dtype=np.int16)
+
>>> y2 = as_strided(y, strides=(1*2, 0), shape=(3, 4)) +
>>> y2 +
array([[5, 5, 5, 5], +
[6, 6, 6, 6], +
[7, 7, 7, 7]], dtype=int16) +
+
+
>>> x2 * y2
+
array([[ 5, 10, 15, 20], +
[ 6, 12, 18, 24], +
[ 7, 14, 21, 28]], dtype=int16) +
+
+

… seems somehow familiar …

+
>>> x = np.array([1, 2, 3, 4], dtype=np.int16)
+
>>> y = np.array([5, 6, 7], dtype=np.int16) +
>>> x[np.newaxis,:] * y[:,np.newaxis] +
array([[ 5, 10, 15, 20], +
[ 6, 12, 18, 24], +
[ 7, 14, 21, 28]], dtype=int16) +
+
+
    +
  • Internally, array broadcasting is indeed implemented using 0-strides.

  • +
+
+
+

More tricks: diagonals

+
+

See also

+

stride-diagonals.py

+
+

Challenge

+
+
    +
  • Pick diagonal entries of the matrix: (assume C memory order):

    +
    >>> x = np.array([[1, 2, 3],
    +
    ... [4, 5, 6], +
    ... [7, 8, 9]], dtype=np.int32) +
    +
    >>> x_diag = as_strided(x, shape=(3,), strides=(???,)) +
    +
    +
  • +
  • Pick the first super-diagonal entries [2, 6].

  • +
  • And the sub-diagonals?

  • +
+
+
(Hint to the last two: slicing first moves the point where striding

starts from.)

+
+
+
+

Solution

+
+
... +
+
+

See also

+

stride-diagonals.py

+
+

Challenge

+
+

Compute the tensor trace:

+
>>> x = np.arange(5*5*5*5).reshape(5, 5, 5, 5)
+
>>> s = 0 +
>>> for i in range(5): +
... for j in range(5): +
... s += x[j, i, j, i] +
+
+

by striding, and using sum() on the result.

+
>>> y = as_strided(x, shape=(5, 5), strides=(TODO, TODO))   
+
>>> s2 = ... +
>>> assert s == s2 +
+
+
+

Solution

+
+
... +
+
+
+

CPU cache effects

+

Memory layout can affect performance:

+
In [1]: x = np.zeros((20000,))
+
+
In [2]: y = np.zeros((20000*67,))[::67] +
+
In [3]: x.shape, y.shape +
Out[3]: ((20000,), (20000,)) +
+
In [4]: %timeit x.sum() +
5.34 us +- 69.8 ns per loop (mean +- std. dev. of 7 runs, 100,000 loops each) +
+
In [5]: %timeit y.sum() +
24.3 us +- 79.7 ns per loop (mean +- std. dev. of 7 runs, 10,000 loops each) +
+
In [6]: x.strides, y.strides +
Out[6]: ((8,), (536,)) +
+
+

Smaller strides are faster?

+../../_images/cpu-cacheline.png +
    +
  • CPU pulls data from main memory to its cache in blocks

  • +
  • If many array items consecutively operated on fit in a single block (small stride):

    +
      +
    • \Rightarrow fewer transfers needed

    • +
    • \Rightarrow faster

    • +
    +
  • +
+
+

See also

+
    +
  • numexpr is designed to mitigate +cache effects when evaluating array expressions.

  • +
  • numba is a compiler for Python code, +that is aware of numpy arrays.

  • +
+
+
+
+
+

2.2.1.5. Findings in dissection

+../../_images/threefundamental.png +
    +
  • memory block: may be shared, .base, .data

  • +
  • data type descriptor: structured data, sub-arrays, byte order, +casting, viewing, .astype(), .view()

  • +
  • strided indexing: strides, C/F-order, slicing w/ integers, +as_strided, broadcasting, stride tricks, diag, CPU cache +coherence

  • +
+
+
+
+

2.2.2. Universal functions

+
+

2.2.2.1. What they are?

+
    +
  • Ufunc performs and elementwise operation on all elements of an array.

    +

    Examples:

    +
    np.add, np.subtract, scipy.special.*, ...
    +
    +
    +
  • +
  • Automatically support: broadcasting, casting, …

  • +
  • The author of an ufunc only has to supply the elementwise operation, +NumPy takes care of the rest.

  • +
  • The elementwise operation needs to be implemented in C (or, e.g., Cython)

  • +
+
+

Parts of an Ufunc

+
    +
  1. Provided by user

    +
    void ufunc_loop(void **args, int *dimensions, int *steps, void *data)
    +
    { +
    /* +
    * int8 output = elementwise_function(int8 input_1, int8 input_2) +
    * +
    * This function must compute the ufunc for many values at once, +
    * in the way shown below. +
    */ +
    char *input_1 = (char*)args[0]; +
    char *input_2 = (char*)args[1]; +
    char *output = (char*)args[2]; +
    int i; +
    +
    for (i = 0; i < dimensions[0]; ++i) { +
    *output = elementwise_function(*input_1, *input_2); +
    input_1 += steps[0]; +
    input_2 += steps[1]; +
    output += steps[2]; +
    } +
    } +
    +
    +
  2. +
  3. The NumPy part, built by

    +
    char types[3]
    +
    +
    types[0] = NPY_BYTE /* type of first input arg */ +
    types[1] = NPY_BYTE /* type of second input arg */ +
    types[2] = NPY_BYTE /* type of third input arg */ +
    +
    PyObject *python_ufunc = PyUFunc_FromFuncAndData( +
    ufunc_loop, +
    NULL, +
    types, +
    1, /* ntypes */ +
    2, /* num_inputs */ +
    1, /* num_outputs */ +
    identity_element, +
    name, +
    docstring, +
    unused) +
    +
    +
      +
    • A ufunc can also support multiple different input-output type +combinations.

    • +
    +
  4. +
+
+
+

Making it easier

+
    +
  1. ufunc_loop is of very generic form, and NumPy provides +pre-made ones

    + ++++ + + + + + + + + + + + + + + + + + + + + +

    PyUfunc_f_f

    float elementwise_func(float input_1)

    PyUfunc_ff_f

    float elementwise_func(float input_1, float input_2)

    PyUfunc_d_d

    double elementwise_func(double input_1)

    PyUfunc_dd_d

    double elementwise_func(double input_1, double input_2)

    PyUfunc_D_D

    elementwise_func(npy_cdouble *input, npy_cdouble* output)

    PyUfunc_DD_D

    elementwise_func(npy_cdouble *in1, npy_cdouble *in2, npy_cdouble* out)

    +
      +
    • Only elementwise_func needs to be supplied

    • +
    • … except when your elementwise function is not in one of the above forms

    • +
    +
  2. +
+
+
+
+

2.2.2.2. Exercise: building an ufunc from scratch

+

The Mandelbrot fractal is defined by the iteration

+
+

z \leftarrow z^2 + c

+

where c = x + i y is a complex number. This iteration is +repeated – if z stays finite no matter how long the iteration +runs, c belongs to the Mandelbrot set.

+
    +
  • Make ufunc called mandel(z0, c) that computes:

    +
    z = z0
    +
    for k in range(iterations): +
    z = z*z + c +
    +
    +

    say, 100 iterations or until z.real**2 + z.imag**2 > 1000. +Use it to determine which c are in the Mandelbrot set.

    +
  • +
  • Our function is a simple one, so make use of the PyUFunc_* helpers.

  • +
  • Write it in Cython

  • +
+
+

See also

+

mandel.pyx, mandelplot.py

+
+

Reminder: some pre-made Ufunc loops:

+ ++++ + + + + + + + + + + + + + + + + + + + + +

PyUfunc_f_f

float elementwise_func(float input_1)

PyUfunc_ff_f

float elementwise_func(float input_1, float input_2)

PyUfunc_d_d

double elementwise_func(double input_1)

PyUfunc_dd_d

double elementwise_func(double input_1, double input_2)

PyUfunc_D_D

elementwise_func(complex_double *input, complex_double* output)

PyUfunc_DD_D

elementwise_func(complex_double *in1, complex_double *in2, complex_double* out)

+

Type codes:

+
NPY_BOOL, NPY_BYTE, NPY_UBYTE, NPY_SHORT, NPY_USHORT, NPY_INT, NPY_UINT,
+
NPY_LONG, NPY_ULONG, NPY_LONGLONG, NPY_ULONGLONG, NPY_FLOAT, NPY_DOUBLE, +
NPY_LONGDOUBLE, NPY_CFLOAT, NPY_CDOUBLE, NPY_CLONGDOUBLE, NPY_DATETIME, +
NPY_TIMEDELTA, NPY_OBJECT, NPY_STRING, NPY_UNICODE, NPY_VOID +
+
+
+
+

2.2.2.3. Solution: building an ufunc from scratch

+
# The elementwise function
+
# ------------------------ +
+
cdef void mandel_single_point(double complex *z_in, +
double complex *c_in, +
double complex *z_out) noexcept nogil: +
# +
# The Mandelbrot iteration +
# +
+
# +
# Some points of note: +
# +
# - It's *NOT* allowed to call any Python functions here. +
# +
# The Ufunc loop runs with the Python Global Interpreter Lock released. +
# Hence, the ``nogil``. +
# +
# - And so all local variables must be declared with ``cdef`` +
# +
# - Note also that this function receives *pointers* to the data; +
# the "traditional" solution to passing complex variables around +
# +
+
cdef double complex z = z_in[0] +
cdef double complex c = c_in[0] +
cdef int k # the integer we use in the for loop +
+
# Straightforward iteration +
+
for k in range(100): +
z = z*z + c +
if z.real**2 + z.imag**2 > 1000: +
break +
+
# Return the answer for this point +
z_out[0] = z +
+
+
# Boilerplate Cython definitions +
# +
# Pulls definitions from the NumPy C headers. +
# ------------------------------------------- +
+
from numpy cimport import_array, import_ufunc +
from numpy cimport (PyUFunc_FromFuncAndData, +
PyUFuncGenericFunction) +
from numpy cimport NPY_CDOUBLE +
from numpy cimport PyUFunc_DD_D +
+
# Required module initialization +
# ------------------------------ +
+
import_array() +
import_ufunc() +
+
+
# The actual ufunc declaration +
# ---------------------------- +
+
cdef PyUFuncGenericFunction loop_func[1] +
cdef char input_output_types[3] +
cdef void *elementwise_funcs[1] +
+
loop_func[0] = PyUFunc_DD_D +
+
input_output_types[0] = NPY_CDOUBLE +
input_output_types[1] = NPY_CDOUBLE +
input_output_types[2] = NPY_CDOUBLE +
+
elementwise_funcs[0] = <void*>mandel_single_point +
+
mandel = PyUFunc_FromFuncAndData( +
loop_func, +
elementwise_funcs, +
input_output_types, +
1, # number of supported input types +
2, # number of input args +
1, # number of output args +
0, # `identity` element, never mind this +
"mandel", # function name +
"mandel(z, c) -> computes iterated z*z + c", # docstring +
0 # unused +
) +
+
+
"""
+
Plot Mandelbrot +
================ +
+
Plot the Mandelbrot ensemble. +
+
""" +
+
import numpy as np +
import mandel +
+
x = np.linspace(-1.7, 0.6, 1000) +
y = np.linspace(-1.4, 1.4, 1000) +
c = x[None, :] + 1j * y[:, None] +
z = mandel.mandel(c, c) +
+
import matplotlib.pyplot as plt +
+
plt.imshow(abs(z) ** 2 < 1000, extent=[-1.7, 0.6, -1.4, 1.4]) +
plt.gray() +
plt.show() +
+
+../../_images/mandelbrot.png +
+

Note

+

Most of the boilerplate could be automated by these Cython modules:

+

https://github.com/cython/cython/wiki/MarkLodato-CreatingUfuncs

+
+

Several accepted input types

+

E.g. supporting both single- and double-precision versions

+
cdef void mandel_single_point(double complex *z_in,
+
double complex *c_in, +
double complex *z_out) nogil: +
... +
+
cdef void mandel_single_point_singleprec(float complex *z_in, +
float complex *c_in, +
float complex *z_out) nogil: +
... +
+
cdef PyUFuncGenericFunction loop_funcs[2] +
cdef char input_output_types[3*2] +
cdef void *elementwise_funcs[1*2] +
+
loop_funcs[0] = PyUFunc_DD_D +
input_output_types[0] = NPY_CDOUBLE +
input_output_types[1] = NPY_CDOUBLE +
input_output_types[2] = NPY_CDOUBLE +
elementwise_funcs[0] = <void*>mandel_single_point +
+
loop_funcs[1] = PyUFunc_FF_F +
input_output_types[3] = NPY_CFLOAT +
input_output_types[4] = NPY_CFLOAT +
input_output_types[5] = NPY_CFLOAT +
elementwise_funcs[1] = <void*>mandel_single_point_singleprec +
+
mandel = PyUFunc_FromFuncAndData( +
loop_func, +
elementwise_funcs, +
input_output_types, +
2, # number of supported input types <---------------- +
2, # number of input args +
1, # number of output args +
0, # `identity` element, never mind this +
"mandel", # function name +
"mandel(z, c) -> computes iterated z*z + c", # docstring +
0 # unused +
) +
+
+
+
+

2.2.2.4. Generalized ufuncs

+

ufunc

+
+

output = elementwise_function(input)

+

Both output and input can be a single array element only.

+
+

generalized ufunc

+
+

output and input can be arrays with a fixed number of dimensions

+

For example, matrix trace (sum of diag elements):

+
input shape = (n, n)
+
output shape = () i.e. scalar +
+
(n, n) -> () +
+
+

Matrix product:

+
input_1 shape = (m, n)
+
input_2 shape = (n, p) +
output shape = (m, p) +
+
(m, n), (n, p) -> (m, p) +
+
+
    +
  • This is called the “signature” of the generalized ufunc

  • +
  • The dimensions on which the g-ufunc acts, are “core dimensions”

  • +
+
+

Status in NumPy

+
    +
  • g-ufuncs are in NumPy already …

  • +
  • new ones can be created with PyUFunc_FromFuncAndDataAndSignature

  • +
  • most linear-algebra functions are implemented as g-ufuncs to enable working +with stacked arrays:

    +
    >>> import numpy as np
    +
    >>> rng = np.random.default_rng(27446968) +
    >>> np.linalg.det(rng.random((3, 5, 5))) +
    array([ 0.01829761, -0.0077266 , -0.05336566]) +
    >>> np.linalg._umath_linalg.det.signature +
    '(m,m)->()' +
    +
    +
  • +
+
+
    +
  • matrix multiplication this way could be useful for operating on +many small matrices at once

  • +
  • Also see tensordot and einsum

  • +
+
+

Generalized ufunc loop

+

Matrix multiplication (m,n),(n,p) -> (m,p)

+
void gufunc_loop(void **args, int *dimensions, int *steps, void *data)
+
{ +
char *input_1 = (char*)args[0]; /* these are as previously */ +
char *input_2 = (char*)args[1]; +
char *output = (char*)args[2]; +
+
int input_1_stride_m = steps[3]; /* strides for the core dimensions */ +
int input_1_stride_n = steps[4]; /* are added after the non-core */ +
int input_2_strides_n = steps[5]; /* steps */ +
int input_2_strides_p = steps[6]; +
int output_strides_n = steps[7]; +
int output_strides_p = steps[8]; +
+
int m = dimension[1]; /* core dimensions are added after */ +
int n = dimension[2]; /* the main dimension; order as in */ +
int p = dimension[3]; /* signature */ +
+
int i; +
+
for (i = 0; i < dimensions[0]; ++i) { +
matmul_for_strided_matrices(input_1, input_2, output, +
strides for each array...); +
+
input_1 += steps[0]; +
input_2 += steps[1]; +
output += steps[2]; +
} +
} +
+
+
+
+
+

2.2.3. Interoperability features

+
+

2.2.3.1. Sharing multidimensional, typed data

+

Suppose you

+
    +
  1. Write a library than handles (multidimensional) binary data,

  2. +
  3. Want to make it easy to manipulate the data with NumPy, or whatever +other library,

  4. +
  5. … but would not like to have NumPy as a dependency.

  6. +
+

Currently, 3 solutions:

+
    +
  1. the “old” buffer interface

  2. +
  3. the array interface

  4. +
  5. the “new” buffer interface (PEP 3118)

  6. +
+
+
+

2.2.3.2. The old buffer protocol

+
    +
  • Only 1-D buffers

  • +
  • No data type information

  • +
  • C-level interface; PyBufferProcs tp_as_buffer in the type object

  • +
  • But it’s integrated into Python (e.g. strings support it)

  • +
+

Mini-exercise using Pillow (Python +Imaging Library):

+
+

See also

+

pilbuffer.py

+
+
>>> from PIL import Image
+
>>> data = np.zeros((200, 200, 4), dtype=np.uint8) +
>>> data[:, :] = [255, 0, 0, 255] # Red +
>>> # In PIL, RGBA images consist of 32-bit integers whose bytes are [RR,GG,BB,AA] +
>>> data = data.view(np.int32).squeeze() +
>>> img = Image.frombuffer("RGBA", (200, 200), data, "raw", "RGBA", 0, 1) +
>>> img.save('test.png') +
+
+

Q:

+
+

Check what happens if data is now modified, and img saved again.

+
+
+
+

2.2.3.3. The old buffer protocol

+
"""
+
From buffer +
============ +
+
Show how to exchange data between numpy and a library that only knows +
the buffer interface. +
""" +
+
import numpy as np +
from PIL import Image +
+
# Let's make a sample image, RGBA format +
+
x = np.zeros((200, 200, 4), dtype=np.uint8) +
+
x[:, :, 0] = 255 # red +
x[:, :, 3] = 255 # opaque +
+
data = x.view(np.int32) # Check that you understand why this is OK! +
+
img = Image.frombuffer("RGBA", (200, 200), data) +
img.save("test.png") +
+
# Modify the original data, and save again. +
+
x[:, :, 1] = 255 +
img.save("test2.png") +
+
+../../_images/test.png +../../_images/test2.png +
+
+

2.2.3.4. Array interface protocol

+
    +
  • Multidimensional buffers

  • +
  • Data type information present

  • +
  • NumPy-specific approach; slowly deprecated (but not going away)

  • +
  • Not integrated in Python otherwise

  • +
+ +
>>> x = np.array([[1, 2], [3, 4]])
+
>>> x.__array_interface__ +
{'data': (171694552, False), # memory address of data, is readonly? +
'descr': [('', '<i4')], # data type descriptor +
'typestr': '<i4', # same, in another form +
'strides': None, # strides; or None if in C-order +
'shape': (2, 2), +
'version': 3, +
} +
+
+
+
::
>>> from PIL import Image
+
>>> img = Image.open('data/test.png') +
>>> img.__array_interface__ +
{'version': 3, +
'data': ..., +
'shape': (200, 200, 4), +
'typestr': '|u1'} +
>>> x = np.asarray(img) +
>>> x.shape +
(200, 200, 4) +
+
+
+
+
+

Note

+

A more C-friendly variant of the array interface is also defined.

+
+
+
+
+

2.2.4. Array siblings: chararray, maskedarray

+
+

2.2.4.1. chararray: vectorized string operations

+
>>> x = np.char.asarray(['a', '  bbb', '  ccc'])
+
>>> x +
chararray(['a', ' bbb', ' ccc'], dtype='<U5') +
>>> x.upper() +
chararray(['A', ' BBB', ' CCC'], dtype='<U5') +
+
+
+
+

2.2.4.2. masked_array missing data

+

Masked arrays are arrays that may have missing or invalid entries.

+

For example, suppose we have an array where the fourth entry is invalid:

+
>>> x = np.array([1, 2, 3, -99, 5])
+
+
+

One way to describe this is to create a masked array:

+
>>> mx = np.ma.masked_array(x, mask=[0, 0, 0, 1, 0])
+
>>> mx +
masked_array(data=[1, 2, 3, --, 5], +
mask=[False, False, False, True, False], +
fill_value=999999) +
+
+

Masked mean ignores masked data:

+
>>> mx.mean()
+
np.float64(2.75) +
>>> np.mean(mx) +
np.float64(2.75) +
+
+
+

Warning

+

Not all NumPy functions respect masks, for instance +np.dot, so check the return types.

+
+

The masked_array returns a view to the original array:

+
>>> mx[1] = 9
+
>>> x +
array([ 1, 9, 3, -99, 5]) +
+
+
+

The mask

+

You can modify the mask by assigning:

+
>>> mx[1] = np.ma.masked
+
>>> mx +
masked_array(data=[1, --, 3, --, 5], +
mask=[False, True, False, True, False], +
fill_value=999999) +
+
+

The mask is cleared on assignment:

+
>>> mx[1] = 9
+
>>> mx +
masked_array(data=[1, 9, 3, --, 5], +
mask=[False, False, False, True, False], +
fill_value=999999) +
+
+

The mask is also available directly:

+
>>> mx.mask
+
array([False, False, False, True, False]) +
+
+

The masked entries can be filled with a given value to get an usual +array back:

+
>>> x2 = mx.filled(-1)
+
>>> x2 +
array([ 1, 9, 3, -1, 5]) +
+
+

The mask can also be cleared:

+
>>> mx.mask = np.ma.nomask
+
>>> mx +
masked_array(data=[1, 9, 3, -99, 5], +
mask=[False, False, False, False, False], +
fill_value=999999) +
+
+
+
+

Domain-aware functions

+

The masked array package also contains domain-aware functions:

+
>>> np.ma.log(np.array([1, 2, -1, -2, 3, -5]))
+
masked_array(data=[0.0, 0.693147180559..., --, --, 1.098612288668..., --], +
mask=[False, False, True, True, False, True], +
fill_value=1e+20) +
+
+
+

Note

+

Streamlined and more seamless support for dealing with missing data +in arrays is making its way into NumPy 1.7. Stay tuned!

+
+ +../../_images/sphx_glr_plot_maskedstats_001.png + +
+
+
+

2.2.4.3. recarray: purely convenience

+
>>> arr = np.array([('a', 1), ('b', 2)], dtype=[('x', 'S1'), ('y', int)])
+
>>> arr2 = arr.view(np.recarray) +
>>> arr2.x +
array([b'a', b'b'], dtype='|S1') +
>>> arr2.y +
array([1, 2]) +
+
+
+
+
+

2.2.5. Summary

+
    +
  • Anatomy of the ndarray: data, dtype, strides.

  • +
  • Universal functions: elementwise operations, how to make new ones

  • +
  • Ndarray subclasses

  • +
  • Various buffer interfaces for integration with other tools

  • +
  • Recent additions: PEP 3118, generalized ufuncs

  • +
+
+
+

2.2.6. Contributing to NumPy/SciPy

+
+
+
+

2.2.6.1. Why

+
    +
  • “There’s a bug?”

  • +
  • “I don’t understand what this is supposed to do?”

  • +
  • “I have this fancy code. Would you like to have it?”

  • +
  • “I’d like to help! What can I do?”

  • +
+
+
+

2.2.6.2. Reporting bugs

+ +
+

Good bug report

+
Title: numpy.random.permutations fails for non-integer arguments
+
+
I'm trying to generate random permutations, using numpy.random.permutations +
+
When calling numpy.random.permutation with non-integer arguments +
it fails with a cryptic error message:: +
+
>>> rng.permutation(12) +
array([ 2, 6, 4, 1, 8, 11, 10, 5, 9, 3, 7, 0]) +
>>> rng.permutation(12.) #doctest: +SKIP +
Traceback (most recent call last): +
File "<stdin>", line 1, in <module> +
File "_generator.pyx", line 4844, in numpy.random._generator.Generator.permutation +
numpy.exceptions.AxisError: axis 0 is out of bounds for array of dimension 0 +
+
This also happens with long arguments, and so +
np.random.permutation(X.shape[0]) where X is an array fails on 64 +
bit windows (where shape is a tuple of longs). +
+
It would be great if it could cast to integer or at least raise a +
proper error for non-integer types. +
+
I'm using NumPy 1.4.1, built from the official tarball, on Windows +
64 with Visual studio 2008, on Python.org 64-bit Python. +
+
+
    +
  1. What are you trying to do?

  2. +
  3. Small code snippet reproducing the bug (if possible)

    +
      +
    • What actually happens

    • +
    • What you’d expect

    • +
    +
  4. +
  5. Platform (Windows / Linux / OSX, 32/64 bits, x86/PPC, …)

  6. +
  7. Version of NumPy/SciPy

    +
    >>> print(np.__version__)
    +
    2... +
    +
    +

    Check that the following is what you expect

    +
    >>> print(np.__file__)
    +
    /... +
    +
    +

    In case you have old/broken NumPy installations lying around.

    +

    If unsure, try to remove existing NumPy installations, and reinstall…

    +
  8. +
+
+
+
+

2.2.6.3. Contributing to documentation

+
    +
  1. Documentation editor

    +
      +
    • https://numpy.org/doc/stable/

    • +
    • Registration

      +
        +
      • Register an account

      • +
      • Subscribe to scipy-dev mailing list (subscribers-only)

      • +
      • Problem with mailing lists: you get mail

        + +
      • +
      • Send a mail @ scipy-dev mailing list; ask for activation:

        +
        To: scipy-dev@scipy.org
        +
        +
        Hi, +
        +
        I'd like to edit NumPy/SciPy docstrings. My account is XXXXX +
        +
        Cheers, +
        N. N. +
        +
        +
      • +
      +
    • +
    +
    +
    +
    +
  2. +
  3. Edit sources and send patches (as for bugs)

  4. +
  5. Complain on the mailing list

  6. +
+
+
+

2.2.6.4. Contributing features

+
+

The contribution of features is documented on https://numpy.org/doc/stable/dev/

+
+
+
+

2.2.6.5. How to help, in general

+
    +
  • Bug fixes always welcome!

    +
      +
    • What irks you most

    • +
    • Browse the tracker

    • +
    +
  • +
  • Documentation work

    + +
  • +
  • Ask on communication channels:

    +
      +
    • numpy-discussion list

    • +
    • scipy-dev list

    • +
    +
  • +
+

+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/advanced_python/index.html b/advanced/advanced_python/index.html new file mode 100644 index 000000000..adf2648d9 --- /dev/null +++ b/advanced/advanced_python/index.html @@ -0,0 +1,1315 @@ + + + + + + + + 2.1. Advanced Python Constructs — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

2.1. Advanced Python Constructs

+

Author Zbigniew Jędrzejewski-Szmek

+

This section covers some features of the Python language which can +be considered advanced — in the sense that not every language has +them, and also in the sense that they are more useful in more +complicated programs or libraries, but not in the sense of being +particularly specialized, or particularly complicated.

+

It is important to underline that this chapter is purely about the +language itself — about features supported through special syntax +complemented by functionality of the Python stdlib, which could not be +implemented through clever external modules.

+

The process of developing the Python programming language, its syntax, +is very transparent; proposed changes are +evaluated from various angles and discussed via Python Enhancement +ProposalsPEPs. As a result, features described in this chapter +were added after it was shown that they indeed solve real problems and +that their use is as simple as possible.

+ +
+

2.1.1. Iterators, generator expressions and generators

+
+

2.1.1.1. Iterators

+ +

An iterator is an object adhering to the iterator protocol +— basically this means that it has a next method, +which, when called, returns the next item in the sequence, and when +there’s nothing to return, raises the +StopIteration exception.

+

An iterator object allows to loop just once. It +holds the state (position) of a single iteration, or from the other +side, each loop over a sequence requires a single iterator +object. This means that we can iterate over the same sequence more +than once concurrently. Separating the iteration logic from the +sequence allows us to have more than one way of iteration.

+

Calling the __iter__ method on a container to +create an iterator object is the most straightforward way to get hold +of an iterator. The iter function does that for us, saving a few +keystrokes.

+
>>> nums = [1, 2, 3]      # note that ... varies: these are different objects
+
>>> iter(nums) +
<...iterator object at ...> +
>>> nums.__iter__() +
<...iterator object at ...> +
>>> nums.__reversed__() +
<...reverseiterator object at ...> +
+
>>> it = iter(nums) +
>>> next(it) +
1 +
>>> next(it) +
2 +
>>> next(it) +
3 +
>>> next(it) +
Traceback (most recent call last): +
File "<stdin>", line 1, in <module> +
StopIteration +
+
+

When used in a loop, StopIteration is +swallowed and causes the loop to finish. But with explicit invocation, +we can see that once the iterator is exhausted, accessing it raises an +exception.

+

Using the for..in loop also uses the __iter__ +method. This allows us to transparently start the iteration over a +sequence. But if we already have the iterator, we want to be able to +use it in an for loop in the same way. In order to achieve this, +iterators in addition to next are also required to have a method +called __iter__ which returns the iterator (self).

+

Support for iteration is pervasive in Python: +all sequences and unordered containers in the standard library allow +this. The concept is also stretched to other things: +e.g. file objects support iteration over lines.

+
>>> with open("/etc/fstab") as f: 
+
... f is f.__iter__() +
... +
True +
+
+

The file is an iterator itself and it’s __iter__ method +doesn’t create a separate object: only a single thread of sequential +access is allowed.

+
+
+

2.1.1.2. Generator expressions

+

A second way in which iterator objects are created is through +generator expressions, the basis for list comprehensions. To +increase clarity, a generator expression must always be enclosed in +parentheses or an expression. If round parentheses are used, then a +generator iterator is created. If rectangular parentheses are used, +the process is short-circuited and we get a list.

+
>>> (i for i in nums)
+
<generator object <genexpr> at 0x...> +
>>> [i for i in nums] +
[1, 2, 3] +
>>> list(i for i in nums) +
[1, 2, 3] +
+
+

The list comprehension syntax also extends to +dictionary and set comprehensions. +A set is created when the generator expression is enclosed in curly +braces. A dict is created when the generator expression contains +“pairs” of the form key:value:

+
>>> {i for i in range(3)}
+
{0, 1, 2} +
>>> {i:i**2 for i in range(3)} +
{0: 0, 1: 1, 2: 4} +
+
+

One gotcha should be mentioned: in old Pythons the index variable +(i) would leak, and in versions >= 3 this is fixed.

+
+
+

2.1.1.3. Generators

+ +

A third way to create iterator objects is to call a generator function. +A generator is a function containing the keyword yield. It must be +noted that the mere presence of this keyword completely changes the +nature of the function: this yield statement doesn’t have to be +invoked, or even reachable, but causes the function to be marked as a +generator. When a normal function is called, the instructions +contained in the body start to be executed. When a generator is +called, the execution stops before the first instruction in the body. +An invocation of a generator function creates a generator object, +adhering to the iterator protocol. As with normal function +invocations, concurrent and recursive invocations are allowed.

+

When next is called, the function is executed until the first yield. +Each encountered yield statement gives a value becomes the return +value of next. After executing the yield statement, the +execution of this function is suspended.

+
>>> def f():
+
... yield 1 +
... yield 2 +
>>> f() +
<generator object f at 0x...> +
>>> gen = f() +
>>> next(gen) +
1 +
>>> next(gen) +
2 +
>>> next(gen) +
Traceback (most recent call last): +
File "<stdin>", line 1, in <module> +
StopIteration +
+
+

Let’s go over the life of the single invocation of the generator +function.

+
>>> def f():
+
... print("-- start --") +
... yield 3 +
... print("-- finish --") +
... yield 4 +
>>> gen = f() +
>>> next(gen) +
-- start -- +
3 +
>>> next(gen) +
-- finish -- +
4 +
>>> next(gen) +
Traceback (most recent call last): +
... +
StopIteration +
+
+

Contrary to a normal function, where executing f() would +immediately cause the first print to be executed, gen is +assigned without executing any statements in the function body. Only +when gen.__next__() is invoked by next, the statements up to +the first yield are executed. The second next prints +-- finish -- and execution halts on the second yield. The third +next falls of the end of the function. +Since no yield was reached, an exception is raised.

+

What happens with the function after a yield, when the control passes +to the caller? The state of each generator is stored in the generator +object. From the point of view of the generator function, is looks +almost as if it was running in a separate thread, but this is just an +illusion: execution is strictly single-threaded, but the interpreter +keeps and restores the state in between the requests for the next value.

+

Why are generators useful? As noted in the parts about iterators, a +generator function is just a different way to create an iterator +object. Everything that can be done with yield statements, could +also be done with next methods. Nevertheless, using a +function and having the interpreter perform its magic to create an +iterator has advantages. A function can be much shorter +than the definition of a class with the required next and +__iter__ methods. What is more important, it is easier for the author +of the generator to understand the state which is kept in local +variables, as opposed to instance attributes, which have to be +used to pass data between consecutive invocations of next on +an iterator object.

+

A broader question is why are iterators useful? When an iterator is +used to power a loop, the loop becomes very simple. The code to +initialise the state, to decide if the loop is finished, and to find +the next value is extracted into a separate place. This highlights the +body of the loop — the interesting part. In addition, it is possible +to reuse the iterator code in other places.

+
+
+

2.1.1.4. Bidirectional communication

+

Each yield statement causes a value to be passed to the +caller. This is the reason for the introduction of generators +by PEP 255. But communication in the +reverse direction is also useful. One obvious way would be some +external state, either a global variable or a shared mutable +object. Direct communication is possible thanks to PEP 342. +It is achieved by turning the previously boring +yield statement into an expression. When the generator resumes +execution after a yield statement, the caller can call a method on +the generator object to either pass a value into the generator, +which then is returned by the yield statement, or a +different method to inject an exception into the generator.

+

The first of the new methods is send(value), which +is similar to next(), but passes value into +the generator to be used for the value of the yield expression. In +fact, g.next() and g.send(None) are equivalent.

+

The second of the new methods is +throw(type, value=None, traceback=None) +which is equivalent to:

+
raise type, value, traceback
+
+
+

at the point of the yield statement.

+

Unlike raise (which immediately raises an exception from the +current execution point), throw() first resumes the generator, and +only then raises the exception. The word throw was picked because +it is suggestive of putting the exception in another location, and is +associated with exceptions in other languages.

+

What happens when an exception is raised inside the generator? It can +be either raised explicitly or when executing some statements or it +can be injected at the point of a yield statement by means of the +throw() method. In either case, such an exception propagates in the +standard manner: it can be intercepted by an except or finally +clause, or otherwise it causes the execution of the generator function +to be aborted and propagates in the caller.

+

For completeness’ sake, it’s worth mentioning that generator iterators +also have a close() method, which can be used to +force a generator that would otherwise be able to provide more values +to finish immediately. It allows the generator __del__ +method to destroy objects holding the state of generator. +Let’s define a generator which just prints what is passed in through +send and throw.

+
>>> import itertools
+
>>> def g(): +
... print('--start--') +
... for i in itertools.count(): +
... print('--yielding %i--' % i) +
... try: +
... ans = yield i +
... except GeneratorExit: +
... print('--closing--') +
... raise +
... except Exception as e: +
... print('--yield raised %r--' % e) +
... else: +
... print('--yield returned %s--' % ans) +
+
>>> it = g() +
>>> next(it) +
--start-- +
--yielding 0-- +
0 +
>>> it.send(11) +
--yield returned 11-- +
--yielding 1-- +
1 +
>>> it.throw(IndexError) +
--yield raised IndexError()-- +
--yielding 2-- +
2 +
>>> it.close() +
--closing-- +
+
+
+
+

2.1.1.5. Chaining generators

+
+

Note

+

This is a preview of PEP 380 (not yet implemented, but accepted +for Python 3.3).

+
+

Let’s say we are writing a generator and we want to yield a number of +values generated by a second generator, a subgenerator. +If yielding of values is the only concern, this can be performed +without much difficulty using a loop such as

+
subgen = some_other_generator()
+
for v in subgen: +
yield v +
+
+

However, if the subgenerator is to interact properly with the caller +in the case of calls to send(), throw() and close(), +things become considerably more difficult. The yield statement has +to be guarded by a try..except..finally structure +similar to the one defined in the previous section to “debug” the +generator function. Such code is provided in PEP 380#id13, here it +suffices to say that new syntax to properly yield from a subgenerator +is being introduced in Python 3.3:

+
yield from some_other_generator()
+
+
+

This behaves like the explicit loop above, repeatedly yielding values +from some_other_generator until it is exhausted, but also forwards +send, throw and close to the subgenerator.

+
+
+
+

2.1.2. Decorators

+ +

Since functions and classes are objects, they can be passed +around. Since they are mutable objects, they can be modified. The act +of altering a function or class object after it has been constructed +but before is is bound to its name is called decorating.

+

There are two things hiding behind the name “decorator” — one is the +function which does the work of decorating, i.e. performs the real +work, and the other one is the expression adhering to the decorator +syntax, i.e. an at-symbol and the name of the decorating function.

+

Function can be decorated by using the decorator syntax for +functions:

+
@decorator             # ②
+
def function(): # ① +
pass +
+
+
    +
  • A function is defined in the standard way. ①

  • +
  • An expression starting with @ placed before the function +definition is the decorator ②. The part after @ must be a simple +expression, usually this is just the name of a function or class. This +part is evaluated first, and after the function defined below is +ready, the decorator is called with the newly defined function object +as the single argument. The value returned by the decorator is +attached to the original name of the function.

  • +
+

Decorators can be applied to functions and to classes. For +classes the semantics are identical — the original class definition +is used as an argument to call the decorator and whatever is returned +is assigned under the original name.

+

Before the decorator syntax was implemented (PEP 318), it was +possible to achieve the same effect by assigning the function or class +object to a temporary variable and then invoking the decorator +explicitly and then assigning the return value to the name of the +function. This sounds like more typing, and it is, and also the name of +the decorated function doubling as a temporary variable must be used +at least three times, which is prone to errors. Nevertheless, the +example above is equivalent to:

+
def function():                  # ①
+
pass +
function = decorator(function) # ② +
+
+

Decorators can be stacked — the order of application is +bottom-to-top, or inside-out. The semantics are such that the originally +defined function is used as an argument for the first decorator, +whatever is returned by the first decorator is used as an argument for +the second decorator, …, and whatever is returned by the last +decorator is attached under the name of the original function.

+

The decorator syntax was chosen for its readability. Since the +decorator is specified before the header of the function, it is +obvious that its is not a part of the function body and its clear that +it can only operate on the whole function. Because the expression is +prefixed with @ is stands out and is hard to miss (“in your face”, +according to the PEP :) ). When more than one decorator is applied, +each one is placed on a separate line in an easy to read way.

+
+

2.1.2.1. Replacing or tweaking the original object

+

Decorators can either return the same function or class object or they +can return a completely different object. In the first case, the +decorator can exploit the fact that function and class objects are +mutable and add attributes, e.g. add a docstring to a class. A +decorator might do something useful even without modifying the object, +for example register the decorated class in a global registry. In the +second case, virtually anything is possible: when something +different is substituted for the original function or class, the new +object can be completely different. Nevertheless, such behaviour is +not the purpose of decorators: they are intended to tweak the +decorated object, not do something unpredictable. Therefore, when a +function is “decorated” by replacing it with a different function, the +new function usually calls the original function, after doing some +preparatory work. Likewise, when a class is “decorated” by replacing +if with a new class, the new class is usually derived from the +original class. When the purpose of the decorator is to do something +“every time”, like to log every call to a decorated function, only the +second type of decorators can be used. On the other hand, if the first +type is sufficient, it is better to use it, because it is simpler.

+
+
+

2.1.2.2. Decorators implemented as classes and as functions

+

The only requirement on decorators is that they can be called with a +single argument. This means that decorators can be implemented as +normal functions, or as classes with a __call__ +method, or in theory, even as lambda functions.

+

Let’s compare the function and class approaches. The decorator +expression (the part after @) can be either just a name, or a +call. The bare-name approach is nice (less to type, looks cleaner, +etc.), but is only possible when no arguments are needed to customise +the decorator. Decorators written as functions can be used in those +two cases:

+
>>> def simple_decorator(function):
+
... print("doing decoration") +
... return function +
>>> @simple_decorator +
... def function(): +
... print("inside function") +
doing decoration +
>>> function() +
inside function +
+
>>> def decorator_with_arguments(arg): +
... print("defining the decorator") +
... def _decorator(function): +
... # in this inner function, arg is available too +
... print("doing decoration, %r" % arg) +
... return function +
... return _decorator +
>>> @decorator_with_arguments("abc") +
... def function(): +
... print("inside function") +
defining the decorator +
doing decoration, 'abc' +
>>> function() +
inside function +
+
+

The two trivial decorators above fall into the category of decorators +which return the original function. If they were to return a new +function, an extra level of nestedness would be required. +In the worst case, three levels of nested functions.

+
>>> def replacing_decorator_with_args(arg):
+
... print("defining the decorator") +
... def _decorator(function): +
... # in this inner function, arg is available too +
... print("doing decoration, %r" % arg) +
... def _wrapper(*args, **kwargs): +
... print("inside wrapper, %r %r" % (args, kwargs)) +
... return function(*args, **kwargs) +
... return _wrapper +
... return _decorator +
>>> @replacing_decorator_with_args("abc") +
... def function(*args, **kwargs): +
... print("inside function, %r %r" % (args, kwargs)) +
... return 14 +
defining the decorator +
doing decoration, 'abc' +
>>> function(11, 12) +
inside wrapper, (11, 12) {} +
inside function, (11, 12) {} +
14 +
+
+

The _wrapper function is defined to accept all positional and +keyword arguments. In general we cannot know what arguments the +decorated function is supposed to accept, so the wrapper function +just passes everything to the wrapped function. One unfortunate +consequence is that the apparent argument list is misleading.

+

Compared to decorators defined as functions, complex decorators +defined as classes are simpler. When an object is created, the +__init__ method is only allowed to return None, +and the type of the created object cannot be changed. This means that +when a decorator is defined as a class, it doesn’t make much sense to +use the argument-less form: the final decorated object would just be +an instance of the decorating class, returned by the constructor call, +which is not very useful. Therefore it’s enough to discuss class-based +decorators where arguments are given in the decorator expression and +the decorator __init__ method is used for decorator construction.

+
>>> class decorator_class(object):
+
... def __init__(self, arg): +
... # this method is called in the decorator expression +
... print("in decorator init, %s" % arg) +
... self.arg = arg +
... def __call__(self, function): +
... # this method is called to do the job +
... print("in decorator call, %s" % self.arg) +
... return function +
>>> deco_instance = decorator_class('foo') +
in decorator init, foo +
>>> @deco_instance +
... def function(*args, **kwargs): +
... print("in function, %s %s" % (args, kwargs)) +
in decorator call, foo +
>>> function() +
in function, () {} +
+
+

Contrary to normal rules (PEP 8) decorators written as classes +behave more like functions and therefore their name often starts with a +lowercase letter.

+

In reality, it doesn’t make much sense to create a new class just to +have a decorator which returns the original function. Objects are +supposed to hold state, and such decorators are more useful when the +decorator returns a new object.

+
>>> class replacing_decorator_class(object):
+
... def __init__(self, arg): +
... # this method is called in the decorator expression +
... print("in decorator init, %s" % arg) +
... self.arg = arg +
... def __call__(self, function): +
... # this method is called to do the job +
... print("in decorator call, %s" % self.arg) +
... self.function = function +
... return self._wrapper +
... def _wrapper(self, *args, **kwargs): +
... print("in the wrapper, %s %s" % (args, kwargs)) +
... return self.function(*args, **kwargs) +
>>> deco_instance = replacing_decorator_class('foo') +
in decorator init, foo +
>>> @deco_instance +
... def function(*args, **kwargs): +
... print("in function, %s %s" % (args, kwargs)) +
in decorator call, foo +
>>> function(11, 12) +
in the wrapper, (11, 12) {} +
in function, (11, 12) {} +
+
+

A decorator like this can do pretty much anything, since it can modify +the original function object and mangle the arguments, call the +original function or not, and afterwards mangle the return value.

+
+
+

2.1.2.3. Copying the docstring and other attributes of the original function

+

When a new function is returned by the decorator to replace the +original function, an unfortunate consequence is that the original +function name, the original docstring, the original argument list are +lost. Those attributes of the original function can partially be “transplanted” +to the new function by setting __doc__ (the docstring), __module__ +and __name__ (the full name of the function), and +__annotations__ (extra information about arguments and the return +value of the function available in Python 3). This can be done +automatically by using functools.update_wrapper.

+ +

One important thing is missing from the list of attributes which can +be copied to the replacement function: the argument list. The default +values for arguments can be modified through the __defaults__, +__kwdefaults__ attributes, but unfortunately the argument list +itself cannot be set as an attribute. This means that +help(function) will display a useless argument list which will be +confusing for the user of the function. An effective but ugly way +around this problem is to create the wrapper dynamically, using +eval. This can be automated by using the external decorator +module. It provides support for the decorator decorator, which takes a +wrapper and turns it into a decorator which preserves the function +signature.

+

To sum things up, decorators should always use functools.update_wrapper +or some other means of copying function attributes.

+
+
+

2.1.2.4. Examples in the standard library

+

First, it should be mentioned that there’s a number of useful +decorators available in the standard library. There are three decorators +which really form a part of the language:

+
    +
  • classmethod causes a method to become a “class method”, +which means that it can be invoked without creating an instance of +the class. When a normal method is invoked, the interpreter inserts +the instance object as the first positional parameter, +self. When a class method is invoked, the class itself is given +as the first parameter, often called cls.

    +

    Class methods are still accessible through the class’ namespace, so +they don’t pollute the module’s namespace. Class methods can be used +to provide alternative constructors:

    +
    class Array(object):
    +
    def __init__(self, data): +
    self.data = data +
    +
    @classmethod +
    def fromfile(cls, file): +
    data = numpy.load(file) +
    return cls(data) +
    +
    +

    This is cleaner than using a multitude of flags to __init__.

    +
  • +
  • staticmethod is applied to methods to make them “static”, +i.e. basically a normal function, but accessible through the class +namespace. This can be useful when the function is only needed +inside this class (its name would then be prefixed with _), or when we +want the user to think of the method as connected to the class, +despite an implementation which doesn’t require this.

  • +
  • property is the pythonic answer to the problem of getters +and setters. A method decorated with property becomes a getter +which is automatically called on attribute access.

    +
    >>> class A(object):
    +
    ... @property +
    ... def a(self): +
    ... "an important attribute" +
    ... return "a value" +
    >>> A.a +
    <property object at 0x...> +
    >>> A().a +
    'a value' +
    +
    +

    In this example, A.a is an read-only attribute. It is also +documented: help(A) includes the docstring for attribute a +taken from the getter method. Defining a as a property allows it +to be a calculated on the fly, and has the side effect of making it +read-only, because no setter is defined.

    +

    To have a setter and a getter, two methods are required, +obviously:

    +
    class Rectangle(object):
    +
    def __init__(self, edge): +
    self.edge = edge +
    +
    @property +
    def area(self): +
    """Computed area. +
    +
    Setting this updates the edge length to the proper value. +
    """ +
    return self.edge**2 +
    +
    @area.setter +
    def area(self, area): +
    self.edge = area ** 0.5 +
    +
    +

    The way that this works, is that the property decorator replaces +the getter method with a property object. This object in turn has +three methods, getter, setter, and deleter, which can be +used as decorators. Their job is to set the getter, setter and +deleter of the property object (stored as attributes fget, +fset, and fdel). The getter can be set like in the example +above, when creating the object. When defining the setter, we +already have the property object under area, and we add the +setter to it by using the setter method. All this happens when +we are creating the class.

    +

    Afterwards, when an instance of the class has been created, the +property object is special. When the interpreter executes attribute +access, assignment, or deletion, the job is delegated to the methods +of the property object.

    +

    To make everything crystal clear, let’s define a “debug” example:

    +
    >>> class D(object):
    +
    ... @property +
    ... def a(self): +
    ... print("getting 1") +
    ... return 1 +
    ... @a.setter +
    ... def a(self, value): +
    ... print("setting %r" % value) +
    ... @a.deleter +
    ... def a(self): +
    ... print("deleting") +
    >>> D.a +
    <property object at 0x...> +
    >>> D.a.fget +
    <function ...> +
    >>> D.a.fset +
    <function ...> +
    >>> D.a.fdel +
    <function ...> +
    >>> d = D() # ... varies, this is not the same `a` function +
    >>> d.a +
    getting 1 +
    1 +
    >>> d.a = 2 +
    setting 2 +
    >>> del d.a +
    deleting +
    >>> d.a +
    getting 1 +
    1 +
    +
    +

    Properties are a bit of a stretch for the decorator syntax. One of the +premises of the decorator syntax — that the name is not duplicated +— is violated, but nothing better has been invented so far. It is +just good style to use the same name for the getter, setter, and +deleter methods.

    +
  • +
+

Some newer examples include:

+ +
+
+

2.1.2.5. Deprecation of functions

+

Let’s say we want to print a deprecation warning on stderr on the +first invocation of a function we don’t like anymore. If we don’t want +to modify the function, we can use a decorator:

+
class deprecated(object):
+
"""Print a deprecation warning once on first use of the function. +
+
>>> @deprecated() # doctest: +SKIP +
... def f(): +
... pass +
>>> f() # doctest: +SKIP +
f is deprecated +
""" +
def __call__(self, func): +
self.func = func +
self.count = 0 +
return self._wrapper +
def _wrapper(self, *args, **kwargs): +
self.count += 1 +
if self.count == 1: +
print(self.func.__name__, 'is deprecated') +
return self.func(*args, **kwargs) +
+
+

It can also be implemented as a function:

+
def deprecated(func):
+
"""Print a deprecation warning once on first use of the function. +
+
>>> @deprecated # doctest: +SKIP +
... def f(): +
... pass +
>>> f() # doctest: +SKIP +
f is deprecated +
""" +
count = [0] +
def wrapper(*args, **kwargs): +
count[0] += 1 +
if count[0] == 1: +
print(func.__name__, 'is deprecated') +
return func(*args, **kwargs) +
return wrapper +
+
+
+
+

2.1.2.6. A while-loop removing decorator

+

Let’s say we have function which returns a lists of things, and this +list created by running a loop. If we don’t know how many objects will +be needed, the standard way to do this is something like:

+
def find_answers():
+
answers = [] +
while True: +
ans = look_for_next_answer() +
if ans is None: +
break +
answers.append(ans) +
return answers +
+
+

This is fine, as long as the body of the loop is fairly compact. Once +it becomes more complicated, as often happens in real code, this +becomes pretty unreadable. We could simplify this by using yield +statements, but then the user would have to explicitly call +list(find_answers()).

+

We can define a decorator which constructs the list for us:

+
def vectorized(generator_func):
+
def wrapper(*args, **kwargs): +
return list(generator_func(*args, **kwargs)) +
return functools.update_wrapper(wrapper, generator_func) +
+
+

Our function then becomes:

+
@vectorized
+
def find_answers(): +
while True: +
ans = look_for_next_answer() +
if ans is None: +
break +
yield ans +
+
+
+
+

2.1.2.7. A plugin registration system

+

This is a class decorator which doesn’t modify the class, but just +puts it in a global registry. It falls into the category of decorators +returning the original object:

+
class WordProcessor(object):
+
PLUGINS = [] +
def process(self, text): +
for plugin in self.PLUGINS: +
text = plugin().cleanup(text) +
return text +
+
@classmethod +
def plugin(cls, plugin): +
cls.PLUGINS.append(plugin) +
+
@WordProcessor.plugin +
class CleanMdashesExtension(object): +
def cleanup(self, text): +
return text.replace('&mdash;', u'\N{em dash}') +
+
+

Here we use a decorator to decentralise the registration of +plugins. We call our decorator with a noun, instead of a verb, because +we use it to declare that our class is a plugin for +WordProcessor. Method plugin simply appends the class to the +list of plugins.

+

A word about the plugin itself: it replaces HTML entity for em-dash +with a real Unicode em-dash character. It exploits the unicode +literal notation to insert a character by using its name in the +unicode database (“EM DASH”). If the Unicode character was inserted +directly, it would be impossible to distinguish it from an en-dash in +the source of a program.

+
+

See also

+

More examples and reading

+ +
+
+
+
+

2.1.3. Context managers

+

A context manager is an object with __enter__ and +__exit__ methods which can be used in the with +statement:

+
with manager as var:
+
do_something(var) +
+
+

is in the simplest case +equivalent to

+
var = manager.__enter__()
+
try: +
do_something(var) +
finally: +
manager.__exit__() +
+
+

In other words, the context manager protocol defined in PEP 343 +permits the extraction of the boring part of a +try..except..finally structure into a separate class +leaving only the interesting do_something block.

+
    +
  1. The __enter__ method is called first. It can +return a value which will be assigned to var. +The as-part is optional: if it isn’t present, the value +returned by __enter__ is simply ignored.

  2. +
  3. The block of code underneath with is executed. Just like with +try clauses, it can either execute successfully to the end, or +it can break, continue or return, or +it can throw an exception. Either way, after the block is finished, +the __exit__ method is called. +If an exception was thrown, the information about the exception is +passed to __exit__, which is described below in the next +subsection. In the normal case, exceptions can be ignored, just +like in a finally clause, and will be rethrown after +__exit__ is finished.

  4. +
+

Let’s say we want to make sure that a file is closed immediately after +we are done writing to it:

+
>>> class closing(object):
+
... def __init__(self, obj): +
... self.obj = obj +
... def __enter__(self): +
... return self.obj +
... def __exit__(self, *args): +
... self.obj.close() +
>>> with closing(open('/tmp/file', 'w')) as f: +
... f.write('the contents\n') +
+
+

Here we have made sure that the f.close() is called when the +with block is exited. Since closing files is such a common +operation, the support for this is already present in the file +class. It has an __exit__ method which calls close and can be +used as a context manager itself:

+
>>> with open('/tmp/file', 'a') as f:
+
... f.write('more contents\n') +
+
+

The common use for try..finally is releasing resources. Various +different cases are implemented similarly: in the __enter__ +phase the resource is acquired, in the __exit__ phase it is +released, and the exception, if thrown, is propagated. As with files, +there’s often a natural operation to perform after the object has been +used and it is most convenient to have the support built in. With each +release, Python provides support in more places:

+ +
+

2.1.3.1. Catching exceptions

+

When an exception is thrown in the with-block, it is passed as +arguments to __exit__. Three arguments are used, the same as +returned by sys.exc_info(): type, value, traceback. When no +exception is thrown, None is used for all three arguments. The +context manager can “swallow” the exception by returning a true value +from __exit__. Exceptions can be easily ignored, because if +__exit__ doesn’t use return and just falls of the end, +None is returned, a false value, and therefore the exception is +rethrown after __exit__ is finished.

+

The ability to catch exceptions opens interesting possibilities. A +classic example comes from unit-tests — we want to make sure that +some code throws the right kind of exception:

+
class assert_raises(object):
+
# based on pytest and unittest.TestCase +
def __init__(self, type): +
self.type = type +
def __enter__(self): +
pass +
def __exit__(self, type, value, traceback): +
if type is None: +
raise AssertionError('exception expected') +
if issubclass(type, self.type): +
return True # swallow the expected exception +
raise AssertionError('wrong exception type') +
+
with assert_raises(KeyError): +
{}['foo'] +
+
+
+
+

2.1.3.2. Using generators to define context managers

+

When discussing generators, it was said that we prefer generators to +iterators implemented as classes because they are shorter, sweeter, +and the state is stored as local, not instance, variables. On the +other hand, as described in Bidirectional communication, the flow +of data between the generator and its caller can be bidirectional. +This includes exceptions, which can be thrown into the +generator. We would like to implement context managers as special +generator functions. In fact, the generator protocol was designed to +support this use case.

+
@contextlib.contextmanager
+
def some_generator(<arguments>): +
<setup> +
try: +
yield <value> +
finally: +
<cleanup> +
+
+

The contextlib.contextmanager helper takes a generator and turns it +into a context manager. The generator has to obey some rules which are +enforced by the wrapper function — most importantly it must +yield exactly once. The part before the yield is executed from +__enter__, the block of code protected by the context manager is +executed when the generator is suspended in yield, and the rest is +executed in __exit__. If an exception is thrown, the interpreter +hands it to the wrapper through __exit__ arguments, and the +wrapper function then throws it at the point of the yield +statement. Through the use of generators, the context manager is +shorter and simpler.

+

Let’s rewrite the closing example as a generator:

+
@contextlib.contextmanager
+
def closing(obj): +
try: +
yield obj +
finally: +
obj.close() +
+
+

Let’s rewrite the assert_raises example as a generator:

+
@contextlib.contextmanager
+
def assert_raises(type): +
try: +
yield +
except type: +
return +
except Exception as value: +
raise AssertionError('wrong exception type') +
else: +
raise AssertionError('exception expected') +
+
+

Here we use a decorator to turn generator functions into context managers!

+

+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/debugging/index.html b/advanced/debugging/index.html new file mode 100644 index 000000000..df17d8c68 --- /dev/null +++ b/advanced/debugging/index.html @@ -0,0 +1,973 @@ + + + + + + + + 2.3. Debugging code — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

2.3. Debugging code

+

Author: Gaël Varoquaux

+

This section explores tools to understand better your code base: +debugging, to find and fix bugs.

+

It is not specific to the scientific Python community, but the strategies +that we will employ are tailored to its needs.

+ + +
+

2.3.1. Avoiding bugs

+
+

2.3.1.1. Coding best practices to avoid getting in trouble

+ +
    +
  • We all write buggy code. Accept it. Deal with it.

  • +
  • Write your code with testing and debugging in mind.

  • +
  • Keep It Simple, Stupid (KISS).

    +
      +
    • What is the simplest thing that could possibly work?

    • +
    +
  • +
  • Don’t Repeat Yourself (DRY).

    +
      +
    • Every piece of knowledge must have a single, unambiguous, +authoritative representation within a system.

    • +
    • Constants, algorithms, etc…

    • +
    +
  • +
  • Try to limit interdependencies of your code. (Loose Coupling)

  • +
  • Give your variables, functions and modules meaningful names (not +mathematics names)

  • +
+
+
+

2.3.1.2. pyflakes: fast static analysis

+

They are several static analysis tools in Python; to name a few:

+ +

Here we focus on pyflakes, which is the simplest tool.

+
+
    +
  • Fast, simple

  • +
  • Detects syntax errors, missing imports, typos on names.

  • +
+
+

Another good recommendation is the flake8 tool which is a combination of +pyflakes and pep8. Thus, in addition to the types of errors that pyflakes +catches, flake8 detects violations of the recommendation in PEP8 style guide.

+

Integrating pyflakes (or flake8) in your editor or IDE is highly +recommended, it does yield productivity gains.

+
+

Running pyflakes on the current edited file

+

You can bind a key to run pyflakes in the current buffer.

+
    +
  • In kate +Menu: ‘settings -> configure kate

    +
    +
      +
    • In plugins enable ‘external tools’

    • +
    • In external Tools’, add pyflakes:

      +
      kdialog --title "pyflakes %filename" --msgbox "$(pyflakes %filename)"
      +
      +
      +
    • +
    +
    +
  • +
  • In TextMate

    +

    Menu: TextMate -> Preferences -> Advanced -> Shell variables, add a +shell variable:

    +
    TM_PYCHECKER = /Library/Frameworks/Python.framework/Versions/Current/bin/pyflakes
    +
    +
    +

    Then Ctrl-Shift-V is binded to a pyflakes report

    +
  • +
  • In vim +In your .vimrc (binds F5 to pyflakes):

    +
    autocmd FileType python let &mp = 'echo "*** running % ***" ; pyflakes %'
    +
    autocmd FileType tex,mp,rst,python imap <Esc>[15~ <C-O>:make!^M +
    autocmd FileType tex,mp,rst,python map <Esc>[15~ :make!^M +
    autocmd FileType tex,mp,rst,python set autowrite +
    +
    +
  • +
  • In emacs +In your .emacs (binds F5 to pyflakes):

    +
    (defun pyflakes-thisfile () (interactive)
    +
    (compile (format "pyflakes %s" (buffer-file-name))) +
    ) +
    +
    (define-minor-mode pyflakes-mode +
    "Toggle pyflakes mode. +
    With no argument, this command toggles the mode. +
    Non-null prefix argument turns on the mode. +
    Null prefix argument turns off the mode." +
    ;; The initial value. +
    nil +
    ;; The indicator for the mode line. +
    " Pyflakes" +
    ;; The minor mode bindings. +
    '( ([f5] . pyflakes-thisfile) ) +
    ) +
    +
    (add-hook 'python-mode-hook (lambda () (pyflakes-mode t))) +
    +
    +
  • +
+
+
+

A type-as-go spell-checker like integration

+
    +
  • In vim

    +
      +
    • Use the pyflakes.vim plugin:

      +
        +
      1. download the zip file from +https://www.vim.org/scripts/script.php?script_id=2441

      2. +
      3. extract the files in ~/.vim/ftplugin/python

      4. +
      5. make sure your vimrc has filetype plugin indent on

      6. +
      +../../_images/vim_pyflakes.png +
    • +
    • Alternatively: use the syntastic +plugin. This can be configured to use flake8 too and also handles +on-the-fly checking for many other languages.

      +../../_images/vim_syntastic.png +
    • +
    +
  • +
  • In emacs

    +

    Use the flymake mode with pyflakes, documented on +https://www.emacswiki.org/emacs/FlyMake and included in Emacs 26 and +more recent. To activate it, use M-x (meta-key then x) and enter +flymake-mode at the prompt. To enable it automatically when +opening a Python file, add the following line to your .emacs file:

    +
    (add-hook 'python-mode-hook '(lambda () (flymake-mode)))
    +
    +
    +
  • +
+
+
+
+
+

2.3.2. Debugging workflow

+

If you do have a non trivial bug, this is when debugging strategies kick +in. There is no silver bullet. Yet, strategies help:

+
+

For debugging a given problem, the favorable situation is when the +problem is isolated in a small number of lines of code, outside +framework or application code, with short modify-run-fail cycles

+
+
    +
  1. Make it fail reliably. Find a test case that makes the code fail +every time.

  2. +
  3. Divide and Conquer. Once you have a failing test case, isolate the +failing code.

    +
      +
    • Which module.

    • +
    • Which function.

    • +
    • Which line of code.

    • +
    +

    => isolate a small reproducible failure: a test case

    +
  4. +
  5. Change one thing at a time and re-run the failing test case.

  6. +
  7. Use the debugger to understand what is going wrong.

  8. +
  9. Take notes and be patient. It may take a while.

  10. +
+
+

Note

+

Once you have gone through this process: isolated a tight piece of +code reproducing the bug and fix the bug using this piece of code, add +the corresponding code to your test suite.

+
+
+
+

2.3.3. Using the Python debugger

+

The python debugger, pdb: https://docs.python.org/3/library/pdb.html, +allows you to inspect your code interactively.

+

Specifically it allows you to:

+
+
    +
  • View the source code.

  • +
  • Walk up and down the call stack.

  • +
  • Inspect values of variables.

  • +
  • Modify values of variables.

  • +
  • Set breakpoints.

  • +
+
+ +
+

2.3.3.1. Invoking the debugger

+

Ways to launch the debugger:

+
    +
  1. Postmortem, launch debugger after module errors.

  2. +
  3. Launch the module with the debugger.

  4. +
  5. Call the debugger inside the module

  6. +
+
+

Postmortem

+

Situation: You’re working in IPython and you get a traceback.

+

Here we debug the file index_error.py. When running it, an +IndexError is raised. Type %debug and drop into the debugger.

+
In [1]: %run index_error.py
+
--------------------------------------------------------------------------- +
IndexError Traceback (most recent call last) +
File ~/src/scientific-python-lectures/advanced/debugging/index_error.py:10 +
6 print(lst[len(lst)]) +
9 if __name__ == "__main__": +
---> 10 index_error() +
+
File ~/src/scientific-python-lectures/advanced/debugging/index_error.py:6, in index_error() +
4 def index_error(): +
5 lst = list("foobar") +
----> 6 print(lst[len(lst)]) +
+
IndexError: list index out of range +
+
In [2]: %debug +
> /home/jarrod/src/scientific-python-lectures/advanced/debugging/index_error.py(6)index_error() +
4 def index_error(): +
5 lst = list("foobar") +
----> 6 print(lst[len(lst)]) +
7 +
8 +
+
ipdb> list +
1 """Small snippet to raise an IndexError.""" +
2 +
3 +
4 def index_error(): +
5 lst = list("foobar") +
----> 6 print(lst[len(lst)]) +
7 +
8 +
9 if __name__ == "__main__": +
10 index_error() +
+
ipdb> len(lst) +
6 +
ipdb> print(lst[len(lst) - 1]) +
r +
ipdb> quit +
+
+ +
+
+

Step-by-step execution

+

Situation: You believe a bug exists in a module but are not sure where.

+

For instance we are trying to debug wiener_filtering.py. +Indeed the code runs, but the filtering does not work well.

+
    +
  • Run the script in IPython with the debugger using %run -d +wiener_filtering.py :

    +
    In [1]: %run -d wiener_filtering.py
    +
    *** Blank or comment +
    *** Blank or comment +
    *** Blank or comment +
    NOTE: Enter 'c' at the ipdb> prompt to continue execution. +
    > /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_filtering.py(1)<module>() +
    ----> 1 """Wiener filtering a noisy raccoon face: this module is buggy""" +
    2 +
    3 import numpy as np +
    4 import scipy as sp +
    5 import matplotlib.pyplot as plt +
    +
    +
  • +
  • Set a break point at line 29 using b 29:

    +
    ipdb> n
    +
    > /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_filtering.py(3)<module>() +
    1 """Wiener filtering a noisy raccoon face: this module is buggy""" +
    2 +
    ----> 3 import numpy as np +
    4 import scipy as sp +
    5 import matplotlib.pyplot as plt +
    +
    ipdb> b 29 +
    Breakpoint 1 at /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_filtering.py:29 +
    +
    +
  • +
  • Continue execution to next breakpoint with c(ont(inue)):

    +
    ipdb> c
    +
    > /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_filtering.py(29)iterated_wiener() +
    27 Do not use this: this is crappy code to demo bugs! +
    28 """ +
    1--> 29 noisy_img = noisy_img +
    30 denoised_img = local_mean(noisy_img, size=size) +
    31 l_var = local_var(noisy_img, size=size) +
    +
    +
  • +
  • Step into code with n(ext) and s(tep): next jumps to the next +statement in the current execution context, while step will go across +execution contexts, i.e. enable exploring inside function calls:

    +
    ipdb> s
    +
    > /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_filtering.py(30)iterated_wiener() +
    28 """ +
    1 29 noisy_img = noisy_img +
    ---> 30 denoised_img = local_mean(noisy_img, size=size) +
    31 l_var = local_var(noisy_img, size=size) +
    32 for i in range(3): +
    +
    ipdb> n +
    > /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_filtering.py(31)iterated_wiener() +
    1 29 noisy_img = noisy_img +
    30 denoised_img = local_mean(noisy_img, size=size) +
    ---> 31 l_var = local_var(noisy_img, size=size) +
    32 for i in range(3): +
    33 res = noisy_img - denoised_img +
    +
    +
  • +
  • Step a few lines and explore the local variables:

    +
    ipdb> n
    +
    > /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_filtering.py(32)iterated_wiener() +
    30 denoised_img = local_mean(noisy_img, size=size) +
    31 l_var = local_var(noisy_img, size=size) +
    ---> 32 for i in range(3): +
    33 res = noisy_img - denoised_img +
    34 noise = (res**2).sum() / res.size +
    +
    ipdb> print(l_var) +
    [[2571 2782 3474 ... 3008 2922 3141] +
    [2105 708 475 ... 469 354 2884] +
    [1697 420 645 ... 273 236 2517] +
    ... +
    [2437 345 432 ... 413 387 4188] +
    [2598 179 247 ... 367 441 3909] +
    [2808 2525 3117 ... 4413 4454 4385]] +
    ipdb> print(l_var.min()) +
    0 +
    +
    +
  • +
+

Oh dear, nothing but integers, and 0 variation. Here is our bug, we are +doing integer arithmetic.

+ +
+
+

Other ways of starting a debugger

+
    +
  • Raising an exception as a poor man break point

    +

    If you find it tedious to note the line number to set a break point, +you can simply raise an exception at the point that you want to +inspect and use IPython’s %debug. Note that in this case you cannot +step or continue the execution.

    +
  • +
  • Debugging test failures using nosetests

    +

    You can run nosetests --pdb to drop in post-mortem debugging on +exceptions, and nosetests --pdb-failure to inspect test failures +using the debugger.

    +

    In addition, you can use the IPython interface for the debugger in nose +by installing the nose plugin +ipdbplugin. You can than +pass --ipdb and --ipdb-failure options to nosetests.

    +
  • +
  • Calling the debugger explicitly

    +

    Insert the following line where you want to drop in the debugger:

    +
    import pdb; pdb.set_trace()
    +
    +
    +
  • +
+
+

Warning

+

When running nosetests, the output is captured, and thus it seems +that the debugger does not work. Simply run the nosetests with the -s +flag.

+
+ +
+
+
+

2.3.3.2. Debugger commands and interaction

+ ++++ + + + + + + + + + + + + + + + + + + + + + + + + + + +

l(list)

Lists the code at the current position

u(p)

Walk up the call stack

d(own)

Walk down the call stack

n(ext)

Execute the next line (does not go down in new functions)

s(tep)

Execute the next statement (goes down in new functions)

bt

Print the call stack

a

Print the local variables

!command

Execute the given Python command (by opposition to pdb commands

+
+

Warning

+

Debugger commands are not Python code

+

You cannot name the variables the way you want. For instance, if in +you cannot override the variables in the current frame with the same +name: use different names than your local variable when typing code +in the debugger.

+
+
+

Getting help when in the debugger

+

Type h or help to access the interactive help:

+
ipdb> help
+
+
Documented commands (type help <topic>): +
======================================== +
EOF commands enable ll pp s until +
a condition exceptions longlist psource skip_hidden up +
alias cont exit n q skip_predicates w +
args context h next quit source whatis +
b continue help p r step where +
break d ignore pdef restart tbreak +
bt debug j pdoc return u +
c disable jump pfile retval unalias +
cl display l pinfo run undisplay +
clear down list pinfo2 rv unt +
+
Miscellaneous help topics: +
========================== +
exec pdb +
+
Undocumented commands: +
====================== +
interact +
+
+
+
+
+
+

2.3.4. Debugging segmentation faults using gdb

+

If you have a segmentation fault, you cannot debug it with pdb, as it +crashes the Python interpreter before it can drop in the debugger. +Similarly, if you have a bug in C code embedded in Python, pdb is +useless. For this we turn to the gnu debugger, +gdb, available on Linux.

+

Before we start with gdb, let us add a few Python-specific tools to it. +For this we add a few macros to our ~/.gdbinit. The optimal choice of +macro depends on your Python version and your gdb version. I have added a +simplified version in gdbinit, but feel free to read +DebuggingWithGdb.

+

To debug with gdb the Python script segfault.py, we can run the +script in gdb as follows

+
$ gdb python
+
... +
(gdb) run segfault.py +
Starting program: /usr/bin/python segfault.py +
[Thread debugging using libthread_db enabled] +
+
Program received signal SIGSEGV, Segmentation fault. +
_strided_byte_copy (dst=0x8537478 "\360\343G", outstrides=4, src= +
0x86c0690 <Address 0x86c0690 out of bounds>, instrides=32, N=3, +
elsize=4) +
at numpy/core/src/multiarray/ctors.c:365 +
365 _FAST_MOVE(Int32); +
(gdb) +
+
+

We get a segfault, and gdb captures it for post-mortem debugging in the C +level stack (not the Python call stack). We can debug the C call stack +using gdb’s commands:

+
(gdb) up
+
#1 0x004af4f5 in _copy_from_same_shape (dest=<value optimized out>, +
src=<value optimized out>, myfunc=0x496780 <_strided_byte_copy>, +
swap=0) +
at numpy/core/src/multiarray/ctors.c:748 +
748 myfunc(dit->dataptr, dest->strides[maxaxis], +
+
+

As you can see, right now, we are in the C code of numpy. We would like +to know what is the Python code that triggers this segfault, so we go up +the stack until we hit the Python execution loop:

+
(gdb) up
+
#8 0x080ddd23 in call_function (f= +
Frame 0x85371ec, for file /home/varoquau/usr/lib/python2.6/site-packages/numpy/core/arrayprint.py, line 156, in _leading_trailing (a=<numpy.ndarray at remote 0x85371b0>, _nc=<module at remote 0xb7f93a64>), throwflag=0) +
at ../Python/ceval.c:3750 +
3750 ../Python/ceval.c: No such file or directory. +
in ../Python/ceval.c +
+
(gdb) up +
#9 PyEval_EvalFrameEx (f= +
Frame 0x85371ec, for file /home/varoquau/usr/lib/python2.6/site-packages/numpy/core/arrayprint.py, line 156, in _leading_trailing (a=<numpy.ndarray at remote 0x85371b0>, _nc=<module at remote 0xb7f93a64>), throwflag=0) +
at ../Python/ceval.c:2412 +
2412 in ../Python/ceval.c +
(gdb) +
+
+

Once we are in the Python execution loop, we can use our special Python +helper function. For instance we can find the corresponding Python code:

+
(gdb) pyframe
+
/home/varoquau/usr/lib/python2.6/site-packages/numpy/core/arrayprint.py (158): _leading_trailing +
(gdb) +
+
+

This is numpy code, we need to go up until we find code that we have +written:

+
(gdb) up
+
... +
(gdb) up +
#34 0x080dc97a in PyEval_EvalFrameEx (f= +
Frame 0x82f064c, for file segfault.py, line 11, in print_big_array (small_array=<numpy.ndarray at remote 0x853ecf0>, big_array=<numpy.ndarray at remote 0x853ed20>), throwflag=0) at ../Python/ceval.c:1630 +
1630 ../Python/ceval.c: No such file or directory. +
in ../Python/ceval.c +
(gdb) pyframe +
segfault.py (12): print_big_array +
+
+

The corresponding code is:

+

+
def make_big_array(small_array): +
big_array = stride_tricks.as_strided( +
small_array, shape=(int(2e6), int(2e6)), strides=(32, 32) +
) +
return big_array +
+
+
+

Thus the segfault happens when printing big_array[-10:]. The reason is +simply that big_array has been allocated with its end outside the +program memory.

+
+

Note

+

For a list of Python-specific commands defined in the gdbinit, read +the source of this file.

+
+
+ +

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/index.html b/advanced/image_processing/auto_examples/index.html new file mode 100644 index 000000000..05bb15108 --- /dev/null +++ b/advanced/image_processing/auto_examples/index.html @@ -0,0 +1,258 @@ + + + + + + + + Examples for the image processing chapter — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Examples for the image processing chapter

+
+

Displaying a Raccoon Face

+
Displaying a Raccoon Face
+
+

Image interpolation

+
Image interpolation
+
+

Plot the block mean of an image

+
Plot the block mean of an image
+
+

Image manipulation and NumPy arrays

+
Image manipulation and NumPy arrays
+
+

Radial mean

+
Radial mean
+
+

Display a Raccoon Face

+
Display a Raccoon Face
+
+

Image sharpening

+
Image sharpening
+
+

Blurring of images

+
Blurring of images
+
+

Synthetic data

+
Synthetic data
+
+

Opening, erosion, and propagation

+
Opening, erosion, and propagation
+
+

Image denoising

+
Image denoising
+
+

Geometrical transformations

+
Geometrical transformations
+
+

Total Variation denoising

+
Total Variation denoising
+
+

Measurements from images

+
Measurements from images
+
+

Find the bounding box of an object

+
Find the bounding box of an object
+
+

Denoising an image with the median filter

+
Denoising an image with the median filter
+
+

Histogram segmentation

+
Histogram segmentation
+
+

Greyscale dilation

+
Greyscale dilation
+
+

Finding edges with Sobel filters

+
Finding edges with Sobel filters
+
+

Cleaning segmentation with mathematical morphology

+
Cleaning segmentation with mathematical morphology
+
+

Segmentation with Gaussian mixture models

+
Segmentation with Gaussian mixture models
+
+

Watershed segmentation

+
Watershed segmentation
+
+

Granulometry

+
Granulometry
+
+

Segmentation with spectral clustering

+
Segmentation with spectral clustering
+
+
+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_GMM.html b/advanced/image_processing/auto_examples/plot_GMM.html new file mode 100644 index 000000000..b140dcad7 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_GMM.html @@ -0,0 +1,268 @@ + + + + + + + + 2.6.8.21. Segmentation with Gaussian mixture models — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.21. Segmentation with Gaussian mixture models

+

This example performs a Gaussian mixture model analysis of the image +histogram to find the right thresholds for separating foreground from +background.

+plot GMM
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
from sklearn.mixture import GaussianMixture +
+
rng = np.random.default_rng(27446968) +
n = 10 +
l = 256 +
im = np.zeros((l, l)) +
points = l * rng.random((2, n**2)) +
im[(points[0]).astype(int), (points[1]).astype(int)] = 1 +
im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) +
+
mask = (im > im.mean()).astype(float) +
+
+
img = mask + 0.3 * rng.normal(size=mask.shape) +
+
hist, bin_edges = np.histogram(img, bins=60) +
bin_centers = 0.5 * (bin_edges[:-1] + bin_edges[1:]) +
+
classif = GaussianMixture(n_components=2) +
classif.fit(img.reshape((img.size, 1))) +
+
threshold = np.mean(classif.means_) +
binary_img = img > threshold +
+
+
plt.figure(figsize=(11, 4)) +
+
plt.subplot(131) +
plt.imshow(img) +
plt.axis("off") +
plt.subplot(132) +
plt.plot(bin_centers, hist, lw=2) +
plt.axvline(0.5, color="r", ls="--", lw=2) +
plt.text(0.57, 0.8, "histogram", fontsize=20, transform=plt.gca().transAxes) +
plt.yticks([]) +
plt.subplot(133) +
plt.imshow(binary_img, cmap="gray", interpolation="nearest") +
plt.axis("off") +
+
plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.780 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_block_mean.html b/advanced/image_processing/auto_examples/plot_block_mean.html new file mode 100644 index 000000000..c220db7b5 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_block_mean.html @@ -0,0 +1,240 @@ + + + + + + + + 2.6.8.3. Plot the block mean of an image — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.3. Plot the block mean of an image

+

An example showing how to use broad-casting to plot the mean of +blocks of an image.

+plot block mean
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
f = sp.datasets.face(gray=True) +
sx, sy = f.shape +
X, Y = np.ogrid[0:sx, 0:sy] +
+
regions = sy // 6 * (X // 4) + Y // 6 +
block_mean = sp.ndimage.mean(f, labels=regions, index=np.arange(1, regions.max() + 1)) +
block_mean.shape = (sx // 4, sy // 6) +
+
plt.figure(figsize=(5, 5)) +
plt.imshow(block_mean, cmap="gray") +
plt.axis("off") +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.190 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_blur.html b/advanced/image_processing/auto_examples/plot_blur.html new file mode 100644 index 000000000..8279c24de --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_blur.html @@ -0,0 +1,244 @@ + + + + + + + + 2.6.8.8. Blurring of images — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.8. Blurring of images

+

An example showing various processes that blur an image.

+plot blur
import scipy as sp
+
import matplotlib.pyplot as plt +
+
face = sp.datasets.face(gray=True) +
blurred_face = sp.ndimage.gaussian_filter(face, sigma=3) +
very_blurred = sp.ndimage.gaussian_filter(face, sigma=5) +
local_mean = sp.ndimage.uniform_filter(face, size=11) +
+
plt.figure(figsize=(9, 3)) +
plt.subplot(131) +
plt.imshow(blurred_face, cmap="gray") +
plt.axis("off") +
plt.subplot(132) +
plt.imshow(very_blurred, cmap="gray") +
plt.axis("off") +
plt.subplot(133) +
plt.imshow(local_mean, cmap="gray") +
plt.axis("off") +
+
plt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.01, right=0.99) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.282 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_clean_morpho.html b/advanced/image_processing/auto_examples/plot_clean_morpho.html new file mode 100644 index 000000000..87b6a68c7 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_clean_morpho.html @@ -0,0 +1,268 @@ + + + + + + + + 2.6.8.20. Cleaning segmentation with mathematical morphology — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.20. Cleaning segmentation with mathematical morphology

+

An example showing how to clean segmentation with mathematical +morphology: removing small regions and holes.

+plot clean morpho
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
rng = np.random.default_rng(27446968) +
n = 10 +
l = 256 +
im = np.zeros((l, l)) +
points = l * rng.random((2, n**2)) +
im[(points[0]).astype(int), (points[1]).astype(int)] = 1 +
im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) +
+
mask = (im > im.mean()).astype(float) +
+
+
img = mask + 0.3 * rng.normal(size=mask.shape) +
+
binary_img = img > 0.5 +
+
# Remove small white regions +
open_img = sp.ndimage.binary_opening(binary_img) +
# Remove small black hole +
close_img = sp.ndimage.binary_closing(open_img) +
+
plt.figure(figsize=(12, 3)) +
+
l = 128 +
+
plt.subplot(141) +
plt.imshow(binary_img[:l, :l], cmap="gray") +
plt.axis("off") +
plt.subplot(142) +
plt.imshow(open_img[:l, :l], cmap="gray") +
plt.axis("off") +
plt.subplot(143) +
plt.imshow(close_img[:l, :l], cmap="gray") +
plt.axis("off") +
plt.subplot(144) +
plt.imshow(mask[:l, :l], cmap="gray") +
plt.contour(close_img[:l, :l], [0.5], linewidths=2, colors="r") +
plt.axis("off") +
+
plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.087 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_denoising.html b/advanced/image_processing/auto_examples/plot_denoising.html new file mode 100644 index 000000000..d7d9940ed --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_denoising.html @@ -0,0 +1,259 @@ + + + + + + + + 2.6.8.16. Denoising an image with the median filter — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.16. Denoising an image with the median filter

+

This example shows the original image, the noisy image, the denoised +one (with the median filter) and the difference between the two.

+Original image, Noisy image, Median filter, Error
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
rng = np.random.default_rng(27446968) +
+
im = np.zeros((20, 20)) +
im[5:-5, 5:-5] = 1 +
im = sp.ndimage.distance_transform_bf(im) +
im_noise = im + 0.2 * rng.normal(size=im.shape) +
+
im_med = sp.ndimage.median_filter(im_noise, 3) +
+
plt.figure(figsize=(16, 5)) +
+
plt.subplot(141) +
plt.imshow(im, interpolation="nearest") +
plt.axis("off") +
plt.title("Original image", fontsize=20) +
plt.subplot(142) +
plt.imshow(im_noise, interpolation="nearest", vmin=0, vmax=5) +
plt.axis("off") +
plt.title("Noisy image", fontsize=20) +
plt.subplot(143) +
plt.imshow(im_med, interpolation="nearest", vmin=0, vmax=5) +
plt.axis("off") +
plt.title("Median filter", fontsize=20) +
plt.subplot(144) +
plt.imshow(np.abs(im - im_med), cmap="hot", interpolation="nearest") +
plt.axis("off") +
plt.title("Error", fontsize=20) +
+
+
plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.131 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_display_face.html b/advanced/image_processing/auto_examples/plot_display_face.html new file mode 100644 index 000000000..27d6cc7d6 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_display_face.html @@ -0,0 +1,243 @@ + + + + + + + + 2.6.8.6. Display a Raccoon Face — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.6. Display a Raccoon Face

+

An example that displays a raccoon face with matplotlib.

+plot display face
import scipy as sp
+
import matplotlib.pyplot as plt +
+
f = sp.datasets.face(gray=True) +
+
plt.figure(figsize=(10, 3.6)) +
+
plt.subplot(131) +
plt.imshow(f, cmap="gray") +
+
plt.subplot(132) +
plt.imshow(f, cmap="gray", vmin=30, vmax=200) +
plt.axis("off") +
+
plt.subplot(133) +
plt.imshow(f, cmap="gray") +
plt.contour(f, [50, 200]) +
plt.axis("off") +
+
plt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.05, right=0.99) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.341 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_face.html b/advanced/image_processing/auto_examples/plot_face.html new file mode 100644 index 000000000..2d189c0ac --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_face.html @@ -0,0 +1,232 @@ + + + + + + + + 2.6.8.1. Displaying a Raccoon Face — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.1. Displaying a Raccoon Face

+

Small example to plot a raccoon face.

+plot face
import scipy as sp
+
import imageio.v3 as iio +
+
f = sp.datasets.face() +
iio.imwrite("face.png", f) # uses the Image module (PIL) +
+
import matplotlib.pyplot as plt +
+
plt.imshow(f) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.533 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_face_denoise.html b/advanced/image_processing/auto_examples/plot_face_denoise.html new file mode 100644 index 000000000..451da0cf8 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_face_denoise.html @@ -0,0 +1,254 @@ + + + + + + + + 2.6.8.11. Image denoising — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.11. Image denoising

+

This example demoes image denoising on a Raccoon face.

+noisy, Gaussian filter, Median filter
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
rng = np.random.default_rng(27446968) +
+
f = sp.datasets.face(gray=True) +
f = f[230:290, 220:320] +
+
noisy = f + 0.4 * f.std() * rng.random(f.shape) +
+
gauss_denoised = sp.ndimage.gaussian_filter(noisy, 2) +
med_denoised = sp.ndimage.median_filter(noisy, 3) +
+
+
plt.figure(figsize=(12, 2.8)) +
+
plt.subplot(131) +
plt.imshow(noisy, cmap="gray", vmin=40, vmax=220) +
plt.axis("off") +
plt.title("noisy", fontsize=20) +
plt.subplot(132) +
plt.imshow(gauss_denoised, cmap="gray", vmin=40, vmax=220) +
plt.axis("off") +
plt.title("Gaussian filter", fontsize=20) +
plt.subplot(133) +
plt.imshow(med_denoised, cmap="gray", vmin=40, vmax=220) +
plt.axis("off") +
plt.title("Median filter", fontsize=20) +
+
plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.201 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_face_tv_denoise.html b/advanced/image_processing/auto_examples/plot_face_tv_denoise.html new file mode 100644 index 000000000..58afa9450 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_face_tv_denoise.html @@ -0,0 +1,257 @@ + + + + + + + + 2.6.8.13. Total Variation denoising — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.13. Total Variation denoising

+

This example demoes Total-Variation (TV) denoising on a Raccoon face.

+noisy, TV denoising, (more) TV denoising
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
from skimage.restoration import denoise_tv_chambolle +
+
rng = np.random.default_rng(27446968) +
+
f = sp.datasets.face(gray=True) +
f = f[230:290, 220:320] +
+
noisy = f + 0.4 * f.std() * rng.random(f.shape) +
+
tv_denoised = denoise_tv_chambolle(noisy, weight=10) +
+
+
plt.figure(figsize=(12, 2.8)) +
+
plt.subplot(131) +
plt.imshow(noisy, cmap="gray", vmin=40, vmax=220) +
plt.axis("off") +
plt.title("noisy", fontsize=20) +
plt.subplot(132) +
plt.imshow(tv_denoised, cmap="gray", vmin=40, vmax=220) +
plt.axis("off") +
plt.title("TV denoising", fontsize=20) +
+
tv_denoised = denoise_tv_chambolle(noisy, weight=50) +
plt.subplot(133) +
plt.imshow(tv_denoised, cmap="gray", vmin=40, vmax=220) +
plt.axis("off") +
plt.title("(more) TV denoising", fontsize=20) +
+
plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.215 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_find_edges.html b/advanced/image_processing/auto_examples/plot_find_edges.html new file mode 100644 index 000000000..9b9715ae8 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_find_edges.html @@ -0,0 +1,267 @@ + + + + + + + + 2.6.8.19. Finding edges with Sobel filters — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.19. Finding edges with Sobel filters

+

The Sobel filter is one of the simplest way of finding edges.

+square, Sobel (x direction), Sobel filter, Sobel for noisy image
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
rng = np.random.default_rng(27446968) +
+
im = np.zeros((256, 256)) +
im[64:-64, 64:-64] = 1 +
+
im = sp.ndimage.rotate(im, 15, mode="constant") +
im = sp.ndimage.gaussian_filter(im, 8) +
+
sx = sp.ndimage.sobel(im, axis=0, mode="constant") +
sy = sp.ndimage.sobel(im, axis=1, mode="constant") +
sob = np.hypot(sx, sy) +
+
plt.figure(figsize=(16, 5)) +
plt.subplot(141) +
plt.imshow(im, cmap="gray") +
plt.axis("off") +
plt.title("square", fontsize=20) +
plt.subplot(142) +
plt.imshow(sx) +
plt.axis("off") +
plt.title("Sobel (x direction)", fontsize=20) +
plt.subplot(143) +
plt.imshow(sob) +
plt.axis("off") +
plt.title("Sobel filter", fontsize=20) +
+
im += 0.07 * rng.random(im.shape) +
+
sx = sp.ndimage.sobel(im, axis=0, mode="constant") +
sy = sp.ndimage.sobel(im, axis=1, mode="constant") +
sob = np.hypot(sx, sy) +
+
plt.subplot(144) +
plt.imshow(sob) +
plt.axis("off") +
plt.title("Sobel for noisy image", fontsize=20) +
+
+
plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=0.9) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.203 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_find_object.html b/advanced/image_processing/auto_examples/plot_find_object.html new file mode 100644 index 000000000..72a32686e --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_find_object.html @@ -0,0 +1,256 @@ + + + + + + + + 2.6.8.15. Find the bounding box of an object — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.15. Find the bounding box of an object

+

This example shows how to extract the bounding box of the largest object

+plot find object
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
rng = np.random.default_rng(27446968) +
n = 10 +
l = 256 +
im = np.zeros((l, l)) +
points = l * rng.random((2, n**2)) +
im[(points[0]).astype(int), (points[1]).astype(int)] = 1 +
im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) +
+
mask = im > im.mean() +
+
label_im, nb_labels = sp.ndimage.label(mask) +
+
# Find the largest connected component +
sizes = sp.ndimage.sum(mask, label_im, range(nb_labels + 1)) +
mask_size = sizes < 1000 +
remove_pixel = mask_size[label_im] +
label_im[remove_pixel] = 0 +
labels = np.unique(label_im) +
label_im = np.searchsorted(labels, label_im) +
+
# Now that we have only one connected component, extract it's bounding box +
slice_x, slice_y = sp.ndimage.find_objects(label_im == 4)[0] +
roi = im[slice_x, slice_y] +
+
plt.figure(figsize=(4, 2)) +
plt.axes((0, 0, 1, 1)) +
plt.imshow(roi) +
plt.axis("off") +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.020 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_geom_face.html b/advanced/image_processing/auto_examples/plot_geom_face.html new file mode 100644 index 000000000..f6deca687 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_geom_face.html @@ -0,0 +1,258 @@ + + + + + + + + 2.6.8.12. Geometrical transformations — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.12. Geometrical transformations

+

This examples demos some simple geometrical transformations on a Raccoon face.

+plot geom face
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
face = sp.datasets.face(gray=True) +
lx, ly = face.shape +
# Cropping +
crop_face = face[lx // 4 : -lx // 4, ly // 4 : -ly // 4] +
# up <-> down flip +
flip_ud_face = np.flipud(face) +
# rotation +
rotate_face = sp.ndimage.rotate(face, 45) +
rotate_face_noreshape = sp.ndimage.rotate(face, 45, reshape=False) +
+
plt.figure(figsize=(12.5, 2.5)) +
+
+
plt.subplot(151) +
plt.imshow(face, cmap="gray") +
plt.axis("off") +
plt.subplot(152) +
plt.imshow(crop_face, cmap="gray") +
plt.axis("off") +
plt.subplot(153) +
plt.imshow(flip_ud_face, cmap="gray") +
plt.axis("off") +
plt.subplot(154) +
plt.imshow(rotate_face, cmap="gray") +
plt.axis("off") +
plt.subplot(155) +
plt.imshow(rotate_face_noreshape, cmap="gray") +
plt.axis("off") +
+
plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.468 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_granulo.html b/advanced/image_processing/auto_examples/plot_granulo.html new file mode 100644 index 000000000..b6579773e --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_granulo.html @@ -0,0 +1,273 @@ + + + + + + + + 2.6.8.23. Granulometry — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.23. Granulometry

+

This example performs a simple granulometry analysis.

+plot granulo
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
+
def disk_structure(n): +
struct = np.zeros((2 * n + 1, 2 * n + 1)) +
x, y = np.indices((2 * n + 1, 2 * n + 1)) +
mask = (x - n) ** 2 + (y - n) ** 2 <= n**2 +
struct[mask] = 1 +
return struct.astype(bool) +
+
+
def granulometry(data, sizes=None): +
s = max(data.shape) +
if sizes is None: +
sizes = range(1, s / 2, 2) +
granulo = [ +
sp.ndimage.binary_opening(data, structure=disk_structure(n)).sum() +
for n in sizes +
] +
return granulo +
+
+
rng = np.random.default_rng(27446968) +
n = 10 +
l = 256 +
im = np.zeros((l, l)) +
points = l * rng.random((2, n**2)) +
im[(points[0]).astype(int), (points[1]).astype(int)] = 1 +
im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) +
+
mask = im > im.mean() +
+
granulo = granulometry(mask, sizes=np.arange(2, 19, 4)) +
+
plt.figure(figsize=(6, 2.2)) +
+
plt.subplot(121) +
plt.imshow(mask, cmap="gray") +
opened = sp.ndimage.binary_opening(mask, structure=disk_structure(10)) +
opened_more = sp.ndimage.binary_opening(mask, structure=disk_structure(14)) +
plt.contour(opened, [0.5], colors="b", linewidths=2) +
plt.contour(opened_more, [0.5], colors="r", linewidths=2) +
plt.axis("off") +
plt.subplot(122) +
plt.plot(np.arange(2, 19, 4), granulo, "ok", ms=8) +
+
+
plt.subplots_adjust(wspace=0.02, hspace=0.15, top=0.95, bottom=0.15, left=0, right=0.95) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.250 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_greyscale_dilation.html b/advanced/image_processing/auto_examples/plot_greyscale_dilation.html new file mode 100644 index 000000000..4c80a8a85 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_greyscale_dilation.html @@ -0,0 +1,254 @@ + + + + + + + + 2.6.8.18. Greyscale dilation — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.18. Greyscale dilation

+

This example illustrates greyscale mathematical morphology.

+plot greyscale dilation
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
im = np.zeros((64, 64)) +
rng = np.random.default_rng(27446968) +
x, y = (63 * rng.random((2, 8))).astype(int) +
im[x, y] = np.arange(8) +
+
bigger_points = sp.ndimage.grey_dilation(im, size=(5, 5), structure=np.ones((5, 5))) +
+
square = np.zeros((16, 16)) +
square[4:-4, 4:-4] = 1 +
dist = sp.ndimage.distance_transform_bf(square) +
dilate_dist = sp.ndimage.grey_dilation(dist, size=(3, 3), structure=np.ones((3, 3))) +
+
plt.figure(figsize=(12.5, 3)) +
plt.subplot(141) +
plt.imshow(im, interpolation="nearest", cmap="nipy_spectral") +
plt.axis("off") +
plt.subplot(142) +
plt.imshow(bigger_points, interpolation="nearest", cmap="nipy_spectral") +
plt.axis("off") +
plt.subplot(143) +
plt.imshow(dist, interpolation="nearest", cmap="nipy_spectral") +
plt.axis("off") +
plt.subplot(144) +
plt.imshow(dilate_dist, interpolation="nearest", cmap="nipy_spectral") +
plt.axis("off") +
+
plt.subplots_adjust(wspace=0, hspace=0.02, top=0.99, bottom=0.01, left=0.01, right=0.99) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.060 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_histo_segmentation.html b/advanced/image_processing/auto_examples/plot_histo_segmentation.html new file mode 100644 index 000000000..778c700e6 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_histo_segmentation.html @@ -0,0 +1,261 @@ + + + + + + + + 2.6.8.17. Histogram segmentation — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.17. Histogram segmentation

+

This example does simple histogram analysis to perform segmentation.

+plot histo segmentation
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
rng = np.random.default_rng(27446968) +
n = 10 +
l = 256 +
im = np.zeros((l, l)) +
points = l * rng.random((2, n**2)) +
im[(points[0]).astype(int), (points[1]).astype(int)] = 1 +
im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) +
+
mask = (im > im.mean()).astype(float) +
+
mask += 0.1 * im +
+
img = mask + 0.2 * rng.normal(size=mask.shape) +
+
hist, bin_edges = np.histogram(img, bins=60) +
bin_centers = 0.5 * (bin_edges[:-1] + bin_edges[1:]) +
+
binary_img = img > 0.5 +
+
plt.figure(figsize=(11, 4)) +
+
plt.subplot(131) +
plt.imshow(img) +
plt.axis("off") +
plt.subplot(132) +
plt.plot(bin_centers, hist, lw=2) +
plt.axvline(0.5, color="r", ls="--", lw=2) +
plt.text(0.57, 0.8, "histogram", fontsize=20, transform=plt.gca().transAxes) +
plt.yticks([]) +
plt.subplot(133) +
plt.imshow(binary_img, cmap="gray", interpolation="nearest") +
plt.axis("off") +
+
plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.110 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_interpolation_face.html b/advanced/image_processing/auto_examples/plot_interpolation_face.html new file mode 100644 index 000000000..c9b5269a4 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_interpolation_face.html @@ -0,0 +1,239 @@ + + + + + + + + 2.6.8.2. Image interpolation — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.2. Image interpolation

+

The example demonstrates image interpolation on a Raccoon face.

+plot interpolation face
import scipy as sp
+
import matplotlib.pyplot as plt +
+
f = sp.datasets.face(gray=True) +
+
plt.figure(figsize=(8, 4)) +
+
plt.subplot(1, 2, 1) +
plt.imshow(f[320:340, 510:530], cmap="gray") +
plt.axis("off") +
+
plt.subplot(1, 2, 2) +
plt.imshow(f[320:340, 510:530], cmap="gray", interpolation="nearest") +
plt.axis("off") +
+
plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.157 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_measure_data.html b/advanced/image_processing/auto_examples/plot_measure_data.html new file mode 100644 index 000000000..7da7ce8a4 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_measure_data.html @@ -0,0 +1,257 @@ + + + + + + + + 2.6.8.14. Measurements from images — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.14. Measurements from images

+

This examples shows how to measure quantities from various images.

+plot measure data
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
rng = np.random.default_rng(27446968) +
n = 10 +
l = 256 +
im = np.zeros((l, l)) +
points = l * rng.random((2, n**2)) +
im[(points[0]).astype(int), (points[1]).astype(int)] = 1 +
im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) +
+
mask = im > im.mean() +
+
label_im, nb_labels = sp.ndimage.label(mask) +
+
sizes = sp.ndimage.sum(mask, label_im, range(nb_labels + 1)) +
mask_size = sizes < 1000 +
remove_pixel = mask_size[label_im] +
label_im[remove_pixel] = 0 +
labels = np.unique(label_im) +
label_clean = np.searchsorted(labels, label_im) +
+
+
plt.figure(figsize=(6, 3)) +
+
plt.subplot(121) +
plt.imshow(label_im, cmap="nipy_spectral") +
plt.axis("off") +
plt.subplot(122) +
plt.imshow(label_clean, vmax=nb_labels, cmap="nipy_spectral") +
plt.axis("off") +
+
plt.subplots_adjust(wspace=0.01, hspace=0.01, top=1, bottom=0, left=0, right=1) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.044 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_numpy_array.html b/advanced/image_processing/auto_examples/plot_numpy_array.html new file mode 100644 index 000000000..c8d14b2c8 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_numpy_array.html @@ -0,0 +1,243 @@ + + + + + + + + 2.6.8.4. Image manipulation and NumPy arrays — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.4. Image manipulation and NumPy arrays

+

This example shows how to do image manipulation using common NumPy arrays +tricks.

+plot numpy array
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
face = sp.datasets.face(gray=True) +
face[10:13, 20:23] +
face[100:120] = 255 +
+
lx, ly = face.shape +
X, Y = np.ogrid[0:lx, 0:ly] +
mask = (X - lx / 2) ** 2 + (Y - ly / 2) ** 2 > lx * ly / 4 +
face[mask] = 0 +
face[range(400), range(400)] = 255 +
+
plt.figure(figsize=(3, 3)) +
plt.axes((0, 0, 1, 1)) +
plt.imshow(face, cmap="gray") +
plt.axis("off") +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.162 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_propagation.html b/advanced/image_processing/auto_examples/plot_propagation.html new file mode 100644 index 000000000..335178bb3 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_propagation.html @@ -0,0 +1,250 @@ + + + + + + + + 2.6.8.10. Opening, erosion, and propagation — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.10. Opening, erosion, and propagation

+

This example shows simple operations of mathematical morphology.

+plot propagation
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
square = np.zeros((32, 32)) +
square[10:-10, 10:-10] = 1 +
rng = np.random.default_rng(27446968) +
x, y = (32 * rng.random((2, 20))).astype(int) +
square[x, y] = 1 +
+
open_square = sp.ndimage.binary_opening(square) +
+
eroded_square = sp.ndimage.binary_erosion(square) +
reconstruction = sp.ndimage.binary_propagation(eroded_square, mask=square) +
+
plt.figure(figsize=(9.5, 3)) +
plt.subplot(131) +
plt.imshow(square, cmap="gray", interpolation="nearest") +
plt.axis("off") +
plt.subplot(132) +
plt.imshow(open_square, cmap="gray", interpolation="nearest") +
plt.axis("off") +
plt.subplot(133) +
plt.imshow(reconstruction, cmap="gray", interpolation="nearest") +
plt.axis("off") +
+
plt.subplots_adjust(wspace=0, hspace=0.02, top=0.99, bottom=0.01, left=0.01, right=0.99) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.045 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_radial_mean.html b/advanced/image_processing/auto_examples/plot_radial_mean.html new file mode 100644 index 000000000..60f31a24d --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_radial_mean.html @@ -0,0 +1,242 @@ + + + + + + + + 2.6.8.5. Radial mean — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.5. Radial mean

+

This example shows how to do a radial mean with scikit-image.

+plot radial mean
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
f = sp.datasets.face(gray=True) +
sx, sy = f.shape +
X, Y = np.ogrid[0:sx, 0:sy] +
+
+
r = np.hypot(X - sx / 2, Y - sy / 2) +
+
rbin = (20 * r / r.max()).astype(int) +
radial_mean = sp.ndimage.mean(f, labels=rbin, index=np.arange(1, rbin.max() + 1)) +
+
plt.figure(figsize=(5, 5)) +
plt.axes((0, 0, 1, 1)) +
plt.imshow(rbin, cmap="nipy_spectral") +
plt.axis("off") +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.176 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_sharpen.html b/advanced/image_processing/auto_examples/plot_sharpen.html new file mode 100644 index 000000000..b5000f664 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_sharpen.html @@ -0,0 +1,248 @@ + + + + + + + + 2.6.8.7. Image sharpening — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.7. Image sharpening

+

This example shows how to sharpen an image in noiseless situation by +applying the filter inverse to the blur.

+plot sharpen
import scipy as sp
+
import matplotlib.pyplot as plt +
+
f = sp.datasets.face(gray=True).astype(float) +
blurred_f = sp.ndimage.gaussian_filter(f, 3) +
+
filter_blurred_f = sp.ndimage.gaussian_filter(blurred_f, 1) +
+
alpha = 30 +
sharpened = blurred_f + alpha * (blurred_f - filter_blurred_f) +
+
plt.figure(figsize=(12, 4)) +
+
plt.subplot(131) +
plt.imshow(f, cmap="gray") +
plt.axis("off") +
plt.subplot(132) +
plt.imshow(blurred_f, cmap="gray") +
plt.axis("off") +
plt.subplot(133) +
plt.imshow(sharpened, cmap="gray") +
plt.axis("off") +
+
plt.tight_layout() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.419 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_spectral_clustering.html b/advanced/image_processing/auto_examples/plot_spectral_clustering.html new file mode 100644 index 000000000..ab62f0a8c --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_spectral_clustering.html @@ -0,0 +1,277 @@ + + + + + + + + 2.6.8.24. Segmentation with spectral clustering — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.24. Segmentation with spectral clustering

+

This example uses spectral clustering to do segmentation.

+
import numpy as np
+
import matplotlib.pyplot as plt +
+
from sklearn.feature_extraction import image +
from sklearn.cluster import spectral_clustering +
+
+
l = 100
+
x, y = np.indices((l, l)) +
+
center1 = (28, 24) +
center2 = (40, 50) +
center3 = (67, 58) +
center4 = (24, 70) +
+
radius1, radius2, radius3, radius4 = 16, 14, 15, 14 +
+
circle1 = (x - center1[0]) ** 2 + (y - center1[1]) ** 2 < radius1**2 +
circle2 = (x - center2[0]) ** 2 + (y - center2[1]) ** 2 < radius2**2 +
circle3 = (x - center3[0]) ** 2 + (y - center3[1]) ** 2 < radius3**2 +
circle4 = (x - center4[0]) ** 2 + (y - center4[1]) ** 2 < radius4**2 +
+
+

4 circles

+
img = circle1 + circle2 + circle3 + circle4
+
mask = img.astype(bool) +
img = img.astype(float) +
+
rng = np.random.default_rng(27446968) +
img += 1 + 0.2 * rng.normal(size=img.shape) +
+
# Convert the image into a graph with the value of the gradient on the +
# edges. +
graph = image.img_to_graph(img, mask=mask) +
+
# Take a decreasing function of the gradient: we take it weakly +
# dependent from the gradient the segmentation is close to a voronoi +
graph.data = np.exp(-graph.data / graph.data.std()) +
+
# Force the solver to be arpack, since amg is numerically +
# unstable on this example +
labels = spectral_clustering(graph, n_clusters=4) +
label_im = -np.ones(mask.shape) +
label_im[mask] = labels +
+
plt.figure(figsize=(6, 3)) +
plt.subplot(121) +
plt.imshow(img, cmap="nipy_spectral", interpolation="nearest") +
plt.axis("off") +
plt.subplot(122) +
plt.imshow(label_im, cmap="nipy_spectral", interpolation="nearest") +
plt.axis("off") +
+
plt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.01, right=0.99) +
plt.show() +
+
+plot spectral clustering

Total running time of the script: (0 minutes 0.182 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_synthetic_data.html b/advanced/image_processing/auto_examples/plot_synthetic_data.html new file mode 100644 index 000000000..4823a3df4 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_synthetic_data.html @@ -0,0 +1,252 @@ + + + + + + + + 2.6.8.9. Synthetic data — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.9. Synthetic data

+

The example generates and displays simple synthetic data.

+plot synthetic data
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
rng = np.random.default_rng(27446968) +
n = 10 +
l = 256 +
im = np.zeros((l, l)) +
points = l * rng.random((2, n**2)) +
im[(points[0]).astype(int), (points[1]).astype(int)] = 1 +
im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) +
+
mask = im > im.mean() +
+
label_im, nb_labels = sp.ndimage.label(mask) +
+
plt.figure(figsize=(9, 3)) +
+
plt.subplot(131) +
plt.imshow(im) +
plt.axis("off") +
plt.subplot(132) +
plt.imshow(mask, cmap="gray") +
plt.axis("off") +
plt.subplot(133) +
plt.imshow(label_im, cmap="nipy_spectral") +
plt.axis("off") +
+
plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.081 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_watershed_segmentation.html b/advanced/image_processing/auto_examples/plot_watershed_segmentation.html new file mode 100644 index 000000000..ef3275785 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_watershed_segmentation.html @@ -0,0 +1,258 @@ + + + + + + + + 2.6.8.22. Watershed segmentation — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.6.8.22. Watershed segmentation

+

This example shows how to do segmentation with watershed.

+plot watershed segmentation
import numpy as np
+
from skimage.segmentation import watershed +
from skimage.feature import peak_local_max +
import matplotlib.pyplot as plt +
import scipy as sp +
+
# Generate an initial image with two overlapping circles +
x, y = np.indices((80, 80)) +
x1, y1, x2, y2 = 28, 28, 44, 52 +
r1, r2 = 16, 20 +
mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1**2 +
mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2**2 +
image = np.logical_or(mask_circle1, mask_circle2) +
# Now we want to separate the two objects in image +
# Generate the markers as local maxima of the distance +
# to the background +
distance = sp.ndimage.distance_transform_edt(image) +
peak_idx = peak_local_max(distance, footprint=np.ones((3, 3)), labels=image) +
peak_mask = np.zeros_like(distance, dtype=bool) +
peak_mask[tuple(peak_idx.T)] = True +
markers = sp.ndimage.label(peak_mask)[0] +
labels = watershed(-distance, markers, mask=image) +
+
plt.figure(figsize=(9, 3.5)) +
plt.subplot(131) +
plt.imshow(image, cmap="gray", interpolation="nearest") +
plt.axis("off") +
plt.subplot(132) +
plt.imshow(-distance, interpolation="nearest") +
plt.axis("off") +
plt.subplot(133) +
plt.imshow(labels, cmap="nipy_spectral", interpolation="nearest") +
plt.axis("off") +
+
plt.subplots_adjust(hspace=0.01, wspace=0.01, top=1, bottom=0, left=0, right=1) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.064 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/sg_execution_times.html b/advanced/image_processing/auto_examples/sg_execution_times.html new file mode 100644 index 000000000..188ba92fb --- /dev/null +++ b/advanced/image_processing/auto_examples/sg_execution_times.html @@ -0,0 +1,298 @@ + + + + + + + + Computation times — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Computation times

+

00:05.201 total execution time for 24 files from advanced/image_processing/auto_examples:

+
+ + + + + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Example

Time

Mem (MB)

Segmentation with Gaussian mixture models (plot_GMM.py)

00:00.780

0.0

Displaying a Raccoon Face (plot_face.py)

00:00.533

0.0

Geometrical transformations (plot_geom_face.py)

00:00.468

0.0

Image sharpening (plot_sharpen.py)

00:00.419

0.0

Display a Raccoon Face (plot_display_face.py)

00:00.341

0.0

Blurring of images (plot_blur.py)

00:00.282

0.0

Granulometry (plot_granulo.py)

00:00.250

0.0

Total Variation denoising (plot_face_tv_denoise.py)

00:00.215

0.0

Finding edges with Sobel filters (plot_find_edges.py)

00:00.203

0.0

Image denoising (plot_face_denoise.py)

00:00.201

0.0

Plot the block mean of an image (plot_block_mean.py)

00:00.190

0.0

Segmentation with spectral clustering (plot_spectral_clustering.py)

00:00.182

0.0

Radial mean (plot_radial_mean.py)

00:00.176

0.0

Image manipulation and NumPy arrays (plot_numpy_array.py)

00:00.162

0.0

Image interpolation (plot_interpolation_face.py)

00:00.157

0.0

Denoising an image with the median filter (plot_denoising.py)

00:00.131

0.0

Histogram segmentation (plot_histo_segmentation.py)

00:00.110

0.0

Cleaning segmentation with mathematical morphology (plot_clean_morpho.py)

00:00.087

0.0

Synthetic data (plot_synthetic_data.py)

00:00.081

0.0

Watershed segmentation (plot_watershed_segmentation.py)

00:00.064

0.0

Greyscale dilation (plot_greyscale_dilation.py)

00:00.060

0.0

Opening, erosion, and propagation (plot_propagation.py)

00:00.045

0.0

Measurements from images (plot_measure_data.py)

00:00.044

0.0

Find the bounding box of an object (plot_find_object.py)

00:00.020

0.0

+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/image_processing/index.html b/advanced/image_processing/index.html new file mode 100644 index 000000000..7e453f397 --- /dev/null +++ b/advanced/image_processing/index.html @@ -0,0 +1,1106 @@ + + + + + + + + 2.6. Image manipulation and processing using NumPy and SciPy — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

2.6. Image manipulation and processing using NumPy and SciPy

+

Authors: Emmanuelle Gouillart, Gaël Varoquaux

+

This section addresses basic image manipulation and processing using the +core scientific modules NumPy and SciPy. Some of the operations covered +by this tutorial may be useful for other kinds of multidimensional array +processing than image processing. In particular, the submodule +scipy.ndimage provides functions operating on n-dimensional NumPy +arrays.

+
+

See also

+

For more advanced image processing and image-specific routines, see the +tutorial scikit-image: image processing, dedicated to the skimage module.

+
+ +

Tools used in this tutorial:

+
    +
  • numpy: basic array manipulation

  • +
  • scipy: scipy.ndimage submodule dedicated to image processing +(n-dimensional images). See the documentation:

    +
    >>> import scipy as sp
    +
    +
    +
  • +
+

Common tasks in image processing:

+
    +
  • Input/Output, displaying images

  • +
  • Basic manipulations: cropping, flipping, rotating, …

  • +
  • Image filtering: denoising, sharpening

  • +
  • Image segmentation: labeling pixels corresponding to different objects

  • +
  • Classification

  • +
  • Feature extraction

  • +
  • Registration

  • +
  • +
+ +
+

2.6.1. Opening and writing to image files

+

Writing an array to a file:

+
import scipy as sp
+
import imageio.v3 as iio +
+
f = sp.datasets.face() +
iio.imwrite("face.png", f) # uses the Image module (PIL) +
+
import matplotlib.pyplot as plt +
+
plt.imshow(f) +
plt.show() +
+
+../../_images/face.png + +

Creating a NumPy array from an image file:

+
>>> import imageio.v3 as iio
+
>>> face = sp.datasets.face() +
>>> iio.imwrite('face.png', face) # First we need to create the PNG file +
+
>>> face = iio.imread('face.png') +
>>> type(face) +
<class 'numpy.ndarray'> +
>>> face.shape, face.dtype +
((768, 1024, 3), dtype('uint8')) +
+
+

dtype is uint8 for 8-bit images (0-255)

+

Opening raw files (camera, 3-D images)

+
>>> face.tofile('face.raw') # Create raw file
+
>>> face_from_raw = np.fromfile('face.raw', dtype=np.uint8) +
>>> face_from_raw.shape +
(2359296,) +
>>> face_from_raw.shape = (768, 1024, 3) +
+
+

Need to know the shape and dtype of the image (how to separate data +bytes).

+

For large data, use np.memmap for memory mapping:

+
>>> face_memmap = np.memmap('face.raw', dtype=np.uint8, shape=(768, 1024, 3))
+
+
+

(data are read from the file, and not loaded into memory)

+

Working on a list of image files

+
>>> rng = np.random.default_rng(27446968)
+
>>> for i in range(10): +
... im = rng.integers(0, 256, 10000, dtype=np.uint8).reshape((100, 100)) +
... iio.imwrite(f'random_{i:02d}.png', im) +
>>> from glob import glob +
>>> filelist = glob('random*.png') +
>>> filelist.sort() +
+
+
+
+

2.6.2. Displaying images

+

Use matplotlib and imshow to display an image inside a +matplotlib figure:

+
>>> f = sp.datasets.face(gray=True)  # retrieve a grayscale image
+
>>> import matplotlib.pyplot as plt +
>>> plt.imshow(f, cmap=plt.cm.gray) +
<matplotlib.image.AxesImage object at 0x...> +
+
+

Increase contrast by setting min and max values:

+
>>> plt.imshow(f, cmap=plt.cm.gray, vmin=30, vmax=200)
+
<matplotlib.image.AxesImage object at 0x...> +
>>> # Remove axes and ticks +
>>> plt.axis('off') +
(np.float64(-0.5), np.float64(1023.5), np.float64(767.5), np.float64(-0.5)) +
+
+

Draw contour lines:

+
>>> plt.contour(f, [50, 200])
+
<matplotlib.contour.QuadContourSet ...> +
+
+
+../../_images/sphx_glr_plot_display_face_001.png + +
+

[Python source code]

+

For smooth intensity variations, use interpolation='bilinear'. For fine inspection of intensity variations, use +interpolation='nearest':

+
>>> plt.imshow(f[320:340, 510:530], cmap=plt.cm.gray, interpolation='bilinear')
+
<matplotlib.image.AxesImage object at 0x...> +
>>> plt.imshow(f[320:340, 510:530], cmap=plt.cm.gray, interpolation='nearest') +
<matplotlib.image.AxesImage object at 0x...> +
+
+
+../../_images/sphx_glr_plot_interpolation_face_001.png + +
+

[Python source code]

+
+

See also

+

More interpolation methods are in Matplotlib’s examples.

+
+
+
+

2.6.3. Basic manipulations

+

Images are arrays: use the whole numpy machinery.

+../../_images/axis_convention.png + +
>>> face = sp.datasets.face(gray=True)
+
>>> face[0, 40] +
np.uint8(127) +
>>> # Slicing +
>>> face[10:13, 20:23] +
array([[141, 153, 145], +
[133, 134, 125], +
[ 96, 92, 94]], dtype=uint8) +
>>> face[100:120] = 255 +
>>> +
>>> lx, ly = face.shape +
>>> X, Y = np.ogrid[0:lx, 0:ly] +
>>> mask = (X - lx / 2) ** 2 + (Y - ly / 2) ** 2 > lx * ly / 4 +
>>> # Masks +
>>> face[mask] = 0 +
>>> # Fancy indexing +
>>> face[range(400), range(400)] = 255 +
+
+
+../../_images/sphx_glr_plot_numpy_array_001.png + +
+

[Python source code]

+
+

2.6.3.1. Statistical information

+
>>> face = sp.datasets.face(gray=True)
+
>>> face.mean() +
np.float64(113.48026784261067) +
>>> face.max(), face.min() +
(np.uint8(250), np.uint8(0)) +
+
+

np.histogram

+ +
+
+

2.6.3.2. Geometrical transformations

+
>>> face = sp.datasets.face(gray=True)
+
>>> lx, ly = face.shape +
>>> # Cropping +
>>> crop_face = face[lx // 4: - lx // 4, ly // 4: - ly // 4] +
>>> # up <-> down flip +
>>> flip_ud_face = np.flipud(face) +
>>> # rotation +
>>> rotate_face = sp.ndimage.rotate(face, 45) +
>>> rotate_face_noreshape = sp.ndimage.rotate(face, 45, reshape=False) +
+
+
+../../_images/sphx_glr_plot_geom_face_001.png + +
+

[Python source code]

+
+
+
+

2.6.4. Image filtering

+

Local filters: replace the value of pixels by a function of the values of +neighboring pixels.

+

Neighbourhood: square (choose size), disk, or more complicated structuring +element.

+
+../../_images/kernels.png + +
+
+

2.6.4.1. Blurring/smoothing

+

Gaussian filter from scipy.ndimage:

+
>>> face = sp.datasets.face(gray=True)
+
>>> blurred_face = sp.ndimage.gaussian_filter(face, sigma=3) +
>>> very_blurred = sp.ndimage.gaussian_filter(face, sigma=5) +
+
+

Uniform filter

+
>>> local_mean = sp.ndimage.uniform_filter(face, size=11)
+
+
+
+../../_images/sphx_glr_plot_blur_001.png + +
+

[Python source code]

+
+
+

2.6.4.2. Sharpening

+

Sharpen a blurred image:

+
>>> face = sp.datasets.face(gray=True).astype(float)
+
>>> blurred_f = sp.ndimage.gaussian_filter(face, 3) +
+
+

increase the weight of edges by adding an approximation of the +Laplacian:

+
>>> filter_blurred_f = sp.ndimage.gaussian_filter(blurred_f, 1)
+
>>> alpha = 30 +
>>> sharpened = blurred_f + alpha * (blurred_f - filter_blurred_f) +
+
+
+../../_images/sphx_glr_plot_sharpen_001.png + +
+

[Python source code]

+
+
+

2.6.4.3. Denoising

+

Noisy face:

+
>>> f = sp.datasets.face(gray=True)
+
>>> f = f[230:290, 220:320] +
>>> rng = np.random.default_rng() +
>>> noisy = f + 0.4 * f.std() * rng.random(f.shape) +
+
+

A Gaussian filter smoothes the noise out… and the edges as well:

+
>>> gauss_denoised = sp.ndimage.gaussian_filter(noisy, 2)
+
+
+

Most local linear isotropic filters blur the image (scipy.ndimage.uniform_filter)

+

A median filter preserves better the edges:

+
>>> med_denoised = sp.ndimage.median_filter(noisy, 3)
+
+
+
+../../_images/sphx_glr_plot_face_denoise_001.png + +
+

[Python source code]

+

Median filter: better result for straight boundaries (low curvature):

+
>>> im = np.zeros((20, 20))
+
>>> im[5:-5, 5:-5] = 1 +
>>> im = sp.ndimage.distance_transform_bf(im) +
>>> rng = np.random.default_rng() +
>>> im_noise = im + 0.2 * rng.standard_normal(im.shape) +
>>> im_med = sp.ndimage.median_filter(im_noise, 3) +
+
+
+../../_images/sphx_glr_plot_denoising_001.png + +
+

[Python source code]

+

Other rank filter: scipy.ndimage.maximum_filter, +scipy.ndimage.percentile_filter

+

Other local non-linear filters: Wiener (scipy.signal.wiener), etc.

+

Non-local filters

+ +
+

See also

+

More denoising filters are available in skimage.denoising, +see the scikit-image: image processing tutorial.

+
+
+
+

2.6.4.4. Mathematical morphology

+

See wikipedia +for a definition of mathematical morphology.

+

Probe an image with a simple shape (a structuring element), and +modify this image according to how the shape locally fits or misses the +image.

+

Structuring element:

+
>>> el = sp.ndimage.generate_binary_structure(2, 1)
+
>>> el +
array([[False, True, False], +
[ True, True, True], +
[False, True, False]]) +
>>> el.astype(int) +
array([[0, 1, 0], +
[1, 1, 1], +
[0, 1, 0]]) +
+
+
+../../_images/diamond_kernel.png +
+

Erosion = minimum filter. Replace the value of a pixel by the minimal value covered by the structuring element.:

+
>>> a = np.zeros((7,7), dtype=int)
+
>>> a[1:6, 2:5] = 1 +
>>> a +
array([[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 1, 1, 1, 0, 0], +
[0, 0, 1, 1, 1, 0, 0], +
[0, 0, 1, 1, 1, 0, 0], +
[0, 0, 1, 1, 1, 0, 0], +
[0, 0, 1, 1, 1, 0, 0], +
[0, 0, 0, 0, 0, 0, 0]]) +
>>> sp.ndimage.binary_erosion(a).astype(a.dtype) +
array([[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 1, 0, 0, 0], +
[0, 0, 0, 1, 0, 0, 0], +
[0, 0, 0, 1, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0]]) +
>>> # Erosion removes objects smaller than the structure +
>>> sp.ndimage.binary_erosion(a, structure=np.ones((5,5))).astype(a.dtype) +
array([[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0]]) +
+
+../../_images/morpho_mat.png +

Dilation: maximum filter:

+
>>> a = np.zeros((5, 5))
+
>>> a[2, 2] = 1 +
>>> a +
array([[0., 0., 0., 0., 0.], +
[0., 0., 0., 0., 0.], +
[0., 0., 1., 0., 0.], +
[0., 0., 0., 0., 0.], +
[0., 0., 0., 0., 0.]]) +
>>> sp.ndimage.binary_dilation(a).astype(a.dtype) +
array([[0., 0., 0., 0., 0.], +
[0., 0., 1., 0., 0.], +
[0., 1., 1., 1., 0.], +
[0., 0., 1., 0., 0.], +
[0., 0., 0., 0., 0.]]) +
+
+

Also works for grey-valued images:

+
>>> rng = np.random.default_rng(27446968)
+
>>> im = np.zeros((64, 64)) +
>>> x, y = (63*rng.random((2, 8))).astype(int) +
>>> im[x, y] = np.arange(8) +
+
>>> bigger_points = sp.ndimage.grey_dilation(im, size=(5, 5), structure=np.ones((5, 5))) +
+
>>> square = np.zeros((16, 16)) +
>>> square[4:-4, 4:-4] = 1 +
>>> dist = sp.ndimage.distance_transform_bf(square) +
>>> dilate_dist = sp.ndimage.grey_dilation(dist, size=(3, 3), \ +
... structure=np.ones((3, 3))) +
+
+
+../../_images/sphx_glr_plot_greyscale_dilation_001.png + +
+

[Python source code]

+

Opening: erosion + dilation:

+
>>> a = np.zeros((5,5), dtype=int)
+
>>> a[1:4, 1:4] = 1; a[4, 4] = 1 +
>>> a +
array([[0, 0, 0, 0, 0], +
[0, 1, 1, 1, 0], +
[0, 1, 1, 1, 0], +
[0, 1, 1, 1, 0], +
[0, 0, 0, 0, 1]]) +
>>> # Opening removes small objects +
>>> sp.ndimage.binary_opening(a, structure=np.ones((3,3))).astype(int) +
array([[0, 0, 0, 0, 0], +
[0, 1, 1, 1, 0], +
[0, 1, 1, 1, 0], +
[0, 1, 1, 1, 0], +
[0, 0, 0, 0, 0]]) +
>>> # Opening can also smooth corners +
>>> sp.ndimage.binary_opening(a).astype(int) +
array([[0, 0, 0, 0, 0], +
[0, 0, 1, 0, 0], +
[0, 1, 1, 1, 0], +
[0, 0, 1, 0, 0], +
[0, 0, 0, 0, 0]]) +
+
+

Application: remove noise:

+
>>> square = np.zeros((32, 32))
+
>>> square[10:-10, 10:-10] = 1 +
>>> rng = np.random.default_rng(27446968) +
>>> x, y = (32*rng.random((2, 20))).astype(int) +
>>> square[x, y] = 1 +
+
>>> open_square = sp.ndimage.binary_opening(square) +
+
>>> eroded_square = sp.ndimage.binary_erosion(square) +
>>> reconstruction = sp.ndimage.binary_propagation(eroded_square, mask=square) +
+
+
+../../_images/sphx_glr_plot_propagation_001.png + +
+

[Python source code]

+

Closing: dilation + erosion

+

Many other mathematical morphology operations: hit and miss transform, tophat, +etc.

+
+
+
+

2.6.5. Feature extraction

+
+

2.6.5.1. Edge detection

+

Synthetic data:

+
>>> im = np.zeros((256, 256))
+
>>> im[64:-64, 64:-64] = 1 +
>>> +
>>> im = sp.ndimage.rotate(im, 15, mode='constant') +
>>> im = sp.ndimage.gaussian_filter(im, 8) +
+
+

Use a gradient operator (Sobel) to find high intensity variations:

+
>>> sx = sp.ndimage.sobel(im, axis=0, mode='constant')
+
>>> sy = sp.ndimage.sobel(im, axis=1, mode='constant') +
>>> sob = np.hypot(sx, sy) +
+
+
+../../_images/sphx_glr_plot_find_edges_001.png + +
+

[Python source code]

+
+
+

2.6.5.2. Segmentation

+
    +
  • Histogram-based segmentation (no spatial information)

  • +
+
>>> n = 10
+
>>> l = 256 +
>>> im = np.zeros((l, l)) +
>>> rng = np.random.default_rng(27446968) +
>>> points = l*rng.random((2, n**2)) +
>>> im[(points[0]).astype(int), (points[1]).astype(int)] = 1 +
>>> im = sp.ndimage.gaussian_filter(im, sigma=l/(4.*n)) +
+
>>> mask = (im > im.mean()).astype(float) +
>>> mask += 0.1 * im +
>>> img = mask + 0.2*rng.standard_normal(mask.shape) +
+
>>> hist, bin_edges = np.histogram(img, bins=60) +
>>> bin_centers = 0.5*(bin_edges[:-1] + bin_edges[1:]) +
+
>>> binary_img = img > 0.5 +
+
+
+../../_images/sphx_glr_plot_histo_segmentation_001.png + +
+

[Python source code]

+

Use mathematical morphology to clean up the result:

+
>>> # Remove small white regions
+
>>> open_img = sp.ndimage.binary_opening(binary_img) +
>>> # Remove small black hole +
>>> close_img = sp.ndimage.binary_closing(open_img) +
+
+
+../../_images/sphx_glr_plot_clean_morpho_001.png + +
+

[Python source code]

+ + +
+

See also

+

More advanced segmentation algorithms are found in the +scikit-image: see scikit-image: image processing.

+
+
+

See also

+

Other Scientific Packages provide algorithms that can be useful for +image processing. In this example, we use the spectral clustering +function of the scikit-learn in order to segment glued objects.

+
>>> from sklearn.feature_extraction import image
+
>>> from sklearn.cluster import spectral_clustering +
+
>>> l = 100 +
>>> x, y = np.indices((l, l)) +
+
>>> center1 = (28, 24) +
>>> center2 = (40, 50) +
>>> center3 = (67, 58) +
>>> center4 = (24, 70) +
>>> radius1, radius2, radius3, radius4 = 16, 14, 15, 14 +
+
>>> circle1 = (x - center1[0])**2 + (y - center1[1])**2 < radius1**2 +
>>> circle2 = (x - center2[0])**2 + (y - center2[1])**2 < radius2**2 +
>>> circle3 = (x - center3[0])**2 + (y - center3[1])**2 < radius3**2 +
>>> circle4 = (x - center4[0])**2 + (y - center4[1])**2 < radius4**2 +
+
>>> # 4 circles +
>>> img = circle1 + circle2 + circle3 + circle4 +
>>> mask = img.astype(bool) +
>>> img = img.astype(float) +
+
>>> rng = np.random.default_rng() +
>>> img += 1 + 0.2*rng.standard_normal(img.shape) +
>>> # Convert the image into a graph with the value of the gradient on +
>>> # the edges. +
>>> graph = image.img_to_graph(img, mask=mask) +
+
>>> # Take a decreasing function of the gradient: we take it weakly +
>>> # dependent from the gradient the segmentation is close to a voronoi +
>>> graph.data = np.exp(-graph.data/graph.data.std()) +
+
>>> labels = spectral_clustering(graph, n_clusters=4, eigen_solver='arpack') +
>>> label_im = -np.ones(mask.shape) +
>>> label_im[mask] = labels +
+
+../../_images/image_spectral_clustering.png +
+
+
+
+

2.6.6. Measuring objects properties: scipy.ndimage.measurements

+

Synthetic data:

+
>>> n = 10
+
>>> l = 256 +
>>> im = np.zeros((l, l)) +
>>> rng = np.random.default_rng(27446968) +
>>> points = l * rng.random((2, n**2)) +
>>> im[(points[0]).astype(int), (points[1]).astype(int)] = 1 +
>>> im = sp.ndimage.gaussian_filter(im, sigma=l/(4.*n)) +
>>> mask = im > im.mean() +
+
+
    +
  • Analysis of connected components

  • +
+

Label connected components: scipy.dimage.label:

+
>>> label_im, nb_labels = sp.ndimage.label(mask)
+
>>> nb_labels # how many regions? +
28 +
>>> plt.imshow(label_im) +
<matplotlib.image.AxesImage object at 0x...> +
+
+
+../../_images/sphx_glr_plot_synthetic_data_001.png + +
+

[Python source code]

+

Compute size, mean_value, etc. of each region:

+
>>> sizes = sp.ndimage.sum(mask, label_im, range(nb_labels + 1))
+
>>> mean_vals = sp.ndimage.sum(im, label_im, range(1, nb_labels + 1)) +
+
+

Clean up small connect components:

+
>>> mask_size = sizes < 1000
+
>>> remove_pixel = mask_size[label_im] +
>>> remove_pixel.shape +
(256, 256) +
>>> label_im[remove_pixel] = 0 +
>>> plt.imshow(label_im) +
<matplotlib.image.AxesImage object at 0x...> +
+
+

Now reassign labels with np.searchsorted:

+
>>> labels = np.unique(label_im)
+
>>> label_im = np.searchsorted(labels, label_im) +
+
+
+../../_images/sphx_glr_plot_measure_data_001.png + +
+

[Python source code]

+

Find region of interest enclosing object:

+
>>> slice_x, slice_y = sp.ndimage.find_objects(label_im)[3]
+
>>> roi = im[slice_x, slice_y] +
>>> plt.imshow(roi) +
<matplotlib.image.AxesImage object at 0x...> +
+
+
+../../_images/sphx_glr_plot_find_object_001.png + +
+

[Python source code]

+

Other spatial measures: scipy.ndimage.center_of_mass, +scipy.ndimage.maximum_position, etc.

+

Can be used outside the limited scope of segmentation applications.

+

Example: block mean:

+
>>> f = sp.datasets.face(gray=True)
+
>>> sx, sy = f.shape +
>>> X, Y = np.ogrid[0:sx, 0:sy] +
>>> regions = (sy//6) * (X//4) + (Y//6) # note that we use broadcasting +
>>> block_mean = sp.ndimage.mean(f, labels=regions, index=np.arange(1, +
... regions.max() +1)) +
>>> block_mean.shape = (sx // 4, sy // 6) +
+
+
+../../_images/sphx_glr_plot_block_mean_001.png + +
+

[Python source code]

+

When regions are regular blocks, it is more efficient to use stride +tricks (Example: fake dimensions with strides).

+

Non-regularly-spaced blocks: radial mean:

+
>>> sx, sy = f.shape
+
>>> X, Y = np.ogrid[0:sx, 0:sy] +
>>> r = np.hypot(X - sx/2, Y - sy/2) +
>>> rbin = (20* r/r.max()).astype(int) +
>>> radial_mean = sp.ndimage.mean(f, labels=rbin, index=np.arange(1, rbin.max() +1)) +
+
+
+../../_images/sphx_glr_plot_radial_mean_001.png + +
+

[Python source code]

+
    +
  • Other measures

  • +
+

Correlation function, Fourier/wavelet spectrum, etc.

+

One example with mathematical morphology: granulometry

+
>>> def disk_structure(n):
+
... struct = np.zeros((2 * n + 1, 2 * n + 1)) +
... x, y = np.indices((2 * n + 1, 2 * n + 1)) +
... mask = (x - n)**2 + (y - n)**2 <= n**2 +
... struct[mask] = 1 +
... return struct.astype(bool) +
... +
>>> +
>>> def granulometry(data, sizes=None): +
... s = max(data.shape) +
... if sizes is None: +
... sizes = range(1, s/2, 2) +
... granulo = [sp.ndimage.binary_opening(data, \ +
... structure=disk_structure(n)).sum() for n in sizes] +
... return granulo +
... +
>>> +
>>> rng = np.random.default_rng(27446968) +
>>> n = 10 +
>>> l = 256 +
>>> im = np.zeros((l, l)) +
>>> points = l*rng.random((2, n**2)) +
>>> im[(points[0]).astype(int), (points[1]).astype(int)] = 1 +
>>> im = sp.ndimage.gaussian_filter(im, sigma=l/(4.*n)) +
>>> +
>>> mask = im > im.mean() +
>>> +
>>> granulo = granulometry(mask, sizes=np.arange(2, 19, 4)) +
+
+
+../../_images/sphx_glr_plot_granulo_001.png + +
+

[Python source code]

+
+
+

2.6.7. Full code examples

+
+
+

2.6.8. Examples for the image processing chapter

+
+

Displaying a Raccoon Face

+
Displaying a Raccoon Face
+
+

Image interpolation

+
Image interpolation
+
+

Plot the block mean of an image

+
Plot the block mean of an image
+
+

Image manipulation and NumPy arrays

+
Image manipulation and NumPy arrays
+
+

Radial mean

+
Radial mean
+
+

Display a Raccoon Face

+
Display a Raccoon Face
+
+

Image sharpening

+
Image sharpening
+
+

Blurring of images

+
Blurring of images
+
+

Synthetic data

+
Synthetic data
+
+

Opening, erosion, and propagation

+
Opening, erosion, and propagation
+
+

Image denoising

+
Image denoising
+
+

Geometrical transformations

+
Geometrical transformations
+
+

Total Variation denoising

+
Total Variation denoising
+
+

Measurements from images

+
Measurements from images
+
+

Find the bounding box of an object

+
Find the bounding box of an object
+
+

Denoising an image with the median filter

+
Denoising an image with the median filter
+
+

Histogram segmentation

+
Histogram segmentation
+
+

Greyscale dilation

+
Greyscale dilation
+
+

Finding edges with Sobel filters

+
Finding edges with Sobel filters
+
+

Cleaning segmentation with mathematical morphology

+
Cleaning segmentation with mathematical morphology
+
+

Segmentation with Gaussian mixture models

+
Segmentation with Gaussian mixture models
+
+

Watershed segmentation

+
Watershed segmentation
+
+

Granulometry

+
Granulometry
+
+

Segmentation with spectral clustering

+
Segmentation with spectral clustering
+
+
+ +

Gallery generated by Sphinx-Gallery

+
+

+
+
+

See also

+

More on image-processing:

+ +
+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/index.html b/advanced/index.html new file mode 100644 index 000000000..3a9504bda --- /dev/null +++ b/advanced/index.html @@ -0,0 +1,567 @@ + + + + + + + + 2. Advanced topics — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

2. Advanced topics

+

This part of the Scientific Python Lectures is dedicated to advanced usage. +It strives to educate the proficient Python coder to be an expert and +tackles various specific topics.

+
+

+
+
+ +
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/interfacing_with_c/interfacing_with_c.html b/advanced/interfacing_with_c/interfacing_with_c.html new file mode 100644 index 000000000..a9da03f11 --- /dev/null +++ b/advanced/interfacing_with_c/interfacing_with_c.html @@ -0,0 +1,1584 @@ + + + + + + + + 2.8. Interfacing with C — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

2.8. Interfacing with C

+

Author: Valentin Haenel

+

This chapter contains an introduction to the many different routes for +making your native code (primarily C/C++) available from Python, a +process commonly referred to wrapping. The goal of this chapter is to +give you a flavour of what technologies exist and what their respective +merits and shortcomings are, so that you can select the appropriate one +for your specific needs. In any case, once you do start wrapping, you +almost certainly will want to consult the respective documentation for +your selected technique.

+ +
+

2.8.1. Introduction

+

This chapter covers the following techniques:

+ +

These four techniques are perhaps the most well known ones, of which Cython is +probably the most advanced one and the one you should consider using first. The +others are also important, if you want to understand the wrapping problem from +different angles. Having said that, there are other alternatives out there, +but having understood the basics of the ones above, you will be in a position +to evaluate the technique of your choice to see if it fits your needs.

+

The following criteria may be useful when evaluating a technology:

+
    +
  • Are additional libraries required?

  • +
  • Is the code autogenerated?

  • +
  • Does it need to be compiled?

  • +
  • Is there good support for interacting with NumPy arrays?

  • +
  • Does it support C++?

  • +
+

Before you set out, you should consider your use case. When interfacing with +native code, there are usually two use-cases that come up:

+
    +
  • Existing code in C/C++ that needs to be leveraged, either because it already +exists, or because it is faster.

  • +
  • Python code too slow, push inner loops to native code

  • +
+

Each technology is demonstrated by wrapping the cos function from +math.h. While this is a mostly a trivial example, it should serve us well +to demonstrate the basics of the wrapping solution. Since each technique also +includes some form of NumPy support, this is also demonstrated using an +example where the cosine is computed on some kind of array.

+

Last but not least, two small warnings:

+
    +
  • All of these techniques may crash (segmentation fault) the Python +interpreter, which is (usually) due to bugs in the C code.

  • +
  • All the examples have been done on Linux, they should be possible on other +operating systems.

  • +
  • You will need a C compiler for most of the examples.

  • +
+
+
+

2.8.2. Python-C-Api

+

The Python-C-API is the backbone of the +standard Python interpreter (a.k.a CPython). Using this API it is possible to +write Python extension module in C and C++. Obviously, these extension modules +can, by virtue of language compatibility, call any function written in C or +C++.

+

When using the Python-C-API, one usually writes much boilerplate code, first to +parse the arguments that were given to a function, and later to construct the +return type.

+

Advantages

+
    +
  • Requires no additional libraries

  • +
  • Lots of low-level control

  • +
  • Entirely usable from C++

  • +
+

Disadvantages

+
    +
  • May require a substantial amount of effort

  • +
  • Much overhead in the code

  • +
  • Must be compiled

  • +
  • High maintenance cost

  • +
  • No forward compatibility across Python versions as C-API changes

  • +
  • Reference count bugs are easy to create and very hard to track down.

  • +
+
+

Note

+

The Python-C-Api example here serves mainly for didactic reasons. Many of +the other techniques actually depend on this, so it is good to have a +high-level understanding of how it works. In 99% of the use-cases you will +be better off, using an alternative technique.

+
+
+

Note

+

Since reference counting bugs are easy to create and hard to track down, +anyone really needing to use the Python C-API should read the section +about objects, types and reference counts +from the official python documentation. Additionally, there is a tool by the +name of cpychecker +which can help discover common errors with reference counting.

+
+
+

2.8.2.1. Example

+

The following C-extension module, make the cos function from the standard +math library available to Python:

+
/*  Example of wrapping cos function from math.h with the Python-C-API. */
+
+
#include <Python.h> +
#include <math.h> +
+
/* wrapped cosine function */ +
static PyObject* cos_func(PyObject* self, PyObject* args) +
{ +
double value; +
double answer; +
+
/* parse the input, from python float to c double */ +
if (!PyArg_ParseTuple(args, "d", &value)) +
return NULL; +
/* if the above function returns -1, an appropriate Python exception will +
* have been set, and the function simply returns NULL +
*/ +
+
/* call cos from libm */ +
answer = cos(value); +
+
/* construct the output from cos, from c double to python float */ +
return Py_BuildValue("f", answer); +
} +
+
/* define functions in module */ +
static PyMethodDef CosMethods[] = +
{ +
{"cos_func", cos_func, METH_VARARGS, "evaluate the cosine"}, +
{NULL, NULL, 0, NULL} +
}; +
+
#if PY_MAJOR_VERSION >= 3 +
/* module initialization */ +
/* Python version 3*/ +
static struct PyModuleDef cModPyDem = +
{ +
PyModuleDef_HEAD_INIT, +
"cos_module", "Some documentation", +
-1, +
CosMethods +
}; +
+
PyMODINIT_FUNC +
PyInit_cos_module(void) +
{ +
return PyModule_Create(&cModPyDem); +
} +
+
#else +
+
/* module initialization */ +
/* Python version 2 */ +
PyMODINIT_FUNC +
initcos_module(void) +
{ +
(void) Py_InitModule("cos_module", CosMethods); +
} +
+
#endif +
+
+

As you can see, there is much boilerplate, both to «massage» the arguments and +return types into place and for the module initialisation. Although some of +this is amortised, as the extension grows, the boilerplate required for each +function(s) remains.

+

The standard python build system, setuptools, supports compiling +C-extensions via a setup.py file:

+
from setuptools import setup, Extension
+
+
+
# define the extension module +
cos_module = Extension("cos_module", sources=["cos_module.c"]) +
+
# run the setup +
setup(ext_modules=[cos_module]) +
+
+

The setup file is called as follows:

+
$ cd advanced/interfacing_with_c/python_c_api
+
+
$ ls +
cos_module.c setup.py +
+
$ python setup.py build_ext --inplace +
running build_ext +
building 'cos_module' extension +
creating build +
creating build/temp.linux-x86_64-2.7 +
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module.c -o build/temp.linux-x86_64-2.7/cos_module.o +
gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_module.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/python_c_api/cos_module.so +
+
$ ls +
build/ cos_module.c cos_module.so setup.py +
+
+
    +
  • build_ext is to build extension modules

  • +
  • --inplace will output the compiled extension module into the current directory

  • +
+

The file cos_module.so contains the compiled extension, which we can now load in the IPython interpreter:

+
+

Note

+

In Python 3, the filename for compiled modules includes metadata on the Python +interpreter (see PEP 3149) and is thus +longer. The import statement is not affected by this.

+
+
In [1]: import cos_module
+
+
In [2]: cos_module? +
Type: module +
String Form:<module 'cos_module' from 'cos_module.so'> +
File: /home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/python_c_api/cos_module.so +
Docstring: <no docstring> +
+
In [3]: dir(cos_module) +
Out[3]: ['__doc__', '__file__', '__name__', '__package__', 'cos_func'] +
+
In [4]: cos_module.cos_func(1.0) +
Out[4]: 0.5403023058681398 +
+
In [5]: cos_module.cos_func(0.0) +
Out[5]: 1.0 +
+
In [6]: cos_module.cos_func(3.14159265359) +
Out[6]: -1.0 +
+
+

Now let’s see how robust this is:

+
In [7]: cos_module.cos_func('foo')
+
--------------------------------------------------------------------------- +
TypeError Traceback (most recent call last) +
<ipython-input-10-11bee483665d> in <module>() +
----> 1 cos_module.cos_func('foo') +
TypeError: a float is required +
+
+
+
+

2.8.2.2. NumPy Support

+

Analog to the Python-C-API, NumPy, which is itself implemented as a +C-extension, comes with the NumPy-C-API. This API can be used +to create and manipulate NumPy arrays from C, when writing a custom +C-extension. See also: Advanced NumPy.

+
+

Note

+

If you do ever need to use the NumPy C-API refer to the documentation about +Arrays and +Iterators.

+
+

The following example shows how to pass NumPy arrays as arguments to functions +and how to iterate over NumPy arrays using the (old) NumPy-C-API. It simply +takes an array as argument applies the cosine function from the math.h and +returns a resulting new array.

+
/*  Example of wrapping the cos function from math.h using the NumPy-C-API. */
+
+
#include <Python.h> +
#include <numpy/arrayobject.h> +
#include <math.h> +
+
+
/* wrapped cosine function */ +
static PyObject* cos_func_np(PyObject* self, PyObject* args) +
{ +
PyArrayObject *arrays[2]; /* holds input and output array */ +
PyObject *ret; +
NpyIter *iter; +
npy_uint32 op_flags[2]; +
npy_uint32 iterator_flags; +
PyArray_Descr *op_dtypes[2]; +
+
NpyIter_IterNextFunc *iternext; +
+
/* parse single NumPy array argument */ +
if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &arrays[0])) { +
return NULL; +
} +
+
arrays[1] = NULL; /* The result will be allocated by the iterator */ +
+
/* Set up and create the iterator */ +
iterator_flags = (NPY_ITER_ZEROSIZE_OK | +
/* +
* Enable buffering in case the input is not behaved +
* (native byte order or not aligned), +
* disabling may speed up some cases when it is known to +
* be unnecessary. +
*/ +
NPY_ITER_BUFFERED | +
/* Manually handle innermost iteration for speed: */ +
NPY_ITER_EXTERNAL_LOOP | +
NPY_ITER_GROWINNER); +
+
op_flags[0] = (NPY_ITER_READONLY | +
/* +
* Required that the arrays are well behaved, since the cos +
* call below requires this. +
*/ +
NPY_ITER_NBO | +
NPY_ITER_ALIGNED); +
+
/* Ask the iterator to allocate an array to write the output to */ +
op_flags[1] = NPY_ITER_WRITEONLY | NPY_ITER_ALLOCATE; +
+
/* +
* Ensure the iteration has the correct type, could be checked +
* specifically here. +
*/ +
op_dtypes[0] = PyArray_DescrFromType(NPY_DOUBLE); +
op_dtypes[1] = op_dtypes[0]; +
+
/* Create the NumPy iterator object: */ +
iter = NpyIter_MultiNew(2, arrays, iterator_flags, +
/* Use input order for output and iteration */ +
NPY_KEEPORDER, +
/* Allow only byte-swapping of input */ +
NPY_EQUIV_CASTING, op_flags, op_dtypes); +
Py_DECREF(op_dtypes[0]); /* The second one is identical. */ +
+
if (iter == NULL) +
return NULL; +
+
iternext = NpyIter_GetIterNext(iter, NULL); +
if (iternext == NULL) { +
NpyIter_Deallocate(iter); +
return NULL; +
} +
+
/* Fetch the output array which was allocated by the iterator: */ +
ret = (PyObject *)NpyIter_GetOperandArray(iter)[1]; +
Py_INCREF(ret); +
+
if (NpyIter_GetIterSize(iter) == 0) { +
/* +
* If there are no elements, the loop cannot be iterated. +
* This check is necessary with NPY_ITER_ZEROSIZE_OK. +
*/ +
NpyIter_Deallocate(iter); +
return ret; +
} +
+
/* The location of the data pointer which the iterator may update */ +
char **dataptr = NpyIter_GetDataPtrArray(iter); +
/* The location of the stride which the iterator may update */ +
npy_intp *strideptr = NpyIter_GetInnerStrideArray(iter); +
/* The location of the inner loop size which the iterator may update */ +
npy_intp *innersizeptr = NpyIter_GetInnerLoopSizePtr(iter); +
+
/* iterate over the arrays */ +
do { +
npy_intp stride = strideptr[0]; +
npy_intp count = *innersizeptr; +
/* out is always contiguous, so use double */ +
double *out = (double *)dataptr[1]; +
char *in = dataptr[0]; +
+
/* The output is allocated and guaranteed contiguous (out++ works): */ +
assert(strideptr[1] == sizeof(double)); +
+
/* +
* For optimization it can make sense to add a check for +
* stride == sizeof(double) to allow the compiler to optimize for that. +
*/ +
while (count--) { +
*out = cos(*(double *)in); +
out++; +
in += stride; +
} +
} while (iternext(iter)); +
+
/* Clean up and return the result */ +
NpyIter_Deallocate(iter); +
return ret; +
} +
+
+
/* define functions in module */ +
static PyMethodDef CosMethods[] = +
{ +
{"cos_func_np", cos_func_np, METH_VARARGS, +
"evaluate the cosine on a NumPy array"}, +
{NULL, NULL, 0, NULL} +
}; +
+
+
#if PY_MAJOR_VERSION >= 3 +
/* module initialization */ +
/* Python version 3*/ +
static struct PyModuleDef cModPyDem = { +
PyModuleDef_HEAD_INIT, +
"cos_module", "Some documentation", +
-1, +
CosMethods +
}; +
PyMODINIT_FUNC PyInit_cos_module_np(void) { +
PyObject *module; +
module = PyModule_Create(&cModPyDem); +
if(module==NULL) return NULL; +
/* IMPORTANT: this must be called */ +
import_array(); +
if (PyErr_Occurred()) return NULL; +
return module; +
} +
+
#else +
/* module initialization */ +
/* Python version 2 */ +
PyMODINIT_FUNC initcos_module_np(void) { +
PyObject *module; +
module = Py_InitModule("cos_module_np", CosMethods); +
if(module==NULL) return; +
/* IMPORTANT: this must be called */ +
import_array(); +
return; +
} +
+
#endif +
+
+

To compile this we can use setuptools again. However we need to be sure to +include the NumPy headers by using numpy.get_include().

+
from setuptools import setup, Extension
+
import numpy +
+
+
# define the extension module +
cos_module_np = Extension( +
"cos_module_np", sources=["cos_module_np.c"], include_dirs=[numpy.get_include()] +
) +
+
# run the setup +
setup(ext_modules=[cos_module_np]) +
+
+

To convince ourselves if this does actually works, we run the following test +script:

+
import cos_module_np
+
import numpy as np +
import matplotlib.pyplot as plt +
+
x = np.arange(0, 2 * np.pi, 0.1) +
y = cos_module_np.cos_func_np(x) +
plt.plot(x, y) +
plt.show() +
+
+
# Below are more specific tests for less common usage +
# --------------------------------------------------- +
+
# The function is OK with `x` not having any elements: +
x_empty = np.array([], dtype=np.float64) +
y_empty = cos_module_np.cos_func_np(x_empty) +
assert np.array_equal(y_empty, np.array([], dtype=np.float64)) +
+
# The function can handle arbitrary dimensions and non-contiguous data. +
# `x_2d` contains the same values, but has a different shape. +
# Note: `x_2d.flags` shows it is not contiguous and `x2.ravel() == x` +
x_2d = x.repeat(2)[::2].reshape(-1, 3) +
y_2d = cos_module_np.cos_func_np(x_2d) +
# When reshaped back, the same result is given: +
assert np.array_equal(y_2d.ravel(), y) +
+
# The function handles incorrect byte-order fine: +
x_not_native_byteorder = x.astype(x.dtype.newbyteorder()) +
y_not_native_byteorder = cos_module_np.cos_func_np(x_not_native_byteorder) +
assert np.array_equal(y_not_native_byteorder, y) +
+
# The function fails if the data type is incorrect: +
x_incorrect_dtype = x.astype(np.float32) +
try: +
cos_module_np.cos_func_np(x_incorrect_dtype) +
assert 0, "This cannot be reached." +
except TypeError: +
# A TypeError will be raised, this can be changed by changing the +
# casting rule. +
pass +
+
+

And this should result in the following figure:

+../../_images/test_cos_module_np.png + +
+
+
+

2.8.3. Ctypes

+

Ctypes is a foreign +function library for Python. It provides C compatible data types, and allows +calling functions in DLLs or shared libraries. It can be used to wrap these +libraries in pure Python.

+

Advantages

+
    +
  • Part of the Python standard library

  • +
  • Does not need to be compiled

  • +
  • Wrapping code entirely in Python

  • +
+

Disadvantages

+
    +
  • Requires code to be wrapped to be available as a shared library +(roughly speaking *.dll in Windows *.so in Linux and *.dylib in Mac OSX.)

  • +
  • No good support for C++

  • +
+
+

2.8.3.1. Example

+

As advertised, the wrapper code is in pure Python.

+
"""Example of wrapping cos function from math.h using ctypes."""
+
+
import ctypes +
+
# find and load the library +
+
# OSX or linux +
from ctypes.util import find_library +
+
libm_name = find_library("m") +
assert libm_name is not None, "Cannot find libm (math) on this system :/ That's bad." +
+
libm = ctypes.cdll.LoadLibrary(libm_name) +
+
# Windows +
# from ctypes import windll +
# libm = cdll.msvcrt +
+
+
# set the argument type +
libm.cos.argtypes = [ctypes.c_double] +
# set the return type +
libm.cos.restype = ctypes.c_double +
+
+
def cos_func(arg): +
"""Wrapper for cos from math.h""" +
return libm.cos(arg) +
+
+
    +
  • Finding and loading the library may vary depending on your operating system, +check the documentation +for details

  • +
  • This may be somewhat deceptive, since the math library exists in compiled +form on the system already. If you were to wrap a in-house library, you would +have to compile it first, which may or may not require some additional effort.

  • +
+

We may now use this, as before:

+
In [8]: import cos_module
+
+
In [9]: cos_module? +
Type: module +
String Form:<module 'cos_module' from 'cos_module.py'> +
File: /home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/ctypes/cos_module.py +
Docstring: <no docstring> +
+
In [10]: dir(cos_module) +
Out[10]: +
['__builtins__', +
'__doc__', +
'__file__', +
'__name__', +
'__package__', +
'cos_func', +
'ctypes', +
'find_library', +
'libm'] +
+
In [11]: cos_module.cos_func(1.0) +
Out[11]: 0.5403023058681398 +
+
In [12]: cos_module.cos_func(0.0) +
Out[12]: 1.0 +
+
In [13]: cos_module.cos_func(3.14159265359) +
Out[13]: -1.0 +
+
+

As with the previous example, this code is somewhat robust, although the error +message is not quite as helpful, since it does not tell us what the type should be.

+
In [14]: cos_module.cos_func('foo')
+
--------------------------------------------------------------------------- +
ArgumentError Traceback (most recent call last) +
<ipython-input-7-11bee483665d> in <module>() +
----> 1 cos_module.cos_func('foo') +
/home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/ctypes/cos_module.py in cos_func(arg) +
12 def cos_func(arg): +
13 ''' Wrapper for cos from math.h ''' +
---> 14 return libm.cos(arg) +
ArgumentError: argument 1: <type 'exceptions.TypeError'>: wrong type +
+
+
+
+

2.8.3.2. NumPy Support

+

NumPy contains some support for interfacing with ctypes. In particular there is +support for exporting certain attributes of a NumPy array as ctypes data-types +and there are functions to convert from C arrays to NumPy arrays and back.

+

For more information, consult the corresponding section in the NumPy Cookbook and the API documentation for +numpy.ndarray.ctypes +and numpy.ctypeslib.

+

For the following example, let’s consider a C function in a library that takes +an input and an output array, computes the cosine of the input array and +stores the result in the output array.

+

The library consists of the following header file (although this is not +strictly needed for this example, we list it for completeness):

+
void cos_doubles(double * in_array, double * out_array, int size);
+
+
+

The function implementation resides in the following C source file:

+
#include <math.h>
+
+
/* Compute the cosine of each element in in_array, storing the result in +
* out_array. */ +
void cos_doubles(double * in_array, double * out_array, int size){ +
int i; +
for(i=0;i<size;i++){ +
out_array[i] = cos(in_array[i]); +
} +
} +
+
+

And since the library is pure C, we can’t use setuptools to compile it, but +must use a combination of make and gcc:

+
m.PHONY : clean
+
+
libcos_doubles.so : cos_doubles.o +
gcc -shared -Wl,-soname,libcos_doubles.so -o libcos_doubles.so cos_doubles.o +
+
cos_doubles.o : cos_doubles.c +
gcc -c -fPIC cos_doubles.c -o cos_doubles.o +
+
clean : +
-rm -vf libcos_doubles.so cos_doubles.o cos_doubles.pyc +
+
+

We can then compile this (on Linux) into the shared library +libcos_doubles.so:

+
$ ls
+
cos_doubles.c cos_doubles.h cos_doubles.py makefile test_cos_doubles.py +
$ make +
gcc -c -fPIC cos_doubles.c -o cos_doubles.o +
gcc -shared -Wl,-soname,libcos_doubles.so -o libcos_doubles.so cos_doubles.o +
$ ls +
cos_doubles.c cos_doubles.o libcos_doubles.so* test_cos_doubles.py +
cos_doubles.h cos_doubles.py makefile +
+
+

Now we can proceed to wrap this library via ctypes with direct support for +(certain kinds of) NumPy arrays:

+
"""Example of wrapping a C library function that accepts a C double array as
+
input using the numpy.ctypeslib.""" +
+
import numpy as np +
import numpy.ctypeslib as npct +
from ctypes import c_int +
+
# input type for the cos_doubles function +
# must be a double array, with single dimension that is contiguous +
array_1d_double = npct.ndpointer(dtype=np.double, ndim=1, flags="CONTIGUOUS") +
+
# load the library, using NumPy mechanisms +
libcd = npct.load_library("libcos_doubles", ".") +
+
# setup the return types and argument types +
libcd.cos_doubles.restype = None +
libcd.cos_doubles.argtypes = [array_1d_double, array_1d_double, c_int] +
+
+
def cos_doubles_func(in_array, out_array): +
return libcd.cos_doubles(in_array, out_array, len(in_array)) +
+
+
    +
  • Note the inherent limitation of contiguous single dimensional NumPy arrays, +since the C functions requires this kind of buffer.

  • +
  • Also note that the output array must be preallocated, for example with +numpy.zeros() and the function will write into it’s buffer.

  • +
  • Although the original signature of the cos_doubles function is ARRAY, +ARRAY, int the final cos_doubles_func takes only two NumPy arrays as +arguments.

  • +
+

And, as before, we convince ourselves that it worked:

+
import numpy as np
+
import matplotlib.pyplot as plt +
import cos_doubles +
+
x = np.arange(0, 2 * np.pi, 0.1) +
y = np.empty_like(x) +
+
cos_doubles.cos_doubles_func(x, y) +
plt.plot(x, y) +
plt.show() +
+
+../../_images/test_cos_doubles.png + +
+
+
+

2.8.4. SWIG

+

SWIG, the Simplified Wrapper Interface Generator, +is a software development tool that connects programs written in C and C++ +with a variety of high-level programming languages, including Python. The +important thing with SWIG is, that it can autogenerate the wrapper code for you. +While this is an advantage in terms of development time, it can also be a +burden. The generated file tend to be quite large and may not be too human +readable and the multiple levels of indirection which are a result of +the wrapping process, may be a bit tricky to understand.

+
+

Note

+

The autogenerated C code uses the Python-C-Api.

+
+

Advantages

+
    +
  • Can automatically wrap entire libraries given the headers

  • +
  • Works nicely with C++

  • +
+

Disadvantages

+
    +
  • Autogenerates enormous files

  • +
  • Hard to debug if something goes wrong

  • +
  • Steep learning curve

  • +
+
+

2.8.4.1. Example

+

Let’s imagine that our cos function lives in a cos_module which has +been written in c and consists of the source file cos_module.c:

+
#include <math.h>
+
+
double cos_func(double arg){ +
return cos(arg); +
} +
+
+

and the header file cos_module.h:

+
double cos_func(double arg);
+
+
+

And our goal is to expose the cos_func to Python. To achieve this with +SWIG, we must write an interface file which contains the instructions for SWIG.

+
/*  Example of wrapping cos function from math.h using SWIG. */
+
+
%module cos_module +
%{ +
/* the resulting C file should be built as a python extension */ +
#define SWIG_FILE_WITH_INIT +
/* Includes the header in the wrapper code */ +
#include "cos_module.h" +
%} +
/* Parse the header file to generate wrappers */ +
%include "cos_module.h" +
+
+

As you can see, not too much code is needed here. For this simple example it is +enough to simply include the header file in the interface file, to expose the +function to Python. However, SWIG does allow for more fine grained +inclusion/exclusion of functions found in header files, check the documentation +for details.

+

Generating the compiled wrappers is a two stage process:

+
    +
  1. Run the swig executable on the interface file to generate the files +cos_module_wrap.c, which is the source file for the autogenerated Python +C-extension and cos_module.py, which is the autogenerated pure python +module.

  2. +
  3. Compile the cos_module_wrap.c into the _cos_module.so. Luckily, +setuptools knows how to handle SWIG interface files, so that our +setup.py is simply:

  4. +
+
from setuptools import setup, Extension
+
+
+
setup(ext_modules=[Extension("_cos_module", sources=["cos_module.c", "cos_module.i"])]) +
+
+
$ cd advanced/interfacing_with_c/swig
+
+
$ ls +
cos_module.c cos_module.h cos_module.i setup.py +
+
$ python setup.py build_ext --inplace +
running build_ext +
building '_cos_module' extension +
swigging cos_module.i to cos_module_wrap.c +
swig -python -o cos_module_wrap.c cos_module.i +
creating build +
creating build/temp.linux-x86_64-2.7 +
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module.c -o build/temp.linux-x86_64-2.7/cos_module.o +
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module_wrap.c -o build/temp.linux-x86_64-2.7/cos_module_wrap.o +
gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_module.o build/temp.linux-x86_64-2.7/cos_module_wrap.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/swig/_cos_module.so +
+
$ ls +
build/ cos_module.c cos_module.h cos_module.i cos_module.py _cos_module.so* cos_module_wrap.c setup.py +
+
+

We can now load and execute the cos_module as we have done in the previous examples:

+
In [15]: import cos_module
+
+
In [16]: cos_module? +
Type: module +
String Form:<module 'cos_module' from 'cos_module.py'> +
File: /home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/swig/cos_module.py +
Docstring: <no docstring> +
+
In [17]: dir(cos_module) +
Out[17]: +
['__builtins__', +
'__doc__', +
'__file__', +
'__name__', +
'__package__', +
'_cos_module', +
'_newclass', +
'_object', +
'_swig_getattr', +
'_swig_property', +
'_swig_repr', +
'_swig_setattr', +
'_swig_setattr_nondynamic', +
'cos_func'] +
+
In [18]: cos_module.cos_func(1.0) +
Out[18]: 0.5403023058681398 +
+
In [19]: cos_module.cos_func(0.0) +
Out[19]: 1.0 +
+
In [20]: cos_module.cos_func(3.14159265359) +
Out[20]: -1.0 +
+
+

Again we test for robustness, and we see that we get a better error message +(although, strictly speaking in Python there is no double type):

+
In [21]: cos_module.cos_func('foo')
+
--------------------------------------------------------------------------- +
TypeError Traceback (most recent call last) +
<ipython-input-7-11bee483665d> in <module>() +
----> 1 cos_module.cos_func('foo') +
TypeError: in method 'cos_func', argument 1 of type 'double' +
+
+
+
+

2.8.4.2. NumPy Support

+

NumPy provides support for SWIG with the numpy.i +file. This interface file defines various so-called typemaps which support +conversion between NumPy arrays and C-Arrays. In the following example we will +take a quick look at how such typemaps work in practice.

+

We have the same cos_doubles function as in the ctypes example:

+
void cos_doubles(double * in_array, double * out_array, int size);
+
+
+
#include <math.h>
+
+
/* Compute the cosine of each element in in_array, storing the result in +
* out_array. */ +
void cos_doubles(double * in_array, double * out_array, int size){ +
int i; +
for(i=0;i<size;i++){ +
out_array[i] = cos(in_array[i]); +
} +
} +
+
+

This is wrapped as cos_doubles_func using the following SWIG interface +file:

+
/*  Example of wrapping a C function that takes a C double array as input using
+
* NumPy typemaps for SWIG. */ +
+
%module cos_doubles +
%{ +
/* the resulting C file should be built as a python extension */ +
#define SWIG_FILE_WITH_INIT +
/* Includes the header in the wrapper code */ +
#include "cos_doubles.h" +
%} +
+
/* include the NumPy typemaps */ +
%include "numpy.i" +
/* need this for correct module initialization */ +
%init %{ +
import_array(); +
%} +
+
/* typemaps for the two arrays, the second will be modified in-place */ +
%apply (double* IN_ARRAY1, int DIM1) {(double * in_array, int size_in)} +
%apply (double* INPLACE_ARRAY1, int DIM1) {(double * out_array, int size_out)} +
+
/* Wrapper for cos_doubles that massages the types */ +
%inline %{ +
/* takes as input two NumPy arrays */ +
void cos_doubles_func(double * in_array, int size_in, double * out_array, int size_out) { +
/* calls the original function, providing only the size of the first */ +
cos_doubles(in_array, out_array, size_in); +
} +
%} +
+
+
    +
  • To use the NumPy typemaps, we need include the numpy.i file.

  • +
  • Observe the call to import_array() which we encountered already in the +NumPy-C-API example.

  • +
  • Since the type maps only support the signature ARRAY, SIZE we need to +wrap the cos_doubles as cos_doubles_func which takes two arrays +including sizes as input.

  • +
  • As opposed to the simple SWIG example, we don’t include the cos_doubles.h +header, There is nothing there that we wish to expose to Python since we +expose the functionality through cos_doubles_func.

  • +
+

And, as before we can use setuptools to wrap this:

+
from setuptools import setup, Extension
+
import numpy +
+
+
setup( +
ext_modules=[ +
Extension( +
"_cos_doubles", +
sources=["cos_doubles.c", "cos_doubles.i"], +
include_dirs=[numpy.get_include()], +
) +
] +
) +
+
+

As previously, we need to use include_dirs to specify the location.

+
$ ls
+
cos_doubles.c cos_doubles.h cos_doubles.i numpy.i setup.py test_cos_doubles.py +
$ python setup.py build_ext -i +
running build_ext +
building '_cos_doubles' extension +
swigging cos_doubles.i to cos_doubles_wrap.c +
swig -python -o cos_doubles_wrap.c cos_doubles.i +
cos_doubles.i:24: Warning(490): Fragment 'NumPy_Backward_Compatibility' not found. +
cos_doubles.i:24: Warning(490): Fragment 'NumPy_Backward_Compatibility' not found. +
cos_doubles.i:24: Warning(490): Fragment 'NumPy_Backward_Compatibility' not found. +
creating build +
creating build/temp.linux-x86_64-2.7 +
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include -I/home/esc/anaconda/include/python2.7 -c cos_doubles.c -o build/temp.linux-x86_64-2.7/cos_doubles.o +
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include -I/home/esc/anaconda/include/python2.7 -c cos_doubles_wrap.c -o build/temp.linux-x86_64-2.7/cos_doubles_wrap.o +
In file included from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1722, +
from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:17, +
from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/arrayobject.h:15, +
from cos_doubles_wrap.c:2706: +
/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/npy_deprecated_api.h:11:2: warning: #warning "Using deprecated NumPy API, disable it by #defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" +
gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_doubles.o build/temp.linux-x86_64-2.7/cos_doubles_wrap.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/swig_numpy/_cos_doubles.so +
$ ls +
build/ cos_doubles.h cos_doubles.py cos_doubles_wrap.c setup.py +
cos_doubles.c cos_doubles.i _cos_doubles.so* numpy.i test_cos_doubles.py +
+
+

And, as before, we convince ourselves that it worked:

+
import numpy as np
+
import matplotlib.pyplot as plt +
import cos_doubles +
+
x = np.arange(0, 2 * np.pi, 0.1) +
y = np.empty_like(x) +
+
cos_doubles.cos_doubles_func(x, y) +
plt.plot(x, y) +
plt.show() +
+
+../../_images/test_cos_doubles1.png + +
+
+
+

2.8.5. Cython

+

Cython is both a Python-like language for writing +C-extensions and an advanced compiler for this language. The Cython language +is a superset of Python, which comes with additional constructs that allow you +call C functions and annotate variables and class attributes with c types. In +this sense one could also call it a Python with types.

+

In addition to the basic use case of wrapping native code, Cython supports an +additional use-case, namely interactive optimization. Basically, one starts out +with a pure-Python script and incrementally adds Cython types to the bottleneck +code to optimize only those code paths that really matter.

+

In this sense it is quite similar to SWIG, since the code can be autogenerated +but in a sense it also quite similar to ctypes since the wrapping code can +(almost) be written in Python.

+

While others solutions that autogenerate code can be quite difficult to debug +(for example SWIG) Cython comes with an extension to the GNU debugger that +helps debug Python, Cython and C code.

+
+

Note

+

The autogenerated C code uses the Python-C-Api.

+
+

Advantages

+
    +
  • Python like language for writing C-extensions

  • +
  • Autogenerated code

  • +
  • Supports incremental optimization

  • +
  • Includes a GNU debugger extension

  • +
  • Support for C++ (Since version 0.13)

  • +
+

Disadvantages

+
    +
  • Must be compiled

  • +
  • Requires an additional library ( but only at build time, at this problem can be +overcome by shipping the generated C files)

  • +
+
+

2.8.5.1. Example

+

The main Cython code for our cos_module is contained in the file +cos_module.pyx:

+
""" Example of wrapping cos function from math.h using Cython. """
+
+
cdef extern from "math.h": +
double cos(double arg) +
+
def cos_func(arg): +
return cos(arg) +
+
+

Note the additional keywords such as cdef and extern. Also the +cos_func is then pure Python.

+

Again we can use the standard setuptools module, but this time we need some +additional pieces from Cython.Build:

+
from setuptools import setup, Extension
+
from Cython.Build import cythonize +
+
+
extensions = [Extension("cos_module", sources=["cos_module.pyx"])] +
+
setup(ext_modules=cythonize(extensions)) +
+
+

Compiling this:

+
$ cd advanced/interfacing_with_c/cython
+
$ ls +
cos_module.pyx setup.py +
$ python setup.py build_ext --inplace +
running build_ext +
cythoning cos_module.pyx to cos_module.c +
building 'cos_module' extension +
creating build +
creating build/temp.linux-x86_64-2.7 +
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module.c -o build/temp.linux-x86_64-2.7/cos_module.o +
gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_module.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/cython/cos_module.so +
$ ls +
build/ cos_module.c cos_module.pyx cos_module.so* setup.py +
+
+

And running it:

+
In [22]: import cos_module
+
+
In [23]: cos_module? +
Type: module +
String Form:<module 'cos_module' from 'cos_module.so'> +
File: /home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/cython/cos_module.so +
Docstring: <no docstring> +
+
In [24]: dir(cos_module) +
Out[24]: +
['__builtins__', +
'__doc__', +
'__file__', +
'__name__', +
'__package__', +
'__test__', +
'cos_func'] +
+
In [25]: cos_module.cos_func(1.0) +
Out[25]: 0.5403023058681398 +
+
In [26]: cos_module.cos_func(0.0) +
Out[26]: 1.0 +
+
In [27]: cos_module.cos_func(3.14159265359) +
Out[27]: -1.0 +
+
+

And, testing a little for robustness, we can see that we get good error messages:

+
In [28]: cos_module.cos_func('foo')
+
--------------------------------------------------------------------------- +
TypeError Traceback (most recent call last) +
<ipython-input-7-11bee483665d> in <module>() +
----> 1 cos_module.cos_func('foo') +
/home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/cython/cos_module.so in cos_module.cos_func (cos_module.c:506)() +
TypeError: a float is required +
+
+

Additionally, it is worth noting that Cython ships with complete +declarations for the C math library, which simplifies the code above to become:

+
""" Simpler example of wrapping cos function from math.h using Cython. """
+
+
from libc.math cimport cos +
+
def cos_func(arg): +
return cos(arg) +
+
+

In this case the cimport statement is used to import the cos function.

+
+
+

2.8.5.2. NumPy Support

+

Cython has support for NumPy via the numpy.pyx file which allows you to add +the NumPy array type to your Cython code. I.e. like specifying that variable +i is of type int, you can specify that variable a is of type +numpy.ndarray with a given dtype. Also, certain optimizations such as +bounds checking are supported. Look at the corresponding section in the Cython +documentation. In case you +want to pass NumPy arrays as C arrays to your Cython wrapped C functions, there +is a section about this in the Cython documentation.

+

In the following example, we will show how to wrap the familiar cos_doubles +function using Cython.

+
void cos_doubles(double * in_array, double * out_array, int size);
+
+
+
#include <math.h>
+
+
/* Compute the cosine of each element in in_array, storing the result in +
* out_array. */ +
void cos_doubles(double * in_array, double * out_array, int size){ +
int i; +
for(i=0;i<size;i++){ +
out_array[i] = cos(in_array[i]); +
} +
} +
+
+

This is wrapped as cos_doubles_func using the following Cython code:

+
""" Example of wrapping a C function that takes C double arrays as input using
+
the NumPy declarations from Cython """ +
+
# cimport the Cython declarations for NumPy +
cimport numpy as np +
+
# if you want to use the NumPy-C-API from Cython +
# (not strictly necessary for this example, but good practice) +
np.import_array() +
+
# cdefine the signature of our c function +
cdef extern from "cos_doubles.h": +
void cos_doubles (double * in_array, double * out_array, int size) +
+
# create the wrapper code, with NumPy type annotations +
def cos_doubles_func(np.ndarray[double, ndim=1, mode="c"] in_array not None, +
np.ndarray[double, ndim=1, mode="c"] out_array not None): +
cos_doubles(<double*> np.PyArray_DATA(in_array), +
<double*> np.PyArray_DATA(out_array), +
in_array.shape[0]) +
+
+

And can be compiled using setuptools:

+
from setuptools import setup, Extension
+
from Cython.Build import cythonize +
import numpy +
+
+
extensions = [ +
Extension( +
"cos_doubles", +
sources=["_cos_doubles.pyx", "cos_doubles.c"], +
include_dirs=[numpy.get_include()], +
) +
] +
+
setup(ext_modules=cythonize(extensions)) +
+
+
    +
  • As with the previous compiled NumPy examples, we need the include_dirs option.

  • +
+
$ ls
+
cos_doubles.c cos_doubles.h _cos_doubles.pyx setup.py test_cos_doubles.py +
$ python setup.py build_ext -i +
running build_ext +
cythoning _cos_doubles.pyx to _cos_doubles.c +
building 'cos_doubles' extension +
creating build +
creating build/temp.linux-x86_64-2.7 +
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include -I/home/esc/anaconda/include/python2.7 -c _cos_doubles.c -o build/temp.linux-x86_64-2.7/_cos_doubles.o +
In file included from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1722, +
from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:17, +
from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/arrayobject.h:15, +
from _cos_doubles.c:253: +
/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/npy_deprecated_api.h:11:2: warning: #warning "Using deprecated NumPy API, disable it by #defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" +
/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/__ufunc_api.h:236: warning: ‘_import_umath’ defined but not used +
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include -I/home/esc/anaconda/include/python2.7 -c cos_doubles.c -o build/temp.linux-x86_64-2.7/cos_doubles.o +
gcc -pthread -shared build/temp.linux-x86_64-2.7/_cos_doubles.o build/temp.linux-x86_64-2.7/cos_doubles.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/cython_numpy/cos_doubles.so +
$ ls +
build/ _cos_doubles.c cos_doubles.c cos_doubles.h _cos_doubles.pyx cos_doubles.so* setup.py test_cos_doubles.py +
+
+

And, as before, we convince ourselves that it worked:

+
import numpy as np
+
import matplotlib.pyplot as plt +
import cos_doubles +
+
x = np.arange(0, 2 * np.pi, 0.1) +
y = np.empty_like(x) +
+
cos_doubles.cos_doubles_func(x, y) +
plt.plot(x, y) +
plt.show() +
+
+../../_images/test_cos_doubles2.png + +
+
+
+

2.8.6. Summary

+

In this section four different techniques for interfacing with native code +have been presented. The table below roughly summarizes some of the aspects of +the techniques.

+ +++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

x

Part of CPython

Compiled

Autogenerated

NumPy Support

Python-C-API

True

True

False

True

Ctypes

True

False

False

True

Swig

False

True

True

True

Cython

False

True

True

True

+

Of all three presented techniques, Cython is the most modern and advanced. In +particular, the ability to optimize code incrementally by adding types to your +Python code is unique.

+
+
+

2.8.7. Further Reading and References

+ +
+
+

2.8.8. Exercises

+

Since this is a brand new section, the exercises are considered more as +pointers as to what to look at next, so pick the ones that you find more +interesting. If you have good ideas for exercises, please let us know!

+
    +
  1. Download the source code for each example and compile and run them on your +machine.

  2. +
  3. Make trivial changes to each example and convince yourself that this works. ( +E.g. change cos for sin.)

  4. +
  5. Most of the examples, especially the ones involving NumPy may still be +fragile and respond badly to input errors. Look for ways to crash the +examples, figure what the problem is and devise a potential solution. +Here are some ideas:

    +
      +
    1. Numerical overflow.

    2. +
    3. Input and output arrays that have different lengths.

    4. +
    5. Multidimensional array.

    6. +
    7. Empty array

    8. +
    9. Arrays with non-double types

    10. +
    +
  6. +
  7. Use the %timeit IPython magic to measure the execution time of the +various solutions

  8. +
+
+

2.8.8.1. Python-C-API

+
    +
  1. Modify the NumPy example such that the function takes two input arguments, where +the second is the preallocated output array, making it similar to the other NumPy examples.

  2. +
  3. Modify the example such that the function only takes a single input array +and modifies this in place.

  4. +
  5. Try to fix the example to use the new NumPy iterator protocol. If you +manage to obtain a working solution, please submit a pull-request on github.

  6. +
  7. You may have noticed, that the NumPy-C-API example is the only NumPy example +that does not wrap cos_doubles but instead applies the cos function +directly to the elements of the NumPy array. Does this have any advantages +over the other techniques.

  8. +
  9. Can you wrap cos_doubles using only the NumPy-C-API. You may need to +ensure that the arrays have the correct type, are one dimensional and +contiguous in memory.

  10. +
+
+
+

2.8.8.2. Ctypes

+
    +
  1. Modify the NumPy example such that cos_doubles_func handles the preallocation for +you, thus making it more like the NumPy-C-API example.

  2. +
+
+
+

2.8.8.3. SWIG

+
    +
  1. Look at the code that SWIG autogenerates, how much of it do you +understand?

  2. +
  3. Modify the NumPy example such that cos_doubles_func handles the preallocation for +you, thus making it more like the NumPy-C-API example.

  4. +
  5. Modify the cos_doubles C function so that it returns an allocated array. +Can you wrap this using SWIG typemaps? If not, why not? Is there a +workaround for this specific situation? (Hint: you know the size of the +output array, so it may be possible to construct a NumPy array from the +returned double *.)

  6. +
+
+
+

2.8.8.4. Cython

+
    +
  1. Look at the code that Cython autogenerates. Take a closer look at some of the +comments that Cython inserts. What do you see?

  2. +
  3. Look at the section Working with NumPy from the Cython +documentation to learn how to incrementally optimize a pure python script that uses NumPy.

  4. +
  5. Modify the NumPy example such that cos_doubles_func handles the preallocation for +you, thus making it more like the NumPy-C-API example.

  6. +
+

+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/index.html b/advanced/mathematical_optimization/auto_examples/index.html new file mode 100644 index 000000000..b8285b86d --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/index.html @@ -0,0 +1,219 @@ + + + + + + + + Examples for the mathematical optimization chapter — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Examples for the mathematical optimization chapter

+
+

Noisy optimization problem

+
Noisy optimization problem
+
+

Smooth vs non-smooth

+
Smooth vs non-smooth
+
+

Curve fitting

+
Curve fitting
+
+

Convex function

+
Convex function
+
+

Finding a minimum in a flat neighborhood

+
Finding a minimum in a flat neighborhood
+
+

Optimization with constraints

+
Optimization with constraints
+
+

Brent’s method

+
Brent's method
+
+

Constraint optimization: visualizing the geometry

+
Constraint optimization: visualizing the geometry
+
+

Alternating optimization

+
Alternating optimization
+
+

Plotting the comparison of optimizers

+
Plotting the comparison of optimizers
+
+

Gradient descent

+
Gradient descent
+
+
+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_1d_optim.html b/advanced/mathematical_optimization/auto_examples/plot_1d_optim.html new file mode 100644 index 000000000..fd24b1b84 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_1d_optim.html @@ -0,0 +1,294 @@ + + + + + + + + 2.7.4.7. Brent’s method — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.7.4.7. Brent’s method

+

Illustration of 1D optimization: Brent’s method

+
    +
  • plot 1d optim
  • +
  • plot 1d optim
  • +
  • plot 1d optim
  • +
  • plot 1d optim
  • +
+
Converged at  6
+
Converged at 23 +
+
+
+

+
+
import numpy as np
+
import matplotlib.pyplot as plt +
import scipy as sp +
+
x = np.linspace(-1, 3, 100) +
x_0 = np.exp(-1) +
+
+
def f(x): +
return (x - x_0) ** 2 + epsilon * np.exp(-5 * (x - 0.5 - x_0) ** 2) +
+
+
for epsilon in (0, 1): +
plt.figure(figsize=(3, 2.5)) +
plt.axes((0, 0, 1, 1)) +
+
# A convex function +
plt.plot(x, f(x), linewidth=2) +
+
# Apply brent method. To have access to the iteration, do this in an +
# artificial way: allow the algorithm to iter only once +
all_x = [] +
all_y = [] +
for iter in range(30): +
result = sp.optimize.minimize_scalar( +
f, +
bracket=(-5, 2.9, 4.5), +
method="Brent", +
options={"maxiter": iter}, +
tol=np.finfo(1.0).eps, +
) +
if result.success: +
print("Converged at ", iter) +
break +
+
this_x = result.x +
all_x.append(this_x) +
all_y.append(f(this_x)) +
if iter < 6: +
plt.text( +
this_x - 0.05 * np.sign(this_x) - 0.05, +
f(this_x) + 1.2 * (0.3 - iter % 2), +
str(iter + 1), +
size=12, +
) +
+
plt.plot(all_x[:10], all_y[:10], "k+", markersize=12, markeredgewidth=2) +
+
plt.plot(all_x[-1], all_y[-1], "rx", markersize=12) +
plt.axis("off") +
plt.ylim(ymin=-1, ymax=8) +
+
plt.figure(figsize=(4, 3)) +
plt.semilogy(np.abs(all_y - all_y[-1]), linewidth=2) +
plt.ylabel("Error on f(x)") +
plt.xlabel("Iteration") +
plt.tight_layout() +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.231 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_compare_optimizers.html b/advanced/mathematical_optimization/auto_examples/plot_compare_optimizers.html new file mode 100644 index 000000000..6d9c86776 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_compare_optimizers.html @@ -0,0 +1,319 @@ + + + + + + + + 2.7.4.10. Plotting the comparison of optimizers — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.7.4.10. Plotting the comparison of optimizers

+

Plots the results from the comparison of optimizers.

+plot compare optimizers
import pickle
+
import sys +
+
import numpy as np +
+
import matplotlib +
import matplotlib.pyplot as plt +
+
results = pickle.load( +
open(f"helper/compare_optimizers_py{sys.version_info[0]}.pkl", "rb") +
) +
n_methods = len(list(results.values())[0]["Rosenbrock "]) +
n_dims = len(results) +
+
symbols = "o>*Ds" +
+
plt.figure(1, figsize=(10, 4)) +
plt.clf() +
+
nipy_spectral = matplotlib.colormaps["nipy_spectral"] +
colors = nipy_spectral(np.linspace(0, 1, n_dims))[:, :3] +
+
method_names = list(list(results.values())[0]["Rosenbrock "].keys()) +
method_names.sort(key=lambda x: x[::-1], reverse=True) +
+
for n_dim_index, ((n_dim, n_dim_bench), color) in enumerate( +
zip(sorted(results.items()), colors, strict=True) +
): +
for (cost_name, cost_bench), symbol in zip( +
sorted(n_dim_bench.items()), symbols, strict=True +
): +
for ( +
method_index, +
method_name, +
) in enumerate(method_names): +
this_bench = cost_bench[method_name] +
bench = np.mean(this_bench) +
plt.semilogy( +
[ +
method_index + 0.1 * n_dim_index, +
], +
[ +
bench, +
], +
marker=symbol, +
color=color, +
) +
+
# Create a legend for the problem type +
for cost_name, symbol in zip(sorted(n_dim_bench.keys()), symbols, strict=True): +
plt.semilogy( +
[ +
-10, +
], +
[ +
0, +
], +
symbol, +
color=".5", +
label=cost_name, +
) +
+
plt.xticks(np.arange(n_methods), method_names, size=11) +
plt.xlim(-0.2, n_methods - 0.5) +
plt.legend(loc="best", numpoints=1, handletextpad=0, prop={"size": 12}, frameon=False) +
plt.ylabel("# function calls (a.u.)") +
+
# Create a second legend for the problem dimensionality +
plt.twinx() +
+
for n_dim, color in zip(sorted(results.keys()), colors, strict=True): +
plt.plot( +
[ +
-10, +
], +
[ +
0, +
], +
"o", +
color=color, +
label="# dim: %i" % n_dim, +
) +
plt.legend( +
loc=(0.47, 0.07), +
numpoints=1, +
handletextpad=0, +
prop={"size": 12}, +
frameon=False, +
ncol=2, +
) +
plt.xlim(-0.2, n_methods - 0.5) +
+
plt.xticks(np.arange(n_methods), method_names) +
plt.yticks(()) +
+
plt.tight_layout() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.569 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_constraints.html b/advanced/mathematical_optimization/auto_examples/plot_constraints.html new file mode 100644 index 000000000..1290b8ccf --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_constraints.html @@ -0,0 +1,284 @@ + + + + + + + + 2.7.4.8. Constraint optimization: visualizing the geometry — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.7.4.8. Constraint optimization: visualizing the geometry

+

A small figure explaining optimization with constraints

+
    +
  • plot constraints
  • +
  • plot constraints
  • +
+
import numpy as np
+
import matplotlib.pyplot as plt +
import scipy as sp +
+
x, y = np.mgrid[-2.9:5.8:0.05, -2.5:5:0.05] # type: ignore[misc] +
x = x.T +
y = y.T +
+
for i in (1, 2): +
# Create 2 figure: only the second one will have the optimization +
# path +
plt.figure(i, figsize=(3, 2.5)) +
plt.clf() +
plt.axes((0, 0, 1, 1)) +
+
contours = plt.contour( +
np.sqrt((x - 3) ** 2 + (y - 2) ** 2), +
extent=[-3, 6, -2.5, 5], +
cmap="gnuplot", +
) +
plt.clabel(contours, inline=1, fmt="%1.1f", fontsize=14) +
plt.plot( +
[-1.5, -1.5, 1.5, 1.5, -1.5], [-1.5, 1.5, 1.5, -1.5, -1.5], "k", linewidth=2 +
) +
plt.fill_between([-1.5, 1.5], [-1.5, -1.5], [1.5, 1.5], color=".8") +
plt.axvline(0, color="k") +
plt.axhline(0, color="k") +
+
plt.text(-0.9, 4.4, "$x_2$", size=20) +
plt.text(5.6, -0.6, "$x_1$", size=20) +
plt.axis("equal") +
plt.axis("off") +
+
# And now plot the optimization path +
accumulator = [] +
+
+
def f(x): +
# Store the list of function calls +
accumulator.append(x) +
return np.sqrt((x[0] - 3) ** 2 + (x[1] - 2) ** 2) +
+
+
# We don't use the gradient, as with the gradient, L-BFGS is too fast, +
# and finds the optimum without showing us a pretty path +
def f_prime(x): +
r = np.sqrt((x[0] - 3) ** 2 + (x[0] - 2) ** 2) +
return np.array(((x[0] - 3) / r, (x[0] - 2) / r)) +
+
+
sp.optimize.minimize( +
f, np.array([0, 0]), method="L-BFGS-B", bounds=((-1.5, 1.5), (-1.5, 1.5)) +
) +
+
accumulated = np.array(accumulator) +
plt.plot(accumulated[:, 0], accumulated[:, 1]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.089 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_convex.html b/advanced/mathematical_optimization/auto_examples/plot_convex.html new file mode 100644 index 000000000..b7f97611c --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_convex.html @@ -0,0 +1,264 @@ + + + + + + + + 2.7.4.4. Convex function — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.7.4.4. Convex function

+

A figure showing the definition of a convex function

+
    +
  • plot convex
  • +
  • plot convex
  • +
+
import numpy as np
+
import matplotlib.pyplot as plt +
+
x = np.linspace(-1, 2) +
+
plt.figure(1, figsize=(3, 2.5)) +
plt.clf() +
+
# A convex function +
plt.plot(x, x**2, linewidth=2) +
plt.text(-0.7, -(0.6**2), "$f$", size=20) +
+
# The tangent in one point +
plt.plot(x, 2 * x - 1) +
plt.plot(1, 1, "k+") +
plt.text(0.3, -0.75, "Tangent to $f$", size=15) +
plt.text(1, 1 - 0.5, "C", size=15) +
+
# Convexity as barycenter +
plt.plot([0.35, 1.85], [0.35**2, 1.85**2]) +
plt.plot([0.35, 1.85], [0.35**2, 1.85**2], "k+") +
plt.text(0.35 - 0.2, 0.35**2 + 0.1, "A", size=15) +
plt.text(1.85 - 0.2, 1.85**2, "B", size=15) +
+
plt.ylim(ymin=-1) +
plt.axis("off") +
plt.tight_layout() +
+
# Convexity as barycenter +
plt.figure(2, figsize=(3, 2.5)) +
plt.clf() +
plt.plot(x, x**2 + np.exp(-5 * (x - 0.5) ** 2), linewidth=2) +
plt.text(-0.7, -(0.6**2), "$f$", size=20) +
+
plt.ylim(ymin=-1) +
plt.axis("off") +
plt.tight_layout() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.047 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_curve_fitting.html b/advanced/mathematical_optimization/auto_examples/plot_curve_fitting.html new file mode 100644 index 000000000..798f3d34d --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_curve_fitting.html @@ -0,0 +1,250 @@ + + + + + + + + 2.7.4.3. Curve fitting — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.7.4.3. Curve fitting

+

A curve fitting example

+plot curve fitting
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
rng = np.random.default_rng(27446968) +
+
+
# Our test function +
def f(t, omega, phi): +
return np.cos(omega * t + phi) +
+
+
# Our x and y data +
x = np.linspace(0, 3, 50) +
y = f(x, 1.5, 1) + 0.1 * np.random.normal(size=50) +
+
# Fit the model: the parameters omega and phi can be found in the +
# `params` vector +
params, params_cov = sp.optimize.curve_fit(f, x, y) +
+
# plot the data and the fitted curve +
t = np.linspace(0, 3, 1000) +
+
plt.figure(1) +
plt.clf() +
plt.plot(x, y, "bx") +
plt.plot(t, f(t, *params), "r-") +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.053 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_exercise_flat_minimum.html b/advanced/mathematical_optimization/auto_examples/plot_exercise_flat_minimum.html new file mode 100644 index 000000000..12d0104b3 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_exercise_flat_minimum.html @@ -0,0 +1,280 @@ + + + + + + + + 2.7.4.5. Finding a minimum in a flat neighborhood — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.7.4.5. Finding a minimum in a flat neighborhood

+

An exercise of finding minimum. This exercise is hard because the +function is very flat around the minimum (all its derivatives are zero). +Thus gradient information is unreliable.

+

The function admits a minimum in [0, 0]. The challenge is to get within +1e-7 of this minimum, starting at x0 = [1, 1].

+

The solution that we adopt here is to give up on using gradient or +information based on local differences, and to rely on the Powell +algorithm. With 162 function evaluations, we get to 1e-8 of the +solution.

+
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
+
def f(x): +
return np.exp(-1 / (0.01 * x[0] ** 2 + x[1] ** 2)) +
+
+
# A well-conditionned version of f: +
def g(x): +
return f([10 * x[0], x[1]]) +
+
+
# The gradient of g. We won't use it here for the optimization. +
def g_prime(x): +
r = np.sqrt(x[0] ** 2 + x[1] ** 2) +
return 2 / r**3 * g(x) * x / r +
+
+
result = sp.optimize.minimize(g, [1, 1], method="Powell", tol=1e-10) +
x_min = result.x +
+
+

Some pretty plotting

+
plt.figure(0)
+
plt.clf() +
t = np.linspace(-1.1, 1.1, 100) +
plt.plot(t, f([0, t])) +
+
plt.figure(1) +
plt.clf() +
X, Y = np.mgrid[-1.5:1.5:100j, -1.1:1.1:100j] # type: ignore[misc] +
plt.imshow(f([X, Y]).T, cmap="gray_r", extent=(-1.5, 1.5, -1.1, 1.1), origin="lower") +
plt.contour(X, Y, f([X, Y]), cmap="gnuplot") +
+
# Plot the gradient +
dX, dY = g_prime([0.1 * X[::5, ::5], Y[::5, ::5]]) +
# Adjust for our preconditioning +
dX *= 0.1 +
plt.quiver(X[::5, ::5], Y[::5, ::5], dX, dY, color=".5") +
+
# Plot our solution +
plt.plot(x_min[0], x_min[1], "r+", markersize=15) +
+
plt.show() +
+
+
    +
  • plot exercise flat minimum
  • +
  • plot exercise flat minimum
  • +
+

Total running time of the script: (0 minutes 0.117 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_exercise_ill_conditioned.html b/advanced/mathematical_optimization/auto_examples/plot_exercise_ill_conditioned.html new file mode 100644 index 000000000..55f05e513 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_exercise_ill_conditioned.html @@ -0,0 +1,310 @@ + + + + + + + + 2.7.4.9. Alternating optimization — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.7.4.9. Alternating optimization

+

The challenge here is that Hessian of the problem is a very +ill-conditioned matrix. This can easily be seen, as the Hessian of the +first term in simply 2 * K.T @ K. Thus the conditioning of the +problem can be judged from looking at the conditioning of K.

+
import time
+
+
import numpy as np +
import scipy as sp +
import matplotlib.pyplot as plt +
+
rng = np.random.default_rng(27446968) +
+
K = rng.normal(size=(100, 100)) +
+
+
def f(x): +
return np.sum((K @ (x - 1)) ** 2) + np.sum(x**2) ** 2 +
+
+
def f_prime(x): +
return 2 * K.T @ K @ (x - 1) + 4 * np.sum(x**2) * x +
+
+
def hessian(x): +
H = 2 * K.T @ K + 4 * 2 * x * x[:, np.newaxis] +
return H + 4 * np.eye(H.shape[0]) * np.sum(x**2) +
+
+

Some pretty plotting

+
plt.figure(1)
+
plt.clf() +
Z = X, Y = np.mgrid[-1.5:1.5:100j, -1.1:1.1:100j] # type: ignore[misc] +
# Complete in the additional dimensions with zeros +
Z = np.reshape(Z, (2, -1)).copy() +
Z.resize((100, Z.shape[-1])) +
Z = np.apply_along_axis(f, 0, Z) +
Z = np.reshape(Z, X.shape) +
plt.imshow(Z.T, cmap="gray_r", extent=(-1.5, 1.5, -1.1, 1.1), origin="lower") +
plt.contour(X, Y, Z, cmap="gnuplot") +
+
# A reference but slow solution: +
t0 = time.time() +
x_ref = sp.optimize.minimize(f, K[0], method="Powell").x +
print(f" Powell: time {time.time() - t0:.2f}s") +
f_ref = f(x_ref) +
+
# Compare different approaches +
t0 = time.time() +
x_bfgs = sp.optimize.minimize(f, K[0], method="BFGS").x +
print( +
f" BFGS: time {time.time() - t0:.2f}s, x error {np.sqrt(np.sum((x_bfgs - x_ref) ** 2)):.2f}, f error {f(x_bfgs) - f_ref:.2f}" +
) +
+
t0 = time.time() +
x_l_bfgs = sp.optimize.minimize(f, K[0], method="L-BFGS-B").x +
print( +
f" L-BFGS: time {time.time() - t0:.2f}s, x error {np.sqrt(np.sum((x_l_bfgs - x_ref) ** 2)):.2f}, f error {f(x_l_bfgs) - f_ref:.2f}" +
) +
+
+
t0 = time.time() +
x_bfgs = sp.optimize.minimize(f, K[0], jac=f_prime, method="BFGS").x +
print( +
f" BFGS w f': time {time.time() - t0:.2f}s, x error {np.sqrt(np.sum((x_bfgs - x_ref) ** 2)):.2f}, f error {f(x_bfgs) - f_ref:.2f}" +
) +
+
t0 = time.time() +
x_l_bfgs = sp.optimize.minimize(f, K[0], jac=f_prime, method="L-BFGS-B").x +
print( +
f"L-BFGS w f': time {time.time() - t0:.2f}s, x error {np.sqrt(np.sum((x_l_bfgs - x_ref) ** 2)):.2f}, f error {f(x_l_bfgs) - f_ref:.2f}" +
) +
+
t0 = time.time() +
x_newton = sp.optimize.minimize( +
f, K[0], jac=f_prime, hess=hessian, method="Newton-CG" +
).x +
print( +
f" Newton: time {time.time() - t0:.2f}s, x error {np.sqrt(np.sum((x_newton - x_ref) ** 2)):.2f}, f error {f(x_newton) - f_ref:.2f}" +
) +
+
plt.show() +
+
+plot exercise ill conditioned
     Powell: time 0.13s
+
BFGS: time 0.82s, x error 0.02, f error -0.03 +
L-BFGS: time 0.06s, x error 0.02, f error -0.03 +
BFGS w f': time 0.06s, x error 0.02, f error -0.03 +
L-BFGS w f': time 0.00s, x error 0.02, f error -0.03 +
Newton: time 0.00s, x error 0.02, f error -0.03 +
+
+

Total running time of the script: (0 minutes 1.296 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_gradient_descent.html b/advanced/mathematical_optimization/auto_examples/plot_gradient_descent.html new file mode 100644 index 000000000..f97da754a --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_gradient_descent.html @@ -0,0 +1,551 @@ + + + + + + + + 2.7.4.11. Gradient descent — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.7.4.11. Gradient descent

+

An example demoing gradient descent by creating figures that trace the +evolution of the optimizer.

+
import numpy as np
+
import matplotlib.pyplot as plt +
import scipy as sp +
+
import collections +
import sys +
import os +
+
sys.path.append(os.path.abspath("helper")) +
from cost_functions import ( +
mk_quad, +
mk_gauss, +
rosenbrock, +
rosenbrock_prime, +
rosenbrock_hessian, +
LoggingFunction, +
CountingFunction, +
) +
+
x_min, x_max = -1, 2 +
y_min, y_max = 2.25 / 3 * x_min - 0.2, 2.25 / 3 * x_max - 0.2 +
+
+

A formatter to print values on contours

+
def super_fmt(value):
+
if value > 1: +
if np.abs(int(value) - value) < 0.1: +
out = f"$10^{{{int(value):d}}}$" +
else: +
out = f"$10^{{{value:.1f}}}$" +
else: +
value = np.exp(value - 0.01) +
if value > 0.1: +
out = f"{value:1.1f}" +
elif value > 0.01: +
out = f"{value:.2f}" +
else: +
out = f"{value:.2e}" +
return out +
+
+

A gradient descent algorithm +do not use: its a toy, use scipy’s optimize.fmin_cg

+
def gradient_descent(x0, f, f_prime, hessian=None, adaptative=False):
+
x_i, y_i = x0 +
all_x_i = [] +
all_y_i = [] +
all_f_i = [] +
+
for i in range(1, 100): +
all_x_i.append(x_i) +
all_y_i.append(y_i) +
all_f_i.append(f([x_i, y_i])) +
dx_i, dy_i = f_prime(np.asarray([x_i, y_i])) +
if adaptative: +
# Compute a step size using a line_search to satisfy the Wolf +
# conditions +
step = sp.optimize.line_search( +
f, +
f_prime, +
np.r_[x_i, y_i], +
-np.r_[dx_i, dy_i], +
np.r_[dx_i, dy_i], +
c2=0.05, +
) +
step = step[0] +
if step is None: +
step = 0 +
else: +
step = 1 +
x_i += -step * dx_i +
y_i += -step * dy_i +
if np.abs(all_f_i[-1]) < 1e-16: +
break +
return all_x_i, all_y_i, all_f_i +
+
+
def gradient_descent_adaptative(x0, f, f_prime, hessian=None): +
return gradient_descent(x0, f, f_prime, adaptative=True) +
+
+
def conjugate_gradient(x0, f, f_prime, hessian=None): +
all_x_i = [x0[0]] +
all_y_i = [x0[1]] +
all_f_i = [f(x0)] +
+
def store(X): +
x, y = X +
all_x_i.append(x) +
all_y_i.append(y) +
all_f_i.append(f(X)) +
+
sp.optimize.minimize( +
f, x0, jac=f_prime, method="CG", callback=store, options={"gtol": 1e-12} +
) +
return all_x_i, all_y_i, all_f_i +
+
+
def newton_cg(x0, f, f_prime, hessian): +
all_x_i = [x0[0]] +
all_y_i = [x0[1]] +
all_f_i = [f(x0)] +
+
def store(X): +
x, y = X +
all_x_i.append(x) +
all_y_i.append(y) +
all_f_i.append(f(X)) +
+
sp.optimize.minimize( +
f, +
x0, +
method="Newton-CG", +
jac=f_prime, +
hess=hessian, +
callback=store, +
options={"xtol": 1e-12}, +
) +
return all_x_i, all_y_i, all_f_i +
+
+
def bfgs(x0, f, f_prime, hessian=None): +
all_x_i = [x0[0]] +
all_y_i = [x0[1]] +
all_f_i = [f(x0)] +
+
def store(X): +
x, y = X +
all_x_i.append(x) +
all_y_i.append(y) +
all_f_i.append(f(X)) +
+
sp.optimize.minimize( +
f, x0, method="BFGS", jac=f_prime, callback=store, options={"gtol": 1e-12} +
) +
return all_x_i, all_y_i, all_f_i +
+
+
def powell(x0, f, f_prime, hessian=None): +
all_x_i = [x0[0]] +
all_y_i = [x0[1]] +
all_f_i = [f(x0)] +
+
def store(X): +
x, y = X +
all_x_i.append(x) +
all_y_i.append(y) +
all_f_i.append(f(X)) +
+
sp.optimize.minimize( +
f, x0, method="Powell", callback=store, options={"ftol": 1e-12} +
) +
return all_x_i, all_y_i, all_f_i +
+
+
def nelder_mead(x0, f, f_prime, hessian=None): +
all_x_i = [x0[0]] +
all_y_i = [x0[1]] +
all_f_i = [f(x0)] +
+
def store(X): +
x, y = X +
all_x_i.append(x) +
all_y_i.append(y) +
all_f_i.append(f(X)) +
+
sp.optimize.minimize( +
f, x0, method="Nelder-Mead", callback=store, options={"ftol": 1e-12} +
) +
return all_x_i, all_y_i, all_f_i +
+
+

Run different optimizers on these problems

+
levels = {}
+
+
for index, ((f, f_prime, hessian), optimizer) in enumerate( +
( +
(mk_quad(0.7), gradient_descent), +
(mk_quad(0.7), gradient_descent_adaptative), +
(mk_quad(0.02), gradient_descent), +
(mk_quad(0.02), gradient_descent_adaptative), +
(mk_gauss(0.02), gradient_descent_adaptative), +
( +
(rosenbrock, rosenbrock_prime, rosenbrock_hessian), +
gradient_descent_adaptative, +
), +
(mk_gauss(0.02), conjugate_gradient), +
((rosenbrock, rosenbrock_prime, rosenbrock_hessian), conjugate_gradient), +
(mk_quad(0.02), newton_cg), +
(mk_gauss(0.02), newton_cg), +
((rosenbrock, rosenbrock_prime, rosenbrock_hessian), newton_cg), +
(mk_quad(0.02), bfgs), +
(mk_gauss(0.02), bfgs), +
((rosenbrock, rosenbrock_prime, rosenbrock_hessian), bfgs), +
(mk_quad(0.02), powell), +
(mk_gauss(0.02), powell), +
((rosenbrock, rosenbrock_prime, rosenbrock_hessian), powell), +
(mk_gauss(0.02), nelder_mead), +
((rosenbrock, rosenbrock_prime, rosenbrock_hessian), nelder_mead), +
) +
): +
# Compute a gradient-descent +
x_i, y_i = 1.6, 1.1 +
counting_f_prime = CountingFunction(f_prime) +
counting_hessian = CountingFunction(hessian) +
logging_f = LoggingFunction(f, counter=counting_f_prime.counter) +
all_x_i, all_y_i, all_f_i = optimizer( +
np.array([x_i, y_i]), logging_f, counting_f_prime, hessian=counting_hessian +
) +
+
# Plot the contour plot +
if not max(all_y_i) < y_max: +
x_min *= 1.2 +
x_max *= 1.2 +
y_min *= 1.2 +
y_max *= 1.2 +
x, y = np.mgrid[x_min:x_max:100j, y_min:y_max:100j] +
x = x.T +
y = y.T +
+
plt.figure(index, figsize=(3, 2.5)) +
plt.clf() +
plt.axes([0, 0, 1, 1]) +
+
X = np.concatenate((x[np.newaxis, ...], y[np.newaxis, ...]), axis=0) +
z = np.apply_along_axis(f, 0, X) +
log_z = np.log(z + 0.01) +
plt.imshow( +
log_z, +
extent=[x_min, x_max, y_min, y_max], +
cmap=plt.cm.gray_r, +
origin="lower", +
vmax=log_z.min() + 1.5 * np.ptp(log_z), +
) +
contours = plt.contour( +
log_z, +
levels=levels.get(f), +
extent=[x_min, x_max, y_min, y_max], +
cmap=plt.cm.gnuplot, +
origin="lower", +
) +
levels[f] = contours.levels +
plt.clabel(contours, inline=1, fmt=super_fmt, fontsize=14) +
+
plt.plot(all_x_i, all_y_i, "b-", linewidth=2) +
plt.plot(all_x_i, all_y_i, "k+") +
+
plt.plot(logging_f.all_x_i, logging_f.all_y_i, "k.", markersize=2) +
+
plt.plot([0], [0], "rx", markersize=12) +
+
plt.xticks(()) +
plt.yticks(()) +
plt.xlim(x_min, x_max) +
plt.ylim(y_min, y_max) +
plt.draw() +
+
plt.figure(index + 100, figsize=(4, 3)) +
plt.clf() +
plt.semilogy(np.maximum(np.abs(all_f_i), 1e-30), linewidth=2, label="# iterations") +
plt.ylabel("Error on f(x)") +
plt.semilogy( +
logging_f.counts, +
np.maximum(np.abs(logging_f.all_f_i), 1e-30), +
linewidth=2, +
color="g", +
label="# function calls", +
) +
plt.legend( +
loc="upper right", +
frameon=True, +
prop={"size": 11}, +
borderaxespad=0, +
handlelength=1.5, +
handletextpad=0.5, +
) +
plt.tight_layout() +
plt.draw() +
+
+
    +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
  • plot gradient descent
  • +
+
/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages/scipy/optimize/_linesearch.py:312: LineSearchWarning: The line search algorithm did not converge
+
alpha_star, phi_star, old_fval, derphi_star = scalar_search_wolfe2( +
/home/runner/work/scientific-python-lectures/scientific-python-lectures/advanced/mathematical_optimization/examples/plot_gradient_descent.py:70: LineSearchWarning: The line search algorithm did not converge +
step = sp.optimize.line_search( +
/home/runner/work/scientific-python-lectures/scientific-python-lectures/advanced/mathematical_optimization/examples/plot_gradient_descent.py:234: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`). Consider using `matplotlib.pyplot.close()`. +
plt.figure(index, figsize=(3, 2.5)) +
/home/runner/work/scientific-python-lectures/scientific-python-lectures/advanced/mathematical_optimization/examples/plot_gradient_descent.py:179: OptimizeWarning: Unknown solver options: ftol +
sp.optimize.minimize( +
+
+

Total running time of the script: (0 minutes 6.858 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_noisy.html b/advanced/mathematical_optimization/auto_examples/plot_noisy.html new file mode 100644 index 000000000..7aace118f --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_noisy.html @@ -0,0 +1,246 @@ + + + + + + + + 2.7.4.1. Noisy optimization problem — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.7.4.1. Noisy optimization problem

+

Draws a figure explaining noisy vs non-noisy optimization

+plot noisy
import numpy as np
+
import matplotlib.pyplot as plt +
+
rng = np.random.default_rng(27446968) +
+
x = np.linspace(-5, 5, 101) +
x_ = np.linspace(-5, 5, 31) +
+
+
def f(x): +
return -np.exp(-(x**2)) +
+
+
# A smooth function +
plt.figure(1, figsize=(3, 2.5)) +
plt.clf() +
+
plt.plot(x_, f(x_) + 0.2 * np.random.normal(size=31), linewidth=2) +
plt.plot(x, f(x), linewidth=2) +
+
plt.ylim(ymin=-1.3) +
plt.axis("off") +
plt.tight_layout() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.017 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_non_bounds_constraints.html b/advanced/mathematical_optimization/auto_examples/plot_non_bounds_constraints.html new file mode 100644 index 000000000..622fc0255 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_non_bounds_constraints.html @@ -0,0 +1,273 @@ + + + + + + + + 2.7.4.6. Optimization with constraints — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.7.4.6. Optimization with constraints

+

An example showing how to do optimization with general constraints using +SLSQP and cobyla.

+plot non bounds constraints
import numpy as np
+
import matplotlib.pyplot as plt +
import scipy as sp +
+
x, y = np.mgrid[-2.03:4.2:0.04, -1.6:3.2:0.04] # type: ignore[misc] +
x = x.T +
y = y.T +
+
plt.figure(1, figsize=(3, 2.5)) +
plt.clf() +
plt.axes((0, 0, 1, 1)) +
+
contours = plt.contour( +
np.sqrt((x - 3) ** 2 + (y - 2) ** 2), +
extent=[-2.03, 4.2, -1.6, 3.2], +
cmap="gnuplot", +
) +
plt.clabel(contours, inline=1, fmt="%1.1f", fontsize=14) +
plt.plot([-1.5, 0, 1.5, 0, -1.5], [0, 1.5, 0, -1.5, 0], "k", linewidth=2) +
plt.fill_between([-1.5, 0, 1.5], [0, -1.5, 0], [0, 1.5, 0], color=".8") +
plt.axvline(0, color="k") +
plt.axhline(0, color="k") +
+
plt.text(-0.9, 2.8, "$x_2$", size=20) +
plt.text(3.6, -0.6, "$x_1$", size=20) +
plt.axis("tight") +
plt.axis("off") +
+
# And now plot the optimization path +
accumulator = [] +
+
+
def f(x): +
# Store the list of function calls +
accumulator.append(x) +
return np.sqrt((x[0] - 3) ** 2 + (x[1] - 2) ** 2) +
+
+
def constraint(x): +
return np.atleast_1d(1.5 - np.sum(np.abs(x))) +
+
+
sp.optimize.minimize( +
f, np.array([0, 0]), method="SLSQP", constraints={"fun": constraint, "type": "ineq"} +
) +
+
accumulated = np.array(accumulator) +
plt.plot(accumulated[:, 0], accumulated[:, 1]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.049 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_smooth.html b/advanced/mathematical_optimization/auto_examples/plot_smooth.html new file mode 100644 index 000000000..2e9a4fd02 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_smooth.html @@ -0,0 +1,252 @@ + + + + + + + + 2.7.4.2. Smooth vs non-smooth — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2.7.4.2. Smooth vs non-smooth

+

Draws a figure to explain smooth versus non smooth optimization.

+
    +
  • plot smooth
  • +
  • plot smooth
  • +
+
import numpy as np
+
import matplotlib.pyplot as plt +
+
x = np.linspace(-1.5, 1.5, 101) +
+
# A smooth function +
plt.figure(1, figsize=(3, 2.5)) +
plt.clf() +
+
plt.plot(x, np.sqrt(0.2 + x**2), linewidth=2) +
plt.text(-1, 0, "$f$", size=20) +
+
plt.ylim(ymin=-0.2) +
plt.axis("off") +
plt.tight_layout() +
+
# A non-smooth function +
plt.figure(2, figsize=(3, 2.5)) +
plt.clf() +
plt.plot(x, np.abs(x), linewidth=2) +
plt.text(-1, 0, "$f$", size=20) +
+
plt.ylim(ymin=-0.2) +
plt.axis("off") +
plt.tight_layout() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.041 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/sg_execution_times.html b/advanced/mathematical_optimization/auto_examples/sg_execution_times.html new file mode 100644 index 000000000..89db96736 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/sg_execution_times.html @@ -0,0 +1,246 @@ + + + + + + + + Computation times — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Computation times

+

00:09.366 total execution time for 11 files from advanced/mathematical_optimization/auto_examples:

+
+ + + + + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Example

Time

Mem (MB)

Gradient descent (plot_gradient_descent.py)

00:06.858

0.0

Alternating optimization (plot_exercise_ill_conditioned.py)

00:01.296

0.0

Plotting the comparison of optimizers (plot_compare_optimizers.py)

00:00.569

0.0

Brent’s method (plot_1d_optim.py)

00:00.231

0.0

Finding a minimum in a flat neighborhood (plot_exercise_flat_minimum.py)

00:00.117

0.0

Constraint optimization: visualizing the geometry (plot_constraints.py)

00:00.089

0.0

Curve fitting (plot_curve_fitting.py)

00:00.053

0.0

Optimization with constraints (plot_non_bounds_constraints.py)

00:00.049

0.0

Convex function (plot_convex.py)

00:00.047

0.0

Smooth vs non-smooth (plot_smooth.py)

00:00.041

0.0

Noisy optimization problem (plot_noisy.py)

00:00.017

0.0

+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/mathematical_optimization/index.html b/advanced/mathematical_optimization/index.html new file mode 100644 index 000000000..c9140bf99 --- /dev/null +++ b/advanced/mathematical_optimization/index.html @@ -0,0 +1,1269 @@ + + + + + + + + 2.7. Mathematical optimization: finding minima of functions — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

2.7. Mathematical optimization: finding minima of functions

+

Authors: Gaël Varoquaux

+

Mathematical optimization deals with the +problem of finding numerically minimums (or maximums or zeros) of +a function. In this context, the function is called cost function, or +objective function, or energy.

+

Here, we are interested in using scipy.optimize for black-box +optimization: we do not rely on the mathematical expression of the +function that we are optimizing. Note that this expression can often be +used for more efficient, non black-box, optimization.

+ +
+

See also

+

References

+

Mathematical optimization is very … mathematical. If you want +performance, it really pays to read the books:

+ +
+ +
+

2.7.1. Knowing your problem

+

Not all optimization problems are equal. Knowing your problem enables you +to choose the right tool.

+ +
+

2.7.1.1. Convex versus non-convex optimization

+ ++++ + + + + + + + + +

convex_1d_1

convex_1d_2

A convex function:

+
    +
  • f is above all its tangents.

  • +
  • equivalently, for two point A, B, f(C) lies below the segment +[f(A), f(B])], if A < C < B

  • +
+

A non-convex function

+

Optimizing convex functions is easy. Optimizing non-convex functions can +be very hard.

+
+

Note

+

It can be proven that for a convex function a local minimum is +also a global minimum. Then, in some sense, the minimum is unique.

+
+
+
+

2.7.1.2. Smooth and non-smooth problems

+ ++++ + + + + + + + + +

smooth_1d_1

smooth_1d_2

A smooth function:

+

The gradient is defined everywhere, and is a continuous function

+

A non-smooth function

+

Optimizing smooth functions is easier +(true in the context of black-box optimization, otherwise +Linear Programming +is an example of methods which deal very efficiently with +piece-wise linear functions).

+
+
+

2.7.1.3. Noisy versus exact cost functions

+ ++++ + + + + + +

Noisy (blue) and non-noisy (green) functions

noisy

+ +
+
+

2.7.1.4. Constraints

+ ++++ + + + + + +

Optimizations under constraints

+

Here:

+

-1 < x_1 < 1

+

-1 < x_2 < 1

+

constraints

+
+
+
+

2.7.2. A review of the different optimizers

+
+

2.7.2.1. Getting started: 1D optimization

+

Let’s get started by finding the minimum of the scalar function +f(x)=\exp[(x-0.5)^2]. scipy.optimize.minimize_scalar() uses +Brent’s method to find the minimum of a function:

+
>>> import numpy as np
+
>>> import scipy as sp +
>>> def f(x): +
... return -np.exp(-(x - 0.5)**2) +
>>> result = sp.optimize.minimize_scalar(f) +
>>> result.success # check if solver was successful +
True +
>>> x_min = result.x +
>>> x_min +
np.float64(0.50...) +
>>> x_min - 0.5 +
np.float64(5.8...e-09) +
+
+ + ++++ + + + + + +
Brent’s method on a quadratic function: it + converges in 3 iterations, as the quadratic + approximation is then exact.

1d_optim_1

1d_optim_2

+ + ++++ + + + + + +
Brent’s method on a non-convex function: note that + the fact that the optimizer avoided the local minimum + is a matter of luck.

1d_optim_3

1d_optim_4

+
+

Note

+

You can use different solvers using the parameter method.

+
+
+

Note

+

scipy.optimize.minimize_scalar() can also be used for optimization +constrained to an interval using the parameter bounds.

+
+
+
+

2.7.2.2. Gradient based methods

+
+

Some intuitions about gradient descent

+

Here we focus on intuitions, not code. Code will follow.

+

Gradient descent +basically consists in taking small steps in the direction of the +gradient, that is the direction of the steepest descent.

+ + +++++ + + + + + + + + + + +
Fixed step gradient descent

A well-conditioned quadratic function.

gradient_quad_cond

gradient_quad_cond_conv

An ill-conditioned quadratic function.

+

The core problem of gradient-methods on ill-conditioned problems is +that the gradient tends not to point in the direction of the +minimum.

+

gradient_quad_icond

gradient_quad_icond_conv

+

We can see that very anisotropic (ill-conditioned) functions are harder +to optimize.

+ +

Also, it clearly can be advantageous to take bigger steps. This +is done in gradient descent code using a +line search.

+ + +++++ + + + + + + + + + + + + + + + + + + +
Adaptive step gradient descent

A well-conditioned quadratic function.

agradient_quad_cond

agradient_quad_cond_conv

An ill-conditioned quadratic function.

agradient_quad_icond

agradient_quad_icond_conv

An ill-conditioned non-quadratic function.

agradient_gauss_icond

agradient_gauss_icond_conv

An ill-conditioned very non-quadratic function.

agradient_rosen_icond

agradient_rosen_icond_conv

+

The more a function looks like a quadratic function (elliptic +iso-curves), the easier it is to optimize.

+
+
+

Conjugate gradient descent

+

The gradient descent algorithms above are toys not to be used on real +problems.

+

As can be seen from the above experiments, one of the problems of the +simple gradient descent algorithms, is that it tends to oscillate across +a valley, each time following the direction of the gradient, that makes +it cross the valley. The conjugate gradient solves this problem by adding +a friction term: each step depends on the two last values of the +gradient and sharp turns are reduced.

+ + +++++ + + + + + + + + + + +
Conjugate gradient descent

An ill-conditioned non-quadratic function.

cg_gauss_icond

cg_gauss_icond_conv

An ill-conditioned very non-quadratic function.

cg_rosen_icond

cg_rosen_icond_conv

+

SciPy provides scipy.optimize.minimize() to find the minimum of scalar +functions of one or more variables. The simple conjugate gradient method can +be used by setting the parameter method to CG

+
>>> def f(x):   # The rosenbrock function
+
... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2 +
>>> sp.optimize.minimize(f, [2, -1], method="CG") +
message: Optimization terminated successfully. +
success: True +
status: 0 +
fun: 1.650...e-11 +
x: [ 1.000e+00 1.000e+00] +
nit: 13 +
jac: [-6.15...e-06 2.53...e-07] +
nfev: 81 +
njev: 27 +
+
+

Gradient methods need the Jacobian (gradient) of the function. They can compute it +numerically, but will perform better if you can pass them the gradient:

+
>>> def jacobian(x):
+
... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] - x[0]**2))) +
>>> sp.optimize.minimize(f, [2, 1], method="CG", jac=jacobian) +
message: Optimization terminated successfully. +
success: True +
status: 0 +
fun: 2.95786...e-14 +
x: [ 1.000e+00 1.000e+00] +
nit: 8 +
jac: [ 7.183e-07 -2.990e-07] +
nfev: 16 +
njev: 16 +
+
+

Note that the function has only been evaluated 27 times, compared to 108 +without the gradient.

+
+
+
+

2.7.2.3. Newton and quasi-newton methods

+
+

Newton methods: using the Hessian (2nd differential)

+

Newton methods use a +local quadratic approximation to compute the jump direction. For this +purpose, they rely on the 2 first derivative of the function: the +gradient and the Hessian.

+ +++++ + + + + + + + + + + + + + + +

An ill-conditioned quadratic function:

+

Note that, as the quadratic approximation is exact, the Newton +method is blazing fast

+

ncg_quad_icond

ncg_quad_icond_conv

An ill-conditioned non-quadratic function:

+

Here we are optimizing a Gaussian, which is always below its +quadratic approximation. As a result, the Newton method overshoots +and leads to oscillations.

+

ncg_gauss_icond

ncg_gauss_icond_conv

An ill-conditioned very non-quadratic function:

ncg_rosen_icond

ncg_rosen_icond_conv

+

In SciPy, you can use the Newton method by setting method to Newton-CG in +scipy.optimize.minimize(). Here, CG refers to the fact that an internal +inversion of the Hessian is performed by conjugate gradient

+
>>> def f(x):   # The rosenbrock function
+
... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2 +
>>> def jacobian(x): +
... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] - x[0]**2))) +
>>> sp.optimize.minimize(f, [2,-1], method="Newton-CG", jac=jacobian) +
message: Optimization terminated successfully. +
success: True +
status: 0 +
fun: 1.5601357400786612e-15 +
x: [ 1.000e+00 1.000e+00] +
nit: 10 +
jac: [ 1.058e-07 -7.483e-08] +
nfev: 11 +
njev: 33 +
nhev: 0 +
+
+

Note that compared to a conjugate gradient (above), Newton’s method has +required less function evaluations, but more gradient evaluations, as it +uses it to approximate the Hessian. Let’s compute the Hessian and pass it +to the algorithm:

+
>>> def hessian(x): # Computed with sympy
+
... return np.array(((1 - 4*x[1] + 12*x[0]**2, -4*x[0]), (-4*x[0], 2))) +
>>> sp.optimize.minimize(f, [2,-1], method="Newton-CG", jac=jacobian, hess=hessian) +
message: Optimization terminated successfully. +
success: True +
status: 0 +
fun: 1.6277298383706738e-15 +
x: [ 1.000e+00 1.000e+00] +
nit: 10 +
jac: [ 1.110e-07 -7.781e-08] +
nfev: 11 +
njev: 11 +
nhev: 10 +
+
+
+

Note

+

At very high-dimension, the inversion of the Hessian can be costly +and unstable (large scale > 250).

+
+
+

Note

+

Newton optimizers should not to be confused with Newton’s root finding +method, based on the same principles, scipy.optimize.newton().

+
+
+
+

Quasi-Newton methods: approximating the Hessian on the fly

+

BFGS: BFGS (Broyden-Fletcher-Goldfarb-Shanno algorithm) refines at +each step an approximation of the Hessian.

+
+
+
+
+

2.7.3. Full code examples

+
+
+

2.7.4. Examples for the mathematical optimization chapter

+
+

Noisy optimization problem

+
Noisy optimization problem
+
+

Smooth vs non-smooth

+
Smooth vs non-smooth
+
+

Curve fitting

+
Curve fitting
+
+

Convex function

+
Convex function
+
+

Finding a minimum in a flat neighborhood

+
Finding a minimum in a flat neighborhood
+
+

Optimization with constraints

+
Optimization with constraints
+
+

Brent’s method

+
Brent's method
+
+

Constraint optimization: visualizing the geometry

+
Constraint optimization: visualizing the geometry
+
+

Alternating optimization

+
Alternating optimization
+
+

Plotting the comparison of optimizers

+
Plotting the comparison of optimizers
+
+

Gradient descent

+
Gradient descent
+
+
+ +

Gallery generated by Sphinx-Gallery

+ +++++ + + + + + + + + + + + + + + +

An ill-conditioned quadratic function:

+

On a exactly quadratic function, BFGS is not as fast as Newton’s +method, but still very fast.

+

bfgs_quad_icond

bfgs_quad_icond_conv

An ill-conditioned non-quadratic function:

+

Here BFGS does better than Newton, as its empirical estimate of the +curvature is better than that given by the Hessian.

+

bfgs_gauss_icond

bfgs_gauss_icond_conv

An ill-conditioned very non-quadratic function:

bfgs_rosen_icond

bfgs_rosen_icond_conv

+
>>> def f(x):   # The rosenbrock function
+
... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2 +
>>> def jacobian(x): +
... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] - x[0]**2))) +
>>> sp.optimize.minimize(f, [2, -1], method="BFGS", jac=jacobian) +
message: Optimization terminated successfully. +
success: True +
status: 0 +
fun: 2.630637192365927e-16 +
x: [ 1.000e+00 1.000e+00] +
nit: 8 +
jac: [ 6.709e-08 -3.222e-08] +
hess_inv: [[ 9.999e-01 2.000e+00] +
[ 2.000e+00 4.499e+00]] +
nfev: 10 +
njev: 10 +
+
+

L-BFGS: Limited-memory BFGS Sits between BFGS and conjugate gradient: +in very high dimensions (> 250) the Hessian matrix is too costly to +compute and invert. L-BFGS keeps a low-rank version. In addition, box bounds +are also supported by L-BFGS-B:

+
>>> def f(x):   # The rosenbrock function
+
... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2 +
>>> def jacobian(x): +
... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] - x[0]**2))) +
>>> sp.optimize.minimize(f, [2, 2], method="L-BFGS-B", jac=jacobian) +
message: CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL +
success: True +
status: 0 +
fun: 1.4417677473...e-15 +
x: [ 1.000e+00 1.000e+00] +
nit: 16 +
jac: [ 1.023e-07 -2.593e-08] +
nfev: 17 +
njev: 17 +
hess_inv: <2x2 LbfgsInvHessProduct with dtype=float64> +
+
+
+

2.7.4.12. Gradient-less methods

+
+

A shooting method: the Powell algorithm

+

Almost a gradient approach

+ +++++ + + + + + + + + + + +

An ill-conditioned quadratic function:

+

Powell’s method isn’t too sensitive to local ill-conditionning in +low dimensions

+

powell_quad_icond

powell_quad_icond_conv

An ill-conditioned very non-quadratic function:

powell_rosen_icond

powell_rosen_icond_conv

+
+
+

Simplex method: the Nelder-Mead

+

The Nelder-Mead algorithms is a generalization of dichotomy approaches to +high-dimensional spaces. The algorithm works by refining a simplex, the generalization of intervals +and triangles to high-dimensional spaces, to bracket the minimum.

+

Strong points: it is robust to noise, as it does not rely on +computing gradients. Thus it can work on functions that are not locally +smooth such as experimental data points, as long as they display a +large-scale bell-shape behavior. However it is slower than gradient-based +methods on smooth, non-noisy functions.

+ +++++ + + + + + + + + + + +

An ill-conditioned non-quadratic function:

nm_gauss_icond

nm_gauss_icond_conv

An ill-conditioned very non-quadratic function:

nm_rosen_icond

nm_rosen_icond_conv

+

Using the Nelder-Mead solver in scipy.optimize.minimize():

+
>>> def f(x):   # The rosenbrock function
+
... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2 +
>>> sp.optimize.minimize(f, [2, -1], method="Nelder-Mead") +
message: Optimization terminated successfully. +
success: True +
status: 0 +
fun: 1.11527915993744e-10 +
x: [ 1.000e+00 1.000e+00] +
nit: 58 +
nfev: 111 +
final_simplex: (array([[ 1.000e+00, 1.000e+00], +
[ 1.000e+00, 1.000e+00], +
[ 1.000e+00, 1.000e+00]]), array([ 1.115e-10, 1.537e-10, 4.988e-10])) +
+
+
+
+
+

2.7.4.13. Global optimizers

+

If your problem does not admit a unique local minimum (which can be hard +to test unless the function is convex), and you do not have prior +information to initialize the optimization close to the solution, you +may need a global optimizer.

+ +
+
+
+

2.7.5. Practical guide to optimization with SciPy

+
+

2.7.5.1. Choosing a method

+

All methods are exposed as the method argument of +scipy.optimize.minimize().

+../../_images/sphx_glr_plot_compare_optimizers_001.png + +
+
Without knowledge of the gradient:
+
    +
  • In general, prefer BFGS or L-BFGS, even if you have to approximate +numerically gradients. These are also the default if you omit the parameter +method - depending if the problem has constraints or bounds

  • +
  • On well-conditioned problems, Powell +and Nelder-Mead, both gradient-free methods, work well in +high dimension, but they collapse for ill-conditioned problems.

  • +
+
+
With knowledge of the gradient:
+
    +
  • BFGS or L-BFGS.

  • +
  • Computational overhead of BFGS is larger than that L-BFGS, itself +larger than that of conjugate gradient. On the other side, BFGS usually +needs less function evaluations than CG. Thus conjugate gradient method +is better than BFGS at optimizing computationally cheap functions.

  • +
+
+
With the Hessian:
+
    +
  • If you can compute the Hessian, prefer the Newton method +(Newton-CG or TCG).

  • +
+
+
If you have noisy measurements:
+
    +
  • Use Nelder-Mead or Powell.

  • +
+
+
+
+
+

2.7.5.2. Making your optimizer faster

+
    +
  • Choose the right method (see above), do compute analytically the +gradient and Hessian, if you can.

  • +
  • Use preconditionning +when possible.

  • +
  • Choose your initialization points wisely. For instance, if you are +running many similar optimizations, warm-restart one with the results of +another.

  • +
  • Relax the tolerance if you don’t need precision using the parameter tol.

  • +
+
+
+

2.7.5.3. Computing gradients

+

Computing gradients, and even more Hessians, is very tedious but worth +the effort. Symbolic computation with Sympy may come in +handy.

+
+

Warning

+

A very common source of optimization not converging well is human +error in the computation of the gradient. You can use +scipy.optimize.check_grad() to check that your gradient is +correct. It returns the norm of the different between the gradient +given, and a gradient computed numerically:

+
>>> sp.optimize.check_grad(f, jacobian, [2, -1])
+
np.float64(2.384185791015625e-07) +
+
+

See also scipy.optimize.approx_fprime() to find your errors.

+
+
+
+

2.7.5.4. Synthetic exercises

+../../_images/sphx_glr_plot_exercise_ill_conditioned_001.png + + + +
+
+
+

2.7.6. Special case: non-linear least-squares

+
+

2.7.6.1. Minimizing the norm of a vector function

+

Least square problems, minimizing the norm of a vector function, have a +specific structure that can be used in the Levenberg–Marquardt algorithm +implemented in scipy.optimize.leastsq().

+

Lets try to minimize the norm of the following vectorial function:

+
>>> def f(x):
+
... return np.arctan(x) - np.arctan(np.linspace(0, 1, len(x))) +
+
>>> x0 = np.zeros(10) +
>>> sp.optimize.leastsq(f, x0) +
(array([0. , 0.11111111, 0.22222222, 0.33333333, 0.44444444, +
0.55555556, 0.66666667, 0.77777778, 0.88888889, 1. ]), 2) +
+
+

This took 67 function evaluations (check it with ‘full_output=1’). What +if we compute the norm ourselves and use a good generic optimizer +(BFGS):

+
>>> def g(x):
+
... return np.sum(f(x)**2) +
>>> result = sp.optimize.minimize(g, x0, method="BFGS") +
>>> result.fun +
np.float64(2.6940...e-11) +
+
+

BFGS needs more function calls, and gives a less precise result.

+
+

Note

+

leastsq is interesting compared to BFGS only if the +dimensionality of the output vector is large, and larger than the number +of parameters to optimize.

+
+
+

Warning

+

If the function is linear, this is a linear-algebra problem, and +should be solved with scipy.linalg.lstsq().

+
+
+
+

2.7.6.2. Curve fitting

+../../_images/sphx_glr_plot_curve_fitting_001.png + +

Least square problems occur often when fitting a non-linear to data. +While it is possible to construct our optimization problem ourselves, +SciPy provides a helper function for this purpose: +scipy.optimize.curve_fit():

+
>>> def f(t, omega, phi):
+
... return np.cos(omega * t + phi) +
+
>>> x = np.linspace(0, 3, 50) +
>>> rng = np.random.default_rng(27446968) +
>>> y = f(x, 1.5, 1) + .1*rng.normal(size=50) +
+
>>> sp.optimize.curve_fit(f, x, y) +
(array([1.4812..., 0.9999...]), array([[ 0.0003..., -0.0004...], +
[-0.0004..., 0.0010...]])) +
+
+ +
+
+
+

2.7.7. Optimization with constraints

+
+

2.7.7.1. Box bounds

+

Box bounds correspond to limiting each of the individual parameters of +the optimization. Note that some problems that are not originally written +as box bounds can be rewritten as such via change of variables. Both +scipy.optimize.minimize_scalar() and scipy.optimize.minimize() +support bound constraints with the parameter bounds:

+
>>> def f(x):
+
... return np.sqrt((x[0] - 3)**2 + (x[1] - 2)**2) +
>>> sp.optimize.minimize(f, np.array([0, 0]), bounds=((-1.5, 1.5), (-1.5, 1.5))) +
message: CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL +
success: True +
status: 0 +
fun: 1.5811388300841898 +
x: [ 1.500e+00 1.500e+00] +
nit: 2 +
jac: [-9.487e-01 -3.162e-01] +
nfev: 9 +
njev: 3 +
hess_inv: <2x2 LbfgsInvHessProduct with dtype=float64> +
+
+../../_images/sphx_glr_plot_constraints_002.png + +
+
+

2.7.7.2. General constraints

+

Equality and inequality constraints specified as functions: f(x) = 0 +and g(x) < 0.

+
    +
  • scipy.optimize.fmin_slsqp() Sequential least square programming: +equality and inequality constraints:

    +../../_images/sphx_glr_plot_non_bounds_constraints_001.png + +
    >>> def f(x):
    +
    ... return np.sqrt((x[0] - 3)**2 + (x[1] - 2)**2) +
    +
    >>> def constraint(x): +
    ... return np.atleast_1d(1.5 - np.sum(np.abs(x))) +
    +
    >>> x0 = np.array([0, 0]) +
    >>> sp.optimize.minimize(f, x0, constraints={"fun": constraint, "type": "ineq"}) +
    message: Optimization terminated successfully +
    success: True +
    status: 0 +
    fun: 2.47487373504... +
    x: [ 1.250e+00 2.500e-01] +
    nit: 5 +
    jac: [-7.071e-01 -7.071e-01] +
    nfev: 15 +
    njev: 5 +
    +
    +
  • +
+
+

Warning

+

The above problem is known as the Lasso +problem in statistics, and there exist very efficient solvers for it +(for instance in scikit-learn). In +general do not use generic solvers when specific ones exist.

+
+ +
+
+
+

2.7.8. Full code examples

+
+
+

2.7.9. Examples for the mathematical optimization chapter

+
+

Noisy optimization problem

+
Noisy optimization problem
+
+

Smooth vs non-smooth

+
Smooth vs non-smooth
+
+

Curve fitting

+
Curve fitting
+
+

Convex function

+
Convex function
+
+

Finding a minimum in a flat neighborhood

+
Finding a minimum in a flat neighborhood
+
+

Optimization with constraints

+
Optimization with constraints
+
+

Brent’s method

+
Brent's method
+
+

Constraint optimization: visualizing the geometry

+
Constraint optimization: visualizing the geometry
+
+

Alternating optimization

+
Alternating optimization
+
+

Plotting the comparison of optimizers

+
Plotting the comparison of optimizers
+
+

Gradient descent

+
Gradient descent
+
+
+ +

Gallery generated by Sphinx-Gallery

+
+

See also

+

Other Software

+

SciPy tries to include the best well-established, general-use, +and permissively-licensed optimization algorithms available. However, +even better options for a given task may be available in other libraries; +please also see IPOPT and PyGMO.

+
+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/optimizing/index.html b/advanced/optimizing/index.html new file mode 100644 index 000000000..20fe8049f --- /dev/null +++ b/advanced/optimizing/index.html @@ -0,0 +1,650 @@ + + + + + + + + 2.4. Optimizing code — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

2.4. Optimizing code

+ +

Author: Gaël Varoquaux

+

This chapter deals with strategies to make Python code go faster.

+ + +
+

2.4.1. Optimization workflow

+
    +
  1. Make it work: write the code in a simple legible ways.

  2. +
  3. Make it work reliably: write automated test cases, make really sure +that your algorithm is right and that if you break it, the tests will +capture the breakage.

  4. +
  5. Optimize the code by profiling simple use-cases to find the +bottlenecks and speeding up these bottleneck, finding a better +algorithm or implementation. Keep in mind that a trade off should be +found between profiling on a realistic example and the simplicity and +speed of execution of the code. For efficient work, it is best to work +with profiling runs lasting around 10s.

  6. +
+
+
+

2.4.2. Profiling Python code

+ +
+

2.4.2.1. Timeit

+

In IPython, use timeit (https://docs.python.org/3/library/timeit.html) to time elementary operations:

+
In [1]: import numpy as np
+
+
In [2]: a = np.arange(1000) +
+
In [3]: %timeit a ** 2 +
934 ns +- 2.49 ns per loop (mean +- std. dev. of 7 runs, 1,000,000 loops each) +
+
In [4]: %timeit a ** 2.1 +
15.8 us +- 185 ns per loop (mean +- std. dev. of 7 runs, 100,000 loops each) +
+
In [5]: %timeit a * a +
1.03 us +- 3.59 ns per loop (mean +- std. dev. of 7 runs, 1,000,000 loops each) +
+
+

Use this to guide your choice between strategies.

+
+

Note

+

For long running calls, using %time instead of %timeit; it is +less precise but faster

+
+
+
+

2.4.2.2. Profiler

+

Useful when you have a large program to profile, for example the +following file:

+
# For this example to run, you also need the 'ica.py' file
+
+
import numpy as np +
import scipy as sp +
+
from ica import fastica +
+
+
# @profile # uncomment this line to run with line_profiler +
def test(): +
rng = np.random.default_rng() +
data = rng.random((5000, 100)) +
u, s, v = sp.linalg.svd(data) +
pca = u[:, :10].T @ data +
results = fastica(pca.T, whiten=False) +
+
+
if __name__ == "__main__": +
test() +
+
+
+

Note

+

This is a combination of two unsupervised learning techniques, principal +component analysis (PCA) and +independent component analysis +(ICA). PCA +is a technique for dimensionality reduction, i.e. an algorithm to explain +the observed variance in your data using less dimensions. ICA is a source +separation technique, for example to unmix multiple signals that have been +recorded through multiple sensors. Doing a PCA first and then an ICA can be +useful if you have more sensors than signals. For more information see: +the FastICA example from scikits-learn.

+
+

To run it, you also need to download the ica module. +In IPython we can time the script:

+
In [6]: %run -t demo.py
+
IPython CPU timings (estimated): +
User : 14.3929 s. +
System: 0.256016 s. +
+
+

and profile it:

+
In [7]: %run -p demo.py
+
916 function calls in 14.551 CPU seconds +
Ordered by: internal time +
ncalls tottime percall cumtime percall filename:lineno (function) +
1 14.457 14.457 14.479 14.479 decomp.py:849 (svd) +
1 0.054 0.054 0.054 0.054 {method 'random_sample' of 'mtrand.RandomState' objects} +
1 0.017 0.017 0.021 0.021 function_base.py:645 (asarray_chkfinite) +
54 0.011 0.000 0.011 0.000 {numpy.core._dotblas.dot} +
2 0.005 0.002 0.005 0.002 {method 'any' of 'numpy.ndarray' objects} +
6 0.001 0.000 0.001 0.000 ica.py:195 (gprime) +
6 0.001 0.000 0.001 0.000 ica.py:192 (g) +
14 0.001 0.000 0.001 0.000 {numpy.linalg.lapack_lite.dsyevd} +
19 0.001 0.000 0.001 0.000 twodim_base.py:204 (diag) +
1 0.001 0.001 0.008 0.008 ica.py:69 (_ica_par) +
1 0.001 0.001 14.551 14.551 {execfile} +
107 0.000 0.000 0.001 0.000 defmatrix.py:239 (__array_finalize__) +
7 0.000 0.000 0.004 0.001 ica.py:58 (_sym_decorrelation) +
7 0.000 0.000 0.002 0.000 linalg.py:841 (eigh) +
172 0.000 0.000 0.000 0.000 {isinstance} +
1 0.000 0.000 14.551 14.551 demo.py:1 (<module>) +
29 0.000 0.000 0.000 0.000 numeric.py:180 (asarray) +
35 0.000 0.000 0.000 0.000 defmatrix.py:193 (__new__) +
35 0.000 0.000 0.001 0.000 defmatrix.py:43 (asmatrix) +
21 0.000 0.000 0.001 0.000 defmatrix.py:287 (__mul__) +
41 0.000 0.000 0.000 0.000 {numpy.core.multiarray.zeros} +
28 0.000 0.000 0.000 0.000 {method 'transpose' of 'numpy.ndarray' objects} +
1 0.000 0.000 0.008 0.008 ica.py:97 (fastica) +
... +
+
+

Clearly the svd (in decomp.py) is what takes most of our time, a.k.a. the +bottleneck. We have to find a way to make this step go faster, or to avoid this +step (algorithmic optimization). Spending time on the rest of the code is +useless.

+ +
+
+

2.4.2.3. Line-profiler

+

The profiler tells us which function takes most of the time, but not +where it is called.

+

For this, we use the +line_profiler: in the +source file, we decorate a few functions that we want to inspect with +@profile (no need to import it)

+
@profile
+
def test(): +
rng = np.random.default_rng() +
data = rng.random((5000, 100)) +
u, s, v = linalg.svd(data) +
pca = u[:, :10] @ data +
results = fastica(pca.T, whiten=False) +
+
+

Then we run the script using the kernprof command, with switches -l, --line-by-line and -v, --view to use the line-by-line profiler and view the results in addition to saving them:

+
$ kernprof -l -v demo.py
+
+
Wrote profile results to demo.py.lprof +
Timer unit: 1e-06 s +
+
Total time: 1.27874 s +
File: demo.py +
Function: test at line 9 +
+
Line # Hits Time Per Hit % Time Line Contents +
============================================================== +
9 @profile +
10 def test(): +
11 1 69.0 69.0 0.0 rng = np.random.default_rng() +
12 1 2453.0 2453.0 0.2 data = rng.random((5000, 100)) +
13 1 1274715.0 1274715.0 99.7 u, s, v = sp.linalg.svd(data) +
14 1 413.0 413.0 0.0 pca = u[:, :10].T @ data +
15 1 1094.0 1094.0 0.1 results = fastica(pca.T, whiten=False) +
+
+

The SVD is taking all the time. We need to optimise this line.

+
+
+
+

2.4.3. Making code go faster

+

Once we have identified the bottlenecks, we need to make the +corresponding code go faster.

+
+

2.4.3.1. Algorithmic optimization

+

The first thing to look for is algorithmic optimization: are there ways +to compute less, or better?

+

For a high-level view of the problem, a good understanding of the maths +behind the algorithm helps. However, it is not uncommon to find simple +changes, like moving computation or memory allocation outside a for +loop, that bring in big gains.

+
+

Example of the SVD

+

In both examples above, the SVD - +Singular Value Decomposition +- is what +takes most of the time. Indeed, the computational cost of this algorithm is +roughly n^3 in the size of the input matrix.

+

However, in both of these example, we are not using all the output of +the SVD, but only the first few rows of its first return argument. If +we use the svd implementation of SciPy, we can ask for an incomplete +version of the SVD. Note that implementations of linear algebra in +SciPy are richer then those in NumPy and should be preferred.

+
In [8]: %timeit np.linalg.svd(data)
+
1 loops, best of 3: 14.5 s per loop +
+
In [9]: import scipy as sp +
+
In [10]: %timeit sp.linalg.svd(data) +
1 loops, best of 3: 14.2 s per loop +
+
In [11]: %timeit sp.linalg.svd(data, full_matrices=False) +
1 loops, best of 3: 295 ms per loop +
+
In [12]: %timeit np.linalg.svd(data, full_matrices=False) +
1 loops, best of 3: 293 ms per loop +
+
+

We can then use this insight to optimize the previous code:

+
def test():
+
rng = np.random.default_rng() +
data = rng.random((5000, 100)) +
u, s, v = sp.linalg.svd(data, full_matrices=False) +
pca = u[:, :10].T @ data +
results = fastica(pca.T, whiten=False) +
+
+
In [13]: import demo
+
+
In [14]: %timeit demo. +
demo.fastica demo.np demo.prof.pdf demo.py demo.pyc +
demo.linalg demo.prof demo.prof.png demo.py.lprof demo.test +
+
In [15]: %timeit demo.test() +
ica.py:65: RuntimeWarning: invalid value encountered in sqrt +
W = (u * np.diag(1.0/np.sqrt(s)) * u.T) * W # W = (W * W.T) ^{-1/2} * W +
1 loops, best of 3: 17.5 s per loop +
+
In [16]: import demo_opt +
+
In [17]: %timeit demo_opt.test() +
1 loops, best of 3: 208 ms per loop +
+
+

Real incomplete SVDs, e.g. computing only the first 10 eigenvectors, can +be computed with arpack, available in scipy.sparse.linalg.eigsh.

+ +
+
+
+
+

2.4.4. Writing faster numerical code

+

A complete discussion on advanced use of NumPy is found in chapter +Advanced NumPy, or in the article The NumPy array: a structure +for efficient numerical computation +by van der Walt et al. Here we +discuss only some commonly encountered tricks to make code faster.

+
    +
  • Vectorizing for loops

    +

    Find tricks to avoid for loops using NumPy arrays. For this, masks and +indices arrays can be useful.

    +
  • +
  • Broadcasting

    +

    Use broadcasting to do operations on arrays as +small as possible before combining them.

    +
  • +
+
    +
  • In place operations

    +
    In [18]: a = np.zeros(1e7)
    +
    +
    In [19]: %timeit global a ; a = 0*a +
    10 loops, best of 3: 111 ms per loop +
    +
    In [20]: %timeit global a ; a *= 0 +
    10 loops, best of 3: 48.4 ms per loop +
    +
    +

    note: we need global a in the timeit so that it work, as it is +assigning to a, and thus considers it as a local variable.

    +
  • +
  • Be easy on the memory: use views, and not copies

    +

    Copying big arrays is as costly as making simple numerical operations +on them:

    +
    In [21]: a = np.zeros(1e7)
    +
    +
    In [22]: %timeit a.copy() +
    10 loops, best of 3: 124 ms per loop +
    +
    In [23]: %timeit a + 1 +
    10 loops, best of 3: 112 ms per loop +
    +
    +
  • +
  • Beware of cache effects

    +

    Memory access is cheaper when it is grouped: accessing a big array in a +continuous way is much faster than random access. This implies amongst +other things that smaller strides are faster (see +CPU cache effects):

    +
    In [24]: c = np.zeros((1e4, 1e4), order='C')
    +
    +
    In [25]: %timeit c.sum(axis=0) +
    1 loops, best of 3: 3.89 s per loop +
    +
    In [26]: %timeit c.sum(axis=1) +
    1 loops, best of 3: 188 ms per loop +
    +
    In [27]: c.strides +
    Out[27]: (80000, 8) +
    +
    +

    This is the reason why Fortran ordering or C ordering may make a big +difference on operations:

    +
    In [28]: rng = np.random.default_rng()
    +
    +
    In [29]: a = rng.random((20, 2**18)) +
    +
    In [30]: b = rng.random((20, 2**18)) +
    +
    In [31]: %timeit b @ a.T +
    8.56 ms +- 83.2 us per loop (mean +- std. dev. of 7 runs, 100 loops each) +
    +
    In [32]: c = np.ascontiguousarray(a.T) +
    +
    In [33]: %timeit b @ c +
    8.79 ms +- 44.5 us per loop (mean +- std. dev. of 7 runs, 100 loops each) +
    +
    +

    Note that copying the data to work around this effect may not be worth it:

    +
    In [34]: %timeit c = np.ascontiguousarray(a.T)
    +
    14.2 ms +- 166 us per loop (mean +- std. dev. of 7 runs, 100 loops each) +
    +
    +

    Using numexpr can be useful to +automatically optimize code for such effects.

    +
  • +
  • Use compiled code

    +

    The last resort, once you are sure that all the high-level +optimizations have been explored, is to transfer the hot spots, i.e. +the few lines or functions in which most of the time is spent, to +compiled code. For compiled code, the preferred option is to use +Cython: it is easy to transform exiting +Python code in compiled code, and with a good use of the +NumPy support +yields efficient code on NumPy arrays, for instance by unrolling loops.

    +
  • +
+
+

Warning

+

For all the above: profile and time your choices. Don’t base your +optimization on theoretical considerations.

+
+ +
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/scipy_sparse/bsr_array.html b/advanced/scipy_sparse/bsr_array.html new file mode 100644 index 000000000..f5b142a58 --- /dev/null +++ b/advanced/scipy_sparse/bsr_array.html @@ -0,0 +1,357 @@ + + + + + + + + Block Compressed Row Format (BSR) — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Block Compressed Row Format (BSR)

+
    +
  • +
    basically a CSR with dense sub-matrices of fixed shape instead of scalar items
      +
    • block size (R, C) must evenly divide the shape of the matrix (M, N)

    • +
    • +
      three NumPy arrays: indices, indptr, data
        +
      • indices is array of column indices for each block

      • +
      • data is array of corresponding nonzero values of shape (nnz, R, C)

      • +
      • +
      +
      +
      +
    • +
    • +
      subclass of _cs_matrix (common CSR/CSC functionality)
        +
      • subclass of _data_matrix (sparse matrix classes with +.data attribute)

      • +
      +
      +
      +
    • +
    +
    +
    +
  • +
  • fast matrix vector products and other arithmetic (sparsetools)

  • +
  • +
    constructor accepts:
      +
    • dense array/matrix

    • +
    • sparse array/matrix

    • +
    • shape tuple (create empty array)

    • +
    • (data, coords) tuple

    • +
    • (data, indices, indptr) tuple

    • +
    +
    +
    +
  • +
  • many arithmetic operations considerably more efficient than CSR for +sparse matrices with dense sub-matrices

  • +
  • +
    use:
      +
    • like CSR

    • +
    • vector-valued finite element discretizations

    • +
    +
    +
    +
  • +
+
+

Examples

+
    +
  • create empty BSR array with (1, 1) block size (like CSR…):

    +
    >>> mtx = sp.sparse.bsr_array((3, 4), dtype=np.int8)
    +
    >>> mtx +
    <Block Sparse Row sparse array of dtype 'int8' +
    with 0 stored elements (blocksize=1x1) and shape (3, 4)> +
    >>> mtx.toarray() +
    array([[0, 0, 0, 0], +
    [0, 0, 0, 0], +
    [0, 0, 0, 0]], dtype=int8) +
    +
    +
  • +
  • create empty BSR array with (3, 2) block size:

    +
    >>> mtx = sp.sparse.bsr_array((3, 4), blocksize=(3, 2), dtype=np.int8)
    +
    >>> mtx +
    <Block Sparse Row sparse array of dtype 'int8' +
    with 0 stored elements (blocksize=3x2) and shape (3, 4)> +
    >>> mtx.toarray() +
    array([[0, 0, 0, 0], +
    [0, 0, 0, 0], +
    [0, 0, 0, 0]], dtype=int8) +
    +
    +
      +
    • a bug?

    • +
    +
  • +
  • create using (data, coords) tuple with (1, 1) block size (like CSR…):

    +
    >>> row = np.array([0, 0, 1, 2, 2, 2])
    +
    >>> col = np.array([0, 2, 2, 0, 1, 2]) +
    >>> data = np.array([1, 2, 3, 4, 5, 6]) +
    >>> mtx = sp.sparse.bsr_array((data, (row, col)), shape=(3, 3)) +
    >>> mtx +
    <Block Sparse Row sparse array of dtype 'int64' +
    with 6 stored elements (blocksize=1x1) and shape (3, 3)> +
    >>> mtx.toarray() +
    array([[1, 0, 2], +
    [0, 0, 3], +
    [4, 5, 6]]...) +
    >>> mtx.data +
    array([[[1]], +
    +
    [[2]], +
    +
    [[3]], +
    +
    [[4]], +
    +
    [[5]], +
    +
    [[6]]]...) +
    >>> mtx.indices +
    array([0, 2, 2, 0, 1, 2]) +
    >>> mtx.indptr +
    array([0, 2, 3, 6]) +
    +
    +
  • +
  • create using (data, indices, indptr) tuple with (2, 2) block size:

    +
    >>> indptr = np.array([0, 2, 3, 6])
    +
    >>> indices = np.array([0, 2, 2, 0, 1, 2]) +
    >>> data = np.array([1, 2, 3, 4, 5, 6]).repeat(4).reshape(6, 2, 2) +
    >>> mtx = sp.sparse.bsr_array((data, indices, indptr), shape=(6, 6)) +
    >>> mtx.toarray() +
    array([[1, 1, 0, 0, 2, 2], +
    [1, 1, 0, 0, 2, 2], +
    [0, 0, 0, 0, 3, 3], +
    [0, 0, 0, 0, 3, 3], +
    [4, 4, 5, 5, 6, 6], +
    [4, 4, 5, 5, 6, 6]]) +
    >>> data +
    array([[[1, 1], +
    [1, 1]], +
    +
    [[2, 2], +
    [2, 2]], +
    +
    [[3, 3], +
    [3, 3]], +
    +
    [[4, 4], +
    [4, 4]], +
    +
    [[5, 5], +
    [5, 5]], +
    +
    [[6, 6], +
    [6, 6]]]) +
    +
    +
  • +
+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/scipy_sparse/coo_array.html b/advanced/scipy_sparse/coo_array.html new file mode 100644 index 000000000..00b422db8 --- /dev/null +++ b/advanced/scipy_sparse/coo_array.html @@ -0,0 +1,314 @@ + + + + + + + + Coordinate Format (COO) — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Coordinate Format (COO)

+
    +
  • +
    also known as the ‘ijv’ or ‘triplet’ format
      +
    • three NumPy arrays: row, col, data.

    • +
    • attribute coords is the tuple (row, col)

    • +
    • data[i] is value at (row[i], col[i]) position

    • +
    • permits duplicate entries

    • +
    • subclass of _data_matrix (sparse matrix classes with +.data attribute)

    • +
    +
    +
    +
  • +
  • fast format for constructing sparse arrays

  • +
  • +
    constructor accepts:
      +
    • dense array/matrix

    • +
    • sparse array/matrix

    • +
    • shape tuple (create empty matrix)

    • +
    • (data, coords) tuple

    • +
    +
    +
    +
  • +
  • very fast conversion to and from CSR/CSC formats

  • +
  • fast matrix * vector (sparsetools)

  • +
  • +
    fast and easy item-wise operations
      +
    • manipulate data array directly (fast NumPy machinery)

    • +
    +
    +
    +
  • +
  • no slicing, no arithmetic (directly, converts to CSR)

  • +
  • +
    use:
      +
    • facilitates fast conversion among sparse formats

    • +
    • when converting to other format (usually CSR or CSC), duplicate +entries are summed together

      +
      +
        +
      • facilitates efficient construction of finite element matrices

      • +
      +
      +
    • +
    +
    +
    +
  • +
+
+

Examples

+
    +
  • create empty COO array:

    +
    >>> mtx = sp.sparse.coo_array((3, 4), dtype=np.int8)
    +
    >>> mtx.toarray() +
    array([[0, 0, 0, 0], +
    [0, 0, 0, 0], +
    [0, 0, 0, 0]], dtype=int8) +
    +
    +
  • +
  • create using (data, ij) tuple:

    +
    >>> row = np.array([0, 3, 1, 0])
    +
    >>> col = np.array([0, 3, 1, 2]) +
    >>> data = np.array([4, 5, 7, 9]) +
    >>> mtx = sp.sparse.coo_array((data, (row, col)), shape=(4, 4)) +
    >>> mtx +
    <COOrdinate sparse array of dtype 'int64' +
    with 4 stored elements and shape (4, 4)> +
    >>> mtx.toarray() +
    array([[4, 0, 9, 0], +
    [0, 7, 0, 0], +
    [0, 0, 0, 0], +
    [0, 0, 0, 5]]) +
    +
    +
  • +
  • duplicates entries are summed together:

    +
    >>> row = np.array([0, 0, 1, 3, 1, 0, 0])
    +
    >>> col = np.array([0, 2, 1, 3, 1, 0, 0]) +
    >>> data = np.array([1, 1, 1, 1, 1, 1, 1]) +
    >>> mtx = sp.sparse.coo_array((data, (row, col)), shape=(4, 4)) +
    >>> mtx.toarray() +
    array([[3, 0, 1, 0], +
    [0, 2, 0, 0], +
    [0, 0, 0, 0], +
    [0, 0, 0, 1]]) +
    +
    +
  • +
  • no slicing…:

    +
    >>> mtx[2, 3]
    +
    Traceback (most recent call last): +
    ... +
    TypeError: 'coo_array' object ... +
    +
    +
  • +
+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/scipy_sparse/csc_array.html b/advanced/scipy_sparse/csc_array.html new file mode 100644 index 000000000..145524ca6 --- /dev/null +++ b/advanced/scipy_sparse/csc_array.html @@ -0,0 +1,312 @@ + + + + + + + + Compressed Sparse Column Format (CSC) — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Compressed Sparse Column Format (CSC)

+
    +
  • +
    column oriented
      +
    • +
      three NumPy arrays: indices, indptr, data
        +
      • indices is array of row indices

      • +
      • data is array of corresponding nonzero values

      • +
      • indptr points to column starts in indices and data

      • +
      • length is n_col + 1, last item = number of values = length of both +indices and data

      • +
      • nonzero values of the i-th column are data[indptr[i]:indptr[i+1]] +with row indices indices[indptr[i]:indptr[i+1]]

      • +
      • item (i, j) can be accessed as data[indptr[j]+k], where k is +position of i in indices[indptr[j]:indptr[j+1]]

      • +
      +
      +
      +
    • +
    • +
      subclass of _cs_matrix (common CSR/CSC functionality)
        +
      • subclass of _data_matrix (sparse array classes with +.data attribute)

      • +
      +
      +
      +
    • +
    +
    +
    +
  • +
  • fast matrix vector products and other arithmetic (sparsetools)

  • +
  • +
    constructor accepts:
      +
    • dense array/matrix

    • +
    • sparse array/matrix

    • +
    • shape tuple (create empty array)

    • +
    • (data, coords) tuple

    • +
    • (data, indices, indptr) tuple

    • +
    +
    +
    +
  • +
  • efficient column slicing, column-oriented operations

  • +
  • slow row slicing, expensive changes to the sparsity structure

  • +
  • +
    use:
      +
    • actual computations (most linear solvers support this format)

    • +
    +
    +
    +
  • +
+
+

Examples

+
    +
  • create empty CSC array:

    +
    >>> mtx = sp.sparse.csc_array((3, 4), dtype=np.int8)
    +
    >>> mtx.toarray() +
    array([[0, 0, 0, 0], +
    [0, 0, 0, 0], +
    [0, 0, 0, 0]], dtype=int8) +
    +
    +
  • +
  • create using (data, coords) tuple:

    +
    >>> row = np.array([0, 0, 1, 2, 2, 2])
    +
    >>> col = np.array([0, 2, 2, 0, 1, 2]) +
    >>> data = np.array([1, 2, 3, 4, 5, 6]) +
    >>> mtx = sp.sparse.csc_array((data, (row, col)), shape=(3, 3)) +
    >>> mtx +
    <Compressed Sparse Column sparse array of dtype 'int64' +
    with 6 stored elements and shape (3, 3)> +
    >>> mtx.toarray() +
    array([[1, 0, 2], +
    [0, 0, 3], +
    [4, 5, 6]]...) +
    >>> mtx.data +
    array([1, 4, 5, 2, 3, 6]...) +
    >>> mtx.indices +
    array([0, 2, 2, 0, 1, 2]) +
    >>> mtx.indptr +
    array([0, 2, 3, 6]) +
    +
    +
  • +
  • create using (data, indices, indptr) tuple:

    +
    >>> data = np.array([1, 4, 5, 2, 3, 6])
    +
    >>> indices = np.array([0, 2, 2, 0, 1, 2]) +
    >>> indptr = np.array([0, 2, 3, 6]) +
    >>> mtx = sp.sparse.csc_array((data, indices, indptr), shape=(3, 3)) +
    >>> mtx.toarray() +
    array([[1, 0, 2], +
    [0, 0, 3], +
    [4, 5, 6]]) +
    +
    +
  • +
+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/scipy_sparse/csr_array.html b/advanced/scipy_sparse/csr_array.html new file mode 100644 index 000000000..ed48e0438 --- /dev/null +++ b/advanced/scipy_sparse/csr_array.html @@ -0,0 +1,312 @@ + + + + + + + + Compressed Sparse Row Format (CSR) — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Compressed Sparse Row Format (CSR)

+
    +
  • +
    row oriented
      +
    • +
      three NumPy arrays: indices, indptr, data
        +
      • indices is array of column indices

      • +
      • data is array of corresponding nonzero values

      • +
      • indptr points to row starts in indices and data

      • +
      • length of indptr is n_row + 1, +last item = number of values = length of both indices and data

      • +
      • nonzero values of the i-th row are data[indptr[i]:indptr[i + 1]] +with column indices indices[indptr[i]:indptr[i + 1]]

      • +
      • item (i, j) can be accessed as data[indptr[i] + k], where k is +position of j in indices[indptr[i]:indptr[i + 1]]

      • +
      +
      +
      +
    • +
    • +
      subclass of _cs_matrix (common CSR/CSC functionality)
        +
      • subclass of _data_matrix (sparse array classes with +.data attribute)

      • +
      +
      +
      +
    • +
    +
    +
    +
  • +
  • fast matrix vector products and other arithmetic (sparsetools)

  • +
  • +
    constructor accepts:
      +
    • dense array/matrix

    • +
    • sparse array/matrix

    • +
    • shape tuple (create empty array)

    • +
    • (data, coords) tuple

    • +
    • (data, indices, indptr) tuple

    • +
    +
    +
    +
  • +
  • efficient row slicing, row-oriented operations

  • +
  • slow column slicing, expensive changes to the sparsity structure

  • +
  • +
    use:
      +
    • actual computations (most linear solvers support this format)

    • +
    +
    +
    +
  • +
+
+

Examples

+
    +
  • create empty CSR array:

    +
    >>> mtx = sp.sparse.csr_array((3, 4), dtype=np.int8)
    +
    >>> mtx.toarray() +
    array([[0, 0, 0, 0], +
    [0, 0, 0, 0], +
    [0, 0, 0, 0]], dtype=int8) +
    +
    +
  • +
  • create using (data, coords) tuple:

    +
    >>> row = np.array([0, 0, 1, 2, 2, 2])
    +
    >>> col = np.array([0, 2, 2, 0, 1, 2]) +
    >>> data = np.array([1, 2, 3, 4, 5, 6]) +
    >>> mtx = sp.sparse.csr_array((data, (row, col)), shape=(3, 3)) +
    >>> mtx +
    <Compressed Sparse Row sparse array of dtype 'int64' +
    with 6 stored elements and shape (3, 3)> +
    >>> mtx.toarray() +
    array([[1, 0, 2], +
    [0, 0, 3], +
    [4, 5, 6]]...) +
    >>> mtx.data +
    array([1, 2, 3, 4, 5, 6]...) +
    >>> mtx.indices +
    array([0, 2, 2, 0, 1, 2]) +
    >>> mtx.indptr +
    array([0, 2, 3, 6]) +
    +
    +
  • +
  • create using (data, indices, indptr) tuple:

    +
    >>> data = np.array([1, 2, 3, 4, 5, 6])
    +
    >>> indices = np.array([0, 2, 2, 0, 1, 2]) +
    >>> indptr = np.array([0, 2, 3, 6]) +
    >>> mtx = sp.sparse.csr_array((data, indices, indptr), shape=(3, 3)) +
    >>> mtx.toarray() +
    array([[1, 0, 2], +
    [0, 0, 3], +
    [4, 5, 6]]) +
    +
    +
  • +
+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/scipy_sparse/dia_array.html b/advanced/scipy_sparse/dia_array.html new file mode 100644 index 000000000..408a0287c --- /dev/null +++ b/advanced/scipy_sparse/dia_array.html @@ -0,0 +1,344 @@ + + + + + + + + Diagonal Format (DIA) — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Diagonal Format (DIA)

+
    +
  • very simple scheme

  • +
  • +
    diagonals in dense NumPy array of shape (n_diag, length)
      +
    • fixed length -> waste space a bit when far from main diagonal

    • +
    • subclass of _data_matrix (sparse array classes with +.data attribute)

    • +
    +
    +
    +
  • +
  • +
    offset for each diagonal
      +
    • 0 is the main diagonal

    • +
    • negative offset = below

    • +
    • positive offset = above

    • +
    +
    +
    +
  • +
  • fast matrix * vector (sparsetools)

  • +
  • +
    fast and easy item-wise operations
      +
    • manipulate data array directly (fast NumPy machinery)

    • +
    +
    +
    +
  • +
  • +
    constructor accepts:
      +
    • dense array/matrix

    • +
    • sparse array/matrix

    • +
    • shape tuple (create empty array)

    • +
    • (data, offsets) tuple

    • +
    +
    +
    +
  • +
  • no slicing, no individual item access

  • +
  • +
    use:
      +
    • rather specialized

    • +
    • solving PDEs by finite differences

    • +
    • with an iterative solver

    • +
    +
    +
    +
  • +
+
+

Examples

+
    +
  • create some DIA arrays:

    +
    >>> data = np.array([[1, 2, 3, 4]]).repeat(3, axis=0)
    +
    >>> data +
    array([[1, 2, 3, 4], +
    [1, 2, 3, 4], +
    [1, 2, 3, 4]]) +
    >>> offsets = np.array([0, -1, 2]) +
    >>> mtx = sp.sparse.dia_array((data, offsets), shape=(4, 4)) +
    >>> mtx +
    <DIAgonal sparse array of dtype 'int64' +
    with 9 stored elements (3 diagonals) and shape (4, 4)> +
    >>> mtx.toarray() +
    array([[1, 0, 3, 0], +
    [1, 2, 0, 4], +
    [0, 2, 3, 0], +
    [0, 0, 3, 4]]) +
    +
    >>> data = np.arange(12).reshape((3, 4)) + 1 +
    >>> data +
    array([[ 1, 2, 3, 4], +
    [ 5, 6, 7, 8], +
    [ 9, 10, 11, 12]]) +
    >>> mtx = sp.sparse.dia_array((data, offsets), shape=(4, 4)) +
    >>> mtx.data +
    array([[ 1, 2, 3, 4], +
    [ 5, 6, 7, 8], +
    [ 9, 10, 11, 12]]) +
    >>> mtx.offsets +
    array([ 0, -1, 2], dtype=int32) +
    >>> print(mtx) +
    <DIAgonal sparse array of dtype 'int64' +
    with 9 stored elements (3 diagonals) and shape (4, 4)> +
    Coords Values +
    (0, 0) 1 +
    (1, 1) 2 +
    (2, 2) 3 +
    (3, 3) 4 +
    (1, 0) 5 +
    (2, 1) 6 +
    (3, 2) 7 +
    (0, 2) 11 +
    (1, 3) 12 +
    >>> mtx.toarray() +
    array([[ 1, 0, 11, 0], +
    [ 5, 2, 0, 12], +
    [ 0, 6, 3, 0], +
    [ 0, 0, 7, 4]]) +
    +
    +
  • +
  • explanation with a scheme:

    +
    offset: row
    +
    +
    2: 9 +
    1: --10------ +
    0: 1 . 11 . +
    -1: 5 2 . 12 +
    -2: . 6 3 . +
    -3: . . 7 4 +
    ---------8 +
    +
    +
  • +
  • matrix-vector multiplication

    +
    >>> vec = np.ones((4, ))
    +
    >>> vec +
    array([1., 1., 1., 1.]) +
    >>> mtx @ vec +
    array([12., 19., 9., 11.]) +
    >>> (mtx * vec).toarray() +
    array([[ 1., 0., 11., 0.], +
    [ 5., 2., 0., 12.], +
    [ 0., 6., 3., 0.], +
    [ 0., 0., 7., 4.]]) +
    +
    +
  • +
+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/scipy_sparse/dok_array.html b/advanced/scipy_sparse/dok_array.html new file mode 100644 index 000000000..a1beb76c7 --- /dev/null +++ b/advanced/scipy_sparse/dok_array.html @@ -0,0 +1,283 @@ + + + + + + + + Dictionary of Keys Format (DOK) — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Dictionary of Keys Format (DOK)

+
    +
  • +
    subclass of Python dict
      +
    • keys are (row, column) index tuples (no duplicate entries allowed)

    • +
    • values are corresponding non-zero values

    • +
    +
    +
    +
  • +
  • efficient for constructing sparse arrays incrementally

  • +
  • +
    constructor accepts:
      +
    • dense array/matrix

    • +
    • sparse array/matrix

    • +
    • shape tuple (create empty array)

    • +
    +
    +
    +
  • +
  • efficient O(1) access to individual elements

  • +
  • flexible slicing, changing sparsity structure is efficient

  • +
  • can be efficiently converted to a coo_array once constructed

  • +
  • slow arithmetic (for loops with dict.items())

  • +
  • +
    use:
      +
    • when sparsity pattern is not known apriori or changes

    • +
    +
    +
    +
  • +
+
+

Examples

+
    +
  • create a DOK array element by element:

    +
    >>> mtx = sp.sparse.dok_array((5, 5), dtype=np.float64)
    +
    >>> mtx +
    <Dictionary Of Keys sparse array of dtype 'float64' +
    with 0 stored elements and shape (5, 5)> +
    >>> for ir in range(5): +
    ... for ic in range(5): +
    ... mtx[ir, ic] = 1.0 * (ir != ic) +
    >>> mtx +
    <Dictionary Of Keys sparse array of dtype 'float64' +
    with 20 stored elements and shape (5, 5)> +
    >>> mtx.toarray() +
    array([[0., 1., 1., 1., 1.], +
    [1., 0., 1., 1., 1.], +
    [1., 1., 0., 1., 1.], +
    [1., 1., 1., 0., 1.], +
    [1., 1., 1., 1., 0.]]) +
    +
    +
  • +
  • slicing and indexing:

    +
    >>> mtx[1, 1]
    +
    np.float64(0.0) +
    >>> mtx[[1], 1:3] +
    <Dictionary Of Keys sparse array of dtype 'float64' +
    with 1 stored elements and shape (1, 2)> +
    >>> mtx[[1], 1:3].toarray() +
    array([[0., 1.]]) +
    >>> mtx[[2, 1], 1:3].toarray() +
    array([[1., 0.], +
    [0., 1.]]) +
    +
    +
  • +
+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/scipy_sparse/index.html b/advanced/scipy_sparse/index.html new file mode 100644 index 000000000..c0816c372 --- /dev/null +++ b/advanced/scipy_sparse/index.html @@ -0,0 +1,250 @@ + + + + + + + + 2.5. Sparse Arrays in SciPy — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/advanced/scipy_sparse/introduction.html b/advanced/scipy_sparse/introduction.html new file mode 100644 index 000000000..714171ffe --- /dev/null +++ b/advanced/scipy_sparse/introduction.html @@ -0,0 +1,307 @@ + + + + + + + + 2.5.1. Introduction — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

2.5.1. Introduction

+

(dense) matrix is:

+
    +
  • mathematical object

  • +
  • data structure for storing a 2D array of values

  • +
+

important features:

+
    +
  • +
    memory allocated once for all items
      +
    • usually a contiguous chunk, think NumPy ndarray

    • +
    +
    +
    +
  • +
  • fast access to individual items (*)

  • +
+
+

2.5.1.1. Why Sparse Matrices?

+
    +
  • the memory grows like n**2 for dense matrix

  • +
  • small example (double precision matrix):

    +
    >>> import numpy as np
    +
    >>> import matplotlib.pyplot as plt +
    >>> x = np.linspace(0, 1e6, 10) +
    >>> plt.plot(x, 8.0 * (x**2) / 1e6, lw=5) +
    [<matplotlib.lines.Line2D object at ...>] +
    >>> plt.xlabel('size n') +
    Text(...'size n') +
    >>> plt.ylabel('memory [MB]') +
    Text(...'memory [MB]') +
    +
    +
  • +
+
+
+

2.5.1.2. Sparse Matrices vs. Sparse Matrix Storage Schemes

+
    +
  • sparse matrix is a matrix, which is almost empty

  • +
  • storing all the zeros is wasteful -> store only nonzero items

  • +
  • think compression

  • +
  • pros: huge memory savings

  • +
  • cons: slow access to individual items, but it depends on actual storage scheme.

  • +
+
+
+

2.5.1.3. Typical Applications

+
    +
  • +
    solution of partial differential equations (PDEs)
      +
    • the finite element method

    • +
    • mechanical engineering, electrotechnics, physics, …

    • +
    +
    +
    +
  • +
  • +
    graph theory
      +
    • nonzero at (i, j) means that node i is connected to node j

    • +
    +
    +
    +
  • +
  • +
    natural language processing
      +
    • nonzero at (i, j) means that the document i contains the word j

    • +
    +
    +
    +
  • +
  • +
+
+
+

2.5.1.4. Prerequisites

+ +
+
+

2.5.1.5. Sparsity Structure Visualization

+
    +
  • spy() from matplotlib

  • +
  • example plots:

  • +
+../../_images/graph.png +../../_images/graph_g.png +../../_images/graph_rcm.png +

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/scipy_sparse/lil_array.html b/advanced/scipy_sparse/lil_array.html new file mode 100644 index 000000000..e1b8f2b6f --- /dev/null +++ b/advanced/scipy_sparse/lil_array.html @@ -0,0 +1,319 @@ + + + + + + + + List of Lists Format (LIL) — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

List of Lists Format (LIL)

+
    +
  • +
    row-based linked list
      +
    • each row is a Python list (sorted) of column indices of non-zero elements

    • +
    • rows stored in a NumPy array (dtype=np.object)

    • +
    • non-zero values data stored analogously

    • +
    +
    +
    +
  • +
  • efficient for constructing sparse arrays incrementally

  • +
  • +
    constructor accepts:
      +
    • dense array/matrix

    • +
    • sparse array/matrix

    • +
    • shape tuple (create empty array)

    • +
    +
    +
    +
  • +
  • flexible slicing, changing sparsity structure is efficient

  • +
  • slow arithmetic, slow column slicing due to being row-based

  • +
  • +
    use:
      +
    • when sparsity pattern is not known apriori or changes

    • +
    • example: reading a sparse array from a text file

    • +
    +
    +
    +
  • +
+
+

Examples

+
    +
  • create an empty LIL array:

    +
    >>> mtx = sp.sparse.lil_array((4, 5))
    +
    +
    +
  • +
  • prepare random data:

    +
    >>> rng = np.random.default_rng(27446968)
    +
    >>> data = np.round(rng.random((2, 3))) +
    >>> data +
    array([[1., 0., 1.], +
    [0., 0., 1.]]) +
    +
    +
  • +
  • assign the data using fancy indexing:

    +
    >>> mtx[:2, [1, 2, 3]] = data
    +
    >>> mtx +
    <List of Lists sparse array of dtype 'float64' +
    with 3 stored elements and shape (4, 5)> +
    >>> print(mtx) +
    <List of Lists sparse array of dtype 'float64' +
    with 3 stored elements and shape (4, 5)> +
    Coords Values +
    (0, 1) 1.0 +
    (0, 3) 1.0 +
    (1, 3) 1.0 +
    >>> mtx.toarray() +
    array([[0., 1., 0., 1., 0.], +
    [0., 0., 0., 1., 0.], +
    [0., 0., 0., 0., 0.], +
    [0., 0., 0., 0., 0.]]) +
    >>> mtx.toarray() +
    array([[0., 1., 0., 1., 0.], +
    [0., 0., 0., 1., 0.], +
    [0., 0., 0., 0., 0.], +
    [0., 0., 0., 0., 0.]]) +
    +
    +
  • +
  • more slicing and indexing:

    +
    >>> mtx = sp.sparse.lil_array([[0, 1, 2, 0], [3, 0, 1, 0], [1, 0, 0, 1]])
    +
    >>> mtx.toarray() +
    array([[0, 1, 2, 0], +
    [3, 0, 1, 0], +
    [1, 0, 0, 1]]...) +
    >>> print(mtx) +
    <List of Lists sparse array of dtype 'int64' +
    with 6 stored elements and shape (3, 4)> +
    Coords Values +
    (0, 1) 1 +
    (0, 2) 2 +
    (1, 0) 3 +
    (1, 2) 1 +
    (2, 0) 1 +
    (2, 3) 1 +
    >>> mtx[:2, :] +
    <List of Lists sparse array of dtype 'int64' +
    with 4 stored elements and shape (2, 4)> +
    >>> mtx[:2, :].toarray() +
    array([[0, 1, 2, 0], +
    [3, 0, 1, 0]]...) +
    >>> mtx[1:2, [0,2]].toarray() +
    array([[3, 1]]...) +
    >>> mtx.toarray() +
    array([[0, 1, 2, 0], +
    [3, 0, 1, 0], +
    [1, 0, 0, 1]]...) +
    +
    +
  • +
+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/scipy_sparse/other_packages.html b/advanced/scipy_sparse/other_packages.html new file mode 100644 index 000000000..330437f08 --- /dev/null +++ b/advanced/scipy_sparse/other_packages.html @@ -0,0 +1,220 @@ + + + + + + + + 2.5.4. Other Interesting Packages — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

2.5.4. Other Interesting Packages

+ +

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/scipy_sparse/solvers.html b/advanced/scipy_sparse/solvers.html new file mode 100644 index 000000000..fe2403568 --- /dev/null +++ b/advanced/scipy_sparse/solvers.html @@ -0,0 +1,547 @@ + + + + + + + + 2.5.3. Linear System Solvers — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

2.5.3. Linear System Solvers

+
    +
  • sparse matrix/eigenvalue problem solvers live in scipy.sparse.linalg

  • +
  • +
    the submodules:
      +
    • dsolve: direct factorization methods for solving linear systems

    • +
    • isolve: iterative methods for solving linear systems

    • +
    • eigen: sparse eigenvalue problem solvers

    • +
    +
    +
    +
  • +
  • all solvers are accessible from:

    +
    >>> import scipy as sp
    +
    >>> sp.sparse.linalg.__all__ +
    ['ArpackError', 'ArpackNoConvergence', ..., 'use_solver'] +
    +
    +
  • +
+
+

2.5.3.1. Sparse Direct Solvers

+
    +
  • +
    default solver: SuperLU
      +
    • included in SciPy

    • +
    • real and complex systems

    • +
    • both single and double precision

    • +
    +
    +
    +
  • +
  • +
    optional: umfpack
      +
    • real and complex systems

    • +
    • double precision only

    • +
    • recommended for performance

    • +
    • wrappers now live in scikits.umfpack

    • +
    • check-out the new scikits.suitesparse by Nathaniel Smith

    • +
    +
    +
    +
  • +
+
+

Examples

+
    +
  • import the whole module, and see its docstring:

    +
    >>> help(sp.sparse.linalg.spsolve)
    +
    Help on function spsolve in module scipy.sparse.linalg._dsolve.linsolve: +
    ... +
    +
    +
  • +
  • both superlu and umfpack can be used (if the latter is installed) as +follows:

    +
    +
      +
    • prepare a linear system:

      +
      >>> import numpy as np
      +
      >>> mtx = sp.sparse.spdiags([[1, 2, 3, 4, 5], [6, 5, 8, 9, 10]], [0, 1], 5, 5, "csc") +
      >>> mtx.toarray() +
      array([[ 1, 5, 0, 0, 0], +
      [ 0, 2, 8, 0, 0], +
      [ 0, 0, 3, 9, 0], +
      [ 0, 0, 0, 4, 10], +
      [ 0, 0, 0, 0, 5]]) +
      >>> rhs = np.array([1, 2, 3, 4, 5], dtype=np.float32) +
      +
      +
    • +
    • solve as single precision real:

      +
      >>> mtx1 = mtx.astype(np.float32)
      +
      >>> x = sp.sparse.linalg.spsolve(mtx1, rhs, use_umfpack=False) +
      >>> print(x) +
      [106. -21. 5.5 -1.5 1. ] +
      >>> print("Error: %s" % (mtx1 * x - rhs)) +
      Error: [0. 0. 0. 0. 0.] +
      +
      +
    • +
    • solve as double precision real:

      +
      >>> mtx2 = mtx.astype(np.float64)
      +
      >>> x = sp.sparse.linalg.spsolve(mtx2, rhs, use_umfpack=True) +
      >>> print(x) +
      [106. -21. 5.5 -1.5 1. ] +
      >>> print("Error: %s" % (mtx2 * x - rhs)) +
      Error: [0. 0. 0. 0. 0.] +
      +
      +
    • +
    • solve as single precision complex:

      +
      >>> mtx1 = mtx.astype(np.complex64)
      +
      >>> x = sp.sparse.linalg.spsolve(mtx1, rhs, use_umfpack=False) +
      >>> print(x) +
      [106. +0.j -21. +0.j 5.5+0.j -1.5+0.j 1. +0.j] +
      >>> print("Error: %s" % (mtx1 * x - rhs)) +
      Error: [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j] +
      +
      +
    • +
    • solve as double precision complex:

      +
      >>> mtx2 = mtx.astype(np.complex128)
      +
      >>> x = sp.sparse.linalg.spsolve(mtx2, rhs, use_umfpack=True) +
      >>> print(x) +
      [106. +0.j -21. +0.j 5.5+0.j -1.5+0.j 1. +0.j] +
      >>> print("Error: %s" % (mtx2 * x - rhs)) +
      Error: [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j] +
      +
      +
    • +
    +
    +
  • +
+
"""
+
Solve a linear system +
======================= +
+
Construct a 1000x1000 lil_array and add some values to it, convert it +
to CSR format and solve A x = b for x:and solve a linear system with a +
direct solver. +
""" +
+
import numpy as np +
import scipy as sp +
import matplotlib.pyplot as plt +
+
rng = np.random.default_rng(27446968) +
+
mtx = sp.sparse.lil_array((1000, 1000), dtype=np.float64) +
mtx[0, :100] = rng.random(100) +
mtx[1, 100:200] = mtx[[0], :100] +
mtx.setdiag(rng.random(1000)) +
+
plt.clf() +
plt.spy(mtx, marker=".", markersize=2) +
plt.show() +
+
mtx = mtx.tocsr() +
rhs = rng.random(1000) +
+
x = sp.sparse.linalg.spsolve(mtx, rhs) +
+
print(f"residual: {np.linalg.norm(mtx @ x - rhs)!r}") +
+
+ +
+
+
+

2.5.3.2. Iterative Solvers

+
    +
  • +
    the isolve module contains the following solvers:
      +
    • bicg (BIConjugate Gradient)

    • +
    • bicgstab (BIConjugate Gradient STABilized)

    • +
    • cg (Conjugate Gradient) - symmetric positive definite matrices +only

    • +
    • cgs (Conjugate Gradient Squared)

    • +
    • gmres (Generalized Minimal RESidual)

    • +
    • minres (MINimum RESidual)

    • +
    • qmr (Quasi-Minimal Residual)

    • +
    +
    +
    +
  • +
+
+

Common Parameters

+
    +
  • mandatory:

    +
    +
    A{sparse array/matrix, dense array/matrix, LinearOperator}

    The N-by-N matrix of the linear system.

    +
    +
    b{array, matrix}

    Right hand side of the linear system. Has shape (N,) or (N,1).

    +
    +
    +
  • +
  • optional:

    +
    +
    x0{array, matrix}

    Starting guess for the solution.

    +
    +
    tolfloat

    Relative tolerance to achieve before terminating.

    +
    +
    maxiterinteger

    Maximum number of iterations. Iteration will stop after maxiter +steps even if the specified tolerance has not been achieved.

    +
    +
    M{sparse array/matrix, dense array/matrix, LinearOperator}

    Preconditioner for A. The preconditioner should approximate the +inverse of A. Effective preconditioning dramatically improves the +rate of convergence, which implies that fewer iterations are needed +to reach a given error tolerance.

    +
    +
    callbackfunction

    User-supplied function to call after each iteration. It is called +as callback(xk), where xk is the current solution vector.

    +
    +
    +
  • +
+
+
+

LinearOperator Class

+
    +
  • common interface for performing matrix vector products

  • +
  • useful abstraction that enables using dense and sparse matrices within +the solvers, as well as matrix-free solutions

  • +
  • has shape and matvec() (+ some optional parameters)

  • +
  • example:

  • +
+
>>> import numpy as np
+
>>> import scipy as sp +
>>> def mv(v): +
... return np.array([2 * v[0], 3 * v[1]]) +
... +
>>> A = sp.sparse.linalg.LinearOperator((2, 2), matvec=mv) +
>>> A +
<2x2 _CustomLinearOperator with dtype=float64> +
>>> A.matvec(np.ones(2)) +
array([2., 3.]) +
>>> A * np.ones(2) +
array([2., 3.]) +
+
+
+
+

A Few Notes on Preconditioning

+
    +
  • problem specific

  • +
  • often hard to develop

  • +
  • +
    if not sure, try ILU
    +
    +
    +
  • +
+
+
+
+

2.5.3.3. Eigenvalue Problem Solvers

+
+

The eigen module

+
    +
  • arpack +* a collection of Fortran77 subroutines designed to solve large scale eigenvalue problems

  • +
  • lobpcg (Locally Optimal Block Preconditioned Conjugate +Gradient Method) +* works very well in combination with PyAMG +* example by Nathan Bell:

    +
    """
    +
    Compute eigenvectors and eigenvalues using a preconditioned eigensolver +
    ======================================================================= +
    +
    In this example Smoothed Aggregation (SA) is used to precondition +
    the LOBPCG eigensolver on a two-dimensional Poisson problem with +
    Dirichlet boundary conditions. +
    """ +
    +
    import numpy as np +
    import scipy as sp +
    import matplotlib.pyplot as plt +
    +
    from pyamg import smoothed_aggregation_solver +
    from pyamg.gallery import poisson +
    +
    N = 100 +
    K = 9 +
    A = poisson((N, N), format="csr") +
    +
    # create the AMG hierarchy +
    ml = smoothed_aggregation_solver(A) +
    +
    # initial approximation to the K eigenvectors +
    X = np.random.random((A.shape[0], K)) +
    +
    # preconditioner based on ml +
    M = ml.aspreconditioner() +
    +
    # compute eigenvalues and eigenvectors with LOBPCG +
    W, V = sp.sparse.linalg.lobpcg(A, X, M=M, tol=1e-8, largest=False) +
    +
    +
    # plot the eigenvectors +
    plt.figure(figsize=(9, 9)) +
    +
    for i in range(K): +
    plt.subplot(3, 3, i + 1) +
    plt.title("Eigenvector %d" % i) +
    plt.pcolor(V[:, i].reshape(N, N)) +
    plt.axis("equal") +
    plt.axis("off") +
    plt.show() +
    +
    + +
  • +
  • example by Nils Wagner:

    + +
  • +
  • output:

    +
    $ python examples/lobpcg_sakurai.py
    +
    Results by LOBPCG for n=2500 +
    +
    [ 0.06250083 0.06250028 0.06250007] +
    +
    Exact eigenvalues +
    +
    [ 0.06250005 0.0625002 0.06250044] +
    +
    Elapsed time 7.01 +
    +
    +
  • +
+../../_images/lobpcg_eigenvalues.png +

+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/advanced/scipy_sparse/storage_schemes.html b/advanced/scipy_sparse/storage_schemes.html new file mode 100644 index 000000000..af3a9b456 --- /dev/null +++ b/advanced/scipy_sparse/storage_schemes.html @@ -0,0 +1,411 @@ + + + + + + + + 2.5.2. Storage Schemes — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

2.5.2. Storage Schemes

+
    +
  • +
    seven sparse array types in scipy.sparse:
      +
    1. csr_array: Compressed Sparse Row format

    2. +
    3. csc_array: Compressed Sparse Column format

    4. +
    5. bsr_array: Block Sparse Row format

    6. +
    7. lil_array: List of Lists format

    8. +
    9. dok_array: Dictionary of Keys format

    10. +
    11. coo_array: COOrdinate format (aka IJV, triplet format)

    12. +
    13. dia_array: DIAgonal format

    14. +
    +
    +
    +
  • +
  • each suitable for some tasks

  • +
  • many employ sparsetools C++ module by Nathan Bell

  • +
  • assume the following is imported:

    +
    >>> import numpy as np
    +
    >>> import scipy as sp +
    >>> import matplotlib.pyplot as plt +
    +
    +
  • +
  • +
    warning for Numpy users:
      +
    • passing a sparse array object to NumPy functions that expect +ndarray/matrix does not work. Use sparse functions.

    • +
    • the older csr_matrix classes use ‘*’ for matrix multiplication (dot product) +and ‘A.multiply(B)’ for elementwise multiplication.

    • +
    • the newer csr_array uses ‘@’ for dot product and ‘*’ for elementwise multiplication

    • +
    • sparse arrays can be 1D or 2D, but not nD for n > 2 (unlike Numpy arrays).

    • +
    +
    +
    +
  • +
+
+

2.5.2.1. Common Methods

+
    +
  • +
    all scipy.sparse array classes are subclasses of sparray
      +
    • +
      default implementation of arithmetic operations
        +
      • always converts to CSR

      • +
      • subclasses override for efficiency

      • +
      +
      +
      +
    • +
    • shape, data type, set/get

    • +
    • indices of nonzero values in the array

    • +
    • format conversion, interaction with NumPy (toarray())

    • +
    • +
    +
    +
    +
  • +
  • +
    attributes:
      +
    • mtx.T - transpose (same as mtx.transpose())

    • +
    • mtx.real - real part of complex matrix

    • +
    • mtx.imag - imaginary part of complex matrix

    • +
    • mtx.size - the number of nonzeros (same as self.getnnz())

    • +
    • mtx.shape - the number of rows and columns (tuple)

    • +
    +
    +
    +
  • +
  • data and indices usually stored in 1D NumPy arrays

  • +
+
+
+

2.5.2.2. Sparse Array Classes

+ +
+
+

2.5.2.3. Summary

+ + ++++++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Summary of storage schemes.

format

matrix * vector

get item

fancy get

set item

fancy set

solvers

note

CSR

sparsetools

yes

yes

slow

.

any

has data array, fast row-wise ops

CSC

sparsetools

yes

yes

slow

.

any

has data array, fast column-wise ops

BSR

sparsetools

.

.

.

.

specialized

has data array, specialized

COO

sparsetools

.

.

.

.

iterative

has data array, facilitates fast conversion

DIA

sparsetools

.

.

.

.

iterative

has data array, specialized

LIL

via CSR

yes

yes

yes

yes

iterative

arithmetic via CSR, incremental construction

DOK

python

yes

one axis only

yes

yes

iterative

O(1) item access, incremental construction, slow arithmetic

+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/guide/auto_examples/index.html b/guide/auto_examples/index.html new file mode 100644 index 000000000..ae48d5edb --- /dev/null +++ b/guide/auto_examples/index.html @@ -0,0 +1,190 @@ + + + + + + + + Examples for the contribution guide — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Examples for the contribution guide

+

Note that every example directory needs to have a README.txt

+
+

A simple example

+
A simple example
+
+
+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/guide/auto_examples/plot_simple.html b/guide/auto_examples/plot_simple.html new file mode 100644 index 000000000..70c703688 --- /dev/null +++ b/guide/auto_examples/plot_simple.html @@ -0,0 +1,201 @@ + + + + + + + + A simple example — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

A simple example

+plot simple
import numpy as np
+
import matplotlib.pyplot as plt +
+
X = np.linspace(-np.pi, np.pi, 100) +
Y = np.sin(X) +
+
plt.plot(X, Y, linewidth=2) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.052 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/guide/auto_examples/sg_execution_times.html b/guide/auto_examples/sg_execution_times.html new file mode 100644 index 000000000..3d58e0206 --- /dev/null +++ b/guide/auto_examples/sg_execution_times.html @@ -0,0 +1,206 @@ + + + + + + + + Computation times — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Computation times

+

00:00.052 total execution time for 1 file from guide/auto_examples:

+
+ + + + + +++++ + + + + + + + + + + + + +

Example

Time

Mem (MB)

A simple example (plot_simple.py)

00:00.052

0.0

+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/guide/index.html b/guide/index.html new file mode 100644 index 000000000..a1d29a14a --- /dev/null +++ b/guide/index.html @@ -0,0 +1,431 @@ + + + + + + + + How to contribute — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

How to contribute

+

Author: Nicolas Rougier

+ + +

Make sure to read this Documentation style guide [1] as well as these +tips, tricks [2] and conventions about documentation content and workflows.

+
+

How to contribute ?

+
    +
  • If you spot typos, unclear or clumsy wording in the lectures, please +help to improve them. Simple text editing can be done by editing files +in your GitHub fork of +the lectures. On every html page of the lectures, an edit +button on the top right links to the editable source of the page (you still +need to create a fork of the project). Edit the source and choose +“Create a new branch for this commit and start a pull request”.

  • +
  • Choose a topic that is not yet covered and write it up !

    +

    First create a new issue on GitHub to explain the topic which you would +like to cover, in order to discuss with editors and contributors about +the scope of the future tutorial.

    +

    Then create a new directory inside one of the chapters directories +(intro, advanced, or packages) and create a file index.rst +for the new tutorial. Add the new file in the table of contents of the +corresponding chapter (in its index.rst).

    +
  • +
+

Keep in mind that tutorials are to be taught at different places and +different parts may be combined into a course on Python for scientific +computing. Thus you want them to be interactive and reasonably short (one +to two hours).

+

Last but not least, the goal of this material is to provide a concise +text to learn the main features of the scientific Python ecosystem. If +you want to contribute to reference material, we suggest that you +contribute to the documentation of the specific packages that you are +interested in.

+
+
+

Using GitHub

+

The easiest way to make your own version of this teaching material +is to fork it under GitHub, and use the git version control system to +maintain your own fork. For this, all you have to do is create an account +on GitHub and click on the fork button, on the top right of this +page. You can use git to pull from your fork, and push back to it the +changes. If you want to contribute the changes back, just fill a +pull request, using the button on the top of your fork’s page.

+

Several resources are available online to learn git and GitHub, such as +https://try.github.io for complete beginners.

+

Please refrain from modifying the Makefile unless it is absolutely +necessary.

+
+
+

Keeping it concise: collapsing paragraphs

+

The HTML output is used for displaying on screen while teaching. The goal +is to have the same material displayed as in the notes. Thus there needs +to be a very concise display, with bullet-lists rather than full-blown +paragraphs and sentences. For more elaborate discussions that people can +read and refer to, please use the tip sphinx directive. It creates +collapsible paragraphs, that can be hidden during an oral +presentation:

+
.. tip::
+
+
Here insert a full-blown discussion, that will be collapsible in +
the HTML version. +
+
It can span on multiple paragraphs +
+
+

This renders as:

+
+
+

Tip

+

Here insert a full-blown discussion, that will be collapsible in +the HTML version.

+

It can span on multiple paragraphs

+
+
+
+
+

Figures and code examples

+

We do not check figures in the repository. +Any figure must be generated from a python script that needs to be named +plot_xxx.py (xxx can be anything of course) and put into the examples +directory. The generated image will be named from the script name.

+../_images/sphx_glr_plot_simple_001.png + +

This is the way to include your image and link it to the code:

+
.. image::  auto_examples/images/sphx_glr_plot_simple_001.png
+
:target: auto_examples/plot_simple.html +
+
+

You can display the corresponding code using the literal-include +directive.

+
"""
+
A simple example +
================= +
+
""" +
+
import numpy as np +
import matplotlib.pyplot as plt +
+
X = np.linspace(-np.pi, np.pi, 100) +
Y = np.sin(X) +
+
plt.plot(X, Y, linewidth=2) +
plt.show() +
+
+
+

Note

+

The transformation of Python scripts into figures and galleries of +examples is provided by the sphinx-gallery package.

+
+
+
+

Using Markup

+

There are three main kinds of markup that should be used: italics, bold +and fixed-font. Italics should be used when introducing a new technical +term, bold should be used for emphasis and fixed-font for source code.

+ +

In restructured-text markup this is:

+
when using *object-oriented programming* in Python you **must** use the
+
``class`` keyword to define your *classes*. +
+
+
+
+

Linking to package documentations

+

The goal of the Scientific Python Lectures is not to duplicate or replace +the documentation of the various packages. You should link as much as +possible to the original documentation.

+

For cross-referencing API documentation we prefer to use the intersphinx +extension. This provides +the directives :mod:, :class: and :func: to cross-link to modules, +classes and functions respectively. For example the :func:`numpy.var` will +create a link like numpy.var().

+
+
+

Chapter, section, subsection, paragraph

+

Try to avoid to go below paragraph granularity or your document might become +difficult to read:

+
=============
+
Chapter title +
============= +
+
Sample content. +
+
Section +
======= +
+
Subsection +
---------- +
+
Paragraph +
......... +
+
And some text. +
+
+
+
+

Admonitions

+
+

Note

+

This is a note

+
+
+

Warning

+

This is a warning

+
+
+
+

Clearing floats

+

Figures positioned with :align: right are float. To flush them, use:

+
|clear-floats|
+
+
+
+
+

References

+ +

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/includes/big_toc_css.html b/includes/big_toc_css.html new file mode 100644 index 000000000..467695ea8 --- /dev/null +++ b/includes/big_toc_css.html @@ -0,0 +1,204 @@ + + + + + + + + <no title> — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +

+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/includes/bigger_toc_css.html b/includes/bigger_toc_css.html new file mode 100644 index 000000000..a8adcfd4f --- /dev/null +++ b/includes/bigger_toc_css.html @@ -0,0 +1,220 @@ + + + + + + + + <no title> — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +

+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 000000000..5bec85baf --- /dev/null +++ b/index.html @@ -0,0 +1,1142 @@ + + + + + + + + Scientific Python Lectures — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Scientific Python Lectures

+
+

One document to learn numerics, science, and data with Python

+
+ +

Tutorials on the scientific Python ecosystem: a quick introduction to +central tools and techniques. The different chapters each correspond +to a 1 to 2 hours course with increasing level of expertise, from +beginner to expert.

+

Release: 2024.2rc0.dev0

+ +
+

+
+
+ +
+
+

+
+ +

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/help/help.html b/intro/help/help.html new file mode 100644 index 000000000..1604d5914 --- /dev/null +++ b/intro/help/help.html @@ -0,0 +1,328 @@ + + + + + + + + 1.6. Getting help and finding documentation — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.6. Getting help and finding documentation

+

Author: Emmanuelle Gouillart

+

Rather than knowing all functions in NumPy and SciPy, it is important to +find rapidly information throughout the documentation and the available +help. Here are some ways to get information:

+
    +
  • In Ipython, help function opens the docstring of the function. Only +type the beginning of the function’s name and use tab completion to +display the matching functions.

    +
    In [1]: help(np.van<TAB>
    +
    +
    In [2]: help(np.vander) +
    Help on _ArrayFunctionDispatcher in module numpy: +
    +
    vander(x, N=None, increasing=False) +
    Generate a Vandermonde matrix. +
    +
    The columns of the output matrix are powers of the input vector. The +
    order of the powers is determined by the `increasing` boolean argument. +
    Specifically, when `increasing` is False, the `i`-th output column is +
    the input vector raised element-wise to the power of ``N - i - 1``. Such +
    a matrix with a geometric progression in each row is named for Alexandre- +
    Theophile Vandermonde. +
    +
    Parameters +
    ---------- +
    x : array_like +
    1-D input array. +
    N : int, optional +
    Number of columns in the output. If `N` is not specified, a square +
    array is returned (``N = len(x)``). +
    increasing : bool, optional +
    Order of the powers of the columns. If True, the powers increase +
    from left to right, if False (the default) they are reversed. +
    +
    .. versionadded:: 1.9.0 +
    +
    Returns +
    ------- +
    out : ndarray +
    Vandermonde matrix. If `increasing` is False, the first column is +
    ``x^(N-1)``, the second ``x^(N-2)`` and so forth. If `increasing` is +
    True, the columns are ``x^0, x^1, ..., x^(N-1)``. +
    +
    See Also +
    -------- +
    polynomial.polynomial.polyvander +
    +
    Examples +
    -------- +
    >>> import numpy as np +
    >>> x = np.array([1, 2, 3, 5]) +
    >>> N = 3 +
    >>> np.vander(x, N) +
    array([[ 1, 1, 1], +
    [ 4, 2, 1], +
    [ 9, 3, 1], +
    [25, 5, 1]]) +
    +
    >>> np.column_stack([x**(N-1-i) for i in range(N)]) +
    array([[ 1, 1, 1], +
    [ 4, 2, 1], +
    [ 9, 3, 1], +
    [25, 5, 1]]) +
    +
    >>> x = np.array([1, 2, 3, 5]) +
    >>> np.vander(x) +
    array([[ 1, 1, 1, 1], +
    [ 8, 4, 2, 1], +
    [ 27, 9, 3, 1], +
    [125, 25, 5, 1]]) +
    >>> np.vander(x, increasing=True) +
    array([[ 1, 1, 1, 1], +
    [ 1, 2, 4, 8], +
    [ 1, 3, 9, 27], +
    [ 1, 5, 25, 125]]) +
    +
    The determinant of a square Vandermonde matrix is the product +
    of the differences between the values of the input vector: +
    +
    >>> np.linalg.det(np.vander(x)) +
    48.000000000000043 # may vary +
    >>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1) +
    48 +
    +
    +
  • +
+

In Ipython it is not possible to open a separated window for help and +documentation; however one can always open a second Ipython shell +just to display help and docstrings…

+
    +
  • Numpy’s and Scipy’s documentations can be browsed online on +https://scipy.org and https://numpy.org. The search button is quite +useful inside +the reference documentation of the two packages.

    +

    Tutorials on various topics as well as the complete API with all +docstrings are found on this website.

    +
  • +
  • Numpy’s and Scipy’s documentation is enriched and updated on a regular +basis by users on a wiki https://numpy.org/doc/stable/. As a result, +some docstrings are clearer or more detailed on the wiki, and you may +want to read directly the documentation on the wiki instead of the +official documentation website. Note that anyone can create an account on +the wiki and write better documentation; this is an easy way to +contribute to an open-source project and improve the tools you are +using!

  • +
  • The SciPy Cookbook https://scipy-cookbook.readthedocs.io gives recipes on many +common problems frequently encountered, such as fitting data points, +solving ODE, etc.

  • +
  • Matplotlib’s website https://matplotlib.org/ features a very +nice gallery with a large number of plots, each of them shows both +the source code and the resulting plot. This is very useful for +learning by example. More standard documentation is also available.

  • +
  • In Ipython, the magical function %psearch search for objects +matching patterns. This is useful if, for example, one does not know +the exact name of a function.

    +
    In [3]: import numpy as np
    +
    +
    +
  • +
  • If everything listed above fails (and Google doesn’t have the +answer)… don’t despair! There is a vibrant Scientific Python community. +Scientific Python is present on various platform. +https://scientific-python.org/community/

    +

    Packages like SciPy and NumPy also have their own channels. Have a look at +their respective websites to find out how to engage with users and +maintainers.

    +
  • +
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/index.html b/intro/index.html new file mode 100644 index 000000000..e2bb6e042 --- /dev/null +++ b/intro/index.html @@ -0,0 +1,578 @@ + + + + + + + + 1. Getting started with Python for science — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1. Getting started with Python for science

+

This part of the Scientific Python Lectures is a self-contained +introduction to everything that is needed to use Python for science, +from the language itself, to numerical computing or plotting.

+
+

+
+
+ +
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/intro.html b/intro/intro.html new file mode 100644 index 000000000..22ba69602 --- /dev/null +++ b/intro/intro.html @@ -0,0 +1,665 @@ + + + + + + + + 1.1. Python scientific computing ecosystem — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.1. Python scientific computing ecosystem

+

Authors: Fernando Perez, Emmanuelle Gouillart, Gaël Varoquaux, +Valentin Haenel

+
+

1.1.1. Why Python?

+
+

1.1.1.1. The scientist’s needs

+
    +
  • Get data (simulation, experiment control),

  • +
  • Manipulate and process data,

  • +
  • Visualize results, quickly to understand, but also with high quality +figures, for reports or publications.

  • +
+
+
+

1.1.1.2. Python’s strengths

+
    +
  • Batteries included Rich collection of already existing bricks +of classic numerical methods, plotting or data processing tools. We +don’t want to re-program the plotting of a curve, a Fourier transform +or a fitting algorithm. Don’t reinvent the wheel!

  • +
  • Easy to learn Most scientists are not paid as programmers, neither +have they been trained so. They need to be able to draw a curve, smooth +a signal, do a Fourier transform in a few minutes.

  • +
  • Easy communication To keep code alive within a lab or a company +it should be as readable as a book by collaborators, students, or +maybe customers. Python syntax is simple, avoiding strange symbols or +lengthy routine specifications that would divert the reader from +mathematical or scientific understanding of the code.

  • +
  • Efficient code Python numerical modules are computationally +efficient. But needless to say that a very fast code becomes useless if +too much time is spent writing it. Python aims for quick development +times and quick execution times.

  • +
  • Universal Python is a language used for many different problems. +Learning Python avoids learning a new software for each new problem.

  • +
+
+
+

1.1.1.3. How does Python compare to other solutions?

+
+

Compiled languages: C, C++, Fortran…

+
+
Pros:
+
    +
  • Very fast. For heavy computations, it’s difficult to outperform these +languages.

  • +
+
+
Cons:
+
    +
  • Painful usage: no interactivity during development, mandatory +compilation steps, verbose syntax, manual memory management. These +are difficult languages for non programmers.

  • +
+
+
+
+
+

Matlab scripting language

+
+
Pros:
+
    +
  • Very rich collection of libraries with numerous algorithms, for many +different domains. Fast execution because these libraries are often written +in a compiled language.

  • +
  • Pleasant development environment: comprehensive and help, integrated +editor, etc.

  • +
  • Commercial support is available.

  • +
+
+
Cons:
+
    +
  • Base language is quite poor and can become restrictive for advanced users.

  • +
  • Not free and not everything is open sourced.

  • +
+
+
+
+
+

Julia

+
+
Pros:
+
    +
  • Fast code, yet interactive and simple.

  • +
  • Easily connects to Python or C.

  • +
+
+
Cons:
+
    +
  • Ecosystem limited to numerical computing.

  • +
  • Still young.

  • +
+
+
+
+
+

Other scripting languages: Scilab, Octave, R, IDL, etc.

+
+
Pros:
+
    +
  • Open-source, free, or at least cheaper than Matlab.

  • +
  • Some features can be very advanced (statistics in R, etc.)

  • +
+
+
Cons:
+
    +
  • Fewer available algorithms than in Matlab, and the language +is not more advanced.

  • +
  • Some software are dedicated to one domain. Ex: Gnuplot to draw +curves. These programs are very powerful, but they are restricted to +a single type of usage, such as plotting.

  • +
+
+
+
+
+

Python

+
+
Pros:
+
    +
  • Very rich scientific computing libraries

  • +
  • Well thought out language, allowing to write very readable and well +structured code: we “code what we think”.

  • +
  • Many libraries beyond scientific computing (web server, +serial port access, etc.)

  • +
  • Free and open-source software, widely spread, with a vibrant community.

  • +
  • A variety of powerful environments to work in, such as +IPython, +Spyder, +Jupyter notebooks, +Pycharm, +Visual Studio Code

  • +
+
+
Cons:
+
    +
  • Not all the algorithms that can be found in more specialized +software or toolboxes.

  • +
+
+
+
+
+
+
+

1.1.2. The scientific Python ecosystem

+

Unlike Matlab, or R, Python does not come with a pre-bundled set +of modules for scientific computing. Below are the basic building blocks +that can be combined to obtain a scientific computing environment:

+
+

+
+

Python, a generic and modern computing language

+
    +
  • The language: flow control, data types (string, int), +data collections (lists, dictionaries), etc.

  • +
  • Modules of the standard library: string processing, file +management, simple network protocols.

  • +
  • A large number of specialized modules or applications written in +Python: web framework, etc. … and scientific +computing.

  • +
  • Development tools (automatic testing, documentation generation)

  • +
+ +

Core numeric libraries

+ +

Advanced interactive environments:

+ +

Domain-specific packages,

+ +

and many more packages not documented in the Scientific Python Lectures.

+ +

+
+
+

1.1.3. Before starting: Installing a working environment

+

Python comes in many flavors, and there are many ways to install it. +However, we recommend to install a scientific-computing distribution, +that comes readily with optimized versions of scientific modules.

+

Under Linux

+

If you have a recent distribution, most of the tools are probably +packaged, and it is recommended to use your package manager.

+

Other systems

+

There are several fully-featured scientific Python distributions:

+ +
+
+

1.1.4. The workflow: interactive environments and text editors

+

Interactive work to test and understand algorithms: In this section, we +describe a workflow combining interactive work and consolidation.

+

Python is a general-purpose language. As such, there is not one blessed +environment to work in, and not only one way of using it. Although +this makes it harder for beginners to find their way, it makes it +possible for Python to be used for programs, in web servers, or +embedded devices.

+
+

1.1.4.1. Interactive work

+

We recommend an interactive work with the IPython console, or its offspring, the Jupyter notebook. They +are handy to explore and understand algorithms.

+ +

Start ipython:

+
In [1]: print('Hello world')
+
Hello world +
+
+

Getting help by using the ? operator after an object:

+
In [2]: print?
+
Signature: print(*args, sep=' ', end='\n', file=None, flush=False) +
Docstring: +
Prints the values to a stream, or to sys.stdout by default. +
+
sep +
string inserted between values, default a space. +
end +
string appended after the last value, default a newline. +
file +
a file-like object (stream); defaults to the current sys.stdout. +
flush +
whether to forcibly flush the stream. +
Type: builtin_function_or_method +
+
+
+

See also

+ +
+
+
+

1.1.4.2. Elaboration of the work in an editor

+

As you move forward, it will be important to not only work interactively, +but also to create and reuse Python files. For this, a powerful code editor +will get you far. Here are several good easy-to-use editors:

+
+
    +
  • Spyder: integrates an IPython +console, a debugger, a profiler…

  • +
  • PyCharm: integrates an IPython +console, notebooks, a debugger… (freely available, +but commercial)

  • +
  • Visual Studio Code: +integrates a Python console, notebooks, a debugger, …

  • +
+
+

Some of these are shipped by the various scientific Python distributions, +and you can find them in the menus.

+

As an exercise, create a file my_file.py in a code editor, and add the +following lines:

+
s = 'Hello world'
+
print(s) +
+
+

Now, you can run it in IPython console or a notebook and explore the +resulting variables:

+
In [3]: %run my_file.py
+
Hello world +
+
In [4]: s +
Out[4]: 'Hello world' +
+
In [5]: %whos +
Variable Type Data/Info +
---------------------------- +
s str Hello world +
+
+ +
+
+

1.1.4.3. IPython and Jupyter Tips and Tricks

+

The user manuals contain a wealth of information. Here we give a quick +introduction to four useful features: history, tab completion, magic +functions, and aliases.

+
+

+
+

Command history Like a UNIX shell, the IPython console supports +command history. Type up and down to navigate previously typed +commands:

+
In [6]: x = 10
+
+
In [7]: <UP> +
+
In [8]: x = 10 +
+
+
+

+
+

Tab completion Tab completion, is a convenient way to explore the +structure of any object you’re dealing with. Simply type object_name.<TAB> to +view the object’s attributes. Besides Python objects and keywords, tab +completion also works on file and directory names.*

+
In [9]: x = 10
+
+
In [10]: x.<TAB> +
as_integer_ratio() conjugate() imag to_bytes() +
bit_count() denominator numerator +
bit_length() from_bytes() real +
+
+
+

+
+

Magic functions +The console and the notebooks support so-called magic functions by prefixing a command with the +% character. For example, the run and whos functions from the +previous section are magic functions. Note that, the setting automagic, +which is enabled by default, allows you to omit the preceding % sign. Thus, +you can just type the magic function and it will work.

+

Other useful magic functions are:

+
    +
  • %cd to change the current directory.

    +
    In [11]: cd /tmp
    +
    /tmp +
    +
    +
  • +
  • %cpaste allows you to paste code, especially code from websites which has +been prefixed with the standard Python prompt (e.g. >>>) or with an ipython +prompt, (e.g. in [3]):

    +
    In [12]: %cpaste
    +
    +
    +
  • +
  • %timeit allows you to time the execution of short snippets using the +timeit module from the standard library:

    +
    In [12]: %timeit x = 10
    +
    11.2 ns +- 0.927 ns per loop (mean +- std. dev. of 7 runs, 100,000,000 loops each) +
    +
    + +
  • +
  • %debug allows you to enter post-mortem debugging. That is to say, if the +code you try to execute, raises an exception, using %debug will enter the +debugger at the point where the exception was thrown.

    +
    In [13]: x === 10
    +
    Cell In[13], line 1 +
    x === 10 +
    ^ +
    SyntaxError: invalid syntax +
    +
    +
    In [14]: %debug +
    > /home/jarrod/.venv/lectures/lib64/python3.11/site-packages/IPython/core/compilerop.py(86)ast_parse() +
    84 Arguments are exactly the same as ast.parse (in the standard library), +
    85 and are passed to the built-in compile function.""" +
    ---> 86 return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1) +
    87 +
    88 def reset_compiler_flags(self): +
    ipdb> locals() +
    {'self': <IPython.core.compilerop.CachingCompiler object at 0x7f30d02efc10>, 'source': 'x === 10\n', 'filename': '<ipython-input-1-8e8bc565444b>', 'symbol': 'exec'} +
    ipdb> +
    +
    +
    +

    See also

    +

    Chapter on debugging

    +
    +
  • +
+
+

+
+

Aliases +Furthermore IPython ships with various aliases which emulate common UNIX +command line tools such as ls to list files, cp to copy files and rm to +remove files (a full list of aliases is shown when typing alias).

+ +

+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/language/basic_types.html b/intro/language/basic_types.html new file mode 100644 index 000000000..1855011b8 --- /dev/null +++ b/intro/language/basic_types.html @@ -0,0 +1,682 @@ + + + + + + + + 1.2.2. Basic types — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.2.2. Basic types

+
+

1.2.2.1. Numerical types

+
+

Tip

+

Python supports the following numerical, scalar types:

+
+
+
Integer:
+
>>> 1 + 1
+
2 +
>>> a = 4 +
>>> type(a) +
<class 'int'> +
+
+
+
Floats:
+
>>> c = 2.1
+
>>> type(c) +
<class 'float'> +
+
+
+
Complex:
+
>>> a = 1.5 + 0.5j
+
>>> a.real +
1.5 +
>>> a.imag +
0.5 +
>>> type(1. + 0j) +
<class 'complex'> +
+
+
+
Booleans:
+
>>> 3 > 4
+
False +
>>> test = (3 > 4) +
>>> test +
False +
>>> type(test) +
<class 'bool'> +
+
+
+
+
+

Tip

+

A Python shell can therefore replace your pocket calculator, with the +basic arithmetic operations +, -, *, /, % (modulo) +natively implemented

+
+
>>> 7 * 3.
+
21.0 +
>>> 2**10 +
1024 +
>>> 8 % 3 +
2 +
+
+

Type conversion (casting):

+
>>> float(1)
+
1.0 +
+
+
+
+

1.2.2.2. Containers

+
+

Tip

+

Python provides many efficient types of containers, in which +collections of objects can be stored.

+
+
+

Lists

+
+

Tip

+

A list is an ordered collection of objects, that may have different +types. For example:

+
+
>>> colors = ['red', 'blue', 'green', 'black', 'white']
+
>>> type(colors) +
<class 'list'> +
+
+

Indexing: accessing individual objects contained in the list:

+
>>> colors[2]
+
'green' +
+
+

Counting from the end with negative indices:

+
>>> colors[-1]
+
'white' +
>>> colors[-2] +
'black' +
+
+
+

Warning

+

Indexing starts at 0 (as in C), not at 1 (as in Fortran or Matlab)!

+
+

Slicing: obtaining sublists of regularly-spaced elements:

+
>>> colors
+
['red', 'blue', 'green', 'black', 'white'] +
>>> colors[2:4] +
['green', 'black'] +
+
+
+

Warning

+

Note that colors[start:stop] contains the elements with indices i +such as start<= i < stop (i ranging from start to +stop-1). Therefore, colors[start:stop] has (stop - start) elements.

+
+

Slicing syntax: colors[start:stop:stride]

+
+

Tip

+

All slicing parameters are optional:

+
>>> colors
+
['red', 'blue', 'green', 'black', 'white'] +
>>> colors[3:] +
['black', 'white'] +
>>> colors[:3] +
['red', 'blue', 'green'] +
>>> colors[::2] +
['red', 'green', 'white'] +
+
+
+

Lists are mutable objects and can be modified:

+
>>> colors[0] = 'yellow'
+
>>> colors +
['yellow', 'blue', 'green', 'black', 'white'] +
>>> colors[2:4] = ['gray', 'purple'] +
>>> colors +
['yellow', 'blue', 'gray', 'purple', 'white'] +
+
+
+

Note

+

The elements of a list may have different types:

+
>>> colors = [3, -200, 'hello']
+
>>> colors +
[3, -200, 'hello'] +
>>> colors[1], colors[2] +
(-200, 'hello') +
+
+
+

Tip

+

For collections of numerical data that all have the same type, it +is often more efficient to use the array type provided by +the numpy module. A NumPy array is a chunk of memory +containing fixed-sized items. With NumPy arrays, operations on +elements can be faster because elements are regularly spaced in +memory and more operations are performed through specialized C +functions instead of Python loops.

+
+
+
+

Tip

+

Python offers a large panel of functions to modify lists, or query +them. Here are a few examples; for more details, see +https://docs.python.org/3/tutorial/datastructures.html#more-on-lists

+
+

Add and remove elements:

+
>>> colors = ['red', 'blue', 'green', 'black', 'white']
+
>>> colors.append('pink') +
>>> colors +
['red', 'blue', 'green', 'black', 'white', 'pink'] +
>>> colors.pop() # removes and returns the last item +
'pink' +
>>> colors +
['red', 'blue', 'green', 'black', 'white'] +
>>> colors.extend(['pink', 'purple']) # extend colors, in-place +
>>> colors +
['red', 'blue', 'green', 'black', 'white', 'pink', 'purple'] +
>>> colors = colors[:-2] +
>>> colors +
['red', 'blue', 'green', 'black', 'white'] +
+
+

Reverse:

+
>>> rcolors = colors[::-1]
+
>>> rcolors +
['white', 'black', 'green', 'blue', 'red'] +
>>> rcolors2 = list(colors) # new object that is a copy of colors in a different memory area +
>>> rcolors2 +
['red', 'blue', 'green', 'black', 'white'] +
>>> rcolors2.reverse() # in-place; reversing rcolors2 does not affect colors +
>>> rcolors2 +
['white', 'black', 'green', 'blue', 'red'] +
+
+

Concatenate and repeat lists:

+
>>> rcolors + colors
+
['white', 'black', 'green', 'blue', 'red', 'red', 'blue', 'green', 'black', 'white'] +
>>> rcolors * 2 +
['white', 'black', 'green', 'blue', 'red', 'white', 'black', 'green', 'blue', 'red'] +
+
+
+

Tip

+

Sort:

+
>>> sorted(rcolors) # new object
+
['black', 'blue', 'green', 'red', 'white'] +
>>> rcolors +
['white', 'black', 'green', 'blue', 'red'] +
>>> rcolors.sort() # in-place +
>>> rcolors +
['black', 'blue', 'green', 'red', 'white'] +
+
+
+ + +
+
+

Strings

+

Different string syntaxes (simple, double or triple quotes):

+
s = 'Hello, how are you?'
+
s = "Hi, what's up" +
s = '''Hello, +
how are you''' # tripling the quotes allows the +
# string to span more than one line +
s = """Hi, +
what's up?""" +
+
+
In [2]: 'Hi, what's up?'
+
Cell In[2], line 1 +
'Hi, what's up?' +
^ +
SyntaxError: unterminated string literal (detected at line 1) +
+
+

This syntax error can be avoided by enclosing the string in double quotes +instead of single quotes. Alternatively, one can prepend a backslash to the +second single quote. Other uses of the backslash are, e.g., the newline character +\n and the tab character \t.

+
+

Tip

+

Strings are collections like lists. Hence they can be indexed and +sliced, using the same syntax and rules.

+
+

Indexing:

+
>>> a = "hello"
+
>>> a[0] +
'h' +
>>> a[1] +
'e' +
>>> a[-1] +
'o' +
+
+
+

Tip

+

(Remember that negative indices correspond to counting from the right +end.)

+
+

Slicing:

+
>>> a = "hello, world!"
+
>>> a[3:6] # 3rd to 6th (excluded) elements: elements 3, 4, 5 +
'lo,' +
>>> a[2:10:2] # Syntax: a[start:stop:step] +
'lo o' +
>>> a[::3] # every three characters, from beginning to end +
'hl r!' +
+
+
+

Tip

+

Accents and special characters can also be handled as in Python 3 +strings consist of Unicode characters.

+
+

A string is an immutable object and it is not possible to modify its +contents. One may however create new strings from the original one.

+
In [3]: a = "hello, world!"
+
+
In [4]: a.replace('l', 'z', 1) +
Out[4]: 'hezlo, world!' +
+
+
+

Tip

+

Strings have many useful methods, such as a.replace as seen +above. Remember the a. object-oriented notation and use tab +completion or help(str) to search for new methods.

+
+
+

See also

+

Python offers advanced possibilities for manipulating strings, +looking for patterns or formatting. The interested reader is referred to +https://docs.python.org/3/library/stdtypes.html#string-methods and +https://docs.python.org/3/library/string.html#format-string-syntax

+
+

String formatting:

+
>>> 'An integer: %i; a float: %f; another string: %s' % (1, 0.1, 'string') # with more values use tuple after %
+
'An integer: 1; a float: 0.100000; another string: string' +
+
>>> i = 102 +
>>> filename = 'processing_of_dataset_%d.txt' % i # no need for tuples with just one value after % +
>>> filename +
'processing_of_dataset_102.txt' +
+
+
+
+

Dictionaries

+
+

Tip

+

A dictionary is basically an efficient table that maps keys to +values.

+
+
>>> tel = {'emmanuelle': 5752, 'sebastian': 5578}
+
>>> tel['francis'] = 5915 +
>>> tel +
{'emmanuelle': 5752, 'sebastian': 5578, 'francis': 5915} +
>>> tel['sebastian'] +
5578 +
>>> tel.keys() +
dict_keys(['emmanuelle', 'sebastian', 'francis']) +
>>> tel.values() +
dict_values([5752, 5578, 5915]) +
>>> 'francis' in tel +
True +
+
+
+

Tip

+

It can be used to conveniently store and retrieve values +associated with a name (a string for a date, a name, etc.). See +https://docs.python.org/3/tutorial/datastructures.html#dictionaries +for more information.

+

A dictionary can have keys (resp. values) with different types:

+
>>> d = {'a':1, 'b':2, 3:'hello'}
+
>>> d +
{'a': 1, 'b': 2, 3: 'hello'} +
+
+
+
+
+

More container types

+

Tuples

+

Tuples are basically immutable lists. The elements of a tuple are written +between parentheses, or just separated by commas:

+
>>> t = 12345, 54321, 'hello!'
+
>>> t[0] +
12345 +
>>> t +
(12345, 54321, 'hello!') +
>>> u = (0, 2) +
+
+

Sets: unordered, unique items:

+
>>> s = set(('a', 'b', 'c', 'a'))
+
>>> s +
{'a', 'b', 'c'} +
>>> s.difference(('a', 'b')) +
{'c'} +
+
+
+
+
+

1.2.2.3. Assignment operator

+
+

Tip

+

Python library reference +says:

+
+

Assignment statements are used to (re)bind names to values and to +modify attributes or items of mutable objects.

+
+

In short, it works as follows (simple assignment):

+
    +
  1. an expression on the right hand side is evaluated, the corresponding +object is created/obtained

  2. +
  3. a name on the left hand side is assigned, or bound, to the +r.h.s. object

  4. +
+
+

Things to note:

+
    +
  • A single object can have several names bound to it:

  • +
+
In [5]: a = [1, 2, 3]
+
+
In [6]: b = a +
+
In [7]: a +
Out[7]: [1, 2, 3] +
+
In [8]: b +
Out[8]: [1, 2, 3] +
+
In [9]: a is b +
Out[9]: True +
+
In [10]: b[1] = 'hi!' +
+
In [11]: a +
Out[11]: [1, 'hi!', 3] +
+
+
    +
  • to change a list in place, use indexing/slices:

  • +
+
In [12]: a = [1, 2, 3]
+
+
In [13]: a +
Out[13]: [1, 2, 3] +
+
In [14]: a = ['a', 'b', 'c'] # Creates another object. +
+
In [15]: a +
Out[15]: ['a', 'b', 'c'] +
+
In [16]: id(a) +
Out[16]: 140028748541120 +
+
In [17]: a[:] = [1, 2, 3] # Modifies object in place. +
+
In [18]: a +
Out[18]: [1, 2, 3] +
+
In [19]: id(a) +
Out[19]: 140028748541120 +
+
+
    +
  • the key concept here is mutable vs. immutable

    +
    +
      +
    • mutable objects can be changed in place

    • +
    • immutable objects cannot be modified once created

    • +
    +
    +
  • +
+
+

See also

+

A very good and detailed explanation of the above issues can +be found in David M. Beazley’s article Types and Objects in Python.

+
+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/language/control_flow.html b/intro/language/control_flow.html new file mode 100644 index 000000000..cc3f8cbfe --- /dev/null +++ b/intro/language/control_flow.html @@ -0,0 +1,462 @@ + + + + + + + + 1.2.3. Control Flow — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.2.3. Control Flow

+

Controls the order in which the code is executed.

+
+

1.2.3.1. if/elif/else

+
>>> if 2**2 == 4:
+
... print("Obvious!") +
... +
Obvious! +
+
+

Blocks are delimited by indentation

+
+

Tip

+

Type the following lines in your Python interpreter, and be careful +to respect the indentation depth. The Ipython shell automatically +increases the indentation depth after a colon : sign; to +decrease the indentation depth, go four spaces to the left with the +Backspace key. Press the Enter key twice to leave the logical block.

+
+
>>> a = 10
+
+
>>> if a == 1: +
... print(1) +
... elif a == 2: +
... print(2) +
... else: +
... print("A lot") +
... +
A lot +
+
+

Indentation is compulsory in scripts as well. As an exercise, re-type the +previous lines with the same indentation in a script condition.py, and +execute the script with run condition.py in Ipython.

+
+
+

1.2.3.2. for/range

+

Iterating with an index:

+
>>> for i in range(4):
+
... print(i) +
0 +
1 +
2 +
3 +
+
+

But most often, it is more readable to iterate over values:

+
>>> for word in ('cool', 'powerful', 'readable'):
+
... print('Python is %s' % word) +
Python is cool +
Python is powerful +
Python is readable +
+
+
+
+

1.2.3.3. while/break/continue

+

Typical C-style while loop (Mandelbrot problem):

+
>>> z = 1 + 1j
+
>>> while abs(z) < 100: +
... z = z**2 + 1 +
>>> z +
(-134+352j) +
+
+

More advanced features

+

break out of enclosing for/while loop:

+
>>> z = 1 + 1j
+
+
>>> while abs(z) < 100: +
... if z.imag == 0: +
... break +
... z = z**2 + 1 +
+
+

continue the next iteration of a loop.:

+
>>> a = [1, 0, 2, 4]
+
>>> for element in a: +
... if element == 0: +
... continue +
... print(1. / element) +
1.0 +
0.5 +
0.25 +
+
+
+
+

1.2.3.4. Conditional Expressions

+
+
if <OBJECT>:
+
+
Evaluates to False:
    +
  • any number equal to zero (0, 0.0, 0+0j)

  • +
  • an empty container (list, tuple, set, dictionary, …)

  • +
  • False, None

  • +
+
+
Evaluates to True:
    +
  • everything else

  • +
+
+
+
+
a == b:
+

Tests equality, with logics:

+
>>> 1 == 1.
+
True +
+
+
+
a is b:
+

Tests identity: both sides are the same object:

+
>>> a = 1
+
>>> b = 1. +
>>> a == b +
True +
>>> a is b +
False +
+
>>> a = 1 +
>>> b = 1 +
>>> a is b +
True +
+
+
+
a in b:
+

For any collection b: b contains a

+
>>> b = [1, 2, 3]
+
>>> 2 in b +
True +
>>> 5 in b +
False +
+
+

If b is a dictionary, this tests that a is a key of b.

+
+
+
+
+

1.2.3.5. Advanced iteration

+
+

Iterate over any sequence

+

You can iterate over any sequence (string, list, keys in a dictionary, lines in +a file, …):

+
>>> vowels = 'aeiouy'
+
+
>>> for i in 'powerful': +
... if i in vowels: +
... print(i) +
o +
e +
u +
+
+
>>> message = "Hello how are you?"
+
>>> message.split() # returns a list +
['Hello', 'how', 'are', 'you?'] +
>>> for word in message.split(): +
... print(word) +
... +
Hello +
how +
are +
you? +
+
+
+

Tip

+

Few languages (in particular, languages for scientific computing) allow to +loop over anything but integers/indices. With Python it is possible to +loop exactly over the objects of interest without bothering with indices +you often don’t care about. This feature can often be used to make +code more readable.

+
+
+

Warning

+

Not safe to modify the sequence you are iterating over.

+
+
+
+

Keeping track of enumeration number

+

Common task is to iterate over a sequence while keeping track of the +item number.

+
    +
  • Could use while loop with a counter as above. Or a for loop:

    +
    >>> words = ('cool', 'powerful', 'readable')
    +
    >>> for i in range(0, len(words)): +
    ... print((i, words[i])) +
    (0, 'cool') +
    (1, 'powerful') +
    (2, 'readable') +
    +
    +
  • +
  • But, Python provides a built-in function - enumerate - for this:

    +
    >>> for index, item in enumerate(words):
    +
    ... print((index, item)) +
    (0, 'cool') +
    (1, 'powerful') +
    (2, 'readable') +
    +
    +
  • +
+
+
+

Looping over a dictionary

+

Use items:

+
>>> d = {'a': 1, 'b':1.2, 'c':1j}
+
+
>>> for key, val in sorted(d.items()): +
... print('Key: %s has value: %s' % (key, val)) +
Key: a has value: 1 +
Key: b has value: 1.2 +
Key: c has value: 1j +
+
+
+

Note

+

The ordering of a dictionary is random, thus we use sorted() +which will sort on the keys.

+
+
+
+
+

1.2.3.6. List Comprehensions

+

Instead of creating a list by means of a loop, one can make use +of a list comprehension with a rather self-explaining syntax.

+
>>> [i**2 for i in range(4)]
+
[0, 1, 4, 9] +
+
+
+ +

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/language/exceptions.html b/intro/language/exceptions.html new file mode 100644 index 000000000..3e71f97c7 --- /dev/null +++ b/intro/language/exceptions.html @@ -0,0 +1,408 @@ + + + + + + + + 1.2.8. Exception handling in Python — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.2.8. Exception handling in Python

+

It is likely that you have raised Exceptions if you have +typed all the previous commands of the tutorial. For example, you may +have raised an exception if you entered a command with a typo.

+

Exceptions are raised by different kinds of errors arising when executing +Python code. In your own code, you may also catch errors, or define custom +error types. You may want to look at the descriptions of the the built-in +Exceptions when looking +for the right exception type.

+
+

1.2.8.1. Exceptions

+

Exceptions are raised by errors in Python:

+
In [1]: 1/0
+
--------------------------------------------------------------------------- +
ZeroDivisionError Traceback (most recent call last) +
Cell In[1], line 1 +
----> 1 1/0 +
+
ZeroDivisionError: division by zero +
+
In [2]: 1 + 'e' +
--------------------------------------------------------------------------- +
TypeError Traceback (most recent call last) +
Cell In[2], line 1 +
----> 1 1 + 'e' +
+
TypeError: unsupported operand type(s) for +: 'int' and 'str' +
+
In [3]: d = {1:1, 2:2} +
+
In [4]: d[3] +
--------------------------------------------------------------------------- +
KeyError Traceback (most recent call last) +
Cell In[4], line 1 +
----> 1 d[3] +
+
KeyError: 3 +
+
In [5]: l = [1, 2, 3] +
+
In [6]: l[4] +
--------------------------------------------------------------------------- +
IndexError Traceback (most recent call last) +
Cell In[6], line 1 +
----> 1 l[4] +
+
IndexError: list index out of range +
+
In [7]: l.foobar +
--------------------------------------------------------------------------- +
AttributeError Traceback (most recent call last) +
Cell In[7], line 1 +
----> 1 l.foobar +
+
AttributeError: 'list' object has no attribute 'foobar' +
+
+

As you can see, there are different types of exceptions for different errors.

+
+
+

1.2.8.2. Catching exceptions

+
+

try/except

+
In [8]: while True:
+
...: try: +
...: x = int(input('Please enter a number: ')) +
...: break +
...: except ValueError: +
...: print('That was no valid number. Try again...') +
...: +
Please enter a number: a +
That was no valid number. Try again... +
Please enter a number: 1 +
+
In [9]: x +
Out[9]: 1 +
+
+
+
+

try/finally

+
In [10]: try:
+
....: x = int(input('Please enter a number: ')) +
....: finally: +
....: print('Thank you for your input') +
....: +
Please enter a number: a +
Thank you for your input +
--------------------------------------------------------------------------- +
ValueError Traceback (most recent call last) +
Cell In[10], line 2 +
1 try: +
----> 2 x = int(input('Please enter a number: ')) +
3 finally: +
4 print('Thank you for your input') +
ValueError: invalid literal for int() with base 10: 'a' +
+
+

Important for resource management (e.g. closing a file)

+
+
+

Easier to ask for forgiveness than for permission

+
In [11]: def print_sorted(collection):
+
....: try: +
....: collection.sort() +
....: except AttributeError: +
....: pass # The pass statement does nothing +
....: print(collection) +
....: +
+
In [12]: print_sorted([1, 3, 2]) +
[1, 2, 3] +
+
In [13]: print_sorted(set((1, 3, 2))) +
{1, 2, 3} +
+
In [14]: print_sorted('132') +
132 +
+
+
+
+
+

1.2.8.3. Raising exceptions

+
    +
  • Capturing and reraising an exception:

    +
    In [15]: def filter_name(name):
    +
    ....: try: +
    ....: name = name.encode('ascii') +
    ....: except UnicodeError as e: +
    ....: if name == 'Gaël': +
    ....: print('OK, Gaël') +
    ....: else: +
    ....: raise e +
    ....: return name +
    ....: +
    +
    In [16]: filter_name('Gaël') +
    OK, Gaël +
    Out[16]: 'Gaël' +
    +
    In [17]: filter_name('Stéfan') +
    --------------------------------------------------------------------------- +
    UnicodeEncodeError Traceback (most recent call last) +
    Cell In[17], line 1 +
    ----> 1 filter_name('Stéfan') +
    +
    Cell In[15], line 8, in filter_name(name) +
    6 print('OK, Gaël') +
    7 else: +
    ----> 8 raise e +
    9 return name +
    +
    Cell In[15], line 3, in filter_name(name) +
    1 def filter_name(name): +
    2 try: +
    ----> 3 name = name.encode('ascii') +
    4 except UnicodeError as e: +
    5 if name == 'Gaël': +
    +
    UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 2: ordinal not in range(128) +
    +
    +
  • +
  • Exceptions to pass messages between parts of the code:

    +
    In [18]: def achilles_arrow(x):
    +
    ....: if abs(x - 1) < 1e-3: +
    ....: raise StopIteration +
    ....: x = 1 - (1-x)/2. +
    ....: return x +
    ....: +
    +
    In [19]: x = 0 +
    +
    In [20]: while True: +
    ....: try: +
    ....: x = achilles_arrow(x) +
    ....: except StopIteration: +
    ....: break +
    ....: +
    ....: +
    +
    In [21]: x +
    Out[21]: 0.9990234375 +
    +
    +
  • +
+

Use exceptions to notify certain conditions are met (e.g. +StopIteration) or not (e.g. custom error raising)

+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/language/first_steps.html b/intro/language/first_steps.html new file mode 100644 index 000000000..432195e56 --- /dev/null +++ b/intro/language/first_steps.html @@ -0,0 +1,261 @@ + + + + + + + + 1.2.1. First steps — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.2.1. First steps

+

Start the Ipython shell (an enhanced interactive Python shell):

+
    +
  • by typing “ipython” from a Linux/Mac terminal, or from the Windows cmd shell,

  • +
  • or by starting the program from a menu, e.g. the Anaconda Navigator, +the Python(x,y) menu if you have installed one of these +scientific-Python suites.

  • +
+
+

Tip

+

If you don’t have Ipython installed on your computer, other Python +shells are available, such as the plain Python shell started by +typing “python” in a terminal, or the Idle interpreter. However, we +advise to use the Ipython shell because of its enhanced features, +especially for interactive scientific computing.

+
+

Once you have started the interpreter, type

+
>>> print("Hello, world!")
+
Hello, world! +
+
+
+

Tip

+

The message “Hello, world!” is then displayed. You just executed your +first Python instruction, congratulations!

+
+

To get yourself started, type the following stack of instructions

+
>>> a = 3
+
>>> b = 2*a +
>>> type(b) +
<class 'int'> +
>>> print(b) +
6 +
>>> a*b +
18 +
>>> b = 'hello' +
>>> type(b) +
<class 'str'> +
>>> b + b +
'hellohello' +
>>> 2*b +
'hellohello' +
+
+
+

Tip

+

Two variables a and b have been defined above. Note that one does +not declare the type of a variable before assigning its value. In C, +conversely, one should write:

+
int a = 3;
+
+
+

In addition, the type of a variable may change, in the sense that at +one point in time it can be equal to a value of a certain type, and a +second point in time, it can be equal to a value of a different +type. b was first equal to an integer, but it became equal to a +string when it was assigned the value ‘hello’. Operations on +integers (b=2*a) are coded natively in Python, and so are some +operations on strings such as additions and multiplications, which +amount respectively to concatenation and repetition.

+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/language/functions.html b/intro/language/functions.html new file mode 100644 index 000000000..f3548d514 --- /dev/null +++ b/intro/language/functions.html @@ -0,0 +1,574 @@ + + + + + + + + 1.2.4. Defining functions — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.2.4. Defining functions

+
+

1.2.4.1. Function definition

+
In [1]: def test():
+
...: print('in test function') +
...: +
...: +
+
In [2]: test() +
in test function +
+
+
+

Warning

+

Function blocks must be indented as other control-flow blocks.

+
+
+
+

1.2.4.2. Return statement

+

Functions can optionally return values.

+
In [3]: def disk_area(radius):
+
...: return 3.14 * radius * radius +
...: +
+
In [4]: disk_area(1.5) +
Out[4]: 7.0649999999999995 +
+
+
+

Note

+

By default, functions return None.

+
+
+

Note

+

Note the syntax to define a function:

+
    +
  • the def keyword;

  • +
  • is followed by the function’s name, then

  • +
  • the arguments of the function are given between parentheses followed +by a colon.

  • +
  • the function body;

  • +
  • and return object for optionally returning values.

  • +
+
+
+
+

1.2.4.3. Parameters

+

Mandatory parameters (positional arguments)

+
In [5]: def double_it(x):
+
...: return x * 2 +
...: +
+
In [6]: double_it(3) +
Out[6]: 6 +
+
In [7]: double_it() +
--------------------------------------------------------------------------- +
TypeError Traceback (most recent call last) +
Cell In[7], line 1 +
----> 1 double_it() +
+
TypeError: double_it() missing 1 required positional argument: 'x' +
+
+

Optional parameters (keyword or named arguments)

+
In [8]: def double_it(x=2):
+
...: return x * 2 +
...: +
+
In [9]: double_it() +
Out[9]: 4 +
+
In [10]: double_it(3) +
Out[10]: 6 +
+
+

Keyword arguments allow you to specify default values.

+
+

Warning

+

Default values are evaluated when the function is defined, not when +it is called. This can be problematic when using mutable types (e.g. +dictionary or list) and modifying them in the function body, since the +modifications will be persistent across invocations of the function.

+

Using an immutable type in a keyword argument:

+
In [11]: bigx = 10
+
+
In [12]: def double_it(x=bigx): +
....: return x * 2 +
....: +
+
In [13]: bigx = 1e9 # Now really big +
+
In [14]: double_it() +
Out[14]: 20 +
+
+

Using an mutable type in a keyword argument (and modifying it inside the +function body):

+
In [15]: def add_to_dict(args={'a': 1, 'b': 2}):
+
....: for i in args.keys(): +
....: args[i] += 1 +
....: print(args) +
....: +
+
In [16]: add_to_dict +
Out[16]: <function __main__.add_to_dict(args={'a': 1, 'b': 2})> +
+
In [17]: add_to_dict() +
{'a': 2, 'b': 3} +
+
In [18]: add_to_dict() +
{'a': 3, 'b': 4} +
+
In [19]: add_to_dict() +
{'a': 4, 'b': 5} +
+
+
+
+

Tip

+

More involved example implementing python’s slicing:

+
In [20]: def slicer(seq, start=None, stop=None, step=None):
+
....: """Implement basic python slicing.""" +
....: return seq[start:stop:step] +
....: +
+
In [21]: rhyme = 'one fish, two fish, red fish, blue fish'.split() +
+
In [22]: rhyme +
Out[22]: ['one', 'fish,', 'two', 'fish,', 'red', 'fish,', 'blue', 'fish'] +
+
In [23]: slicer(rhyme) +
Out[23]: ['one', 'fish,', 'two', 'fish,', 'red', 'fish,', 'blue', 'fish'] +
+
In [24]: slicer(rhyme, step=2) +
Out[24]: ['one', 'two', 'red', 'blue'] +
+
In [25]: slicer(rhyme, 1, step=2) +
Out[25]: ['fish,', 'fish,', 'fish,', 'fish'] +
+
In [26]: slicer(rhyme, start=1, stop=4, step=2) +
Out[26]: ['fish,', 'fish,'] +
+
+

The order of the keyword arguments does not matter:

+
In [27]: slicer(rhyme, step=2, start=1, stop=4)
+
Out[27]: ['fish,', 'fish,'] +
+
+

but it is good practice to use the same ordering as the function’s +definition.

+
+

Keyword arguments are a very convenient feature for defining functions +with a variable number of arguments, especially when default values are +to be used in most calls to the function.

+
+
+

1.2.4.4. Passing by value

+
+

Tip

+

Can you modify the value of a variable inside a function? Most languages +(C, Java, …) distinguish “passing by value” and “passing by reference”. +In Python, such a distinction is somewhat artificial, and it is a bit +subtle whether your variables are going to be modified or not. +Fortunately, there exist clear rules.

+

Parameters to functions are references to objects, which are passed by +value. When you pass a variable to a function, python passes the +reference to the object to which the variable refers (the value). +Not the variable itself.

+
+

If the value passed in a function is immutable, the function does not +modify the caller’s variable. If the value is mutable, the function +may modify the caller’s variable in-place:

+
>>> def try_to_modify(x, y, z):
+
... x = 23 +
... y.append(42) +
... z = [99] # new reference +
... print(x) +
... print(y) +
... print(z) +
... +
>>> a = 77 # immutable variable +
>>> b = [99] # mutable variable +
>>> c = [28] +
>>> try_to_modify(a, b, c) +
23 +
[99, 42] +
[99] +
>>> print(a) +
77 +
>>> print(b) +
[99, 42] +
>>> print(c) +
[28] +
+
+

Functions have a local variable table called a local namespace.

+

The variable x only exists within the function try_to_modify.

+
+
+

1.2.4.5. Global variables

+

Variables declared outside the function can be referenced within the +function:

+
In [28]: x = 5
+
+
In [29]: def addx(y): +
....: return x + y +
....: +
+
In [30]: addx(10) +
Out[30]: 15 +
+
+

But these “global” variables cannot be modified within the function, +unless declared global in the function.

+

This doesn’t work:

+
In [31]: def setx(y):
+
....: x = y +
....: print('x is %d' % x) +
....: +
....: +
+
In [32]: setx(10) +
x is 10 +
+
In [33]: x +
Out[33]: 5 +
+
+

This works:

+
In [34]: def setx(y):
+
....: global x +
....: x = y +
....: print('x is %d' % x) +
....: +
....: +
+
In [35]: setx(10) +
x is 10 +
+
In [36]: x +
Out[36]: 10 +
+
+
+
+

1.2.4.6. Variable number of parameters

+
+
Special forms of parameters:
    +
  • *args: any number of positional arguments packed into a tuple

  • +
  • **kwargs: any number of keyword arguments packed into a dictionary

  • +
+
+
+
In [37]: def variable_args(*args, **kwargs):
+
....: print('args is', args) +
....: print('kwargs is', kwargs) +
....: +
+
In [38]: variable_args('one', 'two', x=1, y=2, z=3) +
args is ('one', 'two') +
kwargs is {'x': 1, 'y': 2, 'z': 3} +
+
+
+
+

1.2.4.7. Docstrings

+

Documentation about what the function does and its parameters. General +convention:

+
In [39]: def funcname(params):
+
....: """Concise one-line sentence describing the function. +
....: +
....: Extended summary which can contain multiple paragraphs. +
....: """ +
....: # function body +
....: pass +
....: +
+
In [40]: funcname? +
Signature: funcname(params) +
Docstring: +
Concise one-line sentence describing the function. +
Extended summary which can contain multiple paragraphs. +
File: ~/src/scientific-python-lectures/<ipython-input-13-64e466df6d64> +
Type: function +
+
+
+

Note

+

Docstring guidelines

+

For the sake of standardization, the Docstring +Conventions webpage +documents the semantics and conventions associated with Python +docstrings.

+

Also, the NumPy and SciPy modules have defined a precise standard +for documenting scientific functions, that you may want to follow for +your own functions, with a Parameters section, an Examples +section, etc. See +https://numpydoc.readthedocs.io/en/latest/format.html#docstring-standard

+
+
+
+

1.2.4.8. Functions are objects

+
+
Functions are first-class objects, which means they can be:
    +
  • assigned to a variable

  • +
  • an item in a list (or any collection)

  • +
  • passed as an argument to another function.

  • +
+
+
+
In [41]: va = variable_args
+
+
In [42]: va('three', x=1, y=2) +
args is ('three',) +
kwargs is {'x': 1, 'y': 2} +
+
+
+
+

1.2.4.9. Methods

+

Methods are functions attached to objects. You’ve seen these in our +examples on lists, dictionaries, strings, etc…

+
+
+

1.2.4.10. Exercises

+ + +
function quicksort(array)
+
var list less, greater +
if length(array) < 2 +
return array +
select and remove a pivot value pivot from array +
for each x in array +
if x < pivot + 1 then append x to less +
else append x to greater +
return concatenate(quicksort(less), pivot, quicksort(greater)) +
+
+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/language/io.html b/intro/language/io.html new file mode 100644 index 000000000..ab346c7af --- /dev/null +++ b/intro/language/io.html @@ -0,0 +1,274 @@ + + + + + + + + 1.2.6. Input and Output — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.2.6. Input and Output

+

To be exhaustive, here are some information about input and output in +Python. Since we will use the NumPy methods to read and write files, +you may skip this chapter at first reading.

+

We write or read strings to/from files (other types must be converted to +strings). To write in a file:

+
>>> f = open('workfile', 'w') # opens the workfile file
+
>>> type(f) +
<class '_io.TextIOWrapper'> +
>>> f.write('This is a test \nand another test') +
>>> f.close() +
+
+

To read from a file

+
In [1]: f = open('workfile', 'r')
+
+
In [2]: s = f.read() +
+
In [3]: print(s) +
This is a test +
and another test +
+
In [4]: f.close() +
+
+ +
+

1.2.6.1. Iterating over a file

+
In [5]: f = open('workfile', 'r')
+
+
In [6]: for line in f: +
...: print(line) +
...: +
This is a test +
and another test +
+
In [7]: f.close() +
+
+
+

File modes

+
    +
  • Read-only: r

  • +
  • Write-only: w

    +
      +
    • Note: Create a new file or overwrite existing file.

    • +
    +
  • +
  • Append a file: a

  • +
  • Read and Write: r+

  • +
  • Binary mode: b

    +
      +
    • Note: Use for binary files, especially on Windows.

    • +
    +
  • +
+

+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/language/oop.html b/intro/language/oop.html new file mode 100644 index 000000000..810b8ea4b --- /dev/null +++ b/intro/language/oop.html @@ -0,0 +1,253 @@ + + + + + + + + 1.2.9. Object-oriented programming (OOP) — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.2.9. Object-oriented programming (OOP)

+

Python supports object-oriented programming (OOP). The goals of OOP are:

+
+
    +
  • to organize the code, and

  • +
  • to reuse code in similar contexts.

  • +
+
+

Here is a small example: we create a Student class, which is an object +gathering several custom functions (methods) and variables (attributes), +we will be able to use:

+
>>> class Student(object):
+
... def __init__(self, name): +
... self.name = name +
... def set_age(self, age): +
... self.age = age +
... def set_major(self, major): +
... self.major = major +
... +
>>> anna = Student('anna') +
>>> anna.set_age(21) +
>>> anna.set_major('physics') +
+
+

In the previous example, the Student class has __init__, set_age and +set_major methods. Its attributes are name, age and major. We +can call these methods and attributes with the following notation: +classinstance.method or classinstance.attribute. The __init__ +constructor is a special method we call with: MyClass(init parameters if +any).

+

Now, suppose we want to create a new class MasterStudent with the same +methods and attributes as the previous one, but with an additional +internship attribute. We won’t copy the previous class, but +inherit from it:

+
>>> class MasterStudent(Student):
+
... internship = 'mandatory, from March to June' +
... +
>>> james = MasterStudent('james') +
>>> james.internship +
'mandatory, from March to June' +
>>> james.set_age(23) +
>>> james.age +
23 +
+
+

The MasterStudent class inherited from the Student attributes and methods.

+

Thanks to classes and object-oriented programming, we can organize code +with different classes corresponding to different objects we encounter +(an Experiment class, an Image class, a Flow class, etc.), with their own +methods and attributes. Then we can use inheritance to consider +variations around a base class and reuse code. Ex : from a Flow +base class, we can create derived StokesFlow, TurbulentFlow, +PotentialFlow, etc.

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/language/python_language.html b/intro/language/python_language.html new file mode 100644 index 000000000..45b9ba960 --- /dev/null +++ b/intro/language/python_language.html @@ -0,0 +1,303 @@ + + + + + + + + 1.2. The Python language — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.2. The Python language

+

Authors: Chris Burns, Christophe Combelles, Emmanuelle Gouillart, +Gaël Varoquaux

+ +../../_images/python-logo.png +
+

Tip

+

Python is a programming language, as are C, Fortran, BASIC, PHP, +etc. Some specific features of Python are as follows:

+
    +
  • an interpreted (as opposed to compiled) language. Contrary to e.g. +C or Fortran, one does not compile Python code before executing it. In +addition, Python can be used interactively: many Python +interpreters are available, from which commands and scripts can be +executed.

  • +
  • a free software released under an open-source license: Python can +be used and distributed free of charge, even for building commercial +software.

  • +
  • multi-platform: Python is available for all major operating +systems, Windows, Linux/Unix, MacOS X, most likely your mobile phone +OS, etc.

  • +
  • a very readable language with clear non-verbose syntax

  • +
  • a language for which a large variety of high-quality packages are +available for various applications, from web frameworks to scientific +computing.

  • +
  • a language very easy to interface with other languages, in particular C +and C++.

  • +
  • Some other features of the language are illustrated just below. For +example, Python is an object-oriented language, with dynamic typing +(the same variable can contain objects of different types during the +course of a program).

  • +
+

See https://www.python.org/about/ for more information about +distinguishing features of Python.

+
+
+ +

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/language/reusing_code.html b/intro/language/reusing_code.html new file mode 100644 index 000000000..22a780a34 --- /dev/null +++ b/intro/language/reusing_code.html @@ -0,0 +1,773 @@ + + + + + + + + 1.2.5. Reusing code: scripts and modules — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.2.5. Reusing code: scripts and modules

+

For now, we have typed all instructions in the interpreter. For longer +sets of instructions we need to change track and write the code in text +files (using a text editor), that we will call either scripts or +modules. Use your favorite text editor (provided it offers syntax +highlighting for Python), or the editor that comes with the Scientific +Python Suite you may be using.

+
+

1.2.5.1. Scripts

+
+

Tip

+

Let us first write a script, that is a file with a sequence of +instructions that are executed each time the script is called. +Instructions may be e.g. copied-and-pasted from the interpreter (but +take care to respect indentation rules!).

+
+

The extension for Python files is .py. Write or copy-and-paste the +following lines in a file called test.py

+
message = "Hello how are you?"
+
for word in message.split(): +
print(word) +
+
+
+

Tip

+

Let us now execute the script interactively, that is inside the +Ipython interpreter. This is maybe the most common use of scripts in +scientific computing.

+
+
+

Note

+

in Ipython, the syntax to execute a script is %run script.py. For +example,

+
+
In [1]: %run test.py
+
Hello +
how +
are +
you? +
+
In [2]: message +
Out[2]: 'Hello how are you?' +
+
+

The script has been executed. Moreover the variables defined in the +script (such as message) are now available inside the interpreter’s +namespace.

+
+

Tip

+

Other interpreters also offer the possibility to execute scripts +(e.g., execfile in the plain Python interpreter, etc.).

+
+

It is also possible In order to execute this script as a standalone +program, by executing the script inside a shell terminal (Linux/Mac +console or cmd Windows console). For example, if we are in the same +directory as the test.py file, we can execute this in a console:

+
$ python test.py
+
Hello +
how +
are +
you? +
+
+
+

Tip

+

Standalone scripts may also take command-line arguments

+

In file.py:

+
import sys
+
print(sys.argv) +
+
+
$ python file.py test arguments
+
['file.py', 'test', 'arguments'] +
+
+
+

Warning

+

Don’t implement option parsing yourself. Use a dedicated module such as +argparse.

+
+
+
+
+

1.2.5.2. Importing objects from modules

+
In [3]: import os
+
+
In [4]: os +
Out[4]: <module 'os' (frozen)> +
+
In [5]: os.listdir('.') +
Out[5]: +
['profile_vljqla3g', +
'profile_opiqsgvm', +
'clr-debug-pipe-1671-35181-out', +
'profile_xpjos9ca', +
'profile_ldwq_g2z', +
'systemd-private-63e9c24443644feeb8d4b2a40cf1b480-haveged.service-hjbBVo', +
'profile_8_2rsj1s', +
'profile_3lizqjwg', +
'profile_2kz2rfqp', +
'profile_ecz_surr', +
'profile_4ykszos_', +
'profile_11ziuez6', +
'clr-debug-pipe-1654-34928-in', +
'clr-debug-pipe-615-862-in', +
'profile_augff_pi', +
'snap-private-tmp', +
'profile_j09siifo', +
'profile_56ka35ba', +
'.Test-unix', +
'profile_4vqz1s29', +
'profile_np_so14h', +
'profile_v47o6p9h', +
'profile_v_v3jbub', +
'profile__w7pjcek', +
'profile_elmz4kdk', +
'profile_uijgtctx', +
'dotnet-diagnostic-615-862-socket', +
'systemd-private-63e9c24443644feeb8d4b2a40cf1b480-systemd-logind.service-wVtXfH', +
'profile_j7bticpb', +
'profile_7qe0bk4f', +
'profile__63efn63', +
'.X11-unix', +
'profile_k1gvdoov', +
'.ICE-unix', +
'.font-unix', +
'profile_tvmx7dqn', +
'profile_vjshp4vh', +
'profile_76qua5_1', +
'profile_6n6cz2vr', +
'profile_5pm0nlnf', +
'profile_ga6kbhr8', +
'profile_ij9ozup1', +
'profile_d5i0armu', +
'profile_4r1xh4ri', +
'profile_x5kjw20k', +
'profile_0hypzgow', +
'profile_uf6uujd2', +
'profile_k1u18zcv', +
'profile_rp3xs_ex', +
'dotnet-diagnostic-1671-35181-socket', +
'profile_bt_5mf31', +
'profile_rzk36k1d', +
'profile_4qbivbpo', +
'profile_22__f0c6', +
'profile__77z6xrn', +
'profile_9i3ux322', +
'profile_9gs54uhd', +
'profile_j1tc79ad', +
'clr-debug-pipe-1654-34928-out', +
'profile_gp23o325', +
'profile_2l_ke68z', +
'.XIM-unix', +
'dotnet-diagnostic-1654-34928-socket', +
'www-data-temp-aspnet-0', +
'profile_psqqkg8b', +
'profile_1cugsmec', +
'clr-debug-pipe-615-862-out', +
'profile_2ta9m44a', +
'profile_999p7gzi', +
'profile_h2io_49d', +
'systemd-private-63e9c24443644feeb8d4b2a40cf1b480-chrony.service-H3kr1y', +
'profile_l89rd3_e', +
'profile_rq9456f6', +
'systemd-private-63e9c24443644feeb8d4b2a40cf1b480-systemd-resolved.service-MWLZPy', +
'profile_yccpaqyp', +
'profile_ge3hemni', +
'profile_ishv245g', +
'profile_8518z0r4', +
'clr-debug-pipe-1671-35181-in'] +
+
+

And also:

+
In [6]: from os import listdir
+
+
+

Importing shorthands:

+
In [7]: import numpy as np
+
+
+
+

Warning

+
from os import *
+
+
+

This is called the star import and please, Do not use it

+
    +
  • Makes the code harder to read and understand: where do symbols come +from?

  • +
  • Makes it impossible to guess the functionality by the context and +the name (hint: os.name is the name of the OS), and to profit +usefully from tab completion.

  • +
  • Restricts the variable names you can use: os.name might override +name, or vise-versa.

  • +
  • Creates possible name clashes between modules.

  • +
  • Makes the code impossible to statically check for undefined +symbols.

  • +
+
+
+

Tip

+

Modules are thus a good way to organize code in a hierarchical way. Actually, +all the scientific computing tools we are going to use are modules:

+
>>> import numpy as np # data arrays
+
>>> np.linspace(0, 10, 6) +
array([ 0., 2., 4., 6., 8., 10.]) +
>>> import scipy as sp # scientific computing +
+
+
+
+
+

1.2.5.3. Creating modules

+
+

Tip

+

If we want to write larger and better organized programs (compared to +simple scripts), where some objects are defined, (variables, +functions, classes) and that we want to reuse several times, we have +to create our own modules.

+
+

Let us create a module demo contained in the file demo.py:

+
+
"A demo module."
+
+
+
def print_b(): +
"Prints b." +
print("b") +
+
+
def print_a(): +
"Prints a." +
print("a") +
+
+
c = 2 +
d = 2 +
+
+
+
+

Tip

+

In this file, we defined two functions print_a and print_b. Suppose +we want to call the print_a function from the interpreter. We could +execute the file as a script, but since we just want to have access to +the function print_a, we are rather going to import it as a module. +The syntax is as follows.

+
+
In [8]: import demo
+
+
In [9]: demo.print_a() +
a +
+
In [10]: demo.print_b() +
b +
+
+

Importing the module gives access to its objects, using the +module.object syntax. Don’t forget to put the module’s name before the +object’s name, otherwise Python won’t recognize the instruction.

+

Introspection

+
In [11]: demo?
+
Type: module +
Base Class: <type 'module'> +
String Form: <module 'demo' from 'demo.py'> +
Namespace: Interactive +
File: /home/varoquau/Projects/Python_talks/scipy_2009_tutorial/source/demo.py +
Docstring: +
A demo module. +
+
In [12]: who +
demo +
+
In [13]: whos +
Variable Type Data/Info +
------------------------------ +
demo module <module 'demo' from 'demo.py'> +
+
In [14]: dir(demo) +
Out[14]: +
['__builtins__', +
'__doc__', +
'__file__', +
'__name__', +
'__package__', +
'c', +
'd', +
'print_a', +
'print_b'] +
+
In [15]: demo.<TAB> +
demo.c demo.print_a demo.py +
demo.d demo.print_b demo.pyc +
+
+

Importing objects from modules into the main namespace

+
In [16]: from demo import print_a, print_b
+
+
In [17]: whos +
Variable Type Data/Info +
-------------------------------- +
demo module <module 'demo' from 'demo.py'> +
print_a function <function print_a at 0xb7421534> +
print_b function <function print_b at 0xb74214c4> +
+
In [18]: print_a() +
a +
+
+
+

Warning

+

Module caching

+
+

Modules are cached: if you modify demo.py and re-import it in the +old session, you will get the old one.

+
+

Solution:

+
+
In [10]: importlib.reload(demo)
+
+
+
+
+
+
+

1.2.5.4. ‘__main__’ and module loading

+
+

Tip

+

Sometimes we want code to be executed when a module is +run directly, but not when it is imported by another module. +if __name__ == '__main__' allows us to check whether the +module is being run directly.

+
+

File demo2.py:

+
+
def print_b():
+
"Prints b." +
print("b") +
+
+
def print_a(): +
"Prints a." +
print("a") +
+
+
# print_b() runs on import +
print_b() +
+
if __name__ == "__main__": +
# print_a() is only executed when the module is run directly. +
print_a() +
+
+
+

Importing it:

+
In [19]: import demo2
+
b +
+
In [20]: import demo2 +
+
+

Running it:

+
In [21]: %run demo2
+
b +
a +
+
+
+
+

1.2.5.5. Scripts or modules? How to organize your code

+
+

Note

+

Rule of thumb

+
    +
  • Sets of instructions that are called several times should be +written inside functions for better code reusability.

  • +
  • Functions (or other bits of code) that are called from several +scripts should be written inside a module, so that only the +module is imported in the different scripts (do not copy-and-paste +your functions in the different scripts!).

  • +
+
+
+

How modules are found and imported

+

When the import mymodule statement is executed, the module mymodule +is searched in a given list of directories. This list includes a list +of installation-dependent default path (e.g., /usr/lib64/python3.11) as +well as the list of directories specified by the environment variable +PYTHONPATH.

+

The list of directories searched by Python is given by the sys.path +variable

+
In [22]: import sys
+
+
In [23]: sys.path +
Out[23]: +
['/home/runner/work/scientific-python-lectures/scientific-python-lectures', +
'/opt/hostedtoolcache/Python/3.12.6/x64/lib/python312.zip', +
'/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12', +
'/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/lib-dynload', +
'/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages'] +
+
+

Modules must be located in the search path, therefore you can:

+
    +
  • write your own modules within directories already defined in the +search path (e.g. $HOME/.venv/lectures/lib64/python3.11/site-packages). +You may use symbolic links (on Linux) to keep the code somewhere else.

  • +
  • modify the environment variable PYTHONPATH to include the +directories containing the user-defined modules.

    +
    +

    Tip

    +

    On Linux/Unix, add the following line to a file read by the shell at +startup (e.g. /etc/profile, .profile)

    +
    export PYTHONPATH=$PYTHONPATH:/home/emma/user_defined_modules
    +
    +
    +

    On Windows, https://support.microsoft.com/kb/310519 explains how to +handle environment variables.

    +
    +
  • +
  • or modify the sys.path variable itself within a Python script.

    +
    +

    Tip

    +
    import sys
    +
    new_path = '/home/emma/user_defined_modules' +
    if new_path not in sys.path: +
    sys.path.append(new_path) +
    +
    +

    This method is not very robust, however, because it makes the code +less portable (user-dependent path) and because you have to add the +directory to your sys.path each time you want to import from a module +in this directory.

    +
    +
  • +
+
+

See also

+

See https://docs.python.org/3/tutorial/modules.html for more information +about modules.

+
+
+
+
+

1.2.5.6. Packages

+

A directory that contains many modules is called a package. A package +is a module with submodules (which can have submodules themselves, etc.). +A special file called __init__.py (which may be empty) tells Python +that the directory is a Python package, from which modules can be +imported.

+
$ ls
+
_build_utils/ fft/ _lib/ odr/ spatial/ +
cluster/ fftpack/ linalg/ optimize/ special/ +
conftest.py __init__.py linalg.pxd optimize.pxd special.pxd +
constants/ integrate/ meson.build setup.py stats/ +
datasets/ interpolate/ misc/ signal/ +
_distributor_init.py io/ ndimage/ sparse/ +
$ cd ndimage +
$ ls +
_filters.py __init__.py _measurements.py morphology.py src/ +
filters.py _interpolation.py measurements.py _ni_docstrings.py tests/ +
_fourier.py interpolation.py meson.build _ni_support.py utils/ +
fourier.py LICENSE.txt _morphology.py setup.py +
+
+

From Ipython:

+
In [24]: import scipy as sp
+
+
In [25]: sp.__file__ +
Out[25]: '/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages/scipy/__init__.py' +
+
In [26]: sp.version.version +
Out[26]: '1.14.1' +
+
In [27]: sp.ndimage.morphology.binary_dilation? +
Signature: +
sp.ndimage.morphology.binary_dilation( +
input, +
structure=None, +
iterations=1, +
mask=None, +
output=None, +
border_value=0, +
origin=0, +
brute_force=False, +
) +
Docstring: +
Multidimensional binary dilation with the given structuring element. +
... +
+
+
+
+

1.2.5.7. Good practices

+
    +
  • Use meaningful object names

  • +
  • Indentation: no choice!

    +
    +

    Tip

    +

    Indenting is compulsory in Python! Every command block following a +colon bears an additional indentation level with respect to the +previous line with a colon. One must therefore indent after +def f(): or while:. At the end of such logical blocks, one +decreases the indentation depth (and re-increases it if a new block +is entered, etc.)

    +

    Strict respect of indentation is the price to pay for getting rid of +{ or ; characters that delineate logical blocks in other +languages. Improper indentation leads to errors such as

    +
    ------------------------------------------------------------
    +
    IndentationError: unexpected indent (test.py, line 2) +
    +
    +

    All this indentation business can be a bit confusing in the +beginning. However, with the clear indentation, and in the absence of +extra characters, the resulting code is very nice to read compared to +other languages.

    +
    +
  • +
  • Indentation depth: Inside your text editor, you may choose to +indent with any positive number of spaces (1, 2, 3, 4, …). However, +it is considered good practice to indent with 4 spaces. You may +configure your editor to map the Tab key to a 4-space +indentation.

  • +
  • Style guidelines

    +

    Long lines: you should not write very long lines that span over more +than (e.g.) 80 characters. Long lines can be broken with the \ +character

    +
    >>> long_line = "Here is a very very long line \
    +
    ... that we break in two parts." +
    +
    +

    Spaces

    +

    Write well-spaced code: put whitespaces after commas, around arithmetic +operators, etc.:

    +
    >>> a = 1 # yes
    +
    >>> a=1 # too cramped +
    +
    +

    A certain number of rules +for writing “beautiful” code (and more importantly using the same +conventions as anybody else!) are given in the Style Guide for Python +Code.

    +
  • +
+
+ +

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/language/standard_library.html b/intro/language/standard_library.html new file mode 100644 index 000000000..27c6dfa8f --- /dev/null +++ b/intro/language/standard_library.html @@ -0,0 +1,644 @@ + + + + + + + + 1.2.7. Standard Library — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.2.7. Standard Library

+
+

Note

+

Reference document for this section:

+ +
+
+

1.2.7.1. os module: operating system functionality

+

“A portable way of using operating system dependent functionality.”

+
+

Directory and file manipulation

+

Current directory:

+
In [1]: import os
+
+
In [2]: os.getcwd() +
Out[2]: '/tmp' +
+
+

List a directory:

+
In [3]: os.listdir(os.curdir)
+
Out[3]: +
['profile_dvest70f', +
'profile_vljqla3g', +
'profile_opiqsgvm', +
'clr-debug-pipe-1671-35181-out', +
'profile_xpjos9ca', +
'profile_ldwq_g2z', +
'systemd-private-63e9c24443644feeb8d4b2a40cf1b480-haveged.service-hjbBVo', +
'profile_8_2rsj1s', +
'profile_3lizqjwg', +
'profile_2kz2rfqp', +
'profile_ecz_surr', +
'profile_4ykszos_', +
'profile_11ziuez6', +
'clr-debug-pipe-1654-34928-in', +
'clr-debug-pipe-615-862-in', +
'profile_augff_pi', +
'snap-private-tmp', +
'profile_j09siifo', +
'profile_56ka35ba', +
'.Test-unix', +
'profile_4vqz1s29', +
'profile_jyzqwe1k', +
'profile_np_so14h', +
'profile_v47o6p9h', +
'profile_v_v3jbub', +
'profile__w7pjcek', +
'profile_elmz4kdk', +
'profile_uijgtctx', +
'profile_j8w6qumk', +
'profile_b9dyy5zp', +
'dotnet-diagnostic-615-862-socket', +
'systemd-private-63e9c24443644feeb8d4b2a40cf1b480-systemd-logind.service-wVtXfH', +
'profile_5m0fjzr5', +
'profile_6_mve7iw', +
'profile_j7bticpb', +
'profile_7qe0bk4f', +
'profile__63efn63', +
'.X11-unix', +
'profile_k1gvdoov', +
'.ICE-unix', +
'.font-unix', +
'profile_tvmx7dqn', +
'profile_vjshp4vh', +
'profile_76qua5_1', +
'profile_6n6cz2vr', +
'profile_5pm0nlnf', +
'profile_ga6kbhr8', +
'profile_ij9ozup1', +
'profile_d5i0armu', +
'profile_4r1xh4ri', +
'profile_267svnq6', +
'profile_x5kjw20k', +
'profile_0hypzgow', +
'profile_uf6uujd2', +
'profile_k1u18zcv', +
'profile_rp3xs_ex', +
'dotnet-diagnostic-1671-35181-socket', +
'profile_fabal2mz', +
'profile_bt_5mf31', +
'profile_rzk36k1d', +
'profile_4qbivbpo', +
'profile_22__f0c6', +
'profile__77z6xrn', +
'profile_g__46icb', +
'profile_9i3ux322', +
'profile_9gs54uhd', +
'profile_j1tc79ad', +
'clr-debug-pipe-1654-34928-out', +
'profile_gp23o325', +
'profile_2l_ke68z', +
'.XIM-unix', +
'dotnet-diagnostic-1654-34928-socket', +
'www-data-temp-aspnet-0', +
'profile_ixn68sfi', +
'profile_psqqkg8b', +
'profile_1cugsmec', +
'clr-debug-pipe-615-862-out', +
'profile_i0ehttqy', +
'profile_2ta9m44a', +
'profile_999p7gzi', +
'profile_h2io_49d', +
'systemd-private-63e9c24443644feeb8d4b2a40cf1b480-chrony.service-H3kr1y', +
'profile_l89rd3_e', +
'profile_rq9456f6', +
'systemd-private-63e9c24443644feeb8d4b2a40cf1b480-systemd-resolved.service-MWLZPy', +
'profile_yccpaqyp', +
'profile_ge3hemni', +
'profile_ishv245g', +
'profile_8518z0r4', +
'clr-debug-pipe-1671-35181-in'] +
+
+

Make a directory:

+
In [4]: os.mkdir('junkdir')
+
+
In [5]: 'junkdir' in os.listdir(os.curdir) +
Out[5]: True +
+
+

Rename the directory:

+
In [6]: os.rename('junkdir', 'foodir')
+
+
In [7]: 'junkdir' in os.listdir(os.curdir) +
Out[7]: False +
+
In [8]: 'foodir' in os.listdir(os.curdir) +
Out[8]: True +
+
In [9]: os.rmdir('foodir') +
+
In [10]: 'foodir' in os.listdir(os.curdir) +
Out[10]: False +
+
+

Delete a file:

+
In [11]: fp = open('junk.txt', 'w')
+
+
In [12]: fp.close() +
+
In [13]: 'junk.txt' in os.listdir(os.curdir) +
Out[13]: True +
+
In [14]: os.remove('junk.txt') +
+
In [15]: 'junk.txt' in os.listdir(os.curdir) +
Out[15]: False +
+
+
+
+

os.path: path manipulations

+

os.path provides common operations on pathnames.

+
In [16]: fp = open('junk.txt', 'w')
+
+
In [17]: fp.close() +
+
In [18]: a = os.path.abspath('junk.txt') +
+
In [19]: a +
Out[19]: '/tmp/junk.txt' +
+
In [20]: os.path.split(a) +
Out[20]: ('/tmp', 'junk.txt') +
+
In [21]: os.path.dirname(a) +
Out[21]: '/tmp' +
+
In [22]: os.path.basename(a) +
Out[22]: 'junk.txt' +
+
In [23]: os.path.splitext(os.path.basename(a)) +
Out[23]: ('junk', '.txt') +
+
In [24]: os.path.exists('junk.txt') +
Out[24]: True +
+
In [25]: os.path.isfile('junk.txt') +
Out[25]: True +
+
In [26]: os.path.isdir('junk.txt') +
Out[26]: False +
+
In [27]: os.path.expanduser('~/local') +
Out[27]: '/home/runner/local' +
+
In [28]: os.path.join(os.path.expanduser('~'), 'local', 'bin') +
Out[28]: '/home/runner/local/bin' +
+
+
+
+

Running an external command

+
In [29]: os.system('ls')
+
Out[29]: 0 +
+
+
+

Note

+

Alternative to os.system

+

A noteworthy alternative to os.system is the sh module. Which provides much more convenient ways to +obtain the output, error stream and exit code of the external command.

+
In [30]: import sh
+
In [31]: com = sh.ls() +
+
In [31]: print(com) +
basic_types.rst exceptions.rst oop.rst standard_library.rst +
control_flow.rst first_steps.rst python_language.rst +
demo2.py functions.rst python-logo.png +
demo.py io.rst reusing_code.rst +
+
In [32]: type(com) +
Out[32]: str +
+
+
+
+
+

Walking a directory

+

os.path.walk generates a list of filenames in a directory tree.

+
In [33]: for dirpath, dirnames, filenames in os.walk(os.curdir):
+
....: for fp in filenames: +
....: print(os.path.abspath(fp)) +
....: +
....: +
/tmp/clr-debug-pipe-1671-35181-out +
/tmp/clr-debug-pipe-1654-34928-in +
/tmp/clr-debug-pipe-615-862-in +
/tmp/dotnet-diagnostic-615-862-socket +
/tmp/dotnet-diagnostic-1671-35181-socket +
/tmp/clr-debug-pipe-1654-34928-out +
/tmp/dotnet-diagnostic-1654-34928-socket +
/tmp/clr-debug-pipe-615-862-out +
/tmp/junk.txt +
/tmp/clr-debug-pipe-1671-35181-in +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/dhist +
/tmp/bookmarks +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
/tmp/README +
+
+
+
+

Environment variables:

+
In [34]: os.environ.keys()
+
Out[34]: KeysView(environ({'SHELL': '/bin/bash', 'COLORTERM': 'truecolor', ...})) +
+
In [35]: os.environ['SHELL'] +
Out[35]: '/bin/bash' +
+
+
+
+
+

1.2.7.2. shutil: high-level file operations

+

The shutil provides useful file operations:

+
+
    +
  • shutil.rmtree: Recursively delete a directory tree.

  • +
  • shutil.move: Recursively move a file or directory to another location.

  • +
  • shutil.copy: Copy files or directories.

  • +
+
+
+
+

1.2.7.3. glob: Pattern matching on files

+

The glob module provides convenient file pattern matching.

+

Find all files ending in .txt:

+
In [36]: import glob
+
+
In [37]: glob.glob('*.txt') +
Out[37]: ['junk.txt'] +
+
+
+
+

1.2.7.4. sys module: system-specific information

+

System-specific information related to the Python interpreter.

+
    +
  • Which version of python are you running and where is it installed:

  • +
+
In [38]: import sys
+
+
In [39]: sys.platform +
Out[39]: 'linux' +
+
In [40]: sys.version +
Out[40]: '3.12.6 (main, Sep 9 2024, 03:08:08) [GCC 11.4.0]' +
+
In [41]: sys.prefix +
Out[41]: '/opt/hostedtoolcache/Python/3.12.6/x64' +
+
+
    +
  • List of command line arguments passed to a Python script:

  • +
+
In [42]: sys.argv
+
Out[42]: +
['/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages/sphinx/__main__.py', +
'-b', +
'latex', +
'-d', +
'build/doctrees', +
'.', +
'build/latex'] +
+
+

sys.path is a list of strings that specifies the search path for +modules. Initialized from PYTHONPATH:

+
In [43]: sys.path
+
Out[43]: +
['/home/runner/work/scientific-python-lectures/scientific-python-lectures', +
'/opt/hostedtoolcache/Python/3.12.6/x64/lib/python312.zip', +
'/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12', +
'/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/lib-dynload', +
'/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages'] +
+
+
+
+

1.2.7.5. pickle: easy persistence

+

Useful to store arbitrary objects to a file. Not safe or fast!

+
In [44]: import pickle
+
+
In [45]: l = [1, None, 'Stan'] +
+
In [46]: with open('test.pkl', 'wb') as file: +
....: pickle.dump(l, file) +
....: +
+
In [47]: with open('test.pkl', 'rb') as file: +
....: out = pickle.load(file) +
....: +
+
In [48]: out +
Out[48]: [1, None, 'Stan'] +
+
+ +

The PYTHONPATH Search Solution

+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/exercises/index.html b/intro/matplotlib/auto_examples/exercises/index.html new file mode 100644 index 000000000..a1a4e6de2 --- /dev/null +++ b/intro/matplotlib/auto_examples/exercises/index.html @@ -0,0 +1,235 @@ + + + + + + + + Code for the chapter’s exercises — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Code for the chapter’s exercises

+
+

Exercise 1

+
Exercise 1
+
+

Exercise 4

+
Exercise 4
+
+

Exercise 3

+
Exercise 3
+
+

Exercise 5

+
Exercise 5
+
+

Exercise 6

+
Exercise 6
+
+

Exercise 2

+
Exercise 2
+
+

Exercise 7

+
Exercise 7
+
+

Exercise 8

+
Exercise 8
+
+

Exercise 9

+
Exercise 9
+
+

Exercise

+
Exercise
+
+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/exercises/plot_exercise_1.html b/intro/matplotlib/auto_examples/exercises/plot_exercise_1.html new file mode 100644 index 000000000..99299bc60 --- /dev/null +++ b/intro/matplotlib/auto_examples/exercises/plot_exercise_1.html @@ -0,0 +1,234 @@ + + + + + + + + Exercise 1 — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Exercise 1

+

Solution of the exercise 1 with matplotlib.

+plot exercise 1
import numpy as np
+
import matplotlib.pyplot as plt +
+
n = 256 +
X = np.linspace(-np.pi, np.pi, 256) +
C, S = np.cos(X), np.sin(X) +
plt.plot(X, C) +
plt.plot(X, S) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.059 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/exercises/plot_exercise_10.html b/intro/matplotlib/auto_examples/exercises/plot_exercise_10.html new file mode 100644 index 000000000..3afbd3d31 --- /dev/null +++ b/intro/matplotlib/auto_examples/exercises/plot_exercise_10.html @@ -0,0 +1,303 @@ + + + + + + + + Exercise — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Exercise

+

Exercises with matplotlib.

+plot exercise 10
import numpy as np
+
import matplotlib.pyplot as plt +
+
plt.figure(figsize=(8, 5), dpi=80) +
plt.subplot(111) +
+
X = np.linspace(-np.pi, np.pi, 256) +
C, S = np.cos(X), np.sin(X) +
+
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine") +
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine") +
+
ax = plt.gca() +
ax.spines["right"].set_color("none") +
ax.spines["top"].set_color("none") +
ax.xaxis.set_ticks_position("bottom") +
ax.spines["bottom"].set_position(("data", 0)) +
ax.yaxis.set_ticks_position("left") +
ax.spines["left"].set_position(("data", 0)) +
+
plt.xlim(X.min() * 1.1, X.max() * 1.1) +
plt.xticks( +
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], +
[r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"], +
) +
+
plt.ylim(C.min() * 1.1, C.max() * 1.1) +
plt.yticks([-1, 1], [r"$-1$", r"$+1$"]) +
+
plt.legend(loc="upper left") +
+
t = 2 * np.pi / 3 +
plt.plot([t, t], [0, np.cos(t)], color="blue", linewidth=1.5, linestyle="--") +
plt.scatter( +
[ +
t, +
], +
[ +
np.cos(t), +
], +
50, +
color="blue", +
) +
plt.annotate( +
r"$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$", +
xy=(t, np.sin(t)), +
xycoords="data", +
xytext=(10, 30), +
textcoords="offset points", +
fontsize=16, +
arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=.2"}, +
) +
+
plt.plot([t, t], [0, np.sin(t)], color="red", linewidth=1.5, linestyle="--") +
plt.scatter( +
[ +
t, +
], +
[ +
np.sin(t), +
], +
50, +
color="red", +
) +
plt.annotate( +
r"$cos(\frac{2\pi}{3})=-\frac{1}{2}$", +
xy=(t, np.cos(t)), +
xycoords="data", +
xytext=(-90, -50), +
textcoords="offset points", +
fontsize=16, +
arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=.2"}, +
) +
+
for label in ax.get_xticklabels() + ax.get_yticklabels(): +
label.set_fontsize(16) +
label.set_bbox({"facecolor": "white", "edgecolor": "None", "alpha": 0.65}) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.102 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/exercises/plot_exercise_2.html b/intro/matplotlib/auto_examples/exercises/plot_exercise_2.html new file mode 100644 index 000000000..5bc6394d0 --- /dev/null +++ b/intro/matplotlib/auto_examples/exercises/plot_exercise_2.html @@ -0,0 +1,256 @@ + + + + + + + + Exercise 2 — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Exercise 2

+

Exercise 2 with matplotlib.

+plot exercise 2
import numpy as np
+
import matplotlib.pyplot as plt +
+
# Create a new figure of size 8x6 points, using 100 dots per inch +
plt.figure(figsize=(8, 6), dpi=80) +
+
# Create a new subplot from a grid of 1x1 +
plt.subplot(111) +
+
X = np.linspace(-np.pi, np.pi, 256) +
C, S = np.cos(X), np.sin(X) +
+
# Plot cosine using blue color with a continuous line of width 1 (pixels) +
plt.plot(X, C, color="blue", linewidth=1.0, linestyle="-") +
+
# Plot sine using green color with a continuous line of width 1 (pixels) +
plt.plot(X, S, color="green", linewidth=1.0, linestyle="-") +
+
# Set x limits +
plt.xlim(-4.0, 4.0) +
+
# Set x ticks +
plt.xticks(np.linspace(-4, 4, 9)) +
+
# Set y limits +
plt.ylim(-1.0, 1.0) +
+
# Set y ticks +
plt.yticks(np.linspace(-1, 1, 5)) +
+
# Show result on screen +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.051 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/exercises/plot_exercise_3.html b/intro/matplotlib/auto_examples/exercises/plot_exercise_3.html new file mode 100644 index 000000000..d42dca2bb --- /dev/null +++ b/intro/matplotlib/auto_examples/exercises/plot_exercise_3.html @@ -0,0 +1,243 @@ + + + + + + + + Exercise 3 — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Exercise 3

+

Exercise 3 with matplotlib.

+plot exercise 3
import numpy as np
+
import matplotlib.pyplot as plt +
+
plt.figure(figsize=(8, 5), dpi=80) +
plt.subplot(111) +
+
X = np.linspace(-np.pi, np.pi, 256) +
C, S = np.cos(X), np.sin(X) +
+
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") +
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") +
+
plt.xlim(-4.0, 4.0) +
plt.xticks(np.linspace(-4, 4, 9)) +
+
plt.ylim(-1.0, 1.0) +
plt.yticks(np.linspace(-1, 1, 5)) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.048 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/exercises/plot_exercise_4.html b/intro/matplotlib/auto_examples/exercises/plot_exercise_4.html new file mode 100644 index 000000000..ef513d725 --- /dev/null +++ b/intro/matplotlib/auto_examples/exercises/plot_exercise_4.html @@ -0,0 +1,241 @@ + + + + + + + + Exercise 4 — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Exercise 4

+

Exercise 4 with matplotlib.

+plot exercise 4
import numpy as np
+
import matplotlib.pyplot as plt +
+
plt.figure(figsize=(8, 5), dpi=80) +
plt.subplot(111) +
+
X = np.linspace(-np.pi, np.pi, 256) +
S = np.sin(X) +
C = np.cos(X) +
+
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") +
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") +
+
plt.xlim(X.min() * 1.1, X.max() * 1.1) +
plt.ylim(C.min() * 1.1, C.max() * 1.1) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.056 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/exercises/plot_exercise_5.html b/intro/matplotlib/auto_examples/exercises/plot_exercise_5.html new file mode 100644 index 000000000..4e582f88c --- /dev/null +++ b/intro/matplotlib/auto_examples/exercises/plot_exercise_5.html @@ -0,0 +1,244 @@ + + + + + + + + Exercise 5 — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Exercise 5

+

Exercise 5 with matplotlib.

+plot exercise 5
import numpy as np
+
import matplotlib.pyplot as plt +
+
plt.figure(figsize=(8, 5), dpi=80) +
plt.subplot(111) +
+
X = np.linspace(-np.pi, np.pi, 256) +
S = np.sin(X) +
C = np.cos(X) +
+
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") +
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") +
+
plt.xlim(X.min() * 1.1, X.max() * 1.1) +
plt.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi]) +
+
plt.ylim(C.min() * 1.1, C.max() * 1.1) +
plt.yticks([-1, 0, +1]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.039 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/exercises/plot_exercise_6.html b/intro/matplotlib/auto_examples/exercises/plot_exercise_6.html new file mode 100644 index 000000000..f37e2aa89 --- /dev/null +++ b/intro/matplotlib/auto_examples/exercises/plot_exercise_6.html @@ -0,0 +1,247 @@ + + + + + + + + Exercise 6 — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Exercise 6

+

Exercise 6 with matplotlib.

+plot exercise 6
import numpy as np
+
import matplotlib.pyplot as plt +
+
plt.figure(figsize=(8, 5), dpi=80) +
plt.subplot(111) +
+
X = np.linspace(-np.pi, np.pi, 256) +
C = np.cos(X) +
S = np.sin(X) +
+
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") +
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") +
+
plt.xlim(X.min() * 1.1, X.max() * 1.1) +
plt.xticks( +
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], +
[r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"], +
) +
+
plt.ylim(C.min() * 1.1, C.max() * 1.1) +
plt.yticks([-1, 0, +1], [r"$-1$", r"$0$", r"$+1$"]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.049 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/exercises/plot_exercise_7.html b/intro/matplotlib/auto_examples/exercises/plot_exercise_7.html new file mode 100644 index 000000000..ef2758b05 --- /dev/null +++ b/intro/matplotlib/auto_examples/exercises/plot_exercise_7.html @@ -0,0 +1,255 @@ + + + + + + + + Exercise 7 — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Exercise 7

+

Exercise 7 with matplotlib

+plot exercise 7
import numpy as np
+
import matplotlib.pyplot as plt +
+
plt.figure(figsize=(8, 5), dpi=80) +
plt.subplot(111) +
+
X = np.linspace(-np.pi, np.pi, 256, endpoint=True) +
C = np.cos(X) +
S = np.sin(X) +
+
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") +
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") +
+
ax = plt.gca() +
ax.spines["right"].set_color("none") +
ax.spines["top"].set_color("none") +
ax.xaxis.set_ticks_position("bottom") +
ax.spines["bottom"].set_position(("data", 0)) +
ax.yaxis.set_ticks_position("left") +
ax.spines["left"].set_position(("data", 0)) +
+
plt.xlim(X.min() * 1.1, X.max() * 1.1) +
plt.xticks( +
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], +
[r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"], +
) +
+
plt.ylim(C.min() * 1.1, C.max() * 1.1) +
plt.yticks([-1, 0, +1], [r"$-1$", r"$0$", r"$+1$"]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.055 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/exercises/plot_exercise_8.html b/intro/matplotlib/auto_examples/exercises/plot_exercise_8.html new file mode 100644 index 000000000..682c51343 --- /dev/null +++ b/intro/matplotlib/auto_examples/exercises/plot_exercise_8.html @@ -0,0 +1,257 @@ + + + + + + + + Exercise 8 — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Exercise 8

+

Exercise 8 with matplotlib.

+plot exercise 8
import numpy as np
+
import matplotlib.pyplot as plt +
+
plt.figure(figsize=(8, 5), dpi=80) +
plt.subplot(111) +
+
X = np.linspace(-np.pi, np.pi, 256, endpoint=True) +
C = np.cos(X) +
S = np.sin(X) +
+
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine") +
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine") +
+
ax = plt.gca() +
ax.spines["right"].set_color("none") +
ax.spines["top"].set_color("none") +
ax.xaxis.set_ticks_position("bottom") +
ax.spines["bottom"].set_position(("data", 0)) +
ax.yaxis.set_ticks_position("left") +
ax.spines["left"].set_position(("data", 0)) +
+
plt.xlim(X.min() * 1.1, X.max() * 1.1) +
plt.xticks( +
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], +
[r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"], +
) +
+
plt.ylim(C.min() * 1.1, C.max() * 1.1) +
plt.yticks([-1, +1], [r"$-1$", r"$+1$"]) +
+
plt.legend(loc="upper left") +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.061 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/exercises/plot_exercise_9.html b/intro/matplotlib/auto_examples/exercises/plot_exercise_9.html new file mode 100644 index 000000000..51b17add5 --- /dev/null +++ b/intro/matplotlib/auto_examples/exercises/plot_exercise_9.html @@ -0,0 +1,300 @@ + + + + + + + + Exercise 9 — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Exercise 9

+

Exercise 9 with matplotlib.

+plot exercise 9
import numpy as np
+
import matplotlib.pyplot as plt +
+
plt.figure(figsize=(8, 5), dpi=80) +
plt.subplot(111) +
+
X = np.linspace(-np.pi, np.pi, 256, endpoint=True) +
C = np.cos(X) +
S = np.sin(X) +
+
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine") +
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine") +
+
ax = plt.gca() +
ax.spines["right"].set_color("none") +
ax.spines["top"].set_color("none") +
ax.xaxis.set_ticks_position("bottom") +
ax.spines["bottom"].set_position(("data", 0)) +
ax.yaxis.set_ticks_position("left") +
ax.spines["left"].set_position(("data", 0)) +
+
plt.xlim(X.min() * 1.1, X.max() * 1.1) +
plt.xticks( +
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], +
[r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"], +
) +
+
plt.ylim(C.min() * 1.1, C.max() * 1.1) +
plt.yticks([-1, +1], [r"$-1$", r"$+1$"]) +
+
t = 2 * np.pi / 3 +
plt.plot([t, t], [0, np.cos(t)], color="blue", linewidth=1.5, linestyle="--") +
plt.scatter( +
[ +
t, +
], +
[ +
np.cos(t), +
], +
50, +
color="blue", +
) +
plt.annotate( +
r"$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$", +
xy=(t, np.sin(t)), +
xycoords="data", +
xytext=(+10, +30), +
textcoords="offset points", +
fontsize=16, +
arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=.2"}, +
) +
+
plt.plot([t, t], [0, np.sin(t)], color="red", linewidth=1.5, linestyle="--") +
plt.scatter( +
[ +
t, +
], +
[ +
np.sin(t), +
], +
50, +
color="red", +
) +
plt.annotate( +
r"$cos(\frac{2\pi}{3})=-\frac{1}{2}$", +
xy=(t, np.cos(t)), +
xycoords="data", +
xytext=(-90, -50), +
textcoords="offset points", +
fontsize=16, +
arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=.2"}, +
) +
+
plt.legend(loc="upper left") +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.104 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/exercises/sg_execution_times.html b/intro/matplotlib/auto_examples/exercises/sg_execution_times.html new file mode 100644 index 000000000..8ab51316f --- /dev/null +++ b/intro/matplotlib/auto_examples/exercises/sg_execution_times.html @@ -0,0 +1,242 @@ + + + + + + + + Computation times — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Computation times

+

00:00.624 total execution time for 10 files from intro/matplotlib/auto_examples/exercises:

+
+ + + + + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Example

Time

Mem (MB)

Exercise 9 (plot_exercise_9.py)

00:00.104

0.0

Exercise (plot_exercise_10.py)

00:00.102

0.0

Exercise 8 (plot_exercise_8.py)

00:00.061

0.0

Exercise 1 (plot_exercise_1.py)

00:00.059

0.0

Exercise 4 (plot_exercise_4.py)

00:00.056

0.0

Exercise 7 (plot_exercise_7.py)

00:00.055

0.0

Exercise 2 (plot_exercise_2.py)

00:00.051

0.0

Exercise 6 (plot_exercise_6.py)

00:00.049

0.0

Exercise 3 (plot_exercise_3.py)

00:00.048

0.0

Exercise 5 (plot_exercise_5.py)

00:00.039

0.0

+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/index.html b/intro/matplotlib/auto_examples/index.html new file mode 100644 index 000000000..533bcff7e --- /dev/null +++ b/intro/matplotlib/auto_examples/index.html @@ -0,0 +1,396 @@ + + + + + + + + Code samples for Matplotlib — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Code samples for Matplotlib

+

The examples here are only examples relevant to the points raised in this +chapter. The matplotlib documentation comes with a much more exhaustive +gallery.

+
+

Pie chart

+
Pie chart
+
+

A simple, good-looking plot

+
A simple, good-looking plot
+
+

Plotting a scatter of points

+
Plotting a scatter of points
+
+

Subplots

+
Subplots
+
+

Horizontal arrangement of subplots

+
Horizontal arrangement of subplots
+
+

A simple plotting example

+
A simple plotting example
+
+

Subplot plot arrangement vertical

+
Subplot plot arrangement vertical
+
+

Simple axes example

+
Simple axes example
+
+

3D plotting

+
3D plotting
+
+

Imshow elaborate

+
Imshow elaborate
+
+

Plotting a vector field: quiver

+
Plotting a vector field: quiver
+
+

Displaying the contours of a function

+
Displaying the contours of a function
+
+

A example of plotting not quite right

+
A example of plotting not quite right
+
+

Plot and filled plots

+
Plot and filled plots
+
+

Plotting in polar coordinates

+
Plotting in polar coordinates
+
+

Subplot grid

+
Subplot grid
+
+

Bar plots

+
Bar plots
+
+

Axes

+
Axes
+
+

Grid

+
Grid
+
+

3D plotting

+
3D plotting
+
+

GridSpec

+
GridSpec
+
+

Demo text printing

+
Demo text printing
+
+
+
+
+

Code for the chapter’s exercises

+
+

Exercise 1

+
Exercise 1
+
+

Exercise 4

+
Exercise 4
+
+

Exercise 3

+
Exercise 3
+
+

Exercise 5

+
Exercise 5
+
+

Exercise 6

+
Exercise 6
+
+

Exercise 2

+
Exercise 2
+
+

Exercise 7

+
Exercise 7
+
+

Exercise 8

+
Exercise 8
+
+

Exercise 9

+
Exercise 9
+
+

Exercise

+
Exercise
+
+
+

Example demoing choices for an option

+
+

The colors matplotlib line plots

+
The colors matplotlib line plots
+
+

Linewidth

+
Linewidth
+
+

Alpha: transparency

+
Alpha: transparency
+
+

Aliased versus anti-aliased

+
Aliased versus anti-aliased
+
+

Aliased versus anti-aliased

+
Aliased versus anti-aliased
+
+

Marker size

+
Marker size
+
+

Marker edge width

+
Marker edge width
+
+

Colormaps

+
Colormaps
+
+

Solid joint style

+
Solid joint style
+
+

Solid cap style

+
Solid cap style
+
+

Marker edge color

+
Marker edge color
+
+

Marker face color

+
Marker face color
+
+

Dash capstyle

+
Dash capstyle
+
+

Dash join style

+
Dash join style
+
+

Markers

+
Markers
+
+

Linestyles

+
Linestyles
+
+

Locators for tick on axis

+
Locators for tick on axis
+
+
+

Code generating the summary figures with a title

+
+

3D plotting vignette

+
3D plotting vignette
+
+

Plotting in polar, decorated

+
Plotting in polar, decorated
+
+

Plot example vignette

+
Plot example vignette
+
+

Multiple plots vignette

+
Multiple plots vignette
+
+

Boxplot with matplotlib

+
Boxplot with matplotlib
+
+

Plot scatter decorated

+
Plot scatter decorated
+
+

Pie chart vignette

+
Pie chart vignette
+
+

Imshow demo

+
Imshow demo
+
+

Bar plot advanced

+
Bar plot advanced
+
+

Plotting quiver decorated

+
Plotting quiver decorated
+
+

Display the contours of a function

+
Display the contours of a function
+
+

Grid elaborate

+
Grid elaborate
+
+

Text printing decorated

+
Text printing decorated
+
+
+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/options/index.html b/intro/matplotlib/auto_examples/options/index.html new file mode 100644 index 000000000..3390fc637 --- /dev/null +++ b/intro/matplotlib/auto_examples/options/index.html @@ -0,0 +1,256 @@ + + + + + + + + Example demoing choices for an option — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Example demoing choices for an option

+
+

The colors matplotlib line plots

+
The colors matplotlib line plots
+
+

Linewidth

+
Linewidth
+
+

Alpha: transparency

+
Alpha: transparency
+
+

Aliased versus anti-aliased

+
Aliased versus anti-aliased
+
+

Aliased versus anti-aliased

+
Aliased versus anti-aliased
+
+

Marker size

+
Marker size
+
+

Marker edge width

+
Marker edge width
+
+

Colormaps

+
Colormaps
+
+

Solid joint style

+
Solid joint style
+
+

Solid cap style

+
Solid cap style
+
+

Marker edge color

+
Marker edge color
+
+

Marker face color

+
Marker face color
+
+

Dash capstyle

+
Dash capstyle
+
+

Dash join style

+
Dash join style
+
+

Markers

+
Markers
+
+

Linestyles

+
Linestyles
+
+

Locators for tick on axis

+
Locators for tick on axis
+
+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/options/plot_aliased.html b/intro/matplotlib/auto_examples/options/plot_aliased.html new file mode 100644 index 000000000..0517a8f50 --- /dev/null +++ b/intro/matplotlib/auto_examples/options/plot_aliased.html @@ -0,0 +1,243 @@ + + + + + + + + Aliased versus anti-aliased — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Aliased versus anti-aliased

+

This example demonstrates aliased versus anti-aliased text.

+plot aliased
import matplotlib.pyplot as plt
+
+
size = 128, 16 +
dpi = 72.0 +
figsize = size[0] / float(dpi), size[1] / float(dpi) +
fig = plt.figure(figsize=figsize, dpi=dpi) +
fig.patch.set_alpha(0) +
+
plt.axes((0, 0, 1, 1), frameon=False) +
+
plt.rcParams["text.antialiased"] = False +
plt.text(0.5, 0.5, "Aliased", ha="center", va="center") +
+
plt.xlim(0, 1) +
plt.ylim(0, 1) +
plt.xticks([]) +
plt.yticks([]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.012 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/options/plot_alpha.html b/intro/matplotlib/auto_examples/options/plot_alpha.html new file mode 100644 index 000000000..4a07101a2 --- /dev/null +++ b/intro/matplotlib/auto_examples/options/plot_alpha.html @@ -0,0 +1,240 @@ + + + + + + + + Alpha: transparency — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Alpha: transparency

+

This example demonstrates using alpha for transparency.

+plot alpha
import matplotlib.pyplot as plt
+
+
size = 256, 16 +
dpi = 72.0 +
figsize = size[0] / float(dpi), size[1] / float(dpi) +
fig = plt.figure(figsize=figsize, dpi=dpi) +
fig.patch.set_alpha(0) +
plt.axes((0, 0.1, 1, 0.8), frameon=False) +
+
for i in range(1, 11): +
plt.axvline(i, linewidth=1, color="blue", alpha=0.25 + 0.75 * i / 10.0) +
+
plt.xlim(0, 11) +
plt.xticks([]) +
plt.yticks([]) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.019 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/options/plot_antialiased.html b/intro/matplotlib/auto_examples/options/plot_antialiased.html new file mode 100644 index 000000000..91ea95b34 --- /dev/null +++ b/intro/matplotlib/auto_examples/options/plot_antialiased.html @@ -0,0 +1,242 @@ + + + + + + + + Aliased versus anti-aliased — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Aliased versus anti-aliased

+

The example shows aliased versus anti-aliased text.

+plot antialiased
import matplotlib.pyplot as plt
+
+
size = 128, 16 +
dpi = 72.0 +
figsize = size[0] / float(dpi), size[1] / float(dpi) +
fig = plt.figure(figsize=figsize, dpi=dpi) +
fig.patch.set_alpha(0) +
plt.axes((0, 0, 1, 1), frameon=False) +
+
plt.rcParams["text.antialiased"] = True +
plt.text(0.5, 0.5, "Anti-aliased", ha="center", va="center") +
+
plt.xlim(0, 1) +
plt.ylim(0, 1) +
plt.xticks([]) +
plt.yticks([]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.013 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/options/plot_color.html b/intro/matplotlib/auto_examples/options/plot_color.html new file mode 100644 index 000000000..f801ee594 --- /dev/null +++ b/intro/matplotlib/auto_examples/options/plot_color.html @@ -0,0 +1,240 @@ + + + + + + + + The colors matplotlib line plots — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

The colors matplotlib line plots

+

An example demoing the various colors taken by matplotlib’s plot.

+plot color
import matplotlib.pyplot as plt
+
+
size = 256, 16 +
dpi = 72.0 +
figsize = size[0] / float(dpi), size[1] / float(dpi) +
fig = plt.figure(figsize=figsize, dpi=dpi) +
fig.patch.set_alpha(0) +
plt.axes((0, 0.1, 1, 0.8), frameon=False) +
+
for i in range(1, 11): +
plt.plot([i, i], [0, 1], lw=1.5) +
+
plt.xlim(0, 11) +
plt.xticks([]) +
plt.yticks([]) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.018 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/options/plot_colormaps.html b/intro/matplotlib/auto_examples/options/plot_colormaps.html new file mode 100644 index 000000000..3dd278606 --- /dev/null +++ b/intro/matplotlib/auto_examples/options/plot_colormaps.html @@ -0,0 +1,246 @@ + + + + + + + + Colormaps — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Colormaps

+

An example plotting the matplotlib colormaps.

+Accent, Blues, BrBG, BuGn, BuPu, CMRmap, Dark2, GnBu, Grays, Greens, Greys, OrRd, Oranges, PRGn, Paired, Pastel1, Pastel2, PiYG, PuBu, PuBuGn, PuOr, PuRd, Purples, RdBu, RdGy, RdPu, RdYlBu, RdYlGn, Reds, Set1, Set2, Set3, Spectral, Wistia, YlGn, YlGnBu, YlOrBr, YlOrRd, afmhot, autumn, binary, bone, brg, bwr, cividis, cool, coolwarm, copper, cubehelix, flag, gist_earth, gist_gray, gist_grey, gist_heat, gist_ncar, gist_rainbow, gist_stern, gist_yarg, gist_yerg, gnuplot, gnuplot2, gray, grey, hot, hsv, inferno, jet, magma, nipy_spectral, ocean, pink, plasma, prism, rainbow, seismic, spring, summer, tab10, tab20, tab20b, tab20c, terrain, turbo, twilight, twilight_shifted, viridis, winter
import numpy as np
+
+
import matplotlib +
import matplotlib.pyplot as plt +
+
+
plt.rc("text", usetex=False) +
a = np.outer(np.arange(0, 1, 0.01), np.ones(10)) +
+
plt.figure(figsize=(10, 5)) +
plt.subplots_adjust(top=0.8, bottom=0.05, left=0.01, right=0.99) +
maps = [m for m in matplotlib.colormaps if not m.endswith("_r")] +
maps.sort() +
l = len(maps) + 1 +
+
for i, m in enumerate(maps): +
plt.subplot(1, l, i + 1) +
plt.axis("off") +
plt.imshow(a, aspect="auto", cmap=plt.get_cmap(m), origin="lower") +
plt.title(m, rotation=90, fontsize=10, va="bottom") +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 1.807 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/options/plot_dash_capstyle.html b/intro/matplotlib/auto_examples/options/plot_dash_capstyle.html new file mode 100644 index 000000000..14e882bbb --- /dev/null +++ b/intro/matplotlib/auto_examples/options/plot_dash_capstyle.html @@ -0,0 +1,266 @@ + + + + + + + + Dash capstyle — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Dash capstyle

+

An example demoing the dash capstyle.

+plot dash capstyle
import numpy as np
+
import matplotlib.pyplot as plt +
+
size = 256, 16 +
dpi = 72.0 +
figsize = size[0] / float(dpi), size[1] / float(dpi) +
fig = plt.figure(figsize=figsize, dpi=dpi) +
fig.patch.set_alpha(0) +
plt.axes((0, 0, 1, 1), frameon=False) +
+
plt.plot( +
np.arange(4), +
np.ones(4), +
color="blue", +
dashes=[15, 15], +
linewidth=8, +
dash_capstyle="butt", +
) +
+
plt.plot( +
5 + np.arange(4), +
np.ones(4), +
color="blue", +
dashes=[15, 15], +
linewidth=8, +
dash_capstyle="round", +
) +
+
plt.plot( +
10 + np.arange(4), +
np.ones(4), +
color="blue", +
dashes=[15, 15], +
linewidth=8, +
dash_capstyle="projecting", +
) +
+
plt.xlim(0, 14) +
plt.xticks([]) +
plt.yticks([]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.014 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/options/plot_dash_joinstyle.html b/intro/matplotlib/auto_examples/options/plot_dash_joinstyle.html new file mode 100644 index 000000000..7f1582ec3 --- /dev/null +++ b/intro/matplotlib/auto_examples/options/plot_dash_joinstyle.html @@ -0,0 +1,265 @@ + + + + + + + + Dash join style — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Dash join style

+

Example demoing the dash join style.

+plot dash joinstyle
import numpy as np
+
import matplotlib.pyplot as plt +
+
size = 256, 16 +
dpi = 72.0 +
figsize = size[0] / float(dpi), size[1] / float(dpi) +
fig = plt.figure(figsize=figsize, dpi=dpi) +
fig.patch.set_alpha(0) +
plt.axes((0, 0, 1, 1), frameon=False) +
+
plt.plot( +
np.arange(3), +
[0, 1, 0], +
color="blue", +
dashes=[12, 5], +
linewidth=8, +
dash_joinstyle="miter", +
) +
plt.plot( +
4 + np.arange(3), +
[0, 1, 0], +
color="blue", +
dashes=[12, 5], +
linewidth=8, +
dash_joinstyle="bevel", +
) +
plt.plot( +
8 + np.arange(3), +
[0, 1, 0], +
color="blue", +
dashes=[12, 5], +
linewidth=8, +
dash_joinstyle="round", +
) +
+
plt.xlim(0, 12) +
plt.ylim(-1, 2) +
plt.xticks([]) +
plt.yticks([]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.014 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/options/plot_linestyles.html b/intro/matplotlib/auto_examples/options/plot_linestyles.html new file mode 100644 index 000000000..e4406e50e --- /dev/null +++ b/intro/matplotlib/auto_examples/options/plot_linestyles.html @@ -0,0 +1,287 @@ + + + + + + + + Linestyles — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Linestyles

+

Plot the different line styles.

+plot linestyles
import numpy as np
+
import matplotlib.pyplot as plt +
+
+
def linestyle(ls, i): +
X = i * 0.5 * np.ones(11) +
Y = np.arange(11) +
plt.plot( +
X, +
Y, +
ls, +
color=(0.0, 0.0, 1, 1), +
lw=3, +
ms=8, +
mfc=(0.75, 0.75, 1, 1), +
mec=(0, 0, 1, 1), +
) +
plt.text(0.5 * i, 10.25, ls, rotation=90, fontsize=15, va="bottom") +
+
+
linestyles = [ +
"-", +
"--", +
":", +
"-.", +
".", +
",", +
"o", +
"^", +
"v", +
"<", +
">", +
"s", +
"+", +
"x", +
"d", +
"1", +
"2", +
"3", +
"4", +
"h", +
"p", +
"|", +
"_", +
"D", +
"H", +
] +
n_lines = len(linestyles) +
+
size = 20 * n_lines, 300 +
dpi = 72.0 +
figsize = size[0] / float(dpi), size[1] / float(dpi) +
fig = plt.figure(figsize=figsize, dpi=dpi) +
plt.axes((0, 0.01, 1, 0.9), frameon=False) +
+
for i, ls in enumerate(linestyles): +
linestyle(ls, i) +
+
plt.xlim(-0.2, 0.2 + 0.5 * n_lines) +
plt.xticks([]) +
plt.yticks([]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.044 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/options/plot_linewidth.html b/intro/matplotlib/auto_examples/options/plot_linewidth.html new file mode 100644 index 000000000..17676ba04 --- /dev/null +++ b/intro/matplotlib/auto_examples/options/plot_linewidth.html @@ -0,0 +1,242 @@ + + + + + + + + Linewidth — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Linewidth

+

Plot various linewidth with matplotlib.

+plot linewidth
import matplotlib.pyplot as plt
+
+
size = 256, 16 +
dpi = 72.0 +
figsize = size[0] / float(dpi), size[1] / float(dpi) +
fig = plt.figure(figsize=figsize, dpi=dpi) +
fig.patch.set_alpha(0) +
plt.axes((0, 0.1, 1, 0.8), frameon=False) +
+
for i in range(1, 11): +
plt.plot([i, i], [0, 1], color="b", lw=i / 2.0) +
+
plt.xlim(0, 11) +
plt.ylim(0, 1) +
plt.xticks([]) +
plt.yticks([]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.020 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/options/plot_markers.html b/intro/matplotlib/auto_examples/options/plot_markers.html new file mode 100644 index 000000000..11b384402 --- /dev/null +++ b/intro/matplotlib/auto_examples/options/plot_markers.html @@ -0,0 +1,287 @@ + + + + + + + + Markers — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Markers

+

Show the different markers of matplotlib.

+plot markers
import numpy as np
+
import matplotlib.pyplot as plt +
+
+
def marker(m, i): +
X = i * 0.5 * np.ones(11) +
Y = np.arange(11) +
+
plt.plot(X, Y, lw=1, marker=m, ms=10, mfc=(0.75, 0.75, 1, 1), mec=(0, 0, 1, 1)) +
plt.text(0.5 * i, 10.25, repr(m), rotation=90, fontsize=15, va="bottom") +
+
+
markers = [ +
0, +
1, +
2, +
3, +
4, +
5, +
6, +
7, +
"o", +
"h", +
"_", +
"1", +
"2", +
"3", +
"4", +
"8", +
"p", +
"^", +
"v", +
"<", +
">", +
"|", +
"d", +
",", +
"+", +
"s", +
"*", +
"|", +
"x", +
"D", +
"H", +
".", +
] +
+
n_markers = len(markers) +
+
size = 20 * n_markers, 300 +
dpi = 72.0 +
figsize = size[0] / float(dpi), size[1] / float(dpi) +
fig = plt.figure(figsize=figsize, dpi=dpi) +
plt.axes((0, 0.01, 1, 0.9), frameon=False) +
+
for i, m in enumerate(markers): +
marker(m, i) +
+
plt.xlim(-0.2, 0.2 + 0.5 * n_markers) +
plt.xticks([]) +
plt.yticks([]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.073 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/options/plot_mec.html b/intro/matplotlib/auto_examples/options/plot_mec.html new file mode 100644 index 000000000..c00814cf3 --- /dev/null +++ b/intro/matplotlib/auto_examples/options/plot_mec.html @@ -0,0 +1,257 @@ + + + + + + + + Marker edge color — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Marker edge color

+

Demo the marker edge color of matplotlib’s markers.

+plot mec
import numpy as np
+
import matplotlib.pyplot as plt +
+
size = 256, 16 +
dpi = 72.0 +
figsize = size[0] / float(dpi), size[1] / float(dpi) +
fig = plt.figure(figsize=figsize, dpi=dpi) +
fig.patch.set_alpha(0) +
plt.axes((0, 0, 1, 1), frameon=False) +
+
rng = np.random.default_rng() +
+
for i in range(1, 11): +
r, g, b = np.random.uniform(0, 1, 3) +
plt.plot( +
[ +
i, +
], +
[ +
1, +
], +
"s", +
markersize=5, +
markerfacecolor="w", +
markeredgewidth=1.5, +
markeredgecolor=(r, g, b, 1), +
) +
+
plt.xlim(0, 11) +
plt.xticks([]) +
plt.yticks([]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.017 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/options/plot_mew.html b/intro/matplotlib/auto_examples/options/plot_mew.html new file mode 100644 index 000000000..a6f4247c8 --- /dev/null +++ b/intro/matplotlib/auto_examples/options/plot_mew.html @@ -0,0 +1,252 @@ + + + + + + + + Marker edge width — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Marker edge width

+

Demo the marker edge widths of matplotlib’s markers.

+plot mew
import matplotlib.pyplot as plt
+
+
size = 256, 16 +
dpi = 72.0 +
figsize = size[0] / float(dpi), size[1] / float(dpi) +
fig = plt.figure(figsize=figsize, dpi=dpi) +
fig.patch.set_alpha(0) +
plt.axes((0, 0, 1, 1), frameon=False) +
+
for i in range(1, 11): +
plt.plot( +
[ +
i, +
], +
[ +
1, +
], +
"s", +
markersize=5, +
markeredgewidth=1 + i / 10.0, +
markeredgecolor="k", +
markerfacecolor="w", +
) +
plt.xlim(0, 11) +
plt.xticks([]) +
plt.yticks([]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.017 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/options/plot_mfc.html b/intro/matplotlib/auto_examples/options/plot_mfc.html new file mode 100644 index 000000000..cc559123d --- /dev/null +++ b/intro/matplotlib/auto_examples/options/plot_mfc.html @@ -0,0 +1,255 @@ + + + + + + + + Marker face color — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Marker face color

+

Demo the marker face color of matplotlib’s markers.

+plot mfc
import numpy as np
+
import matplotlib.pyplot as plt +
+
size = 256, 16 +
dpi = 72.0 +
figsize = size[0] / float(dpi), size[1] / float(dpi) +
fig = plt.figure(figsize=figsize, dpi=dpi) +
fig.patch.set_alpha(0) +
plt.axes((0, 0, 1, 1), frameon=False) +
+
rng = np.random.default_rng() +
+
for i in range(1, 11): +
r, g, b = np.random.uniform(0, 1, 3) +
plt.plot( +
[ +
i, +
], +
[ +
1, +
], +
"s", +
markersize=8, +
markerfacecolor=(r, g, b, 1), +
markeredgewidth=0.1, +
markeredgecolor=(0, 0, 0, 0.5), +
) +
plt.xlim(0, 11) +
plt.xticks([]) +
plt.yticks([]) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.017 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/options/plot_ms.html b/intro/matplotlib/auto_examples/options/plot_ms.html new file mode 100644 index 000000000..a593dc7fb --- /dev/null +++ b/intro/matplotlib/auto_examples/options/plot_ms.html @@ -0,0 +1,253 @@ + + + + + + + + Marker size — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Marker size

+

Demo the marker size control in matplotlib.

+plot ms
import matplotlib.pyplot as plt
+
+
size = 256, 16 +
dpi = 72.0 +
figsize = size[0] / float(dpi), size[1] / float(dpi) +
fig = plt.figure(figsize=figsize, dpi=dpi) +
fig.patch.set_alpha(0) +
plt.axes((0, 0, 1, 1), frameon=False) +
+
for i in range(1, 11): +
plt.plot( +
[ +
i, +
], +
[ +
1, +
], +
"s", +
markersize=i, +
markerfacecolor="w", +
markeredgewidth=0.5, +
markeredgecolor="k", +
) +
+
plt.xlim(0, 11) +
plt.xticks([]) +
plt.yticks([]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.017 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/options/plot_solid_capstyle.html b/intro/matplotlib/auto_examples/options/plot_solid_capstyle.html new file mode 100644 index 000000000..508340dae --- /dev/null +++ b/intro/matplotlib/auto_examples/options/plot_solid_capstyle.html @@ -0,0 +1,253 @@ + + + + + + + + Solid cap style — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Solid cap style

+

An example demoing the solide cap style in matplotlib.

+plot solid capstyle
import numpy as np
+
import matplotlib.pyplot as plt +
+
size = 256, 16 +
dpi = 72.0 +
figsize = size[0] / float(dpi), size[1] / float(dpi) +
fig = plt.figure(figsize=figsize, dpi=dpi) +
fig.patch.set_alpha(0) +
plt.axes((0, 0, 1, 1), frameon=False) +
+
plt.plot(np.arange(4), np.ones(4), color="blue", linewidth=8, solid_capstyle="butt") +
+
plt.plot( +
5 + np.arange(4), np.ones(4), color="blue", linewidth=8, solid_capstyle="round" +
) +
+
plt.plot( +
10 + np.arange(4), +
np.ones(4), +
color="blue", +
linewidth=8, +
solid_capstyle="projecting", +
) +
+
plt.xlim(0, 14) +
plt.xticks([]) +
plt.yticks([]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.013 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/options/plot_solid_joinstyle.html b/intro/matplotlib/auto_examples/options/plot_solid_joinstyle.html new file mode 100644 index 000000000..0240a71cb --- /dev/null +++ b/intro/matplotlib/auto_examples/options/plot_solid_joinstyle.html @@ -0,0 +1,248 @@ + + + + + + + + Solid joint style — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Solid joint style

+

An example showing the different solid joint styles in matplotlib.

+plot solid joinstyle
import numpy as np
+
import matplotlib.pyplot as plt +
+
size = 256, 16 +
dpi = 72.0 +
figsize = size[0] / float(dpi), size[1] / float(dpi) +
fig = plt.figure(figsize=figsize, dpi=dpi) +
fig.patch.set_alpha(0) +
plt.axes((0, 0, 1, 1), frameon=False) +
+
plt.plot(np.arange(3), [0, 1, 0], color="blue", linewidth=8, solid_joinstyle="miter") +
plt.plot( +
4 + np.arange(3), [0, 1, 0], color="blue", linewidth=8, solid_joinstyle="bevel" +
) +
plt.plot( +
8 + np.arange(3), [0, 1, 0], color="blue", linewidth=8, solid_joinstyle="round" +
) +
+
plt.xlim(0, 12) +
plt.ylim(-1, 2) +
plt.xticks([]) +
plt.yticks([]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.014 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/options/plot_ticks.html b/intro/matplotlib/auto_examples/options/plot_ticks.html new file mode 100644 index 000000000..a3a3d88ce --- /dev/null +++ b/intro/matplotlib/auto_examples/options/plot_ticks.html @@ -0,0 +1,272 @@ + + + + + + + + Locators for tick on axis — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Locators for tick on axis

+

An example demoing different locators to position ticks on axis for +matplotlib.

+plot ticks
import numpy as np
+
+
from matplotlib import ticker +
import matplotlib.pyplot as plt +
+
+
def tickline(): +
plt.xlim(0, 10), plt.ylim(-1, 1), plt.yticks([]) +
ax = plt.gca() +
ax.spines["right"].set_color("none") +
ax.spines["left"].set_color("none") +
ax.spines["top"].set_color("none") +
ax.xaxis.set_ticks_position("bottom") +
ax.spines["bottom"].set_position(("data", 0)) +
ax.yaxis.set_ticks_position("none") +
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.1)) +
ax.plot(np.arange(11), np.zeros(11)) +
return ax +
+
+
locators = [ +
"ticker.NullLocator()", +
"ticker.MultipleLocator(1.0)", +
"ticker.FixedLocator([0, 2, 8, 9, 10])", +
"ticker.IndexLocator(3, 1)", +
"ticker.LinearLocator(5)", +
"ticker.LogLocator(2, [1.0])", +
"ticker.AutoLocator()", +
] +
+
n_locators = len(locators) +
+
size = 512, 40 * n_locators +
dpi = 72.0 +
figsize = size[0] / float(dpi), size[1] / float(dpi) +
fig = plt.figure(figsize=figsize, dpi=dpi) +
fig.patch.set_alpha(0) +
+
+
for i, locator in enumerate(locators): +
plt.subplot(n_locators, 1, i + 1) +
ax = tickline() +
ax.xaxis.set_major_locator(eval(locator)) +
plt.text(5, 0.3, locator[7:], ha="center") +
+
plt.subplots_adjust(bottom=0.01, top=0.99, left=0.01, right=0.99) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.923 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/options/sg_execution_times.html b/intro/matplotlib/auto_examples/options/sg_execution_times.html new file mode 100644 index 000000000..c68a1b82b --- /dev/null +++ b/intro/matplotlib/auto_examples/options/sg_execution_times.html @@ -0,0 +1,270 @@ + + + + + + + + Computation times — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Computation times

+

00:03.052 total execution time for 17 files from intro/matplotlib/auto_examples/options:

+
+ + + + + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Example

Time

Mem (MB)

Colormaps (plot_colormaps.py)

00:01.807

0.0

Locators for tick on axis (plot_ticks.py)

00:00.923

0.0

Markers (plot_markers.py)

00:00.073

0.0

Linestyles (plot_linestyles.py)

00:00.044

0.0

Linewidth (plot_linewidth.py)

00:00.020

0.0

Alpha: transparency (plot_alpha.py)

00:00.019

0.0

The colors matplotlib line plots (plot_color.py)

00:00.018

0.0

Marker edge color (plot_mec.py)

00:00.017

0.0

Marker face color (plot_mfc.py)

00:00.017

0.0

Marker size (plot_ms.py)

00:00.017

0.0

Marker edge width (plot_mew.py)

00:00.017

0.0

Solid joint style (plot_solid_joinstyle.py)

00:00.014

0.0

Dash join style (plot_dash_joinstyle.py)

00:00.014

0.0

Dash capstyle (plot_dash_capstyle.py)

00:00.014

0.0

Solid cap style (plot_solid_capstyle.py)

00:00.013

0.0

Aliased versus anti-aliased (plot_antialiased.py)

00:00.013

0.0

Aliased versus anti-aliased (plot_aliased.py)

00:00.012

0.0

+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_axes-2.html b/intro/matplotlib/auto_examples/plot_axes-2.html new file mode 100644 index 000000000..cb60cbf78 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_axes-2.html @@ -0,0 +1,253 @@ + + + + + + + + Axes — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Axes

+

This example shows various axes command to position matplotlib axes.

+plot axes 2
import matplotlib.pyplot as plt
+
+
plt.axes((0.1, 0.1, 0.5, 0.5)) +
plt.xticks([]) +
plt.yticks([]) +
plt.text( +
0.1, 0.1, "axes((0.1, 0.1, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5 +
) +
+
plt.axes((0.2, 0.2, 0.5, 0.5)) +
plt.xticks([]) +
plt.yticks([]) +
plt.text( +
0.1, 0.1, "axes((0.2, 0.2, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5 +
) +
+
plt.axes((0.3, 0.3, 0.5, 0.5)) +
plt.xticks([]) +
plt.yticks([]) +
plt.text( +
0.1, 0.1, "axes((0.3, 0.3, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5 +
) +
+
plt.axes((0.4, 0.4, 0.5, 0.5)) +
plt.xticks([]) +
plt.yticks([]) +
plt.text( +
0.1, 0.1, "axes((0.4, 0.4, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5 +
) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.058 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_axes.html b/intro/matplotlib/auto_examples/plot_axes.html new file mode 100644 index 000000000..bb4c386cd --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_axes.html @@ -0,0 +1,239 @@ + + + + + + + + Simple axes example — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Simple axes example

+

This example shows a couple of simple usage of axes.

+plot axes
import matplotlib.pyplot as plt
+
+
plt.axes((0.1, 0.1, 0.8, 0.8)) +
plt.xticks([]) +
plt.yticks([]) +
plt.text( +
0.6, 0.6, "axes([0.1, 0.1, 0.8, 0.8])", ha="center", va="center", size=20, alpha=0.5 +
) +
+
plt.axes((0.2, 0.2, 0.3, 0.3)) +
plt.xticks([]) +
plt.yticks([]) +
plt.text( +
0.5, 0.5, "axes([0.2, 0.2, 0.3, 0.3])", ha="center", va="center", size=16, alpha=0.5 +
) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.048 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_bad.html b/intro/matplotlib/auto_examples/plot_bad.html new file mode 100644 index 000000000..519762e80 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_bad.html @@ -0,0 +1,237 @@ + + + + + + + + A simple plotting example — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

A simple plotting example

+

A plotting example with a few simple tweaks

+plot bad
import numpy as np
+
import matplotlib +
+
matplotlib.use("Agg") +
import matplotlib.pyplot as plt +
+
fig = plt.figure(figsize=(5, 4), dpi=72) +
axes = fig.add_axes((0.01, 0.01, 0.98, 0.98)) +
x = np.linspace(0, 2, 200) +
y = np.sin(2 * np.pi * x) +
plt.plot(x, y, lw=0.25, c="k") +
plt.xticks(np.arange(0.0, 2.0, 0.1)) +
plt.yticks(np.arange(-1.0, 1.0, 0.1)) +
plt.grid() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.086 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_bar.html b/intro/matplotlib/auto_examples/plot_bar.html new file mode 100644 index 000000000..4a97a42ec --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_bar.html @@ -0,0 +1,247 @@ + + + + + + + + Bar plots — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Bar plots

+

An example of bar plots with matplotlib.

+plot bar
import numpy as np
+
import matplotlib.pyplot as plt +
+
n = 12 +
X = np.arange(n) +
rng = np.random.default_rng() +
Y1 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n) +
Y2 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n) +
+
plt.axes((0.025, 0.025, 0.95, 0.95)) +
plt.bar(X, +Y1, facecolor="#9999ff", edgecolor="white") +
plt.bar(X, -Y2, facecolor="#ff9999", edgecolor="white") +
+
for x, y in zip(X, Y1, strict=True): +
plt.text(x + 0.4, y + 0.05, f"{y:.2f}", ha="center", va="bottom") +
+
for x, y in zip(X, Y2, strict=True): +
plt.text(x + 0.4, -y - 0.05, f"{y:.2f}", ha="center", va="top") +
+
plt.xlim(-0.5, n) +
plt.xticks([]) +
plt.ylim(-1.25, 1.25) +
plt.yticks([]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.056 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_contour.html b/intro/matplotlib/auto_examples/plot_contour.html new file mode 100644 index 000000000..de7095ef6 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_contour.html @@ -0,0 +1,245 @@ + + + + + + + + Displaying the contours of a function — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Displaying the contours of a function

+

An example showing how to display the contours of a function with +matplotlib.

+plot contour
import numpy as np
+
import matplotlib.pyplot as plt +
+
+
def f(x, y): +
return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2) +
+
+
n = 256 +
x = np.linspace(-3, 3, n) +
y = np.linspace(-3, 3, n) +
X, Y = np.meshgrid(x, y) +
+
plt.axes((0.025, 0.025, 0.95, 0.95)) +
+
plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap="hot") +
C = plt.contour(X, Y, f(X, Y), 8, colors="black", linewidths=0.5) +
plt.clabel(C, inline=1, fontsize=10) +
+
plt.xticks([]) +
plt.yticks([]) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.079 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_good.html b/intro/matplotlib/auto_examples/plot_good.html new file mode 100644 index 000000000..7cad4cc48 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_good.html @@ -0,0 +1,237 @@ + + + + + + + + A simple, good-looking plot — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

A simple, good-looking plot

+

Demoing some simple features of matplotlib

+plot good
import numpy as np
+
import matplotlib +
+
matplotlib.use("Agg") +
import matplotlib.pyplot as plt +
+
fig = plt.figure(figsize=(5, 4), dpi=72) +
axes = fig.add_axes((0.01, 0.01, 0.98, 0.98)) +
X = np.linspace(0, 2, 200) +
Y = np.sin(2 * np.pi * X) +
plt.plot(X, Y, lw=2) +
plt.ylim(-1.1, 1.1) +
plt.grid() +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.053 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_grid.html b/intro/matplotlib/auto_examples/plot_grid.html new file mode 100644 index 000000000..3b19bd9cf --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_grid.html @@ -0,0 +1,241 @@ + + + + + + + + Grid — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Grid

+

Displaying a grid on the axes in matploblib.

+plot grid
import matplotlib.pyplot as plt
+
from matplotlib import ticker +
+
ax = plt.axes((0.025, 0.025, 0.95, 0.95)) +
+
ax.set_xlim(0, 4) +
ax.set_ylim(0, 3) +
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.0)) +
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.1)) +
ax.yaxis.set_major_locator(ticker.MultipleLocator(1.0)) +
ax.yaxis.set_minor_locator(ticker.MultipleLocator(0.1)) +
ax.grid(which="major", axis="x", linewidth=0.75, linestyle="-", color="0.75") +
ax.grid(which="minor", axis="x", linewidth=0.25, linestyle="-", color="0.75") +
ax.grid(which="major", axis="y", linewidth=0.75, linestyle="-", color="0.75") +
ax.grid(which="minor", axis="y", linewidth=0.25, linestyle="-", color="0.75") +
ax.set_xticklabels([]) +
ax.set_yticklabels([]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.106 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_gridspec.html b/intro/matplotlib/auto_examples/plot_gridspec.html new file mode 100644 index 000000000..3c3554beb --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_gridspec.html @@ -0,0 +1,255 @@ + + + + + + + + GridSpec — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

GridSpec

+

An example demoing gridspec

+plot gridspec
import matplotlib.pyplot as plt
+
from matplotlib import gridspec +
+
plt.figure(figsize=(6, 4)) +
G = gridspec.GridSpec(3, 3) +
+
axes_1 = plt.subplot(G[0, :]) +
plt.xticks([]) +
plt.yticks([]) +
plt.text(0.5, 0.5, "Axes 1", ha="center", va="center", size=24, alpha=0.5) +
+
axes_2 = plt.subplot(G[1, :-1]) +
plt.xticks([]) +
plt.yticks([]) +
plt.text(0.5, 0.5, "Axes 2", ha="center", va="center", size=24, alpha=0.5) +
+
axes_3 = plt.subplot(G[1:, -1]) +
plt.xticks([]) +
plt.yticks([]) +
plt.text(0.5, 0.5, "Axes 3", ha="center", va="center", size=24, alpha=0.5) +
+
axes_4 = plt.subplot(G[-1, 0]) +
plt.xticks([]) +
plt.yticks([]) +
plt.text(0.5, 0.5, "Axes 4", ha="center", va="center", size=24, alpha=0.5) +
+
axes_5 = plt.subplot(G[-1, -2]) +
plt.xticks([]) +
plt.yticks([]) +
plt.text(0.5, 0.5, "Axes 5", ha="center", va="center", size=24, alpha=0.5) +
+
plt.tight_layout() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.086 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_imshow.html b/intro/matplotlib/auto_examples/plot_imshow.html new file mode 100644 index 000000000..0130f2152 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_imshow.html @@ -0,0 +1,243 @@ + + + + + + + + Imshow elaborate — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Imshow elaborate

+

An example demoing imshow and styling the figure.

+plot imshow
import numpy as np
+
import matplotlib.pyplot as plt +
+
+
def f(x, y): +
return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2) +
+
+
n = 10 +
x = np.linspace(-3, 3, int(3.5 * n)) +
y = np.linspace(-3, 3, int(3.0 * n)) +
X, Y = np.meshgrid(x, y) +
Z = f(X, Y) +
+
plt.axes((0.025, 0.025, 0.95, 0.95)) +
plt.imshow(Z, interpolation="nearest", cmap="bone", origin="lower") +
plt.colorbar(shrink=0.92) +
+
plt.xticks([]) +
plt.yticks([]) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.122 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_multiplot.html b/intro/matplotlib/auto_examples/plot_multiplot.html new file mode 100644 index 000000000..48a2984f3 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_multiplot.html @@ -0,0 +1,243 @@ + + + + + + + + Subplots — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Subplots

+

Show multiple subplots in matplotlib.

+plot multiplot
import matplotlib.pyplot as plt
+
+
fig = plt.figure() +
fig.subplots_adjust(bottom=0.025, left=0.025, top=0.975, right=0.975) +
+
plt.subplot(2, 1, 1) +
plt.xticks([]), plt.yticks([]) +
+
plt.subplot(2, 3, 4) +
plt.xticks([]) +
plt.yticks([]) +
+
plt.subplot(2, 3, 5) +
plt.xticks([]) +
plt.yticks([]) +
+
plt.subplot(2, 3, 6) +
plt.xticks([]) +
plt.yticks([]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.049 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_pie.html b/intro/matplotlib/auto_examples/plot_pie.html new file mode 100644 index 000000000..13680c614 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_pie.html @@ -0,0 +1,237 @@ + + + + + + + + Pie chart — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Pie chart

+

A simple pie chart example with matplotlib.

+plot pie
import numpy as np
+
import matplotlib.pyplot as plt +
+
n = 20 +
Z = np.ones(n) +
Z[-1] *= 2 +
+
plt.axes((0.025, 0.025, 0.95, 0.95)) +
+
plt.pie(Z, explode=Z * 0.05, colors=[f"{i / float(n):f}" for i in range(n)]) +
plt.axis("equal") +
plt.xticks([]) +
plt.yticks() +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.059 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_plot.html b/intro/matplotlib/auto_examples/plot_plot.html new file mode 100644 index 000000000..da58ab776 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_plot.html @@ -0,0 +1,244 @@ + + + + + + + + Plot and filled plots — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Plot and filled plots

+

Simple example of plots and filling between them with matplotlib.

+plot plot
import numpy as np
+
import matplotlib.pyplot as plt +
+
n = 256 +
X = np.linspace(-np.pi, np.pi, n) +
Y = np.sin(2 * X) +
+
plt.axes((0.025, 0.025, 0.95, 0.95)) +
+
plt.plot(X, Y + 1, color="blue", alpha=1.00) +
plt.fill_between(X, 1, Y + 1, color="blue", alpha=0.25) +
+
plt.plot(X, Y - 1, color="blue", alpha=1.00) +
plt.fill_between(X, -1, Y - 1, (Y - 1) > -1, color="blue", alpha=0.25) +
plt.fill_between(X, -1, Y - 1, (Y - 1) < -1, color="red", alpha=0.25) +
+
plt.xlim(-np.pi, np.pi) +
plt.xticks([]) +
plt.ylim(-2.5, 2.5) +
plt.yticks([]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.033 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_plot3d-2.html b/intro/matplotlib/auto_examples/plot_plot3d-2.html new file mode 100644 index 000000000..891caf607 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_plot3d-2.html @@ -0,0 +1,259 @@ + + + + + + + + 3D plotting — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3D plotting

+

Demo 3D plotting with matplotlib and style the figure.

+plot plot3d 2
import matplotlib.pyplot as plt
+
from mpl_toolkits.mplot3d.axes3d import Axes3D, get_test_data +
+
ax: Axes3D = plt.figure().add_subplot(projection="3d") +
X, Y, Z = get_test_data(0.05) +
cset = ax.contourf(X, Y, Z) +
ax.clabel(cset, fontsize=9, inline=1) +
+
plt.xticks([]) +
plt.yticks([]) +
ax.set_zticks([]) +
+
+
ax.text2D( +
-0.05, +
1.05, +
" 3D plots \n", +
horizontalalignment="left", +
verticalalignment="top", +
bbox={"facecolor": "white", "alpha": 1.0}, +
family="DejaVu Sans", +
size="x-large", +
transform=plt.gca().transAxes, +
) +
+
ax.text2D( +
-0.05, +
0.975, +
" Plot 2D or 3D data", +
horizontalalignment="left", +
verticalalignment="top", +
family="DejaVu Sans", +
size="medium", +
transform=plt.gca().transAxes, +
) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.053 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_plot3d.html b/intro/matplotlib/auto_examples/plot_plot3d.html new file mode 100644 index 000000000..303067caa --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_plot3d.html @@ -0,0 +1,238 @@ + + + + + + + + 3D plotting — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3D plotting

+

A simple example of 3D plotting.

+plot plot3d
import numpy as np
+
import matplotlib.pyplot as plt +
from mpl_toolkits.mplot3d import Axes3D +
+
ax: Axes3D = plt.figure().add_subplot(projection="3d") +
X = np.arange(-4, 4, 0.25) +
Y = np.arange(-4, 4, 0.25) +
X, Y = np.meshgrid(X, Y) +
R = np.sqrt(X**2 + Y**2) +
Z = np.sin(R) +
+
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap="hot") +
ax.contourf(X, Y, Z, zdir="z", offset=-2, cmap="hot") +
ax.set_zlim(-2, 2) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.106 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_polar.html b/intro/matplotlib/auto_examples/plot_polar.html new file mode 100644 index 000000000..0208852c9 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_polar.html @@ -0,0 +1,247 @@ + + + + + + + + Plotting in polar coordinates — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Plotting in polar coordinates

+

A simple example showing how to plot in polar coordinates with +matplotlib.

+plot polar
import numpy as np
+
+
import matplotlib +
import matplotlib.pyplot as plt +
+
+
jet = matplotlib.colormaps["jet"] +
+
ax = plt.axes((0.025, 0.025, 0.95, 0.95), polar=True) +
+
N = 20 +
theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N) +
rng = np.random.default_rng() +
radii = 10 * rng.random(N) +
width = np.pi / 4 * rng.random(N) +
bars = plt.bar(theta, radii, width=width, bottom=0.0) +
+
for r, bar in zip(radii, bars, strict=True): +
bar.set_facecolor(jet(r / 10.0)) +
bar.set_alpha(0.5) +
+
ax.set_xticklabels([]) +
ax.set_yticklabels([]) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.096 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_quiver.html b/intro/matplotlib/auto_examples/plot_quiver.html new file mode 100644 index 000000000..7ca6192a1 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_quiver.html @@ -0,0 +1,242 @@ + + + + + + + + Plotting a vector field: quiver — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Plotting a vector field: quiver

+

A simple example showing how to plot a vector field (quiver) with +matplotlib.

+plot quiver
import numpy as np
+
import matplotlib.pyplot as plt +
+
n = 8 +
X, Y = np.mgrid[0:n, 0:n] +
T = np.arctan2(Y - n / 2.0, X - n / 2.0) +
R = 10 + np.sqrt((Y - n / 2.0) ** 2 + (X - n / 2.0) ** 2) +
U, V = R * np.cos(T), R * np.sin(T) +
+
plt.axes((0.025, 0.025, 0.95, 0.95)) +
plt.quiver(X, Y, U, V, R, alpha=0.5) +
plt.quiver(X, Y, U, V, edgecolor="k", facecolor="None", linewidth=0.5) +
+
plt.xlim(-1, n) +
plt.xticks([]) +
plt.ylim(-1, n) +
plt.yticks([]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.034 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_scatter.html b/intro/matplotlib/auto_examples/plot_scatter.html new file mode 100644 index 000000000..ef3ff168f --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_scatter.html @@ -0,0 +1,240 @@ + + + + + + + + Plotting a scatter of points — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Plotting a scatter of points

+

A simple example showing how to plot a scatter of points with matplotlib.

+plot scatter
import numpy as np
+
import matplotlib.pyplot as plt +
+
n = 1024 +
rng = np.random.default_rng() +
X = rng.normal(0, 1, n) +
Y = rng.normal(0, 1, n) +
T = np.arctan2(Y, X) +
+
plt.axes((0.025, 0.025, 0.95, 0.95)) +
plt.scatter(X, Y, s=75, c=T, alpha=0.5) +
+
plt.xlim(-1.5, 1.5) +
plt.xticks([]) +
plt.ylim(-1.5, 1.5) +
plt.yticks([]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.060 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_subplot-grid.html b/intro/matplotlib/auto_examples/plot_subplot-grid.html new file mode 100644 index 000000000..60b324ada --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_subplot-grid.html @@ -0,0 +1,248 @@ + + + + + + + + Subplot grid — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Subplot grid

+

An example showing the subplot grid in matplotlib.

+plot subplot grid
import matplotlib.pyplot as plt
+
+
plt.figure(figsize=(6, 4)) +
plt.subplot(2, 2, 1) +
plt.xticks([]) +
plt.yticks([]) +
plt.text(0.5, 0.5, "subplot(2,2,1)", ha="center", va="center", size=20, alpha=0.5) +
+
plt.subplot(2, 2, 2) +
plt.xticks([]) +
plt.yticks([]) +
plt.text(0.5, 0.5, "subplot(2,2,2)", ha="center", va="center", size=20, alpha=0.5) +
+
plt.subplot(2, 2, 3) +
plt.xticks([]) +
plt.yticks([]) +
+
plt.text(0.5, 0.5, "subplot(2,2,3)", ha="center", va="center", size=20, alpha=0.5) +
+
plt.subplot(2, 2, 4) +
plt.xticks([]) +
plt.yticks([]) +
plt.text(0.5, 0.5, "subplot(2,2,4)", ha="center", va="center", size=20, alpha=0.5) +
+
plt.tight_layout() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.072 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_subplot-horizontal.html b/intro/matplotlib/auto_examples/plot_subplot-horizontal.html new file mode 100644 index 000000000..d68dd8159 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_subplot-horizontal.html @@ -0,0 +1,237 @@ + + + + + + + + Horizontal arrangement of subplots — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Horizontal arrangement of subplots

+

An example showing horizontal arrangement of subplots with matplotlib.

+plot subplot horizontal
import matplotlib.pyplot as plt
+
+
plt.figure(figsize=(6, 4)) +
plt.subplot(2, 1, 1) +
plt.xticks([]) +
plt.yticks([]) +
plt.text(0.5, 0.5, "subplot(2,1,1)", ha="center", va="center", size=24, alpha=0.5) +
+
plt.subplot(2, 1, 2) +
plt.xticks([]) +
plt.yticks([]) +
plt.text(0.5, 0.5, "subplot(2,1,2)", ha="center", va="center", size=24, alpha=0.5) +
+
plt.tight_layout() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.050 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_subplot-vertical.html b/intro/matplotlib/auto_examples/plot_subplot-vertical.html new file mode 100644 index 000000000..0071387fd --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_subplot-vertical.html @@ -0,0 +1,238 @@ + + + + + + + + Subplot plot arrangement vertical — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Subplot plot arrangement vertical

+

An example showing vertical arrangement of subplots with matplotlib.

+plot subplot vertical
import matplotlib.pyplot as plt
+
+
+
plt.figure(figsize=(6, 4)) +
plt.subplot(1, 2, 1) +
plt.xticks([]) +
plt.yticks([]) +
plt.text(0.5, 0.5, "subplot(1,2,1)", ha="center", va="center", size=24, alpha=0.5) +
+
plt.subplot(1, 2, 2) +
plt.xticks([]) +
plt.yticks([]) +
plt.text(0.5, 0.5, "subplot(1,2,2)", ha="center", va="center", size=24, alpha=0.5) +
+
plt.tight_layout() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.041 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_text.html b/intro/matplotlib/auto_examples/plot_text.html new file mode 100644 index 000000000..4627ddfea --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_text.html @@ -0,0 +1,263 @@ + + + + + + + + Demo text printing — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Demo text printing

+

A example showing off elaborate text printing with matplotlib.

+plot text
import numpy as np
+
import matplotlib.pyplot as plt +
+
+
eqs = [] +
eqs.append( +
r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$" +
) +
eqs.append( +
r"$\frac{d\rho}{d t} + \rho \vec{v}\cdot\nabla\vec{v} = -\nabla p + \mu\nabla^2 \vec{v} + \rho \vec{g}$" +
) +
eqs.append(r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$") +
eqs.append(r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$") +
eqs.append(r"$F_G = G\frac{m_1m_2}{r^2}$") +
+
plt.axes((0.025, 0.025, 0.95, 0.95)) +
+
rng = np.random.default_rng() +
+
for i in range(24): +
index = rng.integers(0, len(eqs)) +
eq = eqs[index] +
size = np.random.uniform(12, 32) +
x, y = np.random.uniform(0, 1, 2) +
alpha = np.random.uniform(0.25, 0.75) +
plt.text( +
x, +
y, +
eq, +
ha="center", +
va="center", +
color="#11557c", +
alpha=alpha, +
transform=plt.gca().transAxes, +
fontsize=size, +
clip_on=True, +
) +
plt.xticks([]) +
plt.yticks([]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.730 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_ugly.html b/intro/matplotlib/auto_examples/plot_ugly.html new file mode 100644 index 000000000..f4d0d2855 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_ugly.html @@ -0,0 +1,242 @@ + + + + + + + + A example of plotting not quite right — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

A example of plotting not quite right

+

An “ugly” example of plotting.

+plot ugly
import numpy as np
+
import matplotlib +
+
matplotlib.use("Agg") +
import matplotlib.pyplot as plt +
+
matplotlib.rc("grid", color="black", linestyle="-", linewidth=1) +
+
fig = plt.figure(figsize=(5, 4), dpi=72) +
axes = fig.add_axes((0.01, 0.01, 0.98, 0.98), facecolor=".75") +
X = np.linspace(0, 2, 40) +
Y = np.sin(2 * np.pi * X) +
plt.plot(X, Y, lw=0.05, c="b", antialiased=False) +
+
plt.xticks([]) +
plt.yticks(np.arange(-1.0, 1.0, 0.2)) +
plt.grid() +
ax = plt.gca() +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.036 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/pretty_plots/index.html b/intro/matplotlib/auto_examples/pretty_plots/index.html new file mode 100644 index 000000000..fbeb15382 --- /dev/null +++ b/intro/matplotlib/auto_examples/pretty_plots/index.html @@ -0,0 +1,244 @@ + + + + + + + + Code generating the summary figures with a title — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Code generating the summary figures with a title

+
+

3D plotting vignette

+
3D plotting vignette
+
+

Plotting in polar, decorated

+
Plotting in polar, decorated
+
+

Plot example vignette

+
Plot example vignette
+
+

Multiple plots vignette

+
Multiple plots vignette
+
+

Boxplot with matplotlib

+
Boxplot with matplotlib
+
+

Plot scatter decorated

+
Plot scatter decorated
+
+

Pie chart vignette

+
Pie chart vignette
+
+

Imshow demo

+
Imshow demo
+
+

Bar plot advanced

+
Bar plot advanced
+
+

Plotting quiver decorated

+
Plotting quiver decorated
+
+

Display the contours of a function

+
Display the contours of a function
+
+

Grid elaborate

+
Grid elaborate
+
+

Text printing decorated

+
Text printing decorated
+
+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/pretty_plots/plot_bar_ext.html b/intro/matplotlib/auto_examples/pretty_plots/plot_bar_ext.html new file mode 100644 index 000000000..8c782cecc --- /dev/null +++ b/intro/matplotlib/auto_examples/pretty_plots/plot_bar_ext.html @@ -0,0 +1,278 @@ + + + + + + + + Bar plot advanced — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Bar plot advanced

+

An more elaborate bar plot example

+plot bar ext
import numpy as np
+
import matplotlib.pyplot as plt +
+
n = 16 +
X = np.arange(n) +
Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n) +
Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n) +
plt.bar(X, Y1, facecolor="#9999ff", edgecolor="white") +
plt.bar(X, -Y2, facecolor="#ff9999", edgecolor="white") +
plt.xlim(-0.5, n) +
plt.xticks([]) +
plt.ylim(-1, 1) +
plt.yticks([]) +
+
+
# Add a title and a box around it +
from matplotlib.patches import FancyBboxPatch +
+
ax = plt.gca() +
ax.add_patch( +
FancyBboxPatch( +
(-0.05, 0.87), +
width=0.66, +
height=0.165, +
clip_on=False, +
boxstyle="square,pad=0", +
zorder=3, +
facecolor="white", +
alpha=1.0, +
transform=plt.gca().transAxes, +
) +
) +
+
plt.text( +
-0.05, +
1.02, +
" Bar Plot: plt.bar(...)\n", +
horizontalalignment="left", +
verticalalignment="top", +
size="xx-large", +
transform=plt.gca().transAxes, +
) +
+
plt.text( +
-0.05, +
1.01, +
"\n\n Make a bar plot with rectangles ", +
horizontalalignment="left", +
verticalalignment="top", +
size="large", +
transform=plt.gca().transAxes, +
) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.051 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/pretty_plots/plot_boxplot_ext.html b/intro/matplotlib/auto_examples/pretty_plots/plot_boxplot_ext.html new file mode 100644 index 000000000..d4ce15160 --- /dev/null +++ b/intro/matplotlib/auto_examples/pretty_plots/plot_boxplot_ext.html @@ -0,0 +1,281 @@ + + + + + + + + Boxplot with matplotlib — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Boxplot with matplotlib

+

An example of doing box plots with matplotlib

+plot boxplot ext
import numpy as np
+
import matplotlib.pyplot as plt +
+
+
fig = plt.figure(figsize=(8, 5)) +
axes = plt.subplot(111) +
+
n = 5 +
Z = np.zeros((n, 4)) +
X = np.linspace(0, 2, n) +
rng = np.random.default_rng() +
Y = rng.random((n, 4)) +
plt.boxplot(Y) +
+
plt.xticks([]) +
plt.yticks([]) +
+
+
# Add a title and a box around it +
from matplotlib.patches import FancyBboxPatch +
+
ax = plt.gca() +
ax.add_patch( +
FancyBboxPatch( +
(-0.05, 0.87), +
width=0.66, +
height=0.165, +
clip_on=False, +
boxstyle="square,pad=0", +
zorder=3, +
facecolor="white", +
alpha=1.0, +
transform=plt.gca().transAxes, +
) +
) +
+
plt.text( +
-0.05, +
1.02, +
" Box Plot: plt.boxplot(...)\n ", +
horizontalalignment="left", +
verticalalignment="top", +
size="xx-large", +
transform=axes.transAxes, +
) +
+
plt.text( +
-0.04, +
0.98, +
"\n Make a box and whisker plot ", +
horizontalalignment="left", +
verticalalignment="top", +
size="large", +
transform=axes.transAxes, +
) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.044 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/pretty_plots/plot_contour_ext.html b/intro/matplotlib/auto_examples/pretty_plots/plot_contour_ext.html new file mode 100644 index 000000000..9ea8779df --- /dev/null +++ b/intro/matplotlib/auto_examples/pretty_plots/plot_contour_ext.html @@ -0,0 +1,291 @@ + + + + + + + + Display the contours of a function — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Display the contours of a function

+

An example demoing how to plot the contours of a function, with +additional layout tweaks.

+plot contour ext
/home/runner/work/scientific-python-lectures/scientific-python-lectures/intro/matplotlib/examples/pretty_plots/plot_contour_ext.py:24: UserWarning: The following kwargs were not used by contour: 'linewidth'
+
C = plt.contour(X, Y, f(X, Y), 8, colors="black", linewidth=0.5) +
+
+
+

+
+
import numpy as np
+
import matplotlib.pyplot as plt +
+
+
def f(x, y): +
return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2) +
+
+
n = 256 +
x = np.linspace(-3, 3, n) +
y = np.linspace(-3, 3, n) +
X, Y = np.meshgrid(x, y) +
+
plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap="hot") +
C = plt.contour(X, Y, f(X, Y), 8, colors="black", linewidth=0.5) +
plt.clabel(C, inline=1, fontsize=10) +
plt.xticks([]) +
plt.yticks([]) +
+
+
# Add a title and a box around it +
from matplotlib.patches import FancyBboxPatch +
+
ax = plt.gca() +
ax.add_patch( +
FancyBboxPatch( +
(-0.05, 0.87), +
width=0.66, +
height=0.165, +
clip_on=False, +
boxstyle="square,pad=0", +
zorder=3, +
facecolor="white", +
alpha=1.0, +
transform=plt.gca().transAxes, +
) +
) +
+
plt.text( +
-0.05, +
1.02, +
" Contour Plot: plt.contour(..)\n", +
horizontalalignment="left", +
verticalalignment="top", +
size="xx-large", +
transform=plt.gca().transAxes, +
) +
+
plt.text( +
-0.05, +
1.01, +
"\n\n Draw contour lines and filled contours ", +
horizontalalignment="left", +
verticalalignment="top", +
size="large", +
transform=plt.gca().transAxes, +
) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.080 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/pretty_plots/plot_grid_ext.html b/intro/matplotlib/auto_examples/pretty_plots/plot_grid_ext.html new file mode 100644 index 000000000..6df85ff6b --- /dev/null +++ b/intro/matplotlib/auto_examples/pretty_plots/plot_grid_ext.html @@ -0,0 +1,287 @@ + + + + + + + + Grid elaborate — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Grid elaborate

+

An example displaying a grid on the axes and tweaking the layout.

+plot grid ext
Text(-0.05, 1.01, '\n\n    Draw ticks and grid ')
+
+
+
+

+
+
import matplotlib.pyplot as plt
+
from matplotlib.ticker import MultipleLocator +
+
fig = plt.figure(figsize=(8, 6), dpi=72, facecolor="white") +
axes = plt.subplot(111) +
axes.set_xlim(0, 4) +
axes.set_ylim(0, 3) +
+
axes.xaxis.set_major_locator(MultipleLocator(1.0)) +
axes.xaxis.set_minor_locator(MultipleLocator(0.1)) +
axes.yaxis.set_major_locator(MultipleLocator(1.0)) +
axes.yaxis.set_minor_locator(MultipleLocator(0.1)) +
axes.grid(which="major", axis="x", linewidth=0.75, linestyle="-", color="0.75") +
axes.grid(which="minor", axis="x", linewidth=0.25, linestyle="-", color="0.75") +
axes.grid(which="major", axis="y", linewidth=0.75, linestyle="-", color="0.75") +
axes.grid(which="minor", axis="y", linewidth=0.25, linestyle="-", color="0.75") +
axes.set_xticklabels([]) +
axes.set_yticklabels([]) +
+
+
# Add a title and a box around it +
from matplotlib.patches import FancyBboxPatch +
+
ax = plt.gca() +
ax.add_patch( +
FancyBboxPatch( +
(-0.05, 0.87), +
width=0.66, +
height=0.165, +
clip_on=False, +
boxstyle="square,pad=0", +
zorder=3, +
facecolor="white", +
alpha=1.0, +
transform=plt.gca().transAxes, +
) +
) +
+
plt.text( +
-0.05, +
1.02, +
" Grid: plt.grid(...)\n", +
horizontalalignment="left", +
verticalalignment="top", +
size="xx-large", +
transform=axes.transAxes, +
) +
+
plt.text( +
-0.05, +
1.01, +
"\n\n Draw ticks and grid ", +
horizontalalignment="left", +
verticalalignment="top", +
size="large", +
transform=axes.transAxes, +
) +
+
+

Total running time of the script: (0 minutes 0.107 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/pretty_plots/plot_imshow_ext.html b/intro/matplotlib/auto_examples/pretty_plots/plot_imshow_ext.html new file mode 100644 index 000000000..e4e1d7d23 --- /dev/null +++ b/intro/matplotlib/auto_examples/pretty_plots/plot_imshow_ext.html @@ -0,0 +1,282 @@ + + + + + + + + Imshow demo — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Imshow demo

+

Demoing imshow

+plot imshow ext
import numpy as np
+
import matplotlib.pyplot as plt +
+
+
def f(x, y): +
return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2) +
+
+
n = 10 +
x = np.linspace(-3, 3, 8 * n) +
y = np.linspace(-3, 3, 6 * n) +
X, Y = np.meshgrid(x, y) +
Z = f(X, Y) +
plt.imshow(Z, interpolation="nearest", cmap="bone", origin="lower") +
plt.xticks([]) +
plt.yticks([]) +
+
+
# Add a title and a box around it +
from matplotlib.patches import FancyBboxPatch +
+
ax = plt.gca() +
ax.add_patch( +
FancyBboxPatch( +
(-0.05, 0.87), +
width=0.66, +
height=0.165, +
clip_on=False, +
boxstyle="square,pad=0", +
zorder=3, +
facecolor="white", +
alpha=1.0, +
transform=plt.gca().transAxes, +
) +
) +
+
plt.text( +
-0.05, +
1.02, +
" Imshow: plt.imshow(...)\n", +
horizontalalignment="left", +
verticalalignment="top", +
size="xx-large", +
transform=plt.gca().transAxes, +
) +
+
plt.text( +
-0.05, +
1.01, +
"\n\n Display an image to current axes ", +
horizontalalignment="left", +
verticalalignment="top", +
family="DejaVu Sans", +
size="large", +
transform=plt.gca().transAxes, +
) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.040 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/pretty_plots/plot_multiplot_ext.html b/intro/matplotlib/auto_examples/pretty_plots/plot_multiplot_ext.html new file mode 100644 index 000000000..db047c341 --- /dev/null +++ b/intro/matplotlib/auto_examples/pretty_plots/plot_multiplot_ext.html @@ -0,0 +1,277 @@ + + + + + + + + Multiple plots vignette — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Multiple plots vignette

+

Demo multiple plots and style the figure.

+plot multiplot ext
import matplotlib.pyplot as plt
+
+
ax = plt.subplot(2, 1, 1) +
ax.set_xticklabels([]) +
ax.set_yticklabels([]) +
+
+
# Add a title and a box around it +
from matplotlib.patches import FancyBboxPatch +
+
ax = plt.gca() +
ax.add_patch( +
FancyBboxPatch( +
(-0.05, 0.72), +
width=0.66, +
height=0.34, +
clip_on=False, +
boxstyle="square,pad=0", +
zorder=3, +
facecolor="white", +
alpha=1.0, +
transform=plt.gca().transAxes, +
) +
) +
+
plt.text( +
-0.05, +
1.02, +
" Multiplot: plt.subplot(...)\n", +
horizontalalignment="left", +
verticalalignment="top", +
size="xx-large", +
transform=ax.transAxes, +
) +
plt.text( +
-0.05, +
1.01, +
"\n\n Plot several plots at once ", +
horizontalalignment="left", +
verticalalignment="top", +
size="large", +
transform=ax.transAxes, +
) +
+
ax = plt.subplot(2, 2, 3) +
ax.set_xticklabels([]) +
ax.set_yticklabels([]) +
+
ax = plt.subplot(2, 2, 4) +
ax.set_xticklabels([]) +
ax.set_yticklabels([]) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.081 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/pretty_plots/plot_pie_ext.html b/intro/matplotlib/auto_examples/pretty_plots/plot_pie_ext.html new file mode 100644 index 000000000..b453d274c --- /dev/null +++ b/intro/matplotlib/auto_examples/pretty_plots/plot_pie_ext.html @@ -0,0 +1,281 @@ + + + + + + + + Pie chart vignette — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Pie chart vignette

+

Demo pie chart with matplotlib and style the figure.

+plot pie ext
import numpy as np
+
import matplotlib.pyplot as plt +
+
n = 20 +
X = np.ones(n) +
X[-1] *= 2 +
plt.pie(X, explode=X * 0.05, colors=[f"{i / float(n):f}" for i in range(n)]) +
+
fig = plt.gcf() +
w, h = fig.get_figwidth(), fig.get_figheight() +
r = h / float(w) +
+
plt.xlim(-1.5, 1.5) +
plt.ylim(-1.5 * r, 1.5 * r) +
plt.xticks([]) +
plt.yticks([]) +
+
+
# Add a title and a box around it +
from matplotlib.patches import FancyBboxPatch +
+
ax = plt.gca() +
ax.add_patch( +
FancyBboxPatch( +
(-0.05, 0.87), +
width=0.66, +
height=0.165, +
clip_on=False, +
boxstyle="square,pad=0", +
zorder=3, +
facecolor="white", +
alpha=1.0, +
transform=plt.gca().transAxes, +
) +
) +
+
plt.text( +
-0.05, +
1.02, +
" Pie Chart: plt.pie(...)\n", +
horizontalalignment="left", +
verticalalignment="top", +
size="xx-large", +
transform=plt.gca().transAxes, +
) +
+
plt.text( +
-0.05, +
1.01, +
"\n\n Make a pie chart of an array ", +
horizontalalignment="left", +
verticalalignment="top", +
size="large", +
transform=plt.gca().transAxes, +
) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.058 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/pretty_plots/plot_plot3d_ext.html b/intro/matplotlib/auto_examples/pretty_plots/plot_plot3d_ext.html new file mode 100644 index 000000000..ee1523663 --- /dev/null +++ b/intro/matplotlib/auto_examples/pretty_plots/plot_plot3d_ext.html @@ -0,0 +1,265 @@ + + + + + + + + 3D plotting vignette — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3D plotting vignette

+

Demo 3D plotting with matplotlib and decorate the figure.

+plot plot3d ext
import numpy as np
+
import matplotlib.pyplot as plt +
from mpl_toolkits.mplot3d import Axes3D +
+
fig = plt.figure() +
ax = Axes3D(fig) +
X = np.arange(-4, 4, 0.25) +
Y = np.arange(-4, 4, 0.25) +
X, Y = np.meshgrid(X, Y) +
R = np.sqrt(X**2 + Y**2) +
Z = np.sin(R) +
+
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap="hot") +
ax.contourf(X, Y, Z, zdir="z", offset=-2, cmap="hot") +
ax.set_zlim(-2, 2) +
plt.xticks([]) +
plt.yticks([]) +
ax.set_zticks([]) +
+
ax.text2D( +
0.05, +
0.93, +
" 3D plots \n", +
horizontalalignment="left", +
verticalalignment="top", +
size="xx-large", +
bbox={"facecolor": "white", "alpha": 1.0}, +
transform=plt.gca().transAxes, +
) +
+
ax.text2D( +
0.05, +
0.87, +
" Plot 2D or 3D data", +
horizontalalignment="left", +
verticalalignment="top", +
size="large", +
transform=plt.gca().transAxes, +
) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.038 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/pretty_plots/plot_plot_ext.html b/intro/matplotlib/auto_examples/pretty_plots/plot_plot_ext.html new file mode 100644 index 000000000..3232f6563 --- /dev/null +++ b/intro/matplotlib/auto_examples/pretty_plots/plot_plot_ext.html @@ -0,0 +1,277 @@ + + + + + + + + Plot example vignette — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Plot example vignette

+

An example of plots with matplotlib, and added annotations.

+plot plot ext
import numpy as np
+
import matplotlib.pyplot as plt +
+
n = 256 +
X = np.linspace(0, 2, n) +
Y = np.sin(2 * np.pi * X) +
+
plt.plot(X, Y, lw=2, color="violet") +
plt.xlim(-0.2, 2.2) +
plt.xticks([]) +
plt.ylim(-1.2, 1.2) +
plt.yticks([]) +
+
+
# Add a title and a box around it +
from matplotlib.patches import FancyBboxPatch +
+
ax = plt.gca() +
ax.add_patch( +
FancyBboxPatch( +
(-0.05, 0.87), +
width=0.66, +
height=0.165, +
clip_on=False, +
boxstyle="square,pad=0", +
zorder=3, +
facecolor="white", +
alpha=1.0, +
transform=plt.gca().transAxes, +
) +
) +
+
plt.text( +
-0.05, +
1.02, +
" Regular Plot: plt.plot(...)\n", +
horizontalalignment="left", +
verticalalignment="top", +
size="xx-large", +
transform=plt.gca().transAxes, +
) +
+
plt.text( +
-0.05, +
1.01, +
"\n\n Plot lines and/or markers ", +
horizontalalignment="left", +
verticalalignment="top", +
size="large", +
transform=plt.gca().transAxes, +
) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.031 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/pretty_plots/plot_polar_ext.html b/intro/matplotlib/auto_examples/pretty_plots/plot_polar_ext.html new file mode 100644 index 000000000..f52cd3a61 --- /dev/null +++ b/intro/matplotlib/auto_examples/pretty_plots/plot_polar_ext.html @@ -0,0 +1,270 @@ + + + + + + + + Plotting in polar, decorated — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Plotting in polar, decorated

+

An example showing how to plot in polar coordinate, and some +decorations.

+plot polar ext
import numpy as np
+
+
import matplotlib +
import matplotlib.pyplot as plt +
+
+
plt.subplot(1, 1, 1, polar=True) +
+
N = 20 +
theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N) +
rng = np.random.default_rng() +
radii = 10 * rng.random(N) +
width = np.pi / 4 * rng.random(N) +
bars = plt.bar(theta, radii, width=width, bottom=0.0) +
jet = matplotlib.colormaps["jet"] +
+
for r, bar in zip(radii, bars, strict=True): +
bar.set_facecolor(jet(r / 10.0)) +
bar.set_alpha(0.5) +
plt.gca().set_xticklabels([]) +
plt.gca().set_yticklabels([]) +
+
+
plt.text( +
-0.2, +
1.02, +
" Polar Axis \n", +
horizontalalignment="left", +
verticalalignment="top", +
size="xx-large", +
bbox={"facecolor": "white", "alpha": 1.0}, +
transform=plt.gca().transAxes, +
) +
+
plt.text( +
-0.2, +
1.01, +
"\n\n Plot anything using polar axis ", +
horizontalalignment="left", +
verticalalignment="top", +
size="large", +
transform=plt.gca().transAxes, +
) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.110 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/pretty_plots/plot_quiver_ext.html b/intro/matplotlib/auto_examples/pretty_plots/plot_quiver_ext.html new file mode 100644 index 000000000..5a61f86b4 --- /dev/null +++ b/intro/matplotlib/auto_examples/pretty_plots/plot_quiver_ext.html @@ -0,0 +1,282 @@ + + + + + + + + Plotting quiver decorated — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Plotting quiver decorated

+

An example showing quiver with decorations.

+plot quiver ext
import numpy as np
+
import matplotlib.pyplot as plt +
+
n = 8 +
X, Y = np.mgrid[0:n, 0:n] +
T = np.arctan2(Y - n / 2.0, X - n / 2.0) +
R = 10 + np.sqrt((Y - n / 2.0) ** 2 + (X - n / 2.0) ** 2) +
U, V = R * np.cos(T), R * np.sin(T) +
+
plt.quiver(X, Y, U, V, R, alpha=0.5) +
plt.quiver(X, Y, U, V, edgecolor="k", facecolor="None", linewidth=0.5) +
+
plt.xlim(-1, n) +
plt.xticks([]) +
plt.ylim(-1, n) +
plt.yticks([]) +
+
+
# Add a title and a box around it +
from matplotlib.patches import FancyBboxPatch +
+
ax = plt.gca() +
ax.add_patch( +
FancyBboxPatch( +
(-0.05, 0.87), +
width=0.66, +
height=0.165, +
clip_on=False, +
boxstyle="square,pad=0", +
zorder=3, +
facecolor="white", +
alpha=1.0, +
transform=plt.gca().transAxes, +
) +
) +
+
plt.text( +
-0.05, +
1.02, +
" Quiver Plot: plt.quiver(...)\n", +
horizontalalignment="left", +
verticalalignment="top", +
size="xx-large", +
transform=plt.gca().transAxes, +
) +
+
plt.text( +
-0.05, +
1.01, +
"\n\n Plot a 2-D field of arrows ", +
horizontalalignment="left", +
verticalalignment="top", +
size="large", +
transform=plt.gca().transAxes, +
) +
+
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.051 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/pretty_plots/plot_scatter_ext.html b/intro/matplotlib/auto_examples/pretty_plots/plot_scatter_ext.html new file mode 100644 index 000000000..d9a6681b1 --- /dev/null +++ b/intro/matplotlib/auto_examples/pretty_plots/plot_scatter_ext.html @@ -0,0 +1,280 @@ + + + + + + + + Plot scatter decorated — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Plot scatter decorated

+

An example showing the scatter function, with decorations.

+plot scatter ext
import numpy as np
+
import matplotlib.pyplot as plt +
+
n = 1024 +
rng = np.random.default_rng() +
X = rng.normal(0, 1, n) +
Y = rng.normal(0, 1, n) +
+
T = np.arctan2(Y, X) +
+
plt.scatter(X, Y, s=75, c=T, alpha=0.5) +
plt.xlim(-1.5, 1.5) +
plt.xticks([]) +
plt.ylim(-1.5, 1.5) +
plt.yticks([]) +
+
+
# Add a title and a box around it +
from matplotlib.patches import FancyBboxPatch +
+
ax = plt.gca() +
ax.add_patch( +
FancyBboxPatch( +
(-0.05, 0.87), +
width=0.66, +
height=0.165, +
clip_on=False, +
boxstyle="square,pad=0", +
zorder=3, +
facecolor="white", +
alpha=1.0, +
transform=plt.gca().transAxes, +
) +
) +
+
plt.text( +
-0.05, +
1.02, +
" Scatter Plot: plt.scatter(...)\n", +
horizontalalignment="left", +
verticalalignment="top", +
size="xx-large", +
transform=plt.gca().transAxes, +
) +
+
plt.text( +
-0.05, +
1.01, +
"\n\n Make a scatter plot of x versus y ", +
horizontalalignment="left", +
verticalalignment="top", +
size="large", +
transform=plt.gca().transAxes, +
) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.062 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/pretty_plots/plot_text_ext.html b/intro/matplotlib/auto_examples/pretty_plots/plot_text_ext.html new file mode 100644 index 000000000..5a089a879 --- /dev/null +++ b/intro/matplotlib/auto_examples/pretty_plots/plot_text_ext.html @@ -0,0 +1,303 @@ + + + + + + + + Text printing decorated — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Text printing decorated

+

An example showing text printing and decorating the resulting figure.

+plot text ext
import numpy as np
+
import matplotlib.pyplot as plt +
+
fig = plt.figure() +
plt.xticks([]) +
plt.yticks([]) +
+
eqs = [] +
eqs.append( +
r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$" +
) +
eqs.append( +
r"$\frac{d\rho}{d t} + \rho \vec{v}\cdot\nabla\vec{v} = -\nabla p + \mu\nabla^2 \vec{v} + \rho \vec{g}$" +
) +
eqs.append(r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$") +
eqs.append(r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$") +
eqs.append(r"$F_G = G\frac{m_1m_2}{r^2}$") +
+
rng = np.random.default_rng() +
+
for i in range(24): +
index = rng.integers(0, len(eqs)) +
eq = eqs[index] +
size = rng.uniform(12, 32) +
x, y = rng.uniform(0, 1, 2) +
alpha = rng.uniform(0.25, 0.75) +
plt.text( +
x, +
y, +
eq, +
ha="center", +
va="center", +
color="#11557c", +
alpha=alpha, +
transform=plt.gca().transAxes, +
fontsize=size, +
clip_on=True, +
) +
+
+
# Add a title and a box around it +
from matplotlib.patches import FancyBboxPatch +
+
ax = plt.gca() +
ax.add_patch( +
FancyBboxPatch( +
(-0.05, 0.87), +
width=0.66, +
height=0.165, +
clip_on=False, +
boxstyle="square,pad=0", +
zorder=3, +
facecolor="white", +
alpha=1.0, +
transform=plt.gca().transAxes, +
) +
) +
+
plt.text( +
-0.05, +
1.02, +
" Text: plt.text(...)\n", +
horizontalalignment="left", +
verticalalignment="top", +
size="xx-large", +
transform=plt.gca().transAxes, +
) +
+
plt.text( +
-0.05, +
1.01, +
"\n\n Draw any kind of text ", +
horizontalalignment="left", +
verticalalignment="top", +
size="large", +
transform=plt.gca().transAxes, +
) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.714 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/pretty_plots/sg_execution_times.html b/intro/matplotlib/auto_examples/pretty_plots/sg_execution_times.html new file mode 100644 index 000000000..291696f1e --- /dev/null +++ b/intro/matplotlib/auto_examples/pretty_plots/sg_execution_times.html @@ -0,0 +1,254 @@ + + + + + + + + Computation times — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Computation times

+

00:01.467 total execution time for 13 files from intro/matplotlib/auto_examples/pretty_plots:

+
+ + + + + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Example

Time

Mem (MB)

Text printing decorated (plot_text_ext.py)

00:00.714

0.0

Plotting in polar, decorated (plot_polar_ext.py)

00:00.110

0.0

Grid elaborate (plot_grid_ext.py)

00:00.107

0.0

Multiple plots vignette (plot_multiplot_ext.py)

00:00.081

0.0

Display the contours of a function (plot_contour_ext.py)

00:00.080

0.0

Plot scatter decorated (plot_scatter_ext.py)

00:00.062

0.0

Pie chart vignette (plot_pie_ext.py)

00:00.058

0.0

Plotting quiver decorated (plot_quiver_ext.py)

00:00.051

0.0

Bar plot advanced (plot_bar_ext.py)

00:00.051

0.0

Boxplot with matplotlib (plot_boxplot_ext.py)

00:00.044

0.0

Imshow demo (plot_imshow_ext.py)

00:00.040

0.0

3D plotting vignette (plot_plot3d_ext.py)

00:00.038

0.0

Plot example vignette (plot_plot_ext.py)

00:00.031

0.0

+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/sg_execution_times.html b/intro/matplotlib/auto_examples/sg_execution_times.html new file mode 100644 index 000000000..048eead0b --- /dev/null +++ b/intro/matplotlib/auto_examples/sg_execution_times.html @@ -0,0 +1,290 @@ + + + + + + + + Computation times — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Computation times

+

00:02.112 total execution time for 22 files from intro/matplotlib/auto_examples:

+
+ + + + + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Example

Time

Mem (MB)

Demo text printing (plot_text.py)

00:00.730

0.0

Imshow elaborate (plot_imshow.py)

00:00.122

0.0

3D plotting (plot_plot3d.py)

00:00.106

0.0

Grid (plot_grid.py)

00:00.106

0.0

Plotting in polar coordinates (plot_polar.py)

00:00.096

0.0

A simple plotting example (plot_bad.py)

00:00.086

0.0

GridSpec (plot_gridspec.py)

00:00.086

0.0

Displaying the contours of a function (plot_contour.py)

00:00.079

0.0

Subplot grid (plot_subplot-grid.py)

00:00.072

0.0

Plotting a scatter of points (plot_scatter.py)

00:00.060

0.0

Pie chart (plot_pie.py)

00:00.059

0.0

Axes (plot_axes-2.py)

00:00.058

0.0

Bar plots (plot_bar.py)

00:00.056

0.0

A simple, good-looking plot (plot_good.py)

00:00.053

0.0

3D plotting (plot_plot3d-2.py)

00:00.053

0.0

Horizontal arrangement of subplots (plot_subplot-horizontal.py)

00:00.050

0.0

Subplots (plot_multiplot.py)

00:00.049

0.0

Simple axes example (plot_axes.py)

00:00.048

0.0

Subplot plot arrangement vertical (plot_subplot-vertical.py)

00:00.041

0.0

A example of plotting not quite right (plot_ugly.py)

00:00.036

0.0

Plotting a vector field: quiver (plot_quiver.py)

00:00.034

0.0

Plot and filled plots (plot_plot.py)

00:00.033

0.0

+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/matplotlib/index.html b/intro/matplotlib/index.html new file mode 100644 index 000000000..587a27b50 --- /dev/null +++ b/intro/matplotlib/index.html @@ -0,0 +1,1584 @@ + + + + + + + + 1.4. Matplotlib: plotting — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.4. Matplotlib: plotting

+ +

Authors: Nicolas Rougier, Mike Müller, Gaël Varoquaux

+ +
+

1.4.1. Introduction

+
+

Tip

+

Matplotlib is probably the most +used Python package for 2D-graphics. It provides both a quick +way to visualize data from Python and publication-quality figures in +many formats. We are going to explore matplotlib in interactive mode +covering most common cases.

+
+
+

1.4.1.1. IPython, Jupyter, and matplotlib modes

+
+

Tip

+

The Jupyter notebook and the +IPython enhanced interactive Python, are +tuned for the scientific-computing workflow in Python, +in combination with Matplotlib:

+
+

For interactive matplotlib sessions, turn on the matplotlib mode

+
+
IPython console:
+

When using the IPython console, use:

+
In [1]: %matplotlib
+
+
+
+
Jupyter notebook:
+

In the notebook, insert, at the beginning of the +notebook the following magic:

+
%matplotlib inline
+
+
+
+
+
+
+

1.4.1.2. pyplot

+
+

Tip

+

pyplot provides a procedural interface to the matplotlib object-oriented +plotting library. It is modeled closely after Matlab™. Therefore, the +majority of plotting commands in pyplot have Matlab™ analogs with similar +arguments. Important commands are explained with interactive examples.

+
+
import matplotlib.pyplot as plt
+
+
+
+
+
+

1.4.2. Simple plot

+
+

Tip

+

In this section, we want to draw the cosine and sine functions on the same +plot. Starting from the default settings, we’ll enrich the figure step by +step to make it nicer.

+

First step is to get the data for the sine and cosine functions:

+
+
import numpy as np
+
+
X = np.linspace(-np.pi, np.pi, 256) +
C, S = np.cos(X), np.sin(X) +
+
+

X is now a numpy array with 256 values ranging from -\pi to +\pi +(included). C is the cosine (256 values) and S is the sine (256 +values).

+

To run the example, you can type them in an IPython interactive session:

+
$ ipython --matplotlib
+
+
+

This brings us to the IPython prompt:

+
IPython 0.13 -- An enhanced Interactive Python.
+
? -> Introduction to IPython's features. +
%magic -> Information about IPython's 'magic' % functions. +
help -> Python's own help system. +
object? -> Details about 'object'. ?object also works, ?? prints more. +
+
+
+

Tip

+

You can also download each of the examples and run it using regular +python, but you will lose interactive data manipulation:

+
$ python plot_exercise_1.py
+
+
+

You can get source for each step by clicking on the corresponding figure.

+
+
+

1.4.2.1. Plotting with default settings

+../../_images/sphx_glr_plot_exercise_1_001.png + +
+

Hint

+

Documentation

+ +
+
+

Tip

+

Matplotlib comes with a set of default settings that allow +customizing all kinds of properties. You can control the defaults of +almost every property in matplotlib: figure size and dpi, line width, +color and style, axes, axis and grid properties, text and font +properties and so on.

+
+

+
import numpy as np
+
import matplotlib.pyplot as plt +
+
X = np.linspace(-np.pi, np.pi, 256) +
C, S = np.cos(X), np.sin(X) +
+
plt.plot(X, C) +
plt.plot(X, S) +
+
plt.show() +
+
+
+
+

1.4.2.2. Instantiating defaults

+../../_images/sphx_glr_plot_exercise_2_001.png + +
+

Hint

+

Documentation

+ +
+

In the script below, we’ve instantiated (and commented) all the figure settings +that influence the appearance of the plot.

+
+

Tip

+

The settings have been explicitly set to their default values, but +now you can interactively play with the values to explore their +affect (see Line properties and Line styles below).

+
+

+
import numpy as np
+
import matplotlib.pyplot as plt +
+
# Create a figure of size 8x6 inches, 80 dots per inch +
plt.figure(figsize=(8, 6), dpi=80) +
+
# Create a new subplot from a grid of 1x1 +
plt.subplot(1, 1, 1) +
+
X = np.linspace(-np.pi, np.pi, 256) +
C, S = np.cos(X), np.sin(X) +
+
# Plot cosine with a blue continuous line of width 1 (pixels) +
plt.plot(X, C, color="blue", linewidth=1.0, linestyle="-") +
+
# Plot sine with a green continuous line of width 1 (pixels) +
plt.plot(X, S, color="green", linewidth=1.0, linestyle="-") +
+
# Set x limits +
plt.xlim(-4.0, 4.0) +
+
# Set x ticks +
plt.xticks(np.linspace(-4, 4, 9)) +
+
# Set y limits +
plt.ylim(-1.0, 1.0) +
+
# Set y ticks +
plt.yticks(np.linspace(-1, 1, 5)) +
+
# Save figure using 72 dots per inch +
# plt.savefig("exercise_2.png", dpi=72) +
+
# Show result on screen +
plt.show() +
+
+
+
+

1.4.2.3. Changing colors and line widths

+../../_images/sphx_glr_plot_exercise_3_001.png + +
+

Hint

+

Documentation

+ +
+
+

Tip

+

First step, we want to have the cosine in blue and the sine in red and a +slightly thicker line for both of them. We’ll also slightly alter the figure +size to make it more horizontal.

+
+

+
...
+
plt.figure(figsize=(10, 6), dpi=80) +
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") +
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") +
... +
+
+
+
+

1.4.2.4. Setting limits

+../../_images/sphx_glr_plot_exercise_4_001.png + +
+

Hint

+

Documentation

+ +
+
+

Tip

+

Current limits of the figure are a bit too tight and we want to make +some space in order to clearly see all data points.

+
+

+
...
+
plt.xlim(X.min() * 1.1, X.max() * 1.1) +
plt.ylim(C.min() * 1.1, C.max() * 1.1) +
... +
+
+
+
+

1.4.2.5. Setting ticks

+../../_images/sphx_glr_plot_exercise_5_001.png + +
+

Hint

+

Documentation

+ +
+
+

Tip

+

Current ticks are not ideal because they do not show the interesting values +(\pm \pi,:math:pm pi/2) for sine and cosine. We’ll change them such that they show +only these values.

+
+

+
...
+
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi]) +
plt.yticks([-1, 0, +1]) +
... +
+
+
+
+

1.4.2.6. Setting tick labels

+../../_images/sphx_glr_plot_exercise_6_001.png + +
+

Hint

+

Documentation

+ +
+
+

Tip

+

Ticks are now properly placed but their label is not very explicit. +We could guess that 3.142 is \pi but it would be better to make it +explicit. When we set tick values, we can also provide a +corresponding label in the second argument list. Note that we’ll use +latex to allow for nice rendering of the label.

+
+

+
...
+
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], +
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) +
+
plt.yticks([-1, 0, +1], +
[r'$-1$', r'$0$', r'$+1$']) +
... +
+
+
+
+

1.4.2.7. Moving spines

+../../_images/sphx_glr_plot_exercise_7_001.png + +
+

Hint

+

Documentation

+ +
+
+

Tip

+

Spines are the lines connecting the axis tick marks and noting the +boundaries of the data area. They can be placed at arbitrary +positions and until now, they were on the border of the axis. We’ll +change that since we want to have them in the middle. Since there are +four of them (top/bottom/left/right), we’ll discard the top and right +by setting their color to none and we’ll move the bottom and left +ones to coordinate 0 in data space coordinates.

+
+

+
...
+
ax = plt.gca() # gca stands for 'get current axis' +
ax.spines['right'].set_color('none') +
ax.spines['top'].set_color('none') +
ax.xaxis.set_ticks_position('bottom') +
ax.spines['bottom'].set_position(('data',0)) +
ax.yaxis.set_ticks_position('left') +
ax.spines['left'].set_position(('data',0)) +
... +
+
+
+
+

1.4.2.8. Adding a legend

+../../_images/sphx_glr_plot_exercise_8_001.png + +
+

Hint

+

Documentation

+ +
+
+

Tip

+

Let’s add a legend in the upper left corner. This only requires +adding the keyword argument label (that will be used in the legend +box) to the plot commands.

+
+

+
...
+
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine") +
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine") +
+
plt.legend(loc='upper left') +
... +
+
+
+
+

1.4.2.9. Annotate some points

+../../_images/sphx_glr_plot_exercise_9_001.png + +
+

Hint

+

Documentation

+ +
+
+

Tip

+

Let’s annotate some interesting points using the annotate command. We +chose the 2\pi / 3 value and we want to annotate both the sine and the +cosine. We’ll first draw a marker on the curve as well as a straight +dotted line. Then, we’ll use the annotate command to display some +text with an arrow.

+
+

+
...
+
+
t = 2 * np.pi / 3 +
plt.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5, linestyle="--") +
plt.scatter([t, ], [np.cos(t), ], 50, color='blue') +
+
plt.annotate(r'$cos(\frac{2\pi}{3})=-\frac{1}{2}$', +
xy=(t, np.cos(t)), xycoords='data', +
xytext=(-90, -50), textcoords='offset points', fontsize=16, +
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) +
+
plt.plot([t, t],[0, np.sin(t)], color='red', linewidth=2.5, linestyle="--") +
plt.scatter([t, ],[np.sin(t), ], 50, color='red') +
+
plt.annotate(r'$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$', +
xy=(t, np.sin(t)), xycoords='data', +
xytext=(+10, +30), textcoords='offset points', fontsize=16, +
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) +
... +
+
+
+
+

1.4.2.10. Devil is in the details

+../../_images/sphx_glr_plot_exercise_10_001.png + +
+

Hint

+

Documentation

+ +
+
+

Tip

+

The tick labels are now hardly visible because of the blue and red +lines. We can make them bigger and we can also adjust their +properties such that they’ll be rendered on a semi-transparent white +background. This will allow us to see both the data and the labels.

+
+

+
...
+
for label in ax.get_xticklabels() + ax.get_yticklabels(): +
label.set_fontsize(16) +
label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65)) +
... +
+
+
+
+
+

1.4.3. Figures, Subplots, Axes and Ticks

+

A “figure” in matplotlib means the whole window in the user interface. +Within this figure there can be “subplots”.

+
+

Tip

+

So far we have used implicit figure and axes creation. This is handy for +fast plots. We can have more control over the display using figure, +subplot, and axes explicitly. While subplot positions the plots in a +regular grid, axes allows free placement within the figure. Both can be +useful depending on your intention. We’ve already worked with figures and +subplots without explicitly calling them. When we call plot, matplotlib +calls gca() to get the current axes and gca in turn calls gcf() to +get the current figure. If there is none it calls figure() to make one, +strictly speaking, to make a subplot(111). Let’s look at the details.

+
+
+

1.4.3.1. Figures

+
+

Tip

+

A figure is the windows in the GUI that has “Figure #” as title. Figures +are numbered starting from 1 as opposed to the normal Python way starting +from 0. This is clearly MATLAB-style. There are several parameters that +determine what the figure looks like:

+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Argument

Default

Description

num

1

number of figure

figsize

figure.figsize

figure size in inches (width, height)

dpi

figure.dpi

resolution in dots per inch

facecolor

figure.facecolor

color of the drawing background

edgecolor

figure.edgecolor

color of edge around the drawing background

frameon

True

draw figure frame or not

+
+

Tip

+

The defaults can be specified in the resource file and will be used most of +the time. Only the number of the figure is frequently changed.

+

As with other objects, you can set figure properties also setp or with the +set_something methods.

+

When you work with the GUI you can close a figure by clicking on the x in +the upper right corner. But you can close a figure programmatically by +calling close. Depending on the argument it closes (1) the current figure +(no argument), (2) a specific figure (figure number or figure instance as +argument), or (3) all figures ("all" as argument).

+
+
plt.close(1)     # Closes figure 1
+
+
+
+
+

1.4.3.2. Subplots

+
+

Tip

+

With subplot you can arrange plots in a regular grid. You need to specify +the number of rows and columns and the number of the plot. Note that the +gridspec command +is a more powerful alternative.

+
+

+../../_images/sphx_glr_plot_subplot-horizontal_001.png + +../../_images/sphx_glr_plot_subplot-vertical_001.png + +../../_images/sphx_glr_plot_subplot-grid_001.png + +../../_images/sphx_glr_plot_gridspec_001.png + +
+
+

1.4.3.3. Axes

+

Axes are very similar to subplots but allow placement of plots at any location +in the figure. So if we want to put a smaller plot inside a bigger one we do +so with axes.

+../../_images/sphx_glr_plot_axes_001.png + +../../_images/sphx_glr_plot_axes-2_001.png + +
+
+

1.4.3.4. Ticks

+

Well formatted ticks are an important part of publishing-ready +figures. Matplotlib provides a totally configurable system for ticks. There are +tick locators to specify where ticks should appear and tick formatters to give +ticks the appearance you want. Major and minor ticks can be located and +formatted independently from each other. Per default minor ticks are not shown, +i.e. there is only an empty list for them because it is as NullLocator (see +below).

+
+

Tick Locators

+

Tick locators control the positions of the ticks. They are set as +follows:

+
ax = plt.gca()
+
ax.xaxis.set_major_locator(eval(locator)) +
+
+

There are several locators for different kind of requirements:

+../../_images/sphx_glr_plot_ticks_001.png + +

All of these locators derive from the base class matplotlib.ticker.Locator. +You can make your own locator deriving from it. Handling dates as ticks can be +especially tricky. Therefore, matplotlib provides special locators in +matplotlib.dates.

+
+
+
+
+

1.4.4. Other Types of Plots: examples and exercises

+../../_images/sphx_glr_plot_plot_ext_001.png + +../../_images/sphx_glr_plot_scatter_ext_001.png + +../../_images/sphx_glr_plot_bar_ext_001.png + +../../_images/sphx_glr_plot_contour_ext_001.png + +../../_images/sphx_glr_plot_imshow_ext_001.png + +../../_images/sphx_glr_plot_quiver_ext_001.png + +../../_images/sphx_glr_plot_pie_ext_001.png + +../../_images/sphx_glr_plot_grid_ext_001.png + +../../_images/sphx_glr_plot_multiplot_ext_001.png + +../../_images/sphx_glr_plot_polar_ext_001.png + +../../_images/sphx_glr_plot_plot3d_ext_001.png + +../../_images/sphx_glr_plot_text_ext_001.png + +
+

1.4.4.1. Regular Plots

+../../_images/sphx_glr_plot_plot_001.png + +

Starting from the code below, try to reproduce the graphic taking +care of filled areas:

+
+

Hint

+

You need to use the fill_between() command.

+
+
n = 256
+
X = np.linspace(-np.pi, np.pi, n) +
Y = np.sin(2 * X) +
+
plt.plot(X, Y + 1, color='blue', alpha=1.00) +
plt.plot(X, Y - 1, color='blue', alpha=1.00) +
+
+

Click on the figure for solution.

+
+
+

1.4.4.2. Scatter Plots

+../../_images/sphx_glr_plot_scatter_001.png + +

Starting from the code below, try to reproduce the graphic taking +care of marker size, color and transparency.

+
+

Hint

+

Color is given by angle of (X,Y).

+
+
n = 1024
+
rng = np.random.default_rng() +
X = rng.normal(0,1,n) +
Y = rng.normal(0,1,n) +
+
plt.scatter(X,Y) +
+
+

Click on figure for solution.

+
+
+

1.4.4.3. Bar Plots

+../../_images/sphx_glr_plot_bar_001.png + +

Starting from the code below, try to reproduce the graphic by +adding labels for red bars.

+
+

Hint

+

You need to take care of text alignment.

+
+

+
n = 12
+
X = np.arange(n) +
rng = np.random.default_rng() +
Y1 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n) +
Y2 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n) +
+
plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white') +
plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white') +
+
for x, y in zip(X, Y1): +
plt.text(x + 0.4, y + 0.05, '%.2f' % y, ha='center', va='bottom') +
+
plt.ylim(-1.25, +1.25) +
+
+

Click on figure for solution.

+
+
+

1.4.4.4. Contour Plots

+../../_images/sphx_glr_plot_contour_001.png + +

Starting from the code below, try to reproduce the graphic taking +care of the colormap (see Colormaps below).

+
+

Hint

+

You need to use the clabel() command.

+
+
def f(x, y):
+
return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 -y ** 2) +
+
n = 256 +
x = np.linspace(-3, 3, n) +
y = np.linspace(-3, 3, n) +
X, Y = np.meshgrid(x, y) +
+
plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap='jet') +
C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5) +
+
+

Click on figure for solution.

+
+
+

1.4.4.5. Imshow

+../../_images/sphx_glr_plot_imshow_001.png + +

Starting from the code below, try to reproduce the graphic taking +care of colormap, image interpolation and origin.

+
+

Hint

+

You need to take care of the origin of the image in the imshow command and +use a colorbar()

+
+
def f(x, y):
+
return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) +
+
n = 10 +
x = np.linspace(-3, 3, 4 * n) +
y = np.linspace(-3, 3, 3 * n) +
X, Y = np.meshgrid(x, y) +
plt.imshow(f(X, Y)) +
+
+

Click on the figure for the solution.

+
+
+

1.4.4.6. Pie Charts

+../../_images/sphx_glr_plot_pie_001.png + +

Starting from the code below, try to reproduce the graphic taking +care of colors and slices size.

+
+

Hint

+

You need to modify Z.

+
+
rng = np.random.default_rng()
+
Z = rng.uniform(0, 1, 20) +
plt.pie(Z) +
+
+

Click on the figure for the solution.

+
+
+

1.4.4.7. Quiver Plots

+../../_images/sphx_glr_plot_quiver_001.png + +

Starting from the code below, try to reproduce the graphic taking +care of colors and orientations.

+
+

Hint

+

You need to draw arrows twice.

+
+
n = 8
+
X, Y = np.mgrid[0:n, 0:n] +
plt.quiver(X, Y) +
+
+

Click on figure for solution.

+
+
+

1.4.4.8. Grids

+../../_images/sphx_glr_plot_grid_001.png + +

Starting from the code below, try to reproduce the graphic taking +care of line styles.

+
axes = plt.gca()
+
axes.set_xlim(0, 4) +
axes.set_ylim(0, 3) +
axes.set_xticklabels([]) +
axes.set_yticklabels([]) +
+
+

Click on figure for solution.

+
+
+

1.4.4.9. Multi Plots

+../../_images/sphx_glr_plot_multiplot_001.png + +

Starting from the code below, try to reproduce the graphic.

+
+

Hint

+

You can use several subplots with different partition.

+
+
plt.subplot(2, 2, 1)
+
plt.subplot(2, 2, 3) +
plt.subplot(2, 2, 4) +
+
+

Click on figure for solution.

+
+
+

1.4.4.10. Polar Axis

+../../_images/sphx_glr_plot_polar_001.png + +
+

Hint

+

You only need to modify the axes line

+
+

Starting from the code below, try to reproduce the graphic.

+
plt.axes([0, 0, 1, 1])
+
+
N = 20 +
theta = np.arange(0., 2 * np.pi, 2 * np.pi / N) +
rng = np.random.default_rng() +
radii = 10 * rng.random(N) +
width = np.pi / 4 * rng.random(N) +
bars = plt.bar(theta, radii, width=width, bottom=0.0) +
+
for r, bar in zip(radii, bars): +
bar.set_facecolor(plt.cm.jet(r / 10.)) +
bar.set_alpha(0.5) +
+
+

Click on figure for solution.

+
+
+

1.4.4.11. 3D Plots

+../../_images/sphx_glr_plot_plot3d_001.png + +

Starting from the code below, try to reproduce the graphic.

+
+

Hint

+

You need to use contourf()

+
+
from mpl_toolkits.mplot3d import Axes3D
+
+
fig = plt.figure() +
ax = Axes3D(fig) +
X = np.arange(-4, 4, 0.25) +
Y = np.arange(-4, 4, 0.25) +
X, Y = np.meshgrid(X, Y) +
R = np.sqrt(X**2 + Y**2) +
Z = np.sin(R) +
+
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot') +
+
+

Click on figure for solution.

+
+
+

1.4.4.12. Text

+../../_images/sphx_glr_plot_text_001.png + +

Try to do the same from scratch !

+
+

Hint

+

Have a look at the matplotlib logo.

+
+

Click on figure for solution.

+
+

+
+
+
+

+
+ +
+
+
+

1.4.5. Beyond this tutorial

+

Matplotlib benefits from extensive documentation as well as a large +community of users and developers. Here are some links of interest:

+
+

1.4.5.1. Tutorials

+
    +
  • Pyplot tutorial

    +
      +
    • Introduction

    • +
    • Controlling line properties

    • +
    • Working with multiple figures and axes

    • +
    • Working with text

    • +
    +
  • +
  • Image tutorial

    +
      +
    • Startup commands

    • +
    • Importing image data into NumPy arrays

    • +
    • Plotting NumPy arrays as images

    • +
    +
  • +
  • Text tutorial

    +
      +
    • Text introduction

    • +
    • Basic text commands

    • +
    • Text properties and layout

    • +
    • Writing mathematical expressions

    • +
    • Text rendering With LaTeX

    • +
    • Annotating text

    • +
    +
  • +
+
    +
  • Artist tutorial

    +
      +
    • Introduction

    • +
    • Customizing your objects

    • +
    • Object containers

    • +
    • Figure container

    • +
    • Axes container

    • +
    • Axis containers

    • +
    • Tick containers

    • +
    +
  • +
  • Path tutorial

    +
      +
    • Introduction

    • +
    • Bézier example

    • +
    • Compound paths

    • +
    +
  • +
  • Transforms tutorial

    +
      +
    • Introduction

    • +
    • Data coordinates

    • +
    • Axes coordinates

    • +
    • Blended transformations

    • +
    • Using offset transforms to create a shadow effect

    • +
    • The transformation pipeline

    • +
    +
  • +
+
+
+
+

1.4.5.2. Matplotlib documentation

+
    +
  • User guide

  • +
  • FAQ

    +
      +
    • Installation

    • +
    • Usage

    • +
    • How-To

    • +
    • Troubleshooting

    • +
    • Environment Variables

    • +
    +
  • +
+
+
+
+
+

1.4.5.3. Code documentation

+

The code is well documented and you can quickly access a specific command +from within a python session:

+
>>> import matplotlib.pyplot as plt
+
>>> help(plt.plot) +
Help on function plot in module matplotlib.pyplot: +
+
plot(*args: ...) -> 'list[Line2D]' +
Plot y versus x as lines and/or markers. +
+
Call signatures:: +
+
plot([x], y, [fmt], *, data=None, **kwargs) +
plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs) +
... +
+
+
+
+

1.4.5.4. Galleries

+

The matplotlib gallery is +also incredibly useful when you search how to render a given graphic. Each +example comes with its source.

+
+
+

1.4.5.5. Mailing lists

+

Finally, there is a user mailing list where you can +ask for help and a developers mailing list that is more +technical.

+
+
+
+

1.4.6. Quick references

+

Here is a set of tables that show main properties and styles.

+
+

1.4.6.1. Line properties

+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Property

Description

Appearance

alpha (or a)

alpha transparency on 0-1 scale

../../_images/sphx_glr_plot_alpha_001.png +

antialiased

True or False - use antialised rendering

../../_images/sphx_glr_plot_aliased_001.png +../../_images/sphx_glr_plot_antialiased_001.png +

color (or c)

matplotlib color arg

../../_images/sphx_glr_plot_color_001.png +

linestyle (or ls)

see Line properties

linewidth (or lw)

float, the line width in points

../../_images/sphx_glr_plot_linewidth_001.png +

solid_capstyle

Cap style for solid lines

../../_images/sphx_glr_plot_solid_capstyle_001.png +

solid_joinstyle

Join style for solid lines

../../_images/sphx_glr_plot_solid_joinstyle_001.png +

dash_capstyle

Cap style for dashes

../../_images/sphx_glr_plot_dash_capstyle_001.png +

dash_joinstyle

Join style for dashes

../../_images/sphx_glr_plot_dash_joinstyle_001.png +

marker

see Markers

markeredgewidth (mew)

line width around the marker symbol

../../_images/sphx_glr_plot_mew_001.png +

markeredgecolor (mec)

edge color if a marker is used

../../_images/sphx_glr_plot_mec_001.png +

markerfacecolor (mfc)

face color if a marker is used

../../_images/sphx_glr_plot_mfc_001.png +

markersize (ms)

size of the marker in points

../../_images/sphx_glr_plot_ms_001.png +
+
+
+

1.4.6.2. Line styles

+../../_images/sphx_glr_plot_linestyles_001.png +
+
+

1.4.6.3. Markers

+../../_images/sphx_glr_plot_markers_001.png + +
+
+

1.4.6.4. Colormaps

+

All colormaps can be reversed by appending _r. For instance, gray_r is +the reverse of gray.

+

If you want to know more about colormaps, check the documentation on Colormaps in matplotlib.

+../../_images/sphx_glr_plot_colormaps_001.png + +
+
+
+

1.4.7. Full code examples

+
+

1.4.7.1. Code samples for Matplotlib

+

The examples here are only examples relevant to the points raised in this +chapter. The matplotlib documentation comes with a much more exhaustive +gallery.

+
+

Pie chart

+
Pie chart
+
+

A simple, good-looking plot

+
A simple, good-looking plot
+
+

Plotting a scatter of points

+
Plotting a scatter of points
+
+

Subplots

+
Subplots
+
+

Horizontal arrangement of subplots

+
Horizontal arrangement of subplots
+
+

A simple plotting example

+
A simple plotting example
+
+

Subplot plot arrangement vertical

+
Subplot plot arrangement vertical
+
+

Simple axes example

+
Simple axes example
+
+

3D plotting

+
3D plotting
+
+

Imshow elaborate

+
Imshow elaborate
+
+

Plotting a vector field: quiver

+
Plotting a vector field: quiver
+
+

Displaying the contours of a function

+
Displaying the contours of a function
+
+

A example of plotting not quite right

+
A example of plotting not quite right
+
+

Plot and filled plots

+
Plot and filled plots
+
+

Plotting in polar coordinates

+
Plotting in polar coordinates
+
+

Subplot grid

+
Subplot grid
+
+

Bar plots

+
Bar plots
+
+

Axes

+
Axes
+
+

Grid

+
Grid
+
+

3D plotting

+
3D plotting
+
+

GridSpec

+
GridSpec
+
+

Demo text printing

+
Demo text printing
+
+
+
+
+

1.4.7.2. Code for the chapter’s exercises

+
+

Exercise 1

+
Exercise 1
+
+

Exercise 4

+
Exercise 4
+
+

Exercise 3

+
Exercise 3
+
+

Exercise 5

+
Exercise 5
+
+

Exercise 6

+
Exercise 6
+
+

Exercise 2

+
Exercise 2
+
+

Exercise 7

+
Exercise 7
+
+

Exercise 8

+
Exercise 8
+
+

Exercise 9

+
Exercise 9
+
+

Exercise

+
Exercise
+
+
+

1.4.7.3. Example demoing choices for an option

+
+

The colors matplotlib line plots

+
The colors matplotlib line plots
+
+

Linewidth

+
Linewidth
+
+

Alpha: transparency

+
Alpha: transparency
+
+

Aliased versus anti-aliased

+
Aliased versus anti-aliased
+
+

Aliased versus anti-aliased

+
Aliased versus anti-aliased
+
+

Marker size

+
Marker size
+
+

Marker edge width

+
Marker edge width
+
+

Colormaps

+
Colormaps
+
+

Solid joint style

+
Solid joint style
+
+

Solid cap style

+
Solid cap style
+
+

Marker edge color

+
Marker edge color
+
+

Marker face color

+
Marker face color
+
+

Dash capstyle

+
Dash capstyle
+
+

Dash join style

+
Dash join style
+
+

Markers

+
Markers
+
+

Linestyles

+
Linestyles
+
+

Locators for tick on axis

+
Locators for tick on axis
+
+
+

1.4.7.4. Code generating the summary figures with a title

+
+

3D plotting vignette

+
3D plotting vignette
+
+

Plotting in polar, decorated

+
Plotting in polar, decorated
+
+

Plot example vignette

+
Plot example vignette
+
+

Multiple plots vignette

+
Multiple plots vignette
+
+

Boxplot with matplotlib

+
Boxplot with matplotlib
+
+

Plot scatter decorated

+
Plot scatter decorated
+
+

Pie chart vignette

+
Pie chart vignette
+
+

Imshow demo

+
Imshow demo
+
+

Bar plot advanced

+
Bar plot advanced
+
+

Plotting quiver decorated

+
Plotting quiver decorated
+
+

Display the contours of a function

+
Display the contours of a function
+
+

Grid elaborate

+
Grid elaborate
+
+

Text printing decorated

+
Text printing decorated
+
+
+ +

Gallery generated by Sphinx-Gallery

+

+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/numpy/advanced_operations.html b/intro/numpy/advanced_operations.html new file mode 100644 index 000000000..73c258b0c --- /dev/null +++ b/intro/numpy/advanced_operations.html @@ -0,0 +1,390 @@ + + + + + + + + 1.3.4. Advanced operations — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.3.4. Advanced operations

+ +
+

1.3.4.1. Polynomials

+

NumPy also contains polynomials in different bases:

+

For example, 3x^2 + 2x - 1:

+
>>> p = np.poly1d([3, 2, -1])
+
>>> p(0) +
np.int64(-1) +
>>> p.roots +
array([-1. , 0.33333333]) +
>>> p.order +
2 +
+
+
>>> x = np.linspace(0, 1, 20)
+
>>> rng = np.random.default_rng() +
>>> y = np.cos(x) + 0.3*rng.random(20) +
>>> p = np.poly1d(np.polyfit(x, y, 3)) +
+
>>> t = np.linspace(0, 1, 200) # use a larger number of points for smoother plotting +
>>> plt.plot(x, y, 'o', t, p(t), '-') +
[<matplotlib.lines.Line2D object at ...>, <matplotlib.lines.Line2D object at ...>] +
+
+../../_images/sphx_glr_plot_polyfit_001.png + +

See https://numpy.org/doc/stable/reference/routines.polynomials.poly1d.html +for more.

+
+

More polynomials (with more bases)

+

NumPy also has a more sophisticated polynomial interface, which supports +e.g. the Chebyshev basis.

+

3x^2 + 2x - 1:

+
>>> p = np.polynomial.Polynomial([-1, 2, 3]) # coefs in different order!
+
>>> p(0) +
np.float64(-1.0) +
>>> p.roots() +
array([-1. , 0.33333333]) +
>>> p.degree() # In general polynomials do not always expose 'order' +
2 +
+
+

Example using polynomials in Chebyshev basis, for polynomials in +range [-1, 1]:

+
>>> x = np.linspace(-1, 1, 2000)
+
>>> rng = np.random.default_rng() +
>>> y = np.cos(x) + 0.3*rng.random(2000) +
>>> p = np.polynomial.Chebyshev.fit(x, y, 90) +
+
>>> plt.plot(x, y, 'r.') +
[<matplotlib.lines.Line2D object at ...>] +
>>> plt.plot(x, p(x), 'k-', lw=3) +
[<matplotlib.lines.Line2D object at ...>] +
+
+../../_images/sphx_glr_plot_chebyfit_001.png + +

The Chebyshev polynomials have some advantages in interpolation.

+
+
+
+

1.3.4.2. Loading data files

+
+

Text files

+

Example: populations.txt:

+
# year  hare    lynx    carrot
+1900    30e3    4e3     48300
+1901    47.2e3  6.1e3   48200
+1902    70.2e3  9.8e3   41500
+1903    77.4e3  35.2e3  38200
+
+
>>> data = np.loadtxt('data/populations.txt')
+
>>> data +
array([[ 1900., 30000., 4000., 48300.], +
[ 1901., 47200., 6100., 48200.], +
[ 1902., 70200., 9800., 41500.], +
... +
+
+
>>> np.savetxt('pop2.txt', data)
+
>>> data2 = np.loadtxt('pop2.txt') +
+
+
+

Note

+

If you have a complicated text file, what you can try are:

+
    +
  • np.genfromtxt

  • +
  • Using Python’s I/O functions and e.g. regexps for parsing +(Python is quite well suited for this)

  • +
+
+ +
+
+

Images

+

Using Matplotlib:

+
>>> img = plt.imread('data/elephant.png')
+
>>> img.shape, img.dtype +
((200, 300, 3), dtype('float32')) +
>>> plt.imshow(img) +
<matplotlib.image.AxesImage object at ...> +
>>> plt.savefig('plot.png') +
+
>>> plt.imsave('red_elephant.png', img[:,:,0], cmap=plt.cm.gray) +
+
+../../_images/sphx_glr_plot_elephant_001.png + +

This saved only one channel (of RGB):

+
>>> plt.imshow(plt.imread('red_elephant.png'))
+
<matplotlib.image.AxesImage object at ...> +
+
+../../_images/sphx_glr_plot_elephant_002.png + +

Other libraries:

+
>>> import imageio.v3 as iio
+
>>> iio.imwrite('tiny_elephant.png', (img[::6,::6] * 255).astype(np.uint8)) +
>>> plt.imshow(plt.imread('tiny_elephant.png'), interpolation='nearest') +
<matplotlib.image.AxesImage object at ...> +
+
+../../_images/sphx_glr_plot_elephant_003.png + +
+
+

NumPy’s own format

+

NumPy has its own binary format, not portable but with efficient I/O:

+
>>> data = np.ones((3, 3))
+
>>> np.save('pop.npy', data) +
>>> data3 = np.load('pop.npy') +
+
+
+
+

Well-known (& more obscure) file formats

+
    +
  • HDF5: h5py, PyTables

  • +
  • NetCDF: scipy.io.netcdf_file, netcdf4-python, …

  • +
  • Matlab: scipy.io.loadmat, scipy.io.savemat

  • +
  • MatrixMarket: scipy.io.mmread, scipy.io.mmwrite

  • +
  • IDL: scipy.io.readsav

  • +
+

… if somebody uses it, there’s probably also a Python library for it.

+ + +

+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/numpy/array_object.html b/intro/numpy/array_object.html new file mode 100644 index 000000000..a331438bc --- /dev/null +++ b/intro/numpy/array_object.html @@ -0,0 +1,1027 @@ + + + + + + + + 1.3.1. The NumPy array object — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.3.1. The NumPy array object

+ +
+

1.3.1.1. What are NumPy and NumPy arrays?

+
+

NumPy arrays

+
+
Python objects:
+
    +
  • high-level number objects: integers, floating point

  • +
  • containers: lists (costless insertion and append), dictionaries +(fast lookup)

  • +
+
+
NumPy provides:
+
    +
  • extension package to Python for multi-dimensional arrays

  • +
  • closer to hardware (efficiency)

  • +
  • designed for scientific computation (convenience)

  • +
  • Also known as array oriented computing

  • +
+
+
+
+

+
+
>>> import numpy as np
+
>>> a = np.array([0, 1, 2, 3]) +
>>> a +
array([0, 1, 2, 3]) +
+
+
+

Tip

+

For example, An array containing:

+
    +
  • values of an experiment/simulation at discrete time steps

  • +
  • signal recorded by a measurement device, e.g. sound wave

  • +
  • pixels of an image, grey-level or colour

  • +
  • 3-D data measured at different X-Y-Z positions, e.g. MRI scan

  • +
  • +
+
+

Why it is useful: Memory-efficient container that provides fast numerical +operations.

+
In [1]: L = range(1000)
+
+
In [2]: %timeit [i**2 for i in L] +
50.3 us +- 873 ns per loop (mean +- std. dev. of 7 runs, 10,000 loops each) +
+
In [3]: a = np.arange(1000) +
+
In [4]: %timeit a**2 +
934 ns +- 2.77 ns per loop (mean +- std. dev. of 7 runs, 1,000,000 loops each) +
+
+
+
+

NumPy Reference documentation

+
    +
  • On the web: https://numpy.org/doc/

  • +
  • Interactive help:

    +
    In [5]: np.array?
    +
    Docstring: +
    array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0, +
    like=None) +
    +
    Create an array. +
    +
    Parameters +
    ---------- +
    object : array_like +
    An array, any object exposing the array interface, an object whose +
    ``__array__`` method returns an array, or any (nested) sequence. +
    If object is a scalar, a 0-dimensional array containing object is +
    returned. +
    dtype : data-type, optional +
    The desired data-type for the array. If not given, NumPy will try to use +
    a default ``dtype`` that can represent the values (by applying promotion +
    rules when necessary.) +
    copy : bool, optional +
    If ``True`` (default), then the array data is copied. If ``None``, +
    a copy will only be made if ``__array__`` returns a copy, if obj is +
    a nested sequence, or if a copy is needed to satisfy any of the other +
    requirements (``dtype``, ``order``, etc.). Note that any copy of +
    the data is shallow, i.e., for arrays with object dtype, the new +
    array will point to the same objects. See Examples for `ndarray.copy`. +
    For ``False`` it raises a ``ValueError`` if a copy cannot be avoided. +
    Default: ``True``. +
    order : {'K', 'A', 'C', 'F'}, optional +
    Specify the memory layout of the array. If object is not an array, the +
    newly created array will be in C order (row major) unless 'F' is +
    specified, in which case it will be in Fortran order (column major). +
    If object is an array the following holds. +
    +
    ===== ========= =================================================== +
    order no copy copy=True +
    ===== ========= =================================================== +
    'K' unchanged F & C order preserved, otherwise most similar order +
    'A' unchanged F order if input is F and not C, otherwise C order +
    'C' C order C order +
    'F' F order F order +
    ===== ========= =================================================== +
    +
    When ``copy=None`` and a copy is made for other reasons, the result is +
    the same as if ``copy=True``, with some exceptions for 'A', see the +
    Notes section. The default order is 'K'. +
    subok : bool, optional +
    If True, then sub-classes will be passed-through, otherwise +
    the returned array will be forced to be a base-class array (default). +
    ndmin : int, optional +
    Specifies the minimum number of dimensions that the resulting +
    array should have. Ones will be prepended to the shape as +
    needed to meet this requirement. +
    like : array_like, optional +
    Reference object to allow the creation of arrays which are not +
    NumPy arrays. If an array-like passed in as ``like`` supports +
    the ``__array_function__`` protocol, the result will be defined +
    by it. In this case, it ensures the creation of an array object +
    compatible with that passed in via this argument. +
    +
    .. versionadded:: 1.20.0 +
    +
    Returns +
    ------- +
    out : ndarray +
    An array object satisfying the specified requirements. +
    +
    See Also +
    -------- +
    empty_like : Return an empty array with shape and type of input. +
    ones_like : Return an array of ones with shape and type of input. +
    zeros_like : Return an array of zeros with shape and type of input. +
    full_like : Return a new array with shape of input filled with value. +
    empty : Return a new uninitialized array. +
    ones : Return a new array setting values to one. +
    zeros : Return a new array setting values to zero. +
    full : Return a new array of given shape filled with value. +
    copy: Return an array copy of the given object. +
    +
    +
    Notes +
    ----- +
    When order is 'A' and ``object`` is an array in neither 'C' nor 'F' order, +
    and a copy is forced by a change in dtype, then the order of the result is +
    not necessarily 'C' as expected. This is likely a bug. +
    +
    Examples +
    -------- +
    >>> import numpy as np +
    >>> np.array([1, 2, 3]) +
    array([1, 2, 3]) +
    +
    Upcasting: +
    +
    >>> np.array([1, 2, 3.0]) +
    array([ 1., 2., 3.]) +
    +
    More than one dimension: +
    +
    >>> np.array([[1, 2], [3, 4]]) +
    array([[1, 2], +
    [3, 4]]) +
    +
    Minimum dimensions 2: +
    +
    >>> np.array([1, 2, 3], ndmin=2) +
    array([[1, 2, 3]]) +
    +
    Type provided: +
    +
    >>> np.array([1, 2, 3], dtype=complex) +
    array([ 1.+0.j, 2.+0.j, 3.+0.j]) +
    +
    Data-type consisting of more than one element: +
    +
    >>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')]) +
    >>> x['a'] +
    array([1, 3]) +
    +
    Creating an array from sub-classes: +
    +
    >>> np.array(np.asmatrix('1 2; 3 4')) +
    array([[1, 2], +
    [3, 4]]) +
    +
    >>> np.array(np.asmatrix('1 2; 3 4'), subok=True) +
    matrix([[1, 2], +
    [3, 4]]) +
    Type: builtin_function_or_method +
    +
    +
    +

    Tip

    +
    >>> help(np.array)
    +
    Help on built-in function array in module numpy: +
    +
    array(...) +
    array(object, dtype=None, ... +
    +
    +
    +
  • +
  • Looking for something:

    +
    In [6]: np.con*?
    +
    np.concat +
    np.concatenate +
    np.conj +
    np.conjugate +
    np.convolve +
    +
    +
  • +
+
+
+

Import conventions

+

The recommended convention to import NumPy is:

+
>>> import numpy as np
+
+
+
+
+
+

1.3.1.2. Creating arrays

+
+

Manual construction of arrays

+
    +
  • 1-D:

    +
    >>> a = np.array([0, 1, 2, 3])
    +
    >>> a +
    array([0, 1, 2, 3]) +
    >>> a.ndim +
    1 +
    >>> a.shape +
    (4,) +
    >>> len(a) +
    4 +
    +
    +
  • +
  • 2-D, 3-D, …:

    +
    >>> b = np.array([[0, 1, 2], [3, 4, 5]])    # 2 x 3 array
    +
    >>> b +
    array([[0, 1, 2], +
    [3, 4, 5]]) +
    >>> b.ndim +
    2 +
    >>> b.shape +
    (2, 3) +
    >>> len(b) # returns the size of the first dimension +
    2 +
    +
    >>> c = np.array([[[1], [2]], [[3], [4]]]) +
    >>> c +
    array([[[1], +
    [2]], +
    +
    [[3], +
    [4]]]) +
    >>> c.shape +
    (2, 2, 1) +
    +
    +
  • +
+ +
+
+

Functions for creating arrays

+
+

Tip

+

In practice, we rarely enter items one by one…

+
+
    +
  • Evenly spaced:

    +
    >>> a = np.arange(10) # 0 .. n-1  (!)
    +
    >>> a +
    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) +
    >>> b = np.arange(1, 9, 2) # start, end (exclusive), step +
    >>> b +
    array([1, 3, 5, 7]) +
    +
    +
  • +
  • or by number of points:

    +
    >>> c = np.linspace(0, 1, 6)   # start, end, num-points
    +
    >>> c +
    array([0. , 0.2, 0.4, 0.6, 0.8, 1. ]) +
    >>> d = np.linspace(0, 1, 5, endpoint=False) +
    >>> d +
    array([0. , 0.2, 0.4, 0.6, 0.8]) +
    +
    +
  • +
  • Common arrays:

    +
    >>> a = np.ones((3, 3))  # reminder: (3, 3) is a tuple
    +
    >>> a +
    array([[1., 1., 1.], +
    [1., 1., 1.], +
    [1., 1., 1.]]) +
    >>> b = np.zeros((2, 2)) +
    >>> b +
    array([[0., 0.], +
    [0., 0.]]) +
    >>> c = np.eye(3) +
    >>> c +
    array([[1., 0., 0.], +
    [0., 1., 0.], +
    [0., 0., 1.]]) +
    >>> d = np.diag(np.array([1, 2, 3, 4])) +
    >>> d +
    array([[1, 0, 0, 0], +
    [0, 2, 0, 0], +
    [0, 0, 3, 0], +
    [0, 0, 0, 4]]) +
    +
    +
  • +
  • np.random: random numbers (Mersenne Twister PRNG):

    +
    >>> rng = np.random.default_rng(27446968)
    +
    >>> a = rng.random(4) # uniform in [0, 1] +
    >>> a +
    array([0.64613018, 0.48984931, 0.50851229, 0.22563948]) +
    +
    >>> b = rng.standard_normal(4) # Gaussian +
    >>> b +
    array([-0.38250769, -0.61536465, 0.98131732, 0.59353096]) +
    +
    +
  • +
+ +
+
+
+

1.3.1.3. Basic data types

+

You may have noticed that, in some instances, array elements are displayed with +a trailing dot (e.g. 2. vs 2). This is due to a difference in the +data-type used:

+
>>> a = np.array([1, 2, 3])
+
>>> a.dtype +
dtype('int64') +
+
>>> b = np.array([1., 2., 3.]) +
>>> b.dtype +
dtype('float64') +
+
+
+

Tip

+

Different data-types allow us to store data more compactly in memory, +but most of the time we simply work with floating point numbers. +Note that, in the example above, NumPy auto-detects the data-type +from the input.

+
+
+

You can explicitly specify which data-type you want:

+
>>> c = np.array([1, 2, 3], dtype=float)
+
>>> c.dtype +
dtype('float64') +
+
+

The default data type is floating point:

+
>>> a = np.ones((3, 3))
+
>>> a.dtype +
dtype('float64') +
+
+

There are also other types:

+
+
Complex:
+
>>> d = np.array([1+2j, 3+4j, 5+6*1j])
+
>>> d.dtype +
dtype('complex128') +
+
+
+
Bool:
+
>>> e = np.array([True, False, False, True])
+
>>> e.dtype +
dtype('bool') +
+
+
+
Strings:
+
>>> f = np.array(['Bonjour', 'Hello', 'Hallo'])
+
>>> f.dtype # <--- strings containing max. 7 letters +
dtype('<U7') +
+
+
+
Much more:
+
    +
  • int32

  • +
  • int64

  • +
  • uint32

  • +
  • uint64

  • +
+
+
+
+
+

1.3.1.4. Basic visualization

+

Now that we have our first data arrays, we are going to visualize them.

+

Start by launching IPython:

+
$ ipython # or ipython3 depending on your install
+
+
+

Or the notebook:

+
$ jupyter notebook
+
+
+

Once IPython has started, enable interactive plots:

+
>>> %matplotlib  
+
+
+

Or, from the notebook, enable plots in the notebook:

+
>>> %matplotlib inline 
+
+
+

The inline is important for the notebook, so that plots are displayed in +the notebook and not in a new window.

+

Matplotlib is a 2D plotting package. We can import its functions as below:

+
>>> import matplotlib.pyplot as plt  # the tidy way
+
+
+

And then use (note that you have to use show explicitly if you have not enabled interactive plots with %matplotlib):

+
>>> plt.plot(x, y)       # line plot    
+
>>> plt.show() # <-- shows the plot (not needed with interactive plots) +
+
+

Or, if you have enabled interactive plots with %matplotlib:

+
>>> plt.plot(x, y)       # line plot    
+
+
+
    +
  • 1D plotting:

  • +
+
>>> x = np.linspace(0, 3, 20)
+
>>> y = np.linspace(0, 9, 20) +
>>> plt.plot(x, y) # line plot +
[<matplotlib.lines.Line2D object at ...>] +
>>> plt.plot(x, y, 'o') # dot plot +
[<matplotlib.lines.Line2D object at ...>] +
+
+../../_images/sphx_glr_plot_basic1dplot_001.png + +
    +
  • 2D arrays (such as images):

  • +
+
>>> rng = np.random.default_rng(27446968)
+
>>> image = rng.random((30, 30)) +
>>> plt.imshow(image, cmap=plt.cm.hot) +
<matplotlib.image.AxesImage object at ...> +
>>> plt.colorbar() +
<matplotlib.colorbar.Colorbar object at ...> +
+
+../../_images/sphx_glr_plot_basic2dplot_001.png + +
+

See also

+

More in the: matplotlib chapter

+
+ +
+
+

1.3.1.5. Indexing and slicing

+

The items of an array can be accessed and assigned to the same way as +other Python sequences (e.g. lists):

+
>>> a = np.arange(10)
+
>>> a +
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) +
>>> a[0], a[2], a[-1] +
(np.int64(0), np.int64(2), np.int64(9)) +
+
+
+

Warning

+

Indices begin at 0, like other Python sequences (and C/C++). +In contrast, in Fortran or Matlab, indices begin at 1.

+
+

The usual python idiom for reversing a sequence is supported:

+
>>> a[::-1]
+
array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) +
+
+

For multidimensional arrays, indices are tuples of integers:

+
>>> a = np.diag(np.arange(3))
+
>>> a +
array([[0, 0, 0], +
[0, 1, 0], +
[0, 0, 2]]) +
>>> a[1, 1] +
np.int64(1) +
>>> a[2, 1] = 10 # third line, second column +
>>> a +
array([[ 0, 0, 0], +
[ 0, 1, 0], +
[ 0, 10, 2]]) +
>>> a[1] +
array([0, 1, 0]) +
+
+
+

Note

+
    +
  • In 2D, the first dimension corresponds to rows, the second +to columns.

  • +
  • for multidimensional a, a[0] is interpreted by +taking all elements in the unspecified dimensions.

  • +
+
+

Slicing: Arrays, like other Python sequences can also be sliced:

+
>>> a = np.arange(10)
+
>>> a +
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) +
>>> a[2:9:3] # [start:end:step] +
array([2, 5, 8]) +
+
+

Note that the last index is not included! :

+
>>> a[:4]
+
array([0, 1, 2, 3]) +
+
+

All three slice components are not required: by default, start is 0, +end is the last and step is 1:

+
>>> a[1:3]
+
array([1, 2]) +
>>> a[::2] +
array([0, 2, 4, 6, 8]) +
>>> a[3:] +
array([3, 4, 5, 6, 7, 8, 9]) +
+
+

A small illustrated summary of NumPy indexing and slicing…

+../../_images/numpy_indexing.png + +

You can also combine assignment and slicing:

+
>>> a = np.arange(10)
+
>>> a[5:] = 10 +
>>> a +
array([ 0, 1, 2, 3, 4, 10, 10, 10, 10, 10]) +
>>> b = np.arange(5) +
>>> a[5:] = b[::-1] +
>>> a +
array([0, 1, 2, 3, 4, 4, 3, 2, 1, 0]) +
+
+ + + +
+
+

1.3.1.6. Copies and views

+

A slicing operation creates a view on the original array, which is +just a way of accessing array data. Thus the original array is not +copied in memory. You can use np.may_share_memory() to check if two arrays +share the same memory block. Note however, that this uses heuristics and may +give you false positives.

+

When modifying the view, the original array is modified as well:

+
>>> a = np.arange(10)
+
>>> a +
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) +
>>> b = a[::2] +
>>> b +
array([0, 2, 4, 6, 8]) +
>>> np.may_share_memory(a, b) +
True +
>>> b[0] = 12 +
>>> b +
array([12, 2, 4, 6, 8]) +
>>> a # (!) +
array([12, 1, 2, 3, 4, 5, 6, 7, 8, 9]) +
+
>>> a = np.arange(10) +
>>> c = a[::2].copy() # force a copy +
>>> c[0] = 12 +
>>> a +
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) +
+
>>> np.may_share_memory(a, c) +
False +
+
+

This behavior can be surprising at first sight… but it allows to save both +memory and time.

+ +
+
+

1.3.1.7. Fancy indexing

+
+

Tip

+

NumPy arrays can be indexed with slices, but also with boolean or +integer arrays (masks). This method is called fancy indexing. +It creates copies not views.

+
+
+

Using boolean masks

+
>>> rng = np.random.default_rng(27446968)
+
>>> a = rng.integers(0, 21, 15) +
>>> a +
array([ 3, 13, 12, 10, 10, 10, 18, 4, 8, 5, 6, 11, 12, 17, 3]) +
>>> (a % 3 == 0) +
array([ True, False, True, False, False, False, True, False, False, +
False, True, False, True, False, True]) +
>>> mask = (a % 3 == 0) +
>>> extract_from_a = a[mask] # or, a[a%3==0] +
>>> extract_from_a # extract a sub-array with the mask +
array([ 3, 12, 18, 6, 12, 3]) +
+
+

Indexing with a mask can be very useful to assign a new value to a sub-array:

+
>>> a[a % 3 == 0] = -1
+
>>> a +
array([-1, 13, -1, 10, 10, 10, -1, 4, 8, 5, -1, 11, -1, 17, -1]) +
+
+
+
+

Indexing with an array of integers

+
>>> a = np.arange(0, 100, 10)
+
>>> a +
array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90]) +
+
+

Indexing can be done with an array of integers, where the same index is repeated +several time:

+
>>> a[[2, 3, 2, 4, 2]]  # note: [2, 3, 2, 4, 2] is a Python list
+
array([20, 30, 20, 40, 20]) +
+
+

New values can be assigned with this kind of indexing:

+
>>> a[[9, 7]] = -100
+
>>> a +
array([ 0, 10, 20, 30, 40, 50, 60, -100, 80, -100]) +
+
+
+

Tip

+

When a new array is created by indexing with an array of integers, the +new array has the same shape as the array of integers:

+
>>> a = np.arange(10)
+
>>> idx = np.array([[3, 4], [9, 7]]) +
>>> idx.shape +
(2, 2) +
>>> a[idx] +
array([[3, 4], +
[9, 7]]) +
+
+
+
+

The image below illustrates various fancy indexing applications

+../../_images/numpy_fancy_indexing.png + + +

+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/numpy/auto_examples/index.html b/intro/numpy/auto_examples/index.html new file mode 100644 index 000000000..6dd35c142 --- /dev/null +++ b/intro/numpy/auto_examples/index.html @@ -0,0 +1,213 @@ + + + + + + + + Full code examples for the numpy chapter — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Full code examples for the numpy chapter

+
+

1D plotting

+
1D plotting
+
+

2D plotting

+
2D plotting
+
+

Distances exercise

+
Distances exercise
+
+

Fitting to polynomial

+
Fitting to polynomial
+
+

Fitting in Chebyshev basis

+
Fitting in Chebyshev basis
+
+

Population exercise

+
Population exercise
+
+

Reading and writing an elephant

+
Reading and writing an elephant
+
+

Mandelbrot set

+
Mandelbrot set
+
+

Random walk exercise

+
Random walk exercise
+
+
+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/numpy/auto_examples/plot_basic1dplot.html b/intro/numpy/auto_examples/plot_basic1dplot.html new file mode 100644 index 000000000..687f0d2ff --- /dev/null +++ b/intro/numpy/auto_examples/plot_basic1dplot.html @@ -0,0 +1,232 @@ + + + + + + + + 1D plotting — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

1D plotting

+

Plot a basic 1D figure

+plot basic1dplot
import numpy as np
+
import matplotlib.pyplot as plt +
+
x = np.linspace(0, 3, 20) +
y = np.linspace(0, 9, 20) +
plt.plot(x, y) +
plt.plot(x, y, "o") +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.049 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/numpy/auto_examples/plot_basic2dplot.html b/intro/numpy/auto_examples/plot_basic2dplot.html new file mode 100644 index 000000000..757175005 --- /dev/null +++ b/intro/numpy/auto_examples/plot_basic2dplot.html @@ -0,0 +1,232 @@ + + + + + + + + 2D plotting — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

2D plotting

+

Plot a basic 2D figure

+plot basic2dplot
import numpy as np
+
import matplotlib.pyplot as plt +
+
rng = np.random.default_rng() +
image = rng.random((30, 30)) +
plt.imshow(image, cmap="hot") +
plt.colorbar() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.075 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/numpy/auto_examples/plot_chebyfit.html b/intro/numpy/auto_examples/plot_chebyfit.html new file mode 100644 index 000000000..06e00a9ce --- /dev/null +++ b/intro/numpy/auto_examples/plot_chebyfit.html @@ -0,0 +1,236 @@ + + + + + + + + Fitting in Chebyshev basis — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Fitting in Chebyshev basis

+

Plot noisy data and their polynomial fit in a Chebyshev basis

+plot chebyfit
import numpy as np
+
import matplotlib.pyplot as plt +
+
rng = np.random.default_rng(27446968) +
+
x = np.linspace(-1, 1, 2000) +
y = np.cos(x) + 0.3 * rng.random(2000) +
p = np.polynomial.Chebyshev.fit(x, y, 90) +
+
plt.plot(x, y, "r.") +
plt.plot(x, p(x), "k-", lw=3) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.095 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/numpy/auto_examples/plot_distances.html b/intro/numpy/auto_examples/plot_distances.html new file mode 100644 index 000000000..2f2c4e34b --- /dev/null +++ b/intro/numpy/auto_examples/plot_distances.html @@ -0,0 +1,232 @@ + + + + + + + + Distances exercise — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Distances exercise

+

Plot distances in a grid

+plot distances
import numpy as np
+
import matplotlib.pyplot as plt +
+
x, y = np.arange(5), np.arange(5)[:, np.newaxis] +
distance = np.sqrt(x**2 + y**2) +
plt.pcolor(distance) +
plt.colorbar() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.069 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/numpy/auto_examples/plot_elephant.html b/intro/numpy/auto_examples/plot_elephant.html new file mode 100644 index 000000000..3dbc76a2c --- /dev/null +++ b/intro/numpy/auto_examples/plot_elephant.html @@ -0,0 +1,270 @@ + + + + + + + + Reading and writing an elephant — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Reading and writing an elephant

+

Read and write images

+
import numpy as np
+
import matplotlib.pyplot as plt +
+
+
+

original figure

+
plt.figure()
+
img = plt.imread("../../../data/elephant.png") +
plt.imshow(img) +
+
+plot elephant
<matplotlib.image.AxesImage object at 0x7f5b41410500>
+
+
+
+
+

red channel displayed in grey

+
plt.figure()
+
img_red = img[:, :, 0] +
plt.imshow(img_red, cmap="gray") +
+
+plot elephant
<matplotlib.image.AxesImage object at 0x7f5b41101d00>
+
+
+
+
+

lower resolution

+
plt.figure()
+
img_tiny = img[::6, ::6] +
plt.imshow(img_tiny, interpolation="nearest") +
+
plt.show() +
+
+plot elephant

Total running time of the script: (0 minutes 0.256 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/numpy/auto_examples/plot_mandelbrot.html b/intro/numpy/auto_examples/plot_mandelbrot.html new file mode 100644 index 000000000..dd2094a04 --- /dev/null +++ b/intro/numpy/auto_examples/plot_mandelbrot.html @@ -0,0 +1,257 @@ + + + + + + + + Mandelbrot set — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Mandelbrot set

+

Compute the Mandelbrot fractal and plot it

+plot mandelbrot
import numpy as np
+
import matplotlib.pyplot as plt +
from numpy import newaxis +
import warnings +
+
+
def compute_mandelbrot(N_max, some_threshold, nx, ny): +
# A grid of c-values +
x = np.linspace(-2, 1, nx) +
y = np.linspace(-1.5, 1.5, ny) +
+
c = x[:, newaxis] + 1j * y[newaxis, :] +
+
# Mandelbrot iteration +
+
z = c +
+
# The code below overflows in many regions of the x-y grid, suppress +
# warnings temporarily +
with warnings.catch_warnings(): +
warnings.simplefilter("ignore") +
for j in range(N_max): +
z = z**2 + c +
mandelbrot_set = abs(z) < some_threshold +
+
return mandelbrot_set +
+
+
mandelbrot_set = compute_mandelbrot(50, 50.0, 601, 401) +
+
plt.imshow(mandelbrot_set.T, extent=(-2, 1, -1.5, 1.5)) +
plt.gray() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.079 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/numpy/auto_examples/plot_polyfit.html b/intro/numpy/auto_examples/plot_polyfit.html new file mode 100644 index 000000000..779c689be --- /dev/null +++ b/intro/numpy/auto_examples/plot_polyfit.html @@ -0,0 +1,236 @@ + + + + + + + + Fitting to polynomial — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Fitting to polynomial

+

Plot noisy data and their polynomial fit

+plot polyfit
import numpy as np
+
import matplotlib.pyplot as plt +
+
rng = np.random.default_rng(27446968) +
+
x = np.linspace(0, 1, 20) +
y = np.cos(x) + 0.3 * rng.random(20) +
p = np.poly1d(np.polyfit(x, y, 3)) +
+
t = np.linspace(0, 1, 200) +
plt.plot(x, y, "o", t, p(t), "-") +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.048 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/numpy/auto_examples/plot_populations.html b/intro/numpy/auto_examples/plot_populations.html new file mode 100644 index 000000000..1e9d43254 --- /dev/null +++ b/intro/numpy/auto_examples/plot_populations.html @@ -0,0 +1,234 @@ + + + + + + + + Population exercise — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Population exercise

+

Plot populations of hares, lynxes, and carrots

+plot populations
import numpy as np
+
import matplotlib.pyplot as plt +
+
data = np.loadtxt("../../../data/populations.txt") +
year, hares, lynxes, carrots = data.T +
+
plt.axes((0.2, 0.1, 0.5, 0.8)) +
plt.plot(year, hares, year, lynxes, year, carrots) +
plt.legend(("Hare", "Lynx", "Carrot"), loc=(1.05, 0.5)) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.063 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/numpy/auto_examples/plot_randomwalk.html b/intro/numpy/auto_examples/plot_randomwalk.html new file mode 100644 index 000000000..623b0305f --- /dev/null +++ b/intro/numpy/auto_examples/plot_randomwalk.html @@ -0,0 +1,255 @@ + + + + + + + + Random walk exercise — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Random walk exercise

+

Plot distance as a function of time for a random walk +together with the theoretical result

+plot randomwalk
import numpy as np
+
import matplotlib.pyplot as plt +
+
# We create 1000 realizations with 200 steps each +
n_stories = 1000 +
t_max = 200 +
+
t = np.arange(t_max) +
# Steps can be -1 or 1 (note that randint excludes the upper limit) +
rng = np.random.default_rng() +
steps = 2 * rng.integers(0, 1 + 1, (n_stories, t_max)) - 1 +
+
# The time evolution of the position is obtained by successively +
# summing up individual steps. This is done for each of the +
# realizations, i.e. along axis 1. +
positions = np.cumsum(steps, axis=1) +
+
# Determine the time evolution of the mean square distance. +
sq_distance = positions**2 +
mean_sq_distance = np.mean(sq_distance, axis=0) +
+
# Plot the distance d from the origin as a function of time and +
# compare with the theoretically expected result where d(t) +
# grows as a square root of time t. +
plt.figure(figsize=(4, 3)) +
plt.plot(t, np.sqrt(mean_sq_distance), "g.", t, np.sqrt(t), "y-") +
plt.xlabel(r"$t$") +
plt.ylabel(r"$\sqrt{\langle (\delta x)^2 \rangle}$") +
plt.tight_layout() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.077 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/numpy/auto_examples/sg_execution_times.html b/intro/numpy/auto_examples/sg_execution_times.html new file mode 100644 index 000000000..65a9409fc --- /dev/null +++ b/intro/numpy/auto_examples/sg_execution_times.html @@ -0,0 +1,238 @@ + + + + + + + + Computation times — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Computation times

+

00:00.812 total execution time for 9 files from intro/numpy/auto_examples:

+
+ + + + + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Example

Time

Mem (MB)

Reading and writing an elephant (plot_elephant.py)

00:00.256

0.0

Fitting in Chebyshev basis (plot_chebyfit.py)

00:00.095

0.0

Mandelbrot set (plot_mandelbrot.py)

00:00.079

0.0

Random walk exercise (plot_randomwalk.py)

00:00.077

0.0

2D plotting (plot_basic2dplot.py)

00:00.075

0.0

Distances exercise (plot_distances.py)

00:00.069

0.0

Population exercise (plot_populations.py)

00:00.063

0.0

1D plotting (plot_basic1dplot.py)

00:00.049

0.0

Fitting to polynomial (plot_polyfit.py)

00:00.048

0.0

+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/numpy/elaborate_arrays.html b/intro/numpy/elaborate_arrays.html new file mode 100644 index 000000000..1201f448f --- /dev/null +++ b/intro/numpy/elaborate_arrays.html @@ -0,0 +1,515 @@ + + + + + + + + 1.3.3. More elaborate arrays — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.3.3. More elaborate arrays

+ +
+

1.3.3.1. More data types

+
+

Casting

+

“Bigger” type wins in mixed-type operations:

+
>>> np.array([1, 2, 3]) + 1.5
+
array([2.5, 3.5, 4.5]) +
+
+

Assignment never changes the type!

+
>>> a = np.array([1, 2, 3])
+
>>> a.dtype +
dtype('int64') +
>>> a[0] = 1.9 # <-- float is truncated to integer +
>>> a +
array([1, 2, 3]) +
+
+

Forced casts:

+
>>> a = np.array([1.7, 1.2, 1.6])
+
>>> b = a.astype(int) # <-- truncates to integer +
>>> b +
array([1, 1, 1]) +
+
+

Rounding:

+
>>> a = np.array([1.2, 1.5, 1.6, 2.5, 3.5, 4.5])
+
>>> b = np.around(a) +
>>> b # still floating-point +
array([1., 2., 2., 2., 4., 4.]) +
>>> c = np.around(a).astype(int) +
>>> c +
array([1, 2, 2, 2, 4, 4]) +
+
+
+
+

Different data type sizes

+

Integers (signed):

+ ++++ + + + + + + + + + + + + + + +

int8

8 bits

int16

16 bits

int32

32 bits (same as int on 32-bit platform)

int64

64 bits (same as int on 64-bit platform)

+
>>> np.array([1], dtype=int).dtype
+
dtype('int64') +
>>> np.iinfo(np.int32).max, 2**31 - 1 +
(2147483647, 2147483647) +
+
+

Unsigned integers:

+ ++++ + + + + + + + + + + + + + + +

uint8

8 bits

uint16

16 bits

uint32

32 bits

uint64

64 bits

+
>>> np.iinfo(np.uint32).max, 2**32 - 1
+
(4294967295, 4294967295) +
+
+

Floating-point numbers:

+ ++++ + + + + + + + + + + + + + + + + + +

float16

16 bits

float32

32 bits

float64

64 bits (same as float)

float96

96 bits, platform-dependent (same as np.longdouble)

float128

128 bits, platform-dependent (same as np.longdouble)

+
>>> np.finfo(np.float32).eps
+
np.float32(1.1920929e-07) +
>>> np.finfo(np.float64).eps +
np.float64(2.220446049250313e-16) +
+
>>> np.float32(1e-8) + np.float32(1) == 1 +
np.True_ +
>>> np.float64(1e-8) + np.float64(1) == 1 +
np.False_ +
+
+

Complex floating-point numbers:

+ ++++ + + + + + + + + + + + + + + +

complex64

two 32-bit floats

complex128

two 64-bit floats

complex192

two 96-bit floats, platform-dependent

complex256

two 128-bit floats, platform-dependent

+ +
+
+
+

1.3.3.2. Structured data types

+ ++++ + + + + + + + + + + + +

sensor_code

(4-character string)

position

(float)

value

(float)

+
>>> samples = np.zeros((6,), dtype=[('sensor_code', 'S4'),
+
... ('position', float), ('value', float)]) +
>>> samples.ndim +
1 +
>>> samples.shape +
(6,) +
>>> samples.dtype.names +
('sensor_code', 'position', 'value') +
>>> samples[:] = [('ALFA', 1, 0.37), ('BETA', 1, 0.11), ('TAU', 1, 0.13), +
... ('ALFA', 1.5, 0.37), ('ALFA', 3, 0.11), ('TAU', 1.2, 0.13)] +
>>> samples +
array([(b'ALFA', 1. , 0.37), (b'BETA', 1. , 0.11), (b'TAU', 1. , 0.13), +
(b'ALFA', 1.5, 0.37), (b'ALFA', 3. , 0.11), (b'TAU', 1.2, 0.13)], +
dtype=[('sensor_code', 'S4'), ('position', '<f8'), ('value', '<f8')]) +
+
+

Field access works by indexing with field names:

+
>>> samples['sensor_code']
+
array([b'ALFA', b'BETA', b'TAU', b'ALFA', b'ALFA', b'TAU'], dtype='|S4') +
>>> samples['value'] +
array([0.37, 0.11, 0.13, 0.37, 0.11, 0.13]) +
>>> samples[0] +
np.void((b'ALFA', 1.0, 0.37), dtype=[('sensor_code', 'S4'), ('position', '<f8'), ('value', '<f8')]) +
+
>>> samples[0]['sensor_code'] = 'TAU' +
>>> samples[0] +
np.void((b'TAU', 1.0, 0.37), dtype=[('sensor_code', 'S4'), ('position', '<f8'), ('value', '<f8')]) +
+
+

Multiple fields at once:

+
>>> samples[['position', 'value']]
+
array([(1. , 0.37), (1. , 0.11), (1. , 0.13), (1.5, 0.37), +
(3. , 0.11), (1.2, 0.13)], +
dtype={'names': ['position', 'value'], 'formats': ['<f8', '<f8'], 'offsets': [4, 12], 'itemsize': 20}) +
+
+

Fancy indexing works, as usual:

+
>>> samples[samples['sensor_code'] == b'ALFA']
+
array([(b'ALFA', 1.5, 0.37), (b'ALFA', 3. , 0.11)], +
dtype=[('sensor_code', 'S4'), ('position', '<f8'), ('value', '<f8')]) +
+
+
+

Note

+

There are a bunch of other syntaxes for constructing structured +arrays, see here +and here.

+
+
+
+

1.3.3.3. maskedarray: dealing with (propagation of) missing data

+
    +
  • For floats one could use NaN’s, but masks work for all types:

    +
    >>> x = np.ma.array([1, 2, 3, 4], mask=[0, 1, 0, 1])
    +
    >>> x +
    masked_array(data=[1, --, 3, --], +
    mask=[False, True, False, True], +
    fill_value=999999) +
    +
    +
    >>> y = np.ma.array([1, 2, 3, 4], mask=[0, 1, 1, 1]) +
    >>> x + y +
    masked_array(data=[2, --, --, --], +
    mask=[False, True, True, True], +
    fill_value=999999) +
    +
    +
  • +
  • Masking versions of common functions:

    +
    >>> np.ma.sqrt([1, -1, 2, -2]) 
    +
    masked_array(data=[1.0, --, 1.41421356237... --], +
    mask=[False, True, False, True], +
    fill_value=1e+20) +
    +
    +
  • +
+
+

Note

+

There are other useful array siblings

+
+
+

While it is off topic in a chapter on NumPy, let’s take a moment to +recall good coding practice, which really do pay off in the long run:

+ +

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/numpy/exercises.html b/intro/numpy/exercises.html new file mode 100644 index 000000000..982890678 --- /dev/null +++ b/intro/numpy/exercises.html @@ -0,0 +1,443 @@ + + + + + + + + 1.3.5. Some exercises — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.3.5. Some exercises

+
+

1.3.5.1. Array manipulations

+
    +
  1. Form the 2-D array (without typing it in explicitly):

    +
    [[1,  6, 11],
    +
    [2, 7, 12], +
    [3, 8, 13], +
    [4, 9, 14], +
    [5, 10, 15]] +
    +
    +

    and generate a new array containing its 2nd and 4th rows.

    +
  2. +
  3. Divide each column of the array:

    +
    >>> import numpy as np
    +
    >>> a = np.arange(25).reshape(5, 5) +
    +
    +

    elementwise with the array b = np.array([1., 5, 10, 15, 20]). +(Hint: np.newaxis).

    +
  4. +
  5. Harder one: Generate a 10 x 3 array of random numbers (in range [0,1]). +For each row, pick the number closest to 0.5.

    +
      +
    • Use abs and argmin to find the column j closest for +each row.

    • +
    • Use fancy indexing to extract the numbers. (Hint: a[i,j] – +the array i must contain the row numbers corresponding to stuff in +j.)

    • +
    +
  6. +
+
+
+

1.3.5.2. Picture manipulation: Framing a Face

+

Let’s do some manipulations on NumPy arrays by starting with an image +of a raccoon. scipy provides a 2D array of this image with the +scipy.datasets.face function:

+
>>> import scipy as sp
+
>>> face = sp.datasets.face(gray=True) # 2D grayscale image +
+
+

Here are a few images we will be able to obtain with our manipulations: +use different colormaps, crop the image, change some parts of the image.

+../../_images/faces.png +
    +
  • Let’s use the imshow function of matplotlib to display the image.

    +
    +
    >>> import matplotlib.pyplot as plt
    +
    >>> face = sp.datasets.face(gray=True) +
    >>> plt.imshow(face) +
    <matplotlib.image.AxesImage object at 0x...> +
    +
    +
    +
  • +
  • +
    The face is displayed in false colors. A colormap must be

    specified for it to be displayed in grey.

    +
    >>> plt.imshow(face, cmap=plt.cm.gray)
    +
    <matplotlib.image.AxesImage object at 0x...> +
    +
    +
    +
    +
  • +
  • +
    Create an array of the image with a narrower centeringfor example,

    remove 100 pixels from all the borders of the image. To check the result, +display this new array with imshow.

    +
    >>> crop_face = face[100:-100, 100:-100]
    +
    +
    +
    +
    +
  • +
  • +
    We will now frame the face with a black locket. For this, we

    need to create a mask corresponding to the pixels we want to be +black. The center of the face is around (660, 330), so we defined +the mask by this condition (y-300)**2 + (x-660)**2

    +
    >>> sy, sx = face.shape
    +
    >>> y, x = np.ogrid[0:sy, 0:sx] # x and y indices of pixels +
    >>> y.shape, x.shape +
    ((768, 1), (1, 1024)) +
    >>> centerx, centery = (660, 300) # center of the image +
    >>> mask = ((y - centery)**2 + (x - centerx)**2) > 230**2 # circle +
    +
    +

    then we assign the value 0 to the pixels of the image corresponding +to the mask. The syntax is extremely simple and intuitive:

    +
    >>> face[mask] = 0
    +
    >>> plt.imshow(face) +
    <matplotlib.image.AxesImage object at 0x...> +
    +
    +
    +
    +
  • +
  • +
    Follow-up: copy all instructions of this exercise in a script called

    face_locket.py then execute this script in IPython with %run +face_locket.py.

    +

    Change the circle to an ellipsoid.

    +
    +
    +
  • +
+
+
+

1.3.5.3. Data statistics

+

The data in populations.txt +describes the populations of hares and lynxes (and carrots) in +northern Canada during 20 years:

+
>>> data = np.loadtxt('data/populations.txt')
+
>>> year, hares, lynxes, carrots = data.T # trick: columns to variables +
+
>>> import matplotlib.pyplot as plt +
>>> plt.axes([0.2, 0.1, 0.5, 0.8]) +
<Axes: > +
>>> plt.plot(year, hares, year, lynxes, year, carrots) +
[<matplotlib.lines.Line2D object at ...>, ...] +
>>> plt.legend(('Hare', 'Lynx', 'Carrot'), loc=(1.05, 0.5)) +
<matplotlib.legend.Legend object at ...> +
+
+../../_images/sphx_glr_plot_populations_001.png + +

Computes and print, based on the data in populations.txt

+
    +
  1. The mean and std of the populations of each species for the years +in the period.

  2. +
  3. Which year each species had the largest population.

  4. +
  5. Which species has the largest population for each year. +(Hint: argsort & fancy indexing of +np.array(['H', 'L', 'C']))

  6. +
  7. Which years any of the populations is above 50000. +(Hint: comparisons and np.any)

  8. +
  9. The top 2 years for each species when they had the lowest +populations. (Hint: argsort, fancy indexing)

  10. +
  11. Compare (plot) the change in hare population (see +help(np.gradient)) and the number of lynxes. Check correlation +(see help(np.corrcoef)).

  12. +
+

… all without for-loops.

+

Solution: Python source file

+
+
+

1.3.5.4. Crude integral approximations

+

Write a function f(a, b, c) that returns a^b - c. Form +a 24x12x6 array containing its values in parameter ranges [0,1] x +[0,1] x [0,1].

+

Approximate the 3-d integral

+
+

\int_0^1\int_0^1\int_0^1(a^b-c)da\,db\,dc

+

over this volume with the mean. The exact result is: \ln 2 -
+\frac{1}{2}\approx0.1931\ldots — what is your relative error?

+

(Hints: use elementwise operations and broadcasting. +You can make np.ogrid give a number of points in given range +with np.ogrid[0:1:20j].)

+

Reminder Python functions:

+
def f(a, b, c):
+
return some_result +
+
+

Solution: Python source file

+
+
+

1.3.5.5. Mandelbrot set

+../../_images/sphx_glr_plot_mandelbrot_001.png + +

Write a script that computes the Mandelbrot fractal. The Mandelbrot +iteration:

+
N_max = 50
+
some_threshold = 50 +
+
c = x + 1j*y +
+
z = 0 +
for j in range(N_max): +
z = z**2 + c +
+
+

Point (x, y) belongs to the Mandelbrot set if |z| < +some_threshold.

+

Do this computation by:

+
    +
  1. Construct a grid of c = x + 1j*y values in range [-2, 1] x [-1.5, 1.5]

  2. +
  3. Do the iteration

  4. +
  5. Form the 2-d boolean mask indicating which points are in the set

  6. +
  7. Save the result to an image with:

  8. +
+
+
>>> import matplotlib.pyplot as plt
+
>>> plt.imshow(mask.T, extent=[-2, 1, -1.5, 1.5]) +
<matplotlib.image.AxesImage object at ...> +
>>> plt.gray() +
>>> plt.savefig('mandelbrot.png') +
+
+
+

Solution: Python source file

+
+
+

1.3.5.6. Markov chain

+../../_images/markov-chain.png +

Markov chain transition matrix P, and probability distribution on +the states p:

+
    +
  1. 0 <= P[i,j] <= 1: probability to go from state i to state j

  2. +
  3. Transition rule: p_{new} = P^T p_{old}

  4. +
  5. all(sum(P, axis=1) == 1), p.sum() == 1: normalization

  6. +
+

Write a script that works with 5 states, and:

+
    +
  • Constructs a random matrix, and normalizes each row so that it +is a transition matrix.

  • +
  • Starts from a random (normalized) probability distribution +p and takes 50 steps => p_50

  • +
  • Computes the stationary distribution: the eigenvector of P.T +with eigenvalue 1 (numerically: closest to 1) => p_stationary

  • +
+

Remember to normalize the eigenvector — I didn’t…

+
    +
  • Checks if p_50 and p_stationary are equal to tolerance 1e-5

  • +
+

Toolbox: np.random, @, np.linalg.eig, +reductions, abs(), argmin, comparisons, all, +np.linalg.norm, etc.

+

Solution: Python source file

+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/numpy/gallery.html b/intro/numpy/gallery.html new file mode 100644 index 000000000..2d0688da4 --- /dev/null +++ b/intro/numpy/gallery.html @@ -0,0 +1,252 @@ + + + + + + + + 1.3.6. Full code examples — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.3.6. Full code examples

+
+

1.3.6.1. Full code examples for the numpy chapter

+
+

1D plotting

+
1D plotting
+
+

2D plotting

+
2D plotting
+
+

Distances exercise

+
Distances exercise
+
+

Fitting to polynomial

+
Fitting to polynomial
+
+

Fitting in Chebyshev basis

+
Fitting in Chebyshev basis
+
+

Population exercise

+
Population exercise
+
+

Reading and writing an elephant

+
Reading and writing an elephant
+
+

Mandelbrot set

+
Mandelbrot set
+
+

Random walk exercise

+
Random walk exercise
+
+
+ +

Gallery generated by Sphinx-Gallery

+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/numpy/index.html b/intro/numpy/index.html new file mode 100644 index 000000000..faa784dcd --- /dev/null +++ b/intro/numpy/index.html @@ -0,0 +1,328 @@ + + + + + + + + 1.3. NumPy: creating and manipulating numerical data — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.3. NumPy: creating and manipulating numerical data

+

Authors: Emmanuelle Gouillart, Didrik Pinte, Gaël Varoquaux, and +Pauli Virtanen

+

This chapter gives an overview of NumPy, the core tool for performant +numerical computing with Python.

+
+
+ +
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/numpy/operations.html b/intro/numpy/operations.html new file mode 100644 index 000000000..0d169c9cd --- /dev/null +++ b/intro/numpy/operations.html @@ -0,0 +1,945 @@ + + + + + + + + 1.3.2. Numerical operations on arrays — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.3.2. Numerical operations on arrays

+ +
+

1.3.2.1. Elementwise operations

+
+

Basic operations

+

With scalars:

+
>>> a = np.array([1, 2, 3, 4])
+
>>> a + 1 +
array([2, 3, 4, 5]) +
>>> 2**a +
array([ 2, 4, 8, 16]) +
+
+

All arithmetic operates elementwise:

+
>>> b = np.ones(4) + 1
+
>>> a - b +
array([-1., 0., 1., 2.]) +
>>> a * b +
array([2., 4., 6., 8.]) +
+
>>> j = np.arange(5) +
>>> 2**(j + 1) - j +
array([ 2, 3, 6, 13, 28]) +
+
+

These operations are of course much faster than if you did them in pure python:

+
>>> a = np.arange(10000)
+
>>> %timeit a + 1 +
10000 loops, best of 3: 24.3 us per loop +
>>> l = range(10000) +
>>> %timeit [i+1 for i in l] +
1000 loops, best of 3: 861 us per loop +
+
+
+

Warning

+

Array multiplication is not matrix multiplication:

+
>>> c = np.ones((3, 3))
+
>>> c * c # NOT matrix multiplication! +
array([[1., 1., 1.], +
[1., 1., 1.], +
[1., 1., 1.]]) +
+
+
+
+

Note

+

Matrix multiplication:

+
>>> c @ c
+
array([[3., 3., 3.], +
[3., 3., 3.], +
[3., 3., 3.]]) +
+
+
+ +
+
+

Other operations

+

Comparisons:

+
>>> a = np.array([1, 2, 3, 4])
+
>>> b = np.array([4, 2, 2, 4]) +
>>> a == b +
array([False, True, False, True]) +
>>> a > b +
array([False, False, True, False]) +
+
+
+

Tip

+

Array-wise comparisons:

+
>>> a = np.array([1, 2, 3, 4])
+
>>> b = np.array([4, 2, 2, 4]) +
>>> c = np.array([1, 2, 3, 4]) +
>>> np.array_equal(a, b) +
False +
>>> np.array_equal(a, c) +
True +
+
+
+

Logical operations:

+
>>> a = np.array([1, 1, 0, 0], dtype=bool)
+
>>> b = np.array([1, 0, 1, 0], dtype=bool) +
>>> np.logical_or(a, b) +
array([ True, True, True, False]) +
>>> np.logical_and(a, b) +
array([ True, False, False, False]) +
+
+

Transcendental functions:

+
>>> a = np.arange(5)
+
>>> np.sin(a) +
array([ 0. , 0.84147098, 0.90929743, 0.14112001, -0.7568025 ]) +
>>> np.exp(a) +
array([ 1. , 2.71828183, 7.3890561 , 20.08553692, 54.59815003]) +
>>> np.log(np.exp(a)) +
array([0., 1., 2., 3., 4.]) +
+
+

Shape mismatches

+
>>> a = np.arange(4)
+
>>> a + np.array([1, 2]) +
Traceback (most recent call last): +
File "<stdin>", line 1, in <module> +
ValueError: operands could not be broadcast together with shapes (4,) (2,) +
+
+

Broadcasting? We’ll return to that later.

+

Transposition:

+
>>> a = np.triu(np.ones((3, 3)), 1)   # see help(np.triu)
+
>>> a +
array([[0., 1., 1.], +
[0., 0., 1.], +
[0., 0., 0.]]) +
>>> a.T +
array([[0., 0., 0.], +
[1., 0., 0.], +
[1., 1., 0.]]) +
+
+
+

Note

+

The transposition is a view

+

The transpose returns a view of the original array:

+
>>> a = np.arange(9).reshape(3, 3)
+
>>> a.T[0, 2] = 999 +
>>> a.T +
array([[ 0, 3, 999], +
[ 1, 4, 7], +
[ 2, 5, 8]]) +
>>> a +
array([[ 0, 1, 2], +
[ 3, 4, 5], +
[999, 7, 8]]) +
+
+
+
+

Note

+

Linear algebra

+

The sub-module numpy.linalg implements basic linear algebra, such as +solving linear systems, singular value decomposition, etc. However, it is +not guaranteed to be compiled using efficient routines, and thus we +recommend the use of scipy.linalg, as detailed in section +Linear algebra operations: scipy.linalg

+
+ +
+
+
+

1.3.2.2. Basic reductions

+
+

Computing sums

+
>>> x = np.array([1, 2, 3, 4])
+
>>> np.sum(x) +
np.int64(10) +
>>> x.sum() +
np.int64(10) +
+
+../../_images/reductions.png +

Sum by rows and by columns:

+
>>> x = np.array([[1, 1], [2, 2]])
+
>>> x +
array([[1, 1], +
[2, 2]]) +
>>> x.sum(axis=0) # columns (first dimension) +
array([3, 3]) +
>>> x[:, 0].sum(), x[:, 1].sum() +
(np.int64(3), np.int64(3)) +
>>> x.sum(axis=1) # rows (second dimension) +
array([2, 4]) +
>>> x[0, :].sum(), x[1, :].sum() +
(np.int64(2), np.int64(4)) +
+
+
+

Tip

+

Same idea in higher dimensions:

+
>>> rng = np.random.default_rng(27446968)
+
>>> x = rng.random((2, 2, 2)) +
>>> x.sum(axis=2)[0, 1] +
np.float64(0.73415...) +
>>> x[0, 1, :].sum() +
np.float64(0.73415...) +
+
+
+
+
+

Other reductions

+

— works the same way (and take axis=)

+

Extrema:

+
>>> x = np.array([1, 3, 2])
+
>>> x.min() +
np.int64(1) +
>>> x.max() +
np.int64(3) +
+
>>> x.argmin() # index of minimum +
np.int64(0) +
>>> x.argmax() # index of maximum +
np.int64(1) +
+
+

Logical operations:

+
>>> np.all([True, True, False])
+
np.False_ +
>>> np.any([True, True, False]) +
np.True_ +
+
+
+

Note

+

Can be used for array comparisons:

+
>>> a = np.zeros((100, 100))
+
>>> np.any(a != 0) +
np.False_ +
>>> np.all(a == a) +
np.True_ +
+
>>> a = np.array([1, 2, 3, 2]) +
>>> b = np.array([2, 2, 3, 2]) +
>>> c = np.array([6, 4, 4, 5]) +
>>> ((a <= b) & (b <= c)).all() +
np.True_ +
+
+
+

Statistics:

+
>>> x = np.array([1, 2, 3, 1])
+
>>> y = np.array([[1, 2, 3], [5, 6, 1]]) +
>>> x.mean() +
np.float64(1.75) +
>>> np.median(x) +
np.float64(1.5) +
>>> np.median(y, axis=-1) # last axis +
array([2., 5.]) +
+
>>> x.std() # full population standard dev. +
np.float64(0.82915619758884995) +
+
+

… and many more (best to learn as you go).

+ + +
+
+
+

1.3.2.3. Broadcasting

+
    +
  • Basic operations on numpy arrays (addition, etc.) are elementwise

  • +
  • This works on arrays of the same size.

    +
    +
    +
    Nevertheless, It’s also possible to do operations on arrays of different
    +
    sizes if NumPy can transform these arrays so that they all have
    +
    the same size: this conversion is called broadcasting.
    +
    +
    +
  • +
+

The image below gives an example of broadcasting:

+../../_images/numpy_broadcasting.png + +

Let’s verify:

+
>>> a = np.tile(np.arange(0, 40, 10), (3, 1)).T
+
>>> a +
array([[ 0, 0, 0], +
[10, 10, 10], +
[20, 20, 20], +
[30, 30, 30]]) +
>>> b = np.array([0, 1, 2]) +
>>> a + b +
array([[ 0, 1, 2], +
[10, 11, 12], +
[20, 21, 22], +
[30, 31, 32]]) +
+
+

We have already used broadcasting without knowing it!:

+
>>> a = np.ones((4, 5))
+
>>> a[0] = 2 # we assign an array of dimension 0 to an array of dimension 1 +
>>> a +
array([[2., 2., 2., 2., 2.], +
[1., 1., 1., 1., 1.], +
[1., 1., 1., 1., 1.], +
[1., 1., 1., 1., 1.]]) +
+
+

A useful trick:

+
>>> a = np.arange(0, 40, 10)
+
>>> a.shape +
(4,) +
>>> a = a[:, np.newaxis] # adds a new axis -> 2D array +
>>> a.shape +
(4, 1) +
>>> a +
array([[ 0], +
[10], +
[20], +
[30]]) +
>>> a + b +
array([[ 0, 1, 2], +
[10, 11, 12], +
[20, 21, 22], +
[30, 31, 32]]) +
+
+
+

Tip

+

Broadcasting seems a bit magical, but it is actually quite natural to +use it when we want to solve a problem whose output data is an array +with more dimensions than input data.

+
+ +

A lot of grid-based or network-based problems can also use +broadcasting. For instance, if we want to compute the distance from +the origin of points on a 5x5 grid, we can do

+
>>> x, y = np.arange(5), np.arange(5)[:, np.newaxis]
+
>>> distance = np.sqrt(x ** 2 + y ** 2) +
>>> distance +
array([[0. , 1. , 2. , 3. , 4. ], +
[1. , 1.41421356, 2.23606798, 3.16227766, 4.12310563], +
[2. , 2.23606798, 2.82842712, 3.60555128, 4.47213595], +
[3. , 3.16227766, 3.60555128, 4.24264069, 5. ], +
[4. , 4.12310563, 4.47213595, 5. , 5.65685425]]) +
+
+

Or in color:

+
>>> plt.pcolor(distance)
+
<matplotlib.collections.PolyQuadMesh object at ...> +
>>> plt.colorbar() +
<matplotlib.colorbar.Colorbar object at ...> +
+
+../../_images/sphx_glr_plot_distances_001.png + +

Remark : the numpy.ogrid() function allows to directly create vectors x +and y of the previous example, with two “significant dimensions”:

+
>>> x, y = np.ogrid[0:5, 0:5]
+
>>> x, y +
(array([[0], +
[1], +
[2], +
[3], +
[4]]), array([[0, 1, 2, 3, 4]])) +
>>> x.shape, y.shape +
((5, 1), (1, 5)) +
>>> distance = np.sqrt(x ** 2 + y ** 2) +
+
+
+

Tip

+

So, np.ogrid is very useful as soon as we have to handle +computations on a grid. On the other hand, np.mgrid directly +provides matrices full of indices for cases where we can’t (or don’t +want to) benefit from broadcasting:

+
>>> x, y = np.mgrid[0:4, 0:4]
+
>>> x +
array([[0, 0, 0, 0], +
[1, 1, 1, 1], +
[2, 2, 2, 2], +
[3, 3, 3, 3]]) +
>>> y +
array([[0, 1, 2, 3], +
[0, 1, 2, 3], +
[0, 1, 2, 3], +
[0, 1, 2, 3]]) +
+
+
+
+

See also

+

Broadcasting: discussion of broadcasting in +the Advanced NumPy chapter.

+
+
+
+

1.3.2.4. Array shape manipulation

+
+

Flattening

+
>>> a = np.array([[1, 2, 3], [4, 5, 6]])
+
>>> a.ravel() +
array([1, 2, 3, 4, 5, 6]) +
>>> a.T +
array([[1, 4], +
[2, 5], +
[3, 6]]) +
>>> a.T.ravel() +
array([1, 4, 2, 5, 3, 6]) +
+
+

Higher dimensions: last dimensions ravel out “first”.

+
+
+

Reshaping

+

The inverse operation to flattening:

+
>>> a.shape
+
(2, 3) +
>>> b = a.ravel() +
>>> b = b.reshape((2, 3)) +
>>> b +
array([[1, 2, 3], +
[4, 5, 6]]) +
+
+

Or,

+
>>> a.reshape((2, -1))    # unspecified (-1) value is inferred
+
array([[1, 2, 3], +
[4, 5, 6]]) +
+
+
+

Warning

+

ndarray.reshape may return a view (cf help(np.reshape))), +or copy

+
+
+

Tip

+
>>> b[0, 0] = 99
+
>>> a +
array([[99, 2, 3], +
[ 4, 5, 6]]) +
+
+

Beware: reshape may also return a copy!:

+
>>> a = np.zeros((3, 2))
+
>>> b = a.T.reshape(3*2) +
>>> b[0] = 9 +
>>> a +
array([[0., 0.], +
[0., 0.], +
[0., 0.]]) +
+
+

To understand this you need to learn more about the memory layout of a NumPy array.

+
+
+
+

Adding a dimension

+

Indexing with the np.newaxis object allows us to add an axis to an array +(you have seen this already above in the broadcasting section):

+
>>> z = np.array([1, 2, 3])
+
>>> z +
array([1, 2, 3]) +
+
>>> z[:, np.newaxis] +
array([[1], +
[2], +
[3]]) +
+
>>> z[np.newaxis, :] +
array([[1, 2, 3]]) +
+
+
+
+

Dimension shuffling

+
>>> a = np.arange(4*3*2).reshape(4, 3, 2)
+
>>> a.shape +
(4, 3, 2) +
>>> a[0, 2, 1] +
np.int64(5) +
>>> b = a.transpose(1, 2, 0) +
>>> b.shape +
(3, 2, 4) +
>>> b[2, 1, 0] +
np.int64(5) +
+
+

Also creates a view:

+
>>> b[2, 1, 0] = -1
+
>>> a[0, 2, 1] +
np.int64(-1) +
+
+
+
+

Resizing

+

Size of an array can be changed with ndarray.resize:

+
>>> a = np.arange(4)
+
>>> a.resize((8,)) +
>>> a +
array([0, 1, 2, 3, 0, 0, 0, 0]) +
+
+

However, it must not be referred to somewhere else:

+
>>> b = a
+
>>> a.resize((4,)) +
Traceback (most recent call last): +
File "<stdin>", line 1, in <module> +
ValueError: cannot resize an array that references or is referenced +
by another array in this way. +
Use the np.resize function or refcheck=False +
+
+ +
+
+
+

1.3.2.5. Sorting data

+

Sorting along an axis:

+
>>> a = np.array([[4, 3, 5], [1, 2, 1]])
+
>>> b = np.sort(a, axis=1) +
>>> b +
array([[3, 4, 5], +
[1, 1, 2]]) +
+
+
+

Note

+

Sorts each row separately!

+
+

In-place sort:

+
>>> a.sort(axis=1)
+
>>> a +
array([[3, 4, 5], +
[1, 1, 2]]) +
+
+

Sorting with fancy indexing:

+
>>> a = np.array([4, 3, 1, 2])
+
>>> j = np.argsort(a) +
>>> j +
array([2, 3, 1, 0]) +
>>> a[j] +
array([1, 2, 3, 4]) +
+
+

Finding minima and maxima:

+
>>> a = np.array([4, 3, 1, 2])
+
>>> j_max = np.argmax(a) +
>>> j_min = np.argmin(a) +
>>> j_max, j_min +
(np.int64(0), np.int64(2)) +
+
+ +
+
+

1.3.2.6. Summary

+

What do you need to know to get started?

+
    +
  • Know how to create arrays : array, arange, ones, +zeros.

  • +
  • Know the shape of the array with array.shape, then use slicing +to obtain different views of the array: array[::2], +etc. Adjust the shape of the array using reshape or flatten it +with ravel.

  • +
  • Obtain a subset of the elements of an array and/or modify their values +with masks

    +
    >>> a[a < 0] = 0
    +
    +
    +
  • +
  • Know miscellaneous operations on arrays, such as finding the mean or max +(array.max(), array.mean()). No need to retain everything, but +have the reflex to search in the documentation (online docs, +help())!!

  • +
  • For advanced use: master the indexing with arrays of integers, as well as +broadcasting. Know more NumPy functions to handle various array +operations.

  • +
+ +

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/index.html b/intro/scipy/auto_examples/index.html new file mode 100644 index 000000000..883018cb4 --- /dev/null +++ b/intro/scipy/auto_examples/index.html @@ -0,0 +1,264 @@ + + + + + + + + Full code examples for the SciPy chapter — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Full code examples for the SciPy chapter

+
+

Finding the minimum of a smooth function

+
Finding the minimum of a smooth function
+
+

Resample a signal with scipy.signal.resample

+
Resample a signal with scipy.signal.resample
+
+

Detrending a signal

+
Detrending a signal
+
+

Integrating a simple ODE

+
Integrating a simple ODE
+
+

Normal distribution: histogram and PDF

+
Normal distribution: histogram and PDF
+
+

Integrate the Damped spring-mass oscillator

+
Integrate the Damped spring-mass oscillator
+
+

Comparing 2 sets of samples from Gaussians

+
Comparing 2 sets of samples from Gaussians
+
+

Curve fitting

+
Curve fitting
+
+

Spectrogram, power spectral density

+
Spectrogram, power spectral density
+
+

Demo mathematical morphology

+
Demo mathematical morphology
+
+

Plot geometrical transformations on images

+
Plot geometrical transformations on images
+
+

Demo connected components

+
Demo connected components
+
+

Minima and roots of a function

+
Minima and roots of a function
+
+

Plot filtering on images

+
Plot filtering on images
+
+

Optimization of a two-parameter function

+
Optimization of a two-parameter function
+
+

Plotting and manipulating FFTs for filtering

+
Plotting and manipulating FFTs for filtering
+
+

A demo of 1D interpolation

+
A demo of 1D interpolation
+
+
+
+

Solutions of the exercises for SciPy

+
+

Crude periodicity finding

+
Crude periodicity finding
+
+

Curve fitting: temperature as a function of month of the year

+
Curve fitting: temperature as a function of month of the year
+
+

Simple image blur by convolution with a Gaussian kernel

+
Simple image blur by convolution with a Gaussian kernel
+
+

Image denoising by FFT

+
Image denoising by FFT
+
+
+ +

Gallery generated by Sphinx-Gallery

+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/plot_2d_minimization.html b/intro/scipy/auto_examples/plot_2d_minimization.html new file mode 100644 index 000000000..1515888cc --- /dev/null +++ b/intro/scipy/auto_examples/plot_2d_minimization.html @@ -0,0 +1,316 @@ + + + + + + + + 1.5.12.15. Optimization of a two-parameter function — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

1.5.12.15. Optimization of a two-parameter function

+
import numpy as np
+
+
+
# Define the function that we are interested in +
def sixhump(x): +
return ( +
(4 - 2.1 * x[0] ** 2 + x[0] ** 4 / 3) * x[0] ** 2 +
+ x[0] * x[1] +
+ (-4 + 4 * x[1] ** 2) * x[1] ** 2 +
) +
+
+
# Make a grid to evaluate the function (for plotting) +
xlim = [-2, 2] +
ylim = [-1, 1] +
x = np.linspace(*xlim) # type: ignore[call-overload] +
y = np.linspace(*ylim) # type: ignore[call-overload] +
xg, yg = np.meshgrid(x, y) +
+
+
+

A 2D image plot of the function

+
+

Simple visualization in 2D

+
+
import matplotlib.pyplot as plt
+
+
plt.figure() +
plt.imshow(sixhump([xg, yg]), extent=xlim + ylim, origin="lower") # type: ignore[arg-type] +
plt.colorbar() +
+
+plot 2d minimization
<matplotlib.colorbar.Colorbar object at 0x7f5b3b537ec0>
+
+
+
+
+

A 3D surface plot of the function

+
from mpl_toolkits.mplot3d import Axes3D
+
+
fig = plt.figure() +
ax: Axes3D = fig.add_subplot(111, projection="3d") +
surf = ax.plot_surface( +
xg, +
yg, +
sixhump([xg, yg]), +
rstride=1, +
cstride=1, +
cmap="viridis", +
linewidth=0, +
antialiased=False, +
) +
+
ax.set_xlabel("x") +
ax.set_ylabel("y") +
ax.set_zlabel("f(x, y)") +
ax.set_title("Six-hump Camelback function") +
+
+Six-hump Camelback function
Text(0.5, 1.0, 'Six-hump Camelback function')
+
+
+
+
+

Find minima

+
import scipy as sp
+
+
# local minimization +
res_local = sp.optimize.minimize(sixhump, x0=[0, 0]) +
+
# global minimization +
res_global = sp.optimize.differential_evolution(sixhump, bounds=[xlim, ylim]) +
+
plt.figure() +
# Show the function in 2D +
plt.imshow(sixhump([xg, yg]), extent=xlim + ylim, origin="lower") # type: ignore[arg-type] +
plt.colorbar() +
# Mark the minima +
plt.scatter(res_local.x[0], res_local.x[1], label="local minimizer") +
plt.scatter(res_global.x[0], res_global.x[1], label="global minimizer") +
plt.legend() +
plt.show() +
+
+plot 2d minimization

Total running time of the script: (0 minutes 0.324 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/plot_connect_measurements.html b/intro/scipy/auto_examples/plot_connect_measurements.html new file mode 100644 index 000000000..9023a7e54 --- /dev/null +++ b/intro/scipy/auto_examples/plot_connect_measurements.html @@ -0,0 +1,271 @@ + + + + + + + + 1.5.12.12. Demo connected components — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

1.5.12.12. Demo connected components

+

Extracting and labeling connected components in a 2D array

+
import numpy as np
+
import matplotlib.pyplot as plt +
+
+

Generate some binary data

+
x, y = np.indices((100, 100))
+
sig = ( +
np.sin(2 * np.pi * x / 50.0) +
* np.sin(2 * np.pi * y / 50.0) +
* (1 + x * y / 50.0**2) ** 2 +
) +
mask = sig > 1 +
+
plt.figure(figsize=(7, 3.5)) +
plt.subplot(1, 2, 1) +
plt.imshow(sig) +
plt.axis("off") +
plt.title("sig") +
+
plt.subplot(1, 2, 2) +
plt.imshow(mask, cmap="gray") +
plt.axis("off") +
plt.title("mask") +
plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9) +
+
+sig, mask

Label connected components

+
import scipy as sp
+
+
labels, nb = sp.ndimage.label(mask) +
+
plt.figure(figsize=(3.5, 3.5)) +
plt.imshow(labels) +
plt.title("label") +
plt.axis("off") +
+
plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9) +
+
+label

Extract the 4th connected component, and crop the array around it

+
sl = sp.ndimage.find_objects(labels == 4)
+
plt.figure(figsize=(3.5, 3.5)) +
plt.imshow(sig[sl[0]]) +
plt.title("Cropped connected component") +
plt.axis("off") +
+
plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9) +
+
plt.show() +
+
+Cropped connected component

Total running time of the script: (0 minutes 0.114 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/plot_curve_fit.html b/intro/scipy/auto_examples/plot_curve_fit.html new file mode 100644 index 000000000..519447328 --- /dev/null +++ b/intro/scipy/auto_examples/plot_curve_fit.html @@ -0,0 +1,269 @@ + + + + + + + + 1.5.12.8. Curve fitting — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

1.5.12.8. Curve fitting

+

Demos a simple curve fitting

+

First generate some data

+
import numpy as np
+
+
# Seed the random number generator for reproducibility +
rng = np.random.default_rng(27446968) +
+
x_data = np.linspace(-5, 5, num=50) +
noise = 0.01 * np.cos(100 * x_data) +
a, b = 2.9, 1.5 +
y_data = a * np.cos(b * x_data) + noise +
+
# And plot it +
import matplotlib.pyplot as plt +
+
plt.figure(figsize=(6, 4)) +
plt.scatter(x_data, y_data) +
+
+plot curve fit
<matplotlib.collections.PathCollection object at 0x7f5b3be44590>
+
+
+

Now fit a simple sine function to the data

+
import scipy as sp
+
+
+
def test_func(x, a, b, c): +
return a * np.sin(b * x + c) +
+
+
params, params_covariance = sp.optimize.curve_fit( +
test_func, x_data, y_data, p0=[2, 1, 3] +
) +
+
print(params) +
+
+
[2.900026   1.50012043 1.57079633]
+
+
+

And plot the resulting curve on the data

+
plt.figure(figsize=(6, 4))
+
plt.scatter(x_data, y_data, label="Data") +
plt.plot(x_data, test_func(x_data, *params), label="Fitted function") +
+
plt.legend(loc="best") +
+
plt.show() +
+
+plot curve fit

Total running time of the script: (0 minutes 0.114 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/plot_detrend.html b/intro/scipy/auto_examples/plot_detrend.html new file mode 100644 index 000000000..ec042ae66 --- /dev/null +++ b/intro/scipy/auto_examples/plot_detrend.html @@ -0,0 +1,244 @@ + + + + + + + + 1.5.12.3. Detrending a signal — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

1.5.12.3. Detrending a signal

+

scipy.signal.detrend() removes a linear trend.

+

Generate a random signal with a trend

+
import numpy as np
+
+
t = np.linspace(0, 5, 100) +
rng = np.random.default_rng() +
x = t + rng.normal(size=100) +
+
+

Detrend

+
import scipy as sp
+
+
x_detrended = sp.signal.detrend(x) +
+
+

Plot

+
import matplotlib.pyplot as plt
+
+
plt.figure(figsize=(5, 4)) +
plt.plot(t, x, label="x") +
plt.plot(t, x_detrended, label="x_detrended") +
plt.legend(loc="best") +
plt.show() +
+
+plot detrend

Total running time of the script: (0 minutes 0.055 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/plot_fftpack.html b/intro/scipy/auto_examples/plot_fftpack.html new file mode 100644 index 000000000..8f0bc0e1d --- /dev/null +++ b/intro/scipy/auto_examples/plot_fftpack.html @@ -0,0 +1,335 @@ + + + + + + + + 1.5.12.16. Plotting and manipulating FFTs for filtering — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

1.5.12.16. Plotting and manipulating FFTs for filtering

+

Plot the power of the FFT of a signal and inverse FFT back to reconstruct +a signal.

+

This example demonstrate scipy.fft.fft(), +scipy.fft.fftfreq() and scipy.fft.ifft(). It +implements a basic filter that is very suboptimal, and should not be +used.

+
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
+
+

Generate the signal

+
# Seed the random number generator
+
rng = np.random.default_rng(27446968) +
+
time_step = 0.02 +
period = 5.0 +
+
time_vec = np.arange(0, 20, time_step) +
sig = np.sin(2 * np.pi / period * time_vec) + 0.5 * rng.normal(size=time_vec.size) +
+
plt.figure(figsize=(6, 5)) +
plt.plot(time_vec, sig, label="Original signal") +
+
+plot fftpack
[<matplotlib.lines.Line2D object at 0x7f5b3ac966f0>]
+
+
+
+
+

Compute and plot the power

+
# The FFT of the signal
+
sig_fft = sp.fft.fft(sig) +
+
# And the power (sig_fft is of complex dtype) +
power = np.abs(sig_fft) ** 2 +
+
# The corresponding frequencies +
sample_freq = sp.fft.fftfreq(sig.size, d=time_step) +
+
# Plot the FFT power +
plt.figure(figsize=(6, 5)) +
plt.plot(sample_freq, power) +
plt.xlabel("Frequency [Hz]") +
plt.ylabel("plower") +
+
# Find the peak frequency: we can focus on only the positive frequencies +
pos_mask = np.where(sample_freq > 0) +
freqs = sample_freq[pos_mask] +
peak_freq = freqs[power[pos_mask].argmax()] +
+
# Check that it does indeed correspond to the frequency that we generate +
# the signal with +
np.allclose(peak_freq, 1.0 / period) +
+
# An inner plot to show the peak frequency +
axes = plt.axes((0.55, 0.3, 0.3, 0.5)) +
plt.title("Peak frequency") +
plt.plot(freqs[:8], power[pos_mask][:8]) +
plt.setp(axes, yticks=[]) +
+
# scipy.signal.find_peaks_cwt can also be used for more advanced +
# peak detection +
+
+Peak frequency
[]
+
+
+
+
+

Remove all the high frequencies

+
+

We now remove all the high frequencies and transform back from +frequencies to signal.

+
+
high_freq_fft = sig_fft.copy()
+
high_freq_fft[np.abs(sample_freq) > peak_freq] = 0 +
filtered_sig = sp.fft.ifft(high_freq_fft) +
+
plt.figure(figsize=(6, 5)) +
plt.plot(time_vec, sig, label="Original signal") +
plt.plot(time_vec, filtered_sig, linewidth=3, label="Filtered signal") +
plt.xlabel("Time [s]") +
plt.ylabel("Amplitude") +
+
plt.legend(loc="best") +
+
+plot fftpack
/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages/matplotlib/cbook.py:1762: ComplexWarning: Casting complex values to real discards the imaginary part
+
return math.isfinite(val) +
/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages/matplotlib/cbook.py:1398: ComplexWarning: Casting complex values to real discards the imaginary part +
return np.asarray(x, float) +
+
<matplotlib.legend.Legend object at 0x7f5b3b907b30> +
+
+

Note This is actually a bad way of creating a filter: such brutal +cut-off in frequency space does not control distortion on the signal.

+

Filters should be created using the SciPy filter design code

+
+
+

Total running time of the script: (0 minutes 0.203 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/plot_image_filters.html b/intro/scipy/auto_examples/plot_image_filters.html new file mode 100644 index 000000000..45c9dd836 --- /dev/null +++ b/intro/scipy/auto_examples/plot_image_filters.html @@ -0,0 +1,264 @@ + + + + + + + + 1.5.12.14. Plot filtering on images — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

1.5.12.14. Plot filtering on images

+

Demo filtering for denoising of images.

+noisy, Gaussian filter, median filter, Wiener filter
# Load some data
+
import scipy as sp +
+
face = sp.datasets.face(gray=True) +
face = face[:512, -512:] # crop out square on right +
+
# Apply a variety of filters +
import matplotlib.pyplot as plt +
+
import numpy as np +
+
noisy_face = np.copy(face).astype(float) +
rng = np.random.default_rng() +
noisy_face += face.std() * 0.5 * rng.standard_normal(face.shape) +
blurred_face = sp.ndimage.gaussian_filter(noisy_face, sigma=3) +
median_face = sp.ndimage.median_filter(noisy_face, size=5) +
wiener_face = sp.signal.wiener(noisy_face, (5, 5)) +
+
plt.figure(figsize=(12, 3.5)) +
plt.subplot(141) +
plt.imshow(noisy_face, cmap="gray") +
plt.axis("off") +
plt.title("noisy") +
+
plt.subplot(142) +
plt.imshow(blurred_face, cmap="gray") +
plt.axis("off") +
plt.title("Gaussian filter") +
+
plt.subplot(143) +
plt.imshow(median_face, cmap="gray") +
plt.axis("off") +
plt.title("median filter") +
+
plt.subplot(144) +
plt.imshow(wiener_face, cmap="gray") +
plt.title("Wiener filter") +
plt.axis("off") +
+
plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.458 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/plot_image_transform.html b/intro/scipy/auto_examples/plot_image_transform.html new file mode 100644 index 000000000..88c04b843 --- /dev/null +++ b/intro/scipy/auto_examples/plot_image_transform.html @@ -0,0 +1,267 @@ + + + + + + + + 1.5.12.11. Plot geometrical transformations on images — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

1.5.12.11. Plot geometrical transformations on images

+

Demo geometrical transformations of images.

+plot image transform
Downloading file 'face.dat' from 'https://raw.githubusercontent.com/scipy/dataset-face/main/face.dat' to '/home/runner/.cache/scipy-data'.
+
+
+
+

+
+
# Load some data
+
import scipy as sp +
+
face = sp.datasets.face(gray=True) +
+
# Apply a variety of transformations +
import matplotlib.pyplot as plt +
+
shifted_face = sp.ndimage.shift(face, (50, 50)) +
shifted_face2 = sp.ndimage.shift(face, (50, 50), mode="nearest") +
rotated_face = sp.ndimage.rotate(face, 30) +
cropped_face = face[50:-50, 50:-50] +
zoomed_face = sp.ndimage.zoom(face, 2) +
zoomed_face.shape +
+
plt.figure(figsize=(15, 3)) +
plt.subplot(151) +
plt.imshow(shifted_face, cmap="gray") +
plt.axis("off") +
+
plt.subplot(152) +
plt.imshow(shifted_face2, cmap="gray") +
plt.axis("off") +
+
plt.subplot(153) +
plt.imshow(rotated_face, cmap="gray") +
plt.axis("off") +
+
plt.subplot(154) +
plt.imshow(cropped_face, cmap="gray") +
plt.axis("off") +
+
plt.subplot(155) +
plt.imshow(zoomed_face, cmap="gray") +
plt.axis("off") +
+
plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.975 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/plot_interpolation.html b/intro/scipy/auto_examples/plot_interpolation.html new file mode 100644 index 000000000..c581b1aa3 --- /dev/null +++ b/intro/scipy/auto_examples/plot_interpolation.html @@ -0,0 +1,273 @@ + + + + + + + + 1.5.12.17. A demo of 1D interpolation — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

1.5.12.17. A demo of 1D interpolation

+
    +
  • plot interpolation
  • +
  • plot interpolation
  • +
  • plot interpolation
  • +
+
# Generate data
+
import numpy as np +
+
rng = np.random.default_rng(27446968) +
measured_time = np.linspace(0, 2 * np.pi, 20) +
function = np.sin(measured_time) +
noise = rng.normal(loc=0, scale=0.1, size=20) +
measurements = function + noise +
+
# Smooth the curve and interpolate at new times +
import scipy as sp +
+
smoothing_spline = sp.interpolate.make_smoothing_spline(measured_time, measurements) +
interpolation_time = np.linspace(0, 2 * np.pi, 200) +
smooth_results = smoothing_spline(interpolation_time) +
+
# Plot the data, the interpolant, and the original function +
import matplotlib.pyplot as plt +
+
plt.figure(figsize=(6, 4)) +
plt.plot(measured_time, measurements, ".", ms=6, label="measurements") +
plt.plot(interpolation_time, smooth_results, label="smoothing spline") +
plt.plot(interpolation_time, np.sin(interpolation_time), "--", label="underlying curve") +
plt.legend() +
plt.show() +
+
# Fit the data exactly +
interp_spline = sp.interpolate.make_interp_spline(measured_time, function) +
interp_results = interp_spline(interpolation_time) +
+
# Plot the data, the interpolant, and the original function +
plt.figure(figsize=(6, 4)) +
plt.plot(measured_time, function, ".", ms=6, label="measurements") +
plt.plot(interpolation_time, interp_results, label="interpolating spline") +
plt.plot(interpolation_time, np.sin(interpolation_time), "--", label="underlying curve") +
plt.legend() +
plt.show() +
+
# Plot interpolant, its derivative, and its antiderivative +
plt.figure(figsize=(6, 4)) +
t = interpolation_time +
plt.plot(t, interp_spline(t), label="spline") +
plt.plot(t, interp_spline.derivative()(t), label="derivative") +
plt.plot(t, interp_spline.antiderivative()(t) - 1, label="antiderivative") +
+
plt.legend() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.202 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/plot_mathematical_morpho.html b/intro/scipy/auto_examples/plot_mathematical_morpho.html new file mode 100644 index 000000000..ffbc87038 --- /dev/null +++ b/intro/scipy/auto_examples/plot_mathematical_morpho.html @@ -0,0 +1,264 @@ + + + + + + + + 1.5.12.10. Demo mathematical morphology — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

1.5.12.10. Demo mathematical morphology

+

A basic demo of binary opening and closing.

+a, mask, opened_mask, closed_mask
# Generate some binary data
+
import numpy as np +
+
np.random.seed(0) +
a = np.zeros((50, 50)) +
a[10:-10, 10:-10] = 1 +
a += 0.25 * np.random.standard_normal(a.shape) +
mask = a >= 0.5 +
+
# Apply mathematical morphology +
import scipy as sp +
+
opened_mask = sp.ndimage.binary_opening(mask) +
closed_mask = sp.ndimage.binary_closing(opened_mask) +
+
# Plot +
import matplotlib.pyplot as plt +
+
plt.figure(figsize=(12, 3.5)) +
plt.subplot(141) +
plt.imshow(a, cmap="gray") +
plt.axis("off") +
plt.title("a") +
+
plt.subplot(142) +
plt.imshow(mask, cmap="gray") +
plt.axis("off") +
plt.title("mask") +
+
plt.subplot(143) +
plt.imshow(opened_mask, cmap="gray") +
plt.axis("off") +
plt.title("opened_mask") +
+
plt.subplot(144) +
plt.imshow(closed_mask, cmap="gray") +
plt.title("closed_mask") +
plt.axis("off") +
+
plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.098 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/plot_normal_distribution.html b/intro/scipy/auto_examples/plot_normal_distribution.html new file mode 100644 index 000000000..3d148ddb2 --- /dev/null +++ b/intro/scipy/auto_examples/plot_normal_distribution.html @@ -0,0 +1,240 @@ + + + + + + + + 1.5.12.5. Normal distribution: histogram and PDF — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

1.5.12.5. Normal distribution: histogram and PDF

+

Explore the normal distribution: a histogram built from samples and the +PDF (probability density function).

+plot normal distribution
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
dist = sp.stats.norm(loc=0, scale=1) # standard normal distribution +
sample = dist.rvs(size=100000) # "random variate sample" +
plt.hist( +
sample, +
bins=51, # group the observations into 50 bins +
density=True, # normalize the frequencies +
label="normalized histogram", +
) +
+
x = np.linspace(-5, 5) # possible values of the random variable +
plt.plot(x, dist.pdf(x), label="PDF") +
plt.legend() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.101 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/plot_optimize_example1.html b/intro/scipy/auto_examples/plot_optimize_example1.html new file mode 100644 index 000000000..7e5c57ccc --- /dev/null +++ b/intro/scipy/auto_examples/plot_optimize_example1.html @@ -0,0 +1,257 @@ + + + + + + + + 1.5.12.1. Finding the minimum of a smooth function — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

1.5.12.1. Finding the minimum of a smooth function

+

Demos various methods to find the minimum of a function.

+
import numpy as np
+
import matplotlib.pyplot as plt +
+
+
def f(x): +
return x**2 + 10 * np.sin(x) +
+
+
x = np.arange(-5, 5, 0.1) +
plt.plot(x, f(x)) +
+
+plot optimize example1
[<matplotlib.lines.Line2D object at 0x7f5b414796d0>]
+
+
+

Now find the minimum with a few methods

+
import scipy as sp
+
+
# The default (Nelder Mead) +
print(sp.optimize.minimize(f, x0=0)) +
+
+
 message: Optimization terminated successfully.
+
success: True +
status: 0 +
fun: -7.945823375615215 +
x: [-1.306e+00] +
nit: 5 +
jac: [-1.192e-06] +
hess_inv: [[ 8.589e-02]] +
nfev: 12 +
njev: 6 +
+
+
+
+

Total running time of the script: (0 minutes 0.048 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/plot_optimize_example2.html b/intro/scipy/auto_examples/plot_optimize_example2.html new file mode 100644 index 000000000..37127ba9f --- /dev/null +++ b/intro/scipy/auto_examples/plot_optimize_example2.html @@ -0,0 +1,304 @@ + + + + + + + + 1.5.12.13. Minima and roots of a function — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

1.5.12.13. Minima and roots of a function

+

Demos finding minima and roots of a function.

+
+

Define the function

+
import numpy as np
+
+
x = np.arange(-10, 10, 0.1) +
+
+
def f(x): +
return x**2 + 10 * np.sin(x) +
+
+
+
+

Find minima

+
import scipy as sp
+
+
# Global optimization +
grid = (-10, 10, 0.1) +
xmin_global = sp.optimize.brute(f, (grid,)) +
print(f"Global minima found {xmin_global}") +
+
# Constrain optimization +
xmin_local = sp.optimize.fminbound(f, 0, 10) +
print(f"Local minimum found {xmin_local}") +
+
+
Global minima found [-1.30641113]
+
Local minimum found 3.8374671194983834 +
+
+
+
+

Root finding

+
root = sp.optimize.root(f, 1)  # our initial guess is 1
+
print(f"First root found {root.x}") +
root2 = sp.optimize.root(f, -2.5) +
print(f"Second root found {root2.x}") +
+
+
First root found [0.]
+
Second root found [-2.47948183] +
+
+
+
+

Plot function, minima, and roots

+
import matplotlib.pyplot as plt
+
+
fig = plt.figure(figsize=(6, 4)) +
ax = fig.add_subplot(111) +
+
# Plot the function +
ax.plot(x, f(x), "b-", label="f(x)") +
+
# Plot the minima +
xmins = np.array([xmin_global[0], xmin_local]) +
ax.plot(xmins, f(xmins), "go", label="Minima") +
+
# Plot the roots +
roots = np.array([root.x, root2.x]) +
ax.plot(roots, f(roots), "kv", label="Roots") +
+
# Decorate the figure +
ax.legend(loc="best") +
ax.set_xlabel("x") +
ax.set_ylabel("f(x)") +
ax.axhline(0, color="gray") +
plt.show() +
+
+plot optimize example2

Total running time of the script: (0 minutes 0.070 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/plot_resample.html b/intro/scipy/auto_examples/plot_resample.html new file mode 100644 index 000000000..82cae6768 --- /dev/null +++ b/intro/scipy/auto_examples/plot_resample.html @@ -0,0 +1,244 @@ + + + + + + + + 1.5.12.2. Resample a signal with scipy.signal.resample — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

1.5.12.2. Resample a signal with scipy.signal.resample

+

scipy.signal.resample() uses FFT to resample a 1D signal.

+

Generate a signal with 100 data point

+
import numpy as np
+
+
t = np.linspace(0, 5, 100) +
x = np.sin(t) +
+
+

Downsample it by a factor of 4

+
import scipy as sp
+
+
x_resampled = sp.signal.resample(x, 25) +
+
+

Plot

+
import matplotlib.pyplot as plt
+
+
plt.figure(figsize=(5, 4)) +
plt.plot(t, x, label="Original signal") +
plt.plot(t[::4], x_resampled, "ko", label="Resampled signal") +
+
plt.legend(loc="best") +
plt.show() +
+
+plot resample

Total running time of the script: (0 minutes 0.246 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/plot_solve_ivp_damped_spring_mass.html b/intro/scipy/auto_examples/plot_solve_ivp_damped_spring_mass.html new file mode 100644 index 000000000..42b0ff7a0 --- /dev/null +++ b/intro/scipy/auto_examples/plot_solve_ivp_damped_spring_mass.html @@ -0,0 +1,249 @@ + + + + + + + + 1.5.12.6. Integrate the Damped spring-mass oscillator — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

1.5.12.6. Integrate the Damped spring-mass oscillator

+plot solve ivp damped spring mass
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
m = 0.5 # kg +
k = 4 # N/m +
c = 0.4 # N s/m +
+
zeta = c / (2 * m * np.sqrt(k / m)) +
omega = np.sqrt(k / m) +
+
+
def f(t, z, zeta, omega): +
return (z[1], -zeta * omega * z[1] - omega**2 * z[0]) +
+
+
t_span = (0, 10) +
t_eval = np.linspace(*t_span, 100) +
z0 = [1, 0] +
res = sp.integrate.solve_ivp( +
f, t_span, z0, t_eval=t_eval, args=(zeta, omega), method="LSODA" +
) +
+
plt.figure(figsize=(4, 3)) +
plt.plot(res.t, res.y[0], label="y") +
plt.plot(res.t, res.y[1], label="dy/dt") +
plt.legend(loc="best") +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.052 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/plot_solve_ivp_simple.html b/intro/scipy/auto_examples/plot_solve_ivp_simple.html new file mode 100644 index 000000000..1f35094a8 --- /dev/null +++ b/intro/scipy/auto_examples/plot_solve_ivp_simple.html @@ -0,0 +1,246 @@ + + + + + + + + 1.5.12.4. Integrating a simple ODE — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

1.5.12.4. Integrating a simple ODE

+

Solve the ODE dy/dt = -2y between t = 0..4, with the initial condition +y(t=0) = 1.

+Solution of Initial Value Problem
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
+
def f(t, y): +
return -2 * y +
+
+
t_span = (0, 4) # time interval +
t_eval = np.linspace(*t_span) # times at which to evaluate `y` +
y0 = [ +
1, +
] # initial state +
res = sp.integrate.solve_ivp(f, t_span=t_span, y0=y0, t_eval=t_eval) +
+
plt.figure(figsize=(4, 3)) +
plt.plot(res.t, res.y[0]) +
plt.xlabel("t") +
plt.ylabel("y") +
plt.title("Solution of Initial Value Problem") +
plt.tight_layout() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.080 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/plot_spectrogram.html b/intro/scipy/auto_examples/plot_spectrogram.html new file mode 100644 index 000000000..2f576e48b --- /dev/null +++ b/intro/scipy/auto_examples/plot_spectrogram.html @@ -0,0 +1,292 @@ + + + + + + + + 1.5.12.9. Spectrogram, power spectral density — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

1.5.12.9. Spectrogram, power spectral density

+

Demo spectrogram and power spectral density on a frequency chirp.

+
import numpy as np
+
import matplotlib.pyplot as plt +
+
+
+

Generate a chirp signal

+
# Seed the random number generator
+
np.random.seed(0) +
+
time_step = 0.01 +
time_vec = np.arange(0, 70, time_step) +
+
# A signal with a small frequency chirp +
sig = np.sin(0.5 * np.pi * time_vec * (1 + 0.1 * time_vec)) +
+
plt.figure(figsize=(8, 5)) +
plt.plot(time_vec, sig) +
+
+plot spectrogram
[<matplotlib.lines.Line2D object at 0x7f5b3ae252e0>]
+
+
+
+
+

Compute and plot the spectrogram

+
+

The spectrum of the signal on consecutive time windows

+
+
import scipy as sp
+
+
freqs, times, spectrogram = sp.signal.spectrogram(sig) +
+
plt.figure(figsize=(5, 4)) +
plt.imshow(spectrogram, aspect="auto", cmap="hot_r", origin="lower") +
plt.title("Spectrogram") +
plt.ylabel("Frequency band") +
plt.xlabel("Time window") +
plt.tight_layout() +
+
+Spectrogram
+
+

Compute and plot the power spectral density (PSD)

+
+

The power of the signal per frequency band

+
+
freqs, psd = sp.signal.welch(sig)
+
+
plt.figure(figsize=(5, 4)) +
plt.semilogx(freqs, psd) +
plt.title("PSD: power spectral density") +
plt.xlabel("Frequency") +
plt.ylabel("Power") +
plt.tight_layout() +
+
+PSD: power spectral density
+
+

Total running time of the script: (0 minutes 0.350 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/plot_t_test.html b/intro/scipy/auto_examples/plot_t_test.html new file mode 100644 index 000000000..8db4b5fac --- /dev/null +++ b/intro/scipy/auto_examples/plot_t_test.html @@ -0,0 +1,239 @@ + + + + + + + + 1.5.12.7. Comparing 2 sets of samples from Gaussians — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

1.5.12.7. Comparing 2 sets of samples from Gaussians

+plot t test
import numpy as np
+
import matplotlib.pyplot as plt +
+
# Generates 2 sets of observations +
rng = np.random.default_rng(27446968) +
samples1 = rng.normal(0, size=1000) +
samples2 = rng.normal(1, size=1000) +
+
# Compute a histogram of the sample +
bins = np.linspace(-4, 4, 30) +
histogram1, bins = np.histogram(samples1, bins=bins, density=True) +
histogram2, bins = np.histogram(samples2, bins=bins, density=True) +
+
plt.figure(figsize=(6, 4)) +
plt.hist(samples1, bins=bins, density=True, label="Samples 1") # type: ignore[arg-type] +
plt.hist(samples2, bins=bins, density=True, label="Samples 2") # type: ignore[arg-type] +
plt.legend(loc="best") +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.104 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/sg_execution_times.html b/intro/scipy/auto_examples/sg_execution_times.html new file mode 100644 index 000000000..d62df19b0 --- /dev/null +++ b/intro/scipy/auto_examples/sg_execution_times.html @@ -0,0 +1,270 @@ + + + + + + + + Computation times — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Computation times

+

00:03.592 total execution time for 17 files from intro/scipy/auto_examples:

+
+ + + + + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Example

Time

Mem (MB)

Plot geometrical transformations on images (plot_image_transform.py)

00:00.975

0.0

Plot filtering on images (plot_image_filters.py)

00:00.458

0.0

Spectrogram, power spectral density (plot_spectrogram.py)

00:00.350

0.0

Optimization of a two-parameter function (plot_2d_minimization.py)

00:00.324

0.0

Resample a signal with scipy.signal.resample (plot_resample.py)

00:00.246

0.0

Plotting and manipulating FFTs for filtering (plot_fftpack.py)

00:00.203

0.0

A demo of 1D interpolation (plot_interpolation.py)

00:00.202

0.0

Demo connected components (plot_connect_measurements.py)

00:00.114

0.0

Curve fitting (plot_curve_fit.py)

00:00.114

0.0

Comparing 2 sets of samples from Gaussians (plot_t_test.py)

00:00.104

0.0

Normal distribution: histogram and PDF (plot_normal_distribution.py)

00:00.101

0.0

Demo mathematical morphology (plot_mathematical_morpho.py)

00:00.098

0.0

Integrating a simple ODE (plot_solve_ivp_simple.py)

00:00.080

0.0

Minima and roots of a function (plot_optimize_example2.py)

00:00.070

0.0

Detrending a signal (plot_detrend.py)

00:00.055

0.0

Integrate the Damped spring-mass oscillator (plot_solve_ivp_damped_spring_mass.py)

00:00.052

0.0

Finding the minimum of a smooth function (plot_optimize_example1.py)

00:00.048

0.0

+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/solutions/index.html b/intro/scipy/auto_examples/solutions/index.html new file mode 100644 index 000000000..b03f5a16d --- /dev/null +++ b/intro/scipy/auto_examples/solutions/index.html @@ -0,0 +1,217 @@ + + + + + + + + Solutions of the exercises for SciPy — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Solutions of the exercises for SciPy

+
+

Crude periodicity finding

+
Crude periodicity finding
+
+

Curve fitting: temperature as a function of month of the year

+
Curve fitting: temperature as a function of month of the year
+
+

Simple image blur by convolution with a Gaussian kernel

+
Simple image blur by convolution with a Gaussian kernel
+
+

Image denoising by FFT

+
Image denoising by FFT
+
+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/solutions/plot_curvefit_temperature_data.html b/intro/scipy/auto_examples/solutions/plot_curvefit_temperature_data.html new file mode 100644 index 000000000..414a30b1f --- /dev/null +++ b/intro/scipy/auto_examples/solutions/plot_curvefit_temperature_data.html @@ -0,0 +1,286 @@ + + + + + + + + Curve fitting: temperature as a function of month of the year — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Curve fitting: temperature as a function of month of the year

+

We have the min and max temperatures in Alaska for each months of the +year. We would like to find a function to describe this yearly evolution.

+

For this, we will fit a periodic function.

+
+

The data

+
import numpy as np
+
+
temp_max = np.array([17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18]) +
temp_min = np.array([-62, -59, -56, -46, -32, -18, -9, -13, -25, -46, -52, -58]) +
+
import matplotlib.pyplot as plt +
+
months = np.arange(12) +
plt.plot(months, temp_max, "ro") +
plt.plot(months, temp_min, "bo") +
plt.xlabel("Month") +
plt.ylabel("Min and max temperature") +
+
+plot curvefit temperature data
Text(35.472222222222214, 0.5, 'Min and max temperature')
+
+
+
+
+

Fitting it to a periodic function

+
import scipy as sp
+
+
+
def yearly_temps(times, avg, ampl, time_offset): +
return avg + ampl * np.cos((times + time_offset) * 2 * np.pi / times.max()) +
+
+
res_max, cov_max = sp.optimize.curve_fit(yearly_temps, months, temp_max, [20, 10, 0]) +
res_min, cov_min = sp.optimize.curve_fit(yearly_temps, months, temp_min, [-40, 20, 0]) +
+
+
+
+

Plotting the fit

+
days = np.linspace(0, 12, num=365)
+
+
plt.figure() +
plt.plot(months, temp_max, "ro") +
plt.plot(days, yearly_temps(days, *res_max), "r-") +
plt.plot(months, temp_min, "bo") +
plt.plot(days, yearly_temps(days, *res_min), "b-") +
plt.xlabel("Month") +
plt.ylabel(r"Temperature ($^\circ$C)") +
+
plt.show() +
+
+plot curvefit temperature data

Total running time of the script: (0 minutes 0.108 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/solutions/plot_fft_image_denoise.html b/intro/scipy/auto_examples/solutions/plot_fft_image_denoise.html new file mode 100644 index 000000000..0151c7717 --- /dev/null +++ b/intro/scipy/auto_examples/solutions/plot_fft_image_denoise.html @@ -0,0 +1,346 @@ + + + + + + + + Image denoising by FFT — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Image denoising by FFT

+

Denoise an image (../../../../data/moonlanding.png) by +implementing a blur with an FFT.

+

Implements, via FFT, the following convolution:

+
+

f_1(t) = \int dt'\, K(t-t') f_0(t')

+
+

\tilde{f}_1(\omega) = \tilde{K}(\omega) \tilde{f}_0(\omega)

+
+

Read and plot the image

+
import numpy as np
+
import matplotlib.pyplot as plt +
+
im = plt.imread("../../../../data/moonlanding.png").astype(float) +
+
plt.figure() +
plt.imshow(im, "gray") +
plt.title("Original image") +
+
+Original image
Text(0.5, 1.0, 'Original image')
+
+
+
+
+

Compute the 2d FFT of the input image

+
import scipy as sp
+
+
im_fft = sp.fft.fft2(im) +
+
# Show the results +
+
+
def plot_spectrum(im_fft): +
from matplotlib.colors import LogNorm +
+
# A logarithmic colormap +
plt.imshow(np.abs(im_fft), norm=LogNorm(vmin=5)) +
plt.colorbar() +
+
+
plt.figure() +
plot_spectrum(im_fft) +
plt.title("Fourier transform") +
+
+Fourier transform
Text(0.5, 1.0, 'Fourier transform')
+
+
+
+
+

Filter in FFT

+
# In the lines following, we'll make a copy of the original spectrum and
+
# truncate coefficients. +
+
# Define the fraction of coefficients (in each direction) we keep +
keep_fraction = 0.1 +
+
# Call ff a copy of the original transform. NumPy arrays have a copy +
# method for this purpose. +
im_fft2 = im_fft.copy() +
+
# Set r and c to be the number of rows and columns of the array. +
r, c = im_fft2.shape +
+
# Set to zero all rows with indices between r*keep_fraction and +
# r*(1-keep_fraction): +
im_fft2[int(r * keep_fraction) : int(r * (1 - keep_fraction))] = 0 +
+
# Similarly with the columns: +
im_fft2[:, int(c * keep_fraction) : int(c * (1 - keep_fraction))] = 0 +
+
plt.figure() +
plot_spectrum(im_fft2) +
plt.title("Filtered Spectrum") +
+
+Filtered Spectrum
Text(0.5, 1.0, 'Filtered Spectrum')
+
+
+
+
+

Reconstruct the final image

+
# Reconstruct the denoised image from the filtered spectrum, keep only the
+
# real part for display. +
im_new = sp.fft.ifft2(im_fft2).real +
+
plt.figure() +
plt.imshow(im_new, "gray") +
plt.title("Reconstructed Image") +
+
+Reconstructed Image
Text(0.5, 1.0, 'Reconstructed Image')
+
+
+
+
+

Easier and better: scipy.ndimage.gaussian_filter()

+
+

Implementing filtering directly with FFTs is tricky and time consuming. +We can use the Gaussian filter from scipy.ndimage

+
+
im_blur = sp.ndimage.gaussian_filter(im, 4)
+
+
plt.figure() +
plt.imshow(im_blur, "gray") +
plt.title("Blurred image") +
+
plt.show() +
+
+Blurred image

Total running time of the script: (0 minutes 0.782 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/solutions/plot_image_blur.html b/intro/scipy/auto_examples/solutions/plot_image_blur.html new file mode 100644 index 000000000..301b6e4b9 --- /dev/null +++ b/intro/scipy/auto_examples/solutions/plot_image_blur.html @@ -0,0 +1,320 @@ + + + + + + + + Simple image blur by convolution with a Gaussian kernel — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Simple image blur by convolution with a Gaussian kernel

+

Blur an an image (../../../../data/elephant.png) using a +Gaussian kernel.

+

Convolution is easy to perform with FFT: convolving two signals boils +down to multiplying their FFTs (and performing an inverse FFT).

+
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
+
+

The original image

+
# read image
+
img = plt.imread("../../../../data/elephant.png") +
plt.figure() +
plt.imshow(img) +
+
+plot image blur
<matplotlib.image.AxesImage object at 0x7f5b3aef46e0>
+
+
+
+
+

Prepare an Gaussian convolution kernel

+
# First a 1-D  Gaussian
+
t = np.linspace(-10, 10, 30) +
bump = np.exp(-0.1 * t**2) +
bump /= np.trapezoid(bump) # normalize the integral to 1 +
+
# make a 2-D kernel out of it +
kernel = bump[:, np.newaxis] * bump[np.newaxis, :] +
+
+
+
+

Implement convolution via FFT

+
# Padded fourier transform, with the same shape as the image
+
# We use :func:`scipy.fft.fft2` to have a 2D FFT +
kernel_ft = sp.fft.fft2(kernel, s=img.shape[:2], axes=(0, 1)) +
+
# convolve +
img_ft = sp.fft.fft2(img, axes=(0, 1)) +
# the 'newaxis' is to match to color direction +
img2_ft = kernel_ft[:, :, np.newaxis] * img_ft +
img2 = sp.fft.ifft2(img2_ft, axes=(0, 1)).real +
+
# clip values to range +
img2 = np.clip(img2, 0, 1) +
+
# plot output +
plt.figure() +
plt.imshow(img2) +
+
+plot image blur
<matplotlib.image.AxesImage object at 0x7f5b3acab410>
+
+
+

Further exercise (only if you are familiar with this stuff):

+

A “wrapped border” appears in the upper left and top edges of the +image. This is because the padding is not done correctly, and does +not take the kernel size into account (so the convolution “flows out +of bounds of the image”). Try to remove this artifact.

+
+
+

A function to do it: scipy.signal.fftconvolve()

+
+

The above exercise was only for didactic reasons: there exists a +function in scipy that will do this for us, and probably do a better +job: scipy.signal.fftconvolve()

+
+
# mode='same' is there to enforce the same output shape as input arrays
+
# (ie avoid border effects) +
img3 = sp.signal.fftconvolve(img, kernel[:, :, np.newaxis], mode="same") +
plt.figure() +
plt.imshow(img3) +
+
+plot image blur
<matplotlib.image.AxesImage object at 0x7f5b3bd76ab0>
+
+
+

Note that we still have a decay to zero at the border of the image. +Using scipy.ndimage.gaussian_filter() would get rid of this +artifact

+
+
+

Total running time of the script: (0 minutes 0.321 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/solutions/plot_periodicity_finder.html b/intro/scipy/auto_examples/solutions/plot_periodicity_finder.html new file mode 100644 index 000000000..e5993f7d5 --- /dev/null +++ b/intro/scipy/auto_examples/solutions/plot_periodicity_finder.html @@ -0,0 +1,285 @@ + + + + + + + + Crude periodicity finding — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Crude periodicity finding

+

Discover the periods in evolution of animal populations +(../../../../data/populations.txt)

+
+

Load the data

+
import numpy as np
+
+
data = np.loadtxt("../../../../data/populations.txt") +
years = data[:, 0] +
populations = data[:, 1:] +
+
+
+
+

Plot the data

+
import matplotlib.pyplot as plt
+
+
plt.figure() +
plt.plot(years, populations * 1e-3) +
plt.xlabel("Year") +
plt.ylabel(r"Population number ($\cdot10^3$)") +
plt.legend(["hare", "lynx", "carrot"], loc=1) +
+
+plot periodicity finder
<matplotlib.legend.Legend object at 0x7f5b3bd745c0>
+
+
+
+
+

Plot its periods

+
import scipy as sp
+
+
ft_populations = sp.fft.fft(populations, axis=0) +
frequencies = sp.fft.fftfreq(populations.shape[0], years[1] - years[0]) +
periods = 1 / frequencies +
+
plt.figure() +
plt.plot(periods, abs(ft_populations) * 1e-3, "o") +
plt.xlim(0, 22) +
plt.xlabel("Period") +
plt.ylabel(r"Power ($\cdot10^3$)") +
+
plt.show() +
+
+plot periodicity finder
/home/runner/work/scientific-python-lectures/scientific-python-lectures/intro/scipy/examples/solutions/plot_periodicity_finder.py:39: RuntimeWarning: divide by zero encountered in divide
+
periods = 1 / frequencies +
+
+

There’s probably a period of around 10 years (obvious from the +plot), but for this crude a method, there’s not enough data to say +much more.

+

Total running time of the script: (0 minutes 0.141 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/auto_examples/solutions/sg_execution_times.html b/intro/scipy/auto_examples/solutions/sg_execution_times.html new file mode 100644 index 000000000..14a767f6e --- /dev/null +++ b/intro/scipy/auto_examples/solutions/sg_execution_times.html @@ -0,0 +1,218 @@ + + + + + + + + Computation times — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Computation times

+

00:01.353 total execution time for 4 files from intro/scipy/auto_examples/solutions:

+
+ + + + + +++++ + + + + + + + + + + + + + + + + + + + + + + + + +

Example

Time

Mem (MB)

Image denoising by FFT (plot_fft_image_denoise.py)

00:00.782

0.0

Simple image blur by convolution with a Gaussian kernel (plot_image_blur.py)

00:00.321

0.0

Crude periodicity finding (plot_periodicity_finder.py)

00:00.141

0.0

Curve fitting: temperature as a function of month of the year (plot_curvefit_temperature_data.py)

00:00.108

0.0

+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/image_processing/image_processing.html b/intro/scipy/image_processing/image_processing.html new file mode 100644 index 000000000..c1ddc0142 --- /dev/null +++ b/intro/scipy/image_processing/image_processing.html @@ -0,0 +1,445 @@ + + + + + + + + Geometrical transformations on images — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +

scipy.ndimage provides manipulation of n-dimensional arrays as +images.

+
+

Geometrical transformations on images

+

Changing orientation, resolution, ..

+
>>> import scipy as sp
+
+
>>> # Load an image +
>>> face = sp.datasets.face(gray=True) +
+
>>> # Shift, rotate and zoom it +
>>> shifted_face = sp.ndimage.shift(face, (50, 50)) +
>>> shifted_face2 = sp.ndimage.shift(face, (50, 50), mode='nearest') +
>>> rotated_face = sp.ndimage.rotate(face, 30) +
>>> cropped_face = face[50:-50, 50:-50] +
>>> zoomed_face = sp.ndimage.zoom(face, 2) +
>>> zoomed_face.shape +
(1536, 2048) +
+
+../../../_images/sphx_glr_plot_image_transform_001.png + +
>>> plt.subplot(151)
+
<Axes: > +
+
>>> plt.imshow(shifted_face, cmap=plt.cm.gray) +
<matplotlib.image.AxesImage object at 0x...> +
+
>>> plt.axis('off') +
(np.float64(-0.5), np.float64(1023.5), np.float64(767.5), np.float64(-0.5)) +
+
>>> # etc. +
+
+
+
+

Image filtering

+

Generate a noisy face:

+
>>> import scipy as sp
+
>>> face = sp.datasets.face(gray=True) +
>>> face = face[:512, -512:] # crop out square on right +
>>> import numpy as np +
>>> noisy_face = np.copy(face).astype(float) +
>>> rng = np.random.default_rng() +
>>> noisy_face += face.std() * 0.5 * rng.standard_normal(face.shape) +
+
+

Apply a variety of filters on it:

+
>>> blurred_face = sp.ndimage.gaussian_filter(noisy_face, sigma=3)
+
>>> median_face = sp.ndimage.median_filter(noisy_face, size=5) +
>>> wiener_face = sp.signal.wiener(noisy_face, (5, 5)) +
+
+../../../_images/sphx_glr_plot_image_filters_001.png + +

Other filters in scipy.ndimage.filters and scipy.signal +can be applied to images.

+ +
+
+

Mathematical morphology

+
+

Tip

+

Mathematical morphology stems from set +theory. It characterizes and transforms geometrical structures. Binary +(black and white) images, in particular, can be transformed using this +theory: the sets to be transformed are the sets of neighboring +non-zero-valued pixels. The theory was also extended to gray-valued +images.

+
+../../../_images/morpho_mat1.png +

Mathematical-morphology operations use a structuring element +in order to modify geometrical structures.

+

Let us first generate a structuring element:

+
>>> el = sp.ndimage.generate_binary_structure(2, 1)
+
>>> el +
array([[False, True, False], +
[...True, True, True], +
[False, True, False]]) +
>>> el.astype(int) +
array([[0, 1, 0], +
[1, 1, 1], +
[0, 1, 0]]) +
+
+
    +
  • Erosion scipy.ndimage.binary_erosion()

    +
    >>> a = np.zeros((7, 7), dtype=int)
    +
    >>> a[1:6, 2:5] = 1 +
    >>> a +
    array([[0, 0, 0, 0, 0, 0, 0], +
    [0, 0, 1, 1, 1, 0, 0], +
    [0, 0, 1, 1, 1, 0, 0], +
    [0, 0, 1, 1, 1, 0, 0], +
    [0, 0, 1, 1, 1, 0, 0], +
    [0, 0, 1, 1, 1, 0, 0], +
    [0, 0, 0, 0, 0, 0, 0]]) +
    >>> sp.ndimage.binary_erosion(a).astype(a.dtype) +
    array([[0, 0, 0, 0, 0, 0, 0], +
    [0, 0, 0, 0, 0, 0, 0], +
    [0, 0, 0, 1, 0, 0, 0], +
    [0, 0, 0, 1, 0, 0, 0], +
    [0, 0, 0, 1, 0, 0, 0], +
    [0, 0, 0, 0, 0, 0, 0], +
    [0, 0, 0, 0, 0, 0, 0]]) +
    >>> # Erosion removes objects smaller than the structure +
    >>> sp.ndimage.binary_erosion(a, structure=np.ones((5,5))).astype(a.dtype) +
    array([[0, 0, 0, 0, 0, 0, 0], +
    [0, 0, 0, 0, 0, 0, 0], +
    [0, 0, 0, 0, 0, 0, 0], +
    [0, 0, 0, 0, 0, 0, 0], +
    [0, 0, 0, 0, 0, 0, 0], +
    [0, 0, 0, 0, 0, 0, 0], +
    [0, 0, 0, 0, 0, 0, 0]]) +
    +
    +
  • +
  • Dilation scipy.ndimage.binary_dilation()

    +
    >>> a = np.zeros((5, 5))
    +
    >>> a[2, 2] = 1 +
    >>> a +
    array([[0., 0., 0., 0., 0.], +
    [0., 0., 0., 0., 0.], +
    [0., 0., 1., 0., 0.], +
    [0., 0., 0., 0., 0.], +
    [0., 0., 0., 0., 0.]]) +
    >>> sp.ndimage.binary_dilation(a).astype(a.dtype) +
    array([[0., 0., 0., 0., 0.], +
    [0., 0., 1., 0., 0.], +
    [0., 1., 1., 1., 0.], +
    [0., 0., 1., 0., 0.], +
    [0., 0., 0., 0., 0.]]) +
    +
    +
  • +
  • Opening scipy.ndimage.binary_opening()

    +
    >>> a = np.zeros((5, 5), dtype=int)
    +
    >>> a[1:4, 1:4] = 1 +
    >>> a[4, 4] = 1 +
    >>> a +
    array([[0, 0, 0, 0, 0], +
    [0, 1, 1, 1, 0], +
    [0, 1, 1, 1, 0], +
    [0, 1, 1, 1, 0], +
    [0, 0, 0, 0, 1]]) +
    >>> # Opening removes small objects +
    >>> sp.ndimage.binary_opening(a, structure=np.ones((3, 3))).astype(int) +
    array([[0, 0, 0, 0, 0], +
    [0, 1, 1, 1, 0], +
    [0, 1, 1, 1, 0], +
    [0, 1, 1, 1, 0], +
    [0, 0, 0, 0, 0]]) +
    >>> # Opening can also smooth corners +
    >>> sp.ndimage.binary_opening(a).astype(int) +
    array([[0, 0, 0, 0, 0], +
    [0, 0, 1, 0, 0], +
    [0, 1, 1, 1, 0], +
    [0, 0, 1, 0, 0], +
    [0, 0, 0, 0, 0]]) +
    +
    +
  • +
  • Closing: scipy.ndimage.binary_closing()

  • +
+ +

An opening operation removes small structures, while a closing operation +fills small holes. Such operations can therefore be used to “clean” an +image.

+
>>> a = np.zeros((50, 50))
+
>>> a[10:-10, 10:-10] = 1 +
>>> rng = np.random.default_rng() +
>>> a += 0.25 * rng.standard_normal(a.shape) +
>>> mask = a>=0.5 +
>>> opened_mask = sp.ndimage.binary_opening(mask) +
>>> closed_mask = sp.ndimage.binary_closing(opened_mask) +
+
+../../../_images/sphx_glr_plot_mathematical_morpho_001.png + + +

For gray-valued images, eroding (resp. dilating) amounts to replacing +a pixel by the minimal (resp. maximal) value among pixels covered by the +structuring element centered on the pixel of interest.

+
>>> a = np.zeros((7, 7), dtype=int)
+
>>> a[1:6, 1:6] = 3 +
>>> a[4, 4] = 2; a[2, 3] = 1 +
>>> a +
array([[0, 0, 0, 0, 0, 0, 0], +
[0, 3, 3, 3, 3, 3, 0], +
[0, 3, 3, 1, 3, 3, 0], +
[0, 3, 3, 3, 3, 3, 0], +
[0, 3, 3, 3, 2, 3, 0], +
[0, 3, 3, 3, 3, 3, 0], +
[0, 0, 0, 0, 0, 0, 0]]) +
>>> sp.ndimage.grey_erosion(a, size=(3, 3)) +
array([[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 1, 1, 1, 0, 0], +
[0, 0, 1, 1, 1, 0, 0], +
[0, 0, 3, 2, 2, 0, 0], +
[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0]]) +
+
+
+
+

Connected components and measurements on images

+

Let us first generate a nice synthetic binary image.

+
>>> x, y = np.indices((100, 100))
+
>>> sig = np.sin(2*np.pi*x/50.) * np.sin(2*np.pi*y/50.) * (1+x*y/50.**2)**2 +
>>> mask = sig > 1 +
+
+../../../_images/sphx_glr_plot_connect_measurements_001.png + +../../../_images/sphx_glr_plot_connect_measurements_002.png + +

scipy.ndimage.label() assigns a different label to each connected +component:

+
>>> labels, nb = sp.ndimage.label(mask)
+
>>> nb +
8 +
+
+

Now compute measurements on each connected component:

+
>>> areas = sp.ndimage.sum(mask, labels, range(1, labels.max()+1))
+
>>> areas # The number of pixels in each connected component +
array([190., 45., 424., 278., 459., 190., 549., 424.]) +
>>> maxima = sp.ndimage.maximum(sig, labels, range(1, labels.max()+1)) +
>>> maxima # The maximum signal in each connected component +
array([ 1.80238238, 1.13527605, 5.51954079, 2.49611818, 6.71673619, +
1.80238238, 16.76547217, 5.51954079]) +
+
+../../../_images/sphx_glr_plot_connect_measurements_003.png + +

Extract the 4th connected component, and crop the array around it:

+
>>> sp.ndimage.find_objects(labels)[3]
+
(slice(30, 48, None), slice(30, 48, None)) +
>>> sl = sp.ndimage.find_objects(labels)[3] +
>>> import matplotlib.pyplot as plt +
>>> plt.imshow(sig[sl]) +
<matplotlib.image.AxesImage object at ...> +
+
+

See the summary exercise on Image processing application: counting bubbles and unmolten grains for a more +advanced example.

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/index.html b/intro/scipy/index.html new file mode 100644 index 000000000..ba038d55a --- /dev/null +++ b/intro/scipy/index.html @@ -0,0 +1,1637 @@ + + + + + + + + 1.5. SciPy : high-level scientific computing — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.5. SciPy : high-level scientific computing

+

Authors: Gaël Varoquaux, Adrien Chauve, Andre Espaze, Emmanuelle Gouillart, Ralf Gommers

+ +
+

Tip

+

scipy can be compared to other standard scientific-computing +libraries, such as the GSL (GNU Scientific Library for C and C++), +or Matlab’s toolboxes. scipy is the core package for scientific +routines in Python; it is meant to operate efficiently on numpy +arrays, so that NumPy and SciPy work hand in hand.

+

Before implementing a routine, it is worth checking if the desired +data processing is not already implemented in SciPy. As +non-professional programmers, scientists often tend to re-invent the +wheel, which leads to buggy, non-optimal, difficult-to-share and +unmaintainable code. By contrast, SciPy’s routines are optimized +and tested, and should therefore be used when possible.

+
+ +
+

Warning

+

This tutorial is far from an introduction to numerical computing. +As enumerating the different submodules and functions in SciPy would +be very boring, we concentrate instead on a few examples to give a +general idea of how to use scipy for scientific computing.

+
+

scipy is composed of task-specific sub-modules:

+ ++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

scipy.cluster

Vector quantization / Kmeans

scipy.constants

Physical and mathematical constants

scipy.fft

Fourier transform

scipy.integrate

Integration routines

scipy.interpolate

Interpolation

scipy.io

Data input and output

scipy.linalg

Linear algebra routines

scipy.ndimage

n-dimensional image package

scipy.odr

Orthogonal distance regression

scipy.optimize

Optimization

scipy.signal

Signal processing

scipy.sparse

Sparse matrices

scipy.spatial

Spatial data structures and algorithms

scipy.special

Any special mathematical functions

scipy.stats

Statistics

+
+

Tip

+

They all depend on numpy, but are mostly independent of each +other. The standard way of importing NumPy and these SciPy modules +is:

+
>>> import numpy as np
+
>>> import scipy as sp +
+
+
+
+

1.5.1. File input/output: scipy.io

+

scipy.io contains functions for loading and saving data in +several common formats including Matlab, IDL, Matrix Market, and +Harwell-Boeing.

+

Matlab files: Loading and saving:

+
>>> import scipy as sp
+
>>> a = np.ones((3, 3)) +
>>> sp.io.savemat('file.mat', {'a': a}) # savemat expects a dictionary +
>>> data = sp.io.loadmat('file.mat') +
>>> data['a'] +
array([[1., 1., 1.], +
[1., 1., 1.], +
[1., 1., 1.]]) +
+
+
+

Warning

+

Python / Matlab mismatch: The Matlab file format does not support 1D arrays.

+
>>> a = np.ones(3)
+
>>> a +
array([1., 1., 1.]) +
>>> a.shape +
(3,) +
>>> sp.io.savemat('file.mat', {'a': a}) +
>>> a2 = sp.io.loadmat('file.mat')['a'] +
>>> a2 +
array([[1., 1., 1.]]) +
>>> a2.shape +
(1, 3) +
+
+

Notice that the original array was a one-dimensional array, whereas the +saved and reloaded array is a two-dimensional array with a single row.

+

For other formats, see the scipy.io documentation.

+
+
+

See also

+ +
+
+
+

1.5.2. Special functions: scipy.special

+

“Special” functions are functions commonly used in science and mathematics that +are not considered to be “elementary” functions. Examples include

+
+
    +
  • the gamma function, scipy.special.gamma(),

  • +
  • the error function, scipy.special.erf(),

  • +
  • Bessel functions, such as scipy.special.jv() +(Bessel function of the first kind), and

  • +
  • elliptic functions, such as scipy.special.ellipj() +(Jacobi elliptic functions).

  • +
+
+

Other special functions are combinations of familiar elementary functions, +but they offer better accuracy or robustness than their naive implementations +would.

+

Most of these function are computed elementwise and follow standard +NumPy broadcasting rules when the input arrays have different shapes. +For example, scipy.special.xlog1py() is mathematically equivalent +to x\log(1 + y).

+
>>> import scipy as sp
+
>>> x = np.asarray([1, 2]) +
>>> y = np.asarray([[3], [4], [5]]) +
>>> res = sp.special.xlog1py(x, y) +
>>> res.shape +
(3, 2) +
>>> ref = x * np.log(1 + y) +
>>> np.allclose(res, ref) +
True +
+
+

However, scipy.special.xlog1py() is numerically favorable for small y, +when explicit addition of 1 would lead to loss of precision due to floating +point truncation error.

+
>>> x = 2.5
+
>>> y = 1e-18 +
>>> x * np.log(1 + y) +
np.float64(0.0) +
>>> sp.special.xlog1py(x, y) +
np.float64(2.5e-18) +
+
+

Many special functions also have “logarithmized” variants. For instance, +the gamma function \Gamma(\cdot) is related to the factorial +function by n! = \Gamma(n + 1), but it extends the domain from the +positive integers to the complex plane.

+
>>> x = np.arange(10)
+
>>> np.allclose(sp.special.gamma(x + 1), sp.special.factorial(x)) +
True +
>>> sp.special.gamma(5) < sp.special.gamma(5.5) < sp.special.gamma(6) +
np.True_ +
+
+

The factorial function grows quickly, and so the gamma function overflows +for moderate values of the argument. However, sometimes only the logarithm +of the gamma function is needed. In such cases, we can compute the logarithm +of the gamma function directly using scipy.special.gammaln().

+
>>> x = [5, 50, 500]
+
>>> np.log(sp.special.gamma(x)) +
array([ 3.17805383, 144.56574395, inf]) +
>>> sp.special.gammaln(x) +
array([ 3.17805383, 144.56574395, 2605.11585036]) +
+
+

Such functions can often be used when the intermediate components of a +calculation would overflow or underflow, but the final result would not. +For example, suppose we wish to compute the ratio +\Gamma(500)/\Gamma(499).

+
>>> a = sp.special.gamma(500)
+
>>> b = sp.special.gamma(499) +
>>> a, b +
(np.float64(inf), np.float64(inf)) +
+
+

Both the numerator and denominator overflow, so performing a / b will +not return the result we seek. However, the magnitude of the result should +be moderate, so the use of logarithms comes to mind. Combining the identities +\log(a/b) = \log(a) - \log(b) and \exp(\log(x)) = x, +we get:

+
>>> log_a = sp.special.gammaln(500)
+
>>> log_b = sp.special.gammaln(499) +
>>> log_res = log_a - log_b +
>>> res = np.exp(log_res) +
>>> res +
np.float64(499.0000000...) +
+
+

Similarly, suppose we wish to compute the difference +\log(\Gamma(500) - \Gamma(499)). For this, we use +scipy.special.logsumexp(), which computes +\log(\exp(x) + \exp(y)) using a numerical trick that avoids overflow.

+
>>> res = sp.special.logsumexp([log_a, log_b],
+
... b=[1, -1]) # weights the terms of the sum +
>>> res +
np.float64(2605.113844343...) +
+
+

For more information about these and many other special functions, see +the documentation of scipy.special.

+
+
+

1.5.3. Linear algebra operations: scipy.linalg

+

scipy.linalg provides a Python interface to efficient, compiled +implementations of standard linear algebra operations: the BLAS (Basic +Linear Algebra Subroutines) and LAPACK (Linear Algebra PACKage) libraries.

+

For example, the scipy.linalg.det() function computes the determinant +of a square matrix:

+
>>> import scipy as sp
+
>>> arr = np.array([[1, 2], +
... [3, 4]]) +
>>> sp.linalg.det(arr) +
np.float64(-2.0) +
+
+

Mathematically, the solution of a linear system Ax = b is x = A^{-1}b, +but explicit inversion of a matrix is numerically unstable and should be avoided. +Instead, use scipy.linalg.solve():

+
>>> A = np.array([[1, 2],
+
... [2, 3]]) +
>>> b = np.array([14, 23]) +
>>> x = sp.linalg.solve(A, b) +
>>> x +
array([4., 5.]) +
>>> np.allclose(A @ x, b) +
True +
+
+

Linear systems with special structure can often be solved more efficiently +than more general systems. For example, systems with triangular matrices +can be solved using scipy.linalg.solve_triangular():

+
>>> A_upper = np.triu(A)
+
>>> A_upper +
array([[1, 2], +
[0, 3]]) +
>>> np.allclose(sp.linalg.solve_triangular(A_upper, b, lower=False), +
... sp.linalg.solve(A_upper, b)) +
True +
+
+

scipy.linalg also features matrix factorizations/decompositions +such as the singular value decomposition.

+
>>> A = np.array([[1, 2],
+
... [2, 3]]) +
>>> U, s, Vh = sp.linalg.svd(A) +
>>> s # singular values +
array([4.23606798, 0.23606798]) +
+
+

The original matrix can be recovered by matrix multiplication of the +factors:

+
>>> S = np.diag(s)  # convert to diagonal matrix before matrix multiplication
+
>>> A2 = U @ S @ Vh +
>>> np.allclose(A2, A) +
True +
>>> A3 = (U * s) @ Vh # more efficient: use array math broadcasting rules! +
>>> np.allclose(A3, A) +
True +
+
+

Many other decompositions (e.g. LU, Cholesky, QR), solvers for structured +linear systems (e.g. triangular, circulant), eigenvalue problem algorithms, +matrix functions (e.g. matrix exponential), and routines for special matrix +creation (e.g. block diagonal, toeplitz) are available in scipy.linalg.

+
+
+

1.5.4. Interpolation: scipy.interpolate

+

scipy.interpolate is used for fitting a function – an “interpolant” – +to experimental or computed data. Once fit, the interpolant can be used to +approximate the underlying function at intermediate points; it can also be used +to compute the integral, derivative, or inverse of the function.

+

Some kinds of interpolants, known as “smoothing splines”, are designed to +generate smooth curves from noisy data. For example, suppose we have +the following data:

+
>>> rng = np.random.default_rng(27446968)
+
>>> measured_time = np.linspace(0, 2*np.pi, 20) +
>>> function = np.sin(measured_time) +
>>> noise = rng.normal(loc=0, scale=0.1, size=20) +
>>> measurements = function + noise +
+
+

scipy.interpolate.make_smoothing_spline() can be used to form a curve +similar to the underlying sine function.

+
>>> smoothing_spline = sp.interpolate.make_smoothing_spline(measured_time, measurements)
+
>>> interpolation_time = np.linspace(0, 2*np.pi, 200) +
>>> smooth_results = smoothing_spline(interpolation_time) +
+
+../../_images/sphx_glr_plot_interpolation_001.png + +

On the other hand, if the data are not noisy, it may be desirable to pass +exactly through each point.

+
>>> interp_spline = sp.interpolate.make_interp_spline(measured_time, function)
+
>>> interp_results = interp_spline(interpolation_time) +
+
+../../_images/sphx_glr_plot_interpolation_002.png + +

The derivative and antiderivative methods of the result object can be used +for differentiation and integration. For the latter, the constant of integration is +assumed to be zero, but we can “wrap” the antiderivative to include a nonzero +constant of integration.

+
>>> d_interp_spline = interp_spline.derivative()
+
>>> d_interp_results = d_interp_spline(interpolation_time) +
>>> i_interp_spline = lambda t: interp_spline.antiderivative()(t) - 1 +
>>> i_interp_results = i_interp_spline(interpolation_time) +
+
+../../_images/sphx_glr_plot_interpolation_003.png + +

For functions that are monotonic on an interval (e.g. \sin from \pi/2 +to 3\pi/2), we can reverse the arguments of make_interp_spline to +interpolate the inverse function. Because the first argument is expected to be +monotonically increasing, we also reverse the order of elements in the arrays +with numpy.flip().

+
>>> i = (measured_time > np.pi/2) & (measured_time < 3*np.pi/2)
+
>>> inverse_spline = sp.interpolate.make_interp_spline(np.flip(function[i]), +
... np.flip(measured_time[i])) +
>>> inverse_spline(0) +
array(3.14159265) +
+
+

See the summary exercise on Maximum wind speed prediction at the Sprogø station for a more +advanced spline interpolation example, and read the +SciPy interpolation tutorial +and the scipy.interpolate documentation for much more information.

+
+
+

1.5.5. Optimization and fit: scipy.optimize

+

scipy.optimize provides algorithms for root finding, curve fitting, +and more general optimization.

+
+

1.5.5.1. Root Finding

+

scipy.optimize.root_scalar() attempts to find a root of a specified +scalar-valued function (i.e., an argument at which the function value is zero). +Like many scipy.optimize functions, the function needs an initial +guess of the solution, which the algorithm will refine until it converges or +recognizes failure. We also provide the derivative to improve the rate of +convergence.

+
>>> def f(x):
+
... return (x-1)*(x-2) +
>>> def df(x): +
... return 2*x - 3 +
>>> x0 = 0 # guess +
>>> res = sp.optimize.root_scalar(f, x0=x0, fprime=df) +
>>> res +
converged: True +
flag: converged +
function_calls: 12 +
iterations: 6 +
root: 1.0 +
method: newton +
+
+
+

Warning

+

None of the functions in scipy.optimize that accept a guess are +guaranteed to converge for all possible guesses! (For example, try +x0=1.5 in the example above, where the derivative of the function is +exactly zero.) If this occurs, try a different guess, adjust the options +(like providing a bracket as shown below), or consider whether SciPy +offers a more appropriate method for the problem.

+
+

Note that only one the root at 1.0 is found. By inspection, we can tell +that there is a second root at 2.0. We can direct the function toward a +particular root by changing the guess or by passing a bracket that contains +only the root we seek.

+
>>> res = sp.optimize.root_scalar(f, bracket=(1.5, 10))
+
>>> res.root +
2.0 +
+
+

For multivariate problems, use scipy.optimize.root().

+
>>> def f(x):
+
... # intersection of unit circle and line from origin +
... return [x[0]**2 + x[1]**2 - 1, +
... x[1] - x[0]] +
>>> res = sp.optimize.root(f, x0=[0, 0]) +
>>> np.allclose(f(res.x), 0, atol=1e-10) +
True +
>>> np.allclose(res.x, np.sqrt(2)/2) +
True +
+
+

Over-constrained problems can be solved in the least-squares +sense using scipy.optimize.root() with method='lm' +(Levenberg-Marquardt).

+
>>> def f(x):
+
... # intersection of unit circle, line from origin, and parabola +
... return [x[0]**2 + x[1]**2 - 1, +
... x[1] - x[0], +
... x[1] - x[0]**2] +
>>> res = sp.optimize.root(f, x0=[1, 1], method='lm') +
>>> res.success +
True +
>>> res.x +
array([0.76096066, 0.66017736]) +
+
+

See the documentation of scipy.optimize.root_scalar() +and scipy.optimize.root() for a variety of other solution +algorithms and options.

+
+
+

1.5.5.2. Curve fitting

+../../_images/sphx_glr_plot_curve_fit_001.png + +

Suppose we have data that is sinusoidal but noisy:

+
>>> x = np.linspace(-5, 5, num=50)  # 50 values between -5 and 5
+
>>> noise = 0.01 * np.cos(100 * x) +
>>> a, b = 2.9, 1.5 +
>>> y = a * np.cos(b * x) + noise +
+
+

We can approximate the underlying amplitude, frequency, and phase +from the data by least squares curve fitting. To begin, we write +a function that accepts the independent variable as the first +argument and all parameters to fit as separate arguments:

+
>>> def f(x, a, b, c):
+
... return a * np.sin(b * x + c) +
+
+../../_images/sphx_glr_plot_curve_fit_002.png + +

We then use scipy.optimize.curve_fit() to find a and b:

+
>>> params, _ = sp.optimize.curve_fit(f, x, y, p0=[2, 1, 3])
+
>>> params +
array([2.900026 , 1.50012043, 1.57079633]) +
>>> ref = [a, b, np.pi/2] # what we'd expect +
>>> np.allclose(params, ref, rtol=1e-3) +
True +
+
+
+
+
+

1.5.5.3. Optimization

+../../_images/sphx_glr_plot_optimize_example1_001.png + +

Suppose we wish to minimize the scalar-valued function of a single +variable f(x) = x^2  + 10 \sin(x):

+
>>> def f(x):
+
... return x**2 + 10*np.sin(x) +
>>> x = np.arange(-5, 5, 0.1) +
>>> plt.plot(x, f(x)) +
[<matplotlib.lines.Line2D object at ...>] +
>>> plt.show() +
+
+

We can see that the function has a local minimizer near x = 3.8 +and a global minimizer near x = -1.3, but +the precise values cannot be determined from the plot.

+

The most appropriate function for this purpose is +scipy.optimize.minimize_scalar(). +Since we know the approximate locations of the minima, we will provide +bounds that restrict the search to the vicinity of the global minimum.

+
>>> res = sp.optimize.minimize_scalar(f, bounds=(-2, -1))
+
>>> res +
message: Solution found. +
success: True +
status: 0 +
fun: -7.9458233756... +
x: -1.306440997... +
nit: 8 +
nfev: 8 +
>>> res.fun == f(res.x) +
np.True_ +
+
+

If we did not already know the approximate location of the global minimum, +we could use one of SciPy’s global minimizers, such as +scipy.optimize.differential_evolution(). We are required to pass +bounds, but they do not need to be tight.

+
>>> bounds=[(-5, 5)]  # list of lower, upper bound for each variable
+
>>> res = sp.optimize.differential_evolution(f, bounds=bounds) +
>>> res +
message: Optimization terminated successfully. +
success: True +
fun: -7.9458233756... +
x: [-1.306e+00] +
nit: 6 +
nfev: 111 +
jac: [ 9.948e-06] +
+
+

For multivariate optimization, a good choice for many problems is +scipy.optimize.minimize(). +Suppose we wish to find the minimum of a quadratic function of two +variables, f(x_0, x_1) = (x_0-1)^2 + (x_1-2)^2.

+
>>> def f(x):
+
... return (x[0] - 1)**2 + (x[1] - 2)**2 +
+
+

Like scipy.optimize.root(), scipy.optimize.minimize() +requires a guess x0. (Note that this is the initial value of +both variables rather than the value of the variable we happened to +label x_0.)

+
>>> res = sp.optimize.minimize(f, x0=[0, 0])
+
>>> res +
message: Optimization terminated successfully. +
success: True +
status: 0 +
fun: 1.70578...e-16 +
x: [ 1.000e+00 2.000e+00] +
nit: 2 +
jac: [ 3.219e-09 -8.462e-09] +
hess_inv: [[ 9.000e-01 -2.000e-01] +
[-2.000e-01 6.000e-01]] +
nfev: 9 +
njev: 3 +
+
+ +

This barely scratches the surface of SciPy’s optimization features, which +include mixed integer linear programming, constrained nonlinear programming, +and the solution of assignment problems. For much more information, see the +documentation of scipy.optimize and the advanced chapter +Mathematical optimization: finding minima of functions.

+ +

See the summary exercise on Non linear least squares curve fitting: application to point extraction in topographical lidar data for another, more +advanced example.

+
+
+
+

1.5.6. Statistics and random numbers: scipy.stats

+

scipy.stats contains fundamental tools for statistics in Python.

+
+

1.5.6.1. Statistical Distributions

+

Consider a random variable distributed according to the standard normal. +We draw a sample consisting of 100000 observations from the random variable. +The normalized histogram of the sample is an estimator of the random +variable’s probability density function (PDF):

+
>>> dist = sp.stats.norm(loc=0, scale=1)  # standard normal distribution
+
>>> sample = dist.rvs(size=100000) # "random variate sample" +
>>> plt.hist(sample, bins=50, density=True, label='normalized histogram') +
>>> x = np.linspace(-5, 5) +
>>> plt.plot(x, dist.pdf(x), label='PDF') +
[<matplotlib.lines.Line2D object at ...>] +
>>> plt.legend() +
<matplotlib.legend.Legend object at ...> +
+
+../../_images/sphx_glr_plot_normal_distribution_001.png + + +

Suppose we knew that the sample had been drawn from a distribution belonging +to the family of normal distributions, but we did not know the particular +distribution’s location (mean) and scale (standard deviation). We perform +maximum likelihood estimation of the unknown parameters using the +distribution family’s fit method:

+
>>> loc, scale = sp.stats.norm.fit(sample)
+
>>> loc +
np.float64(0.0015767005...) +
>>> scale +
np.float64(0.9973396878...) +
+
+

Since we know the true parameters of the distribution from which the +sample was drawn, we are not surprised that these estimates are similar.

+ +
+
+

1.5.6.2. Sample Statistics and Hypothesis Tests

+

The sample mean is an estimator of the mean of the distribution from which +the sample was drawn:

+
>>> np.mean(sample)
+
np.float64(0.001576700508...) +
+
+

NumPy includes some of the most fundamental sample statistics (e.g. +numpy.mean(), numpy.var(), numpy.percentile()); +scipy.stats includes many more. For instance, the geometric mean +is a common measure of central tendency for data that tends to be +distributed over many orders of magnitude.

+
>>> sp.stats.gmean(2**sample)
+
np.float64(1.0010934829...) +
+
+

SciPy also includes a variety of hypothesis tests that produce a +sample statistic and a p-value. For instance, suppose we wish to +test the null hypothesis that sample was drawn from a normal +distribution:

+
>>> res = sp.stats.normaltest(sample)
+
>>> res.statistic +
np.float64(5.20841759...) +
>>> res.pvalue +
np.float64(0.07396163283...) +
+
+

Here, statistic is a sample statistic that tends to be high for +samples that are drawn from non-normal distributions. pvalue is +the probability of observing such a high value of the statistic for +a sample that has been drawn from a normal distribution. If the +p-value is unusually small, this may be taken as evidence that +sample was not drawn from the normal distribution. Our statistic +and p-value are moderate, so the test is inconclusive.

+

There are many other features of scipy.stats, including circular +statistics, quasi-Monte Carlo methods, and resampling methods. +For much more information, see the documentation of scipy.stats +and the advanced chapter statistics.

+
+
+
+

1.5.7. Numerical integration: scipy.integrate

+
+

1.5.7.1. Quadrature

+

Suppose we wish to compute the definite integral +\int_0^{\pi / 2} \sin(t) dt numerically. scipy.integrate.quad() +chooses one of several adaptive techniques depending on the parameters, and +is therefore the recommended first choice for integration of function of a single variable:

+
>>> integral, error_estimate = sp.integrate.quad(np.sin, 0, np.pi/2)
+
>>> np.allclose(integral, 1) # numerical result ~ analytical result +
True +
>>> abs(integral - 1) < error_estimate # actual error < estimated error +
True +
+
+

Other functions for numerical quadrature, including integration of +multivariate functions and approximating integrals from samples, are available +in scipy.integrate.

+
+
+

1.5.7.2. Initial Value Problems

+

scipy.integrate also features routines for integrating Ordinary +Differential Equations (ODE). +For example, scipy.integrate.solve_ivp() integrates ODEs of the form:

+
+

\frac{dy}{dt} = f(t, y(t))

+

from an initial time t_0 and initial state y(t=t_0)=t_0 to a final +time t_f or until an event occurs (e.g. a specified state is reached).

+

As an introduction, consider the initial value problem given by +\frac{dy}{dt} = -2 y and the initial condition y(t=0) = 1 on +the interval t = 0 \dots 4. We begin by defining a callable that +computes f(t, y(t)) given the current time and state.

+
>>> def f(t, y):
+
... return -2 * y +
+
+

Then, to compute y as a function of time:

+
>>> t_span = (0, 4)  # time interval
+
>>> t_eval = np.linspace(*t_span) # times at which to evaluate `y` +
>>> y0 = [1,] # initial state +
>>> res = sp.integrate.solve_ivp(f, t_span=t_span, y0=y0, t_eval=t_eval) +
+
+

and plot the result:

+
>>> plt.plot(res.t, res.y[0])
+
[<matplotlib.lines.Line2D object at ...>] +
>>> plt.xlabel('t') +
Text(0.5, ..., 't') +
>>> plt.ylabel('y') +
Text(..., 0.5, 'y') +
>>> plt.title('Solution of Initial Value Problem') +
Text(0.5, 1.0, 'Solution of Initial Value Problem') +
+
+../../_images/sphx_glr_plot_solve_ivp_simple_001.png + +

Let us integrate a more complex ODE: a damped +spring-mass oscillator. +The position of a mass attached to a spring obeys the 2nd order ODE +\ddot{y} + 2 \zeta \omega_0  \dot{y} + \omega_0^2 y = 0 with natural frequency +\omega_0 = \sqrt{k/m}, damping ratio \zeta = c/(2 m \omega_0), +spring constant k, mass m, and damping coefficient c.

+

Before using scipy.integrate.solve_ivp(), the 2nd order ODE +needs to be transformed into a system of first-order ODEs. Note that

+
+

\frac{dy}{dt} = \dot{y}
+\frac{d\dot{y}}{dt} = \ddot{y} = -(2 \zeta \omega_0  \dot{y} + \omega_0^2 y)

+

If we define z = [z_0, z_1] where z_0 = y and z_1 = \dot{y}, +then the first order equation:

+
+

\frac{dz}{dt} =
+\begin{bmatrix}
+    \frac{dz_0}{dt} \\
+    \frac{dz_1}{dt}
+\end{bmatrix} =
+\begin{bmatrix}
+    z_1  \\
+    -(2 \zeta \omega_0  z_1 + \omega_0^2 z_0)
+\end{bmatrix}

+

is equivalent to the original second order equation.

+

We set:

+
>>> m = 0.5  # kg
+
>>> k = 4 # N/m +
>>> c = 0.4 # N s/m +
>>> zeta = c / (2 * m * np.sqrt(k/m)) +
>>> omega = np.sqrt(k / m) +
+
+

and define the function that computes \dot{z} = f(t, z(t)):

+
>>> def f(t, z, zeta, omega):
+
... return (z[1], -2.0 * zeta * omega * z[1] - omega**2 * z[0]) +
+
+../../_images/sphx_glr_plot_solve_ivp_damped_spring_mass_001.png + +

Integration of the system follows:

+
>>> t_span = (0, 10)
+
>>> t_eval = np.linspace(*t_span, 100) +
>>> z0 = [1, 0] +
>>> res = sp.integrate.solve_ivp(f, t_span, z0, t_eval=t_eval, +
... args=(zeta, omega), method='LSODA') +
+
+
+

Tip

+

With the option method=’LSODA’, scipy.integrate.solve_ivp() uses the LSODA +(Livermore Solver for Ordinary Differential equations with Automatic method switching +for stiff and non-stiff problems). See the ODEPACK Fortran library for more details.

+
+
+

See also

+

Partial Differental Equations

+

There is no Partial Differential Equations (PDE) solver in SciPy. +Some Python packages for solving PDE’s are available, such as fipy +or SfePy.

+
+
+
+
+

1.5.8. Fast Fourier transforms: scipy.fft

+

The scipy.fft module computes fast Fourier transforms (FFTs) +and offers utilities to handle them. Some important functions are:

+ +
+

+
+

As an illustration, a (noisy) input signal (sig), and its FFT:

+
>>> sig_fft = sp.fft.fft(sig)  
+
>>> freqs = sp.fft.fftfreq(sig.size, d=time_step) +
+
+ ++++ + + + + + + + + + + +

signal_fig

fft_fig

Signal

FFT

+

As the signal comes from a real-valued function, the Fourier transform is +symmetric.

+

The peak signal frequency can be found with freqs[power.argmax()]

+../../_images/sphx_glr_plot_fftpack_003.png + +

Setting the Fourier component above this frequency to zero and inverting +the FFT with scipy.fft.ifft(), gives a filtered signal.

+
+

Note

+

The code of this example can be found here

+
+ +
+

+
+

Fully worked examples:

+ ++++ + + + + + + + + + + +

Crude periodicity finding (link)

Gaussian image blur (link)

periodicity_finding

image_blur

+
+

+
+ +
+

+
+
+
+

1.5.9. Signal processing: scipy.signal

+
+

Tip

+

scipy.signal is for typical signal processing: 1D, +regularly-sampled signals.

+
+../../_images/sphx_glr_plot_resample_001.png + +

Resampling scipy.signal.resample(): resample a signal to n +points using FFT.

+
>>> t = np.linspace(0, 5, 100)
+
>>> x = np.sin(t) +
+
>>> x_resampled = sp.signal.resample(x, 25) +
+
>>> plt.plot(t, x) +
[<matplotlib.lines.Line2D object at ...>] +
>>> plt.plot(t[::4], x_resampled, 'ko') +
[<matplotlib.lines.Line2D object at ...>] +
+
+
+

Tip

+

Notice how on the side of the window the resampling is less accurate +and has a rippling effect.

+

This resampling is different from the interpolation provided by scipy.interpolate as it +only applies to regularly sampled data.

+
+../../_images/sphx_glr_plot_detrend_001.png + +

Detrending scipy.signal.detrend(): remove linear trend from signal:

+
>>> t = np.linspace(0, 5, 100)
+
>>> rng = np.random.default_rng() +
>>> x = t + rng.normal(size=100) +
+
>>> x_detrended = sp.signal.detrend(x) +
+
>>> plt.plot(t, x) +
[<matplotlib.lines.Line2D object at ...>] +
>>> plt.plot(t, x_detrended) +
[<matplotlib.lines.Line2D object at ...>] +
+
+

Filtering: +For non-linear filtering, scipy.signal has filtering (median +filter scipy.signal.medfilt(), Wiener scipy.signal.wiener()), +but we will discuss this in the image section.

+
+

Tip

+

scipy.signal also has a full-blown set of tools for the design +of linear filter (finite and infinite response filters), but this is +out of the scope of this tutorial.

+
+

Spectral analysis: +scipy.signal.spectrogram() compute a spectrogram –frequency +spectrums over consecutive time windows–, while +scipy.signal.welch() comptes a power spectrum density (PSD).

+

chirp_fig spectrogram_fig psd_fig

+
+
+

1.5.10. Image manipulation: scipy.ndimage

+

scipy.ndimage provides manipulation of n-dimensional arrays as +images.

+
+

1.5.10.1. Geometrical transformations on images

+

Changing orientation, resolution, ..

+
>>> import scipy as sp
+
+
>>> # Load an image +
>>> face = sp.datasets.face(gray=True) +
+
>>> # Shift, rotate and zoom it +
>>> shifted_face = sp.ndimage.shift(face, (50, 50)) +
>>> shifted_face2 = sp.ndimage.shift(face, (50, 50), mode='nearest') +
>>> rotated_face = sp.ndimage.rotate(face, 30) +
>>> cropped_face = face[50:-50, 50:-50] +
>>> zoomed_face = sp.ndimage.zoom(face, 2) +
>>> zoomed_face.shape +
(1536, 2048) +
+
+../../_images/sphx_glr_plot_image_transform_001.png + +
>>> plt.subplot(151)
+
<Axes: > +
+
>>> plt.imshow(shifted_face, cmap=plt.cm.gray) +
<matplotlib.image.AxesImage object at 0x...> +
+
>>> plt.axis('off') +
(np.float64(-0.5), np.float64(1023.5), np.float64(767.5), np.float64(-0.5)) +
+
>>> # etc. +
+
+
+
+

1.5.10.2. Image filtering

+

Generate a noisy face:

+
>>> import scipy as sp
+
>>> face = sp.datasets.face(gray=True) +
>>> face = face[:512, -512:] # crop out square on right +
>>> import numpy as np +
>>> noisy_face = np.copy(face).astype(float) +
>>> rng = np.random.default_rng() +
>>> noisy_face += face.std() * 0.5 * rng.standard_normal(face.shape) +
+
+

Apply a variety of filters on it:

+
>>> blurred_face = sp.ndimage.gaussian_filter(noisy_face, sigma=3)
+
>>> median_face = sp.ndimage.median_filter(noisy_face, size=5) +
>>> wiener_face = sp.signal.wiener(noisy_face, (5, 5)) +
+
+../../_images/sphx_glr_plot_image_filters_001.png + +

Other filters in scipy.ndimage.filters and scipy.signal +can be applied to images.

+ +
+
+

1.5.10.3. Mathematical morphology

+
+

Tip

+

Mathematical morphology stems from set +theory. It characterizes and transforms geometrical structures. Binary +(black and white) images, in particular, can be transformed using this +theory: the sets to be transformed are the sets of neighboring +non-zero-valued pixels. The theory was also extended to gray-valued +images.

+
+../../_images/morpho_mat1.png +

Mathematical-morphology operations use a structuring element +in order to modify geometrical structures.

+

Let us first generate a structuring element:

+
>>> el = sp.ndimage.generate_binary_structure(2, 1)
+
>>> el +
array([[False, True, False], +
[...True, True, True], +
[False, True, False]]) +
>>> el.astype(int) +
array([[0, 1, 0], +
[1, 1, 1], +
[0, 1, 0]]) +
+
+
    +
  • Erosion scipy.ndimage.binary_erosion()

    +
    >>> a = np.zeros((7, 7), dtype=int)
    +
    >>> a[1:6, 2:5] = 1 +
    >>> a +
    array([[0, 0, 0, 0, 0, 0, 0], +
    [0, 0, 1, 1, 1, 0, 0], +
    [0, 0, 1, 1, 1, 0, 0], +
    [0, 0, 1, 1, 1, 0, 0], +
    [0, 0, 1, 1, 1, 0, 0], +
    [0, 0, 1, 1, 1, 0, 0], +
    [0, 0, 0, 0, 0, 0, 0]]) +
    >>> sp.ndimage.binary_erosion(a).astype(a.dtype) +
    array([[0, 0, 0, 0, 0, 0, 0], +
    [0, 0, 0, 0, 0, 0, 0], +
    [0, 0, 0, 1, 0, 0, 0], +
    [0, 0, 0, 1, 0, 0, 0], +
    [0, 0, 0, 1, 0, 0, 0], +
    [0, 0, 0, 0, 0, 0, 0], +
    [0, 0, 0, 0, 0, 0, 0]]) +
    >>> # Erosion removes objects smaller than the structure +
    >>> sp.ndimage.binary_erosion(a, structure=np.ones((5,5))).astype(a.dtype) +
    array([[0, 0, 0, 0, 0, 0, 0], +
    [0, 0, 0, 0, 0, 0, 0], +
    [0, 0, 0, 0, 0, 0, 0], +
    [0, 0, 0, 0, 0, 0, 0], +
    [0, 0, 0, 0, 0, 0, 0], +
    [0, 0, 0, 0, 0, 0, 0], +
    [0, 0, 0, 0, 0, 0, 0]]) +
    +
    +
  • +
  • Dilation scipy.ndimage.binary_dilation()

    +
    >>> a = np.zeros((5, 5))
    +
    >>> a[2, 2] = 1 +
    >>> a +
    array([[0., 0., 0., 0., 0.], +
    [0., 0., 0., 0., 0.], +
    [0., 0., 1., 0., 0.], +
    [0., 0., 0., 0., 0.], +
    [0., 0., 0., 0., 0.]]) +
    >>> sp.ndimage.binary_dilation(a).astype(a.dtype) +
    array([[0., 0., 0., 0., 0.], +
    [0., 0., 1., 0., 0.], +
    [0., 1., 1., 1., 0.], +
    [0., 0., 1., 0., 0.], +
    [0., 0., 0., 0., 0.]]) +
    +
    +
  • +
  • Opening scipy.ndimage.binary_opening()

    +
    >>> a = np.zeros((5, 5), dtype=int)
    +
    >>> a[1:4, 1:4] = 1 +
    >>> a[4, 4] = 1 +
    >>> a +
    array([[0, 0, 0, 0, 0], +
    [0, 1, 1, 1, 0], +
    [0, 1, 1, 1, 0], +
    [0, 1, 1, 1, 0], +
    [0, 0, 0, 0, 1]]) +
    >>> # Opening removes small objects +
    >>> sp.ndimage.binary_opening(a, structure=np.ones((3, 3))).astype(int) +
    array([[0, 0, 0, 0, 0], +
    [0, 1, 1, 1, 0], +
    [0, 1, 1, 1, 0], +
    [0, 1, 1, 1, 0], +
    [0, 0, 0, 0, 0]]) +
    >>> # Opening can also smooth corners +
    >>> sp.ndimage.binary_opening(a).astype(int) +
    array([[0, 0, 0, 0, 0], +
    [0, 0, 1, 0, 0], +
    [0, 1, 1, 1, 0], +
    [0, 0, 1, 0, 0], +
    [0, 0, 0, 0, 0]]) +
    +
    +
  • +
  • Closing: scipy.ndimage.binary_closing()

  • +
+ +

An opening operation removes small structures, while a closing operation +fills small holes. Such operations can therefore be used to “clean” an +image.

+
>>> a = np.zeros((50, 50))
+
>>> a[10:-10, 10:-10] = 1 +
>>> rng = np.random.default_rng() +
>>> a += 0.25 * rng.standard_normal(a.shape) +
>>> mask = a>=0.5 +
>>> opened_mask = sp.ndimage.binary_opening(mask) +
>>> closed_mask = sp.ndimage.binary_closing(opened_mask) +
+
+../../_images/sphx_glr_plot_mathematical_morpho_001.png + + +

For gray-valued images, eroding (resp. dilating) amounts to replacing +a pixel by the minimal (resp. maximal) value among pixels covered by the +structuring element centered on the pixel of interest.

+
>>> a = np.zeros((7, 7), dtype=int)
+
>>> a[1:6, 1:6] = 3 +
>>> a[4, 4] = 2; a[2, 3] = 1 +
>>> a +
array([[0, 0, 0, 0, 0, 0, 0], +
[0, 3, 3, 3, 3, 3, 0], +
[0, 3, 3, 1, 3, 3, 0], +
[0, 3, 3, 3, 3, 3, 0], +
[0, 3, 3, 3, 2, 3, 0], +
[0, 3, 3, 3, 3, 3, 0], +
[0, 0, 0, 0, 0, 0, 0]]) +
>>> sp.ndimage.grey_erosion(a, size=(3, 3)) +
array([[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 1, 1, 1, 0, 0], +
[0, 0, 1, 1, 1, 0, 0], +
[0, 0, 3, 2, 2, 0, 0], +
[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0]]) +
+
+
+
+

1.5.10.4. Connected components and measurements on images

+

Let us first generate a nice synthetic binary image.

+
>>> x, y = np.indices((100, 100))
+
>>> sig = np.sin(2*np.pi*x/50.) * np.sin(2*np.pi*y/50.) * (1+x*y/50.**2)**2 +
>>> mask = sig > 1 +
+
+../../_images/sphx_glr_plot_connect_measurements_001.png + +../../_images/sphx_glr_plot_connect_measurements_002.png + +

scipy.ndimage.label() assigns a different label to each connected +component:

+
>>> labels, nb = sp.ndimage.label(mask)
+
>>> nb +
8 +
+
+

Now compute measurements on each connected component:

+
>>> areas = sp.ndimage.sum(mask, labels, range(1, labels.max()+1))
+
>>> areas # The number of pixels in each connected component +
array([190., 45., 424., 278., 459., 190., 549., 424.]) +
>>> maxima = sp.ndimage.maximum(sig, labels, range(1, labels.max()+1)) +
>>> maxima # The maximum signal in each connected component +
array([ 1.80238238, 1.13527605, 5.51954079, 2.49611818, 6.71673619, +
1.80238238, 16.76547217, 5.51954079]) +
+
+../../_images/sphx_glr_plot_connect_measurements_003.png + +

Extract the 4th connected component, and crop the array around it:

+
>>> sp.ndimage.find_objects(labels)[3]
+
(slice(30, 48, None), slice(30, 48, None)) +
>>> sl = sp.ndimage.find_objects(labels)[3] +
>>> import matplotlib.pyplot as plt +
>>> plt.imshow(sig[sl]) +
<matplotlib.image.AxesImage object at ...> +
+
+

See the summary exercise on Image processing application: counting bubbles and unmolten grains for a more +advanced example.

+
+
+
+

1.5.11. Summary exercises on scientific computing

+

The summary exercises use mainly NumPy, SciPy and Matplotlib. They provide some +real-life examples of scientific computing with Python. Now that the basics of +working with NumPy and SciPy have been introduced, the interested user is +invited to try these exercises.

+

Exercises:

+ +

Proposed solutions:

+ +
+
+

1.5.12. Full code examples for the SciPy chapter

+
+

Finding the minimum of a smooth function

+
Finding the minimum of a smooth function
+
+

Resample a signal with scipy.signal.resample

+
Resample a signal with scipy.signal.resample
+
+

Detrending a signal

+
Detrending a signal
+
+

Integrating a simple ODE

+
Integrating a simple ODE
+
+

Normal distribution: histogram and PDF

+
Normal distribution: histogram and PDF
+
+

Integrate the Damped spring-mass oscillator

+
Integrate the Damped spring-mass oscillator
+
+

Comparing 2 sets of samples from Gaussians

+
Comparing 2 sets of samples from Gaussians
+
+

Curve fitting

+
Curve fitting
+
+

Spectrogram, power spectral density

+
Spectrogram, power spectral density
+
+

Demo mathematical morphology

+
Demo mathematical morphology
+
+

Plot geometrical transformations on images

+
Plot geometrical transformations on images
+
+

Demo connected components

+
Demo connected components
+
+

Minima and roots of a function

+
Minima and roots of a function
+
+

Plot filtering on images

+
Plot filtering on images
+
+

Optimization of a two-parameter function

+
Optimization of a two-parameter function
+
+

Plotting and manipulating FFTs for filtering

+
Plotting and manipulating FFTs for filtering
+
+

A demo of 1D interpolation

+
A demo of 1D interpolation
+
+
+
+

1.5.12.18. Solutions of the exercises for SciPy

+
+

Crude periodicity finding

+
Crude periodicity finding
+
+

Curve fitting: temperature as a function of month of the year

+
Curve fitting: temperature as a function of month of the year
+
+

Simple image blur by convolution with a Gaussian kernel

+
Simple image blur by convolution with a Gaussian kernel
+
+

Image denoising by FFT

+
Image denoising by FFT
+
+
+ +

Gallery generated by Sphinx-Gallery

+
+

See also

+

References to go further

+ +
+
+
+

+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/solutions.html b/intro/scipy/solutions.html new file mode 100644 index 000000000..0d1529253 --- /dev/null +++ b/intro/scipy/solutions.html @@ -0,0 +1,433 @@ + + + + + + + + Solutions — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Solutions

+
+

The Pi Wallis Solution

+

Compute the decimals of Pi using the Wallis formula:

+
"""
+
The correction for the calculation of pi using the Wallis formula. +
""" +
+
from functools import reduce +
+
+
pi = 3.14159265358979312 +
+
my_pi = 1.0 +
+
for i in range(1, 100000): +
my_pi *= 4 * i**2 / (4 * i**2 - 1.0) +
+
my_pi *= 2 +
+
print(pi) +
print(my_pi) +
print(abs(pi - my_pi)) +
+
############################################################################### +
num = 1 +
den = 1 +
for i in range(1, 100000): +
tmp = 4 * i * i +
num *= tmp +
den *= tmp - 1 +
+
better_pi = 2 * (num / den) +
+
print(pi) +
print(better_pi) +
print(abs(pi - better_pi)) +
print(abs(my_pi - better_pi)) +
+
############################################################################### +
# Solution in a single line using more advanced constructs (reduce, lambda, +
# list comprehensions +
print( +
2 +
* reduce( +
lambda x, y: x * y, +
[float(4 * (i**2)) / ((4 * (i**2)) - 1) for i in range(1, 100000)], +
) +
) +
+
+
+
+

The Quicksort Solution

+

Implement the quicksort algorithm, as defined by wikipedia:

+
function quicksort(array)
+
var list less, greater +
if length(array) ≤ 1 +
return array +
select and remove a pivot value pivot from array +
for each x in array +
if x ≤ pivot then append x to less +
else append x to greater +
return concatenate(quicksort(less), pivot, quicksort(greater)) +
+
+
"""
+
Implement the quick sort algorithm. +
""" +
+
+
def qsort(lst): +
"""Quick sort: returns a sorted copy of the list.""" +
if len(lst) <= 1: +
return lst +
pivot, rest = lst[0], lst[1:] +
+
# Could use list comprehension: +
# less_than = [ lt for lt in rest if lt < pivot ] +
+
less_than = [] +
for lt in rest: +
if lt < pivot: +
less_than.append(lt) +
+
# Could use list comprehension: +
# greater_equal = [ ge for ge in rest if ge >= pivot ] +
+
greater_equal = [] +
for ge in rest: +
if ge >= pivot: +
greater_equal.append(ge) +
return qsort(less_than) + [pivot] + qsort(greater_equal) +
+
+
# And now check that qsort does sort: +
assert qsort(range(10)) == range(10) +
assert qsort(range(10)[::-1]) == range(10) +
assert qsort([1, 4, 2, 5, 3]) == sorted([1, 4, 2, 5, 3]) +
+
+
+
+

Fibonacci sequence

+

Write a function that displays the n first terms of the Fibonacci +sequence, defined by:

+
    +
  • u_0 = 1; u_1 = 1

  • +
  • u_(n+2) = u_(n+1) + u_n

  • +
+
>>> def fib(n):
+
... """Display the n first terms of Fibonacci sequence""" +
... a, b = 0, 1 +
... i = 0 +
... while i < n: +
... print(b) +
... a, b = b, a+b +
... i +=1 +
... +
>>> fib(10) +
1 +
1 +
2 +
3 +
5 +
8 +
13 +
21 +
34 +
55 +
+
+
+
+

The Directory Listing Solution

+

Implement a script that takes a directory name as argument, and +returns the list of ‘.py’ files, sorted by name length.

+

Hint: try to understand the docstring of list.sort

+
"""
+
Script to list all the '.py' files in a directory, in the order of file +
name length. +
""" +
+
import os +
import sys +
+
+
def filter_and_sort(file_list): +
"""Out of a list of file names, returns only the ones ending by +
'.py', ordered with increasing file name length. +
""" +
file_list = [filename for filename in file_list if filename.endswith(".py")] +
+
def key(item): +
return len(item) +
+
file_list.sort(key=key) +
return file_list +
+
+
if __name__ == "__main__": +
file_list = os.listdir(sys.argv[-1]) +
sorted_file_list = filter_and_sort(file_list) +
print(sorted_file_list) +
+
+
+
+

The Data File I/O Solution

+

Write a function that will load the column of numbers in data.txt +and calculate the min, max and sum values.

+

Data file:

+
10.2
+
43.1 +
32.6 +
32.5 +
61.3 +
58.2 +
+
+

Solution:

+
"""
+
=================== +
I/O script example +
=================== +
+
Script to read in a column of numbers and calculate the min, max and sum. +
+
Data is stored in data.txt. +
""" +
+
+
def load_data(filename): +
fp = open(filename) +
data_string = fp.read() +
fp.close() +
+
data = [] +
for x in data_string.split(): +
# Data is read in as a string. We need to convert it to floats +
data.append(float(x)) +
+
# Could instead use the following one line with list comprehensions! +
# data = [float(x) for x in data_string.split()] +
return data +
+
+
if __name__ == "__main__": +
data = load_data("data.txt") +
# Python provides these basic math functions +
print(f"min: {min(data):f}") +
print(f"max: {max(data):f}") +
print(f"sum: {sum(data):f}") +
+
+
+
+

The PYTHONPATH Search Solution

+

Write a program to search your PYTHONPATH for the module site.py.

+
"""Script to search the PYTHONPATH for the module site.py"""
+
+
import os +
import sys +
import glob +
+
+
def find_module(module): +
result = [] +
# Loop over the list of paths in sys.path +
for subdir in sys.path: +
# Join the subdir path with the module we're searching for +
pth = os.path.join(subdir, module) +
# Use glob to test if the pth is exists +
res = glob.glob(pth) +
# glob returns a list, if it is not empty, the pth exists +
if len(res) > 0: +
result.append(res) +
return result +
+
+
if __name__ == "__main__": +
result = find_module("site.py") +
print(result) +
+
+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/summary-exercises/answers_image_processing.html b/intro/scipy/summary-exercises/answers_image_processing.html new file mode 100644 index 000000000..af8711f15 --- /dev/null +++ b/intro/scipy/summary-exercises/answers_image_processing.html @@ -0,0 +1,274 @@ + + + + + + + + 1.5.11.4. Example of solution for the image processing exercise: unmolten grains in glass — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
>>> import numpy as np
+
>>> import matplotlib.pyplot as plt +
>>> import scipy as sp +
+
+
+

1.5.11.4. Example of solution for the image processing exercise: unmolten grains in glass

+../../../_images/MV_HFV_012.jpg +
    +
  1. Open the image file MV_HFV_012.jpg and display it. Browse through the +keyword arguments in the docstring of imshow to display the image +with the “right” orientation (origin in the bottom left corner, and not +the upper left corner as for standard arrays).

    +
    >>> dat = plt.imread('data/MV_HFV_012.jpg')
    +
    +
    +
  2. +
  3. Crop the image to remove the lower panel with measure information.

    +
    >>> dat = dat[:-60]
    +
    +
    +
  4. +
  5. Slightly filter the image with a median filter in order to refine its +histogram. Check how the histogram changes.

    +
    >>> filtdat = sp.ndimage.median_filter(dat, size=(7,7))
    +
    >>> hi_dat = np.histogram(dat, bins=np.arange(256)) +
    >>> hi_filtdat = np.histogram(filtdat, bins=np.arange(256)) +
    +
    +../../../_images/exo_histos.png +
  6. +
  7. Using the histogram of the filtered image, determine thresholds that +allow to define masks for sand pixels, glass pixels and bubble pixels. +Other option (homework): write a function that determines automatically +the thresholds from the minima of the histogram.

    +
    >>> void = filtdat <= 50
    +
    >>> sand = np.logical_and(filtdat > 50, filtdat <= 114) +
    >>> glass = filtdat > 114 +
    +
    +
  8. +
  9. Display an image in which the three phases are colored with three +different colors.

    +
    >>> phases = void.astype(int) + 2*glass.astype(int) + 3*sand.astype(int)
    +
    +
    +../../../_images/three_phases.png +
  10. +
  11. Use mathematical morphology to clean the different phases.

    +
    >>> sand_op = sp.ndimage.binary_opening(sand, iterations=2)
    +
    +
    +
  12. +
  13. Attribute labels to all bubbles and sand grains, and remove from the +sand mask grains that are smaller than 10 pixels. To do so, use +sp.ndimage.sum or np.bincount to compute the grain sizes.

    +
    >>> sand_labels, sand_nb = sp.ndimage.label(sand_op)
    +
    >>> sand_areas = np.array(sp.ndimage.sum(sand_op, sand_labels, np.arange(sand_labels.max()+1))) +
    >>> mask = sand_areas > 100 +
    >>> remove_small_sand = mask[sand_labels.ravel()].reshape(sand_labels.shape) +
    +
    +../../../_images/sands.png +
  14. +
  15. Compute the mean size of bubbles.

    +
    >>> bubbles_labels, bubbles_nb = sp.ndimage.label(void)
    +
    >>> bubbles_areas = np.bincount(bubbles_labels.ravel())[1:] +
    >>> mean_bubble_size = bubbles_areas.mean() +
    >>> median_bubble_size = np.median(bubbles_areas) +
    >>> mean_bubble_size, median_bubble_size +
    (np.float64(1699.875), np.float64(65.0)) +
    +
    +
  16. +
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/summary-exercises/auto_examples/index.html b/intro/scipy/summary-exercises/auto_examples/index.html new file mode 100644 index 000000000..b9e8c8a27 --- /dev/null +++ b/intro/scipy/summary-exercises/auto_examples/index.html @@ -0,0 +1,207 @@ + + + + + + + + Examples for the summary excercices — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Examples for the summary excercices

+
+

The lidar system, data (2 of 2 datasets)

+
The lidar system, data (2 of 2 datasets)
+
+

The lidar system, data (1 of 2 datasets)

+
The lidar system, data (1 of 2 datasets)
+
+

The Gumbell distribution, results

+
The Gumbell distribution, results
+
+

The lidar system, data and fit (1 of 2 datasets)

+
The lidar system, data and fit (1 of 2 datasets)
+
+

The lidar system, data and fit (2 of 2 datasets)

+
The lidar system, data and fit (2 of 2 datasets)
+
+

Cumulative wind speed prediction

+
Cumulative wind speed prediction
+
+

The Gumbell distribution

+
The Gumbell distribution
+
+
+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/summary-exercises/auto_examples/plot_cumulative_wind_speed_prediction.html b/intro/scipy/summary-exercises/auto_examples/plot_cumulative_wind_speed_prediction.html new file mode 100644 index 000000000..d420d0162 --- /dev/null +++ b/intro/scipy/summary-exercises/auto_examples/plot_cumulative_wind_speed_prediction.html @@ -0,0 +1,225 @@ + + + + + + + + Cumulative wind speed prediction — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Cumulative wind speed prediction

+

Generate the image cumulative-wind-speed-prediction.png +for the interpolate section of scipy.rst.

+plot cumulative wind speed prediction
Text(42.722222222222214, 0.5, 'Cumulative probability')
+
+
+
+

+
+
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
max_speeds = np.load("max-speeds.npy") +
years_nb = max_speeds.shape[0] +
+
cprob = (np.arange(years_nb, dtype=np.float32) + 1) / (years_nb + 1) +
sorted_max_speeds = np.sort(max_speeds) +
speed_spline = sp.interpolate.UnivariateSpline(cprob, sorted_max_speeds) +
nprob = np.linspace(0, 1, 100) +
fitted_max_speeds = speed_spline(nprob) +
+
fifty_prob = 1.0 - 0.02 +
fifty_wind = speed_spline(fifty_prob) +
+
plt.figure() +
plt.plot(sorted_max_speeds, cprob, "o") +
plt.plot(fitted_max_speeds, nprob, "g--") +
plt.plot([fifty_wind], [fifty_prob], "o", ms=8.0, mfc="y", mec="y") +
plt.text(30, 0.05, rf"$V_{{50}} = {fifty_wind:.2f} \, m/s$") +
plt.plot([fifty_wind, fifty_wind], [plt.axis()[2], fifty_prob], "k--") +
plt.xlabel("Annual wind speed maxima [$m/s$]") +
plt.ylabel("Cumulative probability") +
+
+

Total running time of the script: (0 minutes 0.077 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/summary-exercises/auto_examples/plot_gumbell_wind_speed_prediction.html b/intro/scipy/summary-exercises/auto_examples/plot_gumbell_wind_speed_prediction.html new file mode 100644 index 000000000..83222bae2 --- /dev/null +++ b/intro/scipy/summary-exercises/auto_examples/plot_gumbell_wind_speed_prediction.html @@ -0,0 +1,226 @@ + + + + + + + + The Gumbell distribution — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

The Gumbell distribution

+

Generate the exercise results on the Gumbell distribution

+plot gumbell wind speed prediction
import numpy as np
+
import scipy as sp +
import matplotlib.pyplot as plt +
+
+
def gumbell_dist(arr): +
return -np.log(-np.log(arr)) +
+
+
years_nb = 21 +
wspeeds = np.load("sprog-windspeeds.npy") +
max_speeds = np.array([arr.max() for arr in np.array_split(wspeeds, years_nb)]) +
sorted_max_speeds = np.sort(max_speeds) +
+
cprob = (np.arange(years_nb, dtype=np.float32) + 1) / (years_nb + 1) +
gprob = gumbell_dist(cprob) +
speed_spline = sp.interpolate.UnivariateSpline(gprob, sorted_max_speeds, k=1) +
nprob = gumbell_dist(np.linspace(1e-3, 1 - 1e-3, 100)) +
fitted_max_speeds = speed_spline(nprob) +
+
fifty_prob = gumbell_dist(49.0 / 50.0) +
fifty_wind = speed_spline(fifty_prob) +
+
plt.figure() +
plt.plot(sorted_max_speeds, gprob, "o") +
plt.plot(fitted_max_speeds, nprob, "g--") +
plt.plot([fifty_wind], [fifty_prob], "o", ms=8.0, mfc="y", mec="y") +
plt.plot([fifty_wind, fifty_wind], [plt.axis()[2], fifty_prob], "k--") +
plt.text(35, -1, rf"$V_{{50}} = {fifty_wind:.2f} \, m/s$") +
plt.xlabel("Annual wind speed maxima [$m/s$]") +
plt.ylabel("Gumbell cumulative probability") +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.068 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_complex_data.html b/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_complex_data.html new file mode 100644 index 000000000..e07098dd3 --- /dev/null +++ b/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_complex_data.html @@ -0,0 +1,206 @@ + + + + + + + + The lidar system, data (2 of 2 datasets) — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

The lidar system, data (2 of 2 datasets)

+

Generate a chart of more complex data recorded by the lidar system

+plot optimize lidar complex data
import numpy as np
+
import matplotlib.pyplot as plt +
+
waveform_2 = np.load("waveform_2.npy") +
+
t = np.arange(len(waveform_2)) +
+
fig, ax = plt.subplots(figsize=(8, 6)) +
plt.plot(t, waveform_2) +
plt.xlabel("Time [ns]") +
plt.ylabel("Amplitude [bins]") +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.082 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_complex_data_fit.html b/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_complex_data_fit.html new file mode 100644 index 000000000..5a5ed2c4c --- /dev/null +++ b/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_complex_data_fit.html @@ -0,0 +1,224 @@ + + + + + + + + The lidar system, data and fit (2 of 2 datasets) — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

The lidar system, data and fit (2 of 2 datasets)

+

Generate a chart of the data fitted by Gaussian curve

+plot optimize lidar complex data fit
import numpy as np
+
import matplotlib.pyplot as plt +
import scipy as sp +
+
+
def model(t, coeffs): +
return ( +
coeffs[0] +
+ coeffs[1] * np.exp(-(((t - coeffs[2]) / coeffs[3]) ** 2)) +
+ coeffs[4] * np.exp(-(((t - coeffs[5]) / coeffs[6]) ** 2)) +
+ coeffs[7] * np.exp(-(((t - coeffs[8]) / coeffs[9]) ** 2)) +
) +
+
+
def residuals(coeffs, y, t): +
return y - model(t, coeffs) +
+
+
waveform_2 = np.load("waveform_2.npy") +
t = np.arange(len(waveform_2)) +
+
x0 = np.array([3, 30, 20, 1, 12, 25, 1, 8, 28, 1], dtype=float) +
x, flag = sp.optimize.leastsq(residuals, x0, args=(waveform_2, t)) +
+
fig, ax = plt.subplots(figsize=(8, 6)) +
plt.plot(t, waveform_2, t, model(t, x)) +
plt.xlabel("Time [ns]") +
plt.ylabel("Amplitude [bins]") +
plt.legend(["Waveform", "Model"]) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.077 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_data.html b/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_data.html new file mode 100644 index 000000000..4a96c4c56 --- /dev/null +++ b/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_data.html @@ -0,0 +1,206 @@ + + + + + + + + The lidar system, data (1 of 2 datasets) — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

The lidar system, data (1 of 2 datasets)

+

Generate a chart of the data recorded by the lidar system

+plot optimize lidar data
import numpy as np
+
import matplotlib.pyplot as plt +
+
waveform_1 = np.load("waveform_1.npy") +
+
t = np.arange(len(waveform_1)) +
+
fig, ax = plt.subplots(figsize=(8, 6)) +
plt.plot(t, waveform_1) +
plt.xlabel("Time [ns]") +
plt.ylabel("Amplitude [bins]") +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.066 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_data_fit.html b/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_data_fit.html new file mode 100644 index 000000000..610f2f1bf --- /dev/null +++ b/intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_data_fit.html @@ -0,0 +1,227 @@ + + + + + + + + The lidar system, data and fit (1 of 2 datasets) — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

The lidar system, data and fit (1 of 2 datasets)

+

Generate a chart of the data fitted by Gaussian curve

+plot optimize lidar data fit
[ 2.70363341 27.82020742 15.47924562  3.05636228]
+
+
+
+

+
+
import numpy as np
+
import matplotlib.pyplot as plt +
import scipy as sp +
+
+
def model(t, coeffs): +
return coeffs[0] + coeffs[1] * np.exp(-(((t - coeffs[2]) / coeffs[3]) ** 2)) +
+
+
def residuals(coeffs, y, t): +
return y - model(t, coeffs) +
+
+
waveform_1 = np.load("waveform_1.npy") +
t = np.arange(len(waveform_1)) +
+
x0 = np.array([3, 30, 15, 1], dtype=float) +
x, flag = sp.optimize.leastsq(residuals, x0, args=(waveform_1, t)) +
+
print(x) +
+
fig, ax = plt.subplots(figsize=(8, 6)) +
plt.plot(t, waveform_1, t, model(t, x)) +
plt.xlabel("Time [ns]") +
plt.ylabel("Amplitude [bins]") +
plt.legend(["Waveform", "Model"]) +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.296 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/summary-exercises/auto_examples/plot_sprog_annual_maxima.html b/intro/scipy/summary-exercises/auto_examples/plot_sprog_annual_maxima.html new file mode 100644 index 000000000..7656f0168 --- /dev/null +++ b/intro/scipy/summary-exercises/auto_examples/plot_sprog_annual_maxima.html @@ -0,0 +1,212 @@ + + + + + + + + The Gumbell distribution, results — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

The Gumbell distribution, results

+

Generate the exercise results on the Gumbell distribution

+plot sprog annual maxima
Text(47.097222222222214, 0.5, 'Annual wind speed maxima [$m/s$]')
+
+
+
+

+
+
import numpy as np
+
import matplotlib.pyplot as plt +
+
years_nb = 21 +
wspeeds = np.load("sprog-windspeeds.npy") +
max_speeds = np.array([arr.max() for arr in np.array_split(wspeeds, years_nb)]) +
+
plt.figure() +
plt.bar(np.arange(years_nb) + 1, max_speeds) +
plt.axis("tight") +
plt.xlabel("Year") +
plt.ylabel("Annual wind speed maxima [$m/s$]") +
+
+

Total running time of the script: (0 minutes 0.240 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/summary-exercises/auto_examples/sg_execution_times.html b/intro/scipy/summary-exercises/auto_examples/sg_execution_times.html new file mode 100644 index 000000000..5f42c72c2 --- /dev/null +++ b/intro/scipy/summary-exercises/auto_examples/sg_execution_times.html @@ -0,0 +1,230 @@ + + + + + + + + Computation times — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Computation times

+

00:00.907 total execution time for 7 files from intro/scipy/summary-exercises/auto_examples:

+
+ + + + + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Example

Time

Mem (MB)

The lidar system, data and fit (1 of 2 datasets) (plot_optimize_lidar_data_fit.py)

00:00.296

0.0

The Gumbell distribution, results (plot_sprog_annual_maxima.py)

00:00.240

0.0

The lidar system, data (2 of 2 datasets) (plot_optimize_lidar_complex_data.py)

00:00.082

0.0

The lidar system, data and fit (2 of 2 datasets) (plot_optimize_lidar_complex_data_fit.py)

00:00.077

0.0

Cumulative wind speed prediction (plot_cumulative_wind_speed_prediction.py)

00:00.077

0.0

The Gumbell distribution (plot_gumbell_wind_speed_prediction.py)

00:00.068

0.0

The lidar system, data (1 of 2 datasets) (plot_optimize_lidar_data.py)

00:00.066

0.0

+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/summary-exercises/image-processing.html b/intro/scipy/summary-exercises/image-processing.html new file mode 100644 index 000000000..5092ec397 --- /dev/null +++ b/intro/scipy/summary-exercises/image-processing.html @@ -0,0 +1,238 @@ + + + + + + + + 1.5.11.3. Image processing application: counting bubbles and unmolten grains — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.5.11.3. Image processing application: counting bubbles and unmolten grains

+../../../_images/MV_HFV_012.jpg +
+

Statement of the problem

+
    +
  1. Open the image file MV_HFV_012.jpg and display it. Browse through the keyword arguments +in the docstring of imshow to display the image with the “right” orientation (origin +in the bottom left corner, and not the upper left corner as for standard arrays).

    +

    This Scanning Element Microscopy image shows a glass sample (light gray matrix) with some +bubbles (on black) and unmolten sand grains (dark gray). We wish to determine the +fraction of the sample covered by these three phases, and to estimate the typical size of +sand grains and bubbles, their sizes, etc.

    +
  2. +
  3. Crop the image to remove the lower panel with measure information.

  4. +
  5. Slightly filter the image with a median filter in order to refine its +histogram. Check how the histogram changes.

  6. +
  7. Using the histogram of the filtered image, determine thresholds that allow to define +masks for sand pixels, glass pixels and bubble pixels. Other option (homework): write a +function that determines automatically the thresholds from the minima of the histogram.

  8. +
  9. Display an image in which the three phases are colored with three +different colors.

  10. +
  11. Use mathematical morphology to clean the different phases.

  12. +
  13. Attribute labels to all bubbles and sand grains, and remove from the sand mask grains +that are smaller than 10 pixels. To do so, use ndimage.sum or np.bincount to +compute the grain sizes.

  14. +
  15. Compute the mean size of bubbles.

  16. +
+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/summary-exercises/optimize-fit.html b/intro/scipy/summary-exercises/optimize-fit.html new file mode 100644 index 000000000..be2a5e78a --- /dev/null +++ b/intro/scipy/summary-exercises/optimize-fit.html @@ -0,0 +1,377 @@ + + + + + + + + 1.5.11.2. Non linear least squares curve fitting: application to point extraction in topographical lidar data — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.5.11.2. Non linear least squares curve fitting: application to point extraction in topographical lidar data

+

The goal of this exercise is to fit a model to some data. The data used in this tutorial are lidar data and are described in details in the following introductory paragraph. If you’re impatient and want to practice now, please skip it and go directly to Loading and visualization.

+
+

Introduction

+

Lidars systems are optical rangefinders that analyze property of scattered light +to measure distances. Most of them emit a short light impulsion towards a target +and record the reflected signal. This signal is then processed to extract the +distance between the lidar system and the target.

+

Topographical lidar systems are such systems embedded in airborne +platforms. They measure distances between the platform and the Earth, so as to +deliver information on the Earth’s topography (see [1] for more details).

+ +

In this tutorial, the goal is to analyze the waveform recorded by the lidar +system [2]. Such a signal contains peaks whose center and amplitude permit to +compute the position and some characteristics of the hit target. When the +footprint of the laser beam is around 1m on the Earth surface, the beam can hit +multiple targets during the two-way propagation (for example the ground and the +top of a tree or building). The sum of the contributions of each target hit by +the laser beam then produces a complex signal with multiple peaks, each one +containing information about one target.

+

One state of the art method to extract information from these data is to +decompose them in a sum of Gaussian functions where each function represents the +contribution of a target hit by the laser beam.

+

Therefore, we use the scipy.optimize module to fit a waveform to one +or a sum of Gaussian functions.

+
+
+

Loading and visualization

+

Load the first waveform using:

+
>>> import numpy as np
+
>>> waveform_1 = np.load('intro/scipy/summary-exercises/examples/waveform_1.npy') +
+
+

and visualize it:

+
>>> import matplotlib.pyplot as plt
+
>>> t = np.arange(len(waveform_1)) +
>>> plt.plot(t, waveform_1) +
[<matplotlib.lines.Line2D object at ...>] +
>>> plt.show() +
+
+

As shown below, this waveform is a 80-bin-length signal with a single peak +with an amplitude of approximately 30 in the 15 nanosecond bin. Additionally, the +base level of noise is approximately 3. These values can be used in the initial solution.

+
+../../../_images/sphx_glr_plot_optimize_lidar_data_001.png + +
+
+
+

Fitting a waveform with a simple Gaussian model

+

The signal is very simple and can be modeled as a single Gaussian function and +an offset corresponding to the background noise. To fit the signal with the +function, we must:

+
    +
  • define the model

  • +
  • propose an initial solution

  • +
  • call scipy.optimize.leastsq

  • +
+
+

Model

+

A Gaussian function defined by

+
+

B + A \exp\left\{-\left(\frac{t-\mu}{\sigma}\right)^2\right\}

+

can be defined in python by:

+
>>> def model(t, coeffs):
+
... return coeffs[0] + coeffs[1] * np.exp( - ((t-coeffs[2])/coeffs[3])**2 ) +
+
+

where

+
    +
  • coeffs[0] is B (noise)

  • +
  • coeffs[1] is A (amplitude)

  • +
  • coeffs[2] is \mu (center)

  • +
  • coeffs[3] is \sigma (width)

  • +
+
+
+

Initial solution

+

One possible initial solution that we determine by inspection is:

+
>>> x0 = np.array([3, 30, 15, 1], dtype=float)
+
+
+
+
+

Fit

+

scipy.optimize.leastsq minimizes the sum of squares of the function given as +an argument. Basically, the function to minimize is the residuals (the +difference between the data and the model):

+
>>> def residuals(coeffs, y, t):
+
... return y - model(t, coeffs) +
+
+

So let’s get our solution by calling scipy.optimize.leastsq() with the +following arguments:

+
    +
  • the function to minimize

  • +
  • an initial solution

  • +
  • the additional arguments to pass to the function

  • +
+
>>> import scipy as sp
+
>>> t = np.arange(len(waveform_1)) +
>>> x, flag = sp.optimize.leastsq(residuals, x0, args=(waveform_1, t)) +
>>> x +
array([ 2.70363, 27.82020, 15.47924, 3.05636]) +
+
+

And visualize the solution:

+
fig, ax = plt.subplots(figsize=(8, 6))
+
plt.plot(t, waveform_1, t, model(t, x)) +
plt.xlabel("Time [ns]") +
plt.ylabel("Amplitude [bins]") +
plt.legend(["Waveform", "Model"]) +
plt.show() +
+
+
+../../../_images/sphx_glr_plot_optimize_lidar_data_fit_001.png + +
+

Remark: from scipy v0.8 and above, you should rather use scipy.optimize.curve_fit() which takes the model and the data as arguments, so you don’t need to define the residuals any more.

+
+
+
+

Going further

+
    +
  • Try with a more complex waveform (for instance waveform_2.npy) +that contains three significant peaks. You must adapt the model which is +now a sum of Gaussian functions instead of only one Gaussian peak.

  • +
+
+../../../_images/sphx_glr_plot_optimize_lidar_complex_data_001.png + +
+
    +
  • In some cases, writing an explicit function to compute the Jacobian is faster +than letting leastsq estimate it numerically. Create a function to compute +the Jacobian of the residuals and use it as an input for leastsq.

  • +
  • When we want to detect very small peaks in the signal, or when the initial +guess is too far from a good solution, the result given by the algorithm is +often not satisfying. Adding constraints to the parameters of the model +enables to overcome such limitations. An example of a priori knowledge we can +add is the sign of our variables (which are all positive).

  • +
  • See the solution.

  • +
  • Further exercise: compare the result of scipy.optimize.leastsq() and what you can +get with scipy.optimize.fmin_slsqp() when adding boundary constraints.

  • +
+ +

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/intro/scipy/summary-exercises/stats-interpolate.html b/intro/scipy/summary-exercises/stats-interpolate.html new file mode 100644 index 000000000..ee19ffc25 --- /dev/null +++ b/intro/scipy/summary-exercises/stats-interpolate.html @@ -0,0 +1,345 @@ + + + + + + + + 1.5.11.1. Maximum wind speed prediction at the Sprogø station — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

1.5.11.1. Maximum wind speed prediction at the Sprogø station

+

The exercise goal is to predict the maximum wind speed occurring every +50 years even if no measure exists for such a period. The available +data are only measured over 21 years at the Sprogø meteorological +station located in Denmark. First, the statistical steps will be given +and then illustrated with functions from the scipy.interpolate module. +At the end the interested readers are invited to compute results from +raw data and in a slightly different approach.

+
+

Statistical approach

+

The annual maxima are supposed to fit a normal probability density +function. However such function is not going to be estimated because +it gives a probability from a wind speed maxima. Finding the maximum wind +speed occurring every 50 years requires the opposite approach, the result +needs to be found from a defined probability. That is the quantile function +role and the exercise goal will be to find it. In the current model, +it is supposed that the maximum wind speed occurring every 50 years is +defined as the upper 2% quantile.

+

By definition, the quantile function is the inverse of the cumulative +distribution function. The latter describes the probability distribution +of an annual maxima. In the exercise, the cumulative probability p_i +for a given year i is defined as p_i = i/(N+1) with N = 21, +the number of measured years. Thus it will be possible to calculate +the cumulative probability of every measured wind speed maxima. +From those experimental points, the scipy.interpolate module will be +very useful for fitting the quantile function. Finally the 50 years +maxima is going to be evaluated from the cumulative probability +of the 2% quantile.

+
+
+

Computing the cumulative probabilities

+

The annual wind speeds maxima have already been computed and saved in +the NumPy format in the file examples/max-speeds.npy, thus they will be loaded +by using NumPy:

+
>>> import numpy as np
+
>>> max_speeds = np.load('intro/scipy/summary-exercises/examples/max-speeds.npy') +
>>> years_nb = max_speeds.shape[0] +
+
+

Following the cumulative probability definition p_i from the previous +section, the corresponding values will be:

+
>>> cprob = (np.arange(years_nb, dtype=np.float32) + 1)/(years_nb + 1)
+
+
+

and they are assumed to fit the given wind speeds:

+
>>> sorted_max_speeds = np.sort(max_speeds)
+
+
+
+
+

Prediction with UnivariateSpline

+

In this section the quantile function will be estimated by using the +UnivariateSpline class which can represent a spline from points. The +default behavior is to build a spline of degree 3 and points can +have different weights according to their reliability. Variants are +InterpolatedUnivariateSpline and LSQUnivariateSpline on which +errors checking is going to change. In case a 2D spline is wanted, +the BivariateSpline class family is provided. All those classes +for 1D and 2D splines use the FITPACK Fortran subroutines, that’s why a +lower library access is available through the splrep and splev +functions for respectively representing and evaluating a spline. +Moreover interpolation functions without the use of FITPACK parameters +are also provided for simpler use.

+

For the Sprogø maxima wind speeds, the UnivariateSpline will be +used because a spline of degree 3 seems to correctly fit the data:

+
>>> import scipy as sp
+
>>> quantile_func = sp.interpolate.UnivariateSpline(cprob, sorted_max_speeds) +
+
+

The quantile function is now going to be evaluated from the full range +of probabilities:

+
>>> nprob = np.linspace(0, 1, 100)
+
>>> fitted_max_speeds = quantile_func(nprob) +
+
+

In the current model, the maximum wind speed occurring every 50 years is +defined as the upper 2% quantile. As a result, the cumulative probability +value will be:

+
>>> fifty_prob = 1. - 0.02
+
+
+

So the storm wind speed occurring every 50 years can be guessed by:

+
>>> fifty_wind = quantile_func(fifty_prob)
+
>>> fifty_wind +
array(32.97989825...) +
+
+

The results are now gathered on a Matplotlib figure:

+
+../../../_images/sphx_glr_plot_cumulative_wind_speed_prediction_001.png +
+

Solution: Python source file

+
+
+
+
+

Exercise with the Gumbell distribution

+

The interested readers are now invited to make an exercise by using the wind +speeds measured over 21 years. The measurement period is around 90 minutes (the +original period was around 10 minutes but the file size has been reduced for +making the exercise setup easier). The data are stored in NumPy format inside +the file examples/sprog-windspeeds.npy. Do not look at +the source code for the plots +until you have completed the exercise.

+
    +
  • The first step will be to find the annual maxima by using NumPy +and plot them as a matplotlib bar figure.

  • +
+
+../../../_images/sphx_glr_plot_sprog_annual_maxima_001.png +
+

Solution: Python source file

+
+
+
    +
  • The second step will be to use the Gumbell distribution on cumulative +probabilities p_i defined as -log( -log(p_i) ) for fitting +a linear quantile function (remember that you can define the degree +of the UnivariateSpline). Plotting the annual maxima versus the +Gumbell distribution should give you the following figure.

  • +
+
+../../../_images/sphx_glr_plot_gumbell_wind_speed_prediction_001.png +
+

Solution: Python source file

+
+
+
    +
  • The last step will be to find 34.23 m/s for the maximum wind speed +occurring every 50 years.

  • +
+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/objects.inv b/objects.inv new file mode 100644 index 000000000..8f6cb79ae Binary files /dev/null and b/objects.inv differ diff --git a/packages/index.html b/packages/index.html new file mode 100644 index 000000000..d691f6e85 --- /dev/null +++ b/packages/index.html @@ -0,0 +1,374 @@ + + + + + + + + 3. Packages and applications — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

3. Packages and applications

+

This part of the Scientific Python Lectures is dedicated to various +scientific packages useful for extended needs.

+
+

+
+
+ +
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/index.html b/packages/scikit-image/auto_examples/index.html new file mode 100644 index 000000000..c98e0677f --- /dev/null +++ b/packages/scikit-image/auto_examples/index.html @@ -0,0 +1,219 @@ + + + + + + + + Examples for the scikit-image chapter — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Examples for the scikit-image chapter

+
+

Creating an image

+
Creating an image
+
+

Displaying a simple image

+
Displaying a simple image
+
+

Integers can overflow

+
Integers can overflow
+
+

Equalizing the histogram of an image

+
Equalizing the histogram of an image
+
+

Computing horizontal gradients with the Sobel filter

+
Computing horizontal gradients with the Sobel filter
+
+

Segmentation contours

+
Segmentation contours
+
+

Otsu thresholding

+
Otsu thresholding
+
+

Affine transform

+
Affine transform
+
+

Labelling connected components of an image

+
Labelling connected components of an image
+
+

Various denoising filters

+
Various denoising filters
+
+

Watershed and random walker for segmentation

+
Watershed and random walker for segmentation
+
+
+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_boundaries.html b/packages/scikit-image/auto_examples/plot_boundaries.html new file mode 100644 index 000000000..787972fa5 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_boundaries.html @@ -0,0 +1,243 @@ + + + + + + + + 3.3.11.6. Segmentation contours — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.3.11.6. Segmentation contours

+

Visualize segmentation contours on original grayscale image.

+plot boundaries
from skimage import data, segmentation
+
from skimage import filters +
import matplotlib.pyplot as plt +
import numpy as np +
+
coins = data.coins() +
mask = coins > filters.threshold_otsu(coins) +
clean_border = segmentation.clear_border(mask).astype(int) +
+
coins_edges = segmentation.mark_boundaries(coins, clean_border) +
+
plt.figure(figsize=(8, 3.5)) +
plt.subplot(121) +
plt.imshow(clean_border, cmap="gray") +
plt.axis("off") +
plt.subplot(122) +
plt.imshow(coins_edges) +
plt.axis("off") +
+
plt.tight_layout() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.099 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_camera.html b/packages/scikit-image/auto_examples/plot_camera.html new file mode 100644 index 000000000..475397b4c --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_camera.html @@ -0,0 +1,234 @@ + + + + + + + + 3.3.11.2. Displaying a simple image — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.3.11.2. Displaying a simple image

+

Load and display an image

+plot camera
import matplotlib.pyplot as plt
+
from skimage import data +
+
camera = data.camera() +
+
+
plt.figure(figsize=(4, 4)) +
plt.imshow(camera, cmap="gray", interpolation="nearest") +
plt.axis("off") +
+
plt.tight_layout() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.073 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_camera_uint.html b/packages/scikit-image/auto_examples/plot_camera_uint.html new file mode 100644 index 000000000..1c12de5f9 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_camera_uint.html @@ -0,0 +1,238 @@ + + + + + + + + 3.3.11.3. Integers can overflow — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.3.11.3. Integers can overflow

+

An illustration of overflow problem arising when working with integers

+plot camera uint
import matplotlib.pyplot as plt
+
from skimage import data +
+
camera = data.camera() +
camera_multiply = 3 * camera +
+
plt.figure(figsize=(8, 4)) +
plt.subplot(121) +
plt.imshow(camera, cmap="gray", interpolation="nearest") +
plt.axis("off") +
plt.subplot(122) +
plt.imshow(camera_multiply, cmap="gray", interpolation="nearest") +
plt.axis("off") +
+
plt.tight_layout() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.116 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_check.html b/packages/scikit-image/auto_examples/plot_check.html new file mode 100644 index 000000000..bbad1aaca --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_check.html @@ -0,0 +1,231 @@ + + + + + + + + 3.3.11.1. Creating an image — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.3.11.1. Creating an image

+

How to create an image with basic NumPy commands : np.zeros, slicing…

+

This examples show how to create a simple checkerboard.

+plot check
import numpy as np
+
import matplotlib.pyplot as plt +
+
check = np.zeros((8, 8)) +
check[::2, 1::2] = 1 +
check[1::2, ::2] = 1 +
plt.matshow(check, cmap="gray") +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.059 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_equalize_hist.html b/packages/scikit-image/auto_examples/plot_equalize_hist.html new file mode 100644 index 000000000..f03b36385 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_equalize_hist.html @@ -0,0 +1,238 @@ + + + + + + + + 3.3.11.4. Equalizing the histogram of an image — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.3.11.4. Equalizing the histogram of an image

+

Histogram equalizing makes images have a uniform histogram.

+plot equalize hist
from skimage import data, exposure
+
import matplotlib.pyplot as plt +
+
camera = data.camera() +
camera_equalized = exposure.equalize_hist(camera) +
+
plt.figure(figsize=(7, 3)) +
+
plt.subplot(121) +
plt.imshow(camera, cmap="gray", interpolation="nearest") +
plt.axis("off") +
plt.subplot(122) +
plt.imshow(camera_equalized, cmap="gray", interpolation="nearest") +
plt.axis("off") +
plt.tight_layout() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.089 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_features.html b/packages/scikit-image/auto_examples/plot_features.html new file mode 100644 index 000000000..0f2c174b3 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_features.html @@ -0,0 +1,241 @@ + + + + + + + + 3.3.11.8. Affine transform — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.3.11.8. Affine transform

+

Warping and affine transforms of images.

+plot features
import matplotlib.pyplot as plt
+
+
from skimage import data +
from skimage.feature import corner_harris, corner_subpix, corner_peaks +
from skimage.transform import warp, AffineTransform +
+
+
tform = AffineTransform(scale=(1.3, 1.1), rotation=1, shear=0.7, translation=(210, 50)) +
image = warp(data.checkerboard(), tform.inverse, output_shape=(350, 350)) +
+
coords = corner_peaks(corner_harris(image), min_distance=5) +
coords_subpix = corner_subpix(image, coords, window_size=13) +
+
plt.gray() +
plt.imshow(image, interpolation="nearest") +
plt.plot(coords_subpix[:, 1], coords_subpix[:, 0], "+r", markersize=15, mew=5) +
plt.plot(coords[:, 1], coords[:, 0], ".b", markersize=7) +
plt.axis("off") +
plt.show() +
+
+

Total running time of the script: (0 minutes 5.704 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_filter_coins.html b/packages/scikit-image/auto_examples/plot_filter_coins.html new file mode 100644 index 000000000..73e4f9b7e --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_filter_coins.html @@ -0,0 +1,252 @@ + + + + + + + + 3.3.11.10. Various denoising filters — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.3.11.10. Various denoising filters

+

This example compares several denoising filters available in scikit-image: +a Gaussian filter, a median filter, and total variation denoising.

+Image, Gaussian filter, Median filter, TV filter
import numpy as np
+
import matplotlib.pyplot as plt +
from skimage import data +
from skimage import filters +
from skimage import restoration +
+
coins = data.coins() +
gaussian_filter_coins = filters.gaussian(coins, sigma=2) +
med_filter_coins = filters.median(coins, np.ones((3, 3))) +
tv_filter_coins = restoration.denoise_tv_chambolle(coins, weight=0.1) +
+
plt.figure(figsize=(16, 4)) +
plt.subplot(141) +
plt.imshow(coins[10:80, 300:370], cmap="gray", interpolation="nearest") +
plt.axis("off") +
plt.title("Image") +
plt.subplot(142) +
plt.imshow(gaussian_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest") +
plt.axis("off") +
plt.title("Gaussian filter") +
plt.subplot(143) +
plt.imshow(med_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest") +
plt.axis("off") +
plt.title("Median filter") +
plt.subplot(144) +
plt.imshow(tv_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest") +
plt.axis("off") +
plt.title("TV filter") +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.154 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_labels.html b/packages/scikit-image/auto_examples/plot_labels.html new file mode 100644 index 000000000..61de749a6 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_labels.html @@ -0,0 +1,253 @@ + + + + + + + + 3.3.11.9. Labelling connected components of an image — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.3.11.9. Labelling connected components of an image

+

This example shows how to label connected components of a binary image, using +the dedicated skimage.measure.label function.

+plot labels
from skimage import measure
+
from skimage import filters +
import matplotlib.pyplot as plt +
import numpy as np +
+
n = 12 +
l = 256 +
rng = np.random.default_rng(27446968) +
im = np.zeros((l, l)) +
points = l * rng.random((2, n**2)) +
im[(points[0]).astype(int), (points[1]).astype(int)] = 1 +
im = filters.gaussian(im, sigma=l / (4.0 * n)) +
blobs = im > 0.7 * im.mean() +
+
all_labels = measure.label(blobs) +
blobs_labels = measure.label(blobs, background=0) +
+
plt.figure(figsize=(9, 3.5)) +
plt.subplot(131) +
plt.imshow(blobs, cmap="gray") +
plt.axis("off") +
plt.subplot(132) +
plt.imshow(all_labels, cmap="nipy_spectral") +
plt.axis("off") +
plt.subplot(133) +
plt.imshow(blobs_labels, cmap="nipy_spectral") +
plt.axis("off") +
+
plt.tight_layout() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.074 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_segmentations.html b/packages/scikit-image/auto_examples/plot_segmentations.html new file mode 100644 index 000000000..b02c65224 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_segmentations.html @@ -0,0 +1,274 @@ + + + + + + + + 3.3.11.11. Watershed and random walker for segmentation — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.3.11.11. Watershed and random walker for segmentation

+

This example compares two segmentation methods in order to separate two +connected disks: the watershed algorithm, and the random walker algorithm.

+

Both segmentation methods require seeds, that are pixels belonging +unambigusouly to a reagion. Here, local maxima of the distance map to the +background are used as seeds.

+image, distance map, watershed segmentation, random walker segmentation
import numpy as np
+
from skimage.segmentation import watershed +
from skimage.feature import peak_local_max +
from skimage import measure +
from skimage.segmentation import random_walker +
import matplotlib.pyplot as plt +
import scipy as sp +
+
# Generate an initial image with two overlapping circles +
x, y = np.indices((80, 80)) +
x1, y1, x2, y2 = 28, 28, 44, 52 +
r1, r2 = 16, 20 +
mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1**2 +
mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2**2 +
image = np.logical_or(mask_circle1, mask_circle2) +
# Now we want to separate the two objects in image +
# Generate the markers as local maxima of the distance +
# to the background +
distance = sp.ndimage.distance_transform_edt(image) +
peak_idx = peak_local_max(distance, footprint=np.ones((3, 3)), labels=image) +
peak_mask = np.zeros_like(distance, dtype=bool) +
peak_mask[tuple(peak_idx.T)] = True +
markers = measure.label(peak_mask) +
labels_ws = watershed(-distance, markers, mask=image) +
+
markers[~image] = -1 +
labels_rw = random_walker(image, markers) +
+
plt.figure(figsize=(12, 3.5)) +
plt.subplot(141) +
plt.imshow(image, cmap="gray", interpolation="nearest") +
plt.axis("off") +
plt.title("image") +
plt.subplot(142) +
plt.imshow(-distance, interpolation="nearest") +
plt.axis("off") +
plt.title("distance map") +
plt.subplot(143) +
plt.imshow(labels_ws, cmap="nipy_spectral", interpolation="nearest") +
plt.axis("off") +
plt.title("watershed segmentation") +
plt.subplot(144) +
plt.imshow(labels_rw, cmap="nipy_spectral", interpolation="nearest") +
plt.axis("off") +
plt.title("random walker segmentation") +
+
plt.tight_layout() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.164 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_sobel.html b/packages/scikit-image/auto_examples/plot_sobel.html new file mode 100644 index 000000000..c82bb18df --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_sobel.html @@ -0,0 +1,240 @@ + + + + + + + + 3.3.11.5. Computing horizontal gradients with the Sobel filter — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.3.11.5. Computing horizontal gradients with the Sobel filter

+

This example illustrates the use of the horizontal Sobel filter, to compute +horizontal gradients.

+plot sobel
from skimage import data
+
from skimage import filters +
import matplotlib.pyplot as plt +
+
text = data.text() +
hsobel_text = filters.sobel_h(text) +
+
plt.figure(figsize=(12, 3)) +
+
plt.subplot(121) +
plt.imshow(text, cmap="gray", interpolation="nearest") +
plt.axis("off") +
plt.subplot(122) +
plt.imshow(hsobel_text, cmap="nipy_spectral", interpolation="nearest") +
plt.axis("off") +
plt.tight_layout() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.099 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_threshold.html b/packages/scikit-image/auto_examples/plot_threshold.html new file mode 100644 index 000000000..b8fe25918 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_threshold.html @@ -0,0 +1,245 @@ + + + + + + + + 3.3.11.7. Otsu thresholding — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.3.11.7. Otsu thresholding

+

This example illustrates automatic Otsu thresholding.

+plot threshold
import matplotlib.pyplot as plt
+
from skimage import data +
from skimage import filters +
from skimage import exposure +
+
camera = data.camera() +
val = filters.threshold_otsu(camera) +
+
hist, bins_center = exposure.histogram(camera) +
+
plt.figure(figsize=(9, 4)) +
plt.subplot(131) +
plt.imshow(camera, cmap="gray", interpolation="nearest") +
plt.axis("off") +
plt.subplot(132) +
plt.imshow(camera < val, cmap="gray", interpolation="nearest") +
plt.axis("off") +
plt.subplot(133) +
plt.plot(bins_center, hist, lw=2) +
plt.axvline(val, color="k", ls="--") +
+
plt.tight_layout() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.116 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/sg_execution_times.html b/packages/scikit-image/auto_examples/sg_execution_times.html new file mode 100644 index 000000000..e8f3012ad --- /dev/null +++ b/packages/scikit-image/auto_examples/sg_execution_times.html @@ -0,0 +1,246 @@ + + + + + + + + Computation times — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Computation times

+

00:06.747 total execution time for 11 files from packages/scikit-image/auto_examples:

+
+ + + + + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Example

Time

Mem (MB)

Affine transform (plot_features.py)

00:05.704

0.0

Watershed and random walker for segmentation (plot_segmentations.py)

00:00.164

0.0

Various denoising filters (plot_filter_coins.py)

00:00.154

0.0

Integers can overflow (plot_camera_uint.py)

00:00.116

0.0

Otsu thresholding (plot_threshold.py)

00:00.116

0.0

Segmentation contours (plot_boundaries.py)

00:00.099

0.0

Computing horizontal gradients with the Sobel filter (plot_sobel.py)

00:00.099

0.0

Equalizing the histogram of an image (plot_equalize_hist.py)

00:00.089

0.0

Labelling connected components of an image (plot_labels.py)

00:00.074

0.0

Displaying a simple image (plot_camera.py)

00:00.073

0.0

Creating an image (plot_check.py)

00:00.059

0.0

+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-image/index.html b/packages/scikit-image/index.html new file mode 100644 index 000000000..434e0c590 --- /dev/null +++ b/packages/scikit-image/index.html @@ -0,0 +1,976 @@ + + + + + + + + 3.3. scikit-image: image processing — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

3.3. scikit-image: image processing

+

Author: Emmanuelle Gouillart

+

scikit-image is a Python package dedicated +to image processing, using NumPy arrays as image objects. +This chapter describes how to use scikit-image for various image +processing tasks, and how it relates to other scientific Python +modules such as NumPy and SciPy.

+
+

See also

+

For basic image manipulation, such as image cropping or simple +filtering, a large number of simple operations can be realized with +NumPy and SciPy only. See Image manipulation and processing using NumPy and SciPy.

+

Note that you should be familiar with the content of the previous +chapter before reading the current one, as basic operations such as +masking and labeling are a prerequisite.

+
+ +
+

3.3.1. Introduction and concepts

+

Images are NumPy’s arrays np.ndarray

+
+
image:
+

np.ndarray

+
+
pixels:
+

array values: a[2, 3]

+
+
channels:
+

array dimensions

+
+
image encoding:
+

dtype (np.uint8, np.uint16, np.float)

+
+
filters:
+

functions (numpy, skimage, scipy)

+
+
+
>>> import numpy as np
+
>>> check = np.zeros((8, 8)) +
>>> check[::2, 1::2] = 1 +
>>> check[1::2, ::2] = 1 +
>>> import matplotlib.pyplot as plt +
>>> plt.imshow(check, cmap='gray', interpolation='nearest') +
<matplotlib.image.AxesImage object at ...> +
+
+../../_images/sphx_glr_plot_check_001.png + +
+

3.3.1.1. scikit-image and the scientific Python ecosystem

+

scikit-image is packaged in both pip and conda-based +Python installations, as well as in most Linux distributions. Other +Python packages for image processing & visualization that operate on +NumPy arrays include:

+
+
scipy.ndimage

For N-dimensional arrays. Basic filtering, +mathematical morphology, regions properties

+
+
Mahotas

With a focus on high-speed implementations.

+
+
Napari

A fast, interactive, multi-dimensional image viewer built in Qt.

+
+
+

Some powerful C++ image processing libraries also have Python bindings:

+
+
OpenCV

A highly optimized computer vision library with a focus on real-time +applications.

+
+
ITK

The Insight ToolKit, especially useful for registration and +working with 3D images.

+
+
+

To varying degrees, these tend to be less Pythonic and NumPy-friendly.

+
+
+

3.3.1.2. What is included in scikit-image

+ +

The library contains predominantly image processing algorithms, but +also utility functions to ease data handling and processing. +It contains the following submodules:

+
+
color

Color space conversion.

+
+
data

Test images and example data.

+
+
draw

Drawing primitives (lines, text, etc.) that operate on NumPy +arrays.

+
+
exposure

Image intensity adjustment, e.g., histogram equalization, etc.

+
+
feature

Feature detection and extraction, e.g., texture analysis corners, etc.

+
+
filters

Sharpening, edge finding, rank filters, thresholding, etc.

+
+
graph

Graph-theoretic operations, e.g., shortest paths.

+
+
io

Reading, saving, and displaying images and video.

+
+
measure

Measurement of image properties, e.g., region properties and contours.

+
+
metrics

Metrics corresponding to images, e.g. distance metrics, similarity, etc.

+
+
morphology

Morphological operations, e.g., opening or skeletonization.

+
+
restoration

Restoration algorithms, e.g., deconvolution algorithms, denoising, etc.

+
+
segmentation

Partitioning an image into multiple regions.

+
+
transform

Geometric and other transforms, e.g., rotation or the Radon transform.

+
+
util

Generic utilities.

+
+
+
+
+
+

3.3.2. Importing

+

We import scikit-image using the convention:

+
>>> import skimage as ski
+
+
+

Most functionality lives in subpackages, e.g.:

+
>>> image = ski.data.cat()
+
+
+

You can list all submodules with:

+
>>> for m in dir(ski): print(m)
+
__version__ +
color +
data +
draw +
exposure +
feature +
filters +
future +
graph +
io +
measure +
metrics +
morphology +
registration +
restoration +
segmentation +
transform +
util +
+
+

Most scikit-image functions take NumPy ndarrays as arguments

+
>>> camera = ski.data.camera()
+
>>> camera.dtype +
dtype('uint8') +
>>> camera.shape +
(512, 512) +
>>> filtered_camera = ski.filters.gaussian(camera, sigma=1) +
>>> type(filtered_camera) +
<class 'numpy.ndarray'> +
+
+
+
+

3.3.3. Example data

+

To start off, we need example images to work with. +The library ships with a few of these:

+

skimage.data

+
>>> image = ski.data.cat()
+
>>> image.shape +
(300, 451, 3) +
+
+
+
+

3.3.4. Input/output, data types and colorspaces

+

I/O: skimage.io

+

Save an image to disk: skimage.io.imsave()

+
>>> ski.io.imsave("cat.png", image)
+
+
+

Reading from files: skimage.io.imread()

+
>>> cat = ski.io.imread("cat.png")
+
+
+../../_images/sphx_glr_plot_camera_001.png + +

This works with many data formats supported by the +ImageIO library.

+

Loading also works with URLs:

+
>>> logo = ski.io.imread('https://scikit-image.org/_static/img/logo.png')
+
+
+
+

3.3.4.1. Data types

+../../_images/sphx_glr_plot_camera_uint_001.png + +

Image ndarrays can be represented either by integers (signed or unsigned) or +floats.

+

Careful with overflows with integer data types

+
>>> camera = ski.data.camera()
+
>>> camera.dtype +
dtype('uint8') +
>>> camera_multiply = 3 * camera +
+
+

Different integer sizes are possible: 8-, 16- or 32-bytes, signed or +unsigned.

+
+

Warning

+

An important (if questionable) skimage convention: float images +are supposed to lie in [-1, 1] (in order to have comparable contrast for +all float images)

+
>>> camera_float = ski.util.img_as_float(camera)
+
>>> camera.max(), camera_float.max() +
(np.uint8(255), np.float64(1.0)) +
+
+
+

Some image processing routines need to work with float arrays, and may +hence output an array with a different type and the data range from the +input array

+
>>> camera_sobel = ski.filters.sobel(camera)
+
>>> camera_sobel.max() +
np.float64(0.644...) +
+
+

Utility functions are provided in skimage to convert both the +dtype and the data range, following skimage’s conventions: +util.img_as_float, util.img_as_ubyte, etc.

+

See the user guide for +more details.

+
+
+

3.3.4.2. Colorspaces

+

Color images are of shape (N, M, 3) or (N, M, 4) (when an alpha channel +encodes transparency)

+
>>> face = sp.datasets.face()
+
>>> face.shape +
(768, 1024, 3) +
+
+

Routines converting between different colorspaces (RGB, HSV, LAB etc.) +are available in skimage.color : color.rgb2hsv, color.lab2rgb, +etc. Check the docstring for the expected dtype (and data range) of input +images.

+ + +
+
+
+

3.3.5. Image preprocessing / enhancement

+

Goals: denoising, feature (edges) extraction, …

+
+

3.3.5.1. Local filters

+

Local filters replace the value of pixels by a function of the +values of neighboring pixels. The function can be linear or non-linear.

+

Neighbourhood: square (choose size), disk, or more complicated +structuring element.

+../../_images/kernels.png + +

Example : horizontal Sobel filter

+
>>> text = ski.data.text()
+
>>> hsobel_text = ski.filters.sobel_h(text) +
+
+

Uses the following linear kernel for computing horizontal gradients:

+
1   2   1
+
0 0 0 +
-1 -2 -1 +
+
+../../_images/sphx_glr_plot_sobel_001.png + +
+
+

3.3.5.2. Non-local filters

+

Non-local filters use a large region of the image (or all the image) to +transform the value of one pixel:

+
>>> camera = ski.data.camera()
+
>>> camera_equalized = ski.exposure.equalize_hist(camera) +
+
+

Enhances contrast in large almost uniform regions.

+../../_images/sphx_glr_plot_equalize_hist_001.png + +
+
+

3.3.5.3. Mathematical morphology

+

See wikipedia +for an introduction on mathematical morphology.

+

Probe an image with a simple shape (a structuring element), and +modify this image according to how the shape locally fits or misses the +image.

+

Default structuring element: 4-connectivity of a pixel

+
>>> # Import structuring elements to make them more easily accessible
+
>>> from skimage.morphology import disk, diamond +
+
>>> diamond(1) +
array([[0, 1, 0], +
[1, 1, 1], +
[0, 1, 0]], dtype=uint8) +
+
+../../_images/diamond_kernel.png +

Erosion = minimum filter. Replace the value of a pixel by the minimal value covered by the structuring element.:

+
>>> a = np.zeros((7,7), dtype=np.uint8)
+
>>> a[1:6, 2:5] = 1 +
>>> a +
array([[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 1, 1, 1, 0, 0], +
[0, 0, 1, 1, 1, 0, 0], +
[0, 0, 1, 1, 1, 0, 0], +
[0, 0, 1, 1, 1, 0, 0], +
[0, 0, 1, 1, 1, 0, 0], +
[0, 0, 0, 0, 0, 0, 0]], dtype=uint8) +
>>> ski.morphology.binary_erosion(a, diamond(1)).astype(np.uint8) +
array([[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 1, 0, 0, 0], +
[0, 0, 0, 1, 0, 0, 0], +
[0, 0, 0, 1, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0]], dtype=uint8) +
>>> #Erosion removes objects smaller than the structure +
>>> ski.morphology.binary_erosion(a, diamond(2)).astype(np.uint8) +
array([[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0], +
[0, 0, 0, 0, 0, 0, 0]], dtype=uint8) +
+
+

Dilation: maximum filter:

+
>>> a = np.zeros((5, 5))
+
>>> a[2, 2] = 1 +
>>> a +
array([[0., 0., 0., 0., 0.], +
[0., 0., 0., 0., 0.], +
[0., 0., 1., 0., 0.], +
[0., 0., 0., 0., 0.], +
[0., 0., 0., 0., 0.]]) +
>>> ski.morphology.binary_dilation(a, diamond(1)).astype(np.uint8) +
array([[0, 0, 0, 0, 0], +
[0, 0, 1, 0, 0], +
[0, 1, 1, 1, 0], +
[0, 0, 1, 0, 0], +
[0, 0, 0, 0, 0]], dtype=uint8) +
+
+

Opening: erosion + dilation:

+
>>> a = np.zeros((5,5), dtype=int)
+
>>> a[1:4, 1:4] = 1; a[4, 4] = 1 +
>>> a +
array([[0, 0, 0, 0, 0], +
[0, 1, 1, 1, 0], +
[0, 1, 1, 1, 0], +
[0, 1, 1, 1, 0], +
[0, 0, 0, 0, 1]]) +
>>> ski.morphology.binary_opening(a, diamond(1)).astype(np.uint8) +
array([[0, 0, 0, 0, 0], +
[0, 0, 1, 0, 0], +
[0, 1, 1, 1, 0], +
[0, 0, 1, 0, 0], +
[0, 0, 0, 0, 0]], dtype=uint8) +
+
+

Opening removes small objects and smoothes corners.

+ +

Higher-level mathematical morphology are available: tophat, +skeletonization, etc.

+
+

See also

+

Basic mathematical morphology is also implemented in +scipy.ndimage.morphology. The scipy.ndimage implementation +works on arbitrary-dimensional arrays.

+
+
+ +
+
+
+

3.3.6. Image segmentation

+

Image segmentation is the attribution of different labels to different +regions of the image, for example in order to extract the pixels of an +object of interest.

+
+

3.3.6.1. Binary segmentation: foreground + background

+
+

Histogram-based method: Otsu thresholding

+
+

Tip

+

The Otsu method is a +simple heuristic to find a threshold to separate the foreground from +the background.

+
+ +
camera = ski.data.camera()
+
val = ski.filters.threshold_otsu(camera) +
mask = camera < val +
+
+../../_images/sphx_glr_plot_threshold_001.png + +
+
+

Labeling connected components of a discrete image

+
+

Tip

+

Once you have separated foreground objects, it is use to separate them +from each other. For this, we can assign a different integer labels to +each one.

+
+

Synthetic data:

+
>>> n = 20
+
>>> l = 256 +
>>> im = np.zeros((l, l)) +
>>> rng = np.random.default_rng() +
>>> points = l * rng.random((2, n ** 2)) +
>>> im[(points[0]).astype(int), (points[1]).astype(int)] = 1 +
>>> im = ski.filters.gaussian(im, sigma=l / (4. * n)) +
>>> blobs = im > im.mean() +
+
+

Label all connected components:

+
>>> all_labels = ski.measure.label(blobs)
+
+
+

Label only foreground connected components:

+
>>> blobs_labels = ski.measure.label(blobs, background=0)
+
+
+../../_images/sphx_glr_plot_labels_001.png + +
+

See also

+

scipy.ndimage.find_objects() is useful to return slices on +object in an image.

+
+
+
+
+

3.3.6.2. Marker based methods

+

If you have markers inside a set of regions, you can use these to segment +the regions.

+
+

Watershed segmentation

+

The Watershed (skimage.segmentation.watershed()) is a region-growing +approach that fills “basins” in the image

+
>>> # Generate an initial image with two overlapping circles
+
>>> x, y = np.indices((80, 80)) +
>>> x1, y1, x2, y2 = 28, 28, 44, 52 +
>>> r1, r2 = 16, 20 +
>>> mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1 ** 2 +
>>> mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2 ** 2 +
>>> image = np.logical_or(mask_circle1, mask_circle2) +
>>> # Now we want to separate the two objects in image +
>>> # Generate the markers as local maxima of the distance +
>>> # to the background +
>>> import scipy as sp +
>>> distance = sp.ndimage.distance_transform_edt(image) +
>>> peak_idx = ski.feature.peak_local_max( +
... distance, footprint=np.ones((3, 3)), labels=image +
... ) +
>>> peak_mask = np.zeros_like(distance, dtype=bool) +
>>> peak_mask[tuple(peak_idx.T)] = True +
>>> markers = ski.morphology.label(peak_mask) +
>>> labels_ws = ski.segmentation.watershed( +
... -distance, markers, mask=image +
... ) +
+
+
+
+

Random walker segmentation

+

The random walker algorithm (skimage.segmentation.random_walker()) +is similar to the Watershed, but with a more “probabilistic” approach. It +is based on the idea of the diffusion of labels in the image:

+
>>> # Transform markers image so that 0-valued pixels are to
+
>>> # be labelled, and -1-valued pixels represent background +
>>> markers[~image] = -1 +
>>> labels_rw = ski.segmentation.random_walker(image, markers) +
+
+../../_images/sphx_glr_plot_segmentations_001.png + + + +
+
+
+
+

3.3.7. Measuring regions’ properties

+

Example: compute the size and perimeter of the two segmented regions:

+
>>> properties = ski.measure.regionprops(labels_rw)
+
>>> [float(prop.area) for prop in properties] +
[770.0, 1168.0] +
>>> [prop.perimeter for prop in properties] +
[np.float64(100.91...), np.float64(126.81...)] +
+
+
+

See also

+

for some properties, functions are available as well in +scipy.ndimage.measurements with a different API (a list is +returned).

+
+ +
+
+

3.3.8. Data visualization and interaction

+

Meaningful visualizations are useful when testing a given processing +pipeline.

+

Some image processing operations:

+
>>> coins = ski.data.coins()
+
>>> mask = coins > ski.filters.threshold_otsu(coins) +
>>> clean_border = ski.segmentation.clear_border(mask) +
+
+

Visualize binary result:

+
>>> plt.figure()
+
<Figure size ... with 0 Axes> +
>>> plt.imshow(clean_border, cmap='gray') +
<matplotlib.image.AxesImage object at 0x...> +
+
+

Visualize contour

+
>>> plt.figure()
+
<Figure size ... with 0 Axes> +
>>> plt.imshow(coins, cmap='gray') +
<matplotlib.image.AxesImage object at 0x...> +
>>> plt.contour(clean_border, [0.5]) +
<matplotlib.contour.QuadContourSet ...> +
+
+

Use skimage dedicated utility function:

+
>>> coins_edges = ski.segmentation.mark_boundaries(
+
... coins, clean_border.astype(int) +
... ) +
+
+../../_images/sphx_glr_plot_boundaries_001.png + +
+
+

3.3.9. Feature extraction for computer vision

+

Geometric or textural descriptor can be extracted from images in order to

+
    +
  • classify parts of the image (e.g. sky vs. buildings)

  • +
  • match parts of different images (e.g. for object detection)

  • +
  • and many other applications of +Computer Vision

  • +
+

Example: detecting corners using Harris detector

+
tform = ski.transform.AffineTransform(
+
scale=(1.3, 1.1), rotation=1, shear=0.7, +
translation=(210, 50) +
) +
image = ski.transform.warp( +
data.checkerboard(), tform.inverse, output_shape=(350, 350) +
) +
+
coords = ski.feature.corner_peaks( +
ski.feature.corner_harris(image), min_distance=5 +
) +
coords_subpix = ski.feature.corner_subpix( +
image, coords, window_size=13 +
) +
+
+../../_images/sphx_glr_plot_features_001.png + +

(this example is taken from the plot_corner +example in scikit-image)

+

Points of interest such as corners can then be used to match objects in +different images, as described in the plot_matching +example of scikit-image.

+
+
+

3.3.10. Full code examples

+
+
+

3.3.11. Examples for the scikit-image chapter

+
+

Creating an image

+
Creating an image
+
+

Displaying a simple image

+
Displaying a simple image
+
+

Integers can overflow

+
Integers can overflow
+
+

Equalizing the histogram of an image

+
Equalizing the histogram of an image
+
+

Computing horizontal gradients with the Sobel filter

+
Computing horizontal gradients with the Sobel filter
+
+

Segmentation contours

+
Segmentation contours
+
+

Otsu thresholding

+
Otsu thresholding
+
+

Affine transform

+
Affine transform
+
+

Labelling connected components of an image

+
Labelling connected components of an image
+
+

Various denoising filters

+
Various denoising filters
+
+

Watershed and random walker for segmentation

+
Watershed and random walker for segmentation
+
+
+ +

Gallery generated by Sphinx-Gallery

+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-learn/auto_examples/index.html b/packages/scikit-learn/auto_examples/index.html new file mode 100644 index 000000000..b5a0bfeca --- /dev/null +++ b/packages/scikit-learn/auto_examples/index.html @@ -0,0 +1,237 @@ + + + + + + + + Examples for the scikit-learn chapter — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Examples for the scikit-learn chapter

+
+

Demo PCA in 2D

+
Demo PCA in 2D
+
+

Measuring Decision Tree performance

+
Measuring Decision Tree performance
+
+

A simple linear regression

+
A simple linear regression
+
+

Plot 2D views of the iris dataset

+
Plot 2D views of the iris dataset
+
+

tSNE to visualize digits

+
tSNE to visualize digits
+
+

Use the RidgeCV and LassoCV to set the regularization parameter

+
Use the RidgeCV and LassoCV to set the regularization parameter
+
+

Plot variance and regularization in linear models

+
Plot variance and regularization in linear models
+
+

Simple picture of the formal problem of machine learning

+
Simple picture of the formal problem of machine learning
+
+

Compare classifiers on the digits data

+
Compare classifiers on the digits data
+
+

Plot fitting a 9th order polynomial

+
Plot fitting a 9th order polynomial
+
+

A simple regression analysis on the California housing data

+
A simple regression analysis on the California housing data
+
+

Nearest-neighbor prediction on iris

+
Nearest-neighbor prediction on iris
+
+

Simple visualization and classification of the digits dataset

+
Simple visualization and classification of the digits dataset
+
+

The eigenfaces example: chaining PCA and SVMs

+
The eigenfaces example: chaining PCA and SVMs
+
+

Example of linear and non-linear models

+
Example of linear and non-linear models
+
+

Bias and variance of polynomial fit

+
Bias and variance of polynomial fit
+
+

Tutorial Diagrams

+
Tutorial Diagrams
+
+
+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-learn/auto_examples/plot_ML_flow_chart.html b/packages/scikit-learn/auto_examples/plot_ML_flow_chart.html new file mode 100644 index 000000000..07c62f3fd --- /dev/null +++ b/packages/scikit-learn/auto_examples/plot_ML_flow_chart.html @@ -0,0 +1,386 @@ + + + + + + + + 3.4.8.17. Tutorial Diagrams — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.4.8.17. Tutorial Diagrams

+

This script plots the flow-charts used in the scikit-learn tutorials.

+
    +
  • plot ML flow chart
  • +
  • plot ML flow chart
  • +
  • plot ML flow chart
  • +
+
import numpy as np
+
import matplotlib.pyplot as plt +
from matplotlib.patches import Circle, Rectangle, Polygon, Arrow, FancyArrow +
+
+
def create_base(box_bg="#CCCCCC", arrow1="#88CCFF", arrow2="#88FF88", supervised=True): +
fig = plt.figure(figsize=(9, 6), facecolor="w") +
ax = plt.axes((0, 0, 1, 1), xticks=[], yticks=[], frameon=False) +
ax.set_xlim(0, 9) +
ax.set_ylim(0, 6) +
+
patches = [ +
Rectangle((0.3, 3.6), 1.5, 1.8, zorder=1, fc=box_bg), +
Rectangle((0.5, 3.8), 1.5, 1.8, zorder=2, fc=box_bg), +
Rectangle((0.7, 4.0), 1.5, 1.8, zorder=3, fc=box_bg), +
Rectangle((2.9, 3.6), 0.2, 1.8, fc=box_bg), +
Rectangle((3.1, 3.8), 0.2, 1.8, fc=box_bg), +
Rectangle((3.3, 4.0), 0.2, 1.8, fc=box_bg), +
Rectangle((0.3, 0.2), 1.5, 1.8, fc=box_bg), +
Rectangle((2.9, 0.2), 0.2, 1.8, fc=box_bg), +
Circle((5.5, 3.5), 1.0, fc=box_bg), +
Polygon([[5.5, 1.7], [6.1, 1.1], [5.5, 0.5], [4.9, 1.1]], fc=box_bg), +
FancyArrow( +
2.3, 4.6, 0.35, 0, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2 +
), +
FancyArrow( +
3.75, 4.2, 0.5, -0.2, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2 +
), +
FancyArrow( +
5.5, 2.4, 0, -0.4, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2 +
), +
FancyArrow( +
2.0, 1.1, 0.5, 0, fc=arrow2, width=0.25, head_width=0.5, head_length=0.2 +
), +
FancyArrow( +
3.3, 1.1, 1.3, 0, fc=arrow2, width=0.25, head_width=0.5, head_length=0.2 +
), +
FancyArrow( +
6.2, 1.1, 0.8, 0, fc=arrow2, width=0.25, head_width=0.5, head_length=0.2 +
), +
] +
+
if supervised: +
patches += [ +
Rectangle((0.3, 2.4), 1.5, 0.5, zorder=1, fc=box_bg), +
Rectangle((0.5, 2.6), 1.5, 0.5, zorder=2, fc=box_bg), +
Rectangle((0.7, 2.8), 1.5, 0.5, zorder=3, fc=box_bg), +
FancyArrow( +
2.3, 2.9, 2.0, 0, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2 +
), +
Rectangle((7.3, 0.85), 1.5, 0.5, fc=box_bg), +
] +
else: +
patches += [Rectangle((7.3, 0.2), 1.5, 1.8, fc=box_bg)] +
+
for p in patches: +
ax.add_patch(p) +
+
plt.text( +
1.45, +
4.9, +
"Training\nText,\nDocuments,\nImages,\netc.", +
ha="center", +
va="center", +
fontsize=14, +
) +
+
plt.text(3.6, 4.9, "Feature\nVectors", ha="left", va="center", fontsize=14) +
+
plt.text( +
5.5, 3.5, "Machine\nLearning\nAlgorithm", ha="center", va="center", fontsize=14 +
) +
+
plt.text( +
1.05, +
1.1, +
"New Text,\nDocument,\nImage,\netc.", +
ha="center", +
va="center", +
fontsize=14, +
) +
+
plt.text(3.3, 1.7, "Feature\nVector", ha="left", va="center", fontsize=14) +
+
plt.text(5.5, 1.1, "Predictive\nModel", ha="center", va="center", fontsize=12) +
+
if supervised: +
plt.text(1.45, 3.05, "Labels", ha="center", va="center", fontsize=14) +
+
plt.text(8.05, 1.1, "Expected\nLabel", ha="center", va="center", fontsize=14) +
plt.text( +
8.8, 5.8, "Supervised Learning Model", ha="right", va="top", fontsize=18 +
) +
+
else: +
plt.text( +
8.05, +
1.1, +
"Likelihood\nor Cluster ID\nor Better\nRepresentation", +
ha="center", +
va="center", +
fontsize=12, +
) +
plt.text( +
8.8, 5.8, "Unsupervised Learning Model", ha="right", va="top", fontsize=18 +
) +
+
+
def plot_supervised_chart(annotate=False): +
create_base(supervised=True) +
if annotate: +
fontdict = {"color": "r", "weight": "bold", "size": 14} +
plt.text( +
1.9, +
4.55, +
"X = vec.fit_transform(input)", +
fontdict=fontdict, +
rotation=20, +
ha="left", +
va="bottom", +
) +
plt.text( +
3.7, +
3.2, +
"clf.fit(X, y)", +
fontdict=fontdict, +
rotation=20, +
ha="left", +
va="bottom", +
) +
plt.text( +
1.7, +
1.5, +
"X_new = vec.transform(input)", +
fontdict=fontdict, +
rotation=20, +
ha="left", +
va="bottom", +
) +
plt.text( +
6.1, +
1.5, +
"y_new = clf.predict(X_new)", +
fontdict=fontdict, +
rotation=20, +
ha="left", +
va="bottom", +
) +
+
+
def plot_unsupervised_chart(): +
create_base(supervised=False) +
+
+
if __name__ == "__main__": +
plot_supervised_chart(False) +
plot_supervised_chart(True) +
plot_unsupervised_chart() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.214 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-learn/auto_examples/plot_bias_variance.html b/packages/scikit-learn/auto_examples/plot_bias_variance.html new file mode 100644 index 000000000..da965acf8 --- /dev/null +++ b/packages/scikit-learn/auto_examples/plot_bias_variance.html @@ -0,0 +1,373 @@ + + + + + + + + 3.4.8.16. Bias and variance of polynomial fit — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.4.8.16. Bias and variance of polynomial fit

+

Demo overfitting, underfitting, and validation and learning curves with +polynomial regression.

+

Fit polynomes of different degrees to a dataset: for too small a degree, +the model underfits, while for too large a degree, it overfits.

+
import numpy as np
+
import matplotlib.pyplot as plt +
+
+
def generating_func(x, rng=None, error=0.5): +
rng = np.random.default_rng(rng) +
return rng.normal(10 - 1.0 / (x + 0.1), error) +
+
+

A polynomial regression

+
from sklearn.pipeline import make_pipeline
+
from sklearn.linear_model import LinearRegression +
from sklearn.preprocessing import PolynomialFeatures +
+
+

A simple figure to illustrate the problem

+
n_samples = 8
+
+
rng = np.random.default_rng(27446968) +
x = 10 ** np.linspace(-2, 0, n_samples) +
y = generating_func(x, rng=rng) +
+
x_test = np.linspace(-0.2, 1.2, 1000) +
+
titles = ["d = 1 (under-fit; high bias)", "d = 2", "d = 6 (over-fit; high variance)"] +
degrees = [1, 2, 6] +
+
fig = plt.figure(figsize=(9, 3.5)) +
fig.subplots_adjust(left=0.06, right=0.98, bottom=0.15, top=0.85, wspace=0.05) +
+
for i, d in enumerate(degrees): +
ax = fig.add_subplot(131 + i, xticks=[], yticks=[]) +
ax.scatter(x, y, marker="x", c="k", s=50) +
+
model = make_pipeline(PolynomialFeatures(d), LinearRegression()) +
model.fit(x[:, np.newaxis], y) +
ax.plot(x_test, model.predict(x_test[:, np.newaxis]), "-b") +
+
ax.set_xlim(-0.2, 1.2) +
ax.set_ylim(0, 12) +
ax.set_xlabel("house size") +
if i == 0: +
ax.set_ylabel("price") +
+
ax.set_title(titles[i]) +
+
+d = 1 (under-fit; high bias), d = 2, d = 6 (over-fit; high variance)

Generate a larger dataset

+
from sklearn.model_selection import train_test_split
+
+
n_samples = 200 +
test_size = 0.4 +
error = 1.0 +
+
# randomly sample the data +
x = rng.random(n_samples) +
y = generating_func(x, rng=rng, error=error) +
+
# split into training, validation, and testing sets. +
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=test_size) +
+
# show the training and validation sets +
plt.figure(figsize=(6, 4)) +
plt.scatter(x_train, y_train, color="red", label="Training set") +
plt.scatter(x_test, y_test, color="blue", label="Test set") +
plt.title("The data") +
plt.legend(loc="best") +
+
+The data
<matplotlib.legend.Legend object at 0x7f5b035ac350>
+
+
+

Plot a validation curve

+
from sklearn.model_selection import validation_curve
+
+
degrees = list(range(1, 21)) +
+
model = make_pipeline(PolynomialFeatures(), LinearRegression()) +
+
# The parameter to vary is the "degrees" on the pipeline step +
# "polynomialfeatures" +
train_scores, validation_scores = validation_curve( +
model, +
x[:, np.newaxis], +
y, +
param_name="polynomialfeatures__degree", +
param_range=degrees, +
) +
+
# Plot the mean train error and validation error across folds +
plt.figure(figsize=(6, 4)) +
plt.plot(degrees, validation_scores.mean(axis=1), lw=2, label="cross-validation") +
plt.plot(degrees, train_scores.mean(axis=1), lw=2, label="training") +
+
plt.legend(loc="best") +
plt.xlabel("degree of fit") +
plt.ylabel("explained variance") +
plt.title("Validation curve") +
plt.tight_layout() +
+
+Validation curve
+

Learning curves

+
+

Plot train and test error with an increasing number of samples

+
+
# A learning curve for d=1, 5, 15
+
for d in [1, 5, 15]: +
model = make_pipeline(PolynomialFeatures(degree=d), LinearRegression()) +
+
from sklearn.model_selection import learning_curve +
+
train_sizes, train_scores, validation_scores = learning_curve( +
model, x[:, np.newaxis], y, train_sizes=np.logspace(-1, 0, 20) +
) +
+
# Plot the mean train error and validation error across folds +
plt.figure(figsize=(6, 4)) +
plt.plot( +
train_sizes, validation_scores.mean(axis=1), lw=2, label="cross-validation" +
) +
plt.plot(train_sizes, train_scores.mean(axis=1), lw=2, label="training") +
plt.ylim(ymin=-0.1, ymax=1) +
+
plt.legend(loc="best") +
plt.xlabel("number of train samples") +
plt.ylabel("explained variance") +
plt.title("Learning curve (degree=%i)" % d) +
plt.tight_layout() +
+
+
plt.show() +
+
+
    +
  • Learning curve (degree=1)
  • +
  • Learning curve (degree=5)
  • +
  • Learning curve (degree=15)
  • +
+

Total running time of the script: (0 minutes 1.391 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-learn/auto_examples/plot_california_prediction.html b/packages/scikit-learn/auto_examples/plot_california_prediction.html new file mode 100644 index 000000000..be11681ff --- /dev/null +++ b/packages/scikit-learn/auto_examples/plot_california_prediction.html @@ -0,0 +1,305 @@ + + + + + + + + 3.4.8.11. A simple regression analysis on the California housing data — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.4.8.11. A simple regression analysis on the California housing data

+

Here we perform a simple regression analysis on the California housing +data, exploring two types of regressors.

+
from sklearn.datasets import fetch_california_housing
+
+
data = fetch_california_housing(as_frame=True) +
+
+

Print a histogram of the quantity to predict: price

+
import matplotlib.pyplot as plt
+
+
plt.figure(figsize=(4, 3)) +
plt.hist(data.target) +
plt.xlabel("price ($100k)") +
plt.ylabel("count") +
plt.tight_layout() +
+
+plot california prediction

Print the join histogram for each feature

+
for index, feature_name in enumerate(data.feature_names):
+
plt.figure(figsize=(4, 3)) +
plt.scatter(data.data[feature_name], data.target) +
plt.ylabel("Price", size=15) +
plt.xlabel(feature_name, size=15) +
plt.tight_layout() +
+
+
    +
  • plot california prediction
  • +
  • plot california prediction
  • +
  • plot california prediction
  • +
  • plot california prediction
  • +
  • plot california prediction
  • +
  • plot california prediction
  • +
  • plot california prediction
  • +
  • plot california prediction
  • +
+

Simple prediction

+
from sklearn.model_selection import train_test_split
+
+
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target) +
+
from sklearn.linear_model import LinearRegression +
+
clf = LinearRegression() +
clf.fit(X_train, y_train) +
predicted = clf.predict(X_test) +
expected = y_test +
+
plt.figure(figsize=(4, 3)) +
plt.scatter(expected, predicted) +
plt.plot([0, 8], [0, 8], "--k") +
plt.axis("tight") +
plt.xlabel("True price ($100k)") +
plt.ylabel("Predicted price ($100k)") +
plt.tight_layout() +
+
+plot california prediction

Prediction with gradient boosted tree

+
from sklearn.ensemble import GradientBoostingRegressor
+
+
clf = GradientBoostingRegressor() +
clf.fit(X_train, y_train) +
+
predicted = clf.predict(X_test) +
expected = y_test +
+
plt.figure(figsize=(4, 3)) +
plt.scatter(expected, predicted) +
plt.plot([0, 5], [0, 5], "--k") +
plt.axis("tight") +
plt.xlabel("True price ($100k)") +
plt.ylabel("Predicted price ($100k)") +
plt.tight_layout() +
+
+plot california prediction

Print the error rate

+
import numpy as np
+
+
print(f"RMS: {np.sqrt(np.mean((predicted - expected) ** 2))!r} ") +
+
plt.show() +
+
+
RMS: np.float64(0.5314909993118918)
+
+
+

Total running time of the script: (0 minutes 4.717 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-learn/auto_examples/plot_compare_classifiers.html b/packages/scikit-learn/auto_examples/plot_compare_classifiers.html new file mode 100644 index 000000000..4c6d2cb30 --- /dev/null +++ b/packages/scikit-learn/auto_examples/plot_compare_classifiers.html @@ -0,0 +1,283 @@ + + + + + + + + 3.4.8.9. Compare classifiers on the digits data — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.4.8.9. Compare classifiers on the digits data

+

Compare the performance of a variety of classifiers on a test set for the +digits data.

+
LinearSVC: 0.9344942114287969
+
GaussianNB: 0.8332741681010102 +
KNeighborsClassifier: 0.9804562804949924 +
------------------ +
/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages/sklearn/svm/_base.py:1235: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations. +
warnings.warn( +
LinearSVC(loss='hinge'): 0.9294570108037394 +
LinearSVC(loss='squared_hinge'): 0.9344942114287969 +
------------------- +
KNeighbors(n_neighbors=1): 0.9913675218842191 +
KNeighbors(n_neighbors=2): 0.9848442068835102 +
KNeighbors(n_neighbors=3): 0.9867753449543099 +
KNeighbors(n_neighbors=4): 0.9803719053818863 +
KNeighbors(n_neighbors=5): 0.9804562804949924 +
KNeighbors(n_neighbors=6): 0.9757924194139573 +
KNeighbors(n_neighbors=7): 0.9780645792142071 +
KNeighbors(n_neighbors=8): 0.9780645792142071 +
KNeighbors(n_neighbors=9): 0.9780645792142071 +
KNeighbors(n_neighbors=10): 0.9755550897728812 +
+
+
+

+
+
from sklearn import model_selection, datasets, metrics
+
from sklearn.svm import LinearSVC +
from sklearn.naive_bayes import GaussianNB +
from sklearn.neighbors import KNeighborsClassifier +
+
digits = datasets.load_digits() +
X = digits.data +
y = digits.target +
X_train, X_test, y_train, y_test = model_selection.train_test_split( +
X, y, test_size=0.25, random_state=0 +
) +
+
for Model in [LinearSVC, GaussianNB, KNeighborsClassifier]: +
clf = Model().fit(X_train, y_train) +
y_pred = clf.predict(X_test) +
print(f"{Model.__name__}: {metrics.f1_score(y_test, y_pred, average='macro')}") +
+
print("------------------") +
+
# test SVC loss +
for loss in ["hinge", "squared_hinge"]: +
clf = LinearSVC(loss=loss).fit(X_train, y_train) +
y_pred = clf.predict(X_test) +
print( +
f"LinearSVC(loss='{loss}'): {metrics.f1_score(y_test, y_pred, average='macro')}" +
) +
+
print("-------------------") +
+
# test the number of neighbors +
for n_neighbors in range(1, 11): +
clf = KNeighborsClassifier(n_neighbors=n_neighbors).fit(X_train, y_train) +
y_pred = clf.predict(X_test) +
print( +
f"KNeighbors(n_neighbors={n_neighbors}): {metrics.f1_score(y_test, y_pred, average='macro')}" +
) +
+
+

Total running time of the script: (0 minutes 0.258 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-learn/auto_examples/plot_digits_simple_classif.html b/packages/scikit-learn/auto_examples/plot_digits_simple_classif.html new file mode 100644 index 000000000..11aacab14 --- /dev/null +++ b/packages/scikit-learn/auto_examples/plot_digits_simple_classif.html @@ -0,0 +1,371 @@ + + + + + + + + 3.4.8.13. Simple visualization and classification of the digits dataset — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.4.8.13. Simple visualization and classification of the digits dataset

+

Plot the first few samples of the digits dataset and a 2D representation +built using PCA, then do a simple classification

+
from sklearn.datasets import load_digits
+
+
digits = load_digits() +
+
+
+

Plot the data: images of digits

+

Each data in a 8x8 image

+
import matplotlib.pyplot as plt
+
+
fig = plt.figure(figsize=(6, 6)) # figure size in inches +
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05) +
+
for i in range(64): +
ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[]) +
ax.imshow(digits.images[i], cmap="binary", interpolation="nearest") +
# label the image with the target value +
ax.text(0, 7, str(digits.target[i])) +
+
+plot digits simple classif
+
+

Plot a projection on the 2 first principal axis

+
plt.figure()
+
+
from sklearn.decomposition import PCA +
+
pca = PCA(n_components=2) +
proj = pca.fit_transform(digits.data) +
plt.scatter(proj[:, 0], proj[:, 1], c=digits.target, cmap="Paired") +
plt.colorbar() +
+
+plot digits simple classif
<matplotlib.colorbar.Colorbar object at 0x7f5b03713140>
+
+
+
+
+

Classify with Gaussian naive Bayes

+
from sklearn.naive_bayes import GaussianNB
+
from sklearn.model_selection import train_test_split +
+
# split the data into training and validation sets +
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target) +
+
# train the model +
clf = GaussianNB() +
clf.fit(X_train, y_train) +
+
# use the model to predict the labels of the test data +
predicted = clf.predict(X_test) +
expected = y_test +
+
# Plot the prediction +
fig = plt.figure(figsize=(6, 6)) # figure size in inches +
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05) +
+
# plot the digits: each image is 8x8 pixels +
for i in range(64): +
ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[]) +
ax.imshow(X_test.reshape(-1, 8, 8)[i], cmap="binary", interpolation="nearest") +
+
# label the image with the target value +
if predicted[i] == expected[i]: +
ax.text(0, 7, str(predicted[i]), color="green") +
else: +
ax.text(0, 7, str(predicted[i]), color="red") +
+
+plot digits simple classif
+
+

Quantify the performance

+

First print the number of correct matches

+
matches = predicted == expected
+
print(matches.sum()) +
+
+
395
+
+
+

The total number of data points

+
print(len(matches))
+
+
+
450
+
+
+

And now, the ration of correct predictions

+
matches.sum() / float(len(matches))
+
+
+
np.float64(0.8777777777777778)
+
+
+

Print the classification report

+
from sklearn import metrics
+
+
print(metrics.classification_report(expected, predicted)) +
+
+
              precision    recall  f1-score   support
+
+
0 0.97 0.95 0.96 37 +
1 0.83 0.85 0.84 41 +
2 0.89 0.84 0.86 49 +
3 0.93 0.83 0.88 47 +
4 0.93 0.90 0.92 42 +
5 0.89 0.95 0.92 42 +
6 0.98 0.97 0.97 60 +
7 0.81 0.98 0.88 47 +
8 0.65 0.87 0.75 39 +
9 0.97 0.63 0.76 46 +
+
accuracy 0.88 450 +
macro avg 0.89 0.88 0.87 450 +
weighted avg 0.89 0.88 0.88 450 +
+
+

Print the confusion matrix

+ +
[[35  0  0  0  1  0  0  1  0  0]
+
[ 0 35 0 0 0 0 1 1 4 0] +
[ 0 1 41 0 0 0 0 0 7 0] +
[ 0 0 2 39 0 1 0 2 2 1] +
[ 0 1 0 0 38 0 0 2 1 0] +
[ 0 0 0 0 1 40 0 1 0 0] +
[ 0 0 1 0 1 0 58 0 0 0] +
[ 0 0 0 0 0 1 0 46 0 0] +
[ 0 2 0 1 0 1 0 1 34 0] +
[ 1 3 2 2 0 2 0 3 4 29]] +
+
+

Total running time of the script: (0 minutes 1.749 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-learn/auto_examples/plot_eigenfaces.html b/packages/scikit-learn/auto_examples/plot_eigenfaces.html new file mode 100644 index 000000000..cc95a189e --- /dev/null +++ b/packages/scikit-learn/auto_examples/plot_eigenfaces.html @@ -0,0 +1,1306 @@ + + + + + + + + 3.4.8.14. The eigenfaces example: chaining PCA and SVMs — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.4.8.14. The eigenfaces example: chaining PCA and SVMs

+

The goal of this example is to show how an unsupervised method and a +supervised one can be chained for better prediction. It starts with a +didactic but lengthy way of doing things, and finishes with the +idiomatic approach to pipelining in scikit-learn.

+

Here we’ll take a look at a simple facial recognition example. Ideally, +we would use a dataset consisting of a subset of the Labeled Faces in +the Wild data that is available +with sklearn.datasets.fetch_lfw_people(). However, this is a +relatively large download (~200MB) so we will do the tutorial on a +simpler, less rich dataset. Feel free to explore the LFW dataset.

+
from sklearn import datasets
+
+
faces = datasets.fetch_olivetti_faces() +
faces.data.shape +
+
+
downloading Olivetti faces from https://ndownloader.figshare.com/files/5976027 to /home/runner/scikit_learn_data
+
+
(400, 4096) +
+
+

Let’s visualize these faces to see what we’re working with

+
import matplotlib.pyplot as plt
+
+
fig = plt.figure(figsize=(8, 6)) +
# plot several images +
for i in range(15): +
ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[]) +
ax.imshow(faces.images[i], cmap="bone") +
+
+plot eigenfaces
+

Tip

+

Note is that these faces have already been localized and scaled to a +common size. This is an important preprocessing piece for facial +recognition, and is a process that can require a large collection of +training data. This can be done in scikit-learn, but the challenge is +gathering a sufficient amount of training data for the algorithm to work. +Fortunately, this piece is common enough that it has been done. One good +resource is +OpenCV, +the Open Computer Vision Library.

+
+

We’ll perform a Support Vector classification of the images. We’ll do a +typical train-test split on the images:

+
from sklearn.model_selection import train_test_split
+
+
X_train, X_test, y_train, y_test = train_test_split( +
faces.data, faces.target, random_state=0 +
) +
+
print(X_train.shape, X_test.shape) +
+
+
(300, 4096) (100, 4096)
+
+
+
+

Preprocessing: Principal Component Analysis

+

1850 dimensions is a lot for SVM. We can use PCA to reduce these 1850 +features to a manageable size, while maintaining most of the information +in the dataset.

+
from sklearn import decomposition
+
+
pca = decomposition.PCA(n_components=150, whiten=True) +
pca.fit(X_train) +
+
+
+
PCA(n_components=150, whiten=True)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
+
+
+

One interesting part of PCA is that it computes the “mean” face, which +can be interesting to examine:

+
plt.imshow(pca.mean_.reshape(faces.images[0].shape), cmap="bone")
+
+
+plot eigenfaces
<matplotlib.image.AxesImage object at 0x7f5b015911c0>
+
+
+

The principal components measure deviations about this mean along +orthogonal axes.

+ +
(150, 4096)
+
+
+

It is also interesting to visualize these principal components:

+
fig = plt.figure(figsize=(16, 6))
+
for i in range(30): +
ax = fig.add_subplot(3, 10, i + 1, xticks=[], yticks=[]) +
ax.imshow(pca.components_[i].reshape(faces.images[0].shape), cmap="bone") +
+
+plot eigenfaces

The components (“eigenfaces”) are ordered by their importance from +top-left to bottom-right. We see that the first few components seem to +primarily take care of lighting conditions; the remaining components +pull out certain identifying features: the nose, eyes, eyebrows, etc.

+

With this projection computed, we can now project our original training +and test data onto the PCA basis:

+ +
(300, 150)
+
+
+
+
+
(100, 150)
+
+
+

These projected components correspond to factors in a linear combination +of component images such that the combination approaches the original +face.

+
+
+

Doing the Learning: Support Vector Machines

+

Now we’ll perform support-vector-machine classification on this reduced +dataset:

+
from sklearn import svm
+
+
clf = svm.SVC(C=5.0, gamma=0.001) +
clf.fit(X_train_pca, y_train) +
+
+
+
SVC(C=5.0, gamma=0.001)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
+
+
+

Finally, we can evaluate how well this classification did. First, we +might plot a few of the test-cases with the labels learned from the +training set:

+
import numpy as np
+
+
fig = plt.figure(figsize=(8, 6)) +
for i in range(15): +
ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[]) +
ax.imshow(X_test[i].reshape(faces.images[0].shape), cmap="bone") +
y_pred = clf.predict(X_test_pca[i, np.newaxis])[0] +
color = "black" if y_pred == y_test[i] else "red" +
ax.set_title(y_pred, fontsize="small", color=color) +
+
+13, 30, 34, 19, 24, 6, 15, 26, 14, 21, 3, 13, 11, 34, 1

The classifier is correct on an impressive number of images given the +simplicity of its learning model! Using a linear classifier on 150 +features derived from the pixel-level data, the algorithm correctly +identifies a large number of the people in the images.

+

Again, we can quantify this effectiveness using one of several measures +from sklearn.metrics. First we can do the classification +report, which shows the precision, recall and other measures of the +“goodness” of the classification:

+
from sklearn import metrics
+
+
y_pred = clf.predict(X_test_pca) +
print(metrics.classification_report(y_test, y_pred)) +
+
+
              precision    recall  f1-score   support
+
+
0 1.00 0.50 0.67 6 +
1 1.00 1.00 1.00 4 +
2 0.50 1.00 0.67 2 +
3 1.00 1.00 1.00 1 +
4 0.33 1.00 0.50 1 +
5 1.00 1.00 1.00 5 +
6 1.00 1.00 1.00 4 +
7 1.00 0.67 0.80 3 +
9 1.00 1.00 1.00 1 +
10 1.00 1.00 1.00 4 +
11 1.00 1.00 1.00 1 +
12 0.67 1.00 0.80 2 +
13 1.00 1.00 1.00 3 +
14 1.00 1.00 1.00 5 +
15 1.00 1.00 1.00 3 +
17 1.00 1.00 1.00 6 +
19 1.00 1.00 1.00 4 +
20 1.00 1.00 1.00 1 +
21 1.00 1.00 1.00 1 +
22 1.00 1.00 1.00 2 +
23 1.00 1.00 1.00 1 +
24 1.00 1.00 1.00 2 +
25 1.00 0.50 0.67 2 +
26 1.00 0.75 0.86 4 +
27 1.00 1.00 1.00 1 +
28 0.67 1.00 0.80 2 +
29 1.00 1.00 1.00 3 +
30 1.00 1.00 1.00 4 +
31 1.00 1.00 1.00 3 +
32 1.00 1.00 1.00 3 +
33 1.00 1.00 1.00 2 +
34 1.00 1.00 1.00 3 +
35 1.00 1.00 1.00 1 +
36 1.00 1.00 1.00 3 +
37 1.00 1.00 1.00 3 +
38 1.00 1.00 1.00 1 +
39 1.00 1.00 1.00 3 +
+
accuracy 0.94 100 +
macro avg 0.95 0.96 0.94 100 +
weighted avg 0.97 0.94 0.94 100 +
+
+

Another interesting metric is the confusion matrix, which indicates +how often any two items are mixed-up. The confusion matrix of a perfect +classifier would only have nonzero entries on the diagonal, with zeros +on the off-diagonal:

+ +
[[3 0 0 ... 0 0 0]
+
[0 4 0 ... 0 0 0] +
[0 0 2 ... 0 0 0] +
... +
[0 0 0 ... 3 0 0] +
[0 0 0 ... 0 1 0] +
[0 0 0 ... 0 0 3]] +
+
+
+
+

Pipelining

+

Above we used PCA as a pre-processing step before applying our support +vector machine classifier. Plugging the output of one estimator directly +into the input of a second estimator is a commonly used pattern; for +this reason scikit-learn provides a Pipeline object which automates +this process. The above problem can be re-expressed as a pipeline as +follows:

+
from sklearn.pipeline import Pipeline
+
+
clf = Pipeline( +
[ +
("pca", decomposition.PCA(n_components=150, whiten=True)), +
("svm", svm.LinearSVC(C=1.0)), +
] +
) +
+
clf.fit(X_train, y_train) +
+
y_pred = clf.predict(X_test) +
print(metrics.confusion_matrix(y_pred, y_test)) +
plt.show() +
+
+
[[4 0 0 ... 0 0 0]
+
[0 4 0 ... 0 0 0] +
[0 0 1 ... 0 0 0] +
... +
[1 0 0 ... 3 0 0] +
[0 0 0 ... 0 1 0] +
[0 0 0 ... 0 0 3]] +
+
+
+
+

A Note on Facial Recognition

+

Here we have used PCA “eigenfaces” as a pre-processing step for facial +recognition. The reason we chose this is because PCA is a +broadly-applicable technique, which can be useful for a wide array of +data types. Research in the field of facial recognition in particular, +however, has shown that other more specific feature extraction methods +are can be much more effective.

+

Total running time of the script: (0 minutes 4.145 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-learn/auto_examples/plot_iris_knn.html b/packages/scikit-learn/auto_examples/plot_iris_knn.html new file mode 100644 index 000000000..99d5d9acb --- /dev/null +++ b/packages/scikit-learn/auto_examples/plot_iris_knn.html @@ -0,0 +1,279 @@ + + + + + + + + 3.4.8.12. Nearest-neighbor prediction on iris — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.4.8.12. Nearest-neighbor prediction on iris

+

Plot the decision boundary of nearest neighbor decision on iris, first +with a single nearest neighbor, and then using 3 nearest neighbors.

+
import numpy as np
+
import matplotlib.pyplot as plt +
from sklearn import neighbors, datasets +
from matplotlib.colors import ListedColormap +
+
# Create color maps for 3-class classification problem, as with iris +
cmap_light = ListedColormap(["#FFAAAA", "#AAFFAA", "#AAAAFF"]) +
cmap_bold = ListedColormap(["#FF0000", "#00FF00", "#0000FF"]) +
+
iris = datasets.load_iris() +
X = iris.data[:, :2] # we only take the first two features. We could +
# avoid this ugly slicing by using a two-dim dataset +
y = iris.target +
+
knn = neighbors.KNeighborsClassifier(n_neighbors=1) +
knn.fit(X, y) +
+
x_min, x_max = X[:, 0].min() - 0.1, X[:, 0].max() + 0.1 +
y_min, y_max = X[:, 1].min() - 0.1, X[:, 1].max() + 0.1 +
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100), np.linspace(y_min, y_max, 100)) +
Z = knn.predict(np.c_[xx.ravel(), yy.ravel()]) +
+
+

Put the result into a color plot

+
Z = Z.reshape(xx.shape)
+
plt.figure() +
plt.pcolormesh(xx, yy, Z, cmap=cmap_light) +
+
# Plot also the training points +
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold) +
plt.xlabel("sepal length (cm)") +
plt.ylabel("sepal width (cm)") +
plt.axis("tight") +
+
+plot iris knn
(np.float64(4.180808080808081), np.float64(8.019191919191918), np.float64(1.8868686868686868), np.float64(4.513131313131313))
+
+
+

And now, redo the analysis with 3 neighbors

+
knn = neighbors.KNeighborsClassifier(n_neighbors=3)
+
knn.fit(X, y) +
+
Z = knn.predict(np.c_[xx.ravel(), yy.ravel()]) +
+
# Put the result into a color plot +
Z = Z.reshape(xx.shape) +
plt.figure() +
plt.pcolormesh(xx, yy, Z, cmap=cmap_light) +
+
# Plot also the training points +
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold) +
plt.xlabel("sepal length (cm)") +
plt.ylabel("sepal width (cm)") +
plt.axis("tight") +
+
plt.show() +
+
+plot iris knn

Total running time of the script: (0 minutes 0.795 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-learn/auto_examples/plot_iris_scatter.html b/packages/scikit-learn/auto_examples/plot_iris_scatter.html new file mode 100644 index 000000000..a6fdcfd55 --- /dev/null +++ b/packages/scikit-learn/auto_examples/plot_iris_scatter.html @@ -0,0 +1,247 @@ + + + + + + + + 3.4.8.4. Plot 2D views of the iris dataset — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.4.8.4. Plot 2D views of the iris dataset

+

Plot a simple scatter plot of 2 features of the iris dataset.

+

Note that more elaborate visualization of this dataset is detailed +in the Statistics in Python chapter.

+plot iris scatter
# Load the data
+
from sklearn.datasets import load_iris +
+
iris = load_iris() +
+
from matplotlib import ticker +
import matplotlib.pyplot as plt +
+
# The indices of the features that we are plotting +
x_index = 0 +
y_index = 1 +
+
# this formatter will label the colorbar with the correct target names +
formatter = ticker.FuncFormatter(lambda i, *args: iris.target_names[int(i)]) +
+
plt.figure(figsize=(5, 4)) +
plt.scatter(iris.data[:, x_index], iris.data[:, y_index], c=iris.target) +
plt.colorbar(ticks=[0, 1, 2], format=formatter) +
plt.xlabel(iris.feature_names[x_index]) +
plt.ylabel(iris.feature_names[y_index]) +
+
plt.tight_layout() +
plt.show() +
+
+

Total running time of the script: (0 minutes 0.093 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-learn/auto_examples/plot_linear_model_cv.html b/packages/scikit-learn/auto_examples/plot_linear_model_cv.html new file mode 100644 index 000000000..e6fd7c6df --- /dev/null +++ b/packages/scikit-learn/auto_examples/plot_linear_model_cv.html @@ -0,0 +1,263 @@ + + + + + + + + 3.4.8.6. Use the RidgeCV and LassoCV to set the regularization parameter — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.4.8.6. Use the RidgeCV and LassoCV to set the regularization parameter

+

Load the diabetes dataset

+
from sklearn.datasets import load_diabetes
+
+
data = load_diabetes() +
X, y = data.data, data.target +
print(X.shape) +
+
+
(442, 10)
+
+
+

Compute the cross-validation score with the default hyper-parameters

+
from sklearn.model_selection import cross_val_score
+
from sklearn.linear_model import Ridge, Lasso +
+
for Model in [Ridge, Lasso]: +
model = Model() +
print(f"{Model.__name__}: {cross_val_score(model, X, y).mean()}") +
+
+
Ridge: 0.410174971340889
+
Lasso: 0.3375593674654274 +
+
+

We compute the cross-validation score as a function of alpha, the +strength of the regularization for Lasso and Ridge

+
import numpy as np
+
import matplotlib.pyplot as plt +
+
alphas = np.logspace(-3, -1, 30) +
+
plt.figure(figsize=(5, 3)) +
+
for Model in [Lasso, Ridge]: +
scores = [cross_val_score(Model(alpha), X, y, cv=3).mean() for alpha in alphas] +
plt.plot(alphas, scores, label=Model.__name__) +
+
plt.legend(loc="lower left") +
plt.xlabel("alpha") +
plt.ylabel("cross validation score") +
plt.tight_layout() +
plt.show() +
+
+plot linear model cv

Total running time of the script: (0 minutes 0.391 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-learn/auto_examples/plot_linear_regression.html b/packages/scikit-learn/auto_examples/plot_linear_regression.html new file mode 100644 index 000000000..c6ecc1e56 --- /dev/null +++ b/packages/scikit-learn/auto_examples/plot_linear_regression.html @@ -0,0 +1,253 @@ + + + + + + + + 3.4.8.3. A simple linear regression — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.4.8.3. A simple linear regression

+plot linear regression
import numpy as np
+
import matplotlib.pyplot as plt +
from sklearn.linear_model import LinearRegression +
+
# x from 0 to 30 +
rng = np.random.default_rng() +
x = 30 * rng.random((20, 1)) +
+
# y = a*x + b with noise +
y = 0.5 * x + 1.0 + rng.normal(size=x.shape) +
+
# create a linear regression model +
model = LinearRegression() +
model.fit(x, y) +
+
# predict y from the data +
x_new = np.linspace(0, 30, 100) +
y_new = model.predict(x_new[:, np.newaxis]) +
+
# plot the results +
plt.figure(figsize=(4, 3)) +
ax = plt.axes() +
ax.scatter(x, y) +
ax.plot(x_new, y_new) +
+
ax.set_xlabel("x") +
ax.set_ylabel("y") +
+
ax.axis("tight") +
+
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.047 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-learn/auto_examples/plot_measuring_performance.html b/packages/scikit-learn/auto_examples/plot_measuring_performance.html new file mode 100644 index 000000000..8470cf8b9 --- /dev/null +++ b/packages/scikit-learn/auto_examples/plot_measuring_performance.html @@ -0,0 +1,251 @@ + + + + + + + + 3.4.8.2. Measuring Decision Tree performance — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.4.8.2. Measuring Decision Tree performance

+

Demonstrates overfit when testing on train set.

+

Get the data

+
from sklearn.datasets import fetch_california_housing
+
+
data = fetch_california_housing(as_frame=True) +
+
+

Train and test a model

+ +

Plot predicted as a function of expected

+
import matplotlib.pyplot as plt
+
+
plt.figure(figsize=(4, 3)) +
plt.scatter(expected, predicted) +
plt.plot([0, 5], [0, 5], "--k") +
plt.axis("tight") +
plt.xlabel("True price ($100k)") +
plt.ylabel("Predicted price ($100k)") +
plt.tight_layout() +
+
+plot measuring performance

Pretty much no errors!

+

This is too good to be true: we are testing the model on the train +data, which is not a measure of generalization.

+

The results are not valid

+

Total running time of the script: (0 minutes 1.300 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-learn/auto_examples/plot_pca.html b/packages/scikit-learn/auto_examples/plot_pca.html new file mode 100644 index 000000000..4a9f56a98 --- /dev/null +++ b/packages/scikit-learn/auto_examples/plot_pca.html @@ -0,0 +1,658 @@ + + + + + + + + 3.4.8.1. Demo PCA in 2D — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.4.8.1. Demo PCA in 2D

+

Load the iris data

+
from sklearn import datasets
+
+
iris = datasets.load_iris() +
X = iris.data +
y = iris.target +
+
+

Fit a PCA

+
from sklearn.decomposition import PCA
+
+
pca = PCA(n_components=2, whiten=True) +
pca.fit(X) +
+
+
+
PCA(n_components=2, whiten=True)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
+
+
+

Project the data in 2D

+ +

Visualize the data

+
target_ids = range(len(iris.target_names))
+
+
import matplotlib.pyplot as plt +
+
plt.figure(figsize=(6, 5)) +
for i, c, label in zip(target_ids, "rgbcmykw", iris.target_names, strict=False): +
plt.scatter(X_pca[y == i, 0], X_pca[y == i, 1], c=c, label=label) +
plt.legend() +
plt.show() +
+
+plot pca

Total running time of the script: (0 minutes 0.099 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-learn/auto_examples/plot_polynomial_regression.html b/packages/scikit-learn/auto_examples/plot_polynomial_regression.html new file mode 100644 index 000000000..5444cd19f --- /dev/null +++ b/packages/scikit-learn/auto_examples/plot_polynomial_regression.html @@ -0,0 +1,285 @@ + + + + + + + + 3.4.8.10. Plot fitting a 9th order polynomial — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.4.8.10. Plot fitting a 9th order polynomial

+

Fits data generated from a 9th order polynomial with model of 4th order +and 9th order polynomials, to demonstrate that often simpler models are +to be preferred

+
import numpy as np
+
import matplotlib.pyplot as plt +
from matplotlib.colors import ListedColormap +
+
from sklearn import linear_model +
+
# Create color maps for 3-class classification problem, as with iris +
cmap_light = ListedColormap(["#FFAAAA", "#AAFFAA", "#AAAAFF"]) +
cmap_bold = ListedColormap(["#FF0000", "#00FF00", "#0000FF"]) +
+
+
rng = np.random.default_rng(27446968) +
x = 2 * rng.random(100) - 1 +
+
f = lambda t: 1.2 * t**2 + 0.1 * t**3 - 0.4 * t**5 - 0.5 * t**9 +
y = f(x) + 0.4 * rng.normal(size=100) +
+
x_test = np.linspace(-1, 1, 100) +
+
+

The data

+
plt.figure(figsize=(6, 4))
+
plt.scatter(x, y, s=4) +
+
+plot polynomial regression
<matplotlib.collections.PathCollection object at 0x7f5b029f5ac0>
+
+
+

Fitting 4th and 9th order polynomials

+

For this we need to engineer features: the n_th powers of x:

+
plt.figure(figsize=(6, 4))
+
plt.scatter(x, y, s=4) +
+
X = np.array([x**i for i in range(5)]).T +
X_test = np.array([x_test**i for i in range(5)]).T +
regr = linear_model.LinearRegression() +
regr.fit(X, y) +
plt.plot(x_test, regr.predict(X_test), label="4th order") +
+
X = np.array([x**i for i in range(10)]).T +
X_test = np.array([x_test**i for i in range(10)]).T +
regr = linear_model.LinearRegression() +
regr.fit(X, y) +
plt.plot(x_test, regr.predict(X_test), label="9th order") +
+
plt.legend(loc="best") +
plt.axis("tight") +
plt.title("Fitting a 4th and a 9th order polynomial") +
+
+Fitting a 4th and a 9th order polynomial
Text(0.5, 1.0, 'Fitting a 4th and a 9th order polynomial')
+
+
+

Ground truth

+
plt.figure(figsize=(6, 4))
+
plt.scatter(x, y, s=4) +
plt.plot(x_test, f(x_test), label="truth") +
plt.axis("tight") +
plt.title("Ground truth (9th order polynomial)") +
+
plt.show() +
+
+Ground truth (9th order polynomial)

Total running time of the script: (0 minutes 0.175 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-learn/auto_examples/plot_separator.html b/packages/scikit-learn/auto_examples/plot_separator.html new file mode 100644 index 000000000..846291e5b --- /dev/null +++ b/packages/scikit-learn/auto_examples/plot_separator.html @@ -0,0 +1,258 @@ + + + + + + + + 3.4.8.8. Simple picture of the formal problem of machine learning — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.4.8.8. Simple picture of the formal problem of machine learning

+

This example generates simple synthetic data ploints and shows a +separating hyperplane on them.

+plot separator
import numpy as np
+
import matplotlib.pyplot as plt +
from sklearn.linear_model import SGDClassifier +
from sklearn.datasets import make_blobs +
+
# we create 50 separable synthetic points +
X, Y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.60) +
+
# fit the model +
clf = SGDClassifier(loss="hinge", alpha=0.01, fit_intercept=True) +
clf.fit(X, Y) +
+
# plot the line, the points, and the nearest vectors to the plane +
xx = np.linspace(-1, 5, 10) +
yy = np.linspace(-1, 5, 10) +
+
X1, X2 = np.meshgrid(xx, yy) +
Z = np.empty(X1.shape) +
for (i, j), val in np.ndenumerate(X1): +
x1 = val +
x2 = X2[i, j] +
p = clf.decision_function([[x1, x2]]) +
Z[i, j] = p[0] +
+
plt.figure(figsize=(4, 3)) +
ax = plt.axes() +
ax.contour( +
X1, X2, Z, [-1.0, 0.0, 1.0], colors="k", linestyles=["dashed", "solid", "dashed"] +
) +
ax.scatter(X[:, 0], X[:, 1], c=Y, cmap="Paired") +
+
ax.axis("tight") +
+
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.051 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-learn/auto_examples/plot_svm_non_linear.html b/packages/scikit-learn/auto_examples/plot_svm_non_linear.html new file mode 100644 index 000000000..f892c9115 --- /dev/null +++ b/packages/scikit-learn/auto_examples/plot_svm_non_linear.html @@ -0,0 +1,337 @@ + + + + + + + + 3.4.8.15. Example of linear and non-linear models — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.4.8.15. Example of linear and non-linear models

+

This is an example plot from the tutorial which accompanies an explanation +of the support vector machine GUI.

+
import numpy as np
+
import matplotlib.pyplot as plt +
+
from sklearn import svm +
+
+
rng = np.random.default_rng(27446968) +
+
+

data that is linearly separable

+
def linear_model(rseed=42, n_samples=30):
+
"Generate data according to a linear model" +
np.random.seed(rseed) +
+
data = np.random.normal(0, 10, (n_samples, 2)) +
data[: n_samples // 2] -= 15 +
data[n_samples // 2 :] += 15 +
+
labels = np.ones(n_samples) +
labels[: n_samples // 2] = -1 +
+
return data, labels +
+
+
X, y = linear_model() +
clf = svm.SVC(kernel="linear") +
clf.fit(X, y) +
+
plt.figure(figsize=(6, 4)) +
ax = plt.subplot(111, xticks=[], yticks=[]) +
ax.scatter(X[:, 0], X[:, 1], c=y, cmap="bone") +
+
ax.scatter( +
clf.support_vectors_[:, 0], +
clf.support_vectors_[:, 1], +
s=80, +
edgecolors="k", +
facecolors="none", +
) +
+
delta = 1 +
y_min, y_max = -50, 50 +
x_min, x_max = -50, 50 +
x = np.arange(x_min, x_max + delta, delta) +
y = np.arange(y_min, y_max + delta, delta) +
X1, X2 = np.meshgrid(x, y) +
Z = clf.decision_function(np.c_[X1.ravel(), X2.ravel()]) +
Z = Z.reshape(X1.shape) +
+
ax.contour( +
X1, X2, Z, [-1.0, 0.0, 1.0], colors="k", linestyles=["dashed", "solid", "dashed"] +
) +
+
+plot svm non linear
<matplotlib.contour.QuadContourSet object at 0x7f5b02545790>
+
+
+

data with a non-linear separation

+
def nonlinear_model(rseed=27446968, n_samples=30):
+
rng = np.random.default_rng(rseed) +
+
radius = 40 * rng.random(n_samples) +
far_pts = radius > 20 +
radius[far_pts] *= 1.2 +
radius[~far_pts] *= 1.1 +
+
theta = rng.random(n_samples) * np.pi * 2 +
+
data = np.empty((n_samples, 2)) +
data[:, 0] = radius * np.cos(theta) +
data[:, 1] = radius * np.sin(theta) +
+
labels = np.ones(n_samples) +
labels[far_pts] = -1 +
+
return data, labels +
+
+
X, y = nonlinear_model() +
clf = svm.SVC(kernel="rbf", gamma=0.001, coef0=0, degree=3) +
clf.fit(X, y) +
+
plt.figure(figsize=(6, 4)) +
ax = plt.subplot(1, 1, 1, xticks=[], yticks=[]) +
ax.scatter(X[:, 0], X[:, 1], c=y, cmap="bone", zorder=2) +
+
ax.scatter( +
clf.support_vectors_[:, 0], +
clf.support_vectors_[:, 1], +
s=80, +
edgecolors="k", +
facecolors="none", +
) +
+
delta = 1 +
y_min, y_max = -50, 50 +
x_min, x_max = -50, 50 +
x = np.arange(x_min, x_max + delta, delta) +
y = np.arange(y_min, y_max + delta, delta) +
X1, X2 = np.meshgrid(x, y) +
Z = clf.decision_function(np.c_[X1.ravel(), X2.ravel()]) +
Z = Z.reshape(X1.shape) +
+
ax.contour( +
X1, +
X2, +
Z, +
[-1.0, 0.0, 1.0], +
colors="k", +
linestyles=["dashed", "solid", "dashed"], +
zorder=1, +
) +
+
plt.show() +
+
+plot svm non linear

Total running time of the script: (0 minutes 0.068 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-learn/auto_examples/plot_tsne.html b/packages/scikit-learn/auto_examples/plot_tsne.html new file mode 100644 index 000000000..db2501ac1 --- /dev/null +++ b/packages/scikit-learn/auto_examples/plot_tsne.html @@ -0,0 +1,256 @@ + + + + + + + + 3.4.8.5. tSNE to visualize digits — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.4.8.5. tSNE to visualize digits

+

Here we use sklearn.manifold.TSNE to visualize the digits +datasets. Indeed, the digits are vectors in a 8*8 = 64 dimensional space. +We want to project them in 2D for visualization. tSNE is often a good +solution, as it groups and separates data points based on their local +relationship.

+

Load the iris data

+
from sklearn import datasets
+
+
digits = datasets.load_digits() +
# Take the first 500 data points: it's hard to see 1500 points +
X = digits.data[:500] +
y = digits.target[:500] +
+
+

Fit and transform with a TSNE

+
from sklearn.manifold import TSNE
+
+
tsne = TSNE(n_components=2, random_state=0) +
+
+

Project the data in 2D

+ +

Visualize the data

+
target_ids = range(len(digits.target_names))
+
+
import matplotlib.pyplot as plt +
+
plt.figure(figsize=(6, 5)) +
colors = "r", "g", "b", "c", "m", "y", "k", "w", "orange", "purple" +
for i, c, label in zip(target_ids, colors, digits.target_names, strict=True): +
plt.scatter(X_2d[y == i, 0], X_2d[y == i, 1], c=c, label=label) +
plt.legend() +
plt.show() +
+
+plot tsne

Total running time of the script: (0 minutes 1.216 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-learn/auto_examples/plot_variance_linear_regr.html b/packages/scikit-learn/auto_examples/plot_variance_linear_regr.html new file mode 100644 index 000000000..dab1ec82d --- /dev/null +++ b/packages/scikit-learn/auto_examples/plot_variance_linear_regr.html @@ -0,0 +1,272 @@ + + + + + + + + 3.4.8.7. Plot variance and regularization in linear models — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.4.8.7. Plot variance and regularization in linear models

+
import numpy as np
+
+
# Smaller figures +
import matplotlib.pyplot as plt +
+
plt.rcParams["figure.figsize"] = (3, 2) +
+
+

We consider the situation where we have only 2 data point

+
X = np.c_[0.5, 1].T
+
y = [0.5, 1] +
X_test = np.c_[0, 2].T +
+
+

Without noise, as linear regression fits the data perfectly

+
from sklearn import linear_model
+
+
regr = linear_model.LinearRegression() +
regr.fit(X, y) +
plt.plot(X, y, "o") +
plt.plot(X_test, regr.predict(X_test)) +
+
+plot variance linear regr
[<matplotlib.lines.Line2D object at 0x7f5b029f65d0>]
+
+
+

In real life situation, we have noise (e.g. measurement noise) in our data:

+
rng = np.random.default_rng(27446968)
+
for _ in range(6): +
noisy_X = X + np.random.normal(loc=0, scale=0.1, size=X.shape) +
plt.plot(noisy_X, y, "o") +
regr.fit(noisy_X, y) +
plt.plot(X_test, regr.predict(X_test)) +
+
+plot variance linear regr

As we can see, our linear model captures and amplifies the noise in the +data. It displays a lot of variance.

+

We can use another linear estimator that uses regularization, the +Ridge estimator. This estimator +regularizes the coefficients by shrinking them to zero, under the +assumption that very high correlations are often spurious. The alpha +parameter controls the amount of shrinkage used.

+
regr = linear_model.Ridge(alpha=0.1)
+
np.random.seed(0) +
for _ in range(6): +
noisy_X = X + np.random.normal(loc=0, scale=0.1, size=X.shape) +
plt.plot(noisy_X, y, "o") +
regr.fit(noisy_X, y) +
plt.plot(X_test, regr.predict(X_test)) +
+
plt.show() +
+
+plot variance linear regr

Total running time of the script: (0 minutes 0.107 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-learn/auto_examples/sg_execution_times.html b/packages/scikit-learn/auto_examples/sg_execution_times.html new file mode 100644 index 000000000..44c935715 --- /dev/null +++ b/packages/scikit-learn/auto_examples/sg_execution_times.html @@ -0,0 +1,270 @@ + + + + + + + + Computation times — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Computation times

+

00:16.816 total execution time for 17 files from packages/scikit-learn/auto_examples:

+
+ + + + + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Example

Time

Mem (MB)

A simple regression analysis on the California housing data (plot_california_prediction.py)

00:04.717

0.0

The eigenfaces example: chaining PCA and SVMs (plot_eigenfaces.py)

00:04.145

0.0

Simple visualization and classification of the digits dataset (plot_digits_simple_classif.py)

00:01.749

0.0

Bias and variance of polynomial fit (plot_bias_variance.py)

00:01.391

0.0

Measuring Decision Tree performance (plot_measuring_performance.py)

00:01.300

0.0

tSNE to visualize digits (plot_tsne.py)

00:01.216

0.0

Nearest-neighbor prediction on iris (plot_iris_knn.py)

00:00.795

0.0

Use the RidgeCV and LassoCV to set the regularization parameter (plot_linear_model_cv.py)

00:00.391

0.0

Compare classifiers on the digits data (plot_compare_classifiers.py)

00:00.258

0.0

Tutorial Diagrams (plot_ML_flow_chart.py)

00:00.214

0.0

Plot fitting a 9th order polynomial (plot_polynomial_regression.py)

00:00.175

0.0

Plot variance and regularization in linear models (plot_variance_linear_regr.py)

00:00.107

0.0

Demo PCA in 2D (plot_pca.py)

00:00.099

0.0

Plot 2D views of the iris dataset (plot_iris_scatter.py)

00:00.093

0.0

Example of linear and non-linear models (plot_svm_non_linear.py)

00:00.068

0.0

Simple picture of the formal problem of machine learning (plot_separator.py)

00:00.051

0.0

A simple linear regression (plot_linear_regression.py)

00:00.047

0.0

+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/scikit-learn/index.html b/packages/scikit-learn/index.html new file mode 100644 index 000000000..9d628c625 --- /dev/null +++ b/packages/scikit-learn/index.html @@ -0,0 +1,2020 @@ + + + + + + + + 3.4. scikit-learn: machine learning in Python — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

3.4. scikit-learn: machine learning in Python

+

Authors: Gael Varoquaux

+../../_images/scikit-learn-logo.png + + + +
+

See also

+

Data science in Python

+ +
+ +
+

3.4.1. Introduction: problem settings

+
+

3.4.1.1. What is machine learning?

+
+

Tip

+

Machine Learning is about building programs with tunable +parameters that are adjusted automatically so as to improve their +behavior by adapting to previously seen data.

+

Machine Learning can be considered a subfield of Artificial +Intelligence since those algorithms can be seen as building blocks +to make computers learn to behave more intelligently by somehow +generalizing rather that just storing and retrieving data items +like a database system would do.

+
+
+../../_images/sphx_glr_plot_separator_001.png + +
+

A classification problem

+
+
+

We’ll take a look at two very simple machine learning tasks here. The +first is a classification task: the figure shows a collection of +two-dimensional data, colored according to two different class labels. A +classification algorithm may be used to draw a dividing boundary between +the two clusters of points:

+

By drawing this separating line, we have learned a model which can +generalize to new data: if you were to drop another point onto the +plane which is unlabeled, this algorithm could now predict whether +it’s a blue or a red point.

+
+../../_images/sphx_glr_plot_linear_regression_001.png + +
+

A regression problem

+
+
+
+

+
+

The next simple task we’ll look at is a regression task: a simple +best-fit line to a set of data.

+

Again, this is an example of fitting a model to data, but our focus here +is that the model can make generalizations about new data. The model has +been learned from the training data, and can be used to predict the +result of test data: here, we might be given an x-value, and the model +would allow us to predict the y value.

+
+
+

3.4.1.2. Data in scikit-learn

+
+

The data matrix

+

Machine learning algorithms implemented in scikit-learn expect data +to be stored in a two-dimensional array or matrix. The arrays can be +either numpy arrays, or in some cases scipy.sparse matrices. The +size of the array is expected to be [n_samples, n_features]

+
    +
  • n_samples: The number of samples: each sample is an item to +process (e.g. classify). A sample can be a document, a picture, a +sound, a video, an astronomical object, a row in database or CSV +file, or whatever you can describe with a fixed set of quantitative +traits.

  • +
  • n_features: The number of features or distinct traits that can +be used to describe each item in a quantitative manner. Features are +generally real-valued, but may be boolean or discrete-valued in some +cases.

  • +
+
+

Tip

+

The number of features must be fixed in advance. However it can be +very high dimensional (e.g. millions of features) with most of them +being zeros for a given sample. This is a case where scipy.sparse +matrices can be useful, in that they are much more memory-efficient +than NumPy arrays.

+
+
+
+

A Simple Example: the Iris Dataset

+
+
The application problem
+

As an example of a simple dataset, let us a look at the +iris data stored by scikit-learn. Suppose we want to recognize species of +irises. The data consists of measurements of +three different species of irises:

+ +++++ + + + + + + + + + + + + +

setosa_picture

versicolor_picture

virginica_picture

Setosa Iris

Versicolor Iris

Virginica Iris

+ +

Remember that there must be a fixed number of features for each +sample, and feature number i must be a similar kind of quantity for +each sample.

+
+
+
Loading the Iris Data with Scikit-learn
+

Scikit-learn has a very straightforward set of data on these iris +species. The data consist of the following:

+
    +
  • Features in the Iris dataset:

    +
      +
    • sepal length (cm)

    • +
    • sepal width (cm)

    • +
    • petal length (cm)

    • +
    • petal width (cm)

    • +
    +
  • +
  • Target classes to predict:

    +
      +
    • Setosa

    • +
    • Versicolour

    • +
    • Virginica

    • +
    +
  • +
+

scikit-learn embeds a copy of the iris CSV file along with a +function to load it into NumPy arrays:

+
>>> from sklearn.datasets import load_iris
+
>>> iris = load_iris() +
+
+
+

Note

+

Import sklearn Note that scikit-learn is imported as sklearn

+
+

The features of each sample flower are stored in the data attribute +of the dataset:

+
>>> print(iris.data.shape)
+
(150, 4) +
>>> n_samples, n_features = iris.data.shape +
>>> print(n_samples) +
150 +
>>> print(n_features) +
4 +
>>> print(iris.data[0]) +
[5.1 3.5 1.4 0.2] +
+
+

The information about the class of each sample is stored in the +target attribute of the dataset:

+
>>> print(iris.target.shape)
+
(150,) +
>>> print(iris.target) +
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +
0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 +
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 +
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 +
2 2] +
+
+

The names of the classes are stored in the last attribute, namely +target_names:

+
>>> print(iris.target_names)
+
['setosa' 'versicolor' 'virginica'] +
+
+

This data is four-dimensional, but we can visualize two of the +dimensions at a time using a scatter plot:

+../../_images/sphx_glr_plot_iris_scatter_001.png + + +
+
+
+
+
+

3.4.2. Basic principles of machine learning with scikit-learn

+
+

3.4.2.1. Introducing the scikit-learn estimator object

+

Every algorithm is exposed in scikit-learn via an ‘’Estimator’’ object. +For instance a linear regression is: sklearn.linear_model.LinearRegression

+
>>> from sklearn.linear_model import LinearRegression
+
+
+

Estimator parameters: All the parameters of an estimator can be set +when it is instantiated:

+
>>> model = LinearRegression(n_jobs=1)
+
>>> print(model) +
LinearRegression(n_jobs=1) +
+
+
+

Fitting on data

+

Let’s create some simple data with numpy:

+
>>> import numpy as np
+
>>> x = np.array([0, 1, 2]) +
>>> y = np.array([0, 1, 2]) +
+
>>> X = x[:, np.newaxis] # The input data for sklearn is 2D: (samples == 3 x features == 1) +
>>> X +
array([[0], +
[1], +
[2]]) +
+
>>> model.fit(X, y) +
LinearRegression(n_jobs=1) +
+
+

Estimated parameters: When data is fitted with an estimator, +parameters are estimated from the data at hand. All the estimated +parameters are attributes of the estimator object ending by an +underscore:

+
>>> model.coef_
+
array([1.]) +
+
+
+
+
+

3.4.2.2. Supervised Learning: Classification and regression

+

In Supervised Learning, we have a dataset consisting of both +features and labels. The task is to construct an estimator which is able +to predict the label of an object given the set of features. A +relatively simple example is predicting the species of iris given a set +of measurements of its flower. This is a relatively simple task. Some +more complicated examples are:

+
    +
  • given a multicolor image of an object through a telescope, determine +whether that object is a star, a quasar, or a galaxy.

  • +
  • given a photograph of a person, identify the person in the photo.

  • +
  • given a list of movies a person has watched and their personal rating +of the movie, recommend a list of movies they would like (So-called +recommender systems: a famous example is the Netflix +Prize).

  • +
+
+

Tip

+

What these tasks have in common is that there is one or more unknown +quantities associated with the object which needs to be determined from +other observed quantities.

+
+

Supervised learning is further broken down into two categories, +classification and regression. In classification, the label is +discrete, while in regression, the label is continuous. For example, in +astronomy, the task of determining whether an object is a star, a +galaxy, or a quasar is a classification problem: the label is from three +distinct categories. On the other hand, we might wish to estimate the +age of an object based on such observations: this would be a regression +problem, because the label (age) is a continuous quantity.

+

Classification: K nearest neighbors (kNN) is one of the simplest +learning strategies: given a new, unknown observation, look up in your +reference database which ones have the closest features and assign the +predominant class. Let’s try it out on our iris classification problem:

+
from sklearn import neighbors, datasets
+
iris = datasets.load_iris() +
X, y = iris.data, iris.target +
knn = neighbors.KNeighborsClassifier(n_neighbors=1) +
knn.fit(X, y) +
# What kind of iris has 3cm x 5cm sepal and 4cm x 2cm petal? +
print(iris.target_names[knn.predict([[3, 5, 4, 2]])]) +
+
+
+../../_images/sphx_glr_plot_iris_knn_001.png + +
+

A plot of the sepal space and the prediction of the KNN

+
+
+

Regression: The simplest possible regression setting is the linear +regression one:

+
from sklearn.linear_model import LinearRegression
+
+
# x from 0 to 30 +
rng = np.random.default_rng() +
x = 30 * rng.random((20, 1)) +
+
# y = a*x + b with noise +
y = 0.5 * x + 1.0 + rng.normal(size=x.shape) +
+
# create a linear regression model +
model = LinearRegression() +
model.fit(x, y) +
+
# predict y from the data +
x_new = np.linspace(0, 30, 100) +
y_new = model.predict(x_new[:, np.newaxis]) +
+
+
+
+../../_images/sphx_glr_plot_linear_regression_001.png + +
+

A plot of a simple linear regression.

+
+
+
+
+

3.4.2.3. A recap on Scikit-learn’s estimator interface

+

Scikit-learn strives to have a uniform interface across all methods, and +we’ll see examples of these below. Given a scikit-learn estimator +object named model, the following methods are available:

+
+
In all Estimators:
+
    +
  • model.fit() : fit training data. For supervised learning +applications, this accepts two arguments: the data X and the +labels y (e.g. model.fit(X, y)). For unsupervised learning +applications, this accepts only a single argument, the data X +(e.g. model.fit(X)).

  • +
+
+
In supervised estimators:
+
    +
  • model.predict() : given a trained model, predict the label of a +new set of data. This method accepts one argument, the new data +X_new (e.g. model.predict(X_new)), and returns the learned +label for each object in the array.

  • +
  • model.predict_proba() : For classification problems, some +estimators also provide this method, which returns the probability +that a new observation has each categorical label. In this case, the +label with the highest probability is returned by +model.predict().

  • +
  • model.score() : for classification or regression problems, most +(all?) estimators implement a score method. Scores are between 0 and +1, with a larger score indicating a better fit.

  • +
+
+
In unsupervised estimators:
+
    +
  • model.transform() : given an unsupervised model, transform new +data into the new basis. This also accepts one argument X_new, +and returns the new representation of the data based on the +unsupervised model.

  • +
  • model.fit_transform() : some estimators implement this method, +which more efficiently performs a fit and a transform on the same +input data.

  • +
+
+
+
+
+

3.4.2.4. Regularization: what it is and why it is necessary

+
+

Preferring simpler models

+

Train errors Suppose you are using a 1-nearest neighbor estimator. +How many errors do you expect on your train set?

+
    +
  • Train set error is not a good measurement of prediction performance. +You need to leave out a test set.

  • +
  • In general, we should accept errors on the train set.

  • +
+

An example of regularization The core idea behind regularization is +that we are going to prefer models that are simpler, for a certain +definition of ‘’simpler’’, even if they lead to more errors on the train +set.

+

As an example, let’s generate with a 9th order polynomial, with noise:

+
+../../_images/sphx_glr_plot_polynomial_regression_001.png + +
+

And now, let’s fit a 4th order and a 9th order polynomial to the data.

+
+../../_images/sphx_glr_plot_polynomial_regression_002.png + +
+

With your naked eyes, which model do you prefer, the 4th order one, or +the 9th order one?

+

Let’s look at the ground truth:

+
+../../_images/sphx_glr_plot_polynomial_regression_003.png + +
+
+

Tip

+

Regularization is ubiquitous in machine learning. Most scikit-learn +estimators have a parameter to tune the amount of regularization. For +instance, with k-NN, it is ‘k’, the number of nearest neighbors used to +make the decision. k=1 amounts to no regularization: 0 error on the +training set, whereas large k will push toward smoother decision +boundaries in the feature space.

+
+
+
+

Simple versus complex models for classification

+ ++++ + + + + + + + + + + +

linear

nonlinear

A linear separation

A non-linear separation

+
+

Tip

+

For classification models, the decision boundary, that separates the +class expresses the complexity of the model. For instance, a linear +model, that makes a decision based on a linear combination of +features, is more complex than a non-linear one.

+
+
+
+
+
+

3.4.3. Supervised Learning: Classification of Handwritten Digits

+
+

3.4.3.1. The nature of the data

+ +

In this section we’ll apply scikit-learn to the classification of +handwritten digits. This will go a bit beyond the iris classification we +saw before: we’ll discuss some of the metrics which can be used in +evaluating the effectiveness of a classification model.

+
>>> from sklearn.datasets import load_digits
+
>>> digits = load_digits() +
+
+../../_images/sphx_glr_plot_digits_simple_classif_001.png + +

Let us visualize the data and remind us what we’re looking at (click on +the figure for the full code):

+
# plot the digits: each image is 8x8 pixels
+
for i in range(64): +
ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[]) +
ax.imshow(digits.images[i], cmap=plt.cm.binary, interpolation='nearest') +
+
+
+
+

3.4.3.2. Visualizing the Data on its principal components

+

A good first-step for many problems is to visualize the data using a +Dimensionality Reduction technique. We’ll start with the most +straightforward one, Principal Component Analysis (PCA).

+

PCA seeks orthogonal linear combinations of the features which show the +greatest variance, and as such, can help give you a good idea of the +structure of the data set.

+
>>> from sklearn.decomposition import PCA
+
>>> pca = PCA(n_components=2) +
>>> proj = pca.fit_transform(digits.data) +
>>> plt.scatter(proj[:, 0], proj[:, 1], c=digits.target) +
<matplotlib.collections.PathCollection object at ...> +
>>> plt.colorbar() +
<matplotlib.colorbar.Colorbar object at ...> +
+
+../../_images/sphx_glr_plot_digits_simple_classif_002.png + + +
+
+

3.4.3.3. Gaussian Naive Bayes Classification

+

For most classification problems, it’s nice to have a simple, fast +method to provide a quick baseline classification. If the simple +and fast method is sufficient, then we don’t have to waste CPU cycles on +more complex models. If not, we can use the results of the simple method +to give us clues about our data.

+

One good method to keep in mind is Gaussian Naive Bayes +(sklearn.naive_bayes.GaussianNB).

+ +
+

Tip

+

Gaussian Naive Bayes fits a Gaussian distribution to each training label +independently on each feature, and uses this to quickly give a rough +classification. It is generally not sufficiently accurate for real-world +data, but can perform surprisingly well, for instance on text data.

+
+
>>> from sklearn.naive_bayes import GaussianNB
+
>>> from sklearn.model_selection import train_test_split +
+
>>> # split the data into training and validation sets +
>>> X_train, X_test, y_train, y_test = train_test_split( +
... digits.data, digits.target, random_state=42) +
+
>>> # train the model +
>>> clf = GaussianNB() +
>>> clf.fit(X_train, y_train) +
GaussianNB() +
+
>>> # use the model to predict the labels of the test data +
>>> predicted = clf.predict(X_test) +
>>> expected = y_test +
>>> print(predicted) +
[6 9 3 7 2 2 5 8 5 2 1 1 7 0 4 8 3 7 8 8 4 3 9 7 5 6 3 5 6 3...] +
>>> print(expected) +
[6 9 3 7 2 1 5 2 5 2 1 9 4 0 4 2 3 7 8 8 4 3 9 7 5 6 3 5 6 3...] +
+
+

As above, we plot the digits with the predicted labels to get an idea of +how well the classification is working.

+../../_images/sphx_glr_plot_digits_simple_classif_003.png + + +
+
+

3.4.3.4. Quantitative Measurement of Performance

+

We’d like to measure the performance of our estimator without having to +resort to plotting examples. A simple method might be to simply compare +the number of matches:

+
>>> matches = (predicted == expected)
+
>>> print(matches.sum()) +
385 +
>>> print(len(matches)) +
450 +
>>> matches.sum() / float(len(matches)) +
np.float64(0.8555...) +
+
+

We see that more than 80% of the 450 predictions match the input. But +there are other more sophisticated metrics that can be used to judge the +performance of a classifier: several are available in the +sklearn.metrics submodule.

+

One of the most useful metrics is the classification_report, which +combines several measures and prints a table with the results:

+
>>> from sklearn import metrics
+
>>> print(metrics.classification_report(expected, predicted)) +
precision recall f1-score support +
+
0 1.00 0.95 0.98 43 +
1 0.85 0.78 0.82 37 +
2 0.85 0.61 0.71 38 +
3 0.97 0.83 0.89 46 +
4 0.98 0.84 0.90 55 +
5 0.90 0.95 0.93 59 +
6 0.90 0.96 0.92 45 +
7 0.71 0.98 0.82 41 +
8 0.60 0.89 0.72 38 +
9 0.90 0.73 0.80 48 +
+
accuracy 0.86 450 +
macro avg 0.87 0.85 0.85 450 +
weighted avg 0.88 0.86 0.86 450 +
+
+

Another enlightening metric for this sort of multi-label classification +is a confusion matrix: it helps us visualize which labels are being +interchanged in the classification errors:

+
>>> print(metrics.confusion_matrix(expected, predicted))
+
[[41 0 0 0 0 1 0 1 0 0] +
[ 0 29 2 0 0 0 0 0 4 2] +
[ 0 2 23 0 0 0 1 0 12 0] +
[ 0 0 1 38 0 1 0 0 5 1] +
[ 0 0 0 0 46 0 2 7 0 0] +
[ 0 0 0 0 0 56 1 1 0 1] +
[ 0 0 0 0 1 1 43 0 0 0] +
[ 0 0 0 0 0 1 0 40 0 0] +
[ 0 2 0 0 0 0 0 2 34 0] +
[ 0 1 1 1 0 2 1 5 2 35]] +
+
+

We see here that in particular, the numbers 1, 2, 3, and 9 are often +being labeled 8.

+
+
+
+

3.4.4. Supervised Learning: Regression of Housing Data

+

Here we’ll do a short example of a regression problem: learning a +continuous value from a set of features.

+
+

3.4.4.1. A quick look at the data

+ +

We’ll use the California house prices set, available in scikit-learn. +This records measurements of 8 attributes of housing markets in +California, as well as the median price. The question is: can you predict +the price of a new market given its attributes?:

+
>>> from sklearn.datasets import fetch_california_housing
+
>>> data = fetch_california_housing(as_frame=True) +
>>> print(data.data.shape) +
(20640, 8) +
>>> print(data.target.shape) +
(20640,) +
+
+

We can see that there are just over 20000 data points.

+

The DESCR variable has a long description of the dataset:

+
>>> print(data.DESCR)
+
.. _california_housing_dataset: +
+
California Housing dataset +
-------------------------- +
+
**Data Set Characteristics:** +
+
:Number of Instances: 20640 +
+
:Number of Attributes: 8 numeric, predictive attributes and the target +
+
:Attribute Information: +
- MedInc median income in block group +
- HouseAge median house age in block group +
- AveRooms average number of rooms per household +
- AveBedrms average number of bedrooms per household +
- Population block group population +
- AveOccup average number of household members +
- Latitude block group latitude +
- Longitude block group longitude +
+
:Missing Attribute Values: None +
+
This dataset was obtained from the StatLib repository. +
https://www.dcc.fc.up.pt/~ltorgo/Regression/cal_housing.html +
+
The target variable is the median house value for California districts, +
expressed in hundreds of thousands of dollars ($100,000). +
+
This dataset was derived from the 1990 U.S. census, using one row per census +
block group. A block group is the smallest geographical unit for which the U.S. +
Census Bureau publishes sample data (a block group typically has a population +
of 600 to 3,000 people). +
+
A household is a group of people residing within a home. Since the average +
number of rooms and bedrooms in this dataset are provided per household, these +
columns may take surprisingly large values for block groups with few households +
and many empty houses, such as vacation resorts. +
+
It can be downloaded/loaded using the +
:func:`sklearn.datasets.fetch_california_housing` function. +
+
.. rubric:: References +
+
- Pace, R. Kelley and Ronald Barry, Sparse Spatial Autoregressions, +
Statistics and Probability Letters, 33 (1997) 291-297 +
+
+

It often helps to quickly visualize pieces of the data using histograms, +scatter plots, or other plot types. With matplotlib, let us show a +histogram of the target values: the median price in each neighborhood:

+
>>> plt.hist(data.target)
+
(array([... +
+
+../../_images/sphx_glr_plot_california_prediction_001.png + +

Let’s have a quick look to see if some features are more relevant than +others for our problem:

+
>>> for index, feature_name in enumerate(data.feature_names):
+
... plt.figure() +
... plt.scatter(data.data[feature_name], data.target) +
<Figure size... +
+
+../../_images/sphx_glr_plot_california_prediction_002.png + +../../_images/sphx_glr_plot_california_prediction_003.png + +../../_images/sphx_glr_plot_california_prediction_004.png + +../../_images/sphx_glr_plot_california_prediction_005.png + +../../_images/sphx_glr_plot_california_prediction_006.png + +../../_images/sphx_glr_plot_california_prediction_007.png + +../../_images/sphx_glr_plot_california_prediction_008.png + +../../_images/sphx_glr_plot_california_prediction_009.png + +

This is a manual version of a technique called feature selection.

+
+

Tip

+

Sometimes, in Machine Learning it is useful to use feature selection to +decide which features are the most useful for a particular problem. +Automated methods exist which quantify this sort of exercise of choosing +the most informative features.

+
+
+
+

3.4.4.2. Predicting Home Prices: a Simple Linear Regression

+

Now we’ll use scikit-learn to perform a simple linear regression on +the housing data. There are many possibilities of regressors to use. A +particularly simple one is LinearRegression: this is basically a +wrapper around an ordinary least squares calculation.

+
>>> from sklearn.model_selection import train_test_split
+
>>> X_train, X_test, y_train, y_test = train_test_split(data.data, data.target) +
>>> from sklearn.linear_model import LinearRegression +
>>> clf = LinearRegression() +
>>> clf.fit(X_train, y_train) +
LinearRegression() +
>>> predicted = clf.predict(X_test) +
>>> expected = y_test +
>>> print("RMS: %s" % np.sqrt(np.mean((predicted - expected) ** 2))) +
RMS: 0.7... +
+
+../../_images/sphx_glr_plot_california_prediction_010.png + +

We can plot the error: expected as a function of predicted:

+
>>> plt.scatter(expected, predicted)
+
<matplotlib.collections.PathCollection object at ...> +
+
+
+

Tip

+

The prediction at least correlates with the true price, though there are +clearly some biases. We could imagine evaluating the performance of the +regressor by, say, computing the RMS residuals between the true and +predicted price. There are some subtleties in this, however, which we’ll +cover in a later section.

+
+ +
+
+
+

3.4.5. Measuring prediction performance

+
+

3.4.5.1. A quick test on the K-neighbors classifier

+

Here we’ll continue to look at the digits data, but we’ll switch to the +K-Neighbors classifier. The K-neighbors classifier is an instance-based +classifier. The K-neighbors classifier predicts the label of +an unknown point based on the labels of the K nearest points in the +parameter space.

+
>>> # Get the data
+
>>> from sklearn.datasets import load_digits +
>>> digits = load_digits() +
>>> X = digits.data +
>>> y = digits.target +
+
>>> # Instantiate and train the classifier +
>>> from sklearn.neighbors import KNeighborsClassifier +
>>> clf = KNeighborsClassifier(n_neighbors=1) +
>>> clf.fit(X, y) +
KNeighborsClassifier(...) +
+
>>> # Check the results using metrics +
>>> from sklearn import metrics +
>>> y_pred = clf.predict(X) +
+
>>> print(metrics.confusion_matrix(y_pred, y)) +
[[178 0 0 0 0 0 0 0 0 0] +
[ 0 182 0 0 0 0 0 0 0 0] +
[ 0 0 177 0 0 0 0 0 0 0] +
[ 0 0 0 183 0 0 0 0 0 0] +
[ 0 0 0 0 181 0 0 0 0 0] +
[ 0 0 0 0 0 182 0 0 0 0] +
[ 0 0 0 0 0 0 181 0 0 0] +
[ 0 0 0 0 0 0 0 179 0 0] +
[ 0 0 0 0 0 0 0 0 174 0] +
[ 0 0 0 0 0 0 0 0 0 180]] +
+
+

Apparently, we’ve found a perfect classifier! But this is misleading for +the reasons we saw before: the classifier essentially “memorizes” all the +samples it has already seen. To really test how well this algorithm +does, we need to try some samples it hasn’t yet seen.

+

This problem also occurs with regression models. In the following we +fit an other instance-based model named “decision tree” to the California +Housing price dataset we introduced previously:

+
>>> from sklearn.datasets import fetch_california_housing
+
>>> from sklearn.tree import DecisionTreeRegressor +
+
>>> data = fetch_california_housing(as_frame=True) +
>>> clf = DecisionTreeRegressor().fit(data.data, data.target) +
>>> predicted = clf.predict(data.data) +
>>> expected = data.target +
+
>>> plt.scatter(expected, predicted) +
<matplotlib.collections.PathCollection object at ...> +
>>> plt.plot([0, 50], [0, 50], '--k') +
[<matplotlib.lines.Line2D object at ...] +
+
+
+../../_images/sphx_glr_plot_measuring_performance_001.png + +
+

Here again the predictions are seemingly perfect as the model was able to +perfectly memorize the training set.

+
+

Warning

+

Performance on test set

+

Performance on test set does not measure overfit (as described above)

+
+
+
+

3.4.5.2. A correct approach: Using a validation set

+

Learning the parameters of a prediction function and testing it on the +same data is a methodological mistake: a model that would just repeat the +labels of the samples that it has just seen would have a perfect score +but would fail to predict anything useful on yet-unseen data.

+

To avoid over-fitting, we have to define two different sets:

+
    +
  • a training set X_train, y_train which is used for learning the +parameters of a predictive model

  • +
  • a testing set X_test, y_test which is used for evaluating the fitted +predictive model

  • +
+

In scikit-learn such a random split can be quickly computed with the +train_test_split() function:

+
>>> from sklearn import model_selection
+
>>> X = digits.data +
>>> y = digits.target +
+
>>> X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, +
... test_size=0.25, random_state=0) +
+
>>> print("%r, %r, %r" % (X.shape, X_train.shape, X_test.shape)) +
(1797, 64), (1347, 64), (450, 64) +
+
+

Now we train on the training data, and test on the testing data:

+
>>> clf = KNeighborsClassifier(n_neighbors=1).fit(X_train, y_train)
+
>>> y_pred = clf.predict(X_test) +
+
>>> print(metrics.confusion_matrix(y_test, y_pred)) +
[[37 0 0 0 0 0 0 0 0 0] +
[ 0 43 0 0 0 0 0 0 0 0] +
[ 0 0 43 1 0 0 0 0 0 0] +
[ 0 0 0 45 0 0 0 0 0 0] +
[ 0 0 0 0 38 0 0 0 0 0] +
[ 0 0 0 0 0 47 0 0 0 1] +
[ 0 0 0 0 0 0 52 0 0 0] +
[ 0 0 0 0 0 0 0 48 0 0] +
[ 0 0 0 0 0 0 0 0 48 0] +
[ 0 0 0 1 0 1 0 0 0 45]] +
>>> print(metrics.classification_report(y_test, y_pred)) +
precision recall f1-score support +
+
0 1.00 1.00 1.00 37 +
1 1.00 1.00 1.00 43 +
2 1.00 0.98 0.99 44 +
3 0.96 1.00 0.98 45 +
4 1.00 1.00 1.00 38 +
5 0.98 0.98 0.98 48 +
6 1.00 1.00 1.00 52 +
7 1.00 1.00 1.00 48 +
8 1.00 1.00 1.00 48 +
9 0.98 0.96 0.97 47 +
+
accuracy 0.99 450 +
macro avg 0.99 0.99 0.99 450 +
weighted avg 0.99 0.99 0.99 450 +
+
+

The averaged f1-score is often used as a convenient measure of the +overall performance of an algorithm. It appears in the bottom row +of the classification report; it can also be accessed directly:

+
>>> metrics.f1_score(y_test, y_pred, average="macro")
+
np.float64(0.991367...) +
+
+

The over-fitting we saw previously can be quantified by computing the +f1-score on the training data itself:

+
>>> metrics.f1_score(y_train, clf.predict(X_train), average="macro")
+
np.float64(1.0) +
+
+
+

Note

+

Regression metrics In the case of regression models, we +need to use different metrics, such as explained variance.

+
+
+
+

3.4.5.3. Model Selection via Validation

+
+

Tip

+

We have applied Gaussian Naives, support vectors machines, and +K-nearest neighbors classifiers to the digits dataset. Now that we +have these validation tools in place, we can ask quantitatively which +of the three estimators works best for this dataset.

+
+
    +
  • With the default hyper-parameters for each estimator, which gives the +best f1 score on the validation set? Recall that hyperparameters +are the parameters set when you instantiate the classifier: for +example, the n_neighbors in clf = +KNeighborsClassifier(n_neighbors=1)

    +
    >>> from sklearn.naive_bayes import GaussianNB
    +
    >>> from sklearn.neighbors import KNeighborsClassifier +
    >>> from sklearn.svm import LinearSVC +
    +
    >>> X = digits.data +
    >>> y = digits.target +
    >>> X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, +
    ... test_size=0.25, random_state=0) +
    +
    >>> for Model in [GaussianNB(), KNeighborsClassifier(), LinearSVC(dual=False)]: +
    ... clf = Model.fit(X_train, y_train) +
    ... y_pred = clf.predict(X_test) +
    ... print('%s: %s' % +
    ... (Model.__class__.__name__, metrics.f1_score(y_test, y_pred, average="macro"))) +
    GaussianNB: 0.8... +
    KNeighborsClassifier: 0.9... +
    LinearSVC: 0.9... +
    +
    +
  • +
  • For each classifier, which value for the hyperparameters gives the best +results for the digits data? For LinearSVC, use +loss='l2' and loss='l1'. For +KNeighborsClassifier we use +n_neighbors between 1 and 10. Note that +GaussianNB does not have any adjustable +hyperparameters.

    +
    LinearSVC(loss='l1'): 0.930570687535
    +
    LinearSVC(loss='l2'): 0.933068826918 +
    ------------------- +
    KNeighbors(n_neighbors=1): 0.991367521884 +
    KNeighbors(n_neighbors=2): 0.984844206884 +
    KNeighbors(n_neighbors=3): 0.986775344954 +
    KNeighbors(n_neighbors=4): 0.980371905382 +
    KNeighbors(n_neighbors=5): 0.980456280495 +
    KNeighbors(n_neighbors=6): 0.975792419414 +
    KNeighbors(n_neighbors=7): 0.978064579214 +
    KNeighbors(n_neighbors=8): 0.978064579214 +
    KNeighbors(n_neighbors=9): 0.978064579214 +
    KNeighbors(n_neighbors=10): 0.975555089773 +
    +
    +

    Solution: code source

    +
  • +
+
+
+

3.4.5.4. Cross-validation

+

Cross-validation consists in repeatedly splitting the data in pairs of +train and test sets, called ‘folds’. Scikit-learn comes with a function +to automatically compute score on all these folds. Here we do +KFold with k=5.

+
>>> clf = KNeighborsClassifier()
+
>>> from sklearn.model_selection import cross_val_score +
>>> cross_val_score(clf, X, y, cv=5) +
array([0.947..., 0.955..., 0.966..., 0.980..., 0.963... ]) +
+
+

We can use different splitting strategies, such as random splitting:

+
>>> from sklearn.model_selection import ShuffleSplit
+
>>> cv = ShuffleSplit(n_splits=5) +
>>> cross_val_score(clf, X, y, cv=cv) +
array([...]) +
+
+
+

Tip

+

There exists many different cross-validation strategies +in scikit-learn. They are often useful to take in account non iid +datasets.

+
+
+
+

3.4.5.5. Hyperparameter optimization with cross-validation

+

Consider regularized linear models, such as Ridge Regression, which +uses l2 regularization, and Lasso Regression, which uses l1 +regularization. Choosing their regularization parameter is important.

+

Let us set these parameters on the Diabetes dataset, a simple regression +problem. The diabetes data consists of 10 physiological variables (age, +sex, weight, blood pressure) measure on 442 patients, and an indication +of disease progression after one year:

+
>>> from sklearn.datasets import load_diabetes
+
>>> data = load_diabetes() +
>>> X, y = data.data, data.target +
>>> print(X.shape) +
(442, 10) +
+
+

With the default hyper-parameters: we compute the cross-validation score:

+
>>> from sklearn.linear_model import Ridge, Lasso
+
+
>>> for Model in [Ridge, Lasso]: +
... model = Model() +
... print('%s: %s' % (Model.__name__, cross_val_score(model, X, y).mean())) +
Ridge: 0.4... +
Lasso: 0.3... +
+
+
+

Basic Hyperparameter Optimization

+

We compute the cross-validation score as a function of alpha, the +strength of the regularization for Lasso +and Ridge. We choose 20 values of alpha +between 0.0001 and 1:

+
>>> alphas = np.logspace(-3, -1, 30)
+
+
>>> for Model in [Lasso, Ridge]: +
... scores = [cross_val_score(Model(alpha), X, y, cv=3).mean() +
... for alpha in alphas] +
... plt.plot(alphas, scores, label=Model.__name__) +
[<matplotlib.lines.Line2D object at ... +
+
+../../_images/sphx_glr_plot_linear_model_cv_001.png + + +
+ + +
+

Nested cross-validation

+

How do we measure the performance of these estimators? We have used data +to set the hyperparameters, so we need to test on actually new data. We +can do this by running cross_val_score() +on our CV objects. Here there are 2 cross-validation loops going on, this +is called ‘nested cross validation’:

+
for Model in [RidgeCV, LassoCV]:
+
scores = cross_val_score(Model(alphas=alphas, cv=3), X, y, cv=3) +
print(Model.__name__, np.mean(scores)) +
+
+
+

Note

+

Note that these results do not match the best results of our curves +above, and LassoCV seems to +under-perform RidgeCV. The reason is +that setting the hyper-parameter is harder for Lasso, thus the +estimation error on this hyper-parameter is larger.

+
+
+
+
+
+

3.4.6. Unsupervised Learning: Dimensionality Reduction and Visualization

+

Unsupervised learning is applied on X without y: data without labels. A +typical use case is to find hidden structure in the data.

+
+

3.4.6.1. Dimensionality Reduction: PCA

+

Dimensionality reduction derives a set of new artificial features smaller +than the original feature set. Here we’ll use Principal Component +Analysis (PCA), a +dimensionality reduction that strives to retain most of the variance of +the original data. We’ll use sklearn.decomposition.PCA on the +iris dataset:

+
>>> X = iris.data
+
>>> y = iris.target +
+
+
+

Tip

+

PCA computes linear combinations of +the original features using a truncated Singular Value Decomposition +of the matrix X, to project the data onto a base of the top singular +vectors.

+
+
>>> from sklearn.decomposition import PCA
+
>>> pca = PCA(n_components=2, whiten=True) +
>>> pca.fit(X) +
PCA(n_components=2, whiten=True) +
+
+

Once fitted, PCA exposes the singular +vectors in the components_ attribute:

+
>>> pca.components_
+
array([[ 0.3..., -0.08..., 0.85..., 0.3...], +
[ 0.6..., 0.7..., -0.1..., -0.07...]]) +
+
+

Other attributes are available as well:

+
>>> pca.explained_variance_ratio_
+
array([0.92..., 0.053...]) +
+
+

Let us project the iris dataset along those first two dimensions::

+
>>> X_pca = pca.transform(X)
+
>>> X_pca.shape +
(150, 2) +
+
+

PCA normalizes and whitens the data, which means that the data +is now centered on both components with unit variance:

+
>>> X_pca.mean(axis=0)
+
array([...e-15, ...e-15]) +
>>> X_pca.std(axis=0, ddof=1) +
array([1., 1.]) +
+
+

Furthermore, the samples components do no longer carry any linear +correlation:

+
>>> np.corrcoef(X_pca.T)  
+
array([[1.00000000e+00, 0.0], +
[0.0, 1.00000000e+00]]) +
+
+

With a number of retained components 2 or 3, PCA is useful to visualize +the dataset:

+
>>> target_ids = range(len(iris.target_names))
+
>>> for i, c, label in zip(target_ids, 'rgbcmykw', iris.target_names): +
... plt.scatter(X_pca[y == i, 0], X_pca[y == i, 1], +
... c=c, label=label) +
<matplotlib.collections.PathCollection ... +
+
+../../_images/sphx_glr_plot_pca_001.png + +
+

Tip

+

Note that this projection was determined without any information +about the labels (represented by the colors): this is the sense in +which the learning is unsupervised. Nevertheless, we see that the +projection gives us insight into the distribution of the different +flowers in parameter space: notably, iris setosa is much more +distinct than the other two species.

+
+
+
+

3.4.6.2. Visualization with a non-linear embedding: tSNE

+

For visualization, more complex embeddings can be useful (for statistical +analysis, they are harder to control). sklearn.manifold.TSNE is +such a powerful manifold learning method. We apply it to the digits +dataset, as the digits are vectors of dimension 8*8 = 64. Embedding them +in 2D enables visualization:

+
>>> # Take the first 500 data points: it's hard to see 1500 points
+
>>> X = digits.data[:500] +
>>> y = digits.target[:500] +
+
>>> # Fit and transform with a TSNE +
>>> from sklearn.manifold import TSNE +
>>> tsne = TSNE(n_components=2, learning_rate='auto', init='random', random_state=0) +
>>> X_2d = tsne.fit_transform(X) +
+
>>> # Visualize the data +
>>> plt.scatter(X_2d[:, 0], X_2d[:, 1], c=y) +
<matplotlib.collections.PathCollection object at ...> +
+
+../../_images/sphx_glr_plot_tsne_001.png + + +
+

+
+

sklearn.manifold.TSNE separates quite well the different classes +of digits even though it had no access to the class information.

+
+
+
+
+

3.4.7. Parameter selection, Validation, and Testing

+
+

3.4.7.1. Hyperparameters, Over-fitting, and Under-fitting

+
+

See also

+

This section is adapted from Andrew Ng’s excellent +Coursera course

+
+

The issues associated with validation and cross-validation are some of +the most important aspects of the practice of machine learning. +Selecting the optimal model for your data is vital, and is a piece of +the problem that is not often appreciated by machine learning +practitioners.

+

The central question is: If our estimator is underperforming, how +should we move forward?

+
    +
  • Use simpler or more complicated model?

  • +
  • Add more features to each observed data point?

  • +
  • Add more training samples?

  • +
+

The answer is often counter-intuitive. In particular, Sometimes using +a more complicated model will give worse results. Also, Sometimes +adding training data will not improve your results. The ability to +determine what steps will improve your model is what separates the +successful machine learning practitioners from the unsuccessful.

+
+

Bias-variance trade-off: illustration on a simple regression problem

+ +

Let us start with a simple 1D regression problem. This +will help us to easily visualize the data and the model, and the results +generalize easily to higher-dimensional datasets. We’ll explore a simple +linear regression problem, with sklearn.linear_model.

+
X = np.c_[0.5, 1].T
+
y = [0.5, 1] +
X_test = np.c_[0, 2].T +
+
+

Without noise, as linear regression fits the data perfectly

+
from sklearn import linear_model
+
+
regr = linear_model.LinearRegression() +
regr.fit(X, y) +
plt.plot(X, y, "o") +
plt.plot(X_test, regr.predict(X_test)) +
+
+plot variance linear regr
[<matplotlib.lines.Line2D object at 0x7f5b029f65d0>]
+
+
+

In real life situation, we have noise (e.g. measurement noise) in our data:

+
rng = np.random.default_rng(27446968)
+
for _ in range(6): +
noisy_X = X + np.random.normal(loc=0, scale=0.1, size=X.shape) +
plt.plot(noisy_X, y, "o") +
regr.fit(noisy_X, y) +
plt.plot(X_test, regr.predict(X_test)) +
+
+plot variance linear regr

As we can see, our linear model captures and amplifies the noise in the +data. It displays a lot of variance.

+

We can use another linear estimator that uses regularization, the +Ridge estimator. This estimator +regularizes the coefficients by shrinking them to zero, under the +assumption that very high correlations are often spurious. The alpha +parameter controls the amount of shrinkage used.

+
regr = linear_model.Ridge(alpha=0.1)
+
np.random.seed(0) +
for _ in range(6): +
noisy_X = X + np.random.normal(loc=0, scale=0.1, size=X.shape) +
plt.plot(noisy_X, y, "o") +
regr.fit(noisy_X, y) +
plt.plot(X_test, regr.predict(X_test)) +
+
plt.show() +
+
+plot variance linear regr

As we can see, the estimator displays much less variance. However it +systematically under-estimates the coefficient. It displays a biased +behavior.

+

This is a typical example of bias/variance tradeof: non-regularized +estimator are not biased, but they can display a lot of variance. +Highly-regularized models have little variance, but high bias. This bias +is not necessarily a bad thing: what matters is choosing the +tradeoff between bias and variance that leads to the best prediction +performance. For a specific dataset there is a sweet spot corresponding +to the highest complexity that the data can support, depending on the +amount of noise and of observations available.

+
+
+
+

3.4.7.2. Visualizing the Bias/Variance Tradeoff

+
+

Tip

+

Given a particular dataset and a model (e.g. a polynomial), we’d like to +understand whether bias (underfit) or variance limits prediction, and how +to tune the hyperparameter (here d, the degree of the polynomial) +to give the best fit.

+
+

On a given data, let us fit a simple polynomial regression model with +varying degrees:

+../../_images/sphx_glr_plot_bias_variance_001.png + +
+

Tip

+

In the above figure, we see fits for three different values of d. +For d = 1, the data is under-fit. This means that the model is too +simplistic: no straight line will ever be a good fit to this data. In +this case, we say that the model suffers from high bias. The model +itself is biased, and this will be reflected in the fact that the data +is poorly fit. At the other extreme, for d = 6 the data is over-fit. +This means that the model has too many free parameters (6 in this case) +which can be adjusted to perfectly fit the training data. If we add a +new point to this plot, though, chances are it will be very far from the +curve representing the degree-6 fit. In this case, we say that the model +suffers from high variance. The reason for the term “high variance” is +that if any of the input points are varied slightly, it could result in +a very different model.

+

In the middle, for d = 2, we have found a good mid-point. It fits +the data fairly well, and does not suffer from the bias and variance +problems seen in the figures on either side. What we would like is a way +to quantitatively identify bias and variance, and optimize the +metaparameters (in this case, the polynomial degree d) in order to +determine the best algorithm.

+
+ +
+

Validation Curves

+

Let us create a dataset like in the example above:

+
>>> def generating_func(x, rng, err=0.5):
+
... return rng.normal(10 - 1. / (x + 0.1), err) +
+
>>> # randomly sample more data +
>>> rng = np.random.default_rng(27446968) +
>>> x = rng.random(size=200) +
>>> y = generating_func(x, err=1., rng=rng) +
+
+../../_images/sphx_glr_plot_bias_variance_002.png + +

Central to quantify bias and variance of a model is to apply it on test +data, sampled from the same distribution as the train, but that will +capture independent noise:

+
>>> xtrain, xtest, ytrain, ytest = train_test_split(x, y, test_size=0.4)
+
+
+

Validation curve A validation curve consists in varying a model parameter +that controls its complexity (here the degree of the +polynomial) and measures both error of the model on training data, and on +test data (eg with cross-validation). The model parameter is then +adjusted so that the test error is minimized:

+

We use sklearn.model_selection.validation_curve() to compute train +and test error, and plot it:

+
>>> from sklearn.model_selection import validation_curve
+
+
>>> degrees = np.arange(1, 21) +
+
>>> model = make_pipeline(PolynomialFeatures(), LinearRegression()) +
+
>>> # Vary the "degrees" on the pipeline step "polynomialfeatures" +
>>> train_scores, validation_scores = validation_curve( +
... model, x[:, np.newaxis], y, +
... param_name='polynomialfeatures__degree', +
... param_range=degrees) +
+
>>> # Plot the mean train score and validation score across folds +
>>> plt.plot(degrees, validation_scores.mean(axis=1), label='cross-validation') +
[<matplotlib.lines.Line2D object at ...>] +
>>> plt.plot(degrees, train_scores.mean(axis=1), label='training') +
[<matplotlib.lines.Line2D object at ...>] +
>>> plt.legend(loc='best') +
<matplotlib.legend.Legend object at ...> +
+
+../../_images/sphx_glr_plot_bias_variance_003.png + +

This figure shows why validation is important. On the left side of the +plot, we have very low-degree polynomial, which under-fit the data. This +leads to a low explained variance for both the training set and the +validation set. On the far right side of the plot, we have a very high +degree polynomial, which over-fits the data. This can be seen in the fact +that the training explained variance is very high, while on the +validation set, it is low. Choosing d around 4 or 5 gets us the best +tradeoff.

+
+

Tip

+

The astute reader will realize that something is amiss here: in the +above plot, d = 4 gives the best results. But in the previous plot, +we found that d = 6 vastly over-fits the data. What’s going on here? +The difference is the number of training points used. In the +previous example, there were only eight training points. In this +example, we have 100. As a general rule of thumb, the more training +points used, the more complicated model can be used. But how can you +determine for a given model whether more training points will be +helpful? A useful diagnostic for this are learning curves.

+
+
+
+

Learning Curves

+

A learning curve shows the training and validation score as a +function of the number of training points. Note that when we train on a +subset of the training data, the training score is computed using +this subset, not the full training set. This curve gives a +quantitative view into how beneficial it will be to add training +samples.

+ +

scikit-learn provides +sklearn.model_selection.learning_curve():

+
>>> from sklearn.model_selection import learning_curve
+
>>> train_sizes, train_scores, validation_scores = learning_curve( +
... model, x[:, np.newaxis], y, train_sizes=np.logspace(-1, 0, 20)) +
+
>>> # Plot the mean train score and validation score across folds +
>>> plt.plot(train_sizes, validation_scores.mean(axis=1), label='cross-validation') +
[<matplotlib.lines.Line2D object at ...>] +
>>> plt.plot(train_sizes, train_scores.mean(axis=1), label='training') +
[<matplotlib.lines.Line2D object at ...>] +
+
+
+../../_images/sphx_glr_plot_bias_variance_004.png + +
+

For a degree=1 model

+
+
+

Note that the validation score generally increases with a growing +training set, while the training score generally decreases with a +growing training set. As the training size +increases, they will converge to a single value.

+

From the above discussion, we know that d = 1 is a high-bias +estimator which under-fits the data. This is indicated by the fact that +both the training and validation scores are low. When confronted +with this type of learning curve, we can expect that adding more +training data will not help: both lines converge to a +relatively low score.

+

+

When the learning curves have converged to a low score, we have a +high bias model.

+

A high-bias model can be improved by:

+
    +
  • Using a more sophisticated model (i.e. in this case, increase d)

  • +
  • Gather more features for each sample.

  • +
  • Decrease regularization in a regularized model.

  • +
+

Increasing the number of samples, however, does not improve a high-bias +model.

+

Now let’s look at a high-variance (i.e. over-fit) model:

+
+../../_images/sphx_glr_plot_bias_variance_006.png + +
+

For a degree=15 model

+
+
+

Here we show the learning curve for d = 15. From the above +discussion, we know that d = 15 is a high-variance estimator +which over-fits the data. This is indicated by the fact that the +training score is much higher than the validation score. As we add more +samples to this training set, the training score will continue to +decrease, while the cross-validation error will continue to increase, until they +meet in the middle.

+

+

Learning curves that have not yet converged with the full training +set indicate a high-variance, over-fit model.

+

A high-variance model can be improved by:

+
    +
  • Gathering more training samples.

  • +
  • Using a less-sophisticated model (i.e. in this case, make d +smaller)

  • +
  • Increasing regularization.

  • +
+

In particular, gathering more features for each sample will not help the +results.

+
+
+
+

3.4.7.3. Summary on model selection

+

We’ve seen above that an under-performing algorithm can be due to two +possible situations: high bias (under-fitting) and high variance +(over-fitting). In order to evaluate our algorithm, we set aside a +portion of our training data for cross-validation. Using the technique +of learning curves, we can train on progressively larger subsets of the +data, evaluating the training error and cross-validation error to +determine whether our algorithm has high variance or high bias. But what +do we do with this information?

+
+

High Bias

+

If a model shows high bias, the following actions might help:

+
    +
  • Add more features. In our example of predicting home prices, it +may be helpful to make use of information such as the neighborhood +the house is in, the year the house was built, the size of the lot, +etc. Adding these features to the training and test sets can improve +a high-bias estimator

  • +
  • Use a more sophisticated model. Adding complexity to the model +can help improve on bias. For a polynomial fit, this can be +accomplished by increasing the degree d. Each learning technique has +its own methods of adding complexity.

  • +
  • Use fewer samples. Though this will not improve the +classification, a high-bias algorithm can attain nearly the same +error with a smaller training sample. For algorithms which are +computationally expensive, reducing the training sample size can lead +to very large improvements in speed.

  • +
  • Decrease regularization. Regularization is a technique used to +impose simplicity in some machine learning models, by adding a +penalty term that depends on the characteristics of the parameters. +If a model has high bias, decreasing the effect of regularization can +lead to better results.

  • +
+
+
+

High Variance

+

If a model shows high variance, the following actions might +help:

+
    +
  • Use fewer features. Using a feature selection technique may be +useful, and decrease the over-fitting of the estimator.

  • +
  • Use a simpler model. Model complexity and over-fitting go +hand-in-hand.

  • +
  • Use more training samples. Adding training samples can reduce the +effect of over-fitting, and lead to improvements in a high variance +estimator.

  • +
  • Increase Regularization. Regularization is designed to prevent +over-fitting. In a high-variance model, increasing regularization can +lead to better results.

  • +
+

These choices become very important in real-world situations. For +example, due to limited telescope time, astronomers must seek a balance +between observing a large number of objects, and observing a large +number of features for each object. Determining which is more important +for a particular learning task can inform the observing strategy that +the astronomer employs.

+
+
+
+

3.4.7.4. A last word of caution: separate validation and test set

+

Using validation schemes to determine hyper-parameters means that we are +fitting the hyper-parameters to the particular validation set. In the +same way that parameters can be over-fit to the training set, +hyperparameters can be over-fit to the validation set. Because of this, +the validation error tends to under-predict the classification error of +new data.

+

For this reason, it is recommended to split the data into three sets:

+
    +
  • The training set, used to train the model (usually ~60% of the +data)

  • +
  • The validation set, used to validate the model (usually ~20% of +the data)

  • +
  • The test set, used to evaluate the expected error of the +validated model (usually ~20% of the data)

  • +
+

Many machine learning practitioners do not separate test set and +validation set. But if your goal is to gauge the error of a model on +unknown data, using an independent test set is vital.

+
+

+
+
+
+
+

3.4.8. Examples for the scikit-learn chapter

+
+

Demo PCA in 2D

+
Demo PCA in 2D
+
+

Measuring Decision Tree performance

+
Measuring Decision Tree performance
+
+

A simple linear regression

+
A simple linear regression
+
+

Plot 2D views of the iris dataset

+
Plot 2D views of the iris dataset
+
+

tSNE to visualize digits

+
tSNE to visualize digits
+
+

Use the RidgeCV and LassoCV to set the regularization parameter

+
Use the RidgeCV and LassoCV to set the regularization parameter
+
+

Plot variance and regularization in linear models

+
Plot variance and regularization in linear models
+
+

Simple picture of the formal problem of machine learning

+
Simple picture of the formal problem of machine learning
+
+

Compare classifiers on the digits data

+
Compare classifiers on the digits data
+
+

Plot fitting a 9th order polynomial

+
Plot fitting a 9th order polynomial
+
+

A simple regression analysis on the California housing data

+
A simple regression analysis on the California housing data
+
+

Nearest-neighbor prediction on iris

+
Nearest-neighbor prediction on iris
+
+

Simple visualization and classification of the digits dataset

+
Simple visualization and classification of the digits dataset
+
+

The eigenfaces example: chaining PCA and SVMs

+
The eigenfaces example: chaining PCA and SVMs
+
+

Example of linear and non-linear models

+
Example of linear and non-linear models
+
+

Bias and variance of polynomial fit

+
Bias and variance of polynomial fit
+
+

Tutorial Diagrams

+
Tutorial Diagrams
+
+
+ +

Gallery generated by Sphinx-Gallery

+
+

See also

+

Going further

+ +
+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/statistics/auto_examples/index.html b/packages/statistics/auto_examples/index.html new file mode 100644 index 000000000..0cf22dcd9 --- /dev/null +++ b/packages/statistics/auto_examples/index.html @@ -0,0 +1,227 @@ + + + + + + + + Full code for the figures — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Full code for the figures

+

Code examples for the statistics chapter.

+
+

Boxplots and paired differences

+
Boxplots and paired differences
+
+

Plotting simple quantities of a pandas dataframe

+
Plotting simple quantities of a pandas dataframe
+
+

Analysis of Iris petal and sepal sizes

+
Analysis of Iris petal and sepal sizes
+
+

Simple Regression

+
Simple Regression
+
+

Multiple Regression

+
Multiple Regression
+
+

Test for an education/gender interaction in wages

+
Test for an education/gender interaction in wages
+
+

Visualizing factors influencing wages

+
Visualizing factors influencing wages
+
+

Air fares before and after 9/11

+
Air fares before and after 9/11
+
+
+
+
+

Solutions to this chapter’s exercises

+
+

Relating Gender and IQ

+
Relating Gender and IQ
+
+
+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/statistics/auto_examples/plot_airfare.html b/packages/statistics/auto_examples/plot_airfare.html new file mode 100644 index 000000000..66c3fae33 --- /dev/null +++ b/packages/statistics/auto_examples/plot_airfare.html @@ -0,0 +1,449 @@ + + + + + + + + 3.1.6.8. Air fares before and after 9/11 — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.1.6.8. Air fares before and after 9/11

+

This is a business-intelligence (BI) like application.

+

What is interesting here is that we may want to study fares as a function +of the year, paired accordingly to the trips, or forgetting the year, +only as a function of the trip endpoints.

+

Using statsmodels’ linear models, we find that both with an OLS (ordinary +least square) and a robust fit, the intercept and the slope are +significantly non-zero: the air fares have decreased between 2000 and +2001, and their dependence on distance travelled has also decreased

+
# Standard library imports
+
import os +
+
+

Load the data

+
import pandas
+
import requests +
+
if not os.path.exists("airfares.txt"): +
# Download the file if it is not present +
r = requests.get( +
"https://users.stat.ufl.edu/~winner/data/airq4.dat", +
verify=False, # Wouldn't normally do this, but this site's certificate +
# is not yet distributed +
) +
with open("airfares.txt", "wb") as f: +
f.write(r.content) +
+
# As a separator, ' +' is a regular expression that means 'one of more +
# space' +
data = pandas.read_csv( +
"airfares.txt", +
delim_whitespace=True, +
header=0, +
names=[ +
"city1", +
"city2", +
"pop1", +
"pop2", +
"dist", +
"fare_2000", +
"nb_passengers_2000", +
"fare_2001", +
"nb_passengers_2001", +
], +
) +
+
# we log-transform the number of passengers +
import numpy as np +
+
data["nb_passengers_2000"] = np.log10(data["nb_passengers_2000"]) +
data["nb_passengers_2001"] = np.log10(data["nb_passengers_2001"]) +
+
+
/home/runner/work/scientific-python-lectures/scientific-python-lectures/packages/statistics/examples/plot_airfare.py:38: FutureWarning: The 'delim_whitespace' keyword in pd.read_csv is deprecated and will be removed in a future version. Use ``sep='\s+'`` instead
+
data = pandas.read_csv( +
+
+

Make a dataframe with the year as an attribute, instead of separate columns

+
# This involves a small danse in which we separate the dataframes in 2,
+
# one for year 2000, and one for 2001, before concatenating again. +
+
# Make an index of each flight +
data_flat = data.reset_index() +
+
data_2000 = data_flat[ +
["city1", "city2", "pop1", "pop2", "dist", "fare_2000", "nb_passengers_2000"] +
] +
# Rename the columns +
data_2000.columns = pandas.Index( +
["city1", "city2", "pop1", "pop2", "dist", "fare", "nb_passengers"] +
) +
# Add a column with the year +
data_2000.insert(0, "year", 2000) +
+
data_2001 = data_flat[ +
["city1", "city2", "pop1", "pop2", "dist", "fare_2001", "nb_passengers_2001"] +
] +
# Rename the columns +
data_2001.columns = pandas.Index( +
["city1", "city2", "pop1", "pop2", "dist", "fare", "nb_passengers"] +
) +
# Add a column with the year +
data_2001.insert(0, "year", 2001) +
+
data_flat = pandas.concat([data_2000, data_2001]) +
+
+

Plot scatter matrices highlighting different aspects

+
import seaborn
+
+
seaborn.pairplot( +
data_flat, vars=["fare", "dist", "nb_passengers"], kind="reg", markers="." +
) +
+
# A second plot, to show the effect of the year (ie the 9/11 effect) +
seaborn.pairplot( +
data_flat, +
vars=["fare", "dist", "nb_passengers"], +
kind="reg", +
hue="year", +
markers=".", +
) +
+
+
    +
  • plot airfare
  • +
  • plot airfare
  • +
+
<seaborn.axisgrid.PairGrid object at 0x7f5b013325a0>
+
+
+

Plot the difference in fare

+
import matplotlib.pyplot as plt
+
+
plt.figure(figsize=(5, 2)) +
seaborn.boxplot(data.fare_2001 - data.fare_2000) +
plt.title("Fare: 2001 - 2000") +
plt.subplots_adjust() +
+
plt.figure(figsize=(5, 2)) +
seaborn.boxplot(data.nb_passengers_2001 - data.nb_passengers_2000) +
plt.title("NB passengers: 2001 - 2000") +
plt.subplots_adjust() +
+
+
    +
  • Fare: 2001 - 2000
  • +
  • NB passengers: 2001 - 2000
  • +
+

Statistical testing: dependence of fare on distance and number of +passengers

+
import statsmodels.formula.api as sm
+
+
result = sm.ols(formula="fare ~ 1 + dist + nb_passengers", data=data_flat).fit() +
print(result.summary()) +
+
# Using a robust fit +
result = sm.rlm(formula="fare ~ 1 + dist + nb_passengers", data=data_flat).fit() +
print(result.summary()) +
+
+
                            OLS Regression Results
+
============================================================================== +
Dep. Variable: fare R-squared: 0.275 +
Model: OLS Adj. R-squared: 0.275 +
Method: Least Squares F-statistic: 1585. +
Date: Sun, 06 Oct 2024 Prob (F-statistic): 0.00 +
Time: 19:11:35 Log-Likelihood: -45532. +
No. Observations: 8352 AIC: 9.107e+04 +
Df Residuals: 8349 BIC: 9.109e+04 +
Df Model: 2 +
Covariance Type: nonrobust +
================================================================================= +
coef std err t P>|t| [0.025 0.975] +
--------------------------------------------------------------------------------- +
Intercept 211.2428 2.466 85.669 0.000 206.409 216.076 +
dist 0.0484 0.001 48.149 0.000 0.046 0.050 +
nb_passengers -32.8925 1.127 -29.191 0.000 -35.101 -30.684 +
============================================================================== +
Omnibus: 604.051 Durbin-Watson: 1.446 +
Prob(Omnibus): 0.000 Jarque-Bera (JB): 740.733 +
Skew: 0.710 Prob(JB): 1.42e-161 +
Kurtosis: 3.338 Cond. No. 5.23e+03 +
============================================================================== +
+
Notes: +
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified. +
[2] The condition number is large, 5.23e+03. This might indicate that there are +
strong multicollinearity or other numerical problems. +
Robust linear Model Regression Results +
============================================================================== +
Dep. Variable: fare No. Observations: 8352 +
Model: RLM Df Residuals: 8349 +
Method: IRLS Df Model: 2 +
Norm: HuberT +
Scale Est.: mad +
Cov Type: H1 +
Date: Sun, 06 Oct 2024 +
Time: 19:11:35 +
No. Iterations: 12 +
================================================================================= +
coef std err z P>|z| [0.025 0.975] +
--------------------------------------------------------------------------------- +
Intercept 215.0848 2.448 87.856 0.000 210.287 219.883 +
dist 0.0460 0.001 46.166 0.000 0.044 0.048 +
nb_passengers -35.2686 1.119 -31.526 0.000 -37.461 -33.076 +
================================================================================= +
+
If the model instance has been used for another fit with different fit parameters, then the fit options might not be the correct ones anymore . +
+
+

Statistical testing: regression of fare on distance: 2001/2000 difference

+
result = sm.ols(formula="fare_2001 - fare_2000 ~ 1 + dist", data=data).fit()
+
print(result.summary()) +
+
# Plot the corresponding regression +
data["fare_difference"] = data["fare_2001"] - data["fare_2000"] +
seaborn.lmplot(x="dist", y="fare_difference", data=data) +
+
plt.show() +
+
+plot airfare
                            OLS Regression Results
+
============================================================================== +
Dep. Variable: fare_2001 R-squared: 0.159 +
Model: OLS Adj. R-squared: 0.159 +
Method: Least Squares F-statistic: 791.7 +
Date: Sun, 06 Oct 2024 Prob (F-statistic): 1.20e-159 +
Time: 19:11:35 Log-Likelihood: -22640. +
No. Observations: 4176 AIC: 4.528e+04 +
Df Residuals: 4174 BIC: 4.530e+04 +
Df Model: 1 +
Covariance Type: nonrobust +
============================================================================== +
coef std err t P>|t| [0.025 0.975] +
------------------------------------------------------------------------------ +
Intercept 148.0279 1.673 88.480 0.000 144.748 151.308 +
dist 0.0388 0.001 28.136 0.000 0.036 0.041 +
============================================================================== +
Omnibus: 136.558 Durbin-Watson: 1.544 +
Prob(Omnibus): 0.000 Jarque-Bera (JB): 149.624 +
Skew: 0.462 Prob(JB): 3.23e-33 +
Kurtosis: 2.920 Cond. No. 2.40e+03 +
============================================================================== +
+
Notes: +
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified. +
[2] The condition number is large, 2.4e+03. This might indicate that there are +
strong multicollinearity or other numerical problems. +
+
+

Total running time of the script: (0 minutes 7.718 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/statistics/auto_examples/plot_iris_analysis.html b/packages/statistics/auto_examples/plot_iris_analysis.html new file mode 100644 index 000000000..488c9801c --- /dev/null +++ b/packages/statistics/auto_examples/plot_iris_analysis.html @@ -0,0 +1,297 @@ + + + + + + + + 3.1.6.3. Analysis of Iris petal and sepal sizes — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.1.6.3. Analysis of Iris petal and sepal sizes

+

Illustrate an analysis on a real dataset:

+
    +
  • Visualizing the data to formulate intuitions

  • +
  • Fitting of a linear model

  • +
  • Hypothesis test of the effect of a categorical variable in the presence +of a continuous confound

  • +
+
import matplotlib.pyplot as plt
+
+
import pandas +
from pandas import plotting +
+
from statsmodels.formula.api import ols +
+
# Load the data +
data = pandas.read_csv("iris.csv") +
+
+

Plot a scatter matrix

+
# Express the names as categories
+
categories = pandas.Categorical(data["name"]) +
+
# The parameter 'c' is passed to plt.scatter and will control the color +
plotting.scatter_matrix(data, c=categories.codes, marker="o") +
+
fig = plt.gcf() +
fig.suptitle("blue: setosa, green: versicolor, red: virginica", size=13) +
+
+blue: setosa, green: versicolor, red: virginica
Text(0.5, 0.98, 'blue: setosa, green: versicolor, red: virginica')
+
+
+

Statistical analysis

+
# Let us try to explain the sepal length as a function of the petal
+
# width and the category of iris +
+
model = ols("sepal_width ~ name + petal_length", data).fit() +
print(model.summary()) +
+
# Now formulate a "contrast", to test if the offset for versicolor and +
# virginica are identical +
+
print("Testing the difference between effect of versicolor and virginica") +
print(model.f_test([0, 1, -1, 0])) +
plt.show() +
+
+
                            OLS Regression Results
+
============================================================================== +
Dep. Variable: sepal_width R-squared: 0.478 +
Model: OLS Adj. R-squared: 0.468 +
Method: Least Squares F-statistic: 44.63 +
Date: Sun, 06 Oct 2024 Prob (F-statistic): 1.58e-20 +
Time: 19:11:16 Log-Likelihood: -38.185 +
No. Observations: 150 AIC: 84.37 +
Df Residuals: 146 BIC: 96.41 +
Df Model: 3 +
Covariance Type: nonrobust +
====================================================================================== +
coef std err t P>|t| [0.025 0.975] +
-------------------------------------------------------------------------------------- +
Intercept 2.9813 0.099 29.989 0.000 2.785 3.178 +
name[T.versicolor] -1.4821 0.181 -8.190 0.000 -1.840 -1.124 +
name[T.virginica] -1.6635 0.256 -6.502 0.000 -2.169 -1.158 +
petal_length 0.2983 0.061 4.920 0.000 0.178 0.418 +
============================================================================== +
Omnibus: 2.868 Durbin-Watson: 1.753 +
Prob(Omnibus): 0.238 Jarque-Bera (JB): 2.885 +
Skew: -0.082 Prob(JB): 0.236 +
Kurtosis: 3.659 Cond. No. 54.0 +
============================================================================== +
+
Notes: +
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified. +
Testing the difference between effect of versicolor and virginica +
<F test: F=3.245335346574177, p=0.07369058781701142, df_denom=146, df_num=1> +
+
+

Total running time of the script: (0 minutes 0.427 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/statistics/auto_examples/plot_paired_boxplots.html b/packages/statistics/auto_examples/plot_paired_boxplots.html new file mode 100644 index 000000000..dc0f01998 --- /dev/null +++ b/packages/statistics/auto_examples/plot_paired_boxplots.html @@ -0,0 +1,246 @@ + + + + + + + + 3.1.6.1. Boxplots and paired differences — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.1.6.1. Boxplots and paired differences

+

Plot boxplots for FSIQ, PIQ, and the paired difference between the two: +while the spread (error bars) for FSIQ and PIQ are very large, there is a +systematic (common) effect due to the subjects. This effect is cancelled +out in the difference and the spread of the difference (“paired” by +subject) is much smaller than the spread of the individual measures.

+
    +
  • plot paired boxplots
  • +
  • plot paired boxplots
  • +
+
import pandas
+
+
import matplotlib.pyplot as plt +
+
data = pandas.read_csv("brain_size.csv", sep=";", na_values=".") +
+
# Box plot of FSIQ and PIQ (different measures od IQ) +
plt.figure(figsize=(4, 3)) +
data.boxplot(column=["FSIQ", "PIQ"]) +
+
# Boxplot of the difference +
plt.figure(figsize=(4, 3)) +
plt.boxplot(data["FSIQ"] - data["PIQ"]) +
plt.xticks((1,), ("FSIQ - PIQ",)) +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.072 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/statistics/auto_examples/plot_pandas.html b/packages/statistics/auto_examples/plot_pandas.html new file mode 100644 index 000000000..0b74a1ff5 --- /dev/null +++ b/packages/statistics/auto_examples/plot_pandas.html @@ -0,0 +1,248 @@ + + + + + + + + 3.1.6.2. Plotting simple quantities of a pandas dataframe — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.1.6.2. Plotting simple quantities of a pandas dataframe

+

This example loads from a CSV file data with mixed numerical and +categorical entries, and plots a few quantities, separately for females +and males, thanks to the pandas integrated plotting tool (that uses +matplotlib behind the scene).

+

See http://pandas.pydata.org/pandas-docs/stable/visualization.html

+
    +
  • Female, Male
  • +
  • plot pandas
  • +
  • plot pandas
  • +
+
import pandas
+
+
data = pandas.read_csv("brain_size.csv", sep=";", na_values=".") +
+
# Box plots of different columns for each gender +
groupby_gender = data.groupby("Gender") +
groupby_gender.boxplot(column=["FSIQ", "VIQ", "PIQ"]) +
+
from pandas import plotting +
+
# Scatter matrices for different columns +
plotting.scatter_matrix(data[["Weight", "Height", "MRI_Count"]]) +
plotting.scatter_matrix(data[["PIQ", "VIQ", "FSIQ"]]) +
+
import matplotlib.pyplot as plt +
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.536 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/statistics/auto_examples/plot_regression.html b/packages/statistics/auto_examples/plot_regression.html new file mode 100644 index 000000000..4c875ae48 --- /dev/null +++ b/packages/statistics/auto_examples/plot_regression.html @@ -0,0 +1,311 @@ + + + + + + + + 3.1.6.4. Simple Regression — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.1.6.4. Simple Regression

+

Fit a simple linear regression using ‘statsmodels’, compute corresponding +p-values.

+
# Original author: Thomas Haslwanter
+
+
import numpy as np +
import matplotlib.pyplot as plt +
import pandas +
+
# For statistics. Requires statsmodels 5.0 or more +
from statsmodels.formula.api import ols +
+
# Analysis of Variance (ANOVA) on linear models +
from statsmodels.stats.anova import anova_lm +
+
+

Generate and show the data

+
x = np.linspace(-5, 5, 20)
+
+
# To get reproducible values, provide a seed value +
rng = np.random.default_rng(27446968) +
+
y = -5 + 3 * x + 4 * np.random.normal(size=x.shape) +
+
# Plot the data +
plt.figure(figsize=(5, 4)) +
plt.plot(x, y, "o") +
+
+plot regression
[<matplotlib.lines.Line2D object at 0x7f5b0249c0e0>]
+
+
+

Multilinear regression model, calculating fit, P-values, confidence +intervals etc.

+
# Convert the data into a Pandas DataFrame to use the formulas framework
+
# in statsmodels +
data = pandas.DataFrame({"x": x, "y": y}) +
+
# Fit the model +
model = ols("y ~ x", data).fit() +
+
# Print the summary +
print(model.summary()) +
+
# Perform analysis of variance on fitted linear model +
anova_results = anova_lm(model) +
+
print("\nANOVA results") +
print(anova_results) +
+
+
                            OLS Regression Results
+
============================================================================== +
Dep. Variable: y R-squared: 0.845 +
Model: OLS Adj. R-squared: 0.836 +
Method: Least Squares F-statistic: 97.76 +
Date: Sun, 06 Oct 2024 Prob (F-statistic): 1.06e-08 +
Time: 19:11:17 Log-Likelihood: -53.560 +
No. Observations: 20 AIC: 111.1 +
Df Residuals: 18 BIC: 113.1 +
Df Model: 1 +
Covariance Type: nonrobust +
============================================================================== +
coef std err t P>|t| [0.025 0.975] +
------------------------------------------------------------------------------ +
Intercept -4.1877 0.830 -5.044 0.000 -5.932 -2.444 +
x 2.7046 0.274 9.887 0.000 2.130 3.279 +
============================================================================== +
Omnibus: 1.871 Durbin-Watson: 1.930 +
Prob(Omnibus): 0.392 Jarque-Bera (JB): 0.597 +
Skew: 0.337 Prob(JB): 0.742 +
Kurtosis: 3.512 Cond. No. 3.03 +
============================================================================== +
+
Notes: +
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified. +
+
ANOVA results +
df sum_sq mean_sq F PR(>F) +
x 1.0 1347.476043 1347.476043 97.760281 1.062847e-08 +
Residual 18.0 248.102486 13.783471 NaN NaN +
+
+

Plot the fitted model

+
# Retrieve the parameter estimates
+
offset, coef = model._results.params +
plt.plot(x, x * coef + offset) +
plt.xlabel("x") +
plt.ylabel("y") +
+
plt.show() +
+
+plot regression

Total running time of the script: (0 minutes 0.107 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/statistics/auto_examples/plot_regression_3d.html b/packages/statistics/auto_examples/plot_regression_3d.html new file mode 100644 index 000000000..d915ddc72 --- /dev/null +++ b/packages/statistics/auto_examples/plot_regression_3d.html @@ -0,0 +1,329 @@ + + + + + + + + 3.1.6.5. Multiple Regression — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.1.6.5. Multiple Regression

+

Calculate using ‘statsmodels’ just the best fit, or all the corresponding +statistical parameters.

+

Also shows how to make 3d plots.

+
# Original author: Thomas Haslwanter
+
+
import numpy as np +
import matplotlib.pyplot as plt +
import pandas +
+
# For 3d plots. This import is necessary to have 3D plotting below +
from mpl_toolkits.mplot3d import Axes3D +
+
# For statistics. Requires statsmodels 5.0 or more +
from statsmodels.formula.api import ols +
+
# Analysis of Variance (ANOVA) on linear models +
from statsmodels.stats.anova import anova_lm +
+
+

Generate and show the data

+
x = np.linspace(-5, 5, 21)
+
# We generate a 2D grid +
X, Y = np.meshgrid(x, x) +
+
# To get reproducible values, provide a seed value +
rng = np.random.default_rng(27446968) +
+
# Z is the elevation of this 2D grid +
Z = -5 + 3 * X - 0.5 * Y + 8 * np.random.normal(size=X.shape) +
+
# Plot the data +
ax: Axes3D = plt.figure().add_subplot(projection="3d") +
surf = ax.plot_surface(X, Y, Z, cmap="coolwarm", rstride=1, cstride=1) +
ax.view_init(20, -120) +
ax.set_xlabel("X") +
ax.set_ylabel("Y") +
ax.set_zlabel("Z") +
+
+plot regression 3d
Text(-0.10764513121260137, 0.009865032686848034, 'Z')
+
+
+

Multilinear regression model, calculating fit, P-values, confidence +intervals etc.

+
# Convert the data into a Pandas DataFrame to use the formulas framework
+
# in statsmodels +
+
# First we need to flatten the data: it's 2D layout is not relevant. +
X = X.flatten() +
Y = Y.flatten() +
Z = Z.flatten() +
+
data = pandas.DataFrame({"x": X, "y": Y, "z": Z}) +
+
# Fit the model +
model = ols("z ~ x + y", data).fit() +
+
# Print the summary +
print(model.summary()) +
+
print("\nRetrieving manually the parameter estimates:") +
print(model._results.params) +
# should be array([-4.99754526, 3.00250049, -0.50514907]) +
+
# Perform analysis of variance on fitted linear model +
anova_results = anova_lm(model) +
+
print("\nANOVA results") +
print(anova_results) +
+
plt.show() +
+
+
                            OLS Regression Results
+
============================================================================== +
Dep. Variable: z R-squared: 0.579 +
Model: OLS Adj. R-squared: 0.577 +
Method: Least Squares F-statistic: 300.7 +
Date: Sun, 06 Oct 2024 Prob (F-statistic): 6.43e-83 +
Time: 19:11:17 Log-Likelihood: -1552.0 +
No. Observations: 441 AIC: 3110. +
Df Residuals: 438 BIC: 3122. +
Df Model: 2 +
Covariance Type: nonrobust +
============================================================================== +
coef std err t P>|t| [0.025 0.975] +
------------------------------------------------------------------------------ +
Intercept -4.4332 0.390 -11.358 0.000 -5.200 -3.666 +
x 3.0861 0.129 23.940 0.000 2.833 3.340 +
y -0.6856 0.129 -5.318 0.000 -0.939 -0.432 +
============================================================================== +
Omnibus: 0.560 Durbin-Watson: 1.967 +
Prob(Omnibus): 0.756 Jarque-Bera (JB): 0.651 +
Skew: -0.077 Prob(JB): 0.722 +
Kurtosis: 2.893 Cond. No. 3.03 +
============================================================================== +
+
Notes: +
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified. +
+
Retrieving manually the parameter estimates: +
[-4.43322435 3.08614608 -0.68556194] +
+
ANOVA results +
df sum_sq mean_sq F PR(>F) +
x 1.0 38501.973182 38501.973182 573.111646 1.365553e-81 +
y 1.0 1899.955512 1899.955512 28.281320 1.676135e-07 +
Residual 438.0 29425.094352 67.180581 NaN NaN +
+
+

Total running time of the script: (0 minutes 0.093 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/statistics/auto_examples/plot_wage_data.html b/packages/statistics/auto_examples/plot_wage_data.html new file mode 100644 index 000000000..f927ee560 --- /dev/null +++ b/packages/statistics/auto_examples/plot_wage_data.html @@ -0,0 +1,302 @@ + + + + + + + + 3.1.6.7. Visualizing factors influencing wages — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.1.6.7. Visualizing factors influencing wages

+

This example uses seaborn to quickly plot various factors relating wages, +experience, and education.

+

Seaborn (https://seaborn.pydata.org) is a library that combines +visualization and statistical fits to show trends in data.

+

Note that importing seaborn changes the matplotlib style to have an +“excel-like” feeling. This changes affect other matplotlib figures. To +restore defaults once this example is run, we would need to call +plt.rcdefaults().

+
# Standard library imports
+
import os +
+
import matplotlib.pyplot as plt +
+
+

Load the data

+
import pandas
+
import requests +
+
if not os.path.exists("wages.txt"): +
# Download the file if it is not present +
r = requests.get("http://lib.stat.cmu.edu/datasets/CPS_85_Wages") +
with open("wages.txt", "wb") as f: +
f.write(r.content) +
+
# Give names to the columns +
names = [ +
"EDUCATION: Number of years of education", +
"SOUTH: 1=Person lives in South, 0=Person lives elsewhere", +
"SEX: 1=Female, 0=Male", +
"EXPERIENCE: Number of years of work experience", +
"UNION: 1=Union member, 0=Not union member", +
"WAGE: Wage (dollars per hour)", +
"AGE: years", +
"RACE: 1=Other, 2=Hispanic, 3=White", +
"OCCUPATION: 1=Management, 2=Sales, 3=Clerical, 4=Service, 5=Professional, 6=Other", +
"SECTOR: 0=Other, 1=Manufacturing, 2=Construction", +
"MARR: 0=Unmarried, 1=Married", +
] +
+
short_names = [n.split(":")[0] for n in names] +
+
data = pandas.read_csv( +
"wages.txt", skiprows=27, skipfooter=6, sep=None, header=None, engine="python" +
) +
data.columns = pandas.Index(short_names) +
+
# Log-transform the wages, because they typically are increased with +
# multiplicative factors +
import numpy as np +
+
data["WAGE"] = np.log10(data["WAGE"]) +
+
+

Plot scatter matrices highlighting different aspects

+
import seaborn
+
+
seaborn.pairplot(data, vars=["WAGE", "AGE", "EDUCATION"], kind="reg") +
+
seaborn.pairplot(data, vars=["WAGE", "AGE", "EDUCATION"], kind="reg", hue="SEX") +
plt.suptitle("Effect of gender: 1=Female, 0=Male") +
+
seaborn.pairplot(data, vars=["WAGE", "AGE", "EDUCATION"], kind="reg", hue="RACE") +
plt.suptitle("Effect of race: 1=Other, 2=Hispanic, 3=White") +
+
seaborn.pairplot(data, vars=["WAGE", "AGE", "EDUCATION"], kind="reg", hue="UNION") +
plt.suptitle("Effect of union: 1=Union member, 0=Not union member") +
+
+
    +
  • plot wage data
  • +
  • Effect of gender: 1=Female, 0=Male
  • +
  • Effect of race: 1=Other, 2=Hispanic, 3=White
  • +
  • Effect of union: 1=Union member, 0=Not union member
  • +
+
Text(0.5, 0.98, 'Effect of union: 1=Union member, 0=Not union member')
+
+
+

Plot a simple regression

+
seaborn.lmplot(y="WAGE", x="EDUCATION", data=data)
+
+
plt.show() +
+
+plot wage data

Total running time of the script: (0 minutes 9.494 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/statistics/auto_examples/plot_wage_education_gender.html b/packages/statistics/auto_examples/plot_wage_education_gender.html new file mode 100644 index 000000000..ed72a0bd0 --- /dev/null +++ b/packages/statistics/auto_examples/plot_wage_education_gender.html @@ -0,0 +1,360 @@ + + + + + + + + 3.1.6.6. Test for an education/gender interaction in wages — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

3.1.6.6. Test for an education/gender interaction in wages

+

Wages depend mostly on education. Here we investigate how this dependence +is related to gender: not only does gender create an offset in wages, it +also seems that wages increase more with education for males than +females.

+

Does our data support this last hypothesis? We will test this using +statsmodels’ formulas +(http://statsmodels.sourceforge.net/stable/example_formulas.html).

+

Load and massage the data

+
import pandas
+
+
import urllib.request +
import os +
+
if not os.path.exists("wages.txt"): +
# Download the file if it is not present +
url = "http://lib.stat.cmu.edu/datasets/CPS_85_Wages" +
with urllib.request.urlopen(url) as r, open("wages.txt", "wb") as f: +
f.write(r.read()) +
+
# EDUCATION: Number of years of education +
# SEX: 1=Female, 0=Male +
# WAGE: Wage (dollars per hour) +
data = pandas.read_csv( +
"wages.txt", +
skiprows=27, +
skipfooter=6, +
sep=None, +
header=None, +
names=["education", "gender", "wage"], +
usecols=[0, 2, 5], +
) +
+
# Convert genders to strings (this is particularly useful so that the +
# statsmodels formulas detects that gender is a categorical variable) +
import numpy as np +
+
data["gender"] = np.choose(data.gender, ["male", "female"]) +
+
# Log-transform the wages, because they typically are increased with +
# multiplicative factors +
data["wage"] = np.log10(data["wage"]) +
+
+
/home/runner/work/scientific-python-lectures/scientific-python-lectures/packages/statistics/examples/plot_wage_education_gender.py:32: ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support skipfooter; you can avoid this warning by specifying engine='python'.
+
data = pandas.read_csv( +
+
+

simple plotting

+
import seaborn
+
+
# Plot 2 linear fits for male and female. +
seaborn.lmplot(y="wage", x="education", hue="gender", data=data) +
+
+plot wage education gender
<seaborn.axisgrid.FacetGrid object at 0x7f5b0249eed0>
+
+
+

statistical analysis

+
import statsmodels.formula.api as sm
+
+
# Note that this model is not the plot displayed above: it is one +
# joined model for male and female, not separate models for male and +
# female. The reason is that a single model enables statistical testing +
result = sm.ols(formula="wage ~ education + gender", data=data).fit() +
print(result.summary()) +
+
+
                            OLS Regression Results
+
============================================================================== +
Dep. Variable: wage R-squared: 0.193 +
Model: OLS Adj. R-squared: 0.190 +
Method: Least Squares F-statistic: 63.42 +
Date: Sun, 06 Oct 2024 Prob (F-statistic): 2.01e-25 +
Time: 19:11:18 Log-Likelihood: 86.654 +
No. Observations: 534 AIC: -167.3 +
Df Residuals: 531 BIC: -154.5 +
Df Model: 2 +
Covariance Type: nonrobust +
================================================================================== +
coef std err t P>|t| [0.025 0.975] +
---------------------------------------------------------------------------------- +
Intercept 0.4053 0.046 8.732 0.000 0.314 0.496 +
gender[T.male] 0.1008 0.018 5.625 0.000 0.066 0.136 +
education 0.0334 0.003 9.768 0.000 0.027 0.040 +
============================================================================== +
Omnibus: 4.675 Durbin-Watson: 1.792 +
Prob(Omnibus): 0.097 Jarque-Bera (JB): 4.876 +
Skew: -0.147 Prob(JB): 0.0873 +
Kurtosis: 3.365 Cond. No. 69.7 +
============================================================================== +
+
Notes: +
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified. +
+
+

The plots above highlight that there is not only a different offset in +wage but also a different slope

+

We need to model this using an interaction

+
result = sm.ols(
+
formula="wage ~ education + gender + education * gender", data=data +
).fit() +
print(result.summary()) +
+
+
                            OLS Regression Results
+
============================================================================== +
Dep. Variable: wage R-squared: 0.198 +
Model: OLS Adj. R-squared: 0.194 +
Method: Least Squares F-statistic: 43.72 +
Date: Sun, 06 Oct 2024 Prob (F-statistic): 2.94e-25 +
Time: 19:11:18 Log-Likelihood: 88.503 +
No. Observations: 534 AIC: -169.0 +
Df Residuals: 530 BIC: -151.9 +
Df Model: 3 +
Covariance Type: nonrobust +
============================================================================================ +
coef std err t P>|t| [0.025 0.975] +
-------------------------------------------------------------------------------------------- +
Intercept 0.2998 0.072 4.173 0.000 0.159 0.441 +
gender[T.male] 0.2750 0.093 2.972 0.003 0.093 0.457 +
education 0.0415 0.005 7.647 0.000 0.031 0.052 +
education:gender[T.male] -0.0134 0.007 -1.919 0.056 -0.027 0.000 +
============================================================================== +
Omnibus: 4.838 Durbin-Watson: 1.825 +
Prob(Omnibus): 0.089 Jarque-Bera (JB): 5.000 +
Skew: -0.156 Prob(JB): 0.0821 +
Kurtosis: 3.356 Cond. No. 194. +
============================================================================== +
+
Notes: +
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified. +
+
+

Looking at the p-value of the interaction of gender and education, the +data does not support the hypothesis that education benefits males +more than female (p-value > 0.05).

+
import matplotlib.pyplot as plt
+
+
plt.show() +
+
+

Total running time of the script: (0 minutes 0.520 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/statistics/auto_examples/sg_execution_times.html b/packages/statistics/auto_examples/sg_execution_times.html new file mode 100644 index 000000000..a8976b692 --- /dev/null +++ b/packages/statistics/auto_examples/sg_execution_times.html @@ -0,0 +1,234 @@ + + + + + + + + Computation times — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Computation times

+

00:18.966 total execution time for 8 files from packages/statistics/auto_examples:

+
+ + + + + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Example

Time

Mem (MB)

Visualizing factors influencing wages (plot_wage_data.py)

00:09.494

0.0

Air fares before and after 9/11 (plot_airfare.py)

00:07.718

0.0

Plotting simple quantities of a pandas dataframe (plot_pandas.py)

00:00.536

0.0

Test for an education/gender interaction in wages (plot_wage_education_gender.py)

00:00.520

0.0

Analysis of Iris petal and sepal sizes (plot_iris_analysis.py)

00:00.427

0.0

Simple Regression (plot_regression.py)

00:00.107

0.0

Multiple Regression (plot_regression_3d.py)

00:00.093

0.0

Boxplots and paired differences (plot_paired_boxplots.py)

00:00.072

0.0

+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/statistics/auto_examples/solutions/index.html b/packages/statistics/auto_examples/solutions/index.html new file mode 100644 index 000000000..da5d10ff7 --- /dev/null +++ b/packages/statistics/auto_examples/solutions/index.html @@ -0,0 +1,208 @@ + + + + + + + + 3.1.7.1. Solutions to this chapter’s exercises — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

3.1.7.1. Solutions to this chapter’s exercises

+
+

Relating Gender and IQ

+
Relating Gender and IQ
+
+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/statistics/auto_examples/solutions/plot_brain_size.html b/packages/statistics/auto_examples/solutions/plot_brain_size.html new file mode 100644 index 000000000..b9d22cb5a --- /dev/null +++ b/packages/statistics/auto_examples/solutions/plot_brain_size.html @@ -0,0 +1,302 @@ + + + + + + + + Relating Gender and IQ — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + +
+

Relating Gender and IQ

+

Going back to the brain size + IQ data, test if the VIQ of male and +female are different after removing the effect of brain size, height and +weight.

+

Notice that here ‘Gender’ is a categorical value. As it is a non-float +data type, statsmodels is able to automatically infer this.

+
import pandas
+
from statsmodels.formula.api import ols +
+
data = pandas.read_csv("../brain_size.csv", sep=";", na_values=".") +
+
model = ols("VIQ ~ Gender + MRI_Count + Height", data).fit() +
print(model.summary()) +
+
# Here, we don't need to define a contrast, as we are testing a single +
# coefficient of our model, and not a combination of coefficients. +
# However, defining a contrast, which would then be a 'unit contrast', +
# will give us the same results +
print(model.f_test([0, 1, 0, 0])) +
+
+
                            OLS Regression Results
+
============================================================================== +
Dep. Variable: VIQ R-squared: 0.246 +
Model: OLS Adj. R-squared: 0.181 +
Method: Least Squares F-statistic: 3.809 +
Date: Sun, 06 Oct 2024 Prob (F-statistic): 0.0184 +
Time: 19:11:35 Log-Likelihood: -172.34 +
No. Observations: 39 AIC: 352.7 +
Df Residuals: 35 BIC: 359.3 +
Df Model: 3 +
Covariance Type: nonrobust +
================================================================================== +
coef std err t P>|t| [0.025 0.975] +
---------------------------------------------------------------------------------- +
Intercept 166.6258 88.824 1.876 0.069 -13.696 346.948 +
Gender[T.Male] 8.8524 10.710 0.827 0.414 -12.890 30.595 +
MRI_Count 0.0002 6.46e-05 2.615 0.013 3.78e-05 0.000 +
Height -3.0837 1.276 -2.417 0.021 -5.674 -0.494 +
============================================================================== +
Omnibus: 7.373 Durbin-Watson: 2.109 +
Prob(Omnibus): 0.025 Jarque-Bera (JB): 2.252 +
Skew: 0.005 Prob(JB): 0.324 +
Kurtosis: 1.823 Cond. No. 2.40e+07 +
============================================================================== +
+
Notes: +
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified. +
[2] The condition number is large, 2.4e+07. This might indicate that there are +
strong multicollinearity or other numerical problems. +
<F test: F=0.683196084584229, p=0.4140878441244694, df_denom=35, df_num=1> +
+
+

Here we plot a scatter matrix to get intuitions on our results. +This goes beyond what was asked in the exercise

+
# This plotting is useful to get an intuitions on the relationships between
+
# our different variables +
+
from pandas import plotting +
import matplotlib.pyplot as plt +
+
# Fill in the missing values for Height for plotting +
data["Height"] = data["Height"].ffill() +
+
# The parameter 'c' is passed to plt.scatter and will control the color +
# The same holds for parameters 'marker', 'alpha' and 'cmap', that +
# control respectively the type of marker used, their transparency and +
# the colormap +
plotting.scatter_matrix( +
data[["VIQ", "MRI_Count", "Height"]], +
c=(data["Gender"] == "Female"), +
marker="o", +
alpha=1, +
cmap="winter", +
) +
+
fig = plt.gcf() +
fig.suptitle("blue: male, green: female", size=13) +
+
plt.show() +
+
+blue: male, green: female

Total running time of the script: (0 minutes 0.236 seconds)

+ +

Gallery generated by Sphinx-Gallery

+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/statistics/auto_examples/solutions/sg_execution_times.html b/packages/statistics/auto_examples/solutions/sg_execution_times.html new file mode 100644 index 000000000..8958baa8d --- /dev/null +++ b/packages/statistics/auto_examples/solutions/sg_execution_times.html @@ -0,0 +1,206 @@ + + + + + + + + Computation times — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Computation times

+

00:00.236 total execution time for 1 file from packages/statistics/auto_examples/solutions:

+
+ + + + + +++++ + + + + + + + + + + + + +

Example

Time

Mem (MB)

Relating Gender and IQ (plot_brain_size.py)

00:00.236

0.0

+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/statistics/index.html b/packages/statistics/index.html new file mode 100644 index 000000000..cbb8b3991 --- /dev/null +++ b/packages/statistics/index.html @@ -0,0 +1,1131 @@ + + + + + + + + 3.1. Statistics in Python — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

3.1. Statistics in Python

+

Author: Gaël Varoquaux

+ +
+

See also

+
    +
  • Bayesian statistics in Python: +This chapter does not cover tools for Bayesian statistics. Of +particular interest for Bayesian modelling is PyMC, which implements a probabilistic +programming language in Python.

  • +
  • Read a statistics book: +The Think stats book is +available as free PDF or in print and is a great introduction to +statistics.

  • +
+
+
+

+
+
+

Tip

+

Why Python for statistics?

+

R is a language dedicated to statistics. Python is a general-purpose +language with statistics modules. R has more statistical analysis +features than Python, and specialized syntaxes. However, when it +comes to building complex analysis pipelines that mix statistics with +e.g. image analysis, text mining, or control of a physical +experiment, the richness of Python is an invaluable asset.

+
+ +
+

Tip

+

In this document, the Python inputs are represented with the sign +“>>>”.

+
+

+
+

Disclaimer: Gender questions

+

Some of the examples of this tutorial are chosen around gender +questions. The reason is that on such questions controlling the truth +of a claim actually matters to many people.

+
+
+

3.1.1. Data representation and interaction

+
+

3.1.1.1. Data as a table

+

The setting that we consider for statistical analysis is that of multiple +observations or samples described by a set of different attributes +or features. The data can than be seen as a 2D table, or matrix, with +columns giving the different attributes of the data, and rows the +observations. For instance, the data contained in +examples/brain_size.csv:

+
"";"Gender";"FSIQ";"VIQ";"PIQ";"Weight";"Height";"MRI_Count"
+
"1";"Female";133;132;124;"118";"64.5";816932 +
"2";"Male";140;150;124;".";"72.5";1001121 +
"3";"Male";139;123;150;"143";"73.3";1038437 +
"4";"Male";133;129;128;"172";"68.8";965353 +
"5";"Female";137;132;134;"147";"65.0";951545 +
+
+
+
+

3.1.1.2. The pandas data-frame

+
+

Tip

+

We will store and manipulate this data in a +pandas.DataFrame, from the pandas module. It is the Python equivalent of +the spreadsheet table. It is different from a 2D numpy array as it +has named columns, can contain a mixture of different data types by +column, and has elaborate selection and pivotal mechanisms.

+
+
+

Creating dataframes: reading data files or converting arrays

+ +

Reading from a CSV file: Using the above CSV file that gives +observations of brain size and weight and IQ (Willerman et al. 1991), the +data are a mixture of numerical and categorical values:

+
>>> import pandas
+
>>> data = pandas.read_csv('examples/brain_size.csv', sep=';', na_values=".") +
>>> data +
Unnamed: 0 Gender FSIQ VIQ PIQ Weight Height MRI_Count +
0 1 Female 133 132 124 118.0 64.5 816932 +
1 2 Male 140 150 124 NaN 72.5 1001121 +
2 3 Male 139 123 150 143.0 73.3 1038437 +
3 4 Male 133 129 128 172.0 68.8 965353 +
4 5 Female 137 132 134 147.0 65.0 951545 +
... +
+
+
+

Warning

+

Missing values

+

The weight of the second individual is missing in the CSV file. If we +don’t specify the missing value (NA = not available) marker, we will +not be able to do statistical analysis.

+
+
+

+
+

Creating from arrays: A pandas.DataFrame can also be seen +as a dictionary of 1D ‘series’, eg arrays or lists. If we have 3 +numpy arrays:

+
>>> import numpy as np
+
>>> t = np.linspace(-6, 6, 20) +
>>> sin_t = np.sin(t) +
>>> cos_t = np.cos(t) +
+
+

We can expose them as a pandas.DataFrame:

+
>>> pandas.DataFrame({'t': t, 'sin': sin_t, 'cos': cos_t})
+
t sin cos +
0 -6.000000 0.279415 0.960170 +
1 -5.368421 0.792419 0.609977 +
2 -4.736842 0.999701 0.024451 +
3 -4.105263 0.821291 -0.570509 +
4 -3.473684 0.326021 -0.945363 +
5 -2.842105 -0.295030 -0.955488 +
6 -2.210526 -0.802257 -0.596979 +
7 -1.578947 -0.999967 -0.008151 +
8 -0.947368 -0.811882 0.583822 +
... +
+
+
+

+
+

Other inputs: pandas can input data from +SQL, excel files, or other formats. See the pandas documentation.

+
+

+
+
+
+

Manipulating data

+

data is a pandas.DataFrame, that resembles R’s dataframe:

+
>>> data.shape    # 40 rows and 8 columns
+
(40, 8) +
+
>>> data.columns # It has columns +
Index(['Unnamed: 0', 'Gender', 'FSIQ', 'VIQ', 'PIQ', 'Weight', 'Height', +
'MRI_Count'], +
dtype='object') +
+
>>> print(data['Gender']) # Columns can be addressed by name +
0 Female +
1 Male +
2 Male +
3 Male +
4 Female +
... +
+
>>> # Simpler selector +
>>> data[data['Gender'] == 'Female']['VIQ'].mean() +
np.float64(109.45) +
+
+
+

Note

+

For a quick view on a large dataframe, use its describe +method: pandas.DataFrame.describe().

+
+
+

+
+

groupby: splitting a dataframe on values of categorical variables:

+
>>> groupby_gender = data.groupby('Gender')
+
>>> for gender, value in groupby_gender['VIQ']: +
... print((gender, value.mean())) +
('Female', np.float64(109.45)) +
('Male', np.float64(115.25)) +
+
+

groupby_gender is a powerful object that exposes many +operations on the resulting group of dataframes:

+
>>> groupby_gender.mean()
+
Unnamed: 0 FSIQ VIQ PIQ Weight Height MRI_Count +
Gender +
Female 19.65 111.9 109.45 110.45 137.200000 65.765000 862654.6 +
Male 21.35 115.0 115.25 111.60 166.444444 71.431579 954855.4 +
+
+
+

Tip

+

Use tab-completion on groupby_gender to find more. Other common +grouping functions are median, count (useful for checking to see the +amount of missing values in different subsets) or sum. Groupby +evaluation is lazy, no work is done until an aggregation function is +applied.

+
+
+

+
+../../_images/sphx_glr_plot_pandas_001.png + + +
+

Note

+

groupby_gender.boxplot is used for the plots above (see this +example).

+
+
+

+
+
+
+

Plotting data

+

Pandas comes with some plotting tools (pandas.plotting, using +matplotlib behind the scene) to display statistics of the data in +dataframes:

+

Scatter matrices:

+
>>> from pandas import plotting
+
>>> plotting.scatter_matrix(data[['Weight', 'Height', 'MRI_Count']]) +
array([[<Axes: xlabel='Weight', ylabel='Weight'>, +
<Axes: xlabel='Height', ylabel='Weight'>, +
<Axes: xlabel='MRI_Count', ylabel='Weight'>], +
[<Axes: xlabel='Weight', ylabel='Height'>, +
<Axes: xlabel='Height', ylabel='Height'>, +
<Axes: xlabel='MRI_Count', ylabel='Height'>], +
[<Axes: xlabel='Weight', ylabel='MRI_Count'>, +
<Axes: xlabel='Height', ylabel='MRI_Count'>, +
<Axes: xlabel='MRI_Count', ylabel='MRI_Count'>]], dtype=object) +
+
+../../_images/sphx_glr_plot_pandas_002.png + +
>>> plotting.scatter_matrix(data[['PIQ', 'VIQ', 'FSIQ']])
+
array([[<Axes: xlabel='PIQ', ylabel='PIQ'>, +
<Axes: xlabel='VIQ', ylabel='PIQ'>, +
<Axes: xlabel='FSIQ', ylabel='PIQ'>], +
[<Axes: xlabel='PIQ', ylabel='VIQ'>, +
<Axes: xlabel='VIQ', ylabel='VIQ'>, +
<Axes: xlabel='FSIQ', ylabel='VIQ'>], +
[<Axes: xlabel='PIQ', ylabel='FSIQ'>, +
<Axes: xlabel='VIQ', ylabel='FSIQ'>, +
<Axes: xlabel='FSIQ', ylabel='FSIQ'>]], dtype=object) +
+
+ +../../_images/sphx_glr_plot_pandas_003.png + + +
+
+
+
+

3.1.2. Hypothesis testing: comparing two groups

+

For simple statistical tests, we will +use the scipy.stats sub-module of SciPy:

+
>>> import scipy as sp
+
+
+
+

See also

+

SciPy is a vast library. For a quick summary to the whole library, see +the scipy chapter.

+
+
+

3.1.2.1. Student’s t-test: the simplest statistical test

+
+

One-sample tests: testing the value of a population mean

+../../_images/two_sided.png + +

scipy.stats.ttest_1samp() tests the null hypothesis that the mean +of the population underlying the data is equal to a given value. It returns +the T statistic, +and the p-value (see the +function’s help):

+
>>> sp.stats.ttest_1samp(data['VIQ'], 0)
+
TtestResult(statistic=np.float64(30.088099970...), pvalue=np.float64(1.32891964...e-28), df=np.int64(39)) +
+
+

The p-value of 10^-28 indicates that such an extreme value of the statistic +is unlikely to be observed under the null hypothesis. This may be taken as +evidence that the null hypothesis is false and that the population mean IQ +(VIQ measure) is not 0.

+

Technically, the p-value of the t-test is derived under the assumption that +the means of samples drawn from the population are normally distributed. +This condition is exactly satisfied when the population itself is normally +distributed; however, due to the central limit theorem, the condition is +nearly true for reasonably large samples drawn from populations that follow +a variety of non-normal distributions.

+

Nonetheless, if we are concerned that violation of the normality assumptions +will affect the conclusions of the test, we can use a Wilcoxon signed-rank test, which relaxes +this assumption at the expense of test power:

+
>>> sp.stats.wilcoxon(data['VIQ'])
+
WilcoxonResult(statistic=np.float64(0.0), pvalue=np.float64(1.8189894...e-12)) +
+
+
+
+

Two-sample t-test: testing for difference across populations

+

We have seen above that the mean VIQ in the male and female samples +were different. To test whether this difference is significant (and +suggests that there is a difference in population means), we perform +a two-sample t-test using scipy.stats.ttest_ind():

+
>>> female_viq = data[data['Gender'] == 'Female']['VIQ']
+
>>> male_viq = data[data['Gender'] == 'Male']['VIQ'] +
>>> sp.stats.ttest_ind(female_viq, male_viq) +
TtestResult(statistic=np.float64(-0.77261617232...), pvalue=np.float64(0.4445287677858...), df=np.float64(38.0)) +
+
+

The corresponding non-parametric test is the Mann–Whitney U +test, +scipy.stats.mannwhitneyu().

+
>>> sp.stats.mannwhitneyu(female_viq, male_viq)
+
MannwhitneyuResult(statistic=np.float64(164.5), pvalue=np.float64(0.34228868687...)) +
+
+
+
+
+

3.1.2.2. Paired tests: repeated measurements on the same individuals

+../../_images/sphx_glr_plot_paired_boxplots_001.png + +

PIQ, VIQ, and FSIQ give three measures of IQ. Let us test whether FISQ +and PIQ are significantly different. We can use an “independent sample” test:

+
>>> sp.stats.ttest_ind(data['FSIQ'], data['PIQ'])
+
TtestResult(statistic=np.float64(0.46563759638...), pvalue=np.float64(0.64277250...), df=np.float64(78.0)) +
+
+

The problem with this approach is that it ignores an important relationship +between observations: FSIQ and PIQ are measured on the same individuals. +Thus, the variance due to inter-subject variability is confounding, reducing +the power of the test. This variability can be removed using a “paired test” +or “repeated measures test”:

+
>>> sp.stats.ttest_rel(data['FSIQ'], data['PIQ'])
+
TtestResult(statistic=np.float64(1.784201940...), pvalue=np.float64(0.082172638183...), df=np.int64(39)) +
+
+../../_images/sphx_glr_plot_paired_boxplots_002.png + +

This is equivalent to a one-sample test on the differences between paired +observations:

+
>>> sp.stats.ttest_1samp(data['FSIQ'] - data['PIQ'], 0)
+
TtestResult(statistic=np.float64(1.784201940...), pvalue=np.float64(0.082172638...), df=np.int64(39)) +
+
+

Accordingly, we can perform a nonparametric version of the test with +wilcoxon.

+
>>> sp.stats.wilcoxon(data['FSIQ'], data['PIQ'], method="approx")
+
WilcoxonResult(statistic=np.float64(274.5), pvalue=np.float64(0.106594927135...)) +
+
+ +
+

+
+
+
+
+

3.1.3. Linear models, multiple factors, and analysis of variance

+
+

3.1.3.1. “formulas” to specify statistical models in Python

+
+

A simple linear regression

+../../_images/sphx_glr_plot_regression_001.png + +

Given two set of observations, x and y, we want to test the +hypothesis that y is a linear function of x. In other terms:

+
+

y = x * \textit{coef} + \textit{intercept} + e

+
+

where e is observation noise. We will use the statsmodels module to:

+
    +
  1. Fit a linear model. We will use the simplest strategy, ordinary least +squares (OLS).

  2. +
  3. Test that coef is non zero.

  4. +
+
+

+
+

First, we generate simulated data according to the model:

+
>>> import numpy as np
+
>>> x = np.linspace(-5, 5, 20) +
>>> rng = np.random.default_rng(27446968) +
>>> # normal distributed noise +
>>> y = -5 + 3*x + 4 * rng.normal(size=x.shape) +
>>> # Create a data frame containing all the relevant variables +
>>> data = pandas.DataFrame({'x': x, 'y': y}) +
+
+ +
+

+
+

Then we specify an OLS model and fit it:

+
>>> from statsmodels.formula.api import ols
+
>>> model = ols("y ~ x", data).fit() +
+
+

We can inspect the various statistics derived from the fit:

+
>>> print(model.summary()) 
+
OLS Regression Results +
============================================================================== +
Dep. Variable: y R-squared: 0.901 +
Model: OLS Adj. R-squared: 0.896 +
Method: Least Squares F-statistic: 164.5 +
Date: ... Prob (F-statistic): 1.72e-10 +
Time: ... Log-Likelihood: -51.758 +
No. Observations: 20 AIC: 107.5 +
Df Residuals: 18 BIC: 109.5 +
Df Model: 1 +
Covariance Type: nonrobust +
============================================================================== +
coef std err t P>|t| [0.025 0.975] +
------------------------------------------------------------------------------ +
Intercept -4.2948 0.759 -5.661 0.000 -5.889 -2.701 +
x 3.2060 0.250 12.825 0.000 2.681 3.731 +
============================================================================== +
Omnibus: 1.218 Durbin-Watson: 1.796 +
Prob(Omnibus): 0.544 Jarque-Bera (JB): 0.999 +
Skew: 0.503 Prob(JB): 0.607 +
Kurtosis: 2.568 Cond. No. 3.03 +
============================================================================== +
+
Notes: +
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified. +
+
+ + +
+

+
+
+
+

Categorical variables: comparing groups or multiple categories

+

Let us go back the data on brain size:

+
>>> data = pandas.read_csv('examples/brain_size.csv', sep=';', na_values=".")
+
+
+

We can write a comparison between IQ of male and female using a linear +model:

+
>>> model = ols("VIQ ~ Gender + 1", data).fit()
+
>>> print(model.summary()) +
OLS Regression Results +
============================================================================== +
Dep. Variable: VIQ R-squared: 0.015 +
Model: OLS Adj. R-squared: -0.010 +
Method: Least Squares F-statistic: 0.5969 +
Date: ... Prob (F-statistic): 0.445 +
Time: ... Log-Likelihood: -182.42 +
No. Observations: 40 AIC: 368.8 +
Df Residuals: 38 BIC: 372.2 +
Df Model: 1 +
Covariance Type: nonrobust +
================================================================================== +
coef std err t P>|t| [0.025 0.975] +
---------------------------------------------------------------------------------- +
Intercept 109.4500 5.308 20.619 0.000 98.704 120.196 +
Gender[T.Male] 5.8000 7.507 0.773 0.445 -9.397 20.997 +
============================================================================== +
Omnibus: 26.188 Durbin-Watson: 1.709 +
Prob(Omnibus): 0.000 Jarque-Bera (JB): 3.703 +
Skew: 0.010 Prob(JB): 0.157 +
Kurtosis: 1.510 Cond. No. 2.62 +
============================================================================== +
+
Notes: +
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified. +
+
+ +
+

+
+ +
+
+
+

3.1.3.2. Multiple Regression: including multiple factors

+../../_images/sphx_glr_plot_regression_3d_001.png + +
+

+
+

Consider a linear model explaining a variable z (the dependent +variable) with 2 variables x and y:

+
+

z = x \, c_1 + y \, c_2 + i + e

+
+

Such a model can be seen in 3D as fitting a plane to a cloud of (x, +y, z) points.

+
+

+

+
+

Example: the iris data (examples/iris.csv)

+
+

Tip

+

Sepal and petal size tend to be related: bigger flowers are bigger! +But is there in addition a systematic effect of species?

+
+../../_images/sphx_glr_plot_iris_analysis_001.png + +
>>> data = pandas.read_csv('examples/iris.csv')
+
>>> model = ols('sepal_width ~ name + petal_length', data).fit() +
>>> print(model.summary()) +
OLS Regression Results +
==========================... +
Dep. Variable: sepal_width R-squared: 0.478 +
Model: OLS Adj. R-squared: 0.468 +
Method: Least Squares F-statistic: 44.63 +
Date: ... Prob (F-statistic): 1.58e-20 +
Time: ... Log-Likelihood: -38.185 +
No. Observations: 150 AIC: 84.37 +
Df Residuals: 146 BIC: 96.41 +
Df Model: 3 +
Covariance Type: nonrobust +
==========================... +
coef std err t P>|t| [0.025 0.975] +
------------------------------------------... +
Intercept 2.9813 0.099 29.989 0.000 2.785 3.178 +
name[T.versicolor] -1.4821 0.181 -8.190 0.000 -1.840 -1.124 +
name[T.virginica] -1.6635 0.256 -6.502 0.000 -2.169 -1.158 +
petal_length 0.2983 0.061 4.920 0.000 0.178 0.418 +
==========================... +
Omnibus: 2.868 Durbin-Watson: 1.753 +
Prob(Omnibus): 0.238 Jarque-Bera (JB): 2.885 +
Skew: -0.082 Prob(JB): 0.236 +
Kurtosis: 3.659 Cond. No. 54.0 +
==========================... +
+
Notes: +
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified. +
+
+
+

+
+
+
+

3.1.3.3. Post-hoc hypothesis testing: analysis of variance (ANOVA)

+

In the above iris example, we wish to test if the petal length is +different between versicolor and virginica, after removing the effect of +sepal width. This can be formulated as testing the difference between the +coefficient associated to versicolor and virginica in the linear model +estimated above (it is an Analysis of Variance, ANOVA). For this, we +write a vector of ‘contrast’ on the parameters estimated: we want to +test "name[T.versicolor] - name[T.virginica]", with an F-test:

+
>>> print(model.f_test([0, 1, -1, 0]))
+
<F test: F=3.24533535..., p=0.07369..., df_denom=146, df_num=1> +
+
+

Is this difference significant?

+
+

+
+ +
+

+
+
+
+
+

3.1.4. More visualization: seaborn for statistical exploration

+

Seaborn combines +simple statistical fits with plotting on pandas dataframes.

+

Let us consider a data giving wages and many other personal information +on 500 individuals (Berndt, ER. The Practice of Econometrics. 1991. NY: +Addison-Wesley).

+
+

Tip

+

The full code loading and plotting of the wages data is found in +corresponding example.

+
+
>>> print(data)  
+
EDUCATION SOUTH SEX EXPERIENCE UNION WAGE AGE RACE \ +
0 8 0 1 21 0 0.707570 35 2 +
1 9 0 1 42 0 0.694605 57 3 +
2 12 0 0 1 0 0.824126 19 3 +
3 12 0 0 4 0 0.602060 22 3 +
... +
+
+
+

3.1.4.1. Pairplot: scatter matrices

+

We can easily have an intuition on the interactions between continuous +variables using seaborn.pairplot() to display a scatter matrix:

+
>>> import seaborn
+
>>> seaborn.pairplot(data, vars=['WAGE', 'AGE', 'EDUCATION'], +
... kind='reg') +
+
+../../_images/sphx_glr_plot_wage_data_001.png + +

Categorical variables can be plotted as the hue:

+
>>> seaborn.pairplot(data, vars=['WAGE', 'AGE', 'EDUCATION'],
+
... kind='reg', hue='SEX') +
+
+../../_images/sphx_glr_plot_wage_data_002.png + + +
+
+

3.1.4.2. lmplot: plotting a univariate regression

+../../_images/sphx_glr_plot_wage_data_005.png + +

A regression capturing the relation between one variable and another, eg +wage, and education, can be plotted using seaborn.lmplot():

+
>>> seaborn.lmplot(y='WAGE', x='EDUCATION', data=data)  
+
+
+
+
+
+
+

3.1.5. Testing for interactions

+../../_images/sphx_glr_plot_wage_education_gender_001.png + +

Do wages increase more with education for males than females?

+
+

Tip

+

The plot above is made of two different fits. We need to formulate a +single model that tests for a variance of slope across the two +populations. This is done via an “interaction”.

+
+
>>> result = sm.ols(formula='wage ~ education + gender + education * gender',
+
... data=data).fit() +
>>> print(result.summary()) +
... +
coef std err t P>|t| [0.025 0.975] +
------------------------------------------------------------------------------ +
Intercept 0.2998 0.072 4.173 0.000 0.159 0.441 +
gender[T.male] 0.2750 0.093 2.972 0.003 0.093 0.457 +
education 0.0415 0.005 7.647 0.000 0.031 0.052 +
education:gender[T.male] -0.0134 0.007 -1.919 0.056 -0.027 0.000 +
==========================... +
... +
+
+

Can we conclude that education benefits males more than females?

+
+

+
+ +
+

+
+
+
+

3.1.6. Full code for the figures

+

Code examples for the statistics chapter.

+
+

Boxplots and paired differences

+
Boxplots and paired differences
+
+

Plotting simple quantities of a pandas dataframe

+
Plotting simple quantities of a pandas dataframe
+
+

Analysis of Iris petal and sepal sizes

+
Analysis of Iris petal and sepal sizes
+
+

Simple Regression

+
Simple Regression
+
+

Multiple Regression

+
Multiple Regression
+
+

Test for an education/gender interaction in wages

+
Test for an education/gender interaction in wages
+
+

Visualizing factors influencing wages

+
Visualizing factors influencing wages
+
+

Air fares before and after 9/11

+
Air fares before and after 9/11
+
+
+
+
+

3.1.7. Solutions to this chapter’s exercises

+
+

Relating Gender and IQ

+
Relating Gender and IQ
+
+
+ +

Gallery generated by Sphinx-Gallery

+

+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/packages/sympy.html b/packages/sympy.html new file mode 100644 index 000000000..0089ad905 --- /dev/null +++ b/packages/sympy.html @@ -0,0 +1,688 @@ + + + + + + + + 3.2. Sympy : Symbolic Mathematics in Python — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

3.2. Sympy : Symbolic Mathematics in Python

+

Author: Fabian Pedregosa

+ +

What is SymPy? SymPy is a Python library for symbolic mathematics. It +aims to be an alternative to systems such as Mathematica or Maple while keeping +the code as simple as possible and easily +extensible. SymPy is written entirely in Python and does not require any +external libraries.

+

Sympy documentation and packages for installation can be found on +https://www.sympy.org/

+ +
+

3.2.1. First Steps with SymPy

+
+

3.2.1.1. Using SymPy as a calculator

+

SymPy defines three numerical types: Real, Rational and Integer.

+

The Rational class represents a rational number as a pair of two +Integers: the numerator and the denominator, so Rational(1, 2) +represents 1/2, Rational(5, 2) 5/2 and so on:

+
>>> import sympy as sym
+
>>> a = sym.Rational(1, 2) +
+
>>> a +
1/2 +
+
>>> a*2 +
1 +
+
+

SymPy uses mpmath in the background, which makes it possible to +perform computations using arbitrary-precision arithmetic. That +way, some special constants, like e, pi, oo (Infinity), +are treated as +symbols and can be evaluated with arbitrary precision:

+
>>> sym.pi**2
+
pi**2 +
+
>>> sym.pi.evalf() +
3.14159265358979 +
+
>>> (sym.pi + sym.exp(1)).evalf() +
5.85987448204884 +
+
+

as you see, evalf evaluates the expression to a floating-point number.

+

There is also a class representing mathematical infinity, called +oo:

+
>>> sym.oo > 99999
+
True +
>>> sym.oo + 1 +
oo +
+
+ +
+
+

3.2.1.2. Symbols

+

In contrast to other Computer Algebra Systems, in SymPy you have to declare +symbolic variables explicitly:

+
>>> x = sym.Symbol('x')
+
>>> y = sym.Symbol('y') +
+
+

Then you can manipulate them:

+
>>> x + y + x - y
+
2*x +
+
>>> (x + y) ** 2 +
(x + y)**2 +
+
+

Symbols can now be manipulated using some of python operators: +, -, +*, ** (arithmetic), &, |, ~, >>, << (boolean).

+ +
+
+
+

3.2.2. Algebraic manipulations

+

SymPy is capable of performing powerful algebraic manipulations. We’ll +take a look into some of the most frequently used: expand and simplify.

+
+

3.2.2.1. Expand

+

Use this to expand an algebraic expression. It will try to denest +powers and multiplications:

+
>>> sym.expand((x + y) ** 3)
+
3 2 2 3 +
x + 3*x *y + 3*x*y + y +
>>> 3 * x * y ** 2 + 3 * y * x ** 2 + x ** 3 + y ** 3 +
3 2 2 3 +
x + 3*x *y + 3*x*y + y +
+
+

Further options can be given in form on keywords:

+
>>> sym.expand(x + y, complex=True)
+
re(x) + re(y) + I*im(x) + I*im(y) +
>>> sym.I * sym.im(x) + sym.I * sym.im(y) + sym.re(x) + sym.re(y) +
re(x) + re(y) + I*im(x) + I*im(y) +
+
>>> sym.expand(sym.cos(x + y), trig=True) +
-sin(x)*sin(y) + cos(x)*cos(y) +
>>> sym.cos(x) * sym.cos(y) - sym.sin(x) * sym.sin(y) +
-sin(x)*sin(y) + cos(x)*cos(y) +
+
+
+
+

3.2.2.2. Simplify

+

Use simplify if you would like to transform an expression into a +simpler form:

+
>>> sym.simplify((x + x * y) / x)
+
y + 1 +
+
+

Simplification is a somewhat vague term, and more precises +alternatives to simplify exists: powsimp (simplification of +exponents), trigsimp (for trigonometric expressions) , logcombine, +radsimp, together.

+ +
+
+
+

3.2.3. Calculus

+
+

3.2.3.1. Limits

+

Limits are easy to use in SymPy, they follow the syntax limit(function, +variable, point), so to compute the limit of f(x) as +x \rightarrow 0, you would issue limit(f, x, 0):

+
>>> sym.limit(sym.sin(x) / x, x, 0)
+
1 +
+
+

you can also calculate the limit at infinity:

+
>>> sym.limit(x, x, sym.oo)
+
oo +
+
>>> sym.limit(1 / x, x, sym.oo) +
0 +
+
>>> sym.limit(x ** x, x, 0) +
1 +
+
+
+
+

3.2.3.2. Differentiation

+

You can differentiate any SymPy expression using diff(func, +var). Examples:

+
>>> sym.diff(sym.sin(x), x)
+
cos(x) +
>>> sym.diff(sym.sin(2 * x), x) +
2*cos(2*x) +
+
>>> sym.diff(sym.tan(x), x) +
2 +
tan (x) + 1 +
+
+

You can check that it is correct by:

+
>>> sym.limit((sym.tan(x + y) - sym.tan(x)) / y, y, 0)
+
1 +
------- +
2 +
cos (x) +
+
+

Which is equivalent since

+
+

\sec(x) = \frac{1}{\cos(x)} and \sec^2(x) = \tan^2(x) + 1.

+

You can check this as well:

+
>>> sym.trigsimp(sym.diff(sym.tan(x), x))
+
1 +
------- +
2 +
cos (x) +
+
+

Higher derivatives can be calculated using the diff(func, var, n) method:

+
>>> sym.diff(sym.sin(2 * x), x, 1)
+
2*cos(2*x) +
+
>>> sym.diff(sym.sin(2 * x), x, 2) +
-4*sin(2*x) +
+
>>> sym.diff(sym.sin(2 * x), x, 3) +
-8*cos(2*x) +
+
+
+
+

3.2.3.3. Series expansion

+

SymPy also knows how to compute the Taylor series of an expression at +a point. Use series(expr, var):

+
>>> sym.series(sym.cos(x), x)
+
2 4 +
x x / 6\ +
1 - -- + -- + O\x / +
2 24 +
>>> sym.series(1/sym.cos(x), x) +
2 4 +
x 5*x / 6\ +
1 + -- + ---- + O\x / +
2 24 +
+
+ +
+
+

3.2.3.4. Integration

+

SymPy has support for indefinite and definite integration of transcendental +elementary and special functions via integrate() facility, which uses +the powerful extended Risch-Norman algorithm and some heuristics and pattern +matching. You can integrate elementary functions:

+
>>> sym.integrate(6 * x ** 5, x)
+
6 +
x +
>>> sym.integrate(sym.sin(x), x) +
-cos(x) +
>>> sym.integrate(sym.log(x), x) +
x*log(x) - x +
>>> sym.integrate(2 * x + sym.sinh(x), x) +
2 +
x + cosh(x) +
+
+

Also special functions are handled easily:

+
>>> sym.integrate(sym.exp(-x ** 2) * sym.erf(x), x)
+
____ 2 +
\/ pi *erf (x) +
-------------- +
4 +
+
+

It is possible to compute definite integral:

+
>>> sym.integrate(x**3, (x, -1, 1))
+
0 +
>>> sym.integrate(sym.sin(x), (x, 0, sym.pi / 2)) +
1 +
>>> sym.integrate(sym.cos(x), (x, -sym.pi / 2, sym.pi / 2)) +
2 +
+
+

Also improper integrals are supported as well:

+
>>> sym.integrate(sym.exp(-x), (x, 0, sym.oo))
+
1 +
>>> sym.integrate(sym.exp(-x ** 2), (x, -sym.oo, sym.oo)) +
____ +
\/ pi +
+
+
+
+
+

3.2.4. Equation solving

+

SymPy is able to solve algebraic equations, in one and several +variables using solveset():

+
>>> sym.solveset(x ** 4 - 1, x)
+
{-1, 1, -I, I} +
+
+

As you can see it takes as first argument an expression that is +supposed to be equaled to 0. It also has (limited) support for transcendental +equations:

+
>>> sym.solveset(sym.exp(x) + 1, x)
+
{I*(2*n*pi + pi) | n in Integers} +
+
+ +

Another alternative in the case of polynomial equations is +factor. factor returns the polynomial factorized into irreducible +terms, and is capable of computing the factorization over various +domains:

+
>>> f = x ** 4 - 3 * x ** 2 + 1
+
>>> sym.factor(f) +
/ 2 \ / 2 \ +
\x - x - 1/*\x + x - 1/ +
+
>>> sym.factor(f, modulus=5) +
2 2 +
(x - 2) *(x + 2) +
+
+

SymPy is also able to solve boolean equations, that is, to decide if a +certain boolean expression is satisfiable or not. For this, we use the +function satisfiable:

+
>>> sym.satisfiable(x & y)
+
{x: True, y: True} +
+
+

This tells us that (x & y) is True whenever x and y are both True. +If an expression cannot be true, i.e. no values of its arguments can make +the expression True, it will return False:

+
>>> sym.satisfiable(x & ~x)
+
False +
+
+ +
+
+

3.2.5. Linear Algebra

+
+

3.2.5.1. Matrices

+

Matrices are created as instances from the Matrix class:

+
>>> sym.Matrix([[1, 0], [0, 1]])
+
[1 0] +
[ ] +
[0 1] +
+
+

unlike a NumPy array, you can also put Symbols in it:

+
>>> x, y = sym.symbols('x, y')
+
>>> A = sym.Matrix([[1, x], [y, 1]]) +
>>> A +
[1 x] +
[ ] +
[y 1] +
+
>>> A**2 +
[x*y + 1 2*x ] +
[ ] +
[ 2*y x*y + 1] +
+
+
+
+

3.2.5.2. Differential Equations

+

SymPy is capable of solving (some) Ordinary Differential. +To solve differential equations, use dsolve. First, create +an undefined function by passing cls=Function to the symbols function:

+
>>> f, g = sym.symbols('f g', cls=sym.Function)
+
+
+

f and g are now undefined functions. We can call f(x), and it will represent +an unknown function:

+
>>> f(x)
+
f(x) +
+
>>> f(x).diff(x, x) + f(x) +
2 +
d +
f(x) + ---(f(x)) +
2 +
dx +
+
>>> sym.dsolve(f(x).diff(x, x) + f(x), f(x)) +
f(x) = C1*sin(x) + C2*cos(x) +
+
+

Keyword arguments can be given to this function in order to help if +find the best possible resolution system. For example, if you know +that it is a separable equations, you can use keyword hint='separable' +to force dsolve to resolve it as a separable equation:

+
>>> sym.dsolve(sym.sin(x) * sym.cos(f(x)) + sym.cos(x) * sym.sin(f(x)) * f(x).diff(x), f(x), hint='separable')
+
/ C1 \ / C1 \ +
[f(x) = - acos|------| + 2*pi, f(x) = acos|------|] +
\cos(x)/ \cos(x)/ +
+
+ +

+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/preface.html b/preface.html new file mode 100644 index 000000000..b315293d9 --- /dev/null +++ b/preface.html @@ -0,0 +1,776 @@ + + + + + + + + About the Scientific Python Lectures — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

About the Scientific Python Lectures

+ +

Release: 2024.2rc0.dev0

+https://zenodo.org/badge/doi/10.5281/zenodo.594102.svg + +
+

Authors

+
+

Editors

+
    +
  • Gaël Varoquaux

  • +
  • Emmanuelle Gouillart

  • +
  • Olav Vahtras

  • +
  • Pierre de Buyl

  • +
  • K. Jarrod Millman

  • +
  • Stéfan van der Walt

  • +
+
+
+

Chapter authors

+

Listed by alphabetical order.

+
    +
  • Christopher Burns

  • +
  • Adrian Chauve

  • +
  • Robert Cimrman

  • +
  • Christophe Combelles

  • +
  • André Espaze

  • +
  • Emmanuelle Gouillart

  • +
  • Mike Müller

  • +
  • Fabian Pedregosa

  • +
  • Didrik Pinte

  • +
  • Nicolas Rougier

  • +
  • Gaël Varoquaux

  • +
  • Pauli Virtanen

  • +
  • Zbigniew Jędrzejewski-Szmek

  • +
  • Valentin Haenel (editor from 2011 to 2015)

  • +
+
+
+

Additional Contributions

+

Listed by alphabetical order

+
    +
  • Osayd Abdu

  • +
  • arunpersaud

  • +
  • Ross Barnowski

  • +
  • Sebastian Berg

  • +
  • Lilian Besson

  • +
  • Matthieu Boileau

  • +
  • Joris Van den Bossche

  • +
  • Michael Boyle

  • +
  • Matthew Brett

  • +
  • BSGalvan

  • +
  • Lars Buitinck

  • +
  • Pierre de Buyl

  • +
  • Ozan Çağlayan

  • +
  • Lawrence Chan

  • +
  • Adrien Chauve

  • +
  • Robert Cimrman

  • +
  • Christophe Combelles

  • +
  • David Cournapeau

  • +
  • Dave

  • +
  • dogacan dugmeci

  • +
  • Török Edwin

  • +
  • egens

  • +
  • Andre Espaze

  • +
  • André Espaze

  • +
  • Loïc Estève

  • +
  • Corey Farwell

  • +
  • Tim Gates

  • +
  • Stuart Geiger

  • +
  • Olivier Georg

  • +
  • Daniel Gerigk

  • +
  • Robert Gieseke

  • +
  • Philip Gillißen

  • +
  • Ralf Gommers

  • +
  • Emmanuelle Gouillart

  • +
  • Julia Gustavsen

  • +
  • Omar Gutiérrez

  • +
  • Matt Haberland

  • +
  • Valentin Haenel

  • +
  • Pierre Haessig

  • +
  • Bruno Hanzen

  • +
  • Michael Hartmann

  • +
  • Jonathan Helmus

  • +
  • Andreas Hilboll

  • +
  • Himanshu

  • +
  • Julian Hofer

  • +
  • Tim Hoffmann

  • +
  • B. Hohl

  • +
  • Tarek Hoteit

  • +
  • Gert-Ludwig Ingold

  • +
  • Zbigniew Jędrzejewski-Szmek

  • +
  • Thouis (Ray) Jones

  • +
  • jorgeprietoarranz

  • +
  • josephsalmon

  • +
  • Greg Kiar

  • +
  • kikocorreoso

  • +
  • Vince Knight

  • +
  • LFP6

  • +
  • Manuel López-Ibáñez

  • +
  • Marco Mangan

  • +
  • Nicola Masarone

  • +
  • John McLaughlin

  • +
  • mhemantha

  • +
  • michelemaroni89

  • +
  • K. Jarrod Millman

  • +
  • Mohammad

  • +
  • Zachary Moon

  • +
  • Mike Mueller

  • +
  • negm

  • +
  • John B Nelson

  • +
  • nicoguaro

  • +
  • Sergio Oller

  • +
  • Theofilos Papapanagiotou

  • +
  • patniharshit

  • +
  • Fabian Pedregosa

  • +
  • Philippe Pepiot

  • +
  • Tiago M. D. Pereira

  • +
  • Nicolas Pettiaux

  • +
  • Didrik Pinte

  • +
  • Evgeny Pogrebnyak

  • +
  • reverland

  • +
  • Maximilien Riehl

  • +
  • Kristian Rother

  • +
  • Nicolas P. Rougier

  • +
  • Pamphile Roy

  • +
  • Rutzmoser

  • +
  • Sander

  • +
  • João Felipe Santos

  • +
  • Mark Setchell

  • +
  • Helen Sherwood-Taylor

  • +
  • Shoeboxam

  • +
  • Simon

  • +
  • solarjoe

  • +
  • ssmiller

  • +
  • Scott Staniewicz

  • +
  • strpeter

  • +
  • surfer190

  • +
  • Bartosz Telenczuk

  • +
  • tommyod

  • +
  • Wes Turner

  • +
  • Akihiro Uchida

  • +
  • Utkarsh Upadhyay

  • +
  • Olav Vahtras

  • +
  • Stéfan van der Walt

  • +
  • Gaël Varoquaux

  • +
  • Nelle Varoquaux

  • +
  • Olivier Verdier

  • +
  • VirgileFritsch

  • +
  • Pauli Virtanen

  • +
  • Yosh Wakeham

  • +
  • yasutomo57jp

  • +
+
+
+
+

What’s new

+
+

Release 2024.1 (April 2024)

+
    +
  • Python 3.10, 3.11, 3.12

  • +
  • Renamed Scientific Python Lectures

  • +
  • Removed old content

  • +
  • Major updates to support recent packages

  • +
  • Updates to the SciPy and scikit-image chapters

  • +
+
+
+

Release 2022.1 (August 2022)

+
    +
  • Replace scikit-learn housing example with California data (Marco Mangan)

  • +
  • Fix links and typos (Zachary Moon, Tim Gates, Marco Mangan, Gert-Ludwig Ingold)

  • +
  • Fix fftpack figure (Osayd Abdu)

  • +
  • Update software version (Pierre de Buyl)

  • +
+
+
+

Release 2020.2 (September 2020)

+
    +
  • Replace image i/o from scipy.misc by imageio (Pierre de Buyl)

  • +
  • Update information on dict ordering (Bharath Saiguhan)

  • +
  • Suppress warnings for mandelbrot example (Pierre de Buyl)

  • +
  • Update NumPy introduction and advanced usage for changes to NumPy: wording, bytes +representation, floating point argument to np.zeros (Ross Barnowski)

  • +
  • Fix links to NumPy documentation to use numpy.org (Ross Barnowski)

  • +
  • Update note on transposed arrays (Ross Barnowski with Eric Wieser)

  • +
  • Use generated figure file for lidar data processing (Lawrence Chan)

  • +
  • Update link from PyMC2 to PyMC3 (B. Hohl)

  • +
  • Fix transparent popup menu to have a background (Pierre de Buyl)

  • +
+
+
+

Release 2020.1 (March 2020)

+
    +
  • Fix outdated URLs (Gert-Ludwig Ingold)

  • +
  • Update packages (Pierre de Buyl)

  • +
  • Remove Python 2 continuous integration (Olav Vahtras - EuroSciPy 2019 sprint)

  • +
  • Fix chessboard size (Mark Setchell)

  • +
  • Add objectives and design choices (Gert-Ludwig Ingold and Pierre de Buyl)

  • +
  • Make the numpy advanced iterator example more elaborate (Sebastian Berg)

  • +
  • Use empty list instead of empty tuple to deactivate ticks (Tim Hoffmann)

  • +
  • Fix typos (Sander van Rijn, cydave, Michel Corne) and off by 2 errors +(Andreas Hilboll)

  • +
  • Improve readability of Polynomials example code (Michel Corne)

  • +
  • Replace suggestions for debugging environments (Gert-Ludwig Ingold)

  • +
  • Add section on Python 2 vs Python 3 (Pierre de Buyl)

  • +
+
+
+

Release 2019.1 (May 2019)

+
    +
  • Update matplotlib compatibility to version 2.2 (Mike Mueller, Joris Van den +Bossche, Pierre de Buyl)

  • +
  • Make C-API example cos_module_np Python 2/3 compatible (Michael Boyle)

  • +
  • Fix typos and outdated URLs (Dogacan Dugmeci, Matthieu Boileau, Stuart Geiger, Omar +Gutiérrez, Himanshu, Julian Hofer, Joseph Salmon, Manuel López-Ibáñez, +Nicola Masarone, michelemaroni89, Evgeny Pogrebnyak, tommyod)

  • +
+
+
+

Release 2018.1 (September 2018)

+
    +
  • Fix wordings, typos, colours (Pierre de Buyl, Greg Kiar, Olav Vahtras +Kristian Rother)

  • +
  • Fix interpolation example code (Scott Staniewicz)

  • +
  • Fix CSS for high density displays (Gaël Varoquaux)

  • +
  • Generate indexing figures with PyX (Gert Ingold)

  • +
  • Warn clearly against the use of Python 2 (Bruno Hanzen)

  • +
  • Update external links (Bruno Hanzen)

  • +
  • Update versions of dependencies: sphinx-gallery, pandas, statsmodels +(Gaël Varoquaux)

  • +
+
+
+

Release 2017.1 (October 2017)

+
    +
  • Update optimization chapter (Michael Hartmann, Gaël Varoquaux)

  • +
  • Update SymPy chapter (Vince Knight)

  • +
  • Update advanced NumPy (Bartosz Teleńczuk)

  • +
  • Update scikit-learn chapter (Gaël Varoquaux)

  • +
  • Update SciPy chapter (Gaël Varoquaux)

  • +
  • Make ‘>>>’ in the prompts unselectable (Pierre de Buyl)

  • +
  • Use common package requirements for pip and conda and improve the build +instructions (Gert-Ludwig Ingold, Vince Knight, Pierre de Buyl)

  • +
  • Set up Circle CI (Loïc Estève)

  • +
  • Improved support for Python 3 integer divisions and calls to print (Loïc +Estève, Gert-Ludwig Ingold, Pierre de Buyl, Gaël Varoquaux)

  • +
  • Change test runner to pytest (Pierre de Buyl)

  • +
  • Replace the plot directive by sphinx-gallery (Gert-Ludwig Ingold)

  • +
+
+
+

Release 2016.1 (September 2016)

+
    +
  • Rework of intro chapter (Gaël Varoquaux)

  • +
  • Integrate sphinx-gallery: examples are now Jupyter notebooks (Gaël +Varoquaux, Gert-Ludwig Ingold, Óscar Nájera)

  • +
  • Better Python 3 tests and support (Gert-Ludwig Ingold)

  • +
  • Adapt examples to Matplotlib 1.5 (Gaël Varoquaux)

  • +
  • Modernize numpy chapter (Bartosz Telenczuk)

  • +
+
+
+

Release 2015.3 (November 2015)

+
    +
  • Collapsed sidebar can now pop up for mid-sized display (Gaël Varoquaux)

  • +
  • Replaced pictures of Lena by raccoon face (Thouis Jones)

  • +
+
+
+

Release 2015.2 (October 2015)

+
    +
  • Authors on cover ordered as in bibtex entry (Nicolas Rougier)

  • +
  • Better rendering on mobile (Gaël Varoquaux)

  • +
  • Fix restructured text markup errors (Olav Vahtras)

  • +
+
+
+

Release 2015.1 (September 2015)

+
    +
  • New chapter on statistics with Python (Gaël Varoquaux)

  • +
  • Better layout in PDF (Gaël Varoquaux)

  • +
  • New HTML layout, simplified formatting, mobile-friendly and sidebar +(Gaël Varoquaux, Nelle Varoquaux)

  • +
  • Logos on the HTML front page and on the PDF cover (Nicolas Rougier)

  • +
  • Python 3 compatible code (Gaël Varoquaux, Olav Vahtras)

  • +
  • Code put up to date for more recent versions of project (Pierre de +Buyl, Emmanuelle Gouillart, Gert-Ludwig Ingold, Nicolas Pettiaux, Olav +Vahtras, Gaël Varoquaux, Nelle Varoquaux)

  • +
  • Matplotlib updated with removal of deprecated pylab interface (Nicolas +Rougier)

  • +
+
+
+

Release 2013.2 (21 August 2013)

+
    +
  • NumPy chapter simplified (Valentin Haenel)

  • +
  • New layout for the HTML rendering (Gaël Varoquaux)

  • +
+
+
+

Release 2013.1 (10 Feb 2013)

+
    +
  • Improvements to the advanced image manipulation chapter (Emmanuelle Gouillart)

  • +
  • Upgrade of the introductory language chapter (Valentin Haenel)

  • +
  • Upgrade of the introductory numpy chapter (Valentin Haenel)

  • +
  • New advanced chapter on interfacing with C (Valentin Haenel)

  • +
  • Minor fixes and improvements in various places (Robert Gieseke, Ozan Çağlayan, +Sergio Oller, kikocorreo, Valentin Haenel)

  • +
+
+
+

Release 2012.3 (26 Nov 2012)

+

This release integrates the changes written for the Euroscipy conference:

+
    +
  • Matplotlib chapter completely redone (Nicolas Rougier, Gaël Varoquaux)

  • +
  • New advanced chapter on mathematical optimization (Gaël Varoquaux)

  • +
  • Mayavi chapter redone (Gaël Varoquaux)

  • +
  • Front page layout slightly improved: folding TOC (Gaël Varoquaux)

  • +
+
+
+

Release 2012.2 (22 Jun 2012)

+

Minor release with a few clean ups (Gael Varoquaux).

+
+
+

Release 2012.1 (20 Jun 2012)

+

This is a minor release with many clean ups. In particular, clean up of +the layout (Gael Varoquaux), shortening of the numpy chapters and +deduplications across the intro and advanced chapters (Gael Varoquaux) +and doctesting of all the code (Gael Varoquaux).

+
+
+

Release 2012.0 (22 Apr 2012)

+

This is a minor release with a few clean ups. In particular, clean up the +scikit-learn chapter (Lars Buitinck), more informative section titles +(Gael Varoquaux), and misc fixes (Valentin Haenel, Virgile Fritsch).

+
+
+

Release 2011.1 (16 Oct 2011)

+

This release is a reworked version of the Euroscipy 2011 tutorial. Layout +has been cleaned and optimized (Valentin Haenel and many others), the Traits +chapter has been merged in (Didrik Pinte)

+
+
+

Release 2011 (1 Sept 2011)

+

This release is used for the Euroscipy 2011 tutorial. The numpy +introductory chapter has been rewamped (Pauli Virtanen). The outline of +the introductory chapters has been simplified (Gaël Varoquaux). Advanced +chapters have been added: advanced Python constructs (Zbigniew +Jędrzejewski-Szmek), debugging code (Gaël Varoquaux), optimizing code +(Gaël Varoquaux), image processing (Emmanuelle Gouillart), scikit-learn +(Fabian Pedregosa).

+
+
+
+

License

+

All code and material is licensed under a

+

Creative Commons Attribution 4.0 International License (CC-by)

+

https://creativecommons.org/licenses/by/4.0/

+

See the AUTHORS.rst file for a list of contributors.

+
+
+

Contributing

+

The Scientific Python Lectures are a community-based effort and require +constant maintenance and improvements. New contributions such as wording +improvements or inclusion of new topics are welcome.

+

To propose bugfixes or straightforward improvements to the lectures, see the +contribution guide below.

+

For new topics, read the objectives first and open an issue on the GitHub +project to +discuss it with the editors.

+
+

Objectives and design choices for the lectures

+

Contributors should keep the following objectives and design choices of +the Scientific Python Lectures in mind.

+

Objectives:

+
    +
  • Provide a self-contained introduction to Python and its primary computational +packages, the ”Scientific Python stack“.

  • +
  • Provide tutorials for a selection of widely-used and stable computational +libraries. +Currently, we cover pandas, statmodels, seaborn, scikit-image, +scikit-learn, and sympy.

  • +
  • Automated testing is applied to the code examples as much as possible.

  • +
+

Design choices:

+
    +
  • Each chapter should provide a useful basis for a 1‒2 h tutorial.

  • +
  • The code should be readable.

  • +
  • An idomatic style should be followed, e.g. import numpy as np, +preference for array operations, PEP8 coding conventions.

  • +
+
+
+

Contributing guide

+

The directory guide contains instructions on how to contribute:

+ +
+
+

Building instructions

+

To generate the html output for on-screen display, Type:

+
make html
+
+
+

the generated html files can be found in build/html

+

The first build takes a long time, but information is cached and +subsequent builds will be faster.

+

To generate the pdf file for printing:

+
make pdf
+
+
+

The pdf builder is a bit difficult and you might have some TeX errors. +Tweaking the layout in the *.rst files is usually enough to work +around these problems.

+
+

Requirements

+

Build requirements are listed in the +requirements file:

+
numpy==2.1.1
+
scipy==1.14.1 +
matplotlib==3.9.2 +
pandas==2.2.3 +
patsy==0.5.6 +
pyarrow==17.0.0 +
scikit-learn==1.5.2 +
scikit-image==0.24.0 +
sympy==1.13.3 +
statsmodels==0.14.3 +
seaborn==0.13.2 +
pytest>=8.2 +
sphinx>=8.0 +
sphinx-gallery>=0.17 +
sphinx-copybutton +
coverage>=7.5 +
Pillow +
pooch +
ipython +
pickleshare +
pre-commit==4.0 +
requests +
sphinxcontrib-jquery +
+
+

Ensure that you have a virtual environment or conda environment +set up, then install requirements with:

+
pip install -r requirements.txt
+
+
+

Note that you will also need the following system packages:

+
+
    +
  • Python C development headers (the python3-dev package on Debian, e.g.),

  • +
  • a C compiler like gcc,

  • +
  • GNU Make,

  • +
  • a full LaTeX distribution such as TeX Live (texlive-latex-base, +texlive-latex-extra, texlive-fonts-extra, and latexmk +on Debian/Ubuntu),

  • +
  • dvipng,

  • +
  • latexmk,

  • +
  • git.

  • +
+
+
+
+

Updating the cover

+

Use inkscape to modify the cover in images/, then export to PDF:

+
inkscape --export-filename=cover-2024.pdf cover-2024.svg
+
+
+

Ensure that the images/cover.pdf symlink points to the correct +file.

+

+
+
+
+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/search.html b/search.html new file mode 100644 index 000000000..fa32bc45b --- /dev/null +++ b/search.html @@ -0,0 +1,184 @@ + + + + + + + Search — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +

Search

+ + + + +

+ Searching for multiple words only shows matches that contain + all words. +

+ + +
+ + + +
+ + +
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/searchindex.js b/searchindex.js new file mode 100644 index 000000000..a45b005e5 --- /dev/null +++ b/searchindex.js @@ -0,0 +1 @@ +Search.setIndex({"alltitles": {"1D plotting": [[161, null]], "2D plotting": [[162, null]], "3D Plots": [[157, "d-plots"]], "3D images": [[231, null]], "3D plotting": [[131, null], [132, null]], "3D plotting vignette": [[149, null]], "A 2D image plot of the function": [[177, "a-2d-image-plot-of-the-function"]], "A 3D surface plot of the function": [[177, "a-3d-surface-plot-of-the-function"]], "A Few Notes on Preconditioning": [[65, "a-few-notes-on-preconditioning"]], "A Note on Facial Recognition": [[238, "a-note-on-facial-recognition"]], "A Simple Example: the Iris Dataset": [[251, "a-simple-example-the-iris-dataset"]], "A correct approach: Using a validation set": [[251, "a-correct-approach-using-a-validation-set"]], "A demo of 1D interpolation": [[184, null]], "A example of plotting not quite right": [[140, null]], "A function to do it: scipy.signal.fftconvolve()": [[198, "a-function-to-do-it-scipy-signal-fftconvolve"]], "A last word of caution: separate validation and test set": [[251, "a-last-word-of-caution-separate-validation-and-test-set"]], "A plugin registration system": [[9, "a-plugin-registration-system"]], "A quick look at the data": [[251, "a-quick-look-at-the-data"]], "A quick test on the K-neighbors classifier": [[251, "a-quick-test-on-the-k-neighbors-classifier"]], "A recap on Scikit-learn\u2019s estimator interface": [[251, "a-recap-on-scikit-learn-s-estimator-interface"]], "A review of the different optimizers": [[53, "a-review-of-the-different-optimizers"]], "A shooting method: the Powell algorithm": [[53, "a-shooting-method-the-powell-algorithm"]], "A simple example": [[68, null]], "A simple linear regression": [[242, null], [265, "a-simple-linear-regression"]], "A simple plotting example": [[121, null]], "A simple regression analysis on the California housing data": [[235, null]], "A simple, good-looking plot": [[124, null]], "A type-as-go spell-checker like integration": [[10, "a-type-as-go-spell-checker-like-integration"]], "A while-loop removing decorator": [[9, "a-while-loop-removing-decorator"]], "About the Scientific Python Lectures": [[267, null]], "Acknowledgements": [[251, null]], "Adaptive step gradient descent": [[53, "id8"]], "Adding a dimension": [[175, "adding-a-dimension"]], "Adding a legend": [[157, "adding-a-legend"]], "Additional Contributions": [[0, "additional-contributions"], [267, "additional-contributions"]], "Additional Links": [[54, "additional-links"]], "Admonitions": [[70, "admonitions"]], "Advanced NumPy": [[8, null]], "Advanced Python Constructs": [[9, null]], "Advanced iteration": [[78, "advanced-iteration"]], "Advanced operations": [[158, null]], "Advanced topics": [[38, null]], "Affine transform": [[224, null]], "Air fares before and after 9/11": [[253, null]], "Algebraic manipulations": [[266, "algebraic-manipulations"]], "Algorithmic optimization": [[54, "algorithmic-optimization"]], "Aliased versus anti-aliased": [[101, null], [103, null]], "Alpha: transparency": [[102, null]], "Alternating optimization": [[47, null]], "Analysis of Iris petal and sepal sizes": [[254, null]], "Annotate some points": [[157, "annotate-some-points"]], "Array interface protocol": [[8, "array-interface-protocol"]], "Array manipulations": [[172, "array-manipulations"]], "Array shape manipulation": [[175, "array-shape-manipulation"]], "Array siblings: chararray, maskedarray": [[8, "array-siblings-chararray-maskedarray"]], "Assignment operator": [[77, "assignment-operator"]], "Authors": [[0, null], [267, "authors"]], "Automatically Performing Grid Search": [[251, "automatically-performing-grid-search"]], "Avoiding bugs": [[10, "avoiding-bugs"]], "Axes": [[120, null], [157, "axes"]], "Bar Plots": [[157, "bar-plots"]], "Bar plot advanced": [[142, null]], "Bar plots": [[122, null]], "Basic Hyperparameter Optimization": [[251, "basic-hyperparameter-optimization"]], "Basic data types": [[159, "basic-data-types"]], "Basic manipulations": [[37, "basic-manipulations"]], "Basic operations": [[175, "basic-operations"]], "Basic principles of machine learning with scikit-learn": [[251, "basic-principles-of-machine-learning-with-scikit-learn"]], "Basic reductions": [[175, "basic-reductions"]], "Basic types": [[77, null]], "Basic visualization": [[159, "basic-visualization"]], "Before starting: Installing a working environment": [[76, "before-starting-installing-a-working-environment"]], "Beyond this tutorial": [[157, "beyond-this-tutorial"]], "Bias and variance of polynomial fit": [[234, null]], "Bias-variance trade-off: illustration on a simple regression problem": [[251, "bias-variance-trade-off-illustration-on-a-simple-regression-problem"]], "Bidirectional communication": [[9, "bidirectional-communication"]], "Binary segmentation: foreground + background": [[231, "binary-segmentation-foreground-background"]], "Block Compressed Row Format (BSR)": [[55, null]], "Block of memory": [[8, "block-of-memory"]], "Blurring of images": [[14, null]], "Blurring/smoothing": [[37, "blurring-smoothing"]], "Box bounds": [[53, "box-bounds"]], "Boxplot with matplotlib": [[143, null]], "Boxplots and paired differences": [[255, null]], "Brent\u2019s method": [[41, null]], "Brent\u2019s method on a non-convex function: note that\n the fact that the optimizer avoided the local minimum\n is a matter of luck.": [[53, "id6"]], "Brent\u2019s method on a quadratic function: it\n converges in 3 iterations, as the quadratic\n approximation is then exact.": [[53, "id5"]], "Brian Kernighan": [[10, null]], "Broadcasting": [[8, "broadcasting"], [175, "broadcasting"]], "Brute force: a grid search": [[53, "brute-force-a-grid-search"]], "Building instructions": [[2, "building-instructions"], [267, "building-instructions"]], "Built-in Hyperparameter Search": [[251, "built-in-hyperparameter-search"]], "C and Fortran order": [[8, "c-and-fortran-order"]], "CPU cache effects": [[8, "cpu-cache-effects"]], "Calculus": [[266, "calculus"]], "Casting": [[8, "casting"], [171, "casting"]], "Casting and re-interpretation/views": [[8, "casting-and-re-interpretation-views"]], "Catching exceptions": [[9, "catching-exceptions"], [79, "catching-exceptions"]], "Categorical variables: comparing groups or multiple categories": [[265, "categorical-variables-comparing-groups-or-multiple-categories"]], "Chaining generators": [[9, "chaining-generators"]], "Changing colors and line widths": [[157, "changing-colors-and-line-widths"]], "Chapter authors": [[0, "chapter-authors"], [267, "chapter-authors"]], "Chapter contents": [[8, "chapter-contents"], [9, "chapter-contents"], [10, "chapter-contents"], [157, "chapter-contents"]], "Chapter, section, subsection, paragraph": [[70, "chapter-section-subsection-paragraph"]], "Chapters contents": [[37, "chapters-contents"], [39, "chapters-contents"], [53, "chapters-contents"], [54, "chapters-contents"], [70, "chapters-contents"], [202, "chapters-contents"], [231, "chapters-contents"], [251, "chapters-contents"], [266, "chapters-contents"]], "Choosing a method": [[53, "choosing-a-method"]], "Classify with Gaussian naive Bayes": [[237, "classify-with-gaussian-naive-bayes"]], "Cleaning segmentation with mathematical morphology": [[15, null]], "Clearing floats": [[70, "clearing-floats"]], "Code and notebook": [[251, null], [251, null], [251, null]], "Code documentation": [[157, "code-documentation"]], "Code for the chapter\u2019s exercises": [[87, null], [99, "code-for-the-chapter-s-exercises"], [157, "code-for-the-chapter-s-exercises"]], "Code generating the summary figures with a title": [[99, "code-generating-the-summary-figures-with-a-title"], [141, null], [157, "code-generating-the-summary-figures-with-a-title"]], "Code samples for Matplotlib": [[99, null], [157, "code-samples-for-matplotlib"]], "Coding best practices to avoid getting in trouble": [[10, "coding-best-practices-to-avoid-getting-in-trouble"]], "Colormaps": [[105, null], [157, "colormaps"]], "Colorspaces": [[231, "colorspaces"]], "Common Methods": [[66, "common-methods"]], "Common Parameters": [[65, "common-parameters"]], "Compare classifiers on the digits data": [[236, null]], "Comparing 2 sets of samples from Gaussians": [[193, null]], "Compiled languages: C, C++, Fortran\u2026": [[76, "compiled-languages-c-c-fortran"]], "Compressed Sparse Column Format (CSC)": [[57, null]], "Compressed Sparse Row Format (CSR)": [[58, null]], "Computation times": [[7, null], [36, null], [52, null], [69, null], [98, null], [118, null], [155, null], [156, null], [170, null], [194, null], [200, null], [213, null], [230, null], [250, null], [261, null], [264, null], [268, null]], "Computational linear algebra": [[54, null]], "Compute and plot the power": [[181, "compute-and-plot-the-power"]], "Compute and plot the power spectral density (PSD)": [[192, "compute-and-plot-the-power-spectral-density-psd"]], "Compute and plot the spectrogram": [[192, "compute-and-plot-the-spectrogram"]], "Compute the 2d FFT of the input image": [[197, "compute-the-2d-fft-of-the-input-image"]], "Computing gradients": [[53, "computing-gradients"]], "Computing horizontal gradients with the Sobel filter": [[228, null]], "Computing sums": [[175, "computing-sums"]], "Computing the cumulative probabilities": [[216, "computing-the-cumulative-probabilities"]], "Conditional Expressions": [[78, "conditional-expressions"]], "Conjugate gradient descent": [[53, "conjugate-gradient-descent"], [53, "id9"]], "Connected components and measurements on images": [[201, "connected-components-and-measurements-on-images"], [202, "connected-components-and-measurements-on-images"]], "Constraint optimization: visualizing the geometry": [[43, null]], "Constraints": [[53, "constraints"]], "Containers": [[77, "containers"]], "Contents": [[265, "contents"]], "Context managers": [[9, "context-managers"]], "Contour Plots": [[157, "contour-plots"]], "Contributing": [[2, null], [267, "contributing"]], "Contributing features": [[8, "contributing-features"]], "Contributing guide": [[2, "contributing-guide"], [267, "contributing-guide"]], "Contributing to NumPy/SciPy": [[8, "contributing-to-numpy-scipy"]], "Contributing to documentation": [[8, "contributing-to-documentation"]], "Control Flow": [[78, null]], "Convex function": [[44, null]], "Convex versus non-convex optimization": [[53, "convex-versus-non-convex-optimization"]], "Coordinate Format (COO)": [[56, null]], "Copies and views": [[159, "copies-and-views"]], "Copying the docstring and other attributes of the original function": [[9, "copying-the-docstring-and-other-attributes-of-the-original-function"]], "Creating an image": [[222, null]], "Creating arrays": [[159, "creating-arrays"]], "Creating dataframes: reading data files or converting arrays": [[265, "creating-dataframes-reading-data-files-or-converting-arrays"]], "Creating modules": [[85, "creating-modules"]], "Cross-validation": [[251, "cross-validation"]], "Crude integral approximations": [[172, "crude-integral-approximations"]], "Crude periodicity finding": [[199, null]], "Ctypes": [[39, "id3"], [39, "id13"]], "Cumulative wind speed prediction": [[206, null]], "Curve fitting": [[45, null], [53, "curve-fitting"], [179, null], [202, "curve-fitting"]], "Curve fitting: temperature as a function of month of the year": [[196, null]], "Cython": [[39, "cython"], [39, "id15"]], "Dash capstyle": [[106, null]], "Dash join style": [[107, null]], "Data as a table": [[265, "data-as-a-table"]], "Data in scikit-learn": [[251, "data-in-scikit-learn"]], "Data representation and interaction": [[265, "data-representation-and-interaction"]], "Data statistics": [[172, "data-statistics"]], "Data types": [[8, "data-types"], [231, "data-types"]], "Data visualization and interaction": [[231, "data-visualization-and-interaction"]], "Debugger commands and interaction": [[10, "debugger-commands-and-interaction"]], "Debugging code": [[10, null]], "Debugging segmentation faults using gdb": [[10, "debugging-segmentation-faults-using-gdb"]], "Debugging workflow": [[10, "debugging-workflow"]], "Decorators": [[9, "decorators"]], "Decorators implemented as classes and as functions": [[9, "decorators-implemented-as-classes-and-as-functions"]], "Define the function": [[188, "define-the-function"]], "Defining functions": [[81, null]], "Demo PCA in 2D": [[244, null]], "Demo connected components": [[178, null]], "Demo mathematical morphology": [[185, null]], "Demo text printing": [[139, null]], "Denoising": [[37, "denoising"]], "Denoising an image with the median filter": [[16, null]], "Deprecation of functions": [[9, "deprecation-of-functions"]], "Detrending a signal": [[180, null]], "Devil is in the details": [[157, "devil-is-in-the-details"]], "Diagonal Format (DIA)": [[59, null]], "Dictionaries": [[77, "dictionaries"]], "Dictionary of Keys Format (DOK)": [[60, null]], "Different data type sizes": [[171, "different-data-type-sizes"]], "Differential Equations": [[266, "differential-equations"]], "Differentiation": [[266, "differentiation"]], "Dimension shuffling": [[175, "dimension-shuffling"]], "Dimensionality Reduction: PCA": [[251, "dimensionality-reduction-pca"]], "Dimensionality of the problem": [[53, null]], "Directory and file manipulation": [[86, "directory-and-file-manipulation"]], "Discovering methods:": [[77, null]], "Display a Raccoon Face": [[17, null]], "Display the contours of a function": [[144, null]], "Displaying a Raccoon Face": [[18, null]], "Displaying a simple image": [[220, null]], "Displaying images": [[37, "displaying-images"]], "Displaying the contours of a function": [[123, null]], "Distances exercise": [[164, null]], "Distribution objects and frozen distributions": [[202, null]], "Docstrings": [[81, "docstrings"]], "Doing the Learning: Support Vector Machines": [[238, "doing-the-learning-support-vector-machines"]], "Domain-aware functions": [[8, "domain-aware-functions"]], "Donald Knuth": [[54, null]], "Download": [[73, null]], "Earlier scikit-image versions": [[231, null]], "Easier and better: scipy.ndimage.gaussian_filter()": [[197, "easier-and-better-scipy-ndimage-gaussian-filter"]], "Easier to ask for forgiveness than for permission": [[79, "easier-to-ask-for-forgiveness-than-for-permission"]], "Edge detection": [[37, "edge-detection"]], "Editors": [[0, "editors"], [267, "editors"]], "Eigenvalue Problem Solvers": [[65, "eigenvalue-problem-solvers"]], "Elaboration of the work in an editor": [[76, "elaboration-of-the-work-in-an-editor"]], "Elementwise operations": [[175, "elementwise-operations"]], "Environment variables:": [[86, "environment-variables"]], "Equalizing the histogram of an image": [[223, null]], "Equation solving": [[266, "equation-solving"]], "Example": [[39, "example"], [39, "id5"], [39, "id8"], [39, "id10"]], "Example chapter": [[2, null], [267, null]], "Example data": [[231, "example-data"]], "Example demoing choices for an option": [[99, "example-demoing-choices-for-an-option"], [100, null], [157, "example-demoing-choices-for-an-option"]], "Example of filters comparison: image denoising": [[231, null]], "Example of linear and non-linear models": [[247, null]], "Example of solution for the image processing exercise: unmolten grains in glass": [[204, null]], "Example of the SVD": [[54, "example-of-the-svd"]], "Example:": [[70, null]], "Example: Masked statistics": [[6, null], [8, null]], "Example: fake dimensions with strides": [[8, "example-fake-dimensions-with-strides"]], "Example: reading .wav files": [[8, "example-reading-wav-files"]], "Examples": [[55, "examples"], [56, "examples"], [57, "examples"], [58, "examples"], [59, "examples"], [60, "examples"], [63, "examples"], [65, "examples"]], "Examples for the advanced NumPy chapter": [[5, null]], "Examples for the contribution guide": [[67, null]], "Examples for the image processing chapter": [[11, null], [37, "examples-for-the-image-processing-chapter"]], "Examples for the mathematical optimization chapter": [[40, null], [53, "examples-for-the-mathematical-optimization-chapter"], [53, "id3"]], "Examples for the scikit-image chapter": [[218, null], [231, "examples-for-the-scikit-image-chapter"]], "Examples for the scikit-learn chapter": [[232, null], [251, "examples-for-the-scikit-learn-chapter"]], "Examples for the summary excercices": [[205, null]], "Examples in the standard library": [[9, "examples-in-the-standard-library"]], "Exception handling in Python": [[79, null]], "Exceptions": [[79, "exceptions"]], "Exercise": [[8, null], [37, null], [37, null], [37, null], [53, null], [78, null], [86, null], [89, null], [201, null], [201, null], [201, null], [202, null], [202, null], [202, null], [231, null], [231, null], [265, null], [265, null], [265, null], [265, null], [265, null]], "Exercise (continued)": [[231, null]], "Exercise 1": [[88, null]], "Exercise 2": [[90, null]], "Exercise 3": [[91, null]], "Exercise 4": [[92, null]], "Exercise 5": [[93, null]], "Exercise 6": [[94, null]], "Exercise 7": [[95, null]], "Exercise 8": [[96, null]], "Exercise 9": [[97, null]], "Exercise other operations": [[175, null]], "Exercise with the Gumbell distribution": [[216, "exercise-with-the-gumbell-distribution"]], "Exercise:": [[251, null]], "Exercise: 2-D minimization": [[202, null]], "Exercise: A locally flat minimum": [[53, null]], "Exercise: A simple (?) quadratic function": [[53, null]], "Exercise: Array creation": [[159, null]], "Exercise: Creating arrays using functions": [[159, null]], "Exercise: Curve fitting of temperature data": [[202, null]], "Exercise: Denoise moon landing image": [[202, null]], "Exercise: Elementwise operations": [[175, null]], "Exercise: Fancy indexing": [[159, null]], "Exercise: Fibonacci sequence": [[81, null]], "Exercise: Gradient Boosting Tree Regression": [[251, null]], "Exercise: Indexing and slicing": [[159, null]], "Exercise: Other dimension reduction of digits": [[251, null]], "Exercise: Probability distributions": [[202, null]], "Exercise: Quicksort": [[81, null]], "Exercise: Reductions": [[175, null]], "Exercise: Shape manipulations": [[175, null]], "Exercise: Simple arrays": [[159, null]], "Exercise: Simple visualizations": [[159, null]], "Exercise: Sorting": [[175, null]], "Exercise: Text data files": [[158, null]], "Exercise: Tiling for array creation": [[159, null]], "Exercise: building an ufunc from scratch": [[8, "exercise-building-an-ufunc-from-scratch"]], "Exercise: denoising": [[37, null]], "Exercises": [[39, "exercises"], [81, "exercises"], [266, null], [266, null], [266, null], [266, null], [266, null]], "Expand": [[266, "expand"]], "Fancy indexing": [[159, "fancy-indexing"]], "Fast Fourier transforms: scipy.fft": [[202, "fast-fourier-transforms-scipy-fft"]], "Feature extraction": [[37, "feature-extraction"]], "Feature extraction for computer vision": [[231, "feature-extraction-for-computer-vision"]], "Fibonacci sequence": [[203, "fibonacci-sequence"]], "Figures": [[157, "figures"]], "Figures and code examples": [[70, "figures-and-code-examples"]], "Figures, Subplots, Axes and Ticks": [[157, "figures-subplots-axes-and-ticks"]], "File input/output: scipy.io": [[202, "file-input-output-scipy-io"]], "File modes": [[82, "file-modes"]], "Filter in FFT": [[197, "filter-in-fft"]], "Find minima": [[177, "find-minima"], [188, "find-minima"]], "Find the bounding box of an object": [[22, null]], "Finding a minimum in a flat neighborhood": [[46, null]], "Finding edges with Sobel filters": [[21, null]], "Finding the minimum of a smooth function": [[187, null]], "Findings in dissection": [[8, "findings-in-dissection"]], "First Steps with SymPy": [[266, "first-steps-with-sympy"]], "First steps": [[80, null]], "Fit": [[215, "fit"]], "Fitting a waveform with a simple Gaussian model": [[215, "fitting-a-waveform-with-a-simple-gaussian-model"]], "Fitting in Chebyshev basis": [[163, null]], "Fitting it to a periodic function": [[196, "fitting-it-to-a-periodic-function"]], "Fitting on data": [[251, "fitting-on-data"]], "Fitting to polynomial": [[167, null]], "Fixed step gradient descent": [[53, "id7"]], "Flattening": [[175, "flattening"]], "Foreword": [[70, null]], "From a script to functions": [[76, null]], "Full code examples": [[37, "full-code-examples"], [53, "full-code-examples"], [53, "id2"], [157, "full-code-examples"], [173, null], [231, "full-code-examples"]], "Full code examples for the SciPy chapter": [[176, null], [202, "full-code-examples-for-the-scipy-chapter"]], "Full code examples for the numpy chapter": [[160, null], [173, "full-code-examples-for-the-numpy-chapter"]], "Full code for the figures": [[252, null], [265, "full-code-for-the-figures"]], "Function definition": [[81, "function-definition"]], "Functions are objects": [[81, "functions-are-objects"]], "Functions for creating arrays": [[159, "functions-for-creating-arrays"]], "Further Reading and References": [[39, "further-reading-and-references"]], "Galleries": [[157, "galleries"]], "Gaussian Naive Bayes Classification": [[251, "gaussian-naive-bayes-classification"]], "General constraints": [[53, "general-constraints"]], "Generalized ufuncs": [[8, "generalized-ufuncs"]], "Generate a chirp signal": [[192, "generate-a-chirp-signal"]], "Generate the signal": [[181, "generate-the-signal"]], "Generator expressions": [[9, "generator-expressions"]], "Generators": [[9, "generators"], [9, null]], "Geometrical transformations": [[23, null], [37, "geometrical-transformations"]], "Geometrical transformations on images": [[201, null], [202, "geometrical-transformations-on-images"]], "Getting help": [[76, null]], "Getting help and finding documentation": [[74, null]], "Getting help when in the debugger": [[10, "getting-help-when-in-the-debugger"]], "Getting started with Python for science": [[75, null]], "Getting started: 1D optimization": [[53, "getting-started-1d-optimization"]], "Global optimizers": [[53, "global-optimizers"]], "Global variables": [[81, "global-variables"]], "Going further": [[215, "going-further"]], "Good bug report": [[8, "good-bug-report"]], "Good practices": [[85, "good-practices"], [171, null]], "Gradient based methods": [[53, "gradient-based-methods"]], "Gradient descent": [[48, null]], "Gradient-less methods": [[53, "gradient-less-methods"]], "Granulometry": [[24, null]], "Graphical debuggers and alternatives": [[10, null]], "Grayscale mathematical morphology": [[231, null]], "Greyscale dilation": [[25, null]], "Grid": [[125, null]], "Grid elaborate": [[145, null]], "GridSpec": [[126, null]], "Grids": [[157, "grids"]], "High Bias": [[251, "high-bias"]], "High Variance": [[251, "high-variance"]], "Histogram segmentation": [[26, null]], "Histogram-based method: Otsu thresholding": [[231, "histogram-based-method-otsu-thresholding"]], "Horizontal arrangement of subplots": [[137, null]], "How does Python compare to other solutions?": [[76, "how-does-python-compare-to-other-solutions"]], "How modules are found and imported": [[85, "how-modules-are-found-and-imported"]], "How to contribute": [[70, null]], "How to contribute ?": [[70, "id1"]], "How to help, in general": [[8, "how-to-help-in-general"]], "Hyperparameter optimization with cross-validation": [[251, "hyperparameter-optimization-with-cross-validation"]], "Hyperparameters, Over-fitting, and Under-fitting": [[251, "hyperparameters-over-fitting-and-under-fitting"]], "Hypothesis testing: comparing two groups": [[265, "hypothesis-testing-comparing-two-groups"]], "IPython and Jupyter Tips and Tricks": [[76, "ipython-and-jupyter-tips-and-tricks"]], "IPython, Jupyter, and matplotlib modes": [[157, "ipython-jupyter-and-matplotlib-modes"]], "Image = 2-D numerical array": [[37, null]], "Image denoising": [[19, null]], "Image denoising by FFT": [[197, null]], "Image filtering": [[37, "image-filtering"], [201, "image-filtering"], [202, "image-filtering"]], "Image interpolation": [[27, null]], "Image manipulation and NumPy arrays": [[29, null]], "Image manipulation and processing using NumPy and SciPy": [[37, null]], "Image manipulation: scipy.ndimage": [[202, "image-manipulation-scipy-ndimage"]], "Image preprocessing / enhancement": [[231, "image-preprocessing-enhancement"]], "Image processing application: counting bubbles and unmolten grains": [[214, null]], "Image segmentation": [[231, "image-segmentation"]], "Image sharpening": [[32, null]], "Images": [[158, "images"]], "Implement convolution via FFT": [[198, "implement-convolution-via-fft"]], "Import conventions": [[159, "import-conventions"]], "Importing": [[231, "importing"]], "Importing objects from modules": [[85, "importing-objects-from-modules"]], "Imshow": [[157, "imshow"]], "Imshow demo": [[146, null]], "Imshow elaborate": [[127, null]], "Indexing and slicing": [[159, "indexing-and-slicing"]], "Indexing scheme: strides": [[8, "indexing-scheme-strides"]], "Indexing with an array of integers": [[159, "indexing-with-an-array-of-integers"]], "Initial Value Problems": [[202, "initial-value-problems"]], "Initial solution": [[215, "initial-solution"]], "Input and Output": [[82, null]], "Input/output, data types and colorspaces": [[231, "input-output-data-types-and-colorspaces"]], "Instantiating defaults": [[157, "instantiating-defaults"]], "Integers can overflow": [[221, null]], "Integrate the Damped spring-mass oscillator": [[190, null]], "Integrating a simple ODE": [[191, null]], "Integration": [[266, "integration"]], "Interactive work": [[76, "interactive-work"]], "Interfacing with C": [[39, null]], "Interoperability features": [[8, "interoperability-features"]], "Interpolation: scipy.interpolate": [[202, "interpolation-scipy-interpolate"]], "Introducing the scikit-learn estimator object": [[251, "introducing-the-scikit-learn-estimator-object"]], "Introduction": [[39, "introduction"], [62, null], [157, "introduction"], [215, "introduction"]], "Introduction and concepts": [[231, "introduction-and-concepts"]], "Introduction: problem settings": [[251, "introduction-problem-settings"]], "Invoking the debugger": [[10, "invoking-the-debugger"]], "Iterate over any sequence": [[78, "iterate-over-any-sequence"]], "Iterating over a file": [[82, "iterating-over-a-file"]], "Iterative Solvers": [[65, "iterative-solvers"]], "Iterators": [[9, "iterators"]], "Iterators, generator expressions and generators": [[9, "iterators-generator-expressions-and-generators"]], "It\u2019s\u2026": [[8, "it-s"]], "Julia": [[76, "julia"]], "Keeping it concise: collapsing paragraphs": [[70, "keeping-it-concise-collapsing-paragraphs"]], "Keeping track of enumeration number": [[78, "keeping-track-of-enumeration-number"]], "Knowing your problem": [[53, "knowing-your-problem"]], "Labeling connected components of a discrete image": [[231, "labeling-connected-components-of-a-discrete-image"]], "Labelling connected components of an image": [[226, null]], "Lagrange multipliers": [[53, null]], "Learning Curves": [[251, "learning-curves"]], "Learning curves": [[234, "learning-curves"]], "License": [[3, null], [267, "license"]], "Life of ndarray": [[8, "life-of-ndarray"]], "Limits": [[266, "limits"]], "Line properties": [[157, "line-properties"]], "Line styles": [[157, "line-styles"]], "Line-profiler": [[54, "id1"]], "Linear Algebra": [[266, "linear-algebra"]], "Linear System Solvers": [[65, null]], "Linear algebra operations: scipy.linalg": [[202, "linear-algebra-operations-scipy-linalg"]], "Linear models, multiple factors, and analysis of variance": [[265, "linear-models-multiple-factors-and-analysis-of-variance"]], "LinearOperator Class": [[65, "linearoperator-class"]], "Linestyles": [[108, null]], "Linewidth": [[109, null]], "Link to t-tests between different FSIQ and PIQ": [[265, null]], "Linking to package documentations": [[70, "linking-to-package-documentations"]], "List Comprehensions": [[78, "list-comprehensions"]], "List of Lists Format (LIL)": [[63, null]], "Lists": [[77, "lists"]], "Load the data": [[199, "load-the-data"]], "Loading and visualization": [[215, "loading-and-visualization"]], "Loading data files": [[158, "loading-data-files"]], "Loading the Iris Data with Scikit-learn": [[251, "loading-the-iris-data-with-scikit-learn"]], "Local filters": [[231, "local-filters"]], "Locators for tick on axis": [[117, null]], "Look and feel and matplotlib settings": [[265, null]], "Looping over a dictionary": [[78, "looping-over-a-dictionary"]], "Mailing lists": [[157, "mailing-lists"]], "Main point": [[8, "main-point"]], "Making code go faster": [[54, "making-code-go-faster"]], "Making it easier": [[8, "making-it-easier"]], "Making your optimizer faster": [[53, "making-your-optimizer-faster"]], "Mandelbrot set": [[166, null], [172, "mandelbrot-set"]], "Manipulating data": [[265, "manipulating-data"]], "Manual construction of arrays": [[159, "manual-construction-of-arrays"]], "Marker based methods": [[231, "marker-based-methods"]], "Marker edge color": [[111, null]], "Marker edge width": [[112, null]], "Marker face color": [[113, null]], "Marker size": [[114, null]], "Markers": [[110, null], [157, "markers"]], "Markov chain": [[172, "markov-chain"]], "Mathematical morphology": [[37, "mathematical-morphology"], [201, "mathematical-morphology"], [202, "mathematical-morphology"], [231, "mathematical-morphology"]], "Mathematical optimization: finding minima of functions": [[53, null]], "Matlab scripting language": [[76, "matlab-scripting-language"]], "Matplotlib documentation": [[157, "matplotlib-documentation"]], "Matplotlib: plotting": [[157, null]], "Matrices": [[266, "matrices"]], "Maximization?": [[202, null]], "Maximum wind speed prediction at the Sprog\u00f8 station": [[216, null]], "Measurements from images": [[28, null]], "Measuring Decision Tree performance": [[243, null]], "Measuring objects properties: scipy.ndimage.measurements": [[37, "measuring-objects-properties-scipy-ndimage-measurements"]], "Measuring prediction performance": [[251, "measuring-prediction-performance"]], "Measuring regions\u2019 properties": [[231, "measuring-regions-properties"]], "Methods": [[81, "methods"]], "Methods and Object-Oriented Programming": [[77, null]], "Minima and roots of a function": [[188, null]], "Minimizing the norm of a vector function": [[53, "minimizing-the-norm-of-a-vector-function"]], "Model": [[215, "model"]], "Model Selection via Validation": [[251, "model-selection-via-validation"]], "More container types": [[77, "more-container-types"]], "More data types": [[171, "more-data-types"]], "More elaborate arrays": [[171, null]], "More polynomials (with more bases)": [[158, "more-polynomials-with-more-bases"]], "More tricks: diagonals": [[8, "more-tricks-diagonals"]], "More visualization: seaborn for statistical exploration": [[265, "more-visualization-seaborn-for-statistical-exploration"]], "Moving spines": [[157, "moving-spines"]], "Multi Plots": [[157, "multi-plots"]], "Multiple Regression": [[258, null]], "Multiple Regression: including multiple factors": [[265, "multiple-regression-including-multiple-factors"]], "Multiple plots vignette": [[147, null]], "Nearest-neighbor prediction on iris": [[239, null]], "Nested cross-validation": [[251, "nested-cross-validation"]], "Newton and quasi-newton methods": [[53, "newton-and-quasi-newton-methods"]], "Newton methods: using the Hessian (2nd differential)": [[53, "newton-methods-using-the-hessian-2nd-differential"]], "No optimization without measuring!": [[54, null]], "Noisy gradients": [[53, null]], "Noisy optimization problem": [[49, null]], "Noisy versus exact cost functions": [[53, "noisy-versus-exact-cost-functions"]], "Non linear least squares curve fitting: application to point extraction in topographical lidar data": [[215, null]], "Non-local filters": [[231, "non-local-filters"]], "Normal distribution: histogram and PDF": [[186, null]], "NumPy Reference documentation": [[159, "numpy-reference-documentation"]], "NumPy Support": [[39, "numpy-support"], [39, "id6"], [39, "id9"], [39, "id11"]], "NumPy arrays": [[159, "numpy-arrays"]], "NumPy internals": [[158, null]], "NumPy: creating and manipulating numerical data": [[174, null]], "NumPy\u2019s own format": [[158, "numpy-s-own-format"]], "Numerical integration: scipy.integrate": [[202, "numerical-integration-scipy-integrate"]], "Numerical operations on arrays": [[175, null]], "Numerical types": [[77, "numerical-types"]], "Object-oriented programming (OOP)": [[83, null]], "Objectives": [[266, null]], "Objectives and design choices for the lectures": [[2, "objectives-and-design-choices-for-the-lectures"], [267, "objectives-and-design-choices-for-the-lectures"]], "Old scikit-learn versions": [[251, null]], "One document to learn numerics, science, and data with Python": [[73, "one-document-to-learn-numerics-science-and-data-with-python"]], "One-sample tests: testing the value of a population mean": [[265, "one-sample-tests-testing-the-value-of-a-population-mean"]], "Opening and writing to image files": [[37, "opening-and-writing-to-image-files"]], "Opening, erosion, and propagation": [[30, null]], "Optimization": [[202, "optimization"]], "Optimization and fit: scipy.optimize": [[202, "optimization-and-fit-scipy-optimize"]], "Optimization of a two-parameter function": [[177, null]], "Optimization with constraints": [[50, null], [53, "optimization-with-constraints"]], "Optimization workflow": [[54, "optimization-workflow"]], "Optimizing code": [[54, null]], "Other Interesting Packages": [[64, null]], "Other Types of Plots: examples and exercises": [[157, "other-types-of-plots-examples-and-exercises"]], "Other operations": [[175, "other-operations"]], "Other reductions": [[175, "other-reductions"]], "Other scripting languages: Scilab, Octave, R, IDL, etc.": [[76, "other-scripting-languages-scilab-octave-r-idl-etc"]], "Other ways of starting a debugger": [[10, "other-ways-of-starting-a-debugger"]], "Otsu thresholding": [[229, null]], "Packages": [[85, "packages"]], "Packages and applications": [[217, null]], "Paired tests: repeated measurements on the same individuals": [[265, "paired-tests-repeated-measurements-on-the-same-individuals"]], "Pairplot: scatter matrices": [[265, "pairplot-scatter-matrices"]], "Parameter selection, Validation, and Testing": [[251, "parameter-selection-validation-and-testing"]], "Parameters": [[81, "parameters"]], "Parts of an Ufunc": [[8, "parts-of-an-ufunc"]], "Passing by value": [[81, "passing-by-value"]], "Picture manipulation: Framing a Face": [[172, "picture-manipulation-framing-a-face"]], "Pie Charts": [[157, "pie-charts"]], "Pie chart": [[129, null]], "Pie chart vignette": [[148, null]], "Pipelining": [[238, "pipelining"]], "Plot 2D views of the iris dataset": [[240, null]], "Plot a projection on the 2 first principal axis": [[237, "plot-a-projection-on-the-2-first-principal-axis"]], "Plot and filled plots": [[130, null]], "Plot example vignette": [[150, null]], "Plot filtering on images": [[182, null]], "Plot fitting a 9th order polynomial": [[245, null]], "Plot function, minima, and roots": [[188, "plot-function-minima-and-roots"]], "Plot geometrical transformations on images": [[183, null]], "Plot its periods": [[199, "plot-its-periods"]], "Plot scatter decorated": [[153, null]], "Plot the block mean of an image": [[13, null]], "Plot the data": [[199, "plot-the-data"]], "Plot the data: images of digits": [[237, "plot-the-data-images-of-digits"]], "Plot variance and regularization in linear models": [[249, null]], "Plotting a scatter of points": [[135, null]], "Plotting a vector field: quiver": [[134, null]], "Plotting and manipulating FFTs for filtering": [[181, null]], "Plotting data": [[265, "plotting-data"]], "Plotting in polar coordinates": [[133, null]], "Plotting in polar, decorated": [[151, null]], "Plotting quiver decorated": [[152, null]], "Plotting simple quantities of a pandas dataframe": [[256, null]], "Plotting the comparison of optimizers": [[42, null]], "Plotting the fit": [[196, "plotting-the-fit"]], "Plotting with default settings": [[157, "plotting-with-default-settings"]], "Polar Axis": [[157, "polar-axis"]], "Polynomial regression with scikit-learn": [[251, null]], "Polynomials": [[158, "polynomials"]], "Population exercise": [[168, null]], "Post-hoc hypothesis testing: analysis of variance (ANOVA)": [[265, "post-hoc-hypothesis-testing-analysis-of-variance-anova"]], "Post-mortem debugging without IPython": [[10, null]], "Postmortem": [[10, "postmortem"]], "Postprocessing label images": [[231, null]], "Practical guide to optimization with SciPy": [[53, "practical-guide-to-optimization-with-scipy"]], "Predicting Home Prices: a Simple Linear Regression": [[251, "predicting-home-prices-a-simple-linear-regression"]], "Prediction with UnivariateSpline": [[216, "prediction-with-univariatespline"]], "Preferring simpler models": [[251, "preferring-simpler-models"]], "Prepare an Gaussian convolution kernel": [[198, "prepare-an-gaussian-convolution-kernel"]], "Preprocessing: Principal Component Analysis": [[238, "preprocessing-principal-component-analysis"]], "Prerequisites": [[8, null], [10, null], [53, null], [54, null], [62, "prerequisites"], [251, null]], "Printing": [[266, null]], "Profiler": [[54, "profiler"]], "Profiling Python code": [[54, "profiling-python-code"]], "Profiling outside of IPython, running ``cProfile``": [[54, null]], "Python": [[76, "python"]], "Python for scientific computing": [[84, null]], "Python scientific computing ecosystem": [[76, null]], "Python-C-API": [[39, "id12"]], "Python-C-Api": [[39, "id1"]], "Python\u2019s strengths": [[76, "python-s-strengths"]], "Quadrature": [[202, "quadrature"]], "Quantify the performance": [[237, "quantify-the-performance"]], "Quantitative Measurement of Performance": [[251, "quantitative-measurement-of-performance"]], "Quasi-Newton methods: approximating the Hessian on the fly": [[53, "quasi-newton-methods-approximating-the-hessian-on-the-fly"]], "Question": [[251, null], [251, null], [251, null]], "Questions:": [[251, null]], "Quick Question:": [[251, null]], "Quick read": [[85, null], [157, null], [175, null]], "Quick references": [[157, "quick-references"]], "Quiver Plots": [[157, "quiver-plots"]], "Radial mean": [[31, null]], "Raising exception on numerical errors": [[10, null]], "Raising exceptions": [[79, "raising-exceptions"]], "Random walk exercise": [[169, null]], "Random walker segmentation": [[231, "random-walker-segmentation"]], "Re-interpretation / viewing": [[8, "re-interpretation-viewing"]], "Read and plot the image": [[197, "read-and-plot-the-image"]], "Reading and writing an elephant": [[165, null]], "Reconstruct the final image": [[197, "reconstruct-the-final-image"]], "References": [[70, "references"]], "Regular Plots": [[157, "regular-plots"]], "Regularization: what it is and why it is necessary": [[251, "regularization-what-it-is-and-why-it-is-necessary"]], "Relating Gender and IQ": [[263, null]], "Release 2011 (1 Sept 2011)": [[1, "release-2011-1-sept-2011"], [267, "release-2011-1-sept-2011"]], "Release 2011.1 (16 Oct 2011)": [[1, "release-2011-1-16-oct-2011"], [267, "release-2011-1-16-oct-2011"]], "Release 2012.0 (22 Apr 2012)": [[1, "release-2012-0-22-apr-2012"], [267, "release-2012-0-22-apr-2012"]], "Release 2012.1 (20 Jun 2012)": [[1, "release-2012-1-20-jun-2012"], [267, "release-2012-1-20-jun-2012"]], "Release 2012.2 (22 Jun 2012)": [[1, "release-2012-2-22-jun-2012"], [267, "release-2012-2-22-jun-2012"]], "Release 2012.3 (26 Nov 2012)": [[1, "release-2012-3-26-nov-2012"], [267, "release-2012-3-26-nov-2012"]], "Release 2013.1 (10 Feb 2013)": [[1, "release-2013-1-10-feb-2013"], [267, "release-2013-1-10-feb-2013"]], "Release 2013.2 (21 August 2013)": [[1, "release-2013-2-21-august-2013"], [267, "release-2013-2-21-august-2013"]], "Release 2015.1 (September 2015)": [[1, "release-2015-1-september-2015"], [267, "release-2015-1-september-2015"]], "Release 2015.2 (October 2015)": [[1, "release-2015-2-october-2015"], [267, "release-2015-2-october-2015"]], "Release 2015.3 (November 2015)": [[1, "release-2015-3-november-2015"], [267, "release-2015-3-november-2015"]], "Release 2016.1 (September 2016)": [[1, "release-2016-1-september-2016"], [267, "release-2016-1-september-2016"]], "Release 2017.1 (October 2017)": [[1, "release-2017-1-october-2017"], [267, "release-2017-1-october-2017"]], "Release 2018.1 (September 2018)": [[1, "release-2018-1-september-2018"], [267, "release-2018-1-september-2018"]], "Release 2019.1 (May 2019)": [[1, "release-2019-1-may-2019"], [267, "release-2019-1-may-2019"]], "Release 2020.1 (March 2020)": [[1, "release-2020-1-march-2020"], [267, "release-2020-1-march-2020"]], "Release 2020.2 (September 2020)": [[1, "release-2020-2-september-2020"], [267, "release-2020-2-september-2020"]], "Release 2022.1 (August 2022)": [[1, "release-2022-1-august-2022"], [267, "release-2022-1-august-2022"]], "Release 2024.1 (April 2024)": [[1, "release-2024-1-april-2024"], [267, "release-2024-1-april-2024"]], "Reminder: Navigating the filesystem with IPython": [[158, null]], "Remove all the high frequencies": [[181, "remove-all-the-high-frequencies"]], "Replacing or tweaking the original object": [[9, "replacing-or-tweaking-the-original-object"]], "Reporting bugs": [[8, "reporting-bugs"]], "Requirements": [[2, "requirements"], [265, null], [267, "requirements"]], "Resample a signal with scipy.signal.resample": [[189, null]], "Reshaping": [[175, "reshaping"]], "Resizing": [[175, "resizing"]], "Return statement": [[81, "return-statement"]], "Reusing code: scripts and modules": [[85, null]], "Robust regression": [[265, null]], "Root Finding": [[202, "root-finding"]], "Root finding": [[188, "root-finding"]], "Running an external command": [[86, "running-an-external-command"]], "Running pyflakes on the current edited file": [[10, "running-pyflakes-on-the-current-edited-file"]], "SWIG": [[39, "swig"], [39, "id14"]], "Sample Statistics and Hypothesis Tests": [[202, "sample-statistics-and-hypothesis-tests"]], "Scatter Plots": [[157, "scatter-plots"]], "SciPy : high-level scientific computing": [[202, null]], "Scientific Python Lectures": [[73, null]], "Scipy": [[202, null]], "Scripts": [[85, "scripts"]], "Scripts or modules? How to organize your code": [[85, "scripts-or-modules-how-to-organize-your-code"]], "Section contents": [[158, "section-contents"], [159, "section-contents"], [171, "section-contents"], [175, "section-contents"]], "Segmentation": [[37, "segmentation"]], "Segmentation contours": [[219, null]], "Segmentation with Gaussian mixture models": [[12, null]], "Segmentation with spectral clustering": [[33, null]], "Separator": [[265, null]], "Series expansion": [[266, "series-expansion"]], "Setting limits": [[157, "setting-limits"]], "Setting tick labels": [[157, "setting-tick-labels"]], "Setting ticks": [[157, "setting-ticks"]], "Sharing multidimensional, typed data": [[8, "sharing-multidimensional-typed-data"]], "Sharpening": [[37, "sharpening"]], "Signal processing: scipy.signal": [[202, "signal-processing-scipy-signal"]], "Simple Regression": [[257, null]], "Simple axes example": [[119, null]], "Simple image blur by convolution with a Gaussian kernel": [[198, null]], "Simple picture of the formal problem of machine learning": [[246, null]], "Simple plot": [[157, "simple-plot"]], "Simple versus complex models for classification": [[251, "simple-versus-complex-models-for-classification"]], "Simple visualization and classification of the digits dataset": [[237, null]], "Simplex method: the Nelder-Mead": [[53, "simplex-method-the-nelder-mead"]], "Simplicity": [[9, null]], "Simplify": [[266, "simplify"]], "Slicing with integers": [[8, "slicing-with-integers"]], "Smaller data types": [[171, null]], "Smooth and non-smooth problems": [[53, "smooth-and-non-smooth-problems"]], "Smooth vs non-smooth": [[51, null]], "Solid cap style": [[115, null]], "Solid joint style": [[116, null]], "Solution: building an ufunc from scratch": [[8, "solution-building-an-ufunc-from-scratch"]], "Solutions": [[203, null]], "Solutions of the exercises for SciPy": [[176, "solutions-of-the-exercises-for-scipy"], [195, null], [202, "solutions-of-the-exercises-for-scipy"]], "Solutions to this chapter\u2019s exercises": [[252, "solutions-to-this-chapter-s-exercises"], [262, null], [265, "solutions-to-this-chapter-s-exercises"]], "Some exercises": [[172, null]], "Some intuitions about gradient descent": [[53, "some-intuitions-about-gradient-descent"]], "Sorting data": [[175, "sorting-data"]], "Sparse Array Classes": [[66, "sparse-array-classes"]], "Sparse Arrays in SciPy": [[61, null]], "Sparse Direct Solvers": [[65, "sparse-direct-solvers"]], "Sparse Matrices vs. Sparse Matrix Storage Schemes": [[62, "sparse-matrices-vs-sparse-matrix-storage-schemes"]], "Sparsity Structure Visualization": [[62, "sparsity-structure-visualization"]], "Special case: non-linear least-squares": [[53, "special-case-non-linear-least-squares"]], "Special functions: scipy.special": [[202, "special-functions-scipy-special"]], "Spectrogram, power spectral density": [[192, null]], "Standard Library": [[86, null]], "Statement of the problem": [[214, "statement-of-the-problem"]], "Statistical Distributions": [[202, "statistical-distributions"]], "Statistical approach": [[216, "statistical-approach"]], "Statistical information": [[37, "statistical-information"]], "Statistics and random numbers: scipy.stats": [[202, "statistics-and-random-numbers-scipy-stats"]], "Statistics in Python": [[265, null]], "Step-by-step execution": [[10, "step-by-step-execution"]], "Storage Schemes": [[66, null]], "Strings": [[77, "strings"]], "Structured data types": [[171, "structured-data-types"]], "Student\u2019s t-test: the simplest statistical test": [[265, "student-s-t-test-the-simplest-statistical-test"]], "Subplot grid": [[136, null]], "Subplot plot arrangement vertical": [[138, null]], "Subplots": [[128, null], [157, "subplots"]], "Summary": [[8, "summary"], [9, null], [39, "summary"], [66, "summary"], [175, "summary"]], "Summary exercises on scientific computing": [[202, "summary-exercises-on-scientific-computing"]], "Summary of storage schemes.": [[66, "id1"]], "Summary on model selection": [[251, "summary-on-model-selection"]], "Supervised Learning: Classification and regression": [[251, "supervised-learning-classification-and-regression"]], "Supervised Learning: Classification of Handwritten Digits": [[251, "supervised-learning-classification-of-handwritten-digits"]], "Supervised Learning: Regression of Housing Data": [[251, "supervised-learning-regression-of-housing-data"]], "Symbols": [[266, "symbols"]], "Sympy : Symbolic Mathematics in Python": [[266, null]], "Synthetic data": [[34, null]], "Synthetic exercises": [[53, "synthetic-exercises"]], "Systems of linear equations": [[266, null]], "Take home message: conditioning number and preconditioning": [[53, null]], "Take home messages": [[265, null]], "Terminology:": [[265, null]], "Test for an education/gender interaction in wages": [[260, null]], "Testing for interactions": [[265, "testing-for-interactions"]], "Text": [[157, "text"]], "Text files": [[158, "text-files"]], "Text printing decorated": [[154, null]], "Thanks": [[157, null]], "The Data File I/O Solution": [[203, "the-data-file-i-o-solution"]], "The Directory Listing Solution": [[203, "the-directory-listing-solution"]], "The Gumbell distribution": [[207, null]], "The Gumbell distribution, results": [[212, null]], "The NumPy array object": [[159, null]], "The PYTHONPATH Search Solution": [[203, "the-pythonpath-search-solution"]], "The Pi Wallis Solution": [[203, "the-pi-wallis-solution"]], "The Python language": [[84, null]], "The Quicksort Solution": [[203, "the-quicksort-solution"]], "The application problem": [[251, "the-application-problem"]], "The colors matplotlib line plots": [[104, null]], "The data": [[196, "the-data"]], "The data matrix": [[251, "the-data-matrix"]], "The descriptor": [[8, "the-descriptor"]], "The eigen module": [[65, "the-eigen-module"]], "The eigenfaces example: chaining PCA and SVMs": [[238, null]], "The lidar system, data (1 of 2 datasets)": [[210, null]], "The lidar system, data (2 of 2 datasets)": [[208, null]], "The lidar system, data and fit (1 of 2 datasets)": [[211, null]], "The lidar system, data and fit (2 of 2 datasets)": [[209, null]], "The mask": [[8, "the-mask"]], "The nature of the data": [[251, "the-nature-of-the-data"]], "The old buffer protocol": [[8, "the-old-buffer-protocol"], [8, "id2"]], "The original image": [[198, "the-original-image"]], "The pandas data-frame": [[265, "the-pandas-data-frame"]], "The scientific Python ecosystem": [[76, "the-scientific-python-ecosystem"]], "The scientist\u2019s needs": [[76, "the-scientist-s-needs"]], "The workflow: interactive environments and text editors": [[76, "the-workflow-interactive-environments-and-text-editors"]], "Tick Locators": [[157, "tick-locators"]], "Ticks": [[157, "ticks"]], "Timeit": [[54, "timeit"]], "Tips on specifying model": [[265, null]], "Total Variation denoising": [[20, null]], "Tutorial Diagrams": [[233, null]], "Tutorials": [[157, "tutorials"]], "Two populations": [[265, null]], "Two-sample t-test: testing for difference across populations": [[265, "two-sample-t-test-testing-for-difference-across-populations"]], "Typical Applications": [[62, "typical-applications"]], "Under the notebook": [[76, null]], "Universal functions": [[8, "universal-functions"]], "Unsupervised Learning: Dimensionality Reduction and Visualization": [[251, "unsupervised-learning-dimensionality-reduction-and-visualization"]], "Updating the cover": [[2, "updating-the-cover"], [267, "updating-the-cover"]], "Use the RidgeCV and LassoCV to set the regularization parameter": [[241, null]], "Using GitHub": [[70, "using-github"]], "Using Markup": [[70, "using-markup"]], "Using SymPy as a calculator": [[266, "using-sympy-as-a-calculator"]], "Using boolean masks": [[159, "using-boolean-masks"]], "Using generators to define context managers": [[9, "using-generators-to-define-context-managers"]], "Using the Python debugger": [[10, "using-the-python-debugger"]], "Validation Curves": [[251, "validation-curves"]], "Variable number of parameters": [[81, "variable-number-of-parameters"]], "Various denoising filters": [[225, null]], "Visualization with a non-linear embedding: tSNE": [[251, "visualization-with-a-non-linear-embedding-tsne"]], "Visualizing factors influencing wages": [[259, null]], "Visualizing the Bias/Variance Tradeoff": [[251, "visualizing-the-bias-variance-tradeoff"]], "Visualizing the Data on its principal components": [[251, "visualizing-the-data-on-its-principal-components"]], "Walking a directory": [[86, "walking-a-directory"]], "Watershed and random walker for segmentation": [[227, null]], "Watershed segmentation": [[35, null], [231, "watershed-segmentation"]], "Well-known (& more obscure) file formats": [[158, "well-known-more-obscure-file-formats"]], "What are NumPy and NumPy arrays?": [[159, "what-are-numpy-and-numpy-arrays"]], "What is included in scikit-image": [[231, "what-is-included-in-scikit-image"]], "What is machine learning?": [[251, "what-is-machine-learning"]], "What they are?": [[8, "what-they-are"]], "What\u2019s new": [[1, null], [267, "what-s-new"]], "Why": [[8, "why"]], "Why Python?": [[76, "why-python"]], "Why Sparse Matrices?": [[62, "why-sparse-matrices"]], "Worked Example: Broadcasting": [[175, null]], "Worked Example: diffusion using a random walk algorithm": [[175, null]], "Worked example: Prime number sieve": [[159, null]], "Wrap up exercise": [[10, null]], "Writing faster numerical code": [[54, "writing-faster-numerical-code"]], "chararray: vectorized string operations": [[8, "chararray-vectorized-string-operations"]], "fit_transform": [[251, null]], "for/range": [[78, "for-range"]], "functools.update_wrapper(wrapper, wrapped)": [[9, null]], "glob: Pattern matching on files": [[86, "glob-pattern-matching-on-files"]], "if/elif/else": [[78, "if-elif-else"]], "lmplot: plotting a univariate regression": [[265, "lmplot-plotting-a-univariate-regression"]], "lower resolution": [[165, "lower-resolution"]], "masked_array missing data": [[8, "masked-array-missing-data"]], "maskedarray: dealing with (propagation of) missing data": [[171, "maskedarray-dealing-with-propagation-of-missing-data"]], "numpy.fft": [[202, null]], "original figure": [[165, "original-figure"]], "os module: operating system functionality": [[86, "os-module-operating-system-functionality"]], "os.path: path manipulations": [[86, "os-path-path-manipulations"]], "pickle: easy persistence": [[86, "pickle-easy-persistence"]], "print": [[10, null]], "pyflakes: fast static analysis": [[10, "pyflakes-fast-static-analysis"]], "pyplot": [[157, "pyplot"]], "recarray: purely convenience": [[8, "recarray-purely-convenience"]], "red channel displayed in grey": [[165, "red-channel-displayed-in-grey"]], "scikit-image and the scientific Python ecosystem": [[231, "scikit-image-and-the-scientific-python-ecosystem"]], "scikit-image: image processing": [[231, null]], "scikit-learn: machine learning in Python": [[251, null]], "shutil: high-level file operations": [[86, "shutil-high-level-file-operations"]], "sys module: system-specific information": [[86, "sys-module-system-specific-information"]], "tSNE to visualize digits": [[248, null]], "try/except": [[79, "try-except"]], "try/finally": [[79, "try-finally"]], "while/break/continue": [[78, "while-break-continue"]], "\u2018__main__\u2019 and module loading": [[85, "main-and-module-loading"]], "\u201cformulas\u201d for statistics in Python": [[265, null]], "\u201cformulas\u201d to specify statistical models in Python": [[265, "formulas-to-specify-statistical-models-in-python"]]}, "docnames": ["AUTHORS", "CHANGES", "CONTRIBUTING", "LICENSE", "about", "advanced/advanced_numpy/auto_examples/index", "advanced/advanced_numpy/auto_examples/plot_maskedstats", "advanced/advanced_numpy/auto_examples/sg_execution_times", "advanced/advanced_numpy/index", "advanced/advanced_python/index", "advanced/debugging/index", "advanced/image_processing/auto_examples/index", "advanced/image_processing/auto_examples/plot_GMM", "advanced/image_processing/auto_examples/plot_block_mean", "advanced/image_processing/auto_examples/plot_blur", "advanced/image_processing/auto_examples/plot_clean_morpho", "advanced/image_processing/auto_examples/plot_denoising", "advanced/image_processing/auto_examples/plot_display_face", "advanced/image_processing/auto_examples/plot_face", "advanced/image_processing/auto_examples/plot_face_denoise", "advanced/image_processing/auto_examples/plot_face_tv_denoise", "advanced/image_processing/auto_examples/plot_find_edges", "advanced/image_processing/auto_examples/plot_find_object", "advanced/image_processing/auto_examples/plot_geom_face", "advanced/image_processing/auto_examples/plot_granulo", "advanced/image_processing/auto_examples/plot_greyscale_dilation", "advanced/image_processing/auto_examples/plot_histo_segmentation", "advanced/image_processing/auto_examples/plot_interpolation_face", "advanced/image_processing/auto_examples/plot_measure_data", "advanced/image_processing/auto_examples/plot_numpy_array", "advanced/image_processing/auto_examples/plot_propagation", "advanced/image_processing/auto_examples/plot_radial_mean", "advanced/image_processing/auto_examples/plot_sharpen", "advanced/image_processing/auto_examples/plot_spectral_clustering", "advanced/image_processing/auto_examples/plot_synthetic_data", "advanced/image_processing/auto_examples/plot_watershed_segmentation", "advanced/image_processing/auto_examples/sg_execution_times", "advanced/image_processing/index", "advanced/index", "advanced/interfacing_with_c/interfacing_with_c", "advanced/mathematical_optimization/auto_examples/index", "advanced/mathematical_optimization/auto_examples/plot_1d_optim", "advanced/mathematical_optimization/auto_examples/plot_compare_optimizers", "advanced/mathematical_optimization/auto_examples/plot_constraints", "advanced/mathematical_optimization/auto_examples/plot_convex", "advanced/mathematical_optimization/auto_examples/plot_curve_fitting", "advanced/mathematical_optimization/auto_examples/plot_exercise_flat_minimum", "advanced/mathematical_optimization/auto_examples/plot_exercise_ill_conditioned", "advanced/mathematical_optimization/auto_examples/plot_gradient_descent", "advanced/mathematical_optimization/auto_examples/plot_noisy", "advanced/mathematical_optimization/auto_examples/plot_non_bounds_constraints", "advanced/mathematical_optimization/auto_examples/plot_smooth", "advanced/mathematical_optimization/auto_examples/sg_execution_times", "advanced/mathematical_optimization/index", "advanced/optimizing/index", "advanced/scipy_sparse/bsr_array", "advanced/scipy_sparse/coo_array", "advanced/scipy_sparse/csc_array", "advanced/scipy_sparse/csr_array", "advanced/scipy_sparse/dia_array", "advanced/scipy_sparse/dok_array", "advanced/scipy_sparse/index", "advanced/scipy_sparse/introduction", "advanced/scipy_sparse/lil_array", "advanced/scipy_sparse/other_packages", "advanced/scipy_sparse/solvers", "advanced/scipy_sparse/storage_schemes", "guide/auto_examples/index", "guide/auto_examples/plot_simple", "guide/auto_examples/sg_execution_times", "guide/index", "includes/big_toc_css", "includes/bigger_toc_css", "index", "intro/help/help", "intro/index", "intro/intro", "intro/language/basic_types", "intro/language/control_flow", "intro/language/exceptions", "intro/language/first_steps", "intro/language/functions", "intro/language/io", "intro/language/oop", "intro/language/python_language", "intro/language/reusing_code", "intro/language/standard_library", "intro/matplotlib/auto_examples/exercises/index", "intro/matplotlib/auto_examples/exercises/plot_exercise_1", "intro/matplotlib/auto_examples/exercises/plot_exercise_10", "intro/matplotlib/auto_examples/exercises/plot_exercise_2", "intro/matplotlib/auto_examples/exercises/plot_exercise_3", "intro/matplotlib/auto_examples/exercises/plot_exercise_4", "intro/matplotlib/auto_examples/exercises/plot_exercise_5", "intro/matplotlib/auto_examples/exercises/plot_exercise_6", "intro/matplotlib/auto_examples/exercises/plot_exercise_7", "intro/matplotlib/auto_examples/exercises/plot_exercise_8", "intro/matplotlib/auto_examples/exercises/plot_exercise_9", "intro/matplotlib/auto_examples/exercises/sg_execution_times", "intro/matplotlib/auto_examples/index", "intro/matplotlib/auto_examples/options/index", "intro/matplotlib/auto_examples/options/plot_aliased", "intro/matplotlib/auto_examples/options/plot_alpha", "intro/matplotlib/auto_examples/options/plot_antialiased", "intro/matplotlib/auto_examples/options/plot_color", "intro/matplotlib/auto_examples/options/plot_colormaps", "intro/matplotlib/auto_examples/options/plot_dash_capstyle", "intro/matplotlib/auto_examples/options/plot_dash_joinstyle", "intro/matplotlib/auto_examples/options/plot_linestyles", "intro/matplotlib/auto_examples/options/plot_linewidth", "intro/matplotlib/auto_examples/options/plot_markers", "intro/matplotlib/auto_examples/options/plot_mec", "intro/matplotlib/auto_examples/options/plot_mew", "intro/matplotlib/auto_examples/options/plot_mfc", "intro/matplotlib/auto_examples/options/plot_ms", "intro/matplotlib/auto_examples/options/plot_solid_capstyle", "intro/matplotlib/auto_examples/options/plot_solid_joinstyle", "intro/matplotlib/auto_examples/options/plot_ticks", "intro/matplotlib/auto_examples/options/sg_execution_times", "intro/matplotlib/auto_examples/plot_axes", "intro/matplotlib/auto_examples/plot_axes-2", "intro/matplotlib/auto_examples/plot_bad", "intro/matplotlib/auto_examples/plot_bar", "intro/matplotlib/auto_examples/plot_contour", "intro/matplotlib/auto_examples/plot_good", "intro/matplotlib/auto_examples/plot_grid", "intro/matplotlib/auto_examples/plot_gridspec", "intro/matplotlib/auto_examples/plot_imshow", "intro/matplotlib/auto_examples/plot_multiplot", "intro/matplotlib/auto_examples/plot_pie", "intro/matplotlib/auto_examples/plot_plot", "intro/matplotlib/auto_examples/plot_plot3d", "intro/matplotlib/auto_examples/plot_plot3d-2", "intro/matplotlib/auto_examples/plot_polar", "intro/matplotlib/auto_examples/plot_quiver", "intro/matplotlib/auto_examples/plot_scatter", "intro/matplotlib/auto_examples/plot_subplot-grid", "intro/matplotlib/auto_examples/plot_subplot-horizontal", "intro/matplotlib/auto_examples/plot_subplot-vertical", "intro/matplotlib/auto_examples/plot_text", "intro/matplotlib/auto_examples/plot_ugly", "intro/matplotlib/auto_examples/pretty_plots/index", "intro/matplotlib/auto_examples/pretty_plots/plot_bar_ext", "intro/matplotlib/auto_examples/pretty_plots/plot_boxplot_ext", "intro/matplotlib/auto_examples/pretty_plots/plot_contour_ext", "intro/matplotlib/auto_examples/pretty_plots/plot_grid_ext", "intro/matplotlib/auto_examples/pretty_plots/plot_imshow_ext", "intro/matplotlib/auto_examples/pretty_plots/plot_multiplot_ext", "intro/matplotlib/auto_examples/pretty_plots/plot_pie_ext", "intro/matplotlib/auto_examples/pretty_plots/plot_plot3d_ext", "intro/matplotlib/auto_examples/pretty_plots/plot_plot_ext", "intro/matplotlib/auto_examples/pretty_plots/plot_polar_ext", "intro/matplotlib/auto_examples/pretty_plots/plot_quiver_ext", "intro/matplotlib/auto_examples/pretty_plots/plot_scatter_ext", "intro/matplotlib/auto_examples/pretty_plots/plot_text_ext", "intro/matplotlib/auto_examples/pretty_plots/sg_execution_times", "intro/matplotlib/auto_examples/sg_execution_times", "intro/matplotlib/index", "intro/numpy/advanced_operations", "intro/numpy/array_object", "intro/numpy/auto_examples/index", "intro/numpy/auto_examples/plot_basic1dplot", "intro/numpy/auto_examples/plot_basic2dplot", "intro/numpy/auto_examples/plot_chebyfit", "intro/numpy/auto_examples/plot_distances", "intro/numpy/auto_examples/plot_elephant", "intro/numpy/auto_examples/plot_mandelbrot", "intro/numpy/auto_examples/plot_polyfit", "intro/numpy/auto_examples/plot_populations", "intro/numpy/auto_examples/plot_randomwalk", "intro/numpy/auto_examples/sg_execution_times", "intro/numpy/elaborate_arrays", "intro/numpy/exercises", "intro/numpy/gallery", "intro/numpy/index", "intro/numpy/operations", "intro/scipy/auto_examples/index", "intro/scipy/auto_examples/plot_2d_minimization", "intro/scipy/auto_examples/plot_connect_measurements", "intro/scipy/auto_examples/plot_curve_fit", "intro/scipy/auto_examples/plot_detrend", "intro/scipy/auto_examples/plot_fftpack", "intro/scipy/auto_examples/plot_image_filters", "intro/scipy/auto_examples/plot_image_transform", "intro/scipy/auto_examples/plot_interpolation", "intro/scipy/auto_examples/plot_mathematical_morpho", "intro/scipy/auto_examples/plot_normal_distribution", "intro/scipy/auto_examples/plot_optimize_example1", "intro/scipy/auto_examples/plot_optimize_example2", "intro/scipy/auto_examples/plot_resample", "intro/scipy/auto_examples/plot_solve_ivp_damped_spring_mass", "intro/scipy/auto_examples/plot_solve_ivp_simple", "intro/scipy/auto_examples/plot_spectrogram", "intro/scipy/auto_examples/plot_t_test", "intro/scipy/auto_examples/sg_execution_times", "intro/scipy/auto_examples/solutions/index", "intro/scipy/auto_examples/solutions/plot_curvefit_temperature_data", "intro/scipy/auto_examples/solutions/plot_fft_image_denoise", "intro/scipy/auto_examples/solutions/plot_image_blur", "intro/scipy/auto_examples/solutions/plot_periodicity_finder", "intro/scipy/auto_examples/solutions/sg_execution_times", "intro/scipy/image_processing/image_processing", "intro/scipy/index", "intro/scipy/solutions", "intro/scipy/summary-exercises/answers_image_processing", "intro/scipy/summary-exercises/auto_examples/index", "intro/scipy/summary-exercises/auto_examples/plot_cumulative_wind_speed_prediction", "intro/scipy/summary-exercises/auto_examples/plot_gumbell_wind_speed_prediction", "intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_complex_data", "intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_complex_data_fit", "intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_data", "intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_data_fit", "intro/scipy/summary-exercises/auto_examples/plot_sprog_annual_maxima", "intro/scipy/summary-exercises/auto_examples/sg_execution_times", "intro/scipy/summary-exercises/image-processing", "intro/scipy/summary-exercises/optimize-fit", "intro/scipy/summary-exercises/stats-interpolate", "packages/index", "packages/scikit-image/auto_examples/index", "packages/scikit-image/auto_examples/plot_boundaries", "packages/scikit-image/auto_examples/plot_camera", "packages/scikit-image/auto_examples/plot_camera_uint", "packages/scikit-image/auto_examples/plot_check", "packages/scikit-image/auto_examples/plot_equalize_hist", "packages/scikit-image/auto_examples/plot_features", "packages/scikit-image/auto_examples/plot_filter_coins", "packages/scikit-image/auto_examples/plot_labels", "packages/scikit-image/auto_examples/plot_segmentations", "packages/scikit-image/auto_examples/plot_sobel", "packages/scikit-image/auto_examples/plot_threshold", "packages/scikit-image/auto_examples/sg_execution_times", "packages/scikit-image/index", "packages/scikit-learn/auto_examples/index", "packages/scikit-learn/auto_examples/plot_ML_flow_chart", "packages/scikit-learn/auto_examples/plot_bias_variance", "packages/scikit-learn/auto_examples/plot_california_prediction", "packages/scikit-learn/auto_examples/plot_compare_classifiers", "packages/scikit-learn/auto_examples/plot_digits_simple_classif", "packages/scikit-learn/auto_examples/plot_eigenfaces", "packages/scikit-learn/auto_examples/plot_iris_knn", "packages/scikit-learn/auto_examples/plot_iris_scatter", "packages/scikit-learn/auto_examples/plot_linear_model_cv", "packages/scikit-learn/auto_examples/plot_linear_regression", "packages/scikit-learn/auto_examples/plot_measuring_performance", "packages/scikit-learn/auto_examples/plot_pca", "packages/scikit-learn/auto_examples/plot_polynomial_regression", "packages/scikit-learn/auto_examples/plot_separator", "packages/scikit-learn/auto_examples/plot_svm_non_linear", "packages/scikit-learn/auto_examples/plot_tsne", "packages/scikit-learn/auto_examples/plot_variance_linear_regr", "packages/scikit-learn/auto_examples/sg_execution_times", "packages/scikit-learn/index", "packages/statistics/auto_examples/index", "packages/statistics/auto_examples/plot_airfare", "packages/statistics/auto_examples/plot_iris_analysis", "packages/statistics/auto_examples/plot_paired_boxplots", "packages/statistics/auto_examples/plot_pandas", "packages/statistics/auto_examples/plot_regression", "packages/statistics/auto_examples/plot_regression_3d", "packages/statistics/auto_examples/plot_wage_data", "packages/statistics/auto_examples/plot_wage_education_gender", "packages/statistics/auto_examples/sg_execution_times", "packages/statistics/auto_examples/solutions/index", "packages/statistics/auto_examples/solutions/plot_brain_size", "packages/statistics/auto_examples/solutions/sg_execution_times", "packages/statistics/index", "packages/sympy", "preface", "sg_execution_times"], "envversion": {"sphinx": 63, "sphinx.domains.c": 3, "sphinx.domains.changeset": 1, "sphinx.domains.citation": 1, "sphinx.domains.cpp": 9, "sphinx.domains.index": 1, "sphinx.domains.javascript": 3, "sphinx.domains.math": 2, "sphinx.domains.python": 4, "sphinx.domains.rst": 2, "sphinx.domains.std": 2, "sphinx.ext.intersphinx": 1}, "filenames": ["AUTHORS.rst", "CHANGES.rst", "CONTRIBUTING.rst", "LICENSE.rst", "about.rst", "advanced/advanced_numpy/auto_examples/index.rst", "advanced/advanced_numpy/auto_examples/plot_maskedstats.rst", "advanced/advanced_numpy/auto_examples/sg_execution_times.rst", "advanced/advanced_numpy/index.rst", "advanced/advanced_python/index.rst", "advanced/debugging/index.rst", "advanced/image_processing/auto_examples/index.rst", "advanced/image_processing/auto_examples/plot_GMM.rst", "advanced/image_processing/auto_examples/plot_block_mean.rst", "advanced/image_processing/auto_examples/plot_blur.rst", "advanced/image_processing/auto_examples/plot_clean_morpho.rst", "advanced/image_processing/auto_examples/plot_denoising.rst", "advanced/image_processing/auto_examples/plot_display_face.rst", "advanced/image_processing/auto_examples/plot_face.rst", "advanced/image_processing/auto_examples/plot_face_denoise.rst", "advanced/image_processing/auto_examples/plot_face_tv_denoise.rst", "advanced/image_processing/auto_examples/plot_find_edges.rst", "advanced/image_processing/auto_examples/plot_find_object.rst", "advanced/image_processing/auto_examples/plot_geom_face.rst", "advanced/image_processing/auto_examples/plot_granulo.rst", "advanced/image_processing/auto_examples/plot_greyscale_dilation.rst", "advanced/image_processing/auto_examples/plot_histo_segmentation.rst", "advanced/image_processing/auto_examples/plot_interpolation_face.rst", "advanced/image_processing/auto_examples/plot_measure_data.rst", "advanced/image_processing/auto_examples/plot_numpy_array.rst", "advanced/image_processing/auto_examples/plot_propagation.rst", "advanced/image_processing/auto_examples/plot_radial_mean.rst", "advanced/image_processing/auto_examples/plot_sharpen.rst", "advanced/image_processing/auto_examples/plot_spectral_clustering.rst", "advanced/image_processing/auto_examples/plot_synthetic_data.rst", "advanced/image_processing/auto_examples/plot_watershed_segmentation.rst", "advanced/image_processing/auto_examples/sg_execution_times.rst", "advanced/image_processing/index.rst", "advanced/index.rst", "advanced/interfacing_with_c/interfacing_with_c.rst", "advanced/mathematical_optimization/auto_examples/index.rst", "advanced/mathematical_optimization/auto_examples/plot_1d_optim.rst", "advanced/mathematical_optimization/auto_examples/plot_compare_optimizers.rst", "advanced/mathematical_optimization/auto_examples/plot_constraints.rst", "advanced/mathematical_optimization/auto_examples/plot_convex.rst", "advanced/mathematical_optimization/auto_examples/plot_curve_fitting.rst", "advanced/mathematical_optimization/auto_examples/plot_exercise_flat_minimum.rst", "advanced/mathematical_optimization/auto_examples/plot_exercise_ill_conditioned.rst", "advanced/mathematical_optimization/auto_examples/plot_gradient_descent.rst", "advanced/mathematical_optimization/auto_examples/plot_noisy.rst", "advanced/mathematical_optimization/auto_examples/plot_non_bounds_constraints.rst", "advanced/mathematical_optimization/auto_examples/plot_smooth.rst", "advanced/mathematical_optimization/auto_examples/sg_execution_times.rst", "advanced/mathematical_optimization/index.rst", "advanced/optimizing/index.rst", "advanced/scipy_sparse/bsr_array.rst", "advanced/scipy_sparse/coo_array.rst", "advanced/scipy_sparse/csc_array.rst", "advanced/scipy_sparse/csr_array.rst", "advanced/scipy_sparse/dia_array.rst", "advanced/scipy_sparse/dok_array.rst", "advanced/scipy_sparse/index.rst", "advanced/scipy_sparse/introduction.rst", "advanced/scipy_sparse/lil_array.rst", "advanced/scipy_sparse/other_packages.rst", "advanced/scipy_sparse/solvers.rst", "advanced/scipy_sparse/storage_schemes.rst", "guide/auto_examples/index.rst", "guide/auto_examples/plot_simple.rst", "guide/auto_examples/sg_execution_times.rst", "guide/index.rst", "includes/big_toc_css.rst", "includes/bigger_toc_css.rst", "index.rst", "intro/help/help.rst", "intro/index.rst", "intro/intro.rst", "intro/language/basic_types.rst", "intro/language/control_flow.rst", "intro/language/exceptions.rst", "intro/language/first_steps.rst", "intro/language/functions.rst", "intro/language/io.rst", "intro/language/oop.rst", "intro/language/python_language.rst", "intro/language/reusing_code.rst", "intro/language/standard_library.rst", "intro/matplotlib/auto_examples/exercises/index.rst", "intro/matplotlib/auto_examples/exercises/plot_exercise_1.rst", "intro/matplotlib/auto_examples/exercises/plot_exercise_10.rst", "intro/matplotlib/auto_examples/exercises/plot_exercise_2.rst", "intro/matplotlib/auto_examples/exercises/plot_exercise_3.rst", "intro/matplotlib/auto_examples/exercises/plot_exercise_4.rst", "intro/matplotlib/auto_examples/exercises/plot_exercise_5.rst", "intro/matplotlib/auto_examples/exercises/plot_exercise_6.rst", "intro/matplotlib/auto_examples/exercises/plot_exercise_7.rst", "intro/matplotlib/auto_examples/exercises/plot_exercise_8.rst", "intro/matplotlib/auto_examples/exercises/plot_exercise_9.rst", "intro/matplotlib/auto_examples/exercises/sg_execution_times.rst", "intro/matplotlib/auto_examples/index.rst", "intro/matplotlib/auto_examples/options/index.rst", "intro/matplotlib/auto_examples/options/plot_aliased.rst", "intro/matplotlib/auto_examples/options/plot_alpha.rst", "intro/matplotlib/auto_examples/options/plot_antialiased.rst", "intro/matplotlib/auto_examples/options/plot_color.rst", "intro/matplotlib/auto_examples/options/plot_colormaps.rst", "intro/matplotlib/auto_examples/options/plot_dash_capstyle.rst", "intro/matplotlib/auto_examples/options/plot_dash_joinstyle.rst", "intro/matplotlib/auto_examples/options/plot_linestyles.rst", "intro/matplotlib/auto_examples/options/plot_linewidth.rst", "intro/matplotlib/auto_examples/options/plot_markers.rst", "intro/matplotlib/auto_examples/options/plot_mec.rst", "intro/matplotlib/auto_examples/options/plot_mew.rst", "intro/matplotlib/auto_examples/options/plot_mfc.rst", "intro/matplotlib/auto_examples/options/plot_ms.rst", "intro/matplotlib/auto_examples/options/plot_solid_capstyle.rst", "intro/matplotlib/auto_examples/options/plot_solid_joinstyle.rst", "intro/matplotlib/auto_examples/options/plot_ticks.rst", "intro/matplotlib/auto_examples/options/sg_execution_times.rst", "intro/matplotlib/auto_examples/plot_axes.rst", "intro/matplotlib/auto_examples/plot_axes-2.rst", "intro/matplotlib/auto_examples/plot_bad.rst", "intro/matplotlib/auto_examples/plot_bar.rst", "intro/matplotlib/auto_examples/plot_contour.rst", "intro/matplotlib/auto_examples/plot_good.rst", "intro/matplotlib/auto_examples/plot_grid.rst", "intro/matplotlib/auto_examples/plot_gridspec.rst", "intro/matplotlib/auto_examples/plot_imshow.rst", "intro/matplotlib/auto_examples/plot_multiplot.rst", "intro/matplotlib/auto_examples/plot_pie.rst", "intro/matplotlib/auto_examples/plot_plot.rst", "intro/matplotlib/auto_examples/plot_plot3d.rst", "intro/matplotlib/auto_examples/plot_plot3d-2.rst", "intro/matplotlib/auto_examples/plot_polar.rst", "intro/matplotlib/auto_examples/plot_quiver.rst", "intro/matplotlib/auto_examples/plot_scatter.rst", "intro/matplotlib/auto_examples/plot_subplot-grid.rst", "intro/matplotlib/auto_examples/plot_subplot-horizontal.rst", "intro/matplotlib/auto_examples/plot_subplot-vertical.rst", "intro/matplotlib/auto_examples/plot_text.rst", "intro/matplotlib/auto_examples/plot_ugly.rst", "intro/matplotlib/auto_examples/pretty_plots/index.rst", "intro/matplotlib/auto_examples/pretty_plots/plot_bar_ext.rst", "intro/matplotlib/auto_examples/pretty_plots/plot_boxplot_ext.rst", "intro/matplotlib/auto_examples/pretty_plots/plot_contour_ext.rst", "intro/matplotlib/auto_examples/pretty_plots/plot_grid_ext.rst", "intro/matplotlib/auto_examples/pretty_plots/plot_imshow_ext.rst", "intro/matplotlib/auto_examples/pretty_plots/plot_multiplot_ext.rst", "intro/matplotlib/auto_examples/pretty_plots/plot_pie_ext.rst", "intro/matplotlib/auto_examples/pretty_plots/plot_plot3d_ext.rst", "intro/matplotlib/auto_examples/pretty_plots/plot_plot_ext.rst", "intro/matplotlib/auto_examples/pretty_plots/plot_polar_ext.rst", "intro/matplotlib/auto_examples/pretty_plots/plot_quiver_ext.rst", "intro/matplotlib/auto_examples/pretty_plots/plot_scatter_ext.rst", "intro/matplotlib/auto_examples/pretty_plots/plot_text_ext.rst", "intro/matplotlib/auto_examples/pretty_plots/sg_execution_times.rst", "intro/matplotlib/auto_examples/sg_execution_times.rst", "intro/matplotlib/index.rst", "intro/numpy/advanced_operations.rst", "intro/numpy/array_object.rst", "intro/numpy/auto_examples/index.rst", "intro/numpy/auto_examples/plot_basic1dplot.rst", "intro/numpy/auto_examples/plot_basic2dplot.rst", "intro/numpy/auto_examples/plot_chebyfit.rst", "intro/numpy/auto_examples/plot_distances.rst", "intro/numpy/auto_examples/plot_elephant.rst", "intro/numpy/auto_examples/plot_mandelbrot.rst", "intro/numpy/auto_examples/plot_polyfit.rst", "intro/numpy/auto_examples/plot_populations.rst", "intro/numpy/auto_examples/plot_randomwalk.rst", "intro/numpy/auto_examples/sg_execution_times.rst", "intro/numpy/elaborate_arrays.rst", "intro/numpy/exercises.rst", "intro/numpy/gallery.rst", "intro/numpy/index.rst", "intro/numpy/operations.rst", "intro/scipy/auto_examples/index.rst", "intro/scipy/auto_examples/plot_2d_minimization.rst", "intro/scipy/auto_examples/plot_connect_measurements.rst", "intro/scipy/auto_examples/plot_curve_fit.rst", "intro/scipy/auto_examples/plot_detrend.rst", "intro/scipy/auto_examples/plot_fftpack.rst", "intro/scipy/auto_examples/plot_image_filters.rst", "intro/scipy/auto_examples/plot_image_transform.rst", "intro/scipy/auto_examples/plot_interpolation.rst", "intro/scipy/auto_examples/plot_mathematical_morpho.rst", "intro/scipy/auto_examples/plot_normal_distribution.rst", "intro/scipy/auto_examples/plot_optimize_example1.rst", "intro/scipy/auto_examples/plot_optimize_example2.rst", "intro/scipy/auto_examples/plot_resample.rst", "intro/scipy/auto_examples/plot_solve_ivp_damped_spring_mass.rst", "intro/scipy/auto_examples/plot_solve_ivp_simple.rst", "intro/scipy/auto_examples/plot_spectrogram.rst", "intro/scipy/auto_examples/plot_t_test.rst", "intro/scipy/auto_examples/sg_execution_times.rst", "intro/scipy/auto_examples/solutions/index.rst", "intro/scipy/auto_examples/solutions/plot_curvefit_temperature_data.rst", "intro/scipy/auto_examples/solutions/plot_fft_image_denoise.rst", "intro/scipy/auto_examples/solutions/plot_image_blur.rst", "intro/scipy/auto_examples/solutions/plot_periodicity_finder.rst", "intro/scipy/auto_examples/solutions/sg_execution_times.rst", "intro/scipy/image_processing/image_processing.rst", "intro/scipy/index.rst", "intro/scipy/solutions.rst", "intro/scipy/summary-exercises/answers_image_processing.rst", "intro/scipy/summary-exercises/auto_examples/index.rst", "intro/scipy/summary-exercises/auto_examples/plot_cumulative_wind_speed_prediction.rst", "intro/scipy/summary-exercises/auto_examples/plot_gumbell_wind_speed_prediction.rst", "intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_complex_data.rst", "intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_complex_data_fit.rst", "intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_data.rst", "intro/scipy/summary-exercises/auto_examples/plot_optimize_lidar_data_fit.rst", "intro/scipy/summary-exercises/auto_examples/plot_sprog_annual_maxima.rst", "intro/scipy/summary-exercises/auto_examples/sg_execution_times.rst", "intro/scipy/summary-exercises/image-processing.rst", "intro/scipy/summary-exercises/optimize-fit.rst", "intro/scipy/summary-exercises/stats-interpolate.rst", "packages/index.rst", "packages/scikit-image/auto_examples/index.rst", "packages/scikit-image/auto_examples/plot_boundaries.rst", "packages/scikit-image/auto_examples/plot_camera.rst", "packages/scikit-image/auto_examples/plot_camera_uint.rst", "packages/scikit-image/auto_examples/plot_check.rst", "packages/scikit-image/auto_examples/plot_equalize_hist.rst", "packages/scikit-image/auto_examples/plot_features.rst", "packages/scikit-image/auto_examples/plot_filter_coins.rst", "packages/scikit-image/auto_examples/plot_labels.rst", "packages/scikit-image/auto_examples/plot_segmentations.rst", "packages/scikit-image/auto_examples/plot_sobel.rst", "packages/scikit-image/auto_examples/plot_threshold.rst", "packages/scikit-image/auto_examples/sg_execution_times.rst", "packages/scikit-image/index.rst", "packages/scikit-learn/auto_examples/index.rst", "packages/scikit-learn/auto_examples/plot_ML_flow_chart.rst", "packages/scikit-learn/auto_examples/plot_bias_variance.rst", "packages/scikit-learn/auto_examples/plot_california_prediction.rst", "packages/scikit-learn/auto_examples/plot_compare_classifiers.rst", "packages/scikit-learn/auto_examples/plot_digits_simple_classif.rst", "packages/scikit-learn/auto_examples/plot_eigenfaces.rst", "packages/scikit-learn/auto_examples/plot_iris_knn.rst", "packages/scikit-learn/auto_examples/plot_iris_scatter.rst", "packages/scikit-learn/auto_examples/plot_linear_model_cv.rst", "packages/scikit-learn/auto_examples/plot_linear_regression.rst", "packages/scikit-learn/auto_examples/plot_measuring_performance.rst", "packages/scikit-learn/auto_examples/plot_pca.rst", "packages/scikit-learn/auto_examples/plot_polynomial_regression.rst", "packages/scikit-learn/auto_examples/plot_separator.rst", "packages/scikit-learn/auto_examples/plot_svm_non_linear.rst", "packages/scikit-learn/auto_examples/plot_tsne.rst", "packages/scikit-learn/auto_examples/plot_variance_linear_regr.rst", "packages/scikit-learn/auto_examples/sg_execution_times.rst", "packages/scikit-learn/index.rst", "packages/statistics/auto_examples/index.rst", "packages/statistics/auto_examples/plot_airfare.rst", "packages/statistics/auto_examples/plot_iris_analysis.rst", "packages/statistics/auto_examples/plot_paired_boxplots.rst", "packages/statistics/auto_examples/plot_pandas.rst", "packages/statistics/auto_examples/plot_regression.rst", "packages/statistics/auto_examples/plot_regression_3d.rst", "packages/statistics/auto_examples/plot_wage_data.rst", "packages/statistics/auto_examples/plot_wage_education_gender.rst", "packages/statistics/auto_examples/sg_execution_times.rst", "packages/statistics/auto_examples/solutions/index.rst", "packages/statistics/auto_examples/solutions/plot_brain_size.rst", "packages/statistics/auto_examples/solutions/sg_execution_times.rst", "packages/statistics/index.rst", "packages/sympy.rst", "preface.rst", "sg_execution_times.rst"], "indexentries": {"algebraic": [[266, "index-2", false]], "diff": [[266, "index-0", false], [266, "index-4", false]], "differential": [[266, "index-4", false]], "differentiation": [[266, "index-0", false]], "dsolve": [[266, "index-4", false]], "equations": [[266, "index-2", false], [266, "index-4", false]], "integration": [[266, "index-1", false]], "matrix": [[266, "index-3", false]], "pep 255": [[9, "index-0", false]], "pep 3118": [[8, "index-0", false]], "pep 3129": [[9, "index-7", false]], "pep 318": [[9, "index-4", false], [9, "index-6", false]], "pep 342": [[9, "index-1", false]], "pep 343": [[9, "index-8", false]], "pep 380": [[9, "index-2", false]], "pep 380#id13": [[9, "index-3", false]], "pep 8": [[9, "index-5", false]], "python enhancement proposals": [[8, "index-0", false], [9, "index-0", false], [9, "index-1", false], [9, "index-2", false], [9, "index-3", false], [9, "index-4", false], [9, "index-5", false], [9, "index-6", false], [9, "index-7", false], [9, "index-8", false]], "solve": [[266, "index-2", false]]}, "objects": {}, "objnames": {}, "objtypes": {}, "terms": {"": [9, 10, 22, 24, 37, 38, 39, 40, 47, 48, 52, 54, 65, 70, 73, 74, 75, 77, 78, 79, 81, 82, 85, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 104, 108, 110, 111, 112, 113, 114, 135, 153, 171, 172, 174, 175, 181, 190, 198, 199, 202, 206, 207, 212, 215, 216, 217, 231, 234, 238, 245, 247, 248, 253, 258, 268], "0": [2, 3, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 62, 63, 65, 68, 69, 74, 76, 77, 78, 79, 81, 85, 86, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 175, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 196, 197, 198, 199, 200, 201, 202, 203, 204, 206, 207, 208, 209, 210, 211, 212, 213, 215, 216, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 253, 254, 255, 256, 257, 258, 259, 260, 261, 263, 264, 265, 266, 268], "00": [7, 36, 47, 52, 53, 69, 98, 118, 130, 155, 156, 157, 170, 187, 194, 200, 202, 213, 230, 238, 250, 251, 253, 261, 264, 268], "000": [8, 54, 76, 159, 171, 251, 253, 254, 257, 258, 260, 263, 265], "0000": 53, "000000": 265, "0000000": 202, "000000000000043": 74, "00000000e": 251, "0000ff": [239, 245], "0001": 251, "0002": 263, "0003": 53, "0004": 53, "00082232": 37, "000e": [53, 202], "001": [54, 238, 247, 253], "0010": 53, "0010934829": 202, "0015767005": 202, "001576700508": 202, "002": 54, "00250049": 258, "003": [260, 265], "004": 54, "005": [54, 260, 263, 265], "00640699": 37, "007": [215, 260, 265], "0077266": 8, "008": 54, "008151": 265, "009865032686848034": 258, "00ff00": [239, 245], "01": [14, 17, 25, 28, 30, 33, 35, 46, 48, 52, 53, 65, 105, 108, 110, 117, 118, 121, 124, 140, 142, 144, 145, 146, 147, 148, 150, 151, 152, 153, 154, 155, 178, 179, 182, 183, 185, 192, 200, 202, 246, 250, 268], "010": 265, "011": 54, "012": [101, 118, 268], "01268961003167922": 251, "0126896100317": 251, "013": [103, 115, 118, 263, 268], "0134": [260, 265], "014": [106, 107, 116, 118, 268], "015": 265, "017": [49, 52, 54, 111, 112, 113, 114, 118, 268], "018": [104, 118, 260, 268], "01829761": 8, "0184": 263, "019": [102, 118, 268], "019191919191918": 239, "01e": 260, "02": [12, 15, 16, 19, 20, 21, 23, 24, 25, 26, 27, 30, 34, 47, 48, 142, 143, 144, 145, 146, 147, 148, 150, 151, 152, 153, 154, 156, 181, 187, 206, 216], "020": [22, 36, 109, 118, 268], "021": [54, 263], "023e": 53, "024451": 265, "025": [122, 123, 125, 127, 128, 129, 130, 133, 134, 135, 139, 253, 254, 257, 258, 260, 263, 265], "027": [260, 265], "0279": 253, "02d": 37, "03": [47, 50, 54, 86, 118, 194, 253, 257, 258, 265], "031": [150, 155, 260, 265, 268], "033": [130, 156, 268], "0334": 260, "034": [134, 156, 268], "036": [140, 156, 253, 268], "038": [149, 155, 268], "0388": 253, "039": [93, 98, 268], "04": [50, 143, 250, 253, 268], "040": [146, 155, 260, 268], "041": [51, 52, 138, 156, 253, 268], "0415": [260, 265], "044": [28, 36, 108, 118, 143, 155, 253, 257, 268], "045": [30, 36, 268], "046": [253, 260], "0460": 253, "047": [44, 52, 242, 250, 268], "048": [91, 98, 119, 156, 167, 170, 187, 194, 253, 268], "0484": 253, "049": [50, 52, 94, 98, 128, 156, 161, 170, 268], "05": [17, 36, 41, 43, 48, 105, 122, 129, 132, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 152, 153, 154, 157, 168, 172, 178, 182, 183, 185, 206, 230, 233, 234, 237, 260, 263, 268], "050": [137, 156, 253, 268], "051": [90, 98, 142, 152, 155, 246, 250, 253, 268], "052": [68, 69, 118, 190, 194, 260, 265, 268], "053": [45, 52, 124, 132, 156, 251, 268], "05336566": 8, "054": 54, "055": [95, 98, 180, 194, 268], "056": [92, 98, 122, 156, 260, 265, 268], "05636": 215, "05636228": 211, "058": [120, 148, 155, 156, 268], "058e": 53, "059": [88, 98, 129, 156, 222, 230, 268], "06": [47, 52, 53, 54, 187, 202, 230, 234, 253, 254, 257, 258, 260, 263, 268], "060": [25, 36, 135, 156, 268], "061": [96, 98, 254, 265, 268], "062": [6, 7, 153, 155, 268], "06210169418915616": 251, "0621016941892": 251, "06250005": 65, "06250007": 65, "0625002": 65, "06250028": 65, "06250044": 65, "06250083": 65, "062847e": 257, "063": [168, 170, 268], "064": [35, 36, 268], "0649999999999995": 81, "066": [210, 213, 260, 268], "068": [207, 213, 247, 250, 268], "069": [164, 170, 263, 268], "06e": 257, "07": [21, 42, 53, 171, 251, 258, 261, 263, 268], "070": [188, 194, 268], "071e": 53, "072": [136, 156, 255, 260, 261, 265, 268], "073": [110, 118, 220, 230, 268], "07369": 265, "07369058781701142": 254, "07396163283": 202, "074": [226, 230, 268], "075": [162, 170, 268], "076": 253, "077": [169, 170, 206, 209, 213, 258, 268], "079": [123, 156, 166, 170, 268], "08": [53, 86, 251, 257], "080": [144, 155, 191, 194, 268], "081": [34, 36, 147, 155, 268], "082": [208, 213, 254, 265, 268], "0821": 260, "082172638": 265, "082172638183": 265, "0837": 263, "0848": 253, "08553692": 175, "086": [121, 126, 156, 268], "0861": 258, "08614608": 258, "087": [15, 36, 268], "0873": 260, "088099970": 265, "089": [43, 52, 223, 230, 260, 268], "09": [52, 53, 202, 215, 261, 268], "093": [240, 250, 258, 260, 261, 265, 268], "094352": 258, "095": [163, 170, 268], "096": [133, 156, 268], "097": 260, "097222222222214": 212, "098": [185, 194, 268], "098612288668": 8, "099": [219, 228, 230, 244, 250, 254, 265, 268], "0j": [77, 78], "0x": [9, 37, 172, 201, 202, 231], "0x004af4f5": 10, "0x01": 8, "0x0103": 8, "0x02": 8, "0x0201": 8, "0x03": 8, "0x0301": 8, "0x04": 8, "0x0403": 8, "0x04030201": 8, "0x080dc97a": 10, "0x080ddd23": 10, "0x496780": 10, "0x7f30d02efc10": 76, "0x7f5b013325a0": 253, "0x7f5b015911c0": 238, "0x7f5b0249c0e0": 257, "0x7f5b0249eed0": 260, "0x7f5b02545790": 247, "0x7f5b029f5ac0": 245, "0x7f5b029f65d0": [249, 251], "0x7f5b035ac350": 234, "0x7f5b03713140": 237, "0x7f5b3ac966f0": 181, "0x7f5b3acab410": 198, "0x7f5b3ae252e0": 192, "0x7f5b3aef46e0": 198, "0x7f5b3b537ec0": 177, "0x7f5b3b907b30": 181, "0x7f5b3bd745c0": 199, "0x7f5b3bd76ab0": 198, "0x7f5b3be44590": 179, "0x7f5b41101d00": 165, "0x7f5b41410500": 165, "0x7f5b414796d0": 187, "0x82f064c": 10, "0x85371b0": 10, "0x85371ec": 10, "0x8537478": 10, "0x853ecf0": 10, "0x853ed20": 10, "0x86c0690": 10, "0xb74214c4": 85, "0xb7421534": 85, "0xb7f93a64": 10, "1": [2, 6, 7, 8, 9, 10, 12, 13, 15, 16, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59, 60, 63, 65, 66, 69, 70, 73, 74, 76, 77, 78, 79, 81, 82, 85, 86, 87, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 158, 159, 163, 166, 167, 168, 169, 171, 172, 175, 177, 178, 179, 181, 184, 185, 186, 187, 188, 190, 191, 192, 193, 197, 198, 199, 201, 202, 203, 204, 205, 206, 207, 209, 212, 213, 215, 216, 222, 224, 225, 226, 227, 231, 233, 234, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 251, 253, 254, 255, 257, 258, 259, 260, 263, 264, 265, 266, 268], "10": [8, 10, 12, 15, 17, 20, 22, 24, 26, 28, 29, 30, 34, 37, 39, 41, 42, 46, 48, 53, 54, 59, 62, 65, 76, 77, 78, 79, 81, 85, 86, 89, 97, 98, 102, 105, 106, 108, 110, 112, 115, 117, 123, 127, 133, 134, 144, 146, 151, 152, 157, 159, 171, 172, 175, 185, 187, 188, 190, 196, 198, 199, 201, 202, 203, 204, 214, 215, 216, 225, 231, 234, 236, 238, 241, 245, 246, 247, 251, 263, 265], "100": [8, 10, 29, 33, 37, 41, 46, 47, 48, 53, 54, 65, 68, 70, 76, 78, 90, 159, 172, 175, 178, 179, 180, 189, 190, 201, 202, 204, 206, 207, 216, 231, 238, 239, 242, 245, 251, 266], "1000": [8, 22, 28, 37, 45, 54, 65, 159, 169, 175, 193, 202, 234], "10000": [37, 175], "100000": [77, 186, 202, 203], "1000x1000": 65, "1001121": 265, "1008": 260, "100j": [46, 47, 48], "100k": [235, 243], "101": [49, 51, 186, 194, 253, 268], "1016": 215, "102": [77, 89, 98, 268], "1023": [37, 201, 202], "1024": [37, 77, 135, 153, 157, 172, 231], "102486": 257, "1026": 8, "1027": 8, "1038437": 265, "104": [97, 98, 193, 194, 268], "1042": 175, "105": 175, "105263": 265, "106": [65, 125, 131, 156, 265, 268], "106594927135": 265, "107": [54, 145, 155, 249, 250, 257, 261, 265, 268], "10764513121260137": 258, "107e": 253, "108": [53, 196, 200, 268], "109": [263, 265], "1094": 54, "109e": 253, "11": [1, 8, 9, 10, 12, 14, 26, 37, 39, 42, 48, 52, 53, 54, 59, 76, 77, 79, 81, 85, 86, 102, 104, 108, 109, 110, 111, 112, 113, 114, 117, 159, 171, 172, 175, 230, 236, 238, 252, 254, 257, 258, 260, 261, 263, 265, 267, 268], "110": [26, 36, 151, 155, 265, 268], "110e": 53, "111": [53, 54, 89, 90, 91, 92, 93, 94, 95, 96, 97, 143, 145, 157, 177, 188, 202, 247, 257, 265], "11111111": 53, "111646": 258, "112": [54, 156], "113": [37, 257, 265], "113844343": 202, "114": [178, 179, 194, 204, 268], "115": 265, "11527915993744e": 53, "11557c": [139, 154], "11585036": 202, "115e": 53, "116": [221, 229, 230, 268], "1168": 231, "117": [46, 52, 268], "1172": 175, "1175": 175, "1177": 175, "118": 265, "119": [253, 265], "11bee483665d": 39, "12": [1, 8, 9, 10, 15, 19, 20, 23, 25, 32, 39, 41, 42, 48, 53, 54, 59, 76, 77, 79, 81, 85, 86, 107, 116, 122, 139, 154, 157, 159, 171, 172, 175, 181, 182, 185, 187, 196, 202, 209, 226, 227, 228, 233, 234, 236, 238, 251, 253, 263, 265, 267], "120": [29, 37, 258, 265], "121": [24, 28, 33, 219, 221, 223, 228], "122": [24, 28, 33, 127, 156, 219, 221, 223, 228, 268], "123": 265, "12310563": 175, "1234": 8, "12345": 77, "1235": 236, "124": [54, 254, 265], "1241": 175, "125": [37, 74], "126": 231, "127": [37, 253], "1273": 175, "1274715": 54, "1277": 175, "128": [15, 79, 101, 103, 171, 265], "129": [258, 265], "13": [2, 8, 29, 37, 39, 47, 53, 54, 76, 77, 79, 81, 85, 86, 155, 157, 159, 171, 172, 175, 196, 202, 203, 224, 231, 238, 254, 257, 263, 267], "130": 257, "131": [12, 14, 16, 17, 19, 20, 26, 30, 32, 34, 35, 36, 226, 229, 234, 268], "132": [12, 14, 17, 19, 20, 26, 30, 32, 34, 35, 79, 226, 229, 265], "133": [12, 14, 17, 19, 20, 26, 30, 32, 34, 35, 37, 226, 229, 265], "134": [37, 78, 171, 265], "1346": 175, "1347": [251, 257], "135": 175, "13527605": [201, 202], "136": [253, 260], "137": 265, "139": 265, "1398": 181, "14": [2, 8, 9, 24, 33, 37, 39, 43, 48, 50, 53, 54, 76, 77, 79, 81, 85, 86, 106, 115, 159, 172, 202, 233, 238, 267], "140": 265, "140028748541120": 77, "141": [15, 16, 21, 25, 37, 182, 185, 199, 200, 225, 227, 268], "14112001": 175, "14159265": 202, "14159265358979": 266, "14159265358979312": 203, "14159265359": 39, "142": [15, 16, 21, 25, 157, 182, 185, 225, 227], "143": [15, 16, 21, 25, 182, 185, 225, 227, 265], "144": [15, 16, 21, 25, 182, 185, 202, 225, 227, 253], "145": [37, 238, 250, 268], "146": [254, 265], "147": [260, 265], "1475": 175, "148": 253, "149": 253, "15": [8, 10, 21, 24, 33, 37, 39, 44, 46, 53, 54, 77, 79, 81, 85, 86, 106, 108, 110, 159, 172, 183, 211, 215, 224, 234, 235, 238, 247, 251, 266], "150": [238, 251, 254, 265], "1500": [248, 251], "151": [23, 183, 201, 202, 253, 260], "152": [23, 183], "153": [23, 37, 183], "1536": [201, 202], "154": [23, 183, 225, 230, 260, 268], "1544": 175, "155": [23, 183], "1552": 258, "156": [10, 260], "15625": 8, "157": [27, 36, 265, 268], "1577": 175, "158": [10, 254, 265], "1585": 253, "159": [253, 260, 265], "16": [8, 16, 21, 25, 33, 35, 37, 39, 48, 53, 54, 77, 79, 81, 85, 86, 89, 97, 101, 102, 103, 104, 106, 107, 109, 111, 112, 113, 114, 115, 116, 119, 120, 142, 157, 171, 175, 201, 202, 215, 225, 227, 231, 238, 250, 254], "1600": 8, "16000": 8, "16000l": 8, "161": 253, "1610": 175, "162": [29, 36, 46, 268], "16227766": 175, "162e": 53, "1630": 10, "164": [227, 230, 265, 268], "165": [142, 143, 144, 145, 146, 148, 150, 152, 153, 154], "1654": [85, 86], "1659": 10, "166": [54, 253, 263, 265], "167": 260, "1671": [85, 86], "169": [254, 260, 265], "1697": 10, "1699": 204, "16l": 8, "17": [2, 39, 53, 54, 77, 79, 81, 85, 86, 118, 159, 194, 196, 202, 238, 250, 257, 258, 267], "1712": 175, "1715": 175, "171694552": 8, "172": [54, 263, 265], "1722": 39, "173": [260, 265, 268], "17366l": 8, "174": 251, "17402l": 8, "175": [245, 250, 268], "176": [31, 36, 268], "1762": 181, "177": 251, "178": [251, 254, 265], "17805383": 202, "179": [10, 48, 251], "1793": 10, "1797": 251, "18": [8, 39, 54, 77, 79, 80, 81, 85, 86, 159, 196, 202, 233, 257, 260, 261, 265], "180": [54, 251], "180581": 258, "180808080808081": 239, "181": [251, 254, 263, 265], "182": [33, 36, 251, 265, 268], "183": 251, "183e": 53, "185": [54, 254, 265], "1850": 238, "18627": 8, "187": 171, "1877": 257, "188": [54, 265], "1899": 258, "19": [24, 37, 39, 54, 59, 77, 79, 81, 85, 86, 196, 202, 238, 253, 254, 257, 258, 260, 263, 265], "190": [13, 36, 201, 202, 254, 260, 265, 268], "1900": 158, "1901": 158, "1902": 158, "1903": [6, 8, 158], "191": 253, "1910": [6, 8], "1913": 175, "1917": [6, 8], "1918": [6, 8], "192": 54, "1920929e": 171, "192e": 187, "193": [54, 260], "1931": 172, "194": 260, "195": 54, "196": 265, "198": [175, 260], "1990": 251, "1991": 265, "1997": 251, "1d": [10, 38, 41, 66, 73, 159, 160, 170, 173, 175, 176, 189, 194, 202, 216, 251, 265, 268], "1e": [8, 10, 46, 48, 53, 54, 65, 79, 171, 172, 199, 202, 207], "1e3": 158, "1e4": 54, "1e6": [62, 171], "1e7": 54, "1e9": 81, "1f": [43, 48, 50], "1j": [8, 78, 159, 166, 172], "1m": 215, "1x": 202, "1x1": [55, 90, 157], "2": [2, 8, 9, 10, 12, 15, 16, 19, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 33, 34, 35, 39, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59, 60, 62, 63, 65, 66, 68, 70, 73, 74, 76, 77, 78, 79, 80, 81, 82, 85, 86, 87, 89, 91, 92, 93, 94, 95, 96, 97, 98, 99, 107, 108, 109, 110, 116, 117, 119, 120, 121, 123, 124, 126, 127, 128, 129, 130, 131, 132, 133, 134, 136, 137, 138, 139, 140, 143, 144, 146, 147, 148, 149, 150, 151, 152, 154, 156, 157, 158, 159, 164, 166, 168, 169, 171, 172, 175, 176, 177, 178, 179, 181, 183, 184, 187, 188, 190, 191, 194, 196, 198, 201, 203, 204, 205, 206, 207, 213, 215, 216, 222, 225, 226, 227, 229, 231, 233, 234, 235, 236, 238, 239, 240, 244, 245, 246, 247, 248, 249, 251, 253, 254, 257, 258, 259, 260, 263, 265, 266, 268], "20": [8, 10, 12, 16, 19, 20, 21, 26, 29, 30, 31, 35, 37, 39, 43, 44, 48, 50, 51, 53, 54, 60, 79, 81, 85, 86, 108, 110, 119, 129, 133, 136, 148, 151, 157, 158, 159, 161, 167, 171, 172, 175, 181, 184, 196, 202, 209, 227, 231, 233, 234, 238, 242, 247, 251, 254, 257, 258, 265], "200": [8, 17, 37, 65, 77, 121, 124, 158, 167, 169, 175, 184, 202, 234, 251, 258], "2000": [158, 163, 253], "20000": [8, 251], "200000": 265, "2001": 253, "2008": [8, 215], "2009": 215, "200mb": 238, "201": [19, 36, 268], "2011": 0, "2015": 0, "202": [184, 194, 268], "2024": [2, 73, 86, 253, 254, 257, 258, 260, 263], "203": [21, 36, 181, 194, 268], "204": 54, "2048": [201, 202], "206": 253, "2060": 265, "20640": 251, "208": [54, 265], "20841759": 202, "20e": 253, "20j": 172, "21": [8, 39, 54, 65, 77, 79, 81, 83, 85, 86, 159, 175, 196, 202, 203, 207, 212, 216, 234, 238, 251, 258, 265], "210": [224, 231, 253], "2105": 10, "210526": 265, "21087": 8, "211": 253, "214": [233, 250, 268], "2145": 175, "2147483647": 171, "2148380": 10, "215": [20, 36, 253, 268], "216": [248, 250, 253, 268], "218": 265, "219": 253, "219e": 202, "22": [8, 39, 54, 81, 85, 86, 156, 159, 175, 199, 238, 265], "220": [19, 20, 37], "220446049250313e": 171, "22222222": 53, "222e": 53, "2250": 175, "22563948": 159, "22640": 253, "23": [29, 37, 39, 41, 54, 81, 83, 85, 86, 159, 196, 202, 216, 238, 251, 258], "230": [19, 20, 37, 172], "231": [41, 52, 268], "234": 48, "2359296": 37, "236": [10, 39, 254, 263, 264, 265, 268], "23606798": [175, 202], "238": [254, 265], "239": 54, "23e": 253, "24": [2, 8, 33, 36, 37, 39, 54, 81, 85, 86, 126, 137, 138, 139, 144, 154, 159, 175, 238, 266, 267], "240": [8, 212, 213, 268], "2412": 10, "24264069": 175, "2428": 253, "2437": 10, "2441": 10, "2448": 175, "2453": 54, "245335346574177": 254, "24533535": 265, "246": [189, 194, 263, 268], "247": 10, "248": 257, "24x12x6": 172, "25": [39, 48, 54, 74, 78, 81, 85, 86, 102, 108, 110, 121, 122, 125, 130, 131, 139, 145, 149, 154, 157, 159, 172, 185, 189, 196, 201, 202, 209, 233, 236, 238, 251, 260, 265], "250": [24, 36, 37, 53, 265, 268], "2500": 65, "250e": 53, "2517": 10, "252": 263, "2525": 10, "253": 39, "255": [8, 9, 29, 37, 158, 231], "256": [8, 12, 15, 21, 22, 24, 26, 28, 34, 37, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 102, 104, 106, 107, 109, 111, 112, 113, 114, 115, 116, 123, 130, 144, 150, 157, 165, 170, 204, 226, 231, 254, 265, 268], "256016": 54, "257": 8, "2571": 10, "258": [8, 236, 250, 268], "259": 8, "2598": 10, "26": [10, 39, 54, 81, 85, 86, 238, 265], "260": 8, "2605": 202, "2686": 253, "27": [10, 39, 53, 54, 74, 81, 85, 86, 211, 215, 238, 259, 260], "2706": 39, "271": 171, "272727272728": 8, "273": 10, "274": [257, 265], "27446968": [8, 10, 12, 15, 16, 19, 20, 21, 22, 24, 25, 26, 28, 30, 33, 34, 37, 45, 47, 49, 53, 63, 65, 159, 163, 167, 175, 179, 181, 184, 193, 202, 226, 234, 245, 247, 249, 251, 257, 258, 265], "275": 253, "2750": [260, 265], "276": 263, "278": [201, 202], "2782": 10, "27874": 54, "279": 257, "279415": 265, "28": [8, 10, 33, 35, 37, 39, 54, 81, 86, 175, 196, 202, 209, 227, 231, 238, 253, 258, 265], "2808": 10, "281320": 258, "282": [14, 36, 268], "287": [54, 253], "2884": 10, "29": [10, 54, 81, 86, 237, 238, 251, 253, 254, 265], "290": [19, 20, 37], "291": 251, "2922": 10, "293": 54, "29425": 258, "2948": 265, "295": 54, "295030": 265, "296": [47, 52, 211, 213, 268], "297": 251, "2983": [254, 265], "2998": [260, 265], "2c": [139, 154], "2cm": 251, "2d": [37, 62, 66, 132, 149, 157, 159, 160, 170, 172, 173, 175, 178, 198, 216, 232, 237, 248, 250, 251, 258, 265, 268], "2e": 48, "2e3": 158, "2e6": 10, "2f": [47, 48, 122, 157, 206, 207], "2j": 159, "2nd": [38, 73, 172, 202], "2rc0": [73, 267], "2x": 158, "2x2": [53, 65], "2y": 191, "3": [2, 8, 9, 10, 12, 14, 15, 16, 17, 19, 23, 25, 26, 28, 29, 30, 32, 33, 34, 35, 37, 39, 41, 42, 43, 44, 45, 46, 48, 49, 50, 51, 54, 55, 56, 57, 58, 59, 60, 63, 65, 74, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 89, 97, 98, 99, 107, 108, 110, 111, 113, 116, 117, 119, 120, 123, 125, 126, 127, 128, 136, 139, 142, 143, 144, 145, 146, 147, 148, 150, 152, 153, 154, 157, 158, 159, 161, 163, 167, 169, 171, 172, 175, 177, 178, 179, 181, 182, 183, 185, 188, 190, 191, 199, 201, 202, 203, 204, 207, 209, 211, 215, 216, 219, 221, 223, 224, 225, 226, 227, 228, 231, 233, 234, 235, 236, 237, 238, 239, 241, 242, 243, 245, 246, 247, 249, 251, 253, 254, 255, 257, 258, 259, 260, 263, 265, 266, 268], "30": [10, 17, 32, 37, 41, 48, 54, 81, 86, 89, 97, 157, 159, 162, 175, 183, 193, 198, 201, 202, 206, 209, 211, 215, 238, 241, 242, 247, 251, 253, 263, 265], "300": [108, 110, 158, 172, 175, 225, 231, 238, 243, 250, 258, 268], "30000": 158, "3008": 10, "303": 175, "304": 175, "30641113": 188, "306440997": 202, "306e": [187, 202], "308": [253, 265], "30e3": 158, "31": [10, 49, 54, 81, 86, 159, 171, 175, 196, 202, 238, 253], "310519": 85, "3110": 258, "3117": 10, "3118": 8, "312": 48, "3122": 258, "3129": 9, "314": 260, "3141": 10, "3149": 39, "318": [9, 258], "32": [8, 10, 30, 37, 54, 81, 86, 139, 154, 159, 171, 175, 196, 202, 203, 216, 231, 238, 253, 260], "320": [19, 20, 27, 37], "32000l": 8, "321": [198, 200, 268], "324": [177, 194, 263, 268], "326021": 265, "328193": 8, "32891964": 265, "33": [10, 53, 54, 81, 86, 159, 196, 202, 238, 251, 253], "330": 172, "3322": 8, "33333333": [53, 158], "337": 257, "3375593674654274": 241, "338": 253, "34": [8, 10, 54, 81, 86, 147, 159, 203, 216, 237, 238, 251, 263], "340": [27, 37, 258], "341": [17, 36, 268], "342": 9, "34228868687": 265, "343": 9, "343g": 10, "345": 10, "346": 263, "3474": 10, "34928": [85, 86], "35": [10, 44, 54, 81, 86, 158, 159, 196, 207, 233, 237, 238, 251, 253, 263, 265], "350": [192, 194, 224, 231, 268], "35181": [85, 86], "352": 263, "352j": 78, "353": 200, "354": 10, "356": 260, "358": 258, "359": 263, "36": [8, 10, 81, 86, 238, 265], "360": 10, "364": 268, "365": [10, 196, 260], "365553e": 258, "366": 52, "367": 10, "368": 265, "368421": 265, "369": 175, "37": [10, 81, 86, 171, 196, 202, 237, 238, 251, 253, 254, 265], "370": [225, 231], "372": 265, "373": 263, "3750": 10, "38": [81, 86, 196, 202, 237, 238, 251, 253, 254, 265], "380": 9, "38200": 158, "38250769": 159, "384185791015625e": 53, "385": 251, "38501": 258, "387": 10, "3890561": 175, "39": [81, 86, 199, 237, 238, 263, 265], "390": 258, "3909": 10, "391": [234, 241, 250, 268], "392": 257, "3929": 54, "395": 237, "397": 265, "3cm": 251, "3d": [73, 75, 99, 141, 155, 156, 258, 265, 268], "3rd": 77, "3x": 158, "3x2": 55, "4": [2, 3, 8, 9, 10, 12, 13, 15, 19, 20, 22, 23, 24, 25, 26, 27, 28, 29, 32, 33, 34, 37, 39, 41, 42, 43, 47, 48, 50, 53, 54, 55, 56, 57, 58, 59, 63, 65, 74, 76, 77, 78, 79, 81, 82, 85, 86, 87, 90, 91, 98, 99, 106, 107, 108, 110, 115, 116, 120, 121, 122, 124, 125, 126, 128, 131, 133, 136, 137, 138, 139, 140, 143, 145, 147, 149, 151, 154, 157, 159, 169, 171, 172, 175, 177, 178, 179, 180, 184, 188, 189, 190, 191, 192, 193, 197, 200, 201, 202, 203, 209, 220, 221, 225, 226, 229, 231, 233, 234, 235, 236, 237, 238, 239, 240, 242, 243, 245, 246, 247, 251, 253, 254, 255, 257, 258, 259, 260, 265, 266, 267, 268], "40": [8, 19, 20, 33, 37, 81, 86, 117, 140, 159, 175, 196, 237, 247, 251, 265], "400": [29, 37, 238], "4000": 158, "401": 166, "40472": 8, "4053": 260, "409": 253, "4096": 238, "40e": [253, 263], "41": [54, 81, 86, 159, 237, 251, 254, 265], "410174971340889": 241, "413": [10, 54], "414": 263, "4140878441244694": 263, "41421356": 175, "41421356237": 171, "41500": 158, "417": 263, "4174": 253, "4176": 253, "418": [254, 265], "4188": 10, "419": [32, 36, 268], "42": [81, 86, 159, 206, 237, 247, 251, 260, 265], "420": 10, "424": [201, 202], "42400": 8, "4250": 265, "427": [254, 261, 268], "4294967295": 171, "42e": 253, "43": [54, 86, 159, 203, 251, 260], "431579": 265, "432": [10, 258], "433": 175, "4332": 258, "43322435": 258, "438": [175, 258], "4385": 10, "439": 175, "43e": 258, "44": [8, 35, 54, 86, 159, 227, 231, 251, 254, 265], "441": [10, 258, 260, 265], "4413": 10, "4417677473": 53, "442": [241, 251], "444": 257, "444444": 265, "44444444": 53, "4445287677858": 265, "445": 265, "4454": 10, "446": 253, "448": 253, "45": [23, 37, 86, 159, 201, 202, 233, 251, 265], "450": [237, 251], "4500": 265, "451": 231, "45532": 253, "457": [54, 260, 265], "458": [182, 194, 268], "459": [201, 202], "46": [86, 196, 202, 237, 251, 253], "461": 253, "462": 253, "462e": 202, "46563759638": 265, "466": [253, 265], "467": 155, "468": [23, 36, 254, 265, 268], "469": 10, "46e": 263, "47": [42, 86, 158, 212, 237, 251], "47200": 158, "47213595": 175, "472222222222214": 196, "473684": 265, "47487373504": 53, "475": 10, "476043": 257, "478": [254, 265], "479": 54, "47924": 215, "47924562": 211, "47948183": 188, "48": [54, 74, 86, 201, 202, 251, 253], "480": 253, "48026784261067": 37, "4812": 53, "48200": 158, "4821": [254, 265], "48300": 158, "483e": 53, "4844": 8, "487e": 53, "48984931": 159, "49": [10, 54, 207, 237], "490": 39, "494": [259, 261, 263, 268], "496": 260, "49611818": [201, 202], "499": 202, "499e": 53, "4cm": 251, "4e": [253, 263], "4e3": 158, "4i": 78, "4j": 159, "4th": [172, 178, 201, 202, 245, 251], "4y": 202, "5": [1, 2, 8, 9, 10, 12, 13, 14, 15, 16, 21, 23, 24, 25, 26, 30, 31, 35, 37, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59, 60, 62, 63, 65, 74, 76, 77, 78, 79, 81, 82, 85, 86, 87, 89, 90, 91, 92, 94, 95, 96, 97, 98, 99, 101, 103, 104, 105, 106, 107, 108, 110, 111, 112, 113, 114, 115, 117, 119, 120, 121, 122, 123, 124, 126, 127, 128, 130, 133, 134, 135, 136, 137, 138, 140, 142, 143, 144, 146, 148, 151, 152, 153, 157, 158, 159, 164, 166, 168, 171, 172, 175, 177, 178, 179, 180, 181, 182, 185, 186, 187, 188, 189, 190, 192, 196, 197, 201, 202, 203, 206, 209, 212, 219, 224, 226, 227, 231, 233, 234, 235, 236, 237, 238, 240, 241, 242, 243, 244, 245, 246, 248, 249, 251, 253, 254, 257, 258, 259, 260, 263, 265, 266, 267, 268], "50": [10, 17, 20, 33, 37, 45, 53, 89, 97, 157, 159, 166, 172, 178, 179, 183, 185, 186, 201, 202, 204, 206, 207, 216, 224, 231, 234, 238, 246, 247, 251], "500": [202, 248, 251, 265], "5000": 54, "50000": 172, "50012043": [179, 202], "500e": 53, "502": [254, 265], "503": [260, 265], "50514907": 258, "506": 39, "5062255844787": 8, "507": 265, "50851229": 159, "51": [159, 186, 265], "510": [27, 37, 265], "512": [117, 182, 201, 202, 231, 257], "513": 8, "513131313131313": 239, "51954079": [201, 202], "52": [10, 35, 159, 196, 202, 227, 231, 251], "520": [260, 261, 268], "526": 253, "528e": 253, "53": [10, 53, 159, 257], "530": [27, 37, 260], "530e": 253, "531": 260, "5314909993118918": 235, "533": [18, 36, 268], "534": 260, "535": 175, "536": [8, 256, 261, 268], "537e": 53, "538": 175, "54": [54, 159, 175, 254, 265], "5403023058681398": 39, "54321": 77, "544": [253, 265], "549": [201, 202], "55": [10, 159, 181, 203, 233, 251], "551": 54, "55555556": 53, "5578": 77, "558": 253, "56": [54, 196, 202, 251], "560": [257, 258], "5601357400786612e": 53, "56574395": 202, "568": [175, 265], "569": [42, 52, 268], "57": [12, 26, 265], "570509": 265, "57079633": [179, 202], "573": 258, "5752": 77, "577": 258, "578947": 265, "579": 258, "58": [33, 37, 53, 54, 196, 202, 203, 237], "5811388300841898": 53, "583822": 265, "589e": 187, "58e": [254, 265], "59": [54, 196, 202, 251], "5915": 77, "592": 194, "59353096": 159, "593e": 53, "594454": 10, "595": 263, "5969": 265, "596979": 265, "597": 257, "5976027": 238, "59815003": 175, "5cm": 251, "5e": 202, "5j": 77, "5x5": 175, "6": [2, 8, 10, 13, 17, 24, 28, 33, 37, 39, 41, 43, 44, 48, 50, 53, 54, 55, 57, 58, 59, 63, 65, 76, 77, 79, 80, 81, 82, 85, 86, 87, 90, 98, 99, 110, 119, 126, 128, 136, 137, 138, 145, 146, 157, 158, 159, 165, 171, 172, 175, 179, 181, 184, 187, 188, 193, 201, 202, 203, 208, 209, 210, 211, 215, 231, 233, 234, 236, 237, 238, 244, 245, 247, 248, 249, 251, 254, 258, 259, 260, 263, 265, 266, 267, 268], "60": [12, 26, 37, 159, 204, 237, 246, 251, 265], "600": [10, 251], "601": 166, "602060": 265, "604": [175, 253], "604678": 10, "60555128": 175, "607": 265, "609977": 265, "61": [203, 251], "6100": 158, "615": [85, 86, 263], "61536465": 159, "619": 265, "62": [196, 202, 265], "624": [98, 253], "625": 260, "6258": 263, "6277298383706738e": 53, "63": [25, 37, 237, 254, 260, 265], "630637192365927e": 53, "63e9c24443644feeb8d4b2a40cf1b480": [85, 86], "64": [8, 21, 25, 37, 171, 215, 237, 248, 251, 265], "64277250": 265, "643": 265, "644": 231, "645": [10, 54], "64613018": 159, "647": [260, 265], "64803824": 8, "64e466df6d64": 81, "65": [54, 89, 157, 204, 237, 265], "650": 53, "651": 258, "654": 260, "656489006717": 8, "65685425": 175, "659": [254, 265], "66": [142, 143, 144, 145, 146, 147, 148, 150, 152, 153, 154, 175], "660": 172, "66017736": 202, "661": 265, "6635": [254, 265], "666": 258, "66666667": 53, "669": 253, "67": [8, 33, 37, 53, 238, 258], "673": [175, 253], "67305985": 8, "674": 263, "675": 260, "676135e": 258, "68": 265, "681": 265, "683": 265, "683196084584229": 263, "684": 253, "68556194": 258, "6856": 258, "69": [8, 54, 175, 260], "693147180559": 8, "6940": 53, "694605": 265, "696": 263, "6th": 77, "7": [2, 8, 10, 37, 39, 44, 46, 48, 53, 54, 56, 59, 65, 76, 77, 79, 81, 82, 85, 86, 87, 98, 99, 110, 117, 157, 159, 171, 172, 175, 178, 187, 201, 202, 204, 209, 213, 223, 224, 226, 231, 233, 236, 237, 238, 251, 253, 258, 260, 263, 265, 267, 268], "70": [33, 37, 48, 158, 159, 192], "701": 265, "70200": 158, "703": 265, "70363": 215, "70363341": 211, "704": [224, 230, 265, 268], "7046": 257, "70578": 202, "707570": 265, "708": 10, "709": 265, "709e": 53, "71": [251, 265], "710": [253, 263], "714": [154, 155, 268], "71673619": [201, 202], "717": [235, 250, 268], "718": [253, 261, 268], "71828183": 175, "72": [101, 102, 103, 104, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 121, 124, 140, 145, 147, 157, 251, 260, 265], "722": 258, "722222222222214": 206, "72727272727": 8, "72e": 265, "73": [251, 265], "730": [139, 156, 268], "731": 265, "732": 260, "733": 253, "73415": 175, "736": 175, "736842": 265, "738": 175, "739": 175, "74": 265, "740": 253, "742": 257, "747": 230, "748": [10, 253], "749": [237, 250, 268], "75": [8, 44, 102, 108, 110, 123, 125, 135, 139, 140, 144, 145, 153, 154, 157, 175, 233, 237, 238], "753": [254, 265], "756": 258, "7568025": 175, "758": 265, "759": 265, "76": [237, 257], "760281": 257, "76096066": 202, "765000": 265, "76547217": [201, 202], "767": [37, 201, 202], "768": [37, 172, 231, 260], "769": 8, "77": [81, 158, 159], "770": 231, "77261617232": 265, "773": 265, "77777778": 53, "778394": 10, "78": [251, 265], "780": [12, 36, 268], "781": 265, "781e": 53, "782": [197, 200, 268], "783471": 257, "784201940": 265, "785": [254, 265], "78e": 263, "79": [8, 54], "791": 253, "792": 260, "792419": 265, "793": 265, "795": [239, 250, 268], "796": 265, "799814240254": 8, "8": [2, 8, 9, 10, 12, 19, 20, 21, 24, 25, 26, 27, 37, 39, 41, 43, 46, 50, 53, 54, 59, 62, 65, 74, 76, 77, 79, 81, 85, 86, 87, 89, 90, 91, 92, 93, 94, 95, 97, 98, 99, 102, 104, 105, 106, 107, 108, 109, 110, 113, 115, 116, 117, 119, 123, 134, 139, 143, 144, 145, 146, 152, 154, 157, 159, 168, 171, 172, 175, 181, 187, 192, 201, 202, 203, 206, 207, 208, 209, 210, 211, 215, 219, 221, 222, 231, 233, 234, 235, 236, 237, 238, 239, 248, 251, 254, 258, 260, 261, 263, 265, 266, 267, 268], "80": [8, 35, 85, 89, 90, 91, 92, 93, 94, 95, 96, 97, 157, 159, 215, 225, 227, 231, 238, 247, 251, 265], "800": 8, "8000": 265, "80000": 54, "802257": 265, "80238238": [201, 202], "807": [105, 118, 265, 268], "808": 175, "809": 263, "81": [53, 231, 237, 258], "811882": 265, "812": 170, "816": 250, "816932": 265, "8189894": 265, "82": [47, 251], "82020": 215, "82020742": 211, "821291": 265, "823": 263, "824": 263, "824126": 265, "825": [260, 265], "827": 263, "82842712": 175, "82915619758884995": 175, "83": [54, 171, 237, 251, 258], "830": 257, "833": 258, "8332741681010102": 236, "8349": 253, "8352": 253, "836": 257, "8374671194983834": 188, "838": 260, "84": [76, 237, 251, 254, 265], "840": [254, 265], "841": 54, "84147098": 175, "842105": 265, "845": 257, "849": 54, "85": [44, 76, 233, 234, 237, 251, 253], "8524": 263, "8555": 251, "856": 253, "858": [48, 52, 268], "85987448204884": 266, "86": [76, 237, 238, 251, 260], "861": 175, "862": [85, 86], "862654": 265, "868": [254, 265], "87": [76, 142, 143, 144, 145, 146, 148, 149, 150, 152, 153, 154, 237, 251, 253], "871": [175, 257], "872": 175, "873": 159, "875": 204, "876": [260, 263], "8777777777777778": 237, "88": [76, 237, 251, 253, 260, 263], "882": 8, "883": 253, "885": [254, 265], "8868686868686868": 239, "887": 257, "88888889": 53, "889": 265, "88ccff": 233, "88ff88": 233, "89": [54, 237, 251, 265], "890": 263, "8925": 253, "893": 258, "896": 265, "8e3": 158, "8e8bc565444b": 76, "8i": 10, "8x6": [90, 157], "8x8": [237, 251], "9": [2, 8, 10, 14, 16, 19, 20, 21, 30, 34, 35, 39, 41, 43, 50, 53, 54, 56, 59, 65, 74, 76, 77, 78, 79, 81, 85, 86, 87, 90, 91, 98, 99, 108, 110, 117, 132, 157, 158, 159, 161, 170, 171, 172, 175, 178, 179, 196, 202, 209, 226, 229, 233, 234, 236, 237, 238, 245, 251, 252, 257, 259, 260, 261, 265, 267, 268], "90": [89, 97, 105, 108, 110, 157, 158, 159, 163, 216, 237, 251], "900026": [179, 202], "901": 265, "904": 175, "907": 213, "90929743": 175, "91": 231, "916": 54, "919": [260, 265], "92": [37, 127, 237, 251], "920": [253, 254, 265], "923": [117, 118, 268], "927": 76, "9294570108037394": 236, "93": [149, 237, 251], "930": 257, "930570687535": 251, "932": 257, "933068826918": 251, "934": [54, 159], "9344942114287969": 236, "939": 258, "94": [37, 238, 265], "940": 258, "943": 265, "945363": 265, "9458233756": 202, "945823375615215": 187, "947": 251, "947368": 265, "948": 263, "948e": 202, "94e": 260, "95": [24, 122, 123, 125, 127, 129, 130, 133, 134, 135, 139, 237, 238, 251], "951545": 265, "954855": 265, "955": 251, "955488": 265, "955512": 258, "95786": 53, "96": [37, 171, 237, 238, 251, 254, 265], "960170": 265, "963": 251, "965353": 265, "966": [251, 261], "967": 258, "97": [54, 237, 238, 251, 257], "972": [260, 265], "973": 175, "973182": 258, "975": [128, 132, 183, 194, 253, 254, 257, 258, 260, 263, 265, 268], "9755550897728812": 236, "975555089773": 251, "9757924194139573": 236, "975792419414": 251, "977": 175, "978064579214": 251, "9780645792142071": 236, "97989825": 216, "98": [121, 124, 140, 143, 234, 237, 251, 254, 259, 265], "980": 251, "9800": 158, "9803719053818863": 236, "980371905382": 251, "9804562804949924": 236, "980456280495": 251, "9813": [254, 265], "98131732": 159, "9848442068835102": 236, "984844206884": 251, "986775344954": 251, "9867753449543099": 236, "988e": 53, "989": [254, 265], "99": [8, 14, 17, 25, 30, 33, 39, 54, 81, 105, 117, 159, 175, 178, 182, 183, 185, 251], "990e": 53, "991367": 251, "991367521884": 251, "9913675218842191": 236, "997": 265, "9973396878": 202, "99754526": 258, "999": [175, 265], "9990234375": 79, "999701": 265, "9999": 53, "999967": 265, "99999": 266, "999999": [8, 171], "9999ff": [122, 142, 157], "999e": 53, "9th": [232, 250, 251, 268], "A": [8, 37, 38, 39, 41, 43, 44, 45, 46, 47, 48, 49, 51, 54, 61, 66, 67, 69, 70, 73, 76, 77, 78, 85, 86, 99, 129, 131, 133, 134, 135, 139, 156, 157, 159, 166, 171, 172, 175, 176, 185, 192, 194, 197, 202, 215, 217, 231, 232, 234, 250, 253, 266, 268], "And": [8, 39, 43, 50, 70, 85, 159, 179, 181, 203, 215, 237, 239, 251], "As": [9, 10, 39, 53, 74, 76, 78, 79, 157, 202, 215, 216, 249, 251, 253, 263, 266], "At": [8, 53, 85, 216, 251], "Be": 54, "Being": 77, "But": [8, 9, 76, 78, 81, 85, 157, 171, 175, 251, 265], "By": [53, 81, 202, 216, 251, 265], "For": [2, 8, 9, 10, 37, 39, 53, 54, 70, 76, 77, 78, 79, 81, 82, 84, 85, 157, 158, 159, 171, 172, 175, 196, 201, 202, 216, 231, 245, 251, 257, 258, 265, 266, 267], "If": [8, 9, 10, 39, 53, 54, 70, 74, 76, 78, 80, 81, 85, 157, 158, 159, 171, 175, 202, 215, 231, 251, 253, 265, 266], "In": [1, 8, 9, 10, 37, 39, 53, 54, 65, 70, 74, 76, 77, 79, 80, 81, 82, 83, 84, 85, 86, 157, 158, 159, 171, 175, 197, 202, 215, 216, 238, 244, 249, 251, 265, 266, 267], "It": [9, 10, 38, 39, 53, 65, 70, 73, 77, 79, 85, 157, 159, 175, 181, 201, 202, 231, 238, 249, 251, 265, 266], "Its": [8, 83, 202], "NOT": [8, 175], "No": [8, 10, 39, 77, 175, 253, 254, 257, 258, 260, 263, 265], "Not": [8, 53, 76, 78, 81, 86, 259], "OR": 8, "Of": [39, 60, 265], "On": [9, 53, 70, 85, 159, 175, 202, 238, 244, 251], "One": [8, 9, 37, 77, 85, 215, 238, 251], "Ones": 159, "Or": [78, 159, 175], "Such": [9, 74, 201, 202, 215, 265], "That": [39, 76, 79, 216, 266], "The": [1, 2, 9, 10, 21, 27, 34, 37, 38, 39, 44, 46, 47, 48, 53, 54, 61, 70, 73, 74, 75, 77, 78, 79, 80, 81, 83, 85, 86, 99, 100, 103, 118, 144, 157, 158, 166, 169, 172, 174, 175, 181, 187, 192, 201, 202, 205, 213, 215, 216, 217, 231, 232, 234, 237, 240, 243, 245, 249, 250, 253, 254, 260, 263, 266, 267, 268], "Their": 9, "Then": [10, 53, 54, 70, 83, 157, 202, 265, 266], "There": [8, 9, 10, 39, 70, 74, 76, 157, 159, 171, 199, 202, 251, 266], "These": [39, 53, 76, 175, 215, 238, 251], "To": [2, 8, 9, 10, 39, 41, 48, 54, 70, 76, 80, 82, 84, 157, 172, 175, 202, 204, 214, 215, 231, 251, 257, 258, 259, 265, 266, 267], "With": [9, 10, 46, 53, 77, 78, 157, 175, 202, 231, 238, 251], "_": [9, 108, 110, 139, 154, 202, 249, 251], "_0": 197, "_1": 197, "____": 266, "__all__": 65, "__annotations__": 9, "__array__": 159, "__array_finalize__": 54, "__array_function__": 159, "__array_interface__": 8, "__builtins__": [39, 85], "__call__": [9, 202], "__class__": 251, "__defaults__": 9, "__del__": 9, "__doc__": [9, 39, 85], "__enter__": 9, "__exit__": 9, "__file__": [8, 39, 85], "__gt__": 9, "__init__": [9, 83, 85], "__iter__": 9, "__kwdefaults__": 9, "__le__": 9, "__lt__": 9, "__main__": [10, 54, 73, 75, 81, 84, 86, 203, 233], "__module__": 9, "__mul__": 54, "__name__": [9, 10, 39, 54, 85, 203, 233, 236, 241, 251], "__new__": 54, "__next__": 9, "__package__": [39, 85], "__reversed__": 9, "__test__": 39, "__ufunc_api": 39, "__version__": [8, 231], "_arrayfunctiondispatch": 74, "_base": 236, "_build_util": 85, "_california_housing_dataset": 251, "_copy_from_same_shap": 10, "_cos_doubl": 39, "_cos_modul": 39, "_cs_matrix": [55, 57, 58], "_customlinearoper": 65, "_data_matrix": [55, 56, 57, 58, 59], "_decor": 9, "_distributor_init": 85, "_dotbla": 54, "_dsolv": 65, "_fast_mov": 10, "_filter": 85, "_fourier": 85, "_gener": 8, "_ica_par": 54, "_import_umath": 39, "_interpol": 85, "_io": 82, "_leading_trail": 10, "_lib": 85, "_linesearch": 48, "_measur": 85, "_morphologi": 85, "_nc": 10, "_newclass": 39, "_ni_docstr": 85, "_ni_support": 85, "_object": 39, "_pgtol": 53, "_r": [105, 157], "_result": [257, 258], "_run": 10, "_static": [37, 231], "_strided_byte_copi": 10, "_swig_getattr": 39, "_swig_properti": 39, "_swig_repr": 39, "_swig_setattr": 39, "_swig_setattr_nondynam": 39, "_sym_decorrel": 54, "_umath_linalg": 8, "_winreg": 9, "_wrapper": 9, "a2": 202, "a3": 202, "a_j": 175, "a_upp": 202, "aa": 8, "aaaaff": [239, 245], "aaffaa": [239, 245], "ab": [8, 16, 37, 41, 48, 50, 51, 53, 78, 79, 166, 172, 175, 181, 197, 199, 202, 203], "abc": 9, "abdu": [0, 1, 267], "abil": [9, 39, 251], "abl": [8, 9, 76, 83, 172, 251, 263, 265, 266], "abort": 9, "about": [8, 9, 38, 39, 70, 73, 78, 81, 82, 84, 85, 157, 159, 175, 202, 215, 238, 251], "abov": [8, 9, 39, 53, 54, 59, 74, 77, 78, 80, 159, 172, 175, 198, 202, 215, 238, 251, 260, 265], "absenc": 85, "absolut": 70, "absorb": 265, "abspath": [48, 86], "abstract": 65, "accent": 77, "accept": [8, 9, 10, 39, 55, 56, 57, 58, 59, 60, 63, 202, 251], "access": [8, 9, 10, 41, 54, 57, 58, 59, 60, 62, 65, 66, 76, 77, 85, 157, 159, 171, 216, 231, 251], "accompani": 247, "accomplish": 251, "accord": [9, 37, 202, 216, 231, 247, 251, 265], "accordingli": [253, 265], "account": [8, 70, 74, 198, 251], "accumul": [43, 50], "accur": [37, 202, 251], "accuraci": [202, 237, 238, 251], "achiev": [9, 39, 65, 265], "achilles_arrow": 79, "aco": 266, "acquir": 9, "across": [1, 10, 39, 53, 54, 73, 81, 234, 251, 267], "act": [8, 9], "action": 251, "activ": [8, 10], "actual": [8, 10, 39, 57, 58, 62, 85, 175, 181, 202, 251, 265], "ad": [1, 8, 9, 10, 37, 39, 53, 73, 75, 150, 174, 215, 251, 265, 267], "adapt": [1, 48, 202, 215, 231, 251, 267], "add": [1, 8, 9, 10, 37, 39, 65, 70, 76, 77, 85, 142, 143, 144, 145, 146, 147, 148, 150, 152, 153, 154, 157, 175, 215, 251, 253, 267], "add_ax": [121, 124, 140], "add_patch": [142, 143, 144, 145, 146, 147, 148, 150, 152, 153, 154, 233], "add_subplot": [131, 132, 177, 188, 234, 237, 238, 251, 258], "add_to_dict": 81, "addison": [86, 265], "addit": [8, 9, 10, 38, 39, 47, 53, 73, 80, 83, 84, 85, 144, 175, 202, 215, 265], "addition": [39, 215], "address": [8, 10, 37, 84, 265], "addx": 81, "adher": 9, "adj": [253, 254, 257, 258, 260, 263, 265], "adjust": [8, 46, 157, 175, 202, 231, 251], "admit": [10, 46, 53], "admonit": [2, 267], "adopt": 46, "adrian": [0, 267], "adrien": [0, 202, 267], "advanc": [1, 7, 10, 36, 37, 39, 48, 52, 54, 70, 73, 75, 76, 77, 84, 99, 141, 155, 157, 174, 175, 181, 201, 202, 203, 251, 267, 268], "advanced_numpi": [7, 268], "advantag": [9, 39, 53, 158], "advertis": 39, "advis": 80, "aeioui": 78, "affect": [8, 39, 77, 157, 259, 265], "affin": [218, 230, 231, 268], "affinetransform": [224, 231], "after": [8, 9, 10, 65, 76, 77, 78, 85, 157, 171, 175, 251, 252, 261, 263, 265, 268], "afterward": 9, "ag": [83, 251, 259, 265], "again": [8, 39, 79, 159, 238, 251, 253], "against": [1, 175, 267], "agg": [121, 124, 140], "aggreg": [65, 265], "aic": [253, 254, 257, 258, 260, 263, 265], "aim": [76, 202, 266], "air": [252, 261, 265, 268], "airborn": 215, "airfar": 253, "airq4": 253, "aka": 66, "akihiro": [0, 267], "al": [8, 54, 265], "alaska": [196, 202], "albuquerqu": 175, "alert": 8, "alexandr": 74, "alfa": 171, "algebra": [8, 53, 64, 73, 75, 175, 217], "algorithm": [10, 37, 38, 41, 46, 48, 73, 76, 81, 202, 203, 215, 227, 231, 238, 251, 266], "alia": [10, 76], "alias": [39, 76, 99, 100, 118, 157, 268], "align": [8, 39, 70, 157], "aliv": 76, "all": [1, 3, 5, 8, 9, 10, 11, 37, 39, 40, 46, 53, 54, 62, 65, 66, 67, 70, 74, 76, 77, 79, 84, 85, 86, 99, 157, 159, 160, 171, 172, 173, 175, 176, 197, 202, 203, 204, 205, 214, 215, 216, 218, 231, 232, 251, 252, 258, 265, 267, 268], "all_f_i": 48, "all_i": 41, "all_label": [226, 231], "all_x": 41, "all_x_i": 48, "all_y_i": 48, "allclos": [175, 181, 202], "alloc": [10, 39, 54, 62], "allow": [8, 9, 10, 39, 41, 60, 76, 77, 78, 81, 85, 157, 159, 175, 204, 214, 251, 266], "almost": [9, 10, 39, 53, 62, 157, 231, 265], "along": [169, 175, 238, 251], "alpha": [8, 32, 37, 89, 99, 100, 118, 119, 120, 123, 126, 130, 132, 134, 135, 136, 137, 138, 139, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 231, 241, 246, 249, 251, 263, 268], "alpha_": 251, "alpha_2": [139, 154], "alpha_star": 48, "alphabet": [0, 267], "alreadi": [8, 9, 39, 76, 85, 157, 159, 175, 202, 216, 238, 251], "also": [2, 8, 9, 10, 37, 39, 53, 54, 56, 74, 76, 77, 79, 81, 84, 85, 157, 158, 159, 175, 181, 201, 202, 216, 231, 238, 239, 251, 253, 258, 260, 265, 266, 267], "alter": [8, 9, 157], "altern": [9, 39, 40, 52, 53, 54, 77, 86, 157, 175, 266, 268], "although": [39, 76], "alwai": [8, 9, 39, 53, 54, 66, 74, 158, 265], "amarillo": 175, "amaz": 9, "amg": [33, 65], "amiss": 251, "among": [56, 201, 202], "amongst": 54, "amortis": 39, "amount": [39, 80, 201, 202, 238, 249, 251, 265], "ampl": 196, "amplifi": [249, 251], "amplitud": [181, 202, 208, 209, 210, 211, 215], "an": [2, 9, 10, 11, 14, 15, 17, 32, 35, 36, 37, 38, 39, 41, 46, 48, 50, 53, 54, 59, 63, 70, 73, 74, 75, 77, 78, 79, 80, 81, 83, 84, 85, 104, 105, 106, 115, 116, 117, 122, 123, 126, 127, 136, 137, 138, 140, 142, 143, 144, 145, 146, 148, 150, 151, 152, 153, 154, 160, 170, 172, 173, 174, 175, 181, 197, 201, 202, 204, 214, 215, 216, 218, 220, 221, 227, 230, 231, 234, 238, 247, 251, 252, 253, 254, 259, 261, 263, 265, 266, 267, 268], "anaconda": [39, 76, 80, 265], "analog": [39, 63, 157], "analysi": [12, 24, 26, 37, 38, 54, 73, 202, 217, 231, 232, 239, 250, 251, 252, 257, 258, 260, 261, 268], "analyt": [53, 202], "analyz": 215, "anatomi": 8, "andr": [0, 202, 267], "andrea": [0, 1, 251, 267], "andrew": 251, "andr\u00e9": [0, 267], "angel": 175, "angl": [9, 39, 157], "ani": [8, 9, 39, 54, 66, 70, 73, 75, 76, 81, 83, 85, 154, 157, 159, 172, 175, 202, 215, 238, 251, 266], "anim": 199, "anisotrop": 53, "anna": 83, "annot": [6, 39, 73, 75, 89, 97, 150, 233], "annual": [206, 207, 212, 216], "anoth": [8, 9, 10, 53, 77, 81, 82, 85, 86, 175, 202, 238, 249, 251, 253, 265, 266], "anova": [73, 217, 257, 258], "anova_lm": [257, 258], "anova_result": [257, 258], "answer": [8, 9, 10, 39, 74, 251], "anti": [99, 100, 118, 157, 268], "antialias": [101, 103, 140, 157, 177], "antialis": 157, "antideriv": [184, 202], "anybodi": 85, "anymor": [9, 253], "anyon": [39, 74], "anyth": [9, 70, 78, 151, 251], "api": [1, 8, 38, 70, 73, 74, 157, 231, 253, 254, 257, 258, 260, 263, 265, 267], "apologet": 9, "appar": [9, 251], "appear": [9, 157, 198, 251], "append": [9, 41, 43, 48, 50, 76, 77, 81, 82, 85, 139, 154, 157, 159, 203], "appli": [2, 9, 32, 39, 41, 159, 182, 183, 185, 201, 202, 238, 251, 265, 267], "applic": [8, 9, 10, 37, 38, 61, 73, 75, 76, 84, 159, 201, 202, 231, 238, 253], "apply_along_axi": [47, 48], "apply_optim": 10, "appreci": 251, "approach": [8, 9, 47, 53, 73, 75, 217, 231, 238, 265], "appropri": [39, 202], "approx": 265, "approx0": 172, "approx_fprim": 53, "approxim": [37, 38, 65, 73, 75, 174, 202, 215], "apriori": [60, 63], "ar": [1, 2, 9, 10, 37, 38, 39, 46, 48, 53, 54, 56, 57, 58, 60, 65, 66, 70, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 86, 99, 157, 158, 171, 172, 174, 175, 177, 198, 201, 202, 204, 214, 215, 216, 227, 231, 238, 240, 243, 245, 248, 249, 251, 253, 254, 255, 259, 260, 263, 265, 266, 267], "arang": [8, 13, 24, 25, 31, 37, 39, 42, 54, 59, 105, 106, 107, 108, 110, 115, 116, 117, 121, 122, 131, 133, 140, 142, 149, 151, 157, 159, 164, 169, 172, 175, 181, 187, 188, 192, 196, 202, 204, 206, 207, 208, 209, 210, 211, 212, 215, 216, 247, 251], "arbitrari": [9, 39, 86, 157, 231, 266], "arc3": [89, 97, 157], "arctan": 53, "arctan2": [134, 135, 152, 153], "area": [9, 77, 157, 201, 202, 231], "arg": [8, 9, 10, 39, 76, 81, 157, 177, 190, 193, 202, 209, 211, 215, 240], "argmax": [175, 181, 202], "argmin": [172, 175], "argpars": 85, "argsort": [172, 175], "argtyp": 39, "argument": [1, 8, 9, 10, 39, 53, 54, 74, 76, 81, 85, 86, 157, 159, 202, 203, 204, 214, 215, 231, 251, 266, 267], "argumenterror": 39, "argv": [85, 86, 203], "aris": [79, 221], "arithmet": [8, 10, 55, 56, 57, 58, 60, 63, 66, 77, 85, 175, 266], "around": [2, 8, 9, 46, 54, 83, 85, 142, 143, 144, 145, 146, 147, 148, 150, 152, 153, 154, 157, 171, 172, 178, 199, 201, 202, 215, 216, 251, 265, 267], "arpack": [33, 37, 54, 65], "arpackerror": 65, "arpacknoconverg": 65, "arr": [8, 202, 207, 212], "arr2": 8, "arrai": [1, 2, 9, 11, 36, 38, 39, 43, 48, 50, 53, 54, 55, 56, 57, 58, 59, 60, 62, 63, 65, 73, 74, 75, 76, 77, 81, 85, 148, 157, 158, 174, 178, 188, 196, 197, 198, 201, 202, 203, 204, 207, 209, 211, 212, 214, 215, 216, 231, 238, 245, 251, 258, 266, 267, 268], "arrang": [99, 156, 157, 268], "array_1d_doubl": 39, "array_equ": [39, 175], "array_lik": [74, 159], "array_split": [207, 212], "arrayobject": 39, "arrayprint": 10, "arrow": [152, 157, 233], "arrow1": 233, "arrow2": 233, "arrowprop": [89, 97, 157], "arrowstyl": [89, 97, 157], "art": 215, "articl": [54, 77], "artifact": 198, "artifici": [41, 81, 251], "artist": 157, "arunpersaud": [0, 267], "as_fram": [235, 243, 251], "as_integer_ratio": 76, "as_strid": [8, 10], "asarrai": [8, 48, 54, 181, 202], "asarray_chkfinit": 54, "ascii": 79, "ascontiguousarrai": 54, "asid": 251, "ask": [8, 39, 54, 73, 75, 157, 251, 263], "asmatrix": [54, 159], "aspect": [39, 105, 192, 251, 253, 259, 265], "aspnet": [85, 86], "asprecondition": 65, "assert": [8, 39, 203], "assert_rais": 9, "assertionerror": 9, "asset": 265, "assign": [8, 9, 54, 63, 73, 75, 80, 81, 84, 159, 171, 172, 175, 201, 202, 231, 251], "associ": [9, 77, 81, 251, 265], "assum": [8, 66, 202, 216, 253, 254, 257, 258, 260, 263, 265], "assumpt": [249, 251, 265], "ast": 76, "ast_pars": 76, "astronom": 251, "astronomi": 251, "astut": 251, "astyp": [8, 12, 15, 22, 24, 25, 26, 28, 30, 31, 32, 33, 34, 37, 39, 65, 158, 171, 182, 197, 201, 202, 204, 219, 226, 231], "asv": 54, "atleast_1d": [50, 53], "atol": 202, "attach": [9, 81, 202], "attain": 251, "attempt": 202, "attribut": [3, 38, 39, 55, 56, 57, 58, 59, 66, 73, 76, 77, 79, 83, 159, 204, 214, 231, 251, 253, 265, 267], "attributeerror": 79, "audio_fmt": 8, "audiolab": 8, "author": [1, 3, 8, 9, 10, 37, 39, 53, 54, 61, 70, 73, 74, 76, 84, 157, 174, 202, 231, 251, 257, 258, 265, 266], "authorit": 10, "auto": [105, 159, 192, 251], "auto_exampl": [7, 36, 52, 69, 70, 98, 118, 155, 156, 170, 194, 200, 213, 230, 231, 250, 261, 264], "auto_examples_jupyt": [5, 11, 37, 40, 53, 67, 99, 157, 160, 173, 176, 202, 205, 218, 231, 232, 251, 252, 265], "auto_examples_python": [5, 11, 37, 40, 53, 67, 99, 157, 160, 173, 176, 202, 205, 218, 231, 232, 251, 252, 265], "autocmd": 10, "autogener": 39, "autoloc": 117, "autom": [2, 8, 9, 54, 238, 251, 267], "automag": 76, "automat": [8, 9, 10, 39, 54, 73, 76, 78, 202, 204, 214, 229, 263, 265], "autoregress": 251, "autowrit": 10, "avail": [8, 9, 10, 37, 39, 53, 54, 65, 70, 74, 76, 80, 84, 85, 202, 215, 216, 225, 231, 238, 251, 265], "avebedrm": 251, "aveoccup": 251, "averag": [236, 251, 265], "averoom": 251, "avg": [196, 237, 238, 251], "avoid": [38, 39, 54, 70, 73, 76, 77, 159, 198, 202, 239, 251, 260], "awai": 8, "awar": [38, 73], "ax": [22, 29, 31, 37, 41, 43, 48, 50, 73, 75, 89, 95, 96, 97, 99, 101, 102, 103, 104, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 121, 122, 123, 124, 125, 126, 127, 129, 130, 131, 132, 133, 134, 135, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 152, 153, 154, 156, 168, 172, 175, 177, 181, 188, 198, 201, 202, 208, 209, 210, 211, 215, 231, 233, 234, 237, 238, 242, 246, 247, 251, 258, 265, 268], "axes3d": [131, 132, 149, 157, 177, 258], "axes_1": 126, "axes_2": 126, "axes_3": 126, "axes_4": 126, "axes_5": 126, "axesimag": [37, 158, 159, 165, 172, 198, 201, 202, 231, 238], "axhlin": [43, 50, 188], "axi": [8, 12, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 41, 43, 44, 48, 49, 50, 51, 54, 59, 65, 66, 73, 75, 99, 100, 105, 118, 125, 129, 145, 151, 169, 172, 175, 178, 182, 183, 185, 199, 201, 202, 206, 207, 212, 219, 220, 221, 223, 224, 225, 226, 227, 228, 229, 234, 235, 239, 242, 243, 245, 246, 251, 268], "axiserror": 8, "axisgrid": [253, 260], "axvlin": [12, 26, 43, 50, 102, 229], "b": [0, 1, 8, 10, 24, 43, 44, 47, 48, 53, 54, 65, 66, 77, 78, 80, 81, 82, 85, 86, 109, 111, 113, 140, 159, 171, 172, 175, 179, 188, 196, 202, 203, 215, 224, 234, 242, 248, 251, 267], "back": [8, 39, 70, 85, 157, 175, 181, 260, 263, 265], "backbon": 39, "background": [1, 12, 35, 73, 157, 215, 217, 226, 227, 266, 267], "backslash": 77, "backspac": 78, "backward": 159, "bad": [39, 181, 251], "bad_year": [6, 8], "badli": 39, "balanc": 251, "band": 192, "bandwidth": 171, "bar": [73, 75, 99, 133, 141, 151, 155, 156, 212, 216, 255, 268], "bare": [9, 84, 202], "barnowski": [0, 1, 267], "barri": 251, "bartosz": [0, 1, 267], "barycent": 44, "base": [2, 8, 9, 10, 37, 38, 46, 54, 63, 65, 73, 75, 76, 79, 83, 85, 157, 159, 172, 174, 175, 215, 217, 248, 251, 267], "baselin": 251, "basenam": 86, "bash": 86, "basi": [2, 9, 74, 158, 160, 170, 173, 238, 251, 267, 268], "basic": [9, 38, 39, 53, 55, 73, 75, 76, 81, 84, 157, 161, 162, 174, 181, 185, 202, 203, 215, 217, 222, 231, 266], "basic_typ": 86, "basin": 231, "batteri": 76, "bay": [73, 217], "bayesian": 265, "bb": 8, "bbb": 8, "bbox": [132, 149, 151], "bdb": 10, "beam": 215, "bear": 85, "beauti": [85, 171], "beazlei": [9, 77, 86], "becam": 80, "becaus": [9, 39, 46, 76, 77, 80, 85, 157, 175, 198, 202, 216, 238, 251, 259, 260], "becom": [8, 9, 39, 70, 76, 251], "bedroom": 251, "been": [1, 9, 10, 39, 48, 53, 54, 65, 76, 80, 85, 157, 202, 216, 238, 251, 253, 267], "befor": [9, 10, 39, 54, 65, 73, 75, 80, 84, 85, 159, 201, 202, 231, 238, 251, 252, 261, 265, 268], "begin": [8, 74, 77, 81, 85, 157, 159, 202], "beginn": [70, 73, 76], "behav": [9, 39, 53, 251], "behavior": [8, 53, 159, 216, 251], "behaviour": 9, "behind": [9, 54, 251, 256, 265], "being": [8, 9, 63, 85, 251, 265], "believ": 10, "bell": [53, 65, 66], "belong": [8, 172, 202, 227], "below": [2, 8, 9, 39, 53, 59, 70, 76, 84, 157, 159, 166, 175, 202, 215, 251, 258, 267], "bench": [10, 42], "bench_optim": 10, "benefici": 251, "benefit": [157, 175, 260, 265], "bera": [253, 254, 257, 258, 260, 263, 265], "berg": [0, 1, 267], "berndt": 265, "bernoulli": 266, "besid": 76, "bessel": 202, "besson": [0, 267], "best": [38, 42, 53, 54, 73, 175, 179, 180, 181, 188, 189, 190, 193, 234, 245, 251, 258, 266], "best_params_": 251, "beta": [139, 154, 171], "better": [1, 9, 10, 37, 39, 53, 54, 74, 85, 157, 198, 202, 233, 238, 251, 265, 267], "better_pi": 203, "between": [8, 9, 16, 39, 53, 54, 74, 76, 77, 79, 81, 85, 130, 175, 191, 197, 202, 215, 231, 251, 253, 254, 255, 263], "bevel": [107, 116], "bewar": [54, 175], "beyond": [73, 75, 76, 251, 263], "bfg": [43, 47, 48, 53], "bharath": [1, 267], "bi": 253, "bia": [73, 217, 232, 250, 268], "bias": 251, "bibtex": [1, 267], "bic": [253, 254, 257, 258, 260, 263, 265], "bicg": 65, "bicgstab": 65, "biconjug": 65, "bidirect": [38, 73], "big": [8, 54, 81], "big_arrai": 10, "bigger": [53, 157, 171, 265], "bigger_point": [25, 37], "bigx": 81, "bilinear": 37, "bill": 157, "bimod": 265, "bin": [10, 12, 26, 37, 86, 186, 193, 202, 204, 208, 209, 210, 211, 215], "bin_cent": [12, 26, 37], "bin_edg": [12, 26, 37], "binari": [8, 37, 73, 82, 85, 158, 178, 185, 201, 202, 217, 226, 237, 251], "binary_clos": [15, 37, 185, 201, 202], "binary_dil": [37, 85, 201, 202, 231], "binary_eros": [30, 37, 201, 202, 231], "binary_img": [12, 15, 26, 37], "binary_open": [15, 24, 30, 37, 185, 201, 202, 204, 231], "binary_propag": [30, 37], "bincount": [204, 214], "bind": [10, 37, 77, 231], "bins_cent": 229, "bisect": 10, "bit": [2, 8, 9, 37, 39, 53, 59, 81, 85, 157, 171, 175, 251, 267], "bit_count": 76, "bit_length": 76, "bits_per_sampl": 8, "bivariatesplin": 216, "bla": 202, "black": [15, 37, 53, 77, 123, 140, 144, 157, 172, 201, 202, 214, 238], "blank": 10, "blaze": 53, "blend": 157, "bless": 76, "blob": [226, 231], "blobs_label": [226, 231], "block": [9, 11, 36, 37, 38, 61, 65, 66, 73, 76, 78, 81, 85, 159, 202, 251, 268], "block_align": 8, "block_mean": [13, 37], "blocksiz": 55, "blog": 39, "blood": 251, "blown": [70, 202], "blue": [53, 77, 81, 89, 90, 91, 92, 93, 94, 95, 96, 97, 102, 106, 107, 115, 116, 130, 157, 234, 251, 254, 263], "blur": [11, 32, 36, 38, 73, 176, 195, 197, 200, 202, 268], "blurred_f": [32, 37], "blurred_fac": [14, 37, 182, 201, 202], "bmatrix": 202, "bo": 196, "bodi": [9, 81], "boe": 202, "boil": 198, "boileau": [0, 1, 267], "boilerpl": [8, 39], "bold": [70, 233], "bone": [127, 146, 238, 247], "bonjour": 159, "book": [53, 76, 84, 265], "bookmark": 86, "bool": [24, 33, 35, 37, 74, 77, 159, 175, 227, 231], "boolean": [73, 74, 75, 77, 172, 174, 251, 265, 266], "boost": 235, "border": [157, 172, 198], "border_valu": 85, "borderaxespad": 48, "bore": [9, 202], "bossch": [0, 1, 267], "both": [8, 39, 53, 54, 57, 58, 65, 74, 78, 157, 159, 175, 202, 227, 231, 251, 253, 266], "bother": 78, "bottleneck": [39, 54], "bottom": [8, 9, 12, 14, 15, 16, 17, 19, 20, 21, 23, 24, 25, 26, 27, 28, 30, 33, 34, 35, 89, 95, 96, 97, 105, 108, 110, 117, 122, 128, 133, 151, 157, 178, 182, 183, 185, 204, 214, 233, 234, 237, 238, 251], "bound": [8, 9, 10, 11, 36, 37, 38, 39, 43, 73, 77, 177, 198, 202, 268], "boundari": [37, 65, 157, 215, 239, 251], "box": [11, 36, 37, 38, 73, 142, 143, 144, 145, 146, 147, 148, 150, 152, 153, 154, 157, 255, 256, 268], "box_bg": 233, "boxplot": [99, 141, 155, 157, 252, 253, 256, 261, 265, 268], "boxstyl": [142, 143, 144, 145, 146, 147, 148, 150, 152, 153, 154], "boyd": 53, "boyl": [0, 1, 267], "brace": 9, "bracket": [41, 53, 202], "brain": [263, 265], "brain_siz": [255, 256, 263, 265], "branch": 70, "brand": 39, "break": [8, 9, 10, 41, 48, 54, 73, 75, 76, 79, 84, 85], "breakag": 54, "breakpoint": 10, "brent": [40, 52, 268], "brenth": 10, "brentq": 10, "bretar": 215, "brett": [0, 267], "brick": 76, "bring": [54, 157], "broad": 13, "broadcast": [37, 38, 54, 73, 75, 172, 174, 202], "broader": 9, "broadli": 238, "broken": [8, 85, 251], "brows": [8, 74, 204, 214], "browser": 76, "broyden": 53, "bruce": 9, "bruno": [0, 1, 267], "brutal": 181, "brute": [38, 73, 188], "brute_forc": 85, "bsgalvan": [0, 267], "bsr": [38, 61, 66, 73], "bsr_arrai": [55, 66], "bt": 10, "bubbl": [73, 75, 201, 202, 204], "bubbles_area": 204, "bubbles_label": 204, "bubbles_nb": 204, "buffer": [10, 38, 39, 73], "bug": [38, 39, 55, 73, 159], "bugfix": [2, 267], "buggi": [10, 202], "build": [1, 9, 38, 39, 73, 76, 84, 85, 86, 175, 215, 216, 231, 251, 265], "build_ext": 39, "builder": [2, 267], "built": [8, 9, 39, 54, 73, 76, 78, 79, 159, 186, 231, 237], "builtin_function_or_method": [76, 159], "buitinck": [0, 1, 267], "bullet": [10, 70], "bump": 198, "bunch": 171, "bundl": 76, "burden": 39, "bureau": 251, "burn": [0, 84, 267], "busi": [85, 253], "butt": [106, 115], "button": [70, 74], "buyl": [0, 1, 267], "bx": 45, "byte": [1, 8, 37, 39, 231, 267], "byte_offset": 8, "byte_r": 8, "byteord": 8, "bz2": 9, "bz2file": 9, "b\u00e9zier": 157, "c": [1, 2, 10, 38, 44, 53, 54, 55, 66, 73, 75, 77, 78, 80, 81, 84, 85, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 121, 123, 135, 140, 144, 153, 157, 159, 166, 171, 172, 175, 179, 190, 196, 197, 202, 215, 231, 234, 237, 238, 239, 240, 244, 246, 247, 248, 251, 254, 260, 263, 265, 267], "c1": 266, "c2": [48, 266], "c_": [239, 247, 249, 251], "c_1": 265, "c_2": 265, "c_contigu": 8, "c_doubl": 39, "c_in": 8, "c_int": 39, "cach": [2, 9, 38, 54, 73, 85, 183, 267], "cachingcompil": 76, "cal_hous": 251, "calcul": [9, 73, 77, 202, 203, 216, 217, 251, 257, 258], "calculu": [73, 217], "california": [1, 232, 250, 251, 267, 268], "call": [1, 8, 9, 10, 39, 42, 43, 48, 50, 53, 54, 56, 65, 76, 77, 79, 81, 83, 85, 157, 159, 172, 175, 177, 197, 202, 215, 231, 251, 259, 265, 266, 267], "call_funct": 10, "callabl": 202, "callback": [48, 65], "caller": [9, 81], "camelback": [177, 202], "camera": [37, 220, 221, 223, 229, 231], "camera_equ": [223, 231], "camera_float": 231, "camera_multipli": [221, 231], "camera_sobel": 231, "can": [1, 2, 8, 9, 10, 37, 39, 45, 47, 53, 54, 57, 58, 60, 65, 66, 70, 74, 76, 77, 78, 79, 80, 81, 83, 84, 85, 157, 158, 159, 169, 172, 175, 181, 197, 201, 202, 215, 216, 218, 230, 231, 238, 249, 251, 260, 265, 266, 267, 268], "canada": 172, "canadian": 8, "cancel": 255, "cannot": [8, 9, 10, 39, 77, 81, 159, 175, 202, 251, 266], "cap": [99, 100, 118, 157, 268], "capabl": 266, "capstyl": [99, 100, 118, 157, 268], "captur": [10, 54, 79, 249, 251, 265], "care": [8, 78, 85, 157, 231, 238], "carlo": 202, "carri": 251, "carrot": [8, 158, 168, 172, 199], "case": [8, 9, 10, 38, 39, 54, 73, 157, 159, 171, 175, 202, 215, 216, 238, 251, 266], "cast": [13, 38, 39, 73, 75, 77, 174, 181], "cat": 231, "catch": [10, 38, 73, 75, 84], "catch_warn": [9, 166], "categor": [73, 251, 254, 256, 260, 263], "categori": [9, 73, 251, 254], "caus": [8, 9], "caution": [73, 217], "cbook": 181, "cc": [3, 267], "ccc": 8, "cccccc": 233, "cd": [39, 76, 85], "cdef": [8, 39], "cdefin": 39, "cdll": 39, "cdot": [139, 154, 202, 266], "cdot10": 199, "cell": [76, 77, 79, 81, 238, 244], "cellprofil": 37, "celsiu": 202, "censu": 251, "center": [101, 103, 117, 119, 120, 122, 126, 136, 137, 138, 139, 154, 157, 172, 201, 202, 215, 233, 246, 251], "center1": [33, 37], "center2": [33, 37], "center3": [33, 37], "center4": [33, 37], "center_of_mass": 37, "centeri": 172, "centerx": 172, "central": [73, 202, 251, 265], "certain": [39, 54, 79, 80, 85, 171, 238, 251, 266], "certainli": 39, "certif": 253, "ceval": 10, "cf": 175, "cg": [47, 48, 53, 65], "chain": [38, 73, 75, 174, 232, 250, 251, 268], "challeng": [8, 46, 47, 238], "chan": [0, 1, 267], "chanc": 251, "chang": [1, 8, 9, 10, 37, 39, 53, 54, 57, 58, 60, 63, 70, 73, 75, 76, 77, 80, 85, 159, 171, 172, 175, 201, 202, 204, 214, 216, 251, 259, 265, 267], "channel": [8, 74, 158, 231], "chapter": [1, 38, 73, 75, 76, 82, 85, 159, 171, 174, 175, 217, 240], "char": [8, 39], "charact": [9, 76, 77, 79, 85, 171], "character": [201, 202], "characterist": [215, 251], "chararrai": [38, 73], "charg": 84, "chart": [73, 75, 99, 141, 155, 156, 208, 209, 210, 211, 233, 268], "chauv": [0, 202, 267], "cheap": 53, "cheaper": [54, 76], "cheat": 76, "chebyshev": [158, 160, 170, 173, 268], "check": [8, 10, 37, 39, 53, 65, 70, 85, 157, 159, 172, 175, 181, 201, 202, 203, 204, 214, 216, 222, 231, 251, 265, 266], "check_grad": 53, "checker": [38, 73], "checkerboard": [222, 224, 231], "cheer": 8, "chessboard": [1, 267], "chicago": 175, "choic": [1, 10, 39, 54, 73, 75, 85, 202, 251, 265], "choleski": 202, "choos": [37, 38, 70, 73, 85, 175, 202, 231, 251, 260], "chose": [157, 238], "chosen": [9, 265], "chri": 84, "christoph": [0, 84, 157, 267], "chroni": [85, 86], "chunk": [62, 77], "chunk_id": 8, "chunk_siz": 8, "ci": [1, 267], "cimport": [8, 39], "cimrman": [0, 61, 267], "circ": 196, "circl": [1, 33, 35, 37, 172, 202, 227, 231, 233, 267], "circle1": [33, 37], "circle2": [33, 37], "circle3": [33, 37], "circle4": [33, 37], "circuit": 9, "circul": 202, "circular": 202, "citi": 175, "city1": 253, "city2": 253, "cl": [9, 10, 266], "clabel": [43, 48, 50, 123, 132, 144, 157], "claim": 265, "clariti": 9, "clash": 85, "class": [8, 37, 38, 39, 55, 56, 57, 58, 59, 61, 64, 70, 73, 77, 80, 81, 82, 83, 85, 157, 159, 216, 231, 239, 245, 251, 266], "classic": [9, 76], "classif": [12, 37, 73, 217, 232, 238, 239, 245, 250, 268], "classifi": [73, 217, 231, 232, 238, 250, 268], "classification_report": [237, 238, 251], "classinst": 83, "classmethod": 9, "claus": 9, "clean": [1, 11, 36, 37, 39, 201, 202, 204, 214, 267, 268], "clean_bord": [219, 231], "cleaner": 9, "cleanmdashesextens": 9, "cleanup": 9, "clear": [2, 8, 9, 10, 77, 81, 84, 85, 267], "clear_bord": [219, 231], "clearer": 74, "clearli": [1, 53, 54, 157, 251, 267], "cleric": 259, "clever": [9, 10, 202], "cleverli": 39, "clf": [42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 65, 233, 235, 236, 237, 238, 243, 246, 247, 251], "click": [8, 70, 157, 251], "clip": 198, "clip_on": [139, 142, 143, 144, 145, 146, 147, 148, 150, 152, 153, 154], "close": [8, 9, 33, 37, 48, 53, 79, 82, 86, 157, 185, 201, 202, 203], "close_img": [15, 37], "closed_mask": [185, 201, 202], "closer": [39, 159], "closest": [37, 172, 251], "cloud": 265, "clr": [85, 86], "clue": 251, "clumsi": 70, "cluster": [11, 36, 37, 85, 202, 233, 251, 268], "cluster_std": 246, "cm": [10, 37, 48, 157, 158, 159, 172, 201, 202, 239, 251], "cmap": [10, 12, 13, 14, 15, 16, 17, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 43, 46, 47, 48, 50, 105, 123, 127, 131, 144, 146, 149, 157, 158, 159, 162, 165, 172, 177, 178, 182, 183, 185, 192, 201, 202, 219, 220, 221, 222, 223, 225, 226, 227, 228, 229, 231, 237, 238, 239, 246, 247, 251, 258, 263], "cmap_bold": [239, 245], "cmap_light": [239, 245], "cmd": [10, 80, 85], "cmodpydem": 39, "cmu": [259, 260], "co": [39, 45, 53, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 134, 152, 157, 158, 163, 167, 179, 196, 202, 247, 265, 266], "cobyla": 50, "code": [1, 2, 3, 5, 6, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 67, 68, 73, 74, 75, 76, 78, 79, 80, 83, 84, 86, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 159, 161, 162, 163, 164, 165, 166, 167, 168, 169, 171, 174, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 205, 206, 207, 208, 209, 210, 211, 212, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 253, 254, 255, 256, 257, 258, 259, 260, 263, 266, 267], "codec": 79, "coder": 38, "coef": [158, 253, 254, 257, 258, 260, 263, 265], "coef0": 247, "coef_": 251, "coeff": [209, 211, 215], "coeffici": [197, 202, 249, 251, 263, 265], "coher": 8, "coin": [219, 225, 231], "coins_edg": [219, 231], "coins_zoom": 231, "col": [55, 56, 57, 58], "collabor": 76, "collaps": [1, 2, 53, 267], "collect": [48, 65, 76, 77, 78, 79, 81, 175, 179, 238, 245, 251], "colon": [78, 81, 85], "color": [8, 12, 15, 24, 26, 42, 43, 46, 48, 50, 73, 75, 77, 89, 90, 91, 92, 93, 94, 95, 96, 97, 99, 100, 102, 106, 107, 108, 109, 115, 116, 118, 123, 125, 129, 130, 139, 140, 144, 145, 148, 150, 154, 172, 175, 188, 197, 198, 204, 214, 229, 231, 233, 234, 237, 238, 239, 245, 246, 247, 248, 251, 254, 263, 268], "colorbar": [127, 157, 159, 162, 164, 175, 177, 197, 237, 240, 251], "colormap": [42, 73, 75, 99, 100, 118, 133, 151, 159, 172, 197, 263, 268], "colorspac": [73, 217], "colorterm": 86, "colour": [1, 159, 267], "column": [8, 38, 55, 58, 60, 61, 63, 66, 73, 74, 157, 158, 159, 172, 175, 197, 203, 251, 253, 255, 256, 259, 265], "column_stack": 74, "com": [8, 64, 85, 86, 183, 238], "combel": [0, 84, 267], "combin": [8, 10, 39, 54, 65, 70, 76, 157, 159, 175, 202, 238, 251, 259, 263, 265], "come": [9, 39, 53, 62, 76, 85, 99, 157, 175, 202, 251, 265], "comma": [77, 85, 171], "command": [38, 54, 73, 75, 76, 79, 84, 85, 120, 157, 222, 266], "comment": [10, 39, 157, 171], "commerci": [76, 84], "commit": [2, 54, 70, 267], "common": [1, 3, 9, 29, 37, 38, 39, 53, 55, 57, 58, 61, 73, 74, 76, 78, 85, 86, 157, 159, 171, 202, 238, 251, 255, 265, 267], "commonli": [39, 54, 202, 238], "commun": [2, 8, 10, 38, 73, 74, 76, 157, 267], "compact": 9, "compactli": 159, "compani": 76, "compar": [9, 10, 37, 47, 53, 73, 75, 85, 169, 172, 176, 194, 201, 202, 215, 217, 225, 227, 231, 232, 250, 251, 268], "compare_optim": 10, "compare_optimizers_pi": 42, "comparison": [40, 52, 53, 171, 172, 175, 265, 268], "compat": [1, 39, 159, 267], "compil": [2, 8, 10, 39, 54, 73, 75, 84, 175, 202, 267], "compilerop": 76, "complain": 8, "complement": 9, "complet": [1, 9, 37, 39, 47, 54, 70, 74, 76, 77, 85, 202, 216, 251, 265, 267], "complex": [8, 9, 65, 66, 73, 77, 159, 171, 181, 202, 208, 215, 265, 266], "complex128": [65, 159, 171], "complex192": 171, "complex256": 171, "complex64": [65, 171], "complex_doubl": 8, "complexwarn": 181, "complic": [9, 37, 158, 231, 251], "compon": [22, 37, 54, 73, 75, 159, 176, 194, 217, 218, 230, 268], "components_": [238, 251], "compos": 202, "compound": 157, "comprehens": [9, 73, 75, 76, 84, 203], "compress": [38, 61, 62, 66, 73], "compt": 202, "compulsori": [78, 85], "comput": [2, 8, 9, 10, 37, 38, 39, 48, 57, 58, 65, 70, 73, 75, 78, 80, 85, 157, 159, 166, 172, 174, 193, 201, 203, 204, 214, 215, 217, 218, 238, 241, 251, 257, 265, 266, 267], "computation": [53, 76, 251], "compute_mandelbrot": 166, "con": [62, 76, 159], "concat": [159, 253, 265], "concaten": [48, 77, 80, 81, 159, 203, 253], "concentr": 202, "concept": [9, 73, 77, 217], "concern": [9, 265], "concis": [2, 81, 267], "conclud": 265, "conclus": 265, "concurr": 9, "cond": [253, 254, 257, 258, 260, 263, 265], "conda": [1, 2, 231, 267], "condit": [10, 46, 47, 48, 65, 73, 75, 79, 84, 172, 191, 202, 238, 253, 263, 265], "confer": [1, 267], "confid": [257, 258], "configur": [10, 85, 157], "confound": [254, 265], "confront": 251, "conftest": 85, "confus": [8, 9, 53, 85, 237, 238, 251], "confusion_matrix": [237, 238, 251], "congratul": 80, "conj": 159, "conjug": [38, 65, 73, 76, 159], "conjugate_gradi": 48, "connect": [9, 22, 37, 39, 62, 73, 75, 76, 157, 176, 194, 218, 227, 230, 268], "connectionstyl": [89, 97, 157], "conquer": 10, "consecut": [8, 9, 192, 202], "consequ": [8, 9], "consid": [9, 39, 48, 53, 54, 83, 84, 85, 175, 202, 249, 251, 265], "consider": [9, 54, 55], "consist": [8, 39, 53, 77, 159, 202, 238, 251], "consol": [10, 76, 85, 157], "consolid": 76, "constant": [2, 10, 21, 37, 85, 202, 266, 267], "constrain": [53, 188, 202], "constraint": [38, 40, 52, 73, 215, 268], "construct": [1, 8, 38, 39, 53, 56, 60, 63, 65, 66, 73, 75, 171, 172, 174, 175, 203, 251, 259, 267], "constructor": [9, 55, 56, 57, 58, 59, 60, 63, 83], "consult": 39, "consum": [48, 197], "cont": 10, "contain": [2, 8, 9, 39, 62, 65, 73, 75, 76, 78, 81, 84, 85, 157, 158, 159, 172, 202, 215, 231, 265, 267], "contamin": 202, "content": [1, 77, 253, 259, 267], "context": [10, 38, 53, 73, 83, 85], "contextlib": 9, "contextmanag": 9, "contigu": [39, 62], "continu": [1, 9, 10, 53, 54, 73, 75, 84, 90, 157, 251, 254, 265, 267], "contour": [15, 17, 24, 37, 43, 46, 47, 48, 50, 73, 75, 99, 141, 155, 156, 218, 230, 231, 246, 247, 268], "contourf": [123, 131, 132, 144, 149, 157], "contract": 10, "contrari": [9, 84], "contrast": [37, 159, 202, 231, 254, 263, 265, 266], "contribut": [38, 73, 74, 215], "contributor": [2, 3, 70, 267], "control": [9, 39, 48, 70, 73, 75, 76, 81, 84, 114, 157, 181, 249, 251, 254, 263, 265, 266], "control_flow": 86, "conveni": [9, 38, 73, 76, 77, 81, 86, 159, 251], "convent": [2, 70, 73, 75, 81, 85, 171, 174, 231, 267], "converg": [41, 48, 65, 202, 236, 251], "convergencewarn": 236, "convers": [39, 56, 66, 77, 80, 175, 231], "convert": [8, 33, 37, 39, 53, 56, 60, 65, 66, 73, 82, 202, 203, 231, 257, 258, 260], "convex": [38, 40, 41, 52, 73, 268], "convinc": 39, "convolut": [176, 195, 197, 200, 202, 268], "convolv": [159, 198], "coo": [38, 61, 66, 73], "coo_arrai": [56, 60, 66], "cookbook": [39, 74, 202], "cool": 78, "coolwarm": 258, "coord": [55, 56, 57, 58, 59, 63, 224, 231], "coordin": [38, 61, 66, 73, 99, 151, 156, 157, 268], "coords_subpix": [224, 231], "copi": [8, 38, 39, 47, 54, 73, 75, 76, 77, 83, 85, 86, 172, 174, 175, 181, 182, 197, 201, 202, 203, 251], "copybutton": [2, 267], "core": [8, 10, 37, 39, 53, 54, 76, 174, 202, 251], "corei": [0, 267], "corn": [1, 267], "corner": [37, 157, 201, 202, 204, 214, 231], "corner_harri": [224, 231], "corner_peak": [224, 231], "corner_subpix": [224, 231], "coroutin": 9, "corrcoef": [172, 251], "correct": [2, 39, 53, 73, 157, 159, 203, 217, 237, 238, 240, 253, 266, 267], "correctli": [198, 216, 238, 253, 254, 257, 258, 260, 263, 265], "correl": [37, 172, 249, 251], "correspond": [8, 10, 37, 39, 53, 54, 55, 57, 58, 60, 70, 73, 77, 83, 157, 159, 172, 181, 202, 215, 216, 231, 238, 251, 253, 257, 258, 265], "cos_doubl": 39, "cos_doubles_func": 39, "cos_doubles_wrap": 39, "cos_func": 39, "cos_func_np": 39, "cos_modul": 39, "cos_module_np": [1, 39, 267], "cos_module_wrap": 39, "cos_t": 265, "cosh": 266, "cosin": [39, 89, 90, 96, 97, 157, 159], "cosmethod": 39, "cost": [38, 39, 54, 73], "cost_bench": 42, "cost_funct": 48, "cost_nam": 42, "costless": 159, "costli": [53, 54], "could": [8, 9, 10, 39, 54, 78, 85, 157, 171, 175, 202, 203, 239, 251], "count": [8, 9, 39, 48, 73, 75, 77, 159, 201, 202, 235, 265], "counter": [48, 78, 251], "counterpart": 175, "counting_f_prim": 48, "counting_hessian": 48, "countingfunct": 48, "coupl": [8, 10, 119, 265], "cournapeau": [0, 267], "cours": [9, 70, 73, 84, 159, 175, 251], "coursera": 251, "cov": 253, "cov_max": 196, "cov_min": 196, "covari": [253, 254, 257, 258, 260, 263, 265], "cover": [1, 8, 9, 37, 39, 70, 157, 201, 202, 214, 231, 251, 265], "coverag": [2, 267], "cp": 76, "cpast": 76, "cprob": [206, 207, 216], "cps_85_wage": [259, 260], "cpu": [38, 54, 73, 251], "cpycheck": 39, "cpython": 39, "cramp": 85, "crappi": 10, "crash": [10, 39], "creat": [8, 9, 37, 39, 42, 43, 48, 55, 56, 57, 58, 59, 60, 63, 65, 70, 73, 74, 75, 76, 77, 78, 82, 83, 84, 90, 157, 169, 172, 175, 181, 215, 218, 230, 231, 239, 242, 245, 246, 251, 260, 266, 268], "create_bas": 233, "creatingufunc": 8, "creation": [157, 202], "creativ": [3, 267], "creativecommon": [3, 267], "criteria": 39, "crop": [23, 37, 172, 178, 182, 201, 202, 204, 214, 231], "crop_fac": [23, 37, 172], "cropped_fac": [183, 201, 202], "cross": [53, 70, 73, 159, 217, 234, 241], "cross_val_scor": [241, 251], "cross_valid": 251, "crude": [73, 75, 174, 176, 195, 200, 202, 268], "cryptic": 8, "crystal": 9, "csc": [38, 55, 56, 58, 61, 65, 66, 73], "csc_arrai": [57, 66], "cset": 132, "csr": [38, 55, 56, 57, 61, 65, 66, 73], "csr_arrai": [58, 66], "csr_matrix": 66, "css": [1, 267], "cstride": [131, 149, 157, 177, 258], "csv": [202, 251, 254, 255, 256, 263, 265], "ct": [37, 231], "ctor": 10, "ctrl": 10, "ctype": [38, 73], "ctypeslib": 39, "cumsum": [169, 175], "cumtim": 54, "cumul": [73, 75, 202, 205, 207, 213, 268], "curdir": 86, "curiou": 9, "curli": 9, "current": [2, 8, 9, 38, 39, 65, 73, 76, 86, 146, 157, 158, 202, 216, 231, 267], "curv": [38, 39, 40, 52, 73, 75, 76, 157, 176, 184, 194, 195, 200, 209, 211, 268], "curvatur": [37, 53], "curve_fit": [45, 53, 179, 196, 202, 215], "custom": [39, 76, 79, 83, 157], "customis": 9, "cut": [10, 181], "cv": [241, 251], "cycl": [10, 251], "cydav": [1, 267], "cython": [8, 9, 38, 54, 73], "cython_numpi": 39, "d": [0, 8, 9, 10, 39, 42, 48, 65, 74, 76, 77, 78, 79, 81, 85, 86, 108, 110, 139, 152, 154, 159, 169, 172, 181, 198, 234, 251, 266, 267], "d_": 8, "d_1": 8, "d_2": 8, "d_interp_result": 202, "d_interp_splin": 202, "d_n": 8, "da": 172, "dai": 196, "damp": [176, 194, 202, 268], "daniel": [0, 267], "dans": 253, "dark": 214, "darkest": 37, "dash": [9, 99, 100, 118, 157, 246, 247, 268], "dash_capstyl": [106, 157], "dash_joinstyl": [107, 157], "dat": [183, 204, 253], "data": [1, 6, 9, 11, 24, 33, 36, 37, 38, 39, 45, 53, 54, 55, 56, 57, 58, 59, 62, 63, 66, 74, 75, 76, 77, 85, 86, 89, 95, 96, 97, 117, 132, 149, 157, 163, 165, 167, 168, 178, 179, 182, 183, 184, 185, 189, 197, 198, 204, 205, 213, 216, 217, 219, 220, 221, 223, 224, 225, 228, 229, 232, 234, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 253, 254, 255, 256, 257, 258, 259, 260, 263, 267, 268], "data2": 158, "data3": 158, "data_2000": 253, "data_2001": 253, "data_fisq": 265, "data_flat": 253, "data_id": 8, "data_long": 265, "data_piq": 265, "data_s": 8, "data_str": 203, "databas": [9, 251], "datafram": [73, 252, 253, 257, 258, 261, 268], "dataptr": [10, 39], "dataset": [13, 14, 17, 18, 19, 20, 23, 27, 29, 31, 32, 37, 39, 73, 85, 158, 172, 182, 183, 201, 202, 205, 213, 231, 232, 234, 235, 236, 238, 239, 241, 243, 244, 246, 248, 250, 254, 259, 260, 268], "datastructur": 77, "date": [1, 77, 157, 253, 254, 257, 258, 260, 263, 265, 267], "dave": [0, 267], "david": [0, 9, 77, 86, 267], "db": 172, "dc": 172, "dcc": 251, "ddof": 251, "ddot": 202, "de": [0, 1, 267], "deactiv": [1, 267], "deal": [8, 10, 53, 54, 73, 75, 76, 174], "dear": 10, "debian": [2, 267], "debug": [1, 9, 38, 39, 73, 76, 85, 86, 267], "debugg": [38, 39, 73, 76], "debuggingwithgdb": 10, "decai": 198, "decentralis": 9, "decept": 39, "decid": [9, 251, 266], "decim": [8, 9, 78, 203, 266], "decis": [232, 239, 250, 251, 268], "decision_funct": [246, 247], "decisiontreeregressor": [243, 251], "declar": [8, 9, 39, 80, 81, 266], "deco_inst": 9, "decomp": 54, "decompos": 215, "decomposit": [54, 175, 202, 237, 238, 244, 251], "deconvolut": 231, "decor": [38, 54, 73, 99, 141, 149, 155, 157, 188, 268], "decorator_class": 9, "decorator_with_argu": 9, "decreas": [33, 37, 78, 85, 251, 253], "dedic": [37, 38, 76, 84, 85, 202, 217, 226, 231, 265], "dedupl": [1, 267], "def": [9, 10, 24, 37, 39, 41, 43, 45, 46, 47, 48, 49, 50, 53, 54, 65, 76, 79, 81, 83, 85, 108, 110, 117, 123, 127, 144, 146, 157, 166, 172, 177, 179, 187, 188, 190, 191, 196, 197, 202, 203, 207, 209, 211, 215, 233, 234, 247, 251], "default": [8, 9, 53, 65, 66, 73, 74, 75, 76, 81, 85, 159, 187, 216, 231, 241, 251, 259, 265], "default_rng": [8, 10, 12, 15, 16, 19, 20, 21, 22, 24, 25, 26, 28, 30, 33, 34, 37, 45, 47, 49, 53, 54, 63, 65, 111, 113, 122, 133, 135, 139, 143, 151, 153, 154, 157, 158, 159, 162, 163, 167, 169, 175, 179, 180, 181, 182, 184, 193, 201, 202, 226, 231, 234, 242, 245, 247, 249, 251, 257, 258, 265], "defin": [8, 10, 38, 39, 53, 70, 73, 75, 79, 80, 84, 85, 159, 172, 177, 197, 202, 203, 204, 214, 215, 216, 251, 263, 266], "definit": [8, 9, 37, 44, 65, 73, 75, 84, 202, 216, 251, 266], "defmatrix": 54, "defun": 10, "degre": [158, 202, 216, 231, 234, 247, 251], "deil": 157, "dejavu": [132, 146], "del": 9, "deleg": 9, "delet": [9, 86], "delim_whitespac": 253, "delimit": 78, "delin": 85, "deliv": 215, "deliveri": 8, "delta": [169, 175, 247], "delta_1": [139, 154], "demo": [10, 19, 20, 23, 48, 54, 73, 75, 85, 86, 104, 106, 107, 111, 112, 113, 114, 115, 117, 124, 126, 127, 132, 141, 144, 147, 148, 149, 155, 156, 176, 179, 182, 183, 187, 188, 192, 194, 202, 232, 234, 250, 251, 268], "demo2": [85, 86], "demo_opt": 54, "demonstr": [27, 39, 101, 102, 181, 215, 243, 245], "den": [0, 1, 203, 267], "denest": 266, "denmark": 216, "denois": [11, 36, 38, 73, 176, 182, 195, 200, 218, 230, 268], "denoise_tv_chambol": [20, 225, 231], "denoised_fac": 10, "denoised_img": 10, "denomin": [76, 202, 266], "dens": [55, 56, 57, 58, 59, 60, 62, 63, 65], "densiti": [1, 176, 186, 193, 194, 202, 216, 267, 268], "dep": [253, 254, 257, 258, 260, 263, 265], "depend": [1, 8, 10, 33, 37, 39, 53, 62, 85, 86, 157, 159, 171, 202, 251, 253, 260, 265, 267], "deprec": [1, 8, 38, 39, 73, 253, 267], "depth": [78, 85], "der": [0, 54, 267], "deriv": [9, 46, 53, 83, 157, 184, 202, 238, 251, 265, 266], "derphi_star": 48, "descent": [38, 40, 52, 73, 268], "descr": [8, 251], "describ": [8, 9, 76, 81, 172, 196, 202, 215, 216, 231, 251, 265], "descript": [79, 157, 251], "descriptor": [38, 73, 231], "design": [1, 8, 9, 65, 159, 181, 202, 251], "desir": [159, 202], "despair": 74, "despit": 9, "dest": 10, "destroi": 9, "det": [8, 74, 202], "detail": [8, 39, 53, 73, 74, 75, 77, 82, 175, 202, 215, 231, 240, 265], "detect": [10, 38, 73, 77, 159, 181, 215, 231, 260, 265], "detector": 231, "determin": [8, 74, 157, 169, 202, 204, 214, 215, 251], "detrend": [176, 194, 202, 268], "dev": [2, 8, 9, 54, 76, 159, 171, 175, 267], "dev0": [73, 267], "devel": 265, "develop": [2, 9, 10, 39, 65, 76, 157, 267], "deviat": [202, 238], "devic": [76, 159], "devil": [73, 75], "devis": 39, "df": [202, 253, 254, 257, 258, 260, 263, 265], "df_denom": [254, 263, 265], "df_num": [254, 263, 265], "dhist": 86, "dia": [38, 61, 66, 73], "dia_arrai": [59, 66], "diabet": [241, 251], "diag": [8, 54, 159, 202], "diagnost": [85, 86, 251], "diagon": [38, 61, 66, 73, 202, 238], "diagram": [159, 232, 250, 251, 268], "diamond": 231, "dichotomi": 53, "dict": [1, 8, 9, 60, 157, 251, 267], "dict_kei": 77, "dict_valu": 77, "dictionari": [9, 38, 61, 66, 73, 75, 76, 81, 159, 202, 251, 265], "did": [48, 175, 202, 238, 251], "didact": [39, 198, 238, 251], "didn": 172, "didrik": [0, 1, 174, 267], "diff": 266, "differ": [8, 9, 10, 16, 37, 38, 39, 46, 47, 48, 54, 59, 70, 73, 74, 75, 76, 77, 79, 80, 83, 84, 85, 108, 110, 116, 117, 157, 158, 159, 172, 174, 175, 201, 202, 204, 214, 215, 216, 231, 234, 251, 252, 253, 254, 256, 259, 260, 261, 263, 268], "different": 202, "differenti": [38, 62, 73, 202, 217], "differential_evolut": [177, 202], "difficult": [2, 9, 39, 70, 76, 202, 267], "difficulti": [9, 53], "diffus": 231, "digit": [73, 217, 232, 250, 268], "dilat": [10, 11, 36, 37, 85, 201, 202, 231, 268], "dilate_dist": [25, 37], "dim": [42, 239], "dim1": 39, "dimag": 37, "dimens": [37, 38, 39, 47, 53, 54, 73, 75, 159, 174, 231, 238], "dimension": [37, 39, 42, 54, 65, 73, 159, 201, 202, 217, 231, 248], "dir": [39, 85, 231], "direct": [1, 9, 21, 38, 39, 53, 61, 70, 73, 175, 197, 198, 202, 267], "direct_solv": 65, "directli": [8, 9, 39, 56, 59, 74, 85, 157, 175, 197, 202, 215, 238, 251], "directori": [2, 10, 39, 67, 70, 73, 75, 76, 85, 158, 267], "dirichlet": 65, "dirnam": 86, "dirpath": 86, "disabl": [10, 39], "disadvantag": 39, "discard": [157, 181], "disclaim": 265, "discov": [39, 199], "discret": [55, 73, 159, 251], "discuss": [2, 8, 9, 54, 70, 158, 175, 202, 251, 265, 267], "diseas": 251, "disk": [37, 171, 227, 231], "disk_area": 81, "disk_structur": [24, 37], "displai": [1, 2, 9, 10, 11, 34, 36, 38, 53, 70, 73, 74, 80, 81, 99, 125, 141, 145, 146, 155, 156, 157, 159, 172, 197, 203, 204, 214, 218, 230, 231, 249, 251, 260, 265, 266, 267, 268], "dissect": [38, 73], "dist": [25, 37, 186, 202, 253], "distanc": [35, 160, 169, 170, 173, 175, 202, 215, 227, 231, 253, 268], "distance_arrai": 175, "distance_transform_bf": [16, 25, 37], "distance_transform_edt": [35, 227, 231], "distinct": [81, 251], "distinguish": [9, 81, 84, 251], "distort": 181, "distract": 8, "distribut": [2, 73, 75, 76, 84, 172, 176, 194, 205, 213, 231, 251, 253, 265, 267, 268], "district": 251, "dit": 10, "dive": 84, "divert": 76, "divid": [10, 55, 172, 199, 251], "divis": [1, 79, 267], "dll": 39, "dndebug": 39, "do": [8, 9, 10, 29, 31, 33, 35, 39, 41, 48, 50, 53, 54, 70, 76, 85, 143, 157, 158, 159, 171, 172, 175, 202, 204, 214, 216, 237, 251, 253, 265, 266], "do_someth": 9, "doc": [8, 9, 10, 54, 70, 74, 76, 77, 82, 84, 85, 86, 158, 159, 175, 231, 256], "docstr": [8, 37, 38, 39, 65, 73, 74, 75, 76, 84, 85, 159, 171, 175, 203, 204, 214, 231], "doctest": [1, 8, 9, 267], "doctre": 86, "document": [1, 2, 9, 10, 37, 38, 39, 62, 75, 76, 81, 86, 99, 174, 175, 202, 238, 244, 251, 265, 266, 267], "doe": [8, 9, 10, 26, 39, 53, 66, 73, 74, 75, 77, 79, 80, 81, 84, 159, 181, 198, 202, 203, 251, 260, 265, 266], "doesn": [8, 9, 74, 81], "dogacan": [0, 1, 267], "doi": 215, "dok": [38, 61, 66, 73], "dok_arrai": [60, 66], "dollar": [251, 259, 260], "domain": [38, 73, 76, 202, 266], "don": [8, 9, 10, 39, 43, 53, 54, 74, 76, 78, 80, 85, 171, 175, 215, 251, 263, 265], "done": [9, 39, 53, 54, 70, 159, 169, 198, 238, 265], "dot": [8, 54, 66, 90, 157, 159, 202], "dotnet": [85, 86], "doubl": [8, 9, 39, 62, 65, 77], "double_it": 81, "doubt": 54, "down": [10, 23, 37, 39, 54, 76, 198, 251], "download": [5, 6, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 54, 67, 68, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 99, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 173, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 202, 205, 206, 207, 208, 209, 210, 211, 212, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 263, 265], "downsampl": 189, "dpi": [89, 90, 91, 92, 93, 94, 95, 96, 97, 101, 102, 103, 104, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 121, 124, 140, 145, 157], "draix": 215, "dramat": 65, "draw": [37, 48, 49, 51, 76, 144, 145, 154, 157, 202, 231, 251], "drawn": [202, 265], "drive": 265, "drop": [10, 158, 251], "dry": 10, "dsolv": [65, 266], "dst": 10, "dsyevd": 54, "dt": [190, 191, 197, 202], "dtype": [8, 35, 37, 39, 53, 55, 56, 57, 58, 59, 60, 63, 65, 158, 159, 171, 175, 181, 201, 202, 206, 207, 209, 211, 215, 216, 227, 231, 265], "dual": 251, "due": [39, 63, 159, 202, 251, 255, 265], "dugmeci": [0, 1, 267], "dummi": 265, "dump": 86, "duplic": [9, 56, 60, 70], "durbin": [253, 254, 257, 258, 260, 263, 265], "dure": [70, 76, 84, 172, 175, 215], "dvipng": [2, 267], "dx": [46, 139, 154, 215, 266], "dx_i": 48, "dy": [46, 190, 191, 202], "dy_i": 48, "dylib": 39, "dynam": [9, 84], "dynload": [85, 86], "dz": 202, "dz_0": 202, "dz_1": 202, "e": [2, 8, 9, 10, 37, 39, 53, 54, 76, 77, 78, 79, 80, 81, 84, 85, 139, 154, 157, 158, 159, 169, 171, 202, 231, 249, 251, 265, 266, 267], "each": [2, 8, 9, 37, 39, 53, 54, 55, 59, 63, 65, 66, 73, 74, 76, 81, 85, 157, 159, 169, 171, 172, 175, 196, 197, 201, 202, 203, 215, 231, 235, 237, 251, 253, 256, 265, 267], "earth": 215, "eas": 231, "easi": [8, 9, 39, 53, 54, 56, 59, 73, 74, 75, 76, 84, 198, 266], "easier": [9, 38, 53, 54, 73, 75, 216, 251], "easiest": 70, "easili": [9, 47, 76, 231, 251, 265, 266], "eccentr": 231, "echo": 10, "eckel": 9, "econometr": 265, "ecosystem": [70, 73, 75, 85, 157, 175, 217], "edg": [9, 11, 33, 36, 38, 73, 99, 100, 118, 157, 198, 231, 268], "edgecolor": [89, 122, 134, 142, 152, 157, 247], "edit": [8, 38, 70, 73], "editor": [2, 8, 10, 70, 73, 75, 85], "edu": [253, 259, 260], "educ": [38, 252, 259, 261, 265, 268], "edwin": [0, 267], "effect": [9, 38, 54, 65, 73, 157, 198, 202, 238, 251, 253, 254, 255, 259, 263, 265], "effici": [8, 10, 37, 53, 54, 55, 56, 57, 58, 60, 63, 66, 76, 77, 158, 159, 175, 202, 251], "effort": [2, 9, 39, 53, 267], "eg": [251, 265], "egen": [0, 267], "eig": 172, "eigen": [38, 61, 73], "eigen_solv": 37, "eigenfac": [232, 250, 251, 268], "eigensolv": 65, "eigenvalu": [38, 54, 61, 64, 73, 172, 202], "eigenvector": [54, 65, 172], "eigh": 54, "eight": 251, "eigsh": 54, "einsum": 8, "either": [9, 39, 85, 231, 251], "el": [37, 201, 202], "elabor": [1, 70, 73, 75, 99, 139, 141, 142, 155, 156, 157, 174, 240, 265, 267, 268], "elaps": 65, "electrotechn": 62, "element": [8, 37, 39, 55, 56, 57, 58, 59, 60, 62, 63, 74, 77, 78, 85, 159, 175, 201, 202, 214, 231], "elementari": [54, 202, 266], "elementwis": [8, 66, 73, 75, 172, 174, 202], "elementwise_func": 8, "elementwise_funct": 8, "eleph": [158, 160, 170, 173, 198, 268], "elev": 258, "elif": [48, 73, 75, 84], "ellipj": 202, "ellips": 37, "ellipsoid": 172, "ellipt": [53, 202], "els": [9, 39, 48, 73, 75, 79, 81, 84, 85, 171, 175, 203, 233, 237, 238], "elsewher": 259, "elsiz": 10, "em": 9, "emac": 10, "emacswiki": 10, "emb": 251, "embed": [10, 73, 76, 215, 217], "emit": 215, "emma": 85, "emmanuel": [0, 1, 37, 74, 76, 77, 84, 174, 202, 231, 267], "emphasi": 70, "empir": 53, "emploi": [10, 66, 251], "empti": [1, 39, 55, 56, 57, 58, 59, 60, 62, 63, 78, 85, 157, 159, 203, 246, 247, 251, 267], "empty_lik": [39, 159], "emul": 76, "en": [9, 70, 76, 81], "enabl": [8, 10, 39, 53, 65, 76, 159, 215, 251, 260, 265], "enclos": [9, 37, 77, 78], "encod": [79, 231, 265], "encount": [9, 10, 39, 54, 74, 83, 199], "end": [6, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 68, 76, 77, 81, 85, 86, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 159, 161, 162, 163, 164, 165, 166, 167, 168, 169, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 202, 203, 206, 207, 208, 209, 210, 211, 212, 216, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 251, 253, 254, 255, 256, 257, 258, 259, 260, 263], "endian": 8, "endif": 39, "endogen": 265, "endpoint": [95, 96, 97, 159, 253], "endswith": [105, 203], "energi": 53, "enforc": [9, 198], "engag": 74, "engin": [62, 245, 259, 260], "english": 171, "enhanc": [9, 62, 73, 80, 157, 217, 251], "enlighten": 251, "enorm": 39, "enough": [2, 9, 39, 199, 238, 267], "enrich": [74, 157], "ensembl": [8, 235, 251], "ensur": [2, 39, 159, 267], "enter": [10, 76, 78, 79, 85, 159], "entir": [39, 266], "entiti": [9, 265], "entri": [1, 8, 56, 60, 238, 256, 267], "enumer": [42, 48, 73, 75, 105, 108, 110, 117, 202, 234, 235, 251], "environ": [1, 2, 10, 73, 75, 85, 157, 238, 244, 265, 267], "eof": 10, "ep": [41, 171], "epsilon": 41, "eq": [139, 154], "equal": [43, 53, 65, 78, 80, 129, 172, 175, 218, 230, 231, 265, 266, 268], "equalize_hist": [223, 231], "equat": [62, 73, 202, 217], "equival": [9, 53, 202, 265, 266], "er": 265, "eratosthen": 159, "erf": [202, 266], "eric": [1, 267], "erod": [201, 202], "eroded_img": 37, "eroded_squar": [30, 37], "eroded_tmp": 37, "eros": [11, 36, 37, 201, 202, 231, 268], "err": [251, 253, 254, 257, 258, 260, 263, 265], "error": [1, 2, 8, 9, 16, 39, 41, 47, 48, 53, 65, 77, 79, 85, 86, 171, 172, 202, 216, 234, 235, 243, 251, 253, 254, 255, 257, 258, 260, 263, 265, 267], "error_estim": 202, "esc": [10, 39], "espaz": [0, 202, 267], "especi": [39, 76, 80, 81, 82, 157, 175, 231], "essenti": [86, 202, 251], "est": 253, "establish": 53, "estim": [53, 54, 73, 202, 214, 215, 216, 217, 238, 249, 257, 258, 265], "est\u00e8v": [0, 1, 267], "et": [8, 54, 265], "etc": [8, 9, 10, 37, 73, 74, 75, 77, 81, 83, 84, 85, 159, 171, 172, 175, 201, 202, 214, 231, 238, 251, 257, 258], "euroscipi": [1, 8, 267], "eval": [9, 117, 157], "evalf": 266, "evalu": [8, 9, 39, 46, 53, 77, 78, 81, 177, 191, 202, 216, 238, 251, 265, 266], "even": [9, 53, 65, 84, 159, 175, 216, 251], "evenli": [55, 159], "event": 202, "ever": [10, 39, 251], "everi": [9, 10, 67, 70, 77, 85, 157, 216, 251], "everybodi": 171, "everyon": 10, "everyth": [8, 9, 74, 75, 76, 78, 175], "everywher": 53, "evgeni": [0, 1, 267], "evid": [202, 265], "evil": 54, "evolut": [48, 169, 196, 199], "evolv": 76, "ex": [76, 83], "exact": [8, 38, 65, 73, 74, 172], "exactli": [8, 9, 53, 76, 78, 184, 202, 265], "examin": [159, 202, 238], "exampl": [1, 7, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 38, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 61, 62, 66, 69, 73, 74, 75, 76, 77, 79, 81, 83, 84, 85, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 120, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 141, 142, 143, 144, 145, 146, 147, 148, 149, 151, 152, 153, 154, 155, 156, 158, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 172, 174, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 196, 197, 198, 199, 200, 201, 203, 206, 207, 208, 209, 210, 211, 212, 213, 215, 216, 217, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 233, 234, 235, 236, 237, 239, 240, 241, 242, 243, 244, 245, 246, 248, 249, 250, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 263, 264, 265, 266, 268], "example_formula": 260, "exc_info": 9, "excel": [84, 251, 259, 265], "except": [8, 38, 39, 73, 75, 76, 84, 86, 159, 171], "exchang": 8, "exclud": [77, 169], "exclus": [39, 159, 175], "exec": [10, 76], "execfil": [54, 85], "execut": [7, 9, 36, 38, 39, 52, 54, 69, 73, 76, 78, 79, 80, 84, 85, 98, 118, 155, 156, 170, 172, 194, 200, 213, 230, 250, 261, 264, 268], "exercis": [38, 46, 73, 75, 76, 84, 98, 160, 170, 173, 174, 198, 207, 212, 213, 215, 217, 263, 268], "exercise_2": 157, "exhaust": [9, 82, 99, 157], "exist": [8, 10, 39, 53, 76, 81, 82, 86, 198, 203, 216, 251, 253, 259, 260, 266], "exit": [9, 10, 54, 86], "exogen": 265, "exp": [33, 37, 41, 44, 46, 48, 49, 53, 123, 127, 144, 146, 157, 175, 198, 202, 209, 211, 215, 266], "expand": [73, 217], "expandus": 86, "expans": [73, 217], "expect": [8, 9, 66, 159, 169, 175, 202, 231, 233, 235, 237, 243, 251], "expens": [57, 58, 251, 265], "experi": [53, 76, 83, 159, 175, 259, 265], "experiment": [53, 202, 216], "expert": [38, 73], "expertis": 73, "explain": [8, 43, 49, 51, 54, 70, 78, 85, 157, 171, 231, 234, 251, 254, 265], "explained_variance_ratio_": 251, "explan": [53, 59, 77, 247], "explicit": [9, 157, 171, 202, 215], "explicitli": [9, 10, 48, 157, 159, 172, 266], "explod": [129, 148], "exploit": 9, "explor": [10, 54, 73, 76, 157, 186, 202, 217, 235, 238, 251], "expon": 266, "exponenti": 202, "export": [2, 39, 85, 267], "expos": [39, 53, 158, 159, 251, 265], "exposur": [223, 229, 231], "expr": 266, "express": [8, 38, 53, 73, 75, 77, 84, 157, 159, 238, 251, 253, 254, 265, 266], "ext": 10, "ext_modul": 39, "extend": [9, 77, 81, 201, 202, 217, 266], "extens": [9, 39, 54, 70, 85, 157, 159, 266], "extent": [8, 43, 46, 47, 48, 50, 166, 172, 177], "extern": [1, 9, 10, 39, 54, 73, 75, 266, 267], "extra": [2, 9, 85, 202, 267], "extract": [9, 10, 22, 38, 73, 75, 159, 172, 178, 201, 202, 217, 238], "extract_from_a": 159, "extrem": [172, 202, 251, 265], "extrema": 175, "ey": [47, 159, 238, 251], "eyebrow": 238, "f": [8, 9, 10, 13, 17, 18, 19, 20, 27, 31, 32, 37, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 65, 77, 82, 85, 122, 123, 127, 129, 144, 146, 148, 157, 159, 172, 177, 187, 188, 190, 191, 197, 202, 203, 215, 235, 236, 241, 245, 253, 254, 257, 258, 259, 260, 263, 265, 266], "f1": [237, 238, 251], "f1_score": [236, 251], "f5": 10, "f8": 171, "f_0": 197, "f_1": 197, "f_contigu": 8, "f_g": [139, 154], "f_prime": [43, 47, 48], "f_ref": 47, "f_test": [254, 263, 265], "fabian": [0, 1, 266, 267], "face": [1, 9, 10, 11, 13, 14, 19, 20, 23, 27, 29, 31, 32, 36, 37, 73, 75, 99, 100, 118, 157, 174, 182, 183, 201, 202, 231, 238, 267, 268], "face_from_raw": 37, "face_locket": 172, "face_memmap": 37, "facecolor": [89, 122, 132, 134, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 233, 247], "facetgrid": 260, "facil": 266, "facilit": [56, 66], "fact": [9, 251], "factor": [65, 73, 189, 202, 217, 238, 252, 260, 261, 266, 268], "factori": 202, "fail": [8, 10, 39, 74, 236, 251], "failur": [10, 202], "fairli": [9, 251], "fake": [37, 38, 73], "fakedim": 8, "fall": [9, 260], "fals": [8, 9, 23, 37, 39, 42, 48, 54, 65, 74, 76, 77, 78, 85, 86, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 140, 142, 143, 144, 145, 146, 147, 148, 150, 152, 153, 154, 157, 159, 171, 172, 175, 177, 201, 202, 233, 244, 251, 253, 265, 266], "false_": [171, 175], "famili": [132, 146, 202, 216], "familiar": [8, 39, 198, 202, 231], "famou": 251, "fanci": [8, 37, 63, 66, 73, 75, 171, 172, 174, 175], "fancyarrow": 233, "fancybboxpatch": [142, 143, 144, 145, 146, 147, 148, 150, 152, 153, 154], "faq": 157, "far": [8, 9, 59, 76, 157, 202, 215, 251], "far_pt": 247, "fare": [252, 261, 265, 268], "fare_2000": 253, "fare_2001": 253, "fare_differ": 253, "farmer": 8, "farwel": [0, 267], "fast": [38, 43, 53, 55, 56, 57, 58, 59, 62, 66, 73, 75, 76, 86, 157, 159, 231, 251], "faster": [2, 8, 38, 39, 73, 77, 171, 175, 215, 267], "fastest": [8, 53, 54], "fastica": 54, "fault": [38, 39, 73], "favor": [10, 202], "favorit": 85, "fc": [233, 251], "fdel": 9, "fe": 175, "featur": [9, 35, 38, 62, 70, 73, 74, 76, 78, 80, 81, 84, 124, 157, 202, 217, 224, 227, 233, 235, 238, 239, 240, 245, 251, 265], "feature_extract": [33, 37], "feature_nam": [235, 240, 251], "feel": [10, 238, 259], "felip": [0, 267], "femal": [256, 259, 260, 263, 265], "female_viq": 265, "fernando": 76, "fetch": 39, "fetch_california_h": [235, 243, 251], "fetch_lfw_peopl": 238, "fetch_olivetti_fac": 238, "few": [1, 9, 10, 38, 54, 61, 73, 76, 77, 78, 121, 172, 187, 202, 231, 237, 238, 251, 256, 267], "fewer": [8, 65, 76, 251], "ff": 197, "ff0000": [239, 245], "ff9999": [122, 142, 157], "ffaaaa": [239, 245], "ffill": 263, "fft": [73, 75, 85, 176, 189, 194, 195, 199, 200, 268], "fft2": [197, 198], "fftfreq": [181, 199, 202], "fftpack": [1, 85, 267], "fget": 9, "fib": 203, "field": [8, 99, 152, 156, 157, 171, 238, 268], "fifty_prob": [206, 207, 216], "fifty_wind": [206, 207, 216], "fig": [101, 102, 103, 104, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 121, 124, 128, 140, 143, 145, 148, 149, 154, 157, 177, 188, 208, 209, 210, 211, 215, 233, 234, 237, 238, 251, 254, 263], "figshar": 238, "figsiz": [12, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 41, 42, 43, 44, 48, 49, 50, 51, 65, 89, 90, 91, 92, 93, 94, 95, 96, 97, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 121, 124, 126, 136, 137, 138, 140, 143, 145, 157, 169, 175, 178, 179, 180, 181, 182, 183, 184, 185, 188, 189, 190, 191, 192, 193, 208, 209, 210, 211, 215, 219, 220, 221, 223, 225, 226, 227, 228, 229, 233, 234, 235, 237, 238, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 253, 255, 257], "figur": [1, 2, 12, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 65, 73, 75, 76, 89, 90, 91, 92, 93, 94, 95, 96, 97, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 121, 124, 126, 127, 128, 131, 132, 136, 137, 138, 140, 143, 145, 147, 148, 149, 154, 161, 162, 169, 175, 177, 178, 179, 180, 181, 182, 183, 184, 185, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 206, 207, 212, 216, 217, 219, 220, 221, 223, 225, 226, 227, 228, 229, 231, 233, 234, 235, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 251, 253, 255, 257, 258, 259, 267], "file": [1, 2, 3, 7, 9, 36, 38, 39, 52, 54, 63, 69, 70, 73, 75, 76, 78, 79, 81, 84, 85, 98, 118, 155, 156, 157, 159, 170, 172, 174, 175, 183, 194, 200, 204, 213, 214, 216, 230, 231, 238, 250, 251, 253, 256, 259, 260, 261, 264, 267, 268], "file_list": 203, "fileinput": 9, "filelist": 37, "filenam": [2, 10, 39, 54, 76, 77, 86, 203, 267], "filetyp": 10, "fill": [8, 9, 70, 99, 144, 156, 157, 159, 201, 202, 231, 263, 268], "fill_between": [43, 50, 130, 157], "fill_valu": [8, 171], "filtdat": 204, "filter": [10, 11, 19, 32, 36, 38, 73, 75, 85, 176, 194, 204, 214, 217, 218, 219, 226, 229, 230, 268], "filter_and_sort": 203, "filter_blurred_f": [32, 37], "filter_nam": 79, "filtered_camera": 231, "filtered_sig": 181, "final": [9, 39, 73, 75, 157, 202, 216, 238], "final_simplex": 53, "find": [9, 10, 11, 12, 36, 37, 38, 39, 40, 43, 52, 54, 73, 75, 76, 86, 172, 175, 176, 181, 194, 195, 196, 200, 216, 231, 251, 253, 265, 266, 268], "find_answ": 9, "find_librari": 39, "find_modul": 203, "find_object": [22, 37, 178, 201, 202, 231], "find_peaks_cwt": 181, "finder": 10, "fine": [9, 37, 39], "finfo": [41, 171], "finish": [9, 85, 157, 175, 238], "finit": [8, 55, 56, 59, 62, 202], "fipi": 202, "first": [2, 8, 9, 10, 37, 39, 47, 53, 54, 70, 73, 74, 75, 77, 81, 82, 84, 85, 157, 158, 159, 175, 179, 188, 198, 201, 202, 203, 215, 216, 217, 238, 239, 248, 251, 258, 265, 267], "first_step": 86, "fish": 81, "fisq": 265, "fit": [8, 12, 37, 38, 39, 40, 52, 73, 74, 75, 76, 158, 160, 170, 173, 176, 184, 194, 195, 200, 205, 213, 216, 217, 231, 232, 233, 235, 236, 237, 238, 239, 242, 243, 244, 246, 247, 248, 249, 250, 253, 254, 257, 258, 259, 260, 263, 265, 268], "fit_intercept": 246, "fit_transform": [233, 237, 248], "fitpack": 216, "fitted_max_spe": [206, 207, 216], "fix": [1, 8, 9, 10, 39, 55, 59, 70, 77, 202, 251, 267], "fixedloc": 117, "flag": [8, 9, 10, 39, 76, 202, 209, 211, 215], "flagstaff": 175, "flake8": 10, "flat": [8, 40, 52, 268], "flatten": [73, 75, 174, 258], "flavor": 76, "flavour": [39, 159], "fletcher": 53, "flexibl": [8, 60, 63], "flight": 253, "flip": [23, 37, 202], "flip_ud_fac": [23, 37], "flipud": [23, 37], "float": [1, 2, 8, 12, 15, 26, 32, 33, 37, 39, 65, 77, 101, 102, 103, 104, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 122, 129, 142, 148, 157, 159, 171, 181, 182, 197, 201, 202, 203, 209, 211, 215, 231, 237, 251, 263, 266, 267], "float128": 171, "float16": 171, "float32": [8, 39, 65, 158, 171, 206, 207, 216], "float64": [8, 37, 39, 53, 60, 63, 65, 158, 159, 171, 175, 201, 202, 204, 231, 235, 237, 239, 251, 265], "float96": 171, "floatingpointerror": 10, "flow": [9, 73, 75, 76, 81, 83, 84, 198, 233], "flower": [251, 265], "flush": [70, 76], "fly": [9, 10, 38, 73], "flymak": 10, "fmin_cg": 48, "fmin_slsqp": [53, 215], "fminbound": 188, "fmt": [8, 43, 48, 50, 157], "fmt2": 157, "fmt_id": 8, "fmt_size": 8, "fno": 39, "focu": [10, 53, 181, 231, 251], "fold": [1, 234, 251, 267], "follow": [2, 8, 10, 39, 53, 54, 65, 66, 76, 77, 78, 80, 81, 83, 84, 85, 144, 157, 159, 172, 175, 197, 202, 203, 215, 216, 231, 238, 251, 265, 266, 267], "font": [2, 70, 85, 86, 157, 267], "fontdict": 233, "fontsiz": [12, 16, 19, 20, 21, 26, 43, 48, 50, 89, 97, 105, 108, 110, 123, 132, 139, 144, 154, 157, 233, 238], "foo": [9, 39], "foobar": [10, 79], "foodir": 86, "footprint": [35, 215, 227, 231], "forc": [9, 33, 38, 73, 159, 171, 265, 266], "forcibli": 76, "foreground": [12, 73, 217], "foreign": 39, "forget": [85, 253], "forgiv": [73, 75], "fork": 70, "form": [8, 9, 39, 81, 85, 172, 202, 265, 266], "formal": [232, 250, 251, 268], "format": [1, 8, 10, 37, 38, 61, 65, 66, 73, 75, 77, 81, 157, 171, 174, 202, 216, 231, 240, 265, 267], "formatt": [48, 157, 240], "formul": [254, 265], "formula": [73, 78, 203, 217, 253, 254, 257, 258, 260, 263], "forth": 74, "fortran": [38, 54, 73, 75, 77, 84, 159, 202, 216], "fortran77": 65, "fortun": [81, 238], "forward": [9, 39, 76, 159, 251], "found": [2, 37, 39, 45, 54, 73, 74, 75, 76, 77, 188, 202, 216, 251, 265, 266, 267], "four": [39, 76, 78, 157, 251], "fourier": [37, 73, 75, 76, 85, 197, 198], "fourth": 8, "fp": [86, 203], "fpic": 39, "fprime": 202, "frac": [78, 89, 97, 139, 154, 157, 172, 202, 215, 266], "fractal": [8, 166, 172], "fraction": [197, 214], "fragil": 39, "fragment": 39, "frame": [10, 73, 75, 157, 174, 217], "frameon": [42, 48, 101, 102, 103, 104, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 157, 233], "framework": [10, 76, 84, 257, 258], "franci": 77, "free": [10, 37, 53, 65, 76, 84, 157, 238, 251, 265], "freeli": 76, "freez": 202, "freq": [181, 192, 202], "frequenc": [186, 192, 199, 202], "frequent": [74, 157, 266], "friction": 53, "friendli": [1, 8, 231, 267], "fritsch": [1, 267], "from": [0, 1, 7, 9, 10, 11, 12, 20, 33, 35, 36, 37, 38, 39, 42, 47, 48, 52, 53, 54, 56, 59, 62, 63, 65, 69, 70, 73, 74, 75, 77, 80, 81, 82, 83, 84, 86, 90, 98, 117, 118, 125, 126, 131, 132, 142, 143, 144, 145, 146, 147, 148, 149, 150, 152, 153, 154, 155, 156, 157, 158, 159, 166, 169, 170, 172, 175, 176, 177, 181, 183, 186, 194, 197, 199, 200, 201, 202, 203, 204, 213, 214, 215, 216, 219, 220, 221, 223, 224, 225, 226, 227, 228, 229, 230, 231, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 254, 256, 257, 258, 261, 263, 264, 265, 266, 267, 268], "from_byt": 76, "frombuff": 8, "fromfil": [8, 9, 37], "front": [1, 267], "frozen": 85, "fset": 9, "fsiq": [255, 256], "fstab": 9, "ft_popul": 199, "ftol": 48, "ftplib": 9, "ftplugin": 10, "full": [2, 6, 9, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 38, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 68, 70, 73, 75, 76, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 159, 161, 162, 163, 164, 165, 166, 167, 168, 169, 174, 175, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 206, 207, 208, 209, 210, 211, 212, 215, 216, 217, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 251, 253, 254, 255, 256, 257, 258, 259, 260, 263, 267], "full_lik": 159, "full_matric": 54, "full_output": [10, 53], "fullanalyz": 215, "fulli": [76, 202], "fun": [8, 50, 53, 187, 202], "func": [9, 10, 70, 198, 251, 266], "funcformatt": 240, "funcnam": 81, "function": [10, 33, 37, 38, 39, 40, 41, 42, 43, 45, 46, 48, 49, 50, 51, 52, 54, 55, 57, 58, 65, 66, 70, 73, 74, 75, 77, 78, 83, 84, 85, 99, 141, 153, 155, 156, 157, 158, 169, 171, 172, 174, 175, 176, 179, 184, 186, 194, 195, 200, 203, 204, 214, 215, 216, 226, 231, 241, 243, 251, 253, 254, 265, 266, 268], "function_bas": 54, "function_cal": [10, 202], "functool": 203, "fundament": 202, "further": [38, 73, 75, 77, 198, 202, 251, 266], "furthermor": [76, 251], "futur": [9, 70, 231, 253], "futurewarn": 253, "fwrapv": 39, "g": [2, 8, 9, 37, 39, 46, 48, 53, 54, 76, 77, 79, 80, 81, 84, 85, 111, 113, 126, 139, 154, 158, 159, 169, 175, 202, 206, 207, 231, 248, 249, 251, 265, 266, 267], "g_prime": 46, "gael": [1, 251, 267], "gain": [10, 54], "galaxi": 251, "galleri": [1, 2, 5, 6, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 65, 67, 68, 70, 73, 74, 75, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 99, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 173, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 202, 205, 206, 207, 208, 209, 210, 211, 212, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 263, 265, 267, 268], "gamma": [202, 238, 247], "gammaln": 202, "gate": [0, 1, 267], "gather": [83, 216, 238, 251], "gaug": 251, "gauss_denois": [19, 37], "gaussian": [11, 19, 36, 37, 53, 73, 75, 159, 176, 182, 194, 195, 197, 200, 202, 209, 211, 217, 225, 226, 231, 268], "gaussian_coin": 231, "gaussian_filt": [12, 14, 15, 19, 21, 22, 24, 26, 28, 32, 34, 37, 182, 198, 201, 202], "gaussian_filter_coin": 225, "gaussianmixtur": 12, "gaussiannb": [236, 237, 251], "ga\u00ebl": [0, 1, 10, 37, 39, 53, 54, 76, 79, 84, 157, 174, 202, 251, 265, 267], "gca": [12, 26, 89, 95, 96, 97, 117, 132, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157], "gcc": [2, 39, 86, 267], "gcf": [148, 157, 254, 263], "gdb": [38, 73], "gdbinit": 10, "ge": 203, "geiger": [0, 1, 267], "gen": 9, "gender": [252, 256, 259, 261, 262, 264, 265, 268], "gener": [1, 2, 5, 6, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 54, 65, 67, 68, 70, 73, 74, 75, 76, 81, 86, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 158, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 172, 173, 175, 176, 177, 178, 179, 180, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 193, 196, 197, 198, 199, 201, 202, 205, 206, 207, 208, 209, 210, 211, 212, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 263, 265, 267], "generate_binary_structur": [37, 201, 202], "generating_func": [234, 251], "generator_func": 9, "generatorexit": 9, "genexpr": 9, "genfromtxt": [158, 202], "geograph": 251, "geometr": [11, 36, 38, 73, 74, 75, 176, 194, 231, 268], "geometri": [40, 52, 53, 268], "georg": [0, 267], "gerigk": [0, 267], "gert": [0, 1, 267], "get": [8, 9, 38, 39, 46, 48, 66, 73, 80, 84, 85, 157, 175, 198, 202, 215, 243, 251, 253, 257, 258, 259, 263], "get_cmap": 105, "get_figheight": 148, "get_figwidth": 148, "get_includ": 39, "get_test_data": 132, "get_xticklabel": [89, 157], "get_yticklabel": [89, 157], "getcwd": 86, "getnnz": 66, "getter": 9, "gg": 8, "gi": 215, "giesek": [0, 1, 267], "gil": 9, "gilli\u00dfen": [0, 267], "git": [2, 39, 70, 267], "github": [2, 8, 39, 64, 73, 238, 244, 267], "githubusercont": 183, "give": [9, 10, 39, 46, 53, 74, 76, 85, 157, 159, 172, 174, 175, 202, 216, 251, 259, 263, 265, 266], "given": [8, 9, 10, 39, 53, 65, 81, 85, 157, 159, 171, 172, 175, 202, 215, 216, 231, 238, 251, 265, 266], "glass": [73, 75, 202, 214], "glob": [37, 73, 75, 84, 203], "global": [8, 9, 10, 38, 54, 73, 75, 84, 177, 188, 202], "glu": 37, "gmean": 202, "gmre": 65, "gnu": [2, 10, 39, 202, 267], "gnuplot": [43, 46, 47, 48, 50, 76], "go": [6, 8, 9, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 38, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 68, 70, 73, 75, 77, 78, 81, 84, 85, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 159, 161, 162, 163, 164, 165, 166, 167, 168, 169, 172, 175, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 202, 206, 207, 208, 209, 210, 211, 212, 216, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 251, 253, 254, 255, 256, 257, 258, 259, 260, 263, 265], "goal": [39, 70, 83, 215, 216, 231, 238, 251], "goe": [10, 39, 263], "goldfarb": 53, "gommer": [0, 202, 267], "gone": 10, "good": [9, 10, 38, 39, 53, 54, 73, 75, 76, 77, 81, 84, 99, 156, 157, 158, 202, 215, 238, 243, 248, 251, 265, 268], "googl": 74, "got": 8, "gotcha": 9, "gouillart": [0, 1, 37, 74, 76, 84, 174, 202, 231, 267], "gperftool": 54, "gprime": 54, "gprob": 207, "gradient": [10, 33, 37, 38, 40, 43, 46, 52, 65, 73, 172, 218, 230, 231, 235, 268], "gradient_desc": 48, "gradient_descent_adapt": 48, "gradientboostingregressor": [235, 251], "grai": [8, 10, 12, 13, 14, 15, 17, 19, 20, 21, 23, 24, 26, 27, 29, 30, 31, 32, 34, 35, 37, 77, 157, 158, 159, 165, 166, 172, 178, 182, 183, 185, 188, 197, 201, 202, 214, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 231], "grain": [39, 73, 75, 201, 202], "granular": 70, "granulo": [24, 37], "granulometri": [11, 36, 37, 268], "graph": [33, 37, 62, 231], "graphic": 157, "gray_r": [46, 47, 48, 157], "grayscal": [37, 172, 219], "great": [8, 265], "greater": [81, 203], "greater_equ": 203, "greatest": 251, "green": [53, 77, 90, 157, 237, 254, 263], "greg": [0, 1, 267], "grei": [37, 159, 172], "grey_dil": [25, 37], "grey_eros": [201, 202], "greyscal": [11, 36, 37, 268], "grid": [10, 38, 73, 75, 90, 99, 121, 124, 140, 141, 155, 156, 164, 166, 172, 175, 177, 188, 258, 268], "grid_search": 251, "gridsearchcv": 251, "gridspec": [99, 156, 157, 268], "grisel": 251, "ground": [215, 245, 251], "group": [54, 73, 186, 217, 248, 251], "groupbi": [256, 265], "groupby_gend": [256, 265], "grow": [39, 62, 169, 175, 202, 231, 251], "grown": 9, "gscv": 251, "gsl": 202, "gtol": 48, "guarante": [8, 39, 175, 202], "guard": 9, "guess": [65, 85, 157, 188, 202, 215, 216], "gufunc_loop": 8, "gui": [157, 247], "guid": [8, 10, 38, 54, 69, 70, 73, 85, 157, 171, 231, 268], "guidelin": [81, 85], "guido": [9, 251], "gumbel": [73, 75, 205, 213, 268], "gumbell_dist": 207, "gustavsen": [0, 267], "guti\u00e9rrez": [0, 1, 267], "gzip": 9, "gzipfil": 9, "h": [2, 10, 39, 47, 77, 108, 110, 148, 172, 267], "h1": 253, "h3kr1y": [85, 86], "h5py": 158, "ha": [1, 8, 9, 10, 39, 53, 65, 66, 76, 77, 78, 79, 83, 85, 101, 103, 117, 119, 120, 122, 126, 136, 137, 138, 139, 154, 157, 158, 159, 172, 175, 202, 216, 233, 238, 251, 253, 265, 266, 267], "haberland": [0, 267], "had": [172, 202, 251], "haenel": [0, 1, 39, 76, 267], "haessig": [0, 267], "half": 171, "hallo": 159, "halt": 9, "hand": [9, 53, 65, 77, 175, 202, 251], "handi": [53, 62, 76, 157, 251], "handl": [8, 10, 39, 73, 75, 77, 84, 85, 157, 175, 202, 231, 266], "handlelength": 48, "handletextpad": [42, 48], "handwritten": [73, 217], "hanzen": [0, 1, 267], "happen": [8, 9, 10, 202], "hard": [9, 10, 39, 46, 53, 65, 248, 251], "harder": [53, 76, 85, 172, 251], "hardli": 157, "hardwar": 159, "hare": [8, 158, 168, 172, 199], "harri": 231, "hartmann": [0, 1, 267], "harwel": 202, "haslwant": [257, 258], "hasn": 251, "have": [1, 2, 8, 9, 10, 22, 37, 39, 41, 43, 48, 53, 54, 67, 70, 74, 76, 77, 79, 80, 81, 85, 157, 158, 159, 175, 196, 197, 198, 202, 216, 223, 231, 238, 249, 251, 253, 258, 259, 265, 266, 267], "haveg": [85, 86], "hdf5": 158, "head_length": 233, "head_width": 233, "header": [2, 8, 9, 39, 253, 259, 260, 267], "heavi": 76, "heavili": 202, "height": [142, 143, 144, 145, 146, 147, 148, 150, 152, 153, 154, 157, 256, 263, 265], "helen": [0, 267], "hello": [76, 77, 78, 80, 85, 159], "hellohello": 80, "helmu": [0, 267], "help": [9, 38, 39, 54, 65, 70, 73, 75, 77, 157, 159, 171, 172, 175, 202, 251, 265, 266], "helper": [8, 9, 10, 42, 48, 53], "henc": [8, 77, 231], "here": [8, 9, 10, 37, 39, 46, 47, 53, 54, 70, 74, 76, 77, 82, 83, 84, 85, 99, 157, 171, 172, 202, 227, 235, 238, 248, 251, 253, 260, 263, 265, 266], "hess": [47, 48, 53], "hess_inv": [53, 187, 202], "hessian": [38, 47, 48, 73], "heurist": [159, 231, 266], "hexadecim": 8, "hezlo": 77, "hi": [8, 77], "hi_dat": 204, "hi_filtdat": 204, "hidden": [70, 251], "hide": 9, "hierarch": 85, "hierarchi": 65, "high": [1, 37, 39, 53, 54, 73, 75, 76, 84, 157, 159, 175, 231, 234, 249, 267], "high_freq_fft": 181, "higher": [8, 159, 175, 231, 251, 266], "highest": 251, "highli": [10, 231, 251], "highlight": [9, 85, 253, 259, 260], "hilbol": [0, 1, 267], "himanshu": [0, 1, 267], "hing": [236, 246], "hint": [8, 39, 85, 159, 172, 175, 202, 203, 251, 265, 266], "hispan": 259, "hist": [12, 26, 37, 186, 193, 202, 229, 235, 251], "histogram": [11, 12, 36, 37, 73, 176, 193, 194, 201, 202, 204, 214, 218, 229, 230, 235, 251, 268], "histogram1": 193, "histogram2": 193, "histori": 76, "hit": [10, 37, 54, 215], "hive": 9, "hjbbvo": [85, 86], "hl": 77, "hoc": [73, 217], "hofer": [0, 1, 267], "hoffmann": [0, 1, 267], "hohl": [0, 1, 267], "hold": [9, 39, 159, 263], "hole": [15, 37, 201, 202], "home": [9, 10, 39, 48, 73, 76, 85, 86, 144, 183, 199, 217, 238, 253, 260], "homework": [204, 214], "hook": 10, "hopefulli": 10, "horizont": [99, 156, 157, 218, 230, 231, 268], "horizontalalign": [132, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154], "hostedtoolcach": [48, 85, 86, 181, 236], "hot": [16, 54, 123, 131, 144, 149, 157, 159, 162], "hot_r": 192, "hoteit": [0, 267], "hour": [70, 73, 259, 260], "hous": [1, 39, 73, 217, 232, 234, 250, 267, 268], "houseag": 251, "household": 251, "how": [2, 9, 10, 13, 15, 22, 28, 29, 31, 32, 35, 37, 38, 39, 50, 73, 74, 75, 77, 78, 84, 123, 133, 134, 135, 144, 151, 157, 159, 175, 202, 204, 214, 222, 226, 231, 238, 251, 258, 260, 265, 266, 267], "howev": [8, 9, 10, 39, 53, 54, 74, 76, 77, 80, 85, 159, 175, 202, 216, 238, 251, 263, 265], "hsobel_text": [228, 231], "hspace": [12, 14, 15, 16, 17, 19, 20, 21, 23, 24, 25, 26, 27, 28, 30, 33, 34, 35, 237], "hsv": 231, "html": [1, 2, 8, 9, 10, 54, 70, 76, 77, 81, 82, 85, 86, 158, 238, 244, 251, 256, 260, 265, 267], "http": [3, 8, 9, 10, 37, 54, 64, 70, 74, 76, 77, 81, 82, 84, 85, 86, 158, 159, 183, 215, 231, 238, 251, 253, 256, 259, 260, 265, 266, 267], "hubert": 253, "hue": [253, 259, 260, 265], "huge": 62, "human": [39, 53], "hump": [177, 202], "hundr": 251, "hyper": [241, 251], "hyperparamet": [73, 217], "hyperplan": 246, "hypot": [21, 31, 37], "hypothesi": [73, 75, 217, 254, 260], "hz": 181, "i": [1, 2, 3, 8, 9, 10, 21, 24, 33, 37, 38, 39, 42, 43, 46, 47, 48, 54, 55, 56, 57, 58, 59, 60, 62, 63, 65, 66, 70, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 102, 104, 105, 108, 109, 110, 111, 112, 113, 114, 117, 129, 139, 148, 154, 158, 159, 169, 171, 172, 175, 181, 188, 197, 198, 201, 202, 215, 216, 217, 234, 237, 238, 240, 243, 244, 245, 246, 247, 248, 253, 254, 255, 257, 258, 259, 260, 263, 265, 266, 267], "i1": 8, "i2": 8, "i4": [8, 159], "i_interp_result": 202, "i_interp_splin": 202, "ib\u00e1\u00f1ez": [0, 1, 267], "ic": [60, 85, 86], "ica": 54, "id": [10, 77, 233], "id13": 9, "idea": [39, 175, 202, 231, 251], "ideal": [157, 238], "ident": [8, 9, 39, 78, 202, 254], "identifi": [54, 231, 238, 251], "identity_el": 8, "idiom": 159, "idiomat": 238, "idl": [73, 75, 80, 158, 202], "idomat": [2, 267], "idx": 159, "ie": [198, 231, 253], "ifft": [181, 202], "ifft2": [197, 198], "ignor": [6, 8, 9, 10, 43, 46, 47, 50, 166, 177, 193, 265], "ii": 9, "iid": 251, "iii": 9, "iinfo": 171, "iio": [18, 37, 158], "ij": 56, "ijv": [56, 66], "ill": [47, 53], "illus": 9, "illustr": [25, 41, 73, 84, 159, 202, 216, 221, 228, 229, 234, 254], "ilu": 65, "im": [12, 15, 16, 21, 22, 24, 25, 26, 28, 34, 37, 197, 226, 231, 266], "im_blur": 197, "im_fft": 197, "im_fft2": 197, "im_m": [16, 37], "im_new": 197, "im_nois": [16, 37], "imag": [1, 2, 8, 12, 18, 21, 31, 33, 35, 36, 38, 66, 70, 73, 75, 76, 77, 78, 83, 146, 157, 159, 162, 165, 172, 174, 175, 176, 194, 195, 200, 206, 217, 219, 224, 225, 227, 230, 238, 251, 265, 267, 268], "image_process": [36, 268], "imageio": [1, 18, 37, 158, 202, 231, 267], "imagin": [39, 251], "imaginari": [66, 181], "imap": 10, "img": [8, 12, 15, 26, 33, 37, 158, 165, 198, 231], "img2": 198, "img2_ft": 198, "img3": 198, "img_as_float": 231, "img_as_ubyt": 231, "img_ft": 198, "img_r": 165, "img_tini": 165, "img_to_graph": [33, 37], "immedi": 9, "immut": [77, 81], "impati": 215, "implement": [8, 38, 39, 53, 54, 66, 73, 77, 81, 85, 175, 181, 197, 202, 203, 231, 251, 265], "impli": [54, 65], "implicit": 157, "import": [2, 6, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 54, 62, 65, 66, 68, 70, 73, 74, 75, 76, 79, 84, 86, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 158, 161, 162, 163, 164, 165, 166, 167, 168, 169, 172, 174, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 201, 202, 203, 204, 206, 207, 208, 209, 210, 211, 212, 215, 216, 217, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 251, 253, 254, 255, 256, 257, 258, 259, 260, 263, 265, 266, 267], "import_arrai": [8, 39], "import_ufunc": 8, "importantli": [9, 85, 171], "importlib": 85, "impos": 251, "imposs": [9, 85], "impress": 238, "improp": [85, 266], "improv": [1, 2, 8, 65, 70, 74, 202, 231, 251, 267], "impuls": 215, "imread": [37, 158, 165, 197, 198, 202, 204, 231], "imsav": [158, 202, 231], "imshow": [8, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 46, 47, 48, 73, 75, 99, 105, 141, 155, 156, 158, 159, 162, 165, 166, 172, 177, 178, 182, 183, 185, 192, 197, 198, 201, 202, 204, 214, 219, 220, 221, 223, 224, 225, 226, 227, 228, 229, 231, 237, 238, 251, 268], "imwrit": [18, 37, 158], "in1": 8, "in2": 8, "in_arrai": 39, "in_array1": 39, "inch": [90, 157, 237], "includ": [8, 9, 10, 39, 53, 65, 70, 73, 76, 85, 157, 159, 202, 217, 251], "include_dir": 39, "inclus": [2, 39, 267], "incom": 251, "incomplet": 54, "inconclus": 202, "incorrect": [8, 39], "increas": [9, 37, 73, 74, 78, 85, 202, 203, 234, 236, 251, 259, 260, 265], "incredibli": 157, "increment": [39, 60, 63, 66], "inde": [8, 9, 10, 54, 181, 248], "indefinit": 266, "indent": [10, 78, 81, 85], "indentationerror": 85, "independ": [54, 157, 202, 251, 265], "index": [1, 9, 10, 13, 31, 37, 38, 48, 60, 63, 70, 73, 75, 76, 77, 78, 79, 86, 139, 154, 171, 172, 174, 175, 235, 251, 253, 259, 265, 267], "index_error": 10, "indexerror": [9, 10, 79], "indexloc": 117, "indic": [8, 10, 24, 33, 35, 37, 54, 55, 57, 58, 63, 66, 77, 78, 159, 172, 175, 178, 197, 201, 202, 227, 231, 238, 240, 251, 253, 263, 265], "indirect": 39, "individu": [53, 59, 60, 62, 73, 77, 159, 169, 217, 255], "indptr": [55, 57, 58], "induc": 53, "ineq": [50, 53], "inequ": 53, "inf": 202, "infer": [175, 263], "infin": 266, "infinit": 202, "influenc": [157, 252, 261, 265, 268], "info": [76, 85], "inform": [1, 2, 8, 9, 38, 39, 46, 53, 54, 73, 74, 75, 76, 77, 82, 84, 85, 157, 175, 202, 204, 214, 215, 238, 251, 265, 267], "infti": [78, 139, 154], "ingold": [0, 1, 267], "inher": 39, "inherit": 83, "init": [9, 39, 83, 251], "init_print": 266, "initcos_modul": 39, "initcos_module_np": 39, "initi": [8, 10, 35, 39, 53, 65, 73, 75, 86, 188, 191, 201, 227, 231], "initialis": [9, 39], "inject": 9, "inkscap": [2, 267], "inlin": [39, 43, 48, 50, 123, 132, 144, 157, 159], "inner": [9, 39, 181], "innermost": 39, "innersizeptr": 39, "inplac": 39, "inplace_array1": 39, "input": [8, 37, 39, 54, 73, 74, 75, 76, 79, 81, 84, 85, 159, 175, 198, 215, 217, 233, 238, 251, 265], "input_1": 8, "input_1_stride_m": 8, "input_1_stride_n": 8, "input_2": 8, "input_2_strides_n": 8, "input_2_strides_p": 8, "input_output_typ": 8, "inputoutput": 82, "insert": [9, 10, 39, 70, 76, 77, 157, 159, 253], "insid": [8, 9, 10, 37, 70, 74, 81, 85, 157, 216, 231], "insight": [39, 54, 231, 251, 265], "inspect": [8, 10, 37, 54, 202, 215, 265], "inspir": 39, "instal": [2, 8, 10, 65, 73, 75, 80, 85, 86, 157, 159, 231, 265, 266, 267], "instanc": [8, 9, 10, 53, 54, 157, 159, 175, 202, 215, 251, 253, 265, 266], "instanti": [73, 75, 251], "instead": [1, 8, 9, 39, 54, 55, 74, 77, 78, 171, 202, 203, 215, 253, 265, 267], "instrid": 10, "instruct": [1, 9, 39, 76, 80, 85, 172], "int": [8, 10, 12, 15, 22, 24, 25, 26, 28, 30, 31, 34, 37, 39, 48, 74, 76, 77, 79, 80, 127, 139, 154, 159, 171, 197, 201, 202, 204, 219, 226, 231, 240], "int16": [8, 171], "int32": [8, 10, 59, 159, 171], "int64": [8, 10, 55, 56, 57, 58, 59, 63, 158, 159, 171, 175, 265], "int8": [8, 55, 56, 57, 58, 171], "int_": [139, 154], "int_0": [172, 202], "integ": [1, 10, 37, 38, 65, 73, 75, 77, 78, 80, 139, 154, 169, 171, 174, 175, 202, 218, 230, 231, 265, 266, 267, 268], "integr": [1, 8, 38, 73, 75, 76, 85, 174, 176, 194, 198, 217, 256, 267, 268], "intellig": [251, 253], "intend": 9, "intens": [37, 231], "intent": 157, "inter": 265, "interact": [9, 38, 39, 54, 66, 70, 73, 75, 80, 84, 85, 157, 159, 217, 252, 261, 268], "intercept": [9, 253, 254, 257, 258, 260, 263, 265], "interchang": 251, "interdepend": 10, "interest": [9, 10, 37, 38, 39, 53, 61, 70, 73, 77, 78, 157, 158, 175, 177, 201, 202, 216, 231, 238, 251, 253, 265], "interfac": [1, 10, 38, 48, 65, 73, 84, 157, 158, 159, 202, 217, 267], "interfacing_with_c": 39, "intermedi": 202, "intern": [3, 8, 53, 54, 267], "internship": 83, "interoper": [9, 38, 73], "interp_result": [184, 202], "interp_splin": [184, 202], "interpol": [1, 11, 12, 16, 25, 26, 30, 33, 35, 36, 37, 73, 75, 76, 85, 127, 146, 157, 158, 165, 176, 194, 206, 207, 216, 220, 221, 223, 224, 225, 227, 228, 229, 231, 237, 251, 267, 268], "interpolatedunivariatesplin": 216, "interpolation_tim": [184, 202], "interpret": [9, 10, 38, 39, 73, 78, 80, 84, 85, 86, 159, 265], "intersect": 202, "intersphinx": 70, "interv": [53, 191, 202, 257, 258], "intimid": 8, "intro": [1, 70, 85, 98, 118, 144, 155, 156, 157, 170, 175, 194, 199, 200, 213, 215, 216, 267, 268], "introduc": [9, 70, 73, 84, 202, 217], "introduct": [1, 2, 9, 38, 61, 73, 75, 76, 202, 217, 265, 267], "introductori": [1, 215, 267], "introspect": 85, "intuit": [38, 73, 172, 251, 254, 263, 265], "inu": 10, "invalid": [8, 10, 54, 76, 79], "invalu": 265, "invent": [9, 202], "invers": [32, 53, 65, 175, 181, 198, 202, 216, 224, 231], "inverse_splin": 202, "invert": [53, 54, 202], "investig": 260, "invit": [202, 216], "invoc": [9, 81], "invok": [9, 38, 73], "involv": [39, 81, 253], "io": [70, 73, 74, 75, 76, 81, 85, 86, 158, 231], "ipdb": [10, 76], "ipdbplugin": 10, "ipopt": 53, "ipynb": [6, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 68, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 161, 162, 163, 164, 165, 166, 167, 168, 169, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 206, 207, 208, 209, 210, 211, 212, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 253, 254, 255, 256, 257, 258, 259, 260, 263], "ipython": [2, 39, 62, 73, 74, 75, 77, 78, 80, 81, 85, 159, 172, 251, 267], "ipython3": 159, "iq": [252, 255, 262, 264, 265, 268], "ir": 60, "iri": [73, 232, 244, 245, 248, 250, 252, 261, 265, 268], "iris": 251, "irk": 8, "irl": 253, "irreduc": 266, "is_prim": 159, "isdir": 86, "isfil": 86, "isfinit": 181, "isinst": 54, "isn": [9, 53], "iso": 53, "isol": 10, "isolv": 65, "isotrop": 37, "ispr": 215, "isprsjpr": 215, "issu": [2, 8, 39, 70, 77, 202, 251, 266, 267], "issubclass": 9, "ital": 70, "item": [8, 9, 42, 55, 56, 57, 58, 59, 60, 62, 66, 77, 78, 81, 159, 203, 238, 251], "items": [8, 171], "iter": [1, 8, 38, 39, 41, 48, 59, 61, 66, 73, 75, 84, 85, 166, 172, 202, 204, 236, 253, 267], "iterated_wien": 10, "iterator_flag": 39, "iternext": 39, "itertool": [9, 10], "itk": [37, 231], "its": [2, 8, 9, 10, 37, 46, 48, 53, 54, 65, 70, 73, 76, 77, 80, 81, 85, 157, 158, 159, 172, 184, 202, 204, 214, 217, 231, 238, 265, 266, 267], "itself": [8, 9, 39, 53, 75, 81, 85, 251, 265], "j": [8, 10, 57, 58, 62, 65, 159, 166, 172, 175, 215, 246], "j_max": 175, "j_min": 175, "jac": [47, 48, 53, 187, 202], "jacobi": 202, "jacobian": [53, 215], "jake": 251, "jame": 83, "januari": [202, 215], "jarqu": [253, 254, 257, 258, 260, 263, 265], "jarrod": [0, 10, 76, 267], "java": 81, "jb": [253, 254, 257, 258, 260, 263, 265], "jet": [133, 151, 157], "job": [9, 198], "john": [0, 267], "join": [86, 99, 100, 118, 157, 203, 235, 260, 268], "joint": [99, 100, 118, 157, 268], "jonathan": [0, 267], "jone": [0, 1, 267], "jorgeprietoarranz": [0, 267], "jori": [0, 1, 267], "joseph": [1, 267], "josephsalmon": [0, 267], "journal": 215, "jo\u00e3o": [0, 267], "jpg": [37, 204, 214], "jqueri": [2, 267], "judg": [47, 251], "julia": [0, 73, 75, 267], "julian": [0, 1, 267], "jump": [8, 10, 53, 175], "june": 83, "junk": 86, "junkdir": 86, "jupyt": [1, 5, 6, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 67, 68, 73, 75, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 99, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 173, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 202, 205, 206, 207, 208, 209, 210, 211, 212, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 263, 265, 267], "just": [8, 9, 70, 74, 76, 77, 80, 84, 85, 159, 251, 258], "jv": 202, "j\u0119drzejewski": [0, 1, 9, 267], "k": [0, 8, 39, 41, 43, 44, 47, 48, 50, 53, 54, 57, 58, 65, 73, 112, 114, 121, 134, 152, 158, 159, 163, 190, 197, 202, 206, 207, 217, 229, 234, 235, 243, 246, 247, 248, 265, 267], "kate": 10, "kb": 85, "kdialog": 10, "keep": [2, 9, 10, 53, 54, 73, 75, 76, 85, 197, 251, 266, 267], "keep_fract": 197, "kei": [9, 10, 38, 42, 54, 61, 66, 73, 77, 78, 81, 85, 86, 203], "kellei": 251, "kept": 9, "kernel": [176, 195, 200, 202, 231, 247, 268], "kernel_ft": 198, "kernprof": 54, "keyerror": [9, 79], "keystrok": 9, "keysview": 86, "keyword": [9, 39, 70, 76, 81, 157, 175, 204, 214, 253, 266], "kfold": 251, "kg": [190, 202], "kiar": [0, 1, 267], "kick": 10, "kikocorreo": [1, 267], "kikocorreoso": [0, 267], "kill": 9, "kind": [9, 37, 39, 70, 79, 154, 157, 159, 202, 251, 253, 259, 265], "kindli": 215, "kiss": 10, "kmean": 202, "kneighbor": [236, 251], "kneighborsclassifi": [236, 239, 251], "knew": 202, "knight": [0, 1, 267], "knn": [239, 251], "know": [8, 9, 10, 37, 38, 39, 54, 73, 74, 157, 171, 175, 202, 231, 251, 266], "knowledg": [10, 53, 77, 215], "known": [39, 53, 56, 60, 63, 73, 75, 159, 174, 175, 202], "ko": [189, 202], "kristian": [0, 1, 267], "kurtosi": [253, 254, 257, 258, 260, 263, 265], "kv": 188, "kwarg": [9, 81, 144, 157], "l": [10, 12, 15, 22, 24, 26, 28, 33, 34, 37, 39, 43, 47, 53, 54, 76, 77, 79, 85, 86, 105, 108, 157, 159, 172, 175, 226, 229, 231], "l1": 251, "l2": 251, "l_var": 10, "lab": [76, 231], "lab2rgb": 231, "label": [13, 22, 28, 31, 33, 34, 35, 37, 42, 48, 73, 75, 89, 96, 97, 175, 177, 178, 179, 180, 181, 184, 186, 188, 189, 190, 193, 201, 202, 204, 214, 218, 227, 230, 233, 234, 237, 238, 240, 241, 244, 245, 247, 248, 251, 268], "label_clean": 28, "label_im": [22, 28, 33, 34, 37], "labels_rw": [227, 231], "labels_w": [227, 231], "lambda": [9, 10, 42, 202, 203, 240, 245], "langl": [169, 175], "languag": [1, 9, 10, 39, 62, 73, 75, 78, 81, 85, 265, 267], "lapack": 202, "lapack_lit": 54, "laplacian": 37, "lar": [0, 1, 267], "larg": [8, 37, 39, 53, 54, 65, 74, 76, 77, 84, 132, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 231, 234, 238, 251, 253, 255, 263, 265, 266], "larger": [53, 85, 158, 234, 251], "largest": [8, 22, 65, 172], "laser": 215, "lasso": [53, 241, 251], "lassocv": [232, 250, 251, 268], "last": [8, 9, 10, 39, 53, 54, 56, 57, 58, 70, 73, 76, 77, 79, 81, 158, 159, 175, 216, 217, 260, 265], "later": [39, 85, 157, 175, 251], "latest": [70, 76, 81], "latex": [2, 86, 157, 267], "latexmk": [2, 267], "latitud": 251, "latter": [65, 202, 216], "launch": [10, 159], "law": 175, "lawrenc": [0, 1, 267], "layout": [1, 2, 8, 144, 145, 157, 159, 175, 258, 267], "lazi": 265, "lbfgsinvhessproduct": 53, "ldot": 172, "lead": [53, 85, 202, 251], "leak": 9, "learn": [1, 2, 37, 39, 53, 54, 70, 74, 76, 84, 85, 157, 175, 217, 233, 250, 267, 268], "learning_curv": [234, 251], "learning_r": 251, "least": [8, 9, 38, 39, 70, 73, 75, 76, 202, 251, 253, 254, 257, 258, 260, 263, 265], "leastsq": [53, 209, 211, 215], "leav": [9, 78, 251], "lectur": [1, 10, 38, 39, 48, 70, 75, 76, 81, 85, 86, 144, 157, 175, 199, 202, 217, 253, 260], "left": [8, 12, 14, 15, 16, 17, 19, 20, 21, 23, 24, 25, 26, 27, 28, 30, 33, 34, 35, 74, 77, 78, 81, 89, 95, 96, 97, 105, 117, 120, 128, 132, 139, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 159, 175, 178, 182, 183, 185, 198, 204, 214, 215, 233, 234, 237, 238, 241, 251], "leftarrow": 8, "legend": [42, 48, 73, 75, 89, 96, 97, 168, 172, 177, 179, 180, 181, 184, 186, 188, 189, 190, 193, 199, 202, 209, 211, 215, 234, 241, 244, 245, 248, 251], "legibl": [10, 54], "len": [10, 39, 42, 53, 74, 78, 105, 108, 110, 117, 139, 154, 159, 203, 208, 209, 210, 211, 215, 237, 244, 248, 251], "lena": [1, 267], "length": [9, 39, 57, 58, 59, 81, 203, 215, 239, 251, 254, 265], "lengthi": [76, 238], "less": [9, 38, 39, 54, 73, 81, 85, 202, 203, 231, 238, 251, 265], "less_than": 203, "let": [8, 9, 10, 39, 53, 85, 157, 171, 172, 175, 201, 202, 215, 238, 251, 254, 265], "letter": [9, 159, 251], "level": [8, 9, 10, 39, 48, 54, 73, 75, 76, 84, 85, 157, 159, 215, 231, 238, 265], "levenberg": [53, 202], "leverag": 39, "lfp6": [0, 267], "lfw": 238, "li": 53, "lib": [8, 10, 39, 48, 85, 86, 181, 236, 259, 260], "lib64": [10, 76, 85], "libc": 39, "libcd": 39, "libcos_doubl": 39, "liblinear": 236, "libm": 39, "libm_nam": 39, "librari": [2, 8, 10, 38, 39, 53, 54, 73, 75, 76, 77, 84, 157, 158, 202, 216, 231, 238, 253, 259, 265, 266, 267], "libthread_db": 10, "licens": [53, 73, 84, 85], "lidar": [1, 73, 75, 202, 205, 213, 267, 268], "lie": 231, "life": [9, 38, 73, 202, 249, 251], "light": [214, 215, 238], "lightest": 37, "like": [2, 8, 9, 38, 39, 53, 54, 55, 62, 70, 73, 74, 76, 77, 79, 84, 157, 159, 196, 202, 251, 253, 259, 265, 266, 267], "likelihood": [202, 233, 253, 254, 257, 258, 260, 263, 265], "likewis": 9, "lil": [38, 61, 66, 73], "lil_arrai": [63, 65, 66], "lilian": [0, 267], "lim_": 266, "limit": [9, 10, 37, 39, 53, 73, 75, 76, 90, 169, 215, 217, 251, 265], "linalg": [8, 53, 54, 65, 73, 74, 75, 85, 172, 175], "line": [8, 9, 10, 37, 38, 48, 53, 62, 73, 75, 76, 77, 78, 79, 81, 82, 85, 86, 90, 99, 100, 108, 118, 144, 150, 158, 159, 172, 175, 181, 187, 192, 197, 202, 203, 215, 231, 246, 249, 251, 257, 268], "line2d": [8, 62, 157, 158, 159, 172, 175, 181, 187, 192, 202, 215, 249, 251, 257], "line_profil": 54, "line_search": 48, "linear": [8, 37, 38, 57, 58, 61, 73, 75, 175, 180, 216, 217, 231, 232, 238, 250, 253, 254, 257, 258, 260, 268], "linear_model": [234, 235, 241, 242, 245, 246, 247, 249, 251], "linearli": 247, "linearloc": 117, "linearoper": [38, 61, 73], "linearregress": [234, 235, 242, 245, 249, 251], "linearsvc": [236, 238, 251], "lineno": 54, "linesearchwarn": 48, "linestyl": [89, 90, 91, 92, 93, 94, 95, 96, 97, 99, 100, 118, 125, 140, 145, 157, 246, 247, 268], "linewidth": [15, 24, 41, 43, 44, 48, 49, 50, 51, 68, 70, 89, 90, 91, 92, 93, 94, 95, 96, 97, 99, 100, 102, 106, 107, 115, 116, 118, 123, 125, 134, 140, 144, 145, 152, 157, 177, 181, 268], "link": [1, 2, 8, 38, 63, 73, 85, 157, 202, 267], "linsolv": 65, "linspac": [8, 41, 42, 44, 45, 46, 49, 51, 53, 62, 68, 70, 85, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 121, 123, 124, 127, 130, 140, 143, 144, 146, 150, 157, 158, 159, 161, 163, 166, 167, 177, 179, 180, 184, 186, 189, 190, 191, 193, 196, 198, 202, 206, 207, 216, 234, 239, 242, 245, 246, 251, 257, 258, 265], "linux": [8, 10, 39, 76, 80, 84, 85, 86, 231, 265], "list": [0, 1, 2, 3, 8, 9, 10, 37, 38, 39, 42, 43, 50, 61, 66, 70, 73, 74, 75, 76, 79, 81, 84, 85, 86, 159, 202, 231, 234, 251, 265, 267], "listdir": [85, 86, 203], "listedcolormap": [239, 245], "liter": [9, 70, 77, 79], "littl": [8, 39, 251], "live": [2, 39, 65, 231, 259, 267], "livermor": 202, "ll": [10, 54, 81, 157, 175, 197, 238, 251, 266], "lm": 202, "lmplot": [73, 217, 253, 259, 260], "ln": 172, "lo": [77, 175], "load": [8, 9, 37, 39, 42, 73, 75, 84, 86, 174, 182, 183, 201, 202, 203, 206, 207, 208, 209, 210, 211, 212, 216, 220, 231, 238, 240, 241, 244, 248, 253, 254, 256, 259, 260, 265], "load_data": 203, "load_diabet": [241, 251], "load_digit": [236, 237, 248, 251], "load_iri": [239, 240, 244, 251], "load_librari": 39, "loadlibrari": 39, "loadmat": [158, 202], "loadtxt": [6, 8, 158, 168, 172, 199, 202], "lobpcg": 65, "lobpcg_sakurai": 65, "loc": [42, 48, 89, 96, 97, 157, 168, 172, 179, 180, 181, 184, 186, 188, 189, 190, 193, 199, 202, 234, 241, 245, 249, 251], "local": [8, 9, 10, 35, 37, 46, 54, 65, 73, 76, 81, 86, 177, 188, 202, 217, 227, 238, 248], "local_mean": [10, 14, 37], "local_var": 10, "localcontext": 9, "locat": [8, 9, 39, 73, 75, 85, 86, 99, 100, 118, 202, 216, 268], "lock": [8, 9], "locket": 172, "log": [8, 9, 48, 175, 202, 207, 216, 253, 254, 257, 258, 259, 260, 263, 265, 266], "log10": [253, 259, 260], "log_a": 202, "log_b": 202, "log_r": 202, "log_z": 48, "logarithm": [197, 202], "logcombin": 266, "logging_f": 48, "loggingfunct": 48, "logic": [9, 78, 85, 175], "logical_and": [175, 204], "logical_not": 37, "logical_or": [35, 175, 227, 231], "logind": [85, 86], "logloc": 117, "lognorm": 197, "logo": [1, 37, 86, 157, 231, 267], "logspac": [234, 241, 251], "logsumexp": 202, "long": [2, 8, 9, 53, 54, 85, 171, 251, 265, 267], "long_lin": 85, "longdoubl": 171, "longer": [39, 85, 251], "longitud": 251, "longlist": 10, "look": [8, 9, 10, 39, 47, 53, 54, 73, 74, 77, 79, 99, 156, 157, 159, 175, 216, 217, 238, 260, 266, 268], "look_for_next_answ": 9, "lookup": 159, "loop": [8, 10, 38, 39, 54, 60, 73, 75, 76, 77, 159, 171, 172, 175, 203, 251], "loop_func": 8, "loos": 10, "lose": [8, 157], "loss": [202, 236, 246, 251], "lost": 9, "lot": [39, 78, 175, 238, 249, 251], "loui": 175, "low": [37, 39, 53, 202, 251], "lower": [10, 46, 47, 48, 105, 127, 146, 177, 192, 202, 204, 214, 216, 241, 251], "lowercas": 9, "lowest": 172, "lo\u00efc": [0, 1, 267], "lprof": 54, "lpython2": 39, "lru_cach": 9, "lsoda": [190, 202], "lsqunivariatesplin": 216, "lst": [10, 203], "lstsq": 53, "lt": 203, "ltorgo": 251, "lu": 202, "luckili": 39, "ludwig": [0, 1, 267], "lw": [12, 26, 62, 104, 108, 109, 110, 121, 124, 140, 150, 157, 158, 163, 229, 234], "lx": [23, 29, 37], "ly": [8, 23, 29, 37], "lynx": [8, 158, 168, 172, 199], "l\u00f3pez": [0, 1, 267], "m": [0, 8, 10, 24, 39, 54, 55, 65, 77, 105, 108, 110, 157, 184, 190, 202, 206, 207, 212, 216, 231, 248, 267], "m_0": [139, 154], "m_1m_2": [139, 154], "ma": [6, 8, 171], "mac": [39, 80, 85], "machin": [39, 73, 76, 217, 232, 233, 247, 250, 268], "machineri": [37, 56, 59], "maco": 84, "macro": [10, 236, 237, 238, 251], "mad": 253, "made": [8, 9, 159, 265], "magic": [9, 39, 74, 76, 157, 175], "magnitud": 202, "mahota": 231, "mai": [8, 10, 37, 39, 48, 53, 54, 70, 74, 77, 79, 80, 81, 82, 85, 159, 171, 175, 202, 231, 251, 253, 265], "mail": [8, 73, 75], "mailman3": 8, "main": [10, 38, 39, 59, 70, 73, 85, 86, 157, 183, 265], "mainli": [39, 202], "maintain": [9, 70, 74, 238], "mainten": [2, 39, 267], "major": [1, 83, 84, 125, 145, 157, 159, 267], "make": [1, 2, 9, 10, 38, 39, 70, 73, 76, 78, 85, 86, 142, 143, 148, 153, 157, 172, 177, 197, 198, 216, 223, 231, 251, 253, 258, 265, 266, 267], "make_big_arrai": 10, "make_blob": 246, "make_interp_splin": [184, 202], "make_pipelin": [234, 251], "make_smoothing_splin": [184, 202], "makefil": [39, 70], "male": [256, 259, 260, 263, 265], "male_viq": 265, "mallet": 215, "man": 10, "manag": [38, 39, 73, 76, 79, 171, 238, 259, 265], "mandatori": [65, 76, 81, 83], "mandel": 8, "mandel_single_point": 8, "mandel_single_point_singleprec": 8, "mandelbrot": [1, 8, 73, 75, 78, 160, 170, 173, 174, 267, 268], "mandelbrot_set": 166, "mandelplot": 8, "mangan": [0, 1, 267], "mangl": 9, "mani": [1, 8, 9, 10, 37, 39, 53, 54, 55, 66, 74, 76, 77, 84, 85, 157, 166, 175, 202, 231, 251, 265, 267], "manifold": [248, 251], "manipul": [1, 8, 11, 36, 38, 39, 56, 59, 73, 75, 76, 77, 85, 157, 176, 194, 201, 217, 231, 267, 268], "mann": 265, "manner": [9, 251], "mannwhitneyu": 265, "mannwhitneyuresult": 265, "manual": [8, 39, 73, 75, 76, 174, 251, 258], "manuel": [0, 1, 267], "manufactur": 259, "map": [10, 37, 39, 77, 85, 105, 227, 239, 245], "mapl": 266, "mappingproxi": 8, "march": 83, "marco": [0, 1, 267], "mark": [0, 1, 9, 157, 177, 267], "mark_boundari": [219, 231], "marker": [35, 42, 65, 73, 75, 99, 100, 118, 150, 217, 227, 234, 253, 254, 263, 265, 268], "markeredgecolor": [111, 112, 113, 114, 157], "markeredgewidth": [41, 111, 112, 113, 114, 157], "markerfacecolor": [111, 112, 113, 114, 157], "markers": [41, 46, 48, 65, 111, 112, 113, 114, 157, 224], "market": [202, 251], "marklodato": 8, "markov": [73, 75, 174], "markup": [1, 2, 267], "marquardt": [53, 202], "marr": 259, "marri": 259, "masaron": [0, 1, 267], "mask": [5, 7, 12, 15, 22, 24, 26, 28, 29, 30, 33, 34, 35, 37, 38, 54, 73, 75, 85, 171, 172, 174, 175, 178, 185, 201, 202, 204, 214, 219, 227, 231, 268], "mask_circle1": [35, 227, 231], "mask_circle2": [35, 227, 231], "mask_siz": [22, 28, 37], "masked_arrai": [6, 38, 73, 171], "maskedarrai": [38, 73, 75, 174], "mass": [176, 194, 202, 268], "massag": [39, 260], "master": 175, "masterstud": 83, "mat": 202, "match": [73, 74, 75, 84, 198, 231, 237, 251, 266], "materi": [3, 70, 267], "math": [39, 53, 54, 157, 181, 202, 203], "mathemat": [1, 10, 11, 25, 30, 36, 38, 62, 73, 75, 76, 157, 176, 194, 204, 214, 217, 267, 268], "mathematica": 266, "mathematical_optim": [48, 52, 268], "mathrm": 8, "matlab": [73, 75, 77, 157, 158, 159, 202], "matmul_for_strided_matric": 8, "matploblib": 125, "matplotlib": [1, 2, 6, 8, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 62, 65, 66, 68, 70, 73, 74, 75, 76, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 100, 101, 102, 103, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 158, 159, 161, 162, 163, 164, 165, 166, 167, 168, 169, 172, 175, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 201, 202, 204, 206, 207, 208, 209, 210, 211, 212, 215, 216, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 231, 233, 234, 235, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 251, 253, 254, 255, 256, 257, 258, 259, 260, 263, 267, 268], "matric": [8, 38, 55, 56, 61, 65, 73, 175, 202, 217, 251, 253, 256, 259], "matrix": [8, 38, 47, 53, 54, 55, 56, 57, 58, 59, 60, 61, 63, 64, 65, 66, 73, 74, 159, 172, 175, 202, 214, 237, 238, 253, 254, 257, 258, 260, 263, 265, 266], "matrixmarket": 158, "matshow": [10, 222], "matt": [0, 267], "matter": [8, 39, 81, 251, 265], "matthew": [0, 267], "matthieu": [0, 1, 267], "matvec": 65, "max": [13, 24, 31, 37, 48, 89, 92, 93, 94, 95, 96, 97, 157, 159, 171, 175, 196, 201, 202, 203, 204, 206, 207, 212, 216, 231, 239], "max_open_warn": 48, "max_spe": [206, 207, 212, 216], "maxaxi": 10, "maxim": 201, "maxima": [10, 35, 175, 201, 202, 206, 207, 212, 216, 227, 231], "maximilien": [0, 267], "maximum": [37, 48, 53, 65, 73, 75, 175, 201, 202, 231], "maximum_filt": 37, "maximum_posit": 37, "maxit": [41, 65], "may_share_memori": 159, "mayavi": [1, 267], "mayb": [76, 85], "mb": [7, 36, 52, 62, 69, 98, 118, 155, 156, 170, 194, 200, 213, 230, 250, 261, 264, 268], "mc": [139, 154], "mclaughlin": [0, 267], "mdash": 9, "mead": [38, 48, 73, 187], "mean": [8, 9, 11, 12, 15, 22, 24, 26, 28, 34, 36, 37, 42, 54, 62, 73, 76, 78, 81, 157, 159, 169, 171, 172, 175, 202, 204, 214, 226, 231, 234, 235, 238, 241, 251, 253, 268], "mean_": 238, "mean_bubble_s": 204, "mean_sq": [257, 258], "mean_sq_dist": [169, 175], "mean_val": 37, "mean_valu": 37, "meaning": [10, 37, 85, 231], "means_": 12, "meant": 202, "measur": [11, 36, 38, 39, 53, 73, 75, 85, 159, 184, 204, 214, 215, 216, 217, 226, 227, 232, 238, 249, 250, 255, 268], "measured_tim": [184, 202], "mec": [108, 110, 157, 206, 207], "mechan": [39, 62, 265], "med_denois": [19, 37], "med_filter_coin": 225, "medfilt": 202, "median": [11, 19, 36, 37, 175, 182, 202, 204, 214, 225, 231, 251, 265, 268], "median_bubble_s": 204, "median_coin": 231, "median_fac": [182, 201, 202], "median_filt": [16, 19, 37, 182, 201, 202, 204], "medinc": 251, "medium": 132, "meet": [159, 251], "mem": [7, 36, 52, 69, 98, 118, 155, 156, 170, 194, 200, 213, 230, 250, 261, 264, 268], "member": [251, 259], "memmap": 37, "memoiz": 9, "memor": 251, "memori": [10, 37, 38, 39, 48, 53, 54, 62, 73, 76, 77, 159, 171, 175, 251], "memory_profil": 54, "memoryview": 9, "mention": 9, "menu": [1, 10, 76, 80, 267], "mere": 9, "merg": [1, 267], "merit": 39, "mersenn": 159, "meshgrid": [123, 127, 131, 144, 146, 149, 157, 177, 202, 239, 246, 247, 258], "meson": 85, "messag": [8, 39, 78, 79, 80, 85, 187, 202], "met": 79, "meta": 10, "metadata": 39, "metaparamet": 251, "meteorolog": 216, "meth_vararg": 39, "method": [9, 37, 38, 39, 40, 43, 46, 47, 48, 50, 52, 54, 61, 62, 65, 73, 75, 76, 82, 83, 84, 85, 157, 159, 187, 190, 197, 199, 202, 215, 217, 227, 238, 251, 253, 254, 257, 258, 260, 263, 265, 266, 268], "method_index": 42, "method_nam": 42, "methodolog": 251, "metric": [231, 236, 237, 238, 251, 265], "mew": [157, 224], "mfc": [108, 110, 157, 206, 207], "mgrid": [43, 46, 47, 48, 50, 53, 134, 152, 157, 175], "mhemantha": [0, 267], "michael": [0, 1, 267], "michel": [1, 267], "michelemaroni89": [0, 1, 267], "microscopi": 214, "microsoft": 85, "mid": [1, 251, 267], "middl": [157, 251], "might": [2, 8, 9, 70, 85, 159, 175, 238, 251, 253, 263, 265, 267], "mike": [0, 1, 157, 267], "mile": 175, "milepost": 175, "million": 251, "millman": [0, 267], "min": [10, 37, 48, 89, 92, 93, 94, 95, 96, 97, 157, 175, 196, 202, 203, 239], "min_dist": [224, 231], "mind": [2, 8, 10, 54, 70, 202, 251, 267], "mine": 265, "mini": 8, "minim": [37, 38, 43, 46, 47, 48, 50, 65, 73, 177, 187, 201, 215, 231, 251], "minima": [38, 73, 175, 176, 194, 202, 204, 214, 268], "minimize_scalar": [41, 53, 202], "minimum": [37, 40, 52, 65, 84, 159, 175, 176, 188, 194, 202, 231, 268], "minor": [1, 10, 125, 145, 157, 267], "minr": 65, "minut": [6, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 68, 76, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 161, 162, 163, 164, 165, 166, 167, 168, 169, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 206, 207, 208, 209, 210, 211, 212, 216, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 253, 254, 255, 256, 257, 258, 259, 260, 263], "misc": [1, 43, 46, 47, 50, 85, 267], "miscellan": [10, 175], "mislead": [9, 251], "mismatch": [175, 202], "miss": [9, 10, 37, 38, 73, 75, 81, 174, 231, 251, 263, 265], "mistak": 251, "miter": [107, 116], "mitig": 8, "mix": [171, 202, 238, 256, 265], "mixtur": [11, 36, 37, 265, 268], "mk_gauss": 48, "mk_quad": 48, "mkdir": 86, "ml": 65, "mmread": 158, "mmwrite": 158, "mobil": [1, 84, 267], "mod": 70, "mode": [10, 21, 37, 39, 73, 75, 183, 198, 201, 202], "model": [11, 36, 37, 45, 73, 75, 157, 209, 211, 216, 217, 232, 233, 234, 236, 237, 238, 241, 242, 243, 245, 246, 250, 253, 254, 257, 258, 260, 263, 268], "model_select": [234, 235, 236, 237, 238, 241, 251], "moder": 202, "modern": [1, 39, 76, 265, 267], "modif": 81, "modifi": [2, 8, 9, 10, 37, 39, 70, 77, 78, 81, 85, 157, 159, 175, 201, 202, 231, 251, 267], "modul": [8, 9, 10, 18, 37, 38, 39, 54, 61, 66, 70, 73, 74, 75, 76, 77, 81, 84, 157, 159, 175, 202, 203, 215, 216, 231, 265], "modulo": 77, "modulu": 266, "mohammad": [0, 267], "moin": 9, "moment": 171, "monoton": [10, 202], "mont": 202, "month": [176, 195, 200, 202, 268], "moon": [0, 1, 267], "moonland": [197, 202], "more": [1, 9, 10, 20, 37, 38, 39, 48, 53, 54, 55, 63, 70, 73, 74, 75, 76, 78, 81, 82, 84, 85, 86, 99, 142, 157, 159, 174, 175, 181, 199, 201, 202, 203, 208, 215, 217, 231, 238, 240, 251, 253, 257, 258, 260, 266, 267], "moreov": [85, 216], "morpholog": 231, "morphologi": [11, 25, 30, 36, 38, 73, 75, 85, 176, 194, 204, 214, 217, 268], "mortem": 76, "most": [8, 9, 10, 37, 39, 54, 56, 57, 58, 76, 78, 79, 81, 84, 85, 157, 159, 175, 202, 215, 231, 238, 251, 266], "mostli": [39, 202, 260], "move": [8, 54, 73, 75, 76, 86, 159, 251], "movi": 251, "mp": 10, "mpl_toolkit": [131, 132, 149, 157, 177, 258], "mplot3d": [131, 132, 149, 157, 177, 258], "mpmath": 266, "mri": [37, 159, 231, 265], "mri_count": [256, 263, 265], "msgbox": 10, "msvcrt": 39, "mtrand": 54, "mtx": [55, 56, 57, 58, 59, 60, 63, 65, 66], "mtx1": 65, "mtx2": 65, "mu": [10, 139, 154, 215], "much": [2, 9, 39, 48, 53, 54, 70, 76, 86, 99, 157, 159, 175, 199, 202, 238, 243, 251, 255, 267], "mueller": [0, 1, 267], "multi": [73, 75, 84, 159, 231, 251], "multiarrai": [10, 54], "multicollinear": [253, 263], "multicolor": 251, "multidimension": [37, 38, 39, 73, 85, 159], "multigrid": 64, "multilinear": [257, 258], "multipl": [8, 39, 54, 59, 66, 70, 73, 80, 81, 99, 128, 141, 155, 157, 159, 171, 175, 202, 215, 217, 231, 252, 259, 260, 261, 266, 268], "multipleloc": [117, 125, 145], "multipli": [66, 198], "multiplot": 147, "multiprocess": 9, "multitud": 9, "multivari": 202, "must": [8, 9, 10, 39, 55, 70, 81, 82, 85, 172, 175, 215, 251, 265], "mutabl": [9, 77, 81], "mv": 65, "mv_hfv_012": [204, 214], "mwlzpy": [85, 86], "mx": 8, "my": 8, "my_fil": 76, "my_pi": 203, "myclass": 83, "myfunc": 10, "mymodul": 85, "m\u00fcller": [0, 157, 251, 267], "n": [8, 9, 10, 12, 15, 22, 24, 26, 28, 34, 37, 54, 55, 62, 65, 66, 74, 76, 77, 81, 88, 122, 123, 127, 129, 130, 132, 133, 134, 135, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 159, 171, 190, 201, 202, 203, 208, 209, 210, 211, 215, 216, 226, 231, 259, 266], "n_cluster": [33, 37], "n_col": 57, "n_compon": [12, 237, 238, 244, 248, 251], "n_diag": 59, "n_dim": 42, "n_dim_bench": 42, "n_dim_index": 42, "n_featur": 251, "n_job": 251, "n_line": 108, "n_locat": 117, "n_marker": 110, "n_max": [159, 166, 172], "n_method": 42, "n_neighbor": [236, 239, 251], "n_row": 58, "n_sampl": [234, 246, 247, 251], "n_split": 251, "n_stori": [169, 175], "n_th": 245, "na": 265, "na_valu": [255, 256, 263, 265], "nabla": [139, 154], "naiv": [73, 202, 217], "naive_bay": [236, 237, 251], "nake": 251, "nalgorithm": 233, "name": [8, 9, 10, 39, 70, 74, 76, 77, 79, 81, 83, 85, 159, 171, 203, 231, 240, 251, 253, 254, 259, 260, 265], "namespac": [9, 81, 85], "nan": [171, 257, 258, 265], "nand": 82, "nanosecond": 215, "nanova": [257, 258], "napari": 231, "narrow": 172, "nathan": [65, 66], "nathaniel": 65, "nativ": [39, 77, 80], "natur": [9, 53, 62, 73, 175, 202, 217], "navig": [76, 80], "nb": [178, 201, 202, 253], "nb_label": [22, 28, 34, 37], "nb_passeng": 253, "nb_passengers_2000": 253, "nb_passengers_2001": 253, "nbsp": [238, 244], "nbviewer": [238, 244], "ncall": 54, "ncol": 42, "nd": [8, 66], "ndarrai": [10, 37, 38, 39, 54, 62, 66, 73, 74, 159, 175, 231], "ndarrayobject": 39, "ndarraytyp": 39, "ndenumer": 246, "ndim": [39, 159, 171], "ndimag": [12, 13, 14, 15, 16, 19, 21, 22, 23, 24, 25, 26, 28, 30, 31, 32, 34, 35, 38, 73, 75, 85, 178, 182, 183, 185, 198, 201, 204, 214, 227, 231], "ndmin": 159, "ndocument": 233, "ndownload": 238, "ndpointer": 39, "nearest": [12, 16, 25, 26, 27, 30, 33, 35, 37, 127, 146, 158, 165, 183, 201, 202, 220, 221, 223, 224, 225, 227, 228, 229, 231, 232, 237, 246, 250, 251, 268], "nearli": [251, 265], "necessari": [39, 70, 73, 77, 84, 85, 157, 159, 175, 217, 231, 258], "necessarili": [159, 251], "need": [2, 8, 9, 10, 37, 39, 53, 54, 65, 67, 70, 73, 75, 77, 85, 157, 159, 171, 172, 175, 202, 203, 215, 216, 217, 231, 245, 251, 258, 259, 260, 263, 265, 267], "needless": 76, "neg": [59, 77, 202], "negm": [0, 267], "neighbor": [37, 73, 201, 202, 217, 231, 232, 236, 250, 268], "neighborhood": [40, 52, 53, 251, 268], "neighbourhood": [37, 231], "neither": [76, 159], "nelder": [38, 48, 73, 187], "nelder_mead": 48, "nell": [0, 1, 267], "nelson": [0, 267], "nest": [9, 73, 159], "nested": 9, "net": [64, 260], "netc": 233, "netcdf": 158, "netcdf4": 158, "netcdf_fil": 158, "netflix": 251, "network": [76, 175], "never": [8, 171], "nevertheless": [9, 175, 251], "new": [2, 8, 9, 10, 39, 54, 65, 70, 73, 76, 77, 81, 82, 83, 85, 90, 157, 159, 172, 175, 184, 233, 251], "new_path": 85, "newaxi": [8, 47, 48, 159, 164, 166, 172, 175, 198, 234, 238, 242, 251], "newbyteord": 39, "newer": [9, 66], "newli": [9, 159], "newlin": [76, 77], "newton": [38, 47, 48, 73, 202], "newton_cg": 48, "next": [8, 9, 10, 39, 78, 85, 157, 175, 251], "nfev": [53, 187, 202], "ng": 251, "nhev": 53, "nice": [9, 39, 74, 85, 157, 201, 202, 251], "nicer": 157, "nicoguaro": [0, 267], "nicola": [0, 1, 70, 157, 267], "nil": [10, 65], "nimag": 233, "nipy_spectr": [25, 28, 31, 33, 34, 35, 42, 226, 227, 228], "nit": [53, 187, 202], "njev": [53, 187, 202], "nlabel": 233, "nlearn": 233, "nmodel": 233, "nn": 251, "nntplib": 9, "nnz": 55, "noced": 53, "node": 62, "noexcept": 8, "nogil": [8, 9], "nois": [10, 37, 53, 179, 184, 202, 215, 242, 249, 251, 265], "noise_level": 10, "noiseless": 32, "noisi": [10, 16, 19, 20, 21, 37, 38, 40, 52, 73, 163, 167, 182, 201, 202, 268], "noisy_fac": [10, 182, 201, 202], "noisy_img": 10, "noisy_x": [249, 251], "nomask": 8, "non": [8, 10, 37, 38, 39, 40, 49, 52, 60, 63, 73, 75, 76, 84, 201, 202, 217, 232, 250, 253, 263, 265, 268], "none": [8, 9, 24, 37, 39, 48, 74, 76, 78, 81, 85, 86, 89, 95, 96, 97, 117, 134, 152, 157, 159, 201, 202, 234, 247, 251, 259, 260], "nonetheless": 265, "nonlinear": 202, "nonlinear_model": 247, "nonparametr": 265, "nonrobust": [253, 254, 257, 258, 260, 263, 265], "nonzero": [55, 57, 58, 62, 66, 159, 202, 238], "nope": 202, "nor": [159, 233], "norm": [38, 65, 73, 172, 186, 197, 202, 253], "norm_of_projected_gradient_": 53, "normal": [9, 12, 15, 16, 26, 33, 45, 47, 49, 53, 135, 153, 157, 172, 176, 180, 181, 184, 193, 194, 198, 202, 216, 234, 242, 245, 247, 249, 251, 253, 257, 258, 265, 268], "normaltest": 202, "norman": 266, "northern": 172, "nose": [10, 238], "nosetest": 10, "notabl": 251, "notat": [9, 77, 83], "note": [1, 2, 8, 9, 10, 37, 38, 39, 54, 61, 66, 67, 70, 73, 74, 76, 77, 80, 81, 82, 157, 159, 169, 175, 181, 198, 202, 231, 240, 251, 253, 254, 257, 258, 259, 260, 263, 265, 267], "notebook": [1, 5, 6, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 67, 68, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 99, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 173, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 202, 205, 206, 207, 208, 209, 210, 211, 212, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 252, 253, 254, 255, 256, 257, 258, 259, 260, 263, 265, 267], "noteworthi": 86, "noth": [9, 10, 39, 79], "notic": [39, 159, 202, 263], "notifi": 79, "noun": 9, "now": [1, 8, 10, 22, 35, 37, 39, 43, 50, 65, 76, 81, 83, 85, 157, 159, 172, 179, 181, 187, 201, 202, 203, 215, 216, 227, 231, 237, 238, 239, 251, 254, 266, 267], "np": [1, 2, 6, 8, 10, 12, 13, 15, 16, 19, 20, 21, 22, 23, 24, 25, 26, 28, 29, 30, 31, 33, 34, 35, 37, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59, 60, 62, 63, 65, 66, 68, 70, 74, 85, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 105, 106, 107, 108, 110, 111, 113, 115, 116, 117, 121, 122, 123, 124, 127, 129, 130, 131, 133, 134, 135, 139, 140, 142, 143, 144, 146, 148, 149, 150, 151, 152, 153, 154, 157, 158, 159, 161, 162, 163, 164, 165, 166, 167, 168, 169, 171, 172, 175, 177, 178, 179, 180, 181, 182, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 201, 202, 204, 206, 207, 208, 209, 210, 211, 212, 214, 215, 216, 219, 222, 225, 226, 227, 231, 233, 234, 235, 237, 238, 239, 241, 242, 245, 246, 247, 249, 251, 253, 257, 258, 259, 260, 265, 267], "npct": 39, "nprob": [206, 207, 216], "npy": [158, 206, 207, 208, 209, 210, 211, 212, 215, 216], "npy_1_7_api_vers": 39, "npy_bool": 8, "npy_byt": 8, "npy_cdoubl": 8, "npy_cfloat": 8, "npy_clongdoubl": 8, "npy_datetim": 8, "npy_deprecated_api": 39, "npy_doubl": [8, 39], "npy_equiv_cast": 39, "npy_float": 8, "npy_int": 8, "npy_intp": [8, 39], "npy_iter_align": 39, "npy_iter_alloc": 39, "npy_iter_buff": 39, "npy_iter_external_loop": 39, "npy_iter_growinn": 39, "npy_iter_nbo": 39, "npy_iter_readonli": 39, "npy_iter_writeonli": 39, "npy_iter_zerosize_ok": 39, "npy_keepord": 39, "npy_long": 8, "npy_longdoubl": 8, "npy_longlong": 8, "npy_no_deprecated_api": 39, "npy_object": 8, "npy_short": 8, "npy_str": 8, "npy_timedelta": 8, "npy_ubyt": 8, "npy_uint": 8, "npy_uint32": 39, "npy_ulong": 8, "npy_ulonglong": 8, "npy_unicod": 8, "npy_ushort": 8, "npy_void": 8, "npyiter": 39, "npyiter_dealloc": 39, "npyiter_getdataptrarrai": 39, "npyiter_getinnerloopsizeptr": 39, "npyiter_getinnerstridearrai": 39, "npyiter_getiternext": 39, "npyiter_getiters": 39, "npyiter_getoperandarrai": 39, "npyiter_iternextfunc": 39, "npyiter_multinew": 39, "nrepresent": 233, "nretriev": 258, "ntext": 233, "ntype": 8, "null": [8, 10, 39, 202, 265], "nullloc": [117, 157], "num": [9, 157, 159, 179, 196, 202, 203], "num_channel": 8, "num_input": 8, "num_output": 8, "numba": 8, "number": [8, 9, 10, 57, 58, 65, 66, 73, 74, 75, 76, 79, 84, 85, 157, 158, 171, 172, 175, 179, 181, 192, 197, 199, 201, 203, 216, 231, 234, 236, 237, 238, 251, 253, 259, 260, 263, 266], "numer": [33, 38, 39, 53, 75, 76, 84, 85, 159, 172, 215, 251, 253, 256, 263, 265, 266], "numexpr": [8, 54], "numpi": [1, 2, 6, 9, 10, 11, 12, 13, 15, 16, 19, 20, 21, 22, 23, 24, 25, 26, 28, 30, 31, 33, 34, 35, 36, 38, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59, 62, 63, 65, 66, 68, 70, 73, 74, 75, 76, 77, 81, 82, 84, 85, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 105, 106, 107, 108, 110, 111, 113, 115, 116, 117, 121, 122, 123, 124, 127, 129, 130, 131, 133, 134, 135, 139, 140, 142, 143, 144, 146, 148, 149, 150, 151, 152, 153, 154, 157, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 175, 177, 178, 179, 180, 181, 182, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 201, 204, 206, 207, 208, 209, 210, 211, 212, 215, 216, 219, 222, 225, 226, 227, 231, 233, 234, 235, 238, 239, 241, 242, 245, 246, 247, 249, 251, 253, 257, 258, 259, 260, 265, 266, 267, 268], "numpoint": 42, "numpy_backward_compat": 39, "numpydoc": 81, "nutshel": 8, "nvector": 233, "nx": 166, "ny": [166, 265], "n\u00e1jera": [1, 267], "o": [1, 6, 8, 10, 39, 42, 48, 54, 60, 66, 73, 75, 77, 78, 84, 85, 108, 110, 158, 159, 161, 167, 199, 206, 207, 231, 249, 251, 253, 254, 257, 259, 260, 263, 266, 267], "o2": 39, "o3": 39, "obei": [9, 202], "obj": [9, 159], "object": [1, 8, 11, 35, 36, 38, 39, 53, 54, 56, 62, 63, 66, 70, 73, 74, 75, 76, 78, 79, 84, 86, 157, 158, 165, 172, 174, 175, 177, 179, 181, 187, 192, 198, 199, 201, 215, 217, 227, 231, 234, 237, 238, 245, 247, 249, 253, 257, 260, 265, 268], "object_nam": 76, "obscur": [73, 75, 174], "observ": [39, 54, 186, 193, 202, 251, 253, 254, 257, 258, 260, 263, 265, 266], "obtain": [39, 76, 77, 86, 159, 169, 172, 175, 251], "obviou": [9, 78, 199], "obvious": [9, 39], "occup": 259, "occupi": 8, "occur": [53, 201, 202, 216, 251], "oct": [253, 254, 257, 258, 260, 263], "octav": [73, 75], "od": [74, 176, 194, 202, 255, 268], "odd": [159, 175], "odepack": 202, "odr": [85, 202], "off": [1, 8, 10, 12, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 39, 41, 43, 44, 49, 50, 51, 54, 65, 73, 105, 139, 171, 178, 181, 182, 183, 185, 201, 202, 219, 220, 221, 223, 224, 225, 226, 227, 228, 229, 231, 238, 267], "offer": [8, 77, 85, 202], "offici": [8, 39, 74], "offset": [8, 59, 89, 97, 131, 149, 157, 171, 202, 215, 254, 257, 260], "offset_1": 8, "offset_2": 8, "offset_3": 8, "offspr": 76, "often": [9, 10, 53, 54, 65, 76, 77, 78, 202, 215, 231, 238, 245, 248, 249, 251], "ogrid": [13, 29, 31, 37, 172, 175], "oh": 10, "ok": [8, 24, 39, 79], "oklahoma": 175, "ol": [253, 254, 257, 258, 260, 263, 265], "olav": [0, 1, 267], "old": [1, 9, 38, 39, 73, 85, 172, 267], "old_fval": 48, "older": 66, "olivetti": 238, "olivi": [0, 251, 267], "oller": [0, 1, 267], "omar": [0, 1, 267], "omega": [45, 53, 190, 197, 202], "omega_0": 202, "omit": [53, 76], "omnibu": [253, 254, 257, 258, 260, 263, 265], "onc": [8, 9, 10, 39, 41, 54, 60, 62, 77, 80, 147, 159, 171, 202, 231, 251, 259], "one": [8, 9, 10, 16, 21, 22, 37, 39, 43, 44, 53, 66, 70, 74, 76, 77, 78, 80, 81, 83, 84, 85, 157, 158, 159, 171, 172, 175, 202, 203, 215, 231, 238, 251, 253, 260, 265, 266], "ones": [8, 25, 33, 35, 37, 39, 53, 59, 65, 105, 106, 108, 110, 115, 129, 148, 157, 158, 159, 175, 201, 202, 203, 225, 227, 231, 247, 251, 253], "ones_lik": 159, "onli": [8, 9, 22, 39, 41, 43, 53, 54, 62, 65, 66, 74, 76, 81, 82, 84, 85, 99, 157, 158, 159, 181, 197, 198, 202, 203, 215, 216, 231, 238, 239, 249, 251, 253, 260, 265], "onlin": [53, 70, 74, 175], "ont": 10, "onto": [238, 251], "oo": 266, "oop": [73, 75, 77, 84, 86], "op": 66, "op_dtyp": 39, "op_flag": 39, "opaqu": 8, "open": [2, 8, 9, 10, 11, 24, 36, 38, 42, 48, 73, 74, 76, 82, 84, 86, 185, 201, 202, 203, 204, 214, 231, 238, 253, 259, 260, 267, 268], "open_img": [15, 37], "open_squar": [30, 37], "opencv": [37, 231, 238], "opened_mask": [185, 201, 202], "opened_mor": 24, "oper": [2, 9, 30, 37, 38, 39, 54, 55, 56, 57, 58, 59, 66, 73, 75, 76, 80, 84, 85, 159, 171, 172, 174, 201, 231, 265, 266, 267], "operand": [8, 79, 175], "oppos": [9, 39, 84, 157], "opposit": [10, 201, 202, 216], "opt": [48, 85, 86, 181, 236], "optic": 215, "optim": [1, 10, 38, 39, 41, 45, 46, 48, 51, 52, 65, 73, 75, 76, 85, 159, 176, 179, 187, 188, 194, 196, 209, 211, 215, 217, 231, 267, 268], "optimis": 54, "optimizewarn": 48, "optimum": 43, "option": [8, 9, 10, 37, 39, 41, 48, 53, 54, 62, 65, 73, 74, 75, 77, 81, 85, 118, 159, 202, 204, 214, 251, 253, 266, 268], "oral": 70, "orang": 248, "order": [0, 1, 9, 37, 38, 39, 54, 70, 73, 74, 77, 78, 81, 85, 157, 158, 159, 201, 202, 203, 204, 214, 227, 231, 232, 238, 250, 251, 266, 267, 268], "ordin": 79, "ordinari": [202, 251, 253, 265, 266], "org": [1, 3, 8, 9, 10, 37, 54, 70, 74, 76, 77, 82, 84, 85, 86, 158, 159, 215, 231, 238, 244, 256, 259, 265, 266, 267], "organ": [73, 75, 83, 84], "orient": [57, 58, 70, 73, 75, 84, 157, 159, 201, 202, 204, 214], "origin": [8, 16, 37, 38, 39, 46, 47, 48, 53, 70, 73, 77, 85, 105, 127, 146, 157, 159, 169, 175, 177, 181, 184, 189, 192, 197, 202, 204, 214, 216, 219, 238, 251, 257, 258], "orthogon": [202, 238, 251], "osayd": [0, 1, 267], "oscil": [53, 176, 194, 202, 268], "osx": [8, 39], "other": [1, 8, 37, 38, 39, 53, 54, 55, 56, 57, 58, 61, 73, 75, 77, 80, 81, 82, 84, 85, 158, 159, 171, 174, 201, 202, 204, 214, 231, 238, 253, 259, 263, 265, 266, 267], "otherwis": [8, 9, 53, 85, 159], "otsu": [73, 218, 230, 268], "our": [8, 9, 10, 39, 45, 46, 53, 54, 77, 81, 85, 159, 172, 188, 202, 215, 238, 249, 251, 260, 263], "ourselv": [39, 53], "out": [8, 9, 10, 37, 39, 48, 54, 65, 74, 76, 77, 78, 79, 81, 85, 86, 158, 159, 175, 182, 198, 201, 202, 203, 238, 251, 255, 265], "out_arrai": 39, "outdat": [1, 267], "outer": [8, 105], "outlier": 265, "outlin": [1, 267], "outperform": 76, "output": [2, 8, 10, 37, 39, 53, 54, 65, 70, 73, 74, 75, 84, 85, 86, 175, 198, 217, 238, 266, 267], "output_shap": [224, 231], "output_strides_n": 8, "output_strides_p": 8, "outsid": [10, 37, 81, 265], "outstrid": 10, "over": [8, 9, 10, 39, 73, 75, 84, 85, 157, 172, 202, 203, 216, 217, 234, 266], "overal": 251, "overcom": [39, 215], "overfit": [234, 243, 251], "overflow": [39, 166, 202, 218, 230, 231, 268], "overflowerror": 8, "overhead": [39, 53], "overlai": 202, "overlap": [8, 35, 227, 231], "overload": 177, "overrid": [10, 66, 85], "overshoot": 53, "overview": 174, "overwrit": 82, "own": [8, 10, 64, 70, 73, 74, 75, 77, 79, 81, 83, 85, 157, 159, 174, 251], "owndata": 8, "ozan": [0, 1, 267], "p": [0, 8, 10, 54, 108, 110, 139, 154, 158, 163, 167, 172, 202, 233, 246, 253, 254, 257, 258, 260, 263, 265, 267], "p0": [179, 202], "p_": 172, "p_50": 172, "p_i": 216, "p_stationari": 172, "pace": 251, "pack": 81, "packag": [1, 2, 8, 10, 37, 38, 39, 48, 61, 73, 74, 75, 76, 84, 86, 157, 159, 181, 202, 230, 231, 236, 250, 253, 260, 261, 264, 265, 266, 267, 268], "pad": [142, 143, 144, 145, 146, 147, 148, 150, 152, 153, 154, 198], "page": [1, 70, 73, 171, 238, 244, 267], "pai": [53, 85, 171], "paid": 76, "pain": 76, "pair": [9, 73, 217, 237, 246, 251, 252, 253, 261, 266, 268], "pairgrid": 253, "pairplot": [73, 217, 253, 259], "pamphil": [0, 267], "panda": [1, 2, 73, 76, 217, 252, 253, 254, 255, 257, 258, 259, 260, 261, 263, 267, 268], "panel": [77, 204, 214], "papapanagiot": [0, 267], "par": 159, "parabola": 202, "paragraph": [2, 81, 215, 267], "parallel": 9, "param": [45, 81, 179, 202, 257, 258], "param_grid": 10, "param_nam": [234, 251], "param_rang": [234, 251], "paramet": [9, 38, 45, 53, 61, 73, 74, 75, 77, 83, 84, 157, 159, 172, 176, 194, 202, 215, 216, 217, 232, 234, 249, 250, 253, 254, 257, 258, 263, 265, 268], "parametr": 265, "params_cov": 45, "params_covari": 179, "parenthes": [9, 77, 81], "pars": [39, 76, 85, 158], "parserwarn": 260, "part": [9, 10, 37, 38, 39, 66, 70, 73, 75, 79, 85, 157, 159, 172, 175, 181, 197, 202, 215, 217, 231, 238, 265, 266], "partial": [9, 62, 202], "particular": [1, 37, 39, 78, 84, 201, 202, 238, 251, 265, 267], "particularli": [9, 251, 260], "partit": [157, 231], "pass": [8, 9, 10, 39, 53, 66, 73, 75, 76, 79, 84, 85, 86, 157, 159, 175, 202, 215, 254, 263, 266], "passeng": 253, "past": [76, 85, 251], "patch": [8, 101, 102, 103, 104, 106, 107, 109, 111, 112, 113, 114, 115, 116, 117, 142, 143, 144, 145, 146, 147, 148, 150, 152, 153, 154, 233], "path": [39, 43, 48, 50, 73, 75, 85, 157, 203, 231, 253, 259, 260], "pathcollect": [179, 245, 251], "pathnam": 86, "patient": [10, 251], "patniharshit": [0, 267], "patsi": [2, 267], "pattern": [60, 63, 73, 74, 75, 77, 84, 238, 266], "pauli": [0, 1, 8, 174, 267], "pca": [54, 73, 217, 232, 237, 250, 268], "pcaifittedpca": [238, 244], "pcolor": [65, 164, 175], "pcolormesh": 239, "pd": 253, "pdb": 10, "pde": [59, 62, 202], "pdef": 10, "pdf": [1, 2, 53, 54, 73, 176, 194, 202, 265, 267, 268], "pdoc": 10, "peak": [181, 202, 215], "peak_freq": 181, "peak_idx": [35, 227, 231], "peak_local_max": [35, 227, 231], "peak_mask": [35, 227, 231], "pedregosa": [0, 1, 266, 267], "penalti": 251, "peopl": [70, 238, 251, 265], "pep": [8, 9, 39], "pep8": [2, 10, 267], "pepiot": [0, 267], "per": [8, 54, 73, 76, 90, 157, 159, 171, 175, 192, 251, 259, 260], "percal": 54, "percentil": 202, "percentile_filt": 37, "pereira": [0, 267], "perez": 76, "perfect": [238, 251], "perfectli": [249, 251], "perform": [8, 9, 12, 24, 26, 53, 54, 65, 73, 77, 174, 198, 201, 202, 217, 232, 235, 236, 238, 250, 257, 258, 265, 266, 268], "perhap": 39, "perimet": 231, "period": [172, 176, 181, 195, 200, 202, 216, 268], "permiss": [53, 73, 75], "permit": [9, 56, 215], "permut": 8, "persist": [73, 75, 81, 84], "person": [251, 259, 265], "pervas": 9, "petal": [251, 252, 261, 265, 268], "petal_length": [254, 265], "pettiaux": [0, 1, 267], "pfile": 10, "phase": [9, 202, 204, 214], "phi": [45, 53], "phi_star": 48, "philip": [0, 267], "philipp": [0, 267], "phone": 84, "phoni": 39, "photo": 251, "photogrammetri": 215, "photograph": 251, "php": [10, 84], "physic": [62, 83, 175, 202, 265], "physiolog": 251, "pi": [39, 68, 70, 78, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 121, 124, 130, 133, 139, 140, 150, 151, 154, 157, 178, 181, 184, 192, 196, 201, 202, 247, 266], "pick": [8, 9, 39, 172], "pickl": [42, 73, 75, 84], "pickleshar": [2, 267], "pictur": [1, 73, 75, 174, 232, 250, 251, 267, 268], "pie": [73, 75, 99, 141, 155, 156, 268], "piec": [10, 39, 53, 238, 251], "pierr": [0, 1, 267], "pil": [8, 18, 37], "pilbuff": 8, "pillow": [2, 8, 267], "pinfo": 10, "pinfo2": 10, "pink": 77, "pint": [0, 1, 174, 267], "pip": [1, 2, 231, 267], "pipe": [85, 86], "pipelin": [157, 231, 234, 251, 265], "piq": [255, 256], "pivot": [81, 203, 265], "pixel": [37, 90, 157, 159, 172, 201, 202, 204, 214, 227, 231, 237, 238, 251], "pkl": [42, 86], "place": [1, 8, 9, 10, 39, 54, 70, 77, 81, 157, 171, 175, 251, 267], "placement": 157, "plai": [8, 157], "plain": [80, 85], "plan": 76, "plane": [202, 246, 251, 265], "platform": [8, 74, 84, 86, 171, 215], "pleas": [39, 53, 70, 79, 85, 215, 238, 244], "pleasant": 76, "ploint": 246, "plot": [1, 6, 8, 11, 12, 18, 24, 26, 36, 37, 39, 40, 41, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 62, 65, 68, 70, 73, 74, 75, 76, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 99, 100, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 141, 143, 144, 155, 156, 158, 159, 160, 163, 164, 166, 167, 168, 169, 170, 172, 173, 175, 176, 179, 180, 184, 185, 186, 187, 189, 190, 191, 194, 198, 202, 206, 207, 208, 209, 210, 211, 215, 216, 217, 224, 229, 231, 232, 233, 234, 235, 238, 239, 241, 242, 243, 246, 247, 250, 251, 252, 253, 254, 255, 257, 258, 259, 260, 261, 263, 267, 268], "plot_1d_optim": [41, 52, 268], "plot_2d_minim": [177, 194, 268], "plot_airfar": [253, 261, 268], "plot_alias": [101, 118, 268], "plot_alpha": [102, 118, 268], "plot_antialias": [103, 118, 268], "plot_ax": [119, 120, 156, 268], "plot_bad": [121, 156, 268], "plot_bar": [122, 156, 268], "plot_bar_ext": [142, 155, 268], "plot_basic1dplot": [161, 170, 268], "plot_basic2dplot": [162, 170, 268], "plot_bias_vari": [234, 250, 268], "plot_block_mean": [13, 36, 268], "plot_blur": [14, 36, 268], "plot_boundari": [219, 230, 268], "plot_boxplot_ext": [143, 155, 268], "plot_brain_s": [263, 264, 268], "plot_california_predict": [235, 250, 268], "plot_camera": [220, 230, 268], "plot_camera_uint": [221, 230, 268], "plot_chebyfit": [163, 170, 268], "plot_check": [222, 230, 268], "plot_clean_morpho": [15, 36, 268], "plot_color": [104, 118, 268], "plot_colormap": [105, 118, 268], "plot_compare_classifi": [236, 250, 268], "plot_compare_optim": [42, 52, 268], "plot_connect_measur": [178, 194, 268], "plot_constraint": [43, 52, 268], "plot_contour": [123, 156, 268], "plot_contour_ext": [144, 155, 268], "plot_convex": [44, 52, 268], "plot_corn": 231, "plot_cumulative_wind_speed_predict": [206, 213, 268], "plot_curve_fit": [45, 52, 179, 194, 268], "plot_curvefit_temperature_data": [196, 200, 268], "plot_dash_capstyl": [106, 118, 268], "plot_dash_joinstyl": [107, 118, 268], "plot_denois": [16, 36, 268], "plot_detrend": [180, 194, 268], "plot_digits_simple_classif": [237, 250, 268], "plot_display_fac": [17, 36, 268], "plot_dist": [164, 170, 268], "plot_eigenfac": [238, 250, 268], "plot_eleph": [165, 170, 268], "plot_equalize_hist": [223, 230, 268], "plot_exercise_1": [88, 98, 157, 268], "plot_exercise_10": [89, 98, 268], "plot_exercise_2": [90, 98, 268], "plot_exercise_3": [91, 98, 268], "plot_exercise_4": [92, 98, 268], "plot_exercise_5": [93, 98, 268], "plot_exercise_6": [94, 98, 268], "plot_exercise_7": [95, 98, 268], "plot_exercise_8": [96, 98, 268], "plot_exercise_9": [97, 98, 268], "plot_exercise_flat_minimum": [46, 52, 268], "plot_exercise_ill_condit": [47, 52, 268], "plot_fac": [18, 36, 268], "plot_face_denois": [19, 36, 268], "plot_face_tv_denois": [20, 36, 268], "plot_featur": [224, 230, 268], "plot_fft_image_denois": [197, 200, 268], "plot_fftpack": [181, 194, 268], "plot_filter_coin": [225, 230, 268], "plot_find_edg": [21, 36, 268], "plot_find_object": [22, 36, 268], "plot_geom_fac": [23, 36, 268], "plot_gmm": [12, 36, 268], "plot_good": [124, 156, 268], "plot_gradient_desc": [48, 52, 268], "plot_granulo": [24, 36, 268], "plot_greyscale_dil": [25, 36, 268], "plot_grid": [125, 156, 268], "plot_grid_ext": [145, 155, 268], "plot_gridspec": [126, 156, 268], "plot_gumbell_wind_speed_predict": [207, 213, 268], "plot_histo_segment": [26, 36, 268], "plot_image_blur": [198, 200, 268], "plot_image_filt": [182, 194, 268], "plot_image_transform": [183, 194, 268], "plot_imshow": [127, 156, 268], "plot_imshow_ext": [146, 155, 268], "plot_interpol": [184, 194, 268], "plot_interpolation_fac": [27, 36, 268], "plot_iris_analysi": [254, 261, 268], "plot_iris_knn": [239, 250, 268], "plot_iris_scatt": [240, 250, 268], "plot_label": [226, 230, 268], "plot_linear_model_cv": [241, 250, 268], "plot_linear_regress": [242, 250, 268], "plot_linestyl": [108, 118, 268], "plot_linewidth": [109, 118, 268], "plot_m": [114, 118, 268], "plot_mandelbrot": [166, 170, 268], "plot_mark": [110, 118, 268], "plot_maskedstat": [6, 7, 268], "plot_match": 231, "plot_mathematical_morpho": [185, 194, 268], "plot_measure_data": [28, 36, 268], "plot_measuring_perform": [243, 250, 268], "plot_mec": [111, 118, 268], "plot_mew": [112, 118, 268], "plot_mfc": [113, 118, 268], "plot_ml_flow_chart": [233, 250, 268], "plot_multiplot": [128, 156, 268], "plot_multiplot_ext": [147, 155, 268], "plot_noisi": [49, 52, 268], "plot_non_bounds_constraint": [50, 52, 268], "plot_normal_distribut": [186, 194, 268], "plot_numpy_arrai": [29, 36, 268], "plot_optimize_example1": [187, 194, 268], "plot_optimize_example2": [188, 194, 268], "plot_optimize_lidar_complex_data": [208, 213, 268], "plot_optimize_lidar_complex_data_fit": [209, 213, 268], "plot_optimize_lidar_data": [210, 213, 268], "plot_optimize_lidar_data_fit": [211, 213, 268], "plot_paired_boxplot": [255, 261, 268], "plot_panda": [256, 261, 268], "plot_pca": [244, 250, 268], "plot_periodicity_find": [199, 200, 268], "plot_pi": [129, 156, 268], "plot_pie_ext": [148, 155, 268], "plot_plot": [130, 156, 268], "plot_plot3d": [131, 132, 156, 268], "plot_plot3d_ext": [149, 155, 268], "plot_plot_ext": [150, 155, 268], "plot_polar": [133, 156, 268], "plot_polar_ext": [151, 155, 268], "plot_polyfit": [167, 170, 268], "plot_polynomial_regress": [245, 250, 268], "plot_popul": [168, 170, 268], "plot_propag": [30, 36, 268], "plot_quiv": [134, 156, 268], "plot_quiver_ext": [152, 155, 268], "plot_radial_mean": [31, 36, 268], "plot_randomwalk": [169, 170, 268], "plot_regress": [257, 261, 268], "plot_regression_3d": [258, 261, 268], "plot_resampl": [189, 194, 268], "plot_scatt": [135, 156, 268], "plot_scatter_ext": [153, 155, 268], "plot_segment": [227, 230, 268], "plot_separ": [246, 250, 268], "plot_sharpen": [32, 36, 268], "plot_simpl": [68, 69, 70, 268], "plot_smooth": [51, 52, 268], "plot_sobel": [228, 230, 268], "plot_solid_capstyl": [115, 118, 268], "plot_solid_joinstyl": [116, 118, 268], "plot_solve_ivp_damped_spring_mass": [190, 194, 268], "plot_solve_ivp_simpl": [191, 194, 268], "plot_spectral_clust": [33, 36, 268], "plot_spectrogram": [192, 194, 268], "plot_spectrum": 197, "plot_sprog_annual_maxima": [212, 213, 268], "plot_subplot": [136, 137, 138, 156, 268], "plot_supervised_chart": 233, "plot_surfac": [131, 149, 157, 177, 258], "plot_svm_non_linear": [247, 250, 268], "plot_synthetic_data": [34, 36, 268], "plot_t_test": [193, 194, 268], "plot_text": [139, 156, 268], "plot_text_ext": [154, 155, 268], "plot_threshold": [229, 230, 268], "plot_tick": [117, 118, 268], "plot_tsn": [248, 250, 268], "plot_ugli": [140, 156, 268], "plot_unsupervised_chart": 233, "plot_variance_linear_regr": [249, 250, 268], "plot_wage_data": [259, 261, 268], "plot_wage_education_gend": [260, 261, 268], "plot_watershed_segment": [35, 36, 268], "plot_xxx": 70, "plower": 181, "plt": [6, 8, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 62, 65, 66, 68, 70, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 158, 159, 161, 162, 163, 164, 165, 166, 167, 168, 169, 172, 175, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 201, 202, 204, 206, 207, 208, 209, 210, 211, 212, 215, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 231, 233, 234, 235, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 251, 253, 254, 255, 256, 257, 258, 259, 260, 263, 265], "plug": 238, "plugin": [10, 38, 73], "pm": 157, "png": [8, 18, 37, 54, 70, 86, 157, 158, 165, 172, 197, 198, 202, 206, 231], "pocket": 77, "pogrebnyak": [0, 1, 267], "point": [1, 2, 9, 10, 12, 15, 22, 24, 26, 28, 34, 37, 38, 44, 53, 57, 58, 73, 74, 75, 76, 80, 89, 90, 97, 99, 156, 158, 159, 171, 172, 175, 189, 202, 216, 226, 231, 237, 239, 246, 248, 249, 251, 265, 266, 267, 268], "pointer": [8, 39], "poisson": 65, "polar": [73, 75, 99, 141, 155, 156, 268], "pollut": 9, "poly1d": [158, 167], "polyfit": [158, 167], "polygon": 233, "polynom": 234, "polynomi": [1, 73, 74, 75, 160, 163, 170, 173, 174, 232, 250, 266, 267, 268], "polynomialfeatur": [234, 251], "polynomialfeatures__degre": [234, 251], "polyquadmesh": 175, "polyvand": 74, "pooch": [2, 267], "pool": 9, "poor": [10, 76], "poorli": 251, "pop": [1, 77, 158, 267], "pop1": 253, "pop2": [158, 253], "popul": [6, 8, 73, 158, 160, 170, 172, 173, 175, 199, 251, 268], "popup": [1, 267], "port": 76, "portabl": [85, 86, 158], "portion": 251, "pos_mask": 181, "posit": [9, 10, 39, 56, 57, 58, 59, 65, 70, 79, 81, 85, 117, 120, 157, 159, 169, 171, 175, 181, 202, 215], "possibl": [2, 8, 9, 39, 53, 54, 70, 74, 76, 77, 78, 85, 175, 186, 202, 215, 216, 231, 251, 265, 266, 267], "possibli": [8, 10], "post": [39, 73, 76, 217], "postmortem": [38, 73], "potenti": 39, "potentialflow": 83, "powel": [38, 46, 47, 48, 73], "power": [9, 37, 74, 76, 78, 157, 176, 194, 199, 202, 231, 245, 251, 265, 266, 268], "powsimp": 266, "pp": [10, 215], "ppc": 8, "pr": [257, 258], "practic": [38, 39, 73, 75, 81, 84, 159, 215, 251, 265], "practition": 251, "pre": [2, 8, 76, 238, 267], "prealloc": 39, "preced": 76, "precis": [8, 9, 53, 54, 62, 65, 81, 202, 237, 238, 251, 266], "precondit": [38, 46, 61, 73], "precondition": 65, "predict": [73, 75, 202, 205, 213, 217, 232, 233, 234, 235, 236, 237, 238, 242, 243, 245, 249, 250, 265, 268], "predict_proba": 251, "predomin": 251, "predominantli": 231, "prefer": [2, 8, 9, 10, 53, 54, 70, 73, 202, 245, 265, 267], "prefix": [9, 10, 76, 86], "prematur": 54, "premis": 9, "prepar": [63, 65], "preparatori": 9, "prepend": [77, 159], "preprocess": [73, 217, 234, 251], "prerequisit": [38, 61, 73, 231], "prescal": 53, "presenc": [9, 254], "present": [8, 9, 39, 70, 74, 253, 259, 260], "preserv": [8, 9, 37, 159], "press": [76, 77, 78], "pressur": 251, "pretti": [9, 43, 46, 47, 53, 243], "pretty_plot": [144, 155, 268], "prevent": 251, "preview": 9, "previou": [9, 39, 54, 76, 78, 79, 83, 85, 175, 216, 231, 251, 265], "previous": [8, 9, 39, 76, 251], "price": [73, 85, 217, 234, 235, 243], "primari": [2, 267], "primarili": [39, 238], "prime_2": [139, 154], "prime_2u": [139, 154], "prime_siev": 159, "primit": 231, "princip": [54, 73, 217], "principl": [53, 73, 217], "print": [1, 2, 8, 9, 41, 47, 48, 59, 63, 65, 76, 78, 79, 80, 81, 82, 85, 86, 99, 141, 155, 156, 157, 159, 172, 179, 187, 188, 203, 211, 231, 235, 236, 237, 238, 241, 251, 253, 254, 257, 258, 260, 263, 265, 267, 268], "print_a": 85, "print_b": 85, "print_big_arrai": 10, "print_sort": 79, "prior": [8, 53], "priori": 215, "privat": [85, 86], "prize": 251, "prng": 159, "pro": [62, 76], "prob": [253, 254, 257, 258, 260, 263, 265], "probabilist": [231, 265], "probabl": [39, 73, 75, 76, 157, 158, 171, 172, 175, 186, 198, 199, 206, 207, 251], "probe": [37, 231], "problem": [2, 8, 9, 10, 38, 39, 40, 42, 47, 48, 52, 54, 61, 64, 73, 74, 75, 76, 78, 175, 191, 217, 221, 232, 234, 238, 239, 245, 250, 253, 263, 265, 267, 268], "problemat": 81, "proce": 39, "procedur": 157, "process": [1, 9, 10, 14, 38, 39, 54, 62, 73, 75, 76, 175, 201, 215, 217, 238, 251, 267], "processing_of_dataset_": 77, "processing_of_dataset_102": 77, "processpoolexecutor": 9, "prod_": 78, "produc": [8, 9, 37, 202, 215], "product": [8, 10, 55, 57, 58, 65, 66, 74], "prof": 54, "profession": [86, 202, 259], "profici": 38, "profil": [38, 73, 76, 85], "profile_0hypzgow": [85, 86], "profile_11ziuez6": [85, 86], "profile_1cugsmec": [85, 86], "profile_22__f0c6": [85, 86], "profile_267svnq6": 86, "profile_2kz2rfqp": [85, 86], "profile_2l_ke68z": [85, 86], "profile_2ta9m44a": [85, 86], "profile_3lizqjwg": [85, 86], "profile_4qbivbpo": [85, 86], "profile_4r1xh4ri": [85, 86], "profile_4vqz1s29": [85, 86], "profile_4ykszos_": [85, 86], "profile_56ka35ba": [85, 86], "profile_5m0fjzr5": 86, "profile_5pm0nlnf": [85, 86], "profile_6_mve7iw": 86, "profile_6n6cz2vr": [85, 86], "profile_76qua5_1": [85, 86], "profile_7qe0bk4f": [85, 86], "profile_8518z0r4": [85, 86], "profile_8_2rsj1": [85, 86], "profile_999p7gzi": [85, 86], "profile_9gs54uhd": [85, 86], "profile_9i3ux322": [85, 86], "profile__63efn63": [85, 86], "profile__77z6xrn": [85, 86], "profile__w7pjcek": [85, 86], "profile_augff_pi": [85, 86], "profile_b9dyy5zp": 86, "profile_bt_5mf31": [85, 86], "profile_d5i0armu": [85, 86], "profile_dvest70f": 86, "profile_ecz_surr": [85, 86], "profile_elmz4kdk": [85, 86], "profile_fabal2mz": 86, "profile_g__46icb": 86, "profile_ga6kbhr8": [85, 86], "profile_ge3hemni": [85, 86], "profile_gp23o325": [85, 86], "profile_h2io_49d": [85, 86], "profile_i0ehttqi": 86, "profile_ij9ozup1": [85, 86], "profile_ishv245g": [85, 86], "profile_ixn68sfi": 86, "profile_j09siifo": [85, 86], "profile_j1tc79ad": [85, 86], "profile_j7bticpb": [85, 86], "profile_j8w6qumk": 86, "profile_jyzqwe1k": 86, "profile_k1gvdoov": [85, 86], "profile_k1u18zcv": [85, 86], "profile_l89rd3_": [85, 86], "profile_ldwq_g2z": [85, 86], "profile_np_so14h": [85, 86], "profile_opiqsgvm": [85, 86], "profile_psqqkg8b": [85, 86], "profile_rp3xs_ex": [85, 86], "profile_rq9456f6": [85, 86], "profile_rzk36k1d": [85, 86], "profile_tvmx7dqn": [85, 86], "profile_uf6uujd2": [85, 86], "profile_uijgtctx": [85, 86], "profile_v47o6p9h": [85, 86], "profile_v_v3jbub": [85, 86], "profile_vjshp4vh": [85, 86], "profile_vljqla3g": [85, 86], "profile_x5kjw20k": [85, 86], "profile_xpjos9ca": [85, 86], "profile_yccpaqyp": [85, 86], "profit": 85, "program": [9, 10, 39, 53, 54, 70, 73, 75, 76, 80, 84, 85, 86, 202, 203, 251, 265], "programm": [76, 202], "programmat": 157, "progress": [74, 76, 251], "proj": [237, 251], "project": [1, 2, 9, 70, 74, 85, 106, 115, 131, 132, 177, 238, 244, 248, 251, 258, 267], "promot": 159, "prompt": [1, 10, 76, 157, 267], "prone": 9, "prop": [42, 48, 231], "propag": [9, 11, 36, 37, 73, 75, 174, 215, 268], "proper": [8, 9], "properli": [9, 157], "properti": [9, 38, 73, 75, 215, 217], "propos": [2, 9, 202, 215, 267], "protect": 9, "protocol": [9, 38, 39, 73, 76, 159], "prototyp": 39, "proven": 53, "provid": [2, 8, 9, 37, 39, 53, 70, 77, 78, 85, 86, 157, 159, 172, 175, 201, 202, 203, 215, 216, 231, 238, 251, 257, 258, 267], "psd": 202, "psearch": 74, "psourc": 10, "pt": 251, "pth": 203, "pthread": 39, "ptp": 48, "public": [76, 157], "publish": [157, 251], "pudb": 10, "pull": [8, 39, 70, 238], "pure": [9, 38, 39, 73, 175], "purpl": [77, 248], "purpos": [8, 9, 53, 76, 197, 202, 265], "push": [39, 70, 251], "put": [1, 9, 70, 85, 157, 239, 266, 267], "pvalu": [202, 265], "pwd": 158, "pxd": 85, "py": [6, 7, 8, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 65, 68, 69, 70, 76, 78, 85, 86, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 159, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 172, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 196, 197, 198, 199, 200, 203, 206, 207, 208, 209, 210, 211, 212, 213, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 253, 254, 255, 256, 257, 258, 259, 260, 261, 263, 264, 268], "py_buildvalu": 39, "py_decref": 39, "py_incref": 39, "py_initmodul": 39, "py_major_vers": 39, "pyamg": [64, 65], "pyamg_with_lobpcg": 65, "pyarg_parsetupl": 39, "pyarray_data": 39, "pyarray_descr": [8, 39], "pyarray_descrfromtyp": 39, "pyarray_typ": 39, "pyarrayobject": [8, 39], "pyarrow": [2, 267], "pybufferproc": 8, "pyc": [39, 54, 85], "pycf_only_ast": 76, "pycharm": 76, "pycheck": 10, "pydata": [256, 259], "pyerr_occur": 39, "pyeval_evalframeex": 10, "pyflak": [38, 73], "pyfram": 10, "pygmo": 53, "pyhkei": 9, "pyinit_cos_modul": 39, "pyinit_cos_module_np": 39, "pylab": [1, 267], "pylint": 10, "pymc": 265, "pymc2": [1, 267], "pymc3": [1, 267], "pymethoddef": 39, "pymodinit_func": 39, "pymodule_cr": 39, "pymoduledef": 39, "pymoduledef_head_init": 39, "pyobject": [8, 39], "pyobject_head": 8, "pypi": 9, "pyplot": [6, 8, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 62, 65, 66, 68, 70, 73, 75, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 159, 161, 162, 163, 164, 165, 166, 167, 168, 169, 172, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 201, 202, 204, 206, 207, 208, 209, 210, 211, 212, 215, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 231, 233, 234, 235, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 253, 254, 255, 256, 257, 258, 259, 260, 263, 265], "pyspars": 64, "pytabl": 158, "pytest": [1, 2, 9, 267], "python": [1, 2, 5, 6, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 38, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 60, 63, 65, 66, 67, 68, 70, 74, 77, 78, 80, 81, 82, 83, 85, 86, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 99, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 202, 203, 205, 206, 207, 208, 209, 210, 211, 212, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 252, 253, 254, 255, 256, 257, 258, 259, 260, 263], "python2": [10, 39], "python3": [2, 10, 48, 76, 85, 86, 181, 236, 267], "python312": [85, 86], "python_c_api": 39, "python_languag": 86, "python_talk": 85, "python_ufunc": 8, "pythondecoratorlibrari": 9, "pythonpath": [85, 86], "pyufunc_": 8, "pyufunc_d_d": 8, "pyufunc_dd_d": 8, "pyufunc_f_f": 8, "pyufunc_ff_f": 8, "pyufunc_fromfuncanddata": 8, "pyufunc_fromfuncanddataandsignatur": 8, "pyufuncgenericfunct": 8, "pyx": [1, 8, 39, 267], "q": [8, 10], "qmr": 65, "qr": 202, "qsort": 203, "qt": 231, "quad": 202, "quadcontourset": [37, 231, 247], "quadrat": 202, "quadratur": [73, 75], "qualiti": [76, 84, 157, 251], "quantifi": [238, 251], "quantil": 216, "quantile_func": 216, "quantit": [73, 217], "quantiti": [28, 235, 251, 252, 261, 265, 268], "quantiz": 202, "quasar": 251, "quasi": [38, 65, 73, 202], "queri": 77, "question": [8, 9, 231, 265], "quick": [39, 73, 75, 76, 203, 217, 265], "quicker": 175, "quickli": [10, 76, 157, 202, 251, 259], "quickref": 76, "quickstart": 76, "quit": [10, 39, 74, 76, 99, 156, 157, 158, 175, 251, 268], "quiver": [46, 73, 75, 99, 141, 155, 156, 268], "quot": 77, "r": [2, 8, 9, 10, 12, 15, 24, 26, 31, 37, 43, 45, 46, 55, 65, 73, 75, 77, 82, 89, 94, 95, 96, 97, 111, 113, 131, 133, 134, 139, 148, 149, 151, 152, 154, 157, 158, 163, 169, 175, 196, 197, 199, 224, 233, 235, 248, 251, 253, 254, 257, 258, 259, 260, 263, 265, 267], "r1": [35, 227, 231], "r2": [35, 227, 231], "r_": 48, "raccoon": [1, 10, 11, 19, 20, 23, 27, 36, 37, 172, 267, 268], "race": [259, 265], "rad": [89, 97, 157], "radial": [11, 36, 37, 268], "radial_mean": [31, 37], "radii": [133, 151, 157], "radiu": [81, 247], "radius1": [33, 37], "radius2": [33, 37], "radius3": [33, 37], "radius4": [33, 37], "radon": 231, "radsimp": 266, "rai": [0, 267], "rais": [8, 9, 39, 73, 74, 75, 76, 84, 99, 157, 159], "ralf": [0, 202, 267], "randint": 169, "random": [8, 10, 12, 15, 16, 19, 20, 21, 22, 24, 25, 26, 28, 30, 33, 34, 37, 45, 47, 49, 53, 54, 63, 65, 73, 75, 78, 111, 113, 122, 133, 135, 139, 142, 143, 151, 153, 154, 157, 158, 159, 160, 162, 163, 167, 170, 172, 173, 179, 180, 181, 182, 184, 185, 186, 192, 193, 201, 218, 226, 230, 234, 242, 245, 247, 249, 251, 257, 258, 265, 268], "random_": 37, "random_a": 10, "random_b": 10, "random_sampl": 54, "random_st": [236, 238, 246, 248, 251], "random_walk": [227, 231], "randomli": [175, 234, 251], "randomst": 54, "rang": [8, 9, 10, 22, 24, 28, 29, 37, 41, 48, 53, 60, 65, 73, 74, 75, 77, 79, 84, 102, 104, 109, 111, 112, 113, 114, 129, 139, 148, 154, 157, 158, 159, 166, 172, 175, 198, 201, 202, 203, 216, 231, 234, 236, 237, 238, 244, 245, 248, 249, 251], "rangefind": 215, "ranger": 8, "rangl": [169, 175], "rank": [37, 53, 231, 265], "rapidli": 74, "rare": [159, 171], "rate": [8, 65, 202, 235, 251], "rather": [59, 70, 74, 78, 85, 202, 215, 251], "ratio": 202, "ration": [237, 266], "ravel": [39, 175, 204, 239, 247], "raw": [8, 37, 183, 216], "rb": [42, 86], "rbf": 247, "rbin": [31, 37], "rc": [105, 140], "rcdefault": [259, 265], "rcolor": 77, "rcolors2": 77, "rcparam": [48, 101, 103, 249], "re": [10, 38, 73, 76, 77, 78, 85, 190, 191, 202, 203, 215, 238, 251, 266], "reach": [9, 39, 65, 202], "reachabl": 9, "read": [2, 9, 10, 37, 38, 53, 63, 70, 73, 74, 82, 160, 170, 173, 198, 202, 203, 231, 260, 267, 268], "read_csv": [253, 254, 255, 256, 259, 260, 263, 265], "readabl": [1, 2, 9, 39, 76, 78, 84, 267], "reader": [76, 77, 216, 251], "readi": [9, 53, 76, 157], "readili": 76, "readm": [67, 86], "readonli": 8, "readsav": 158, "readthedoc": [70, 74, 76, 81], "reagion": 227, "real": [8, 9, 53, 54, 65, 66, 76, 77, 181, 197, 198, 202, 231, 249, 251, 254, 266], "realist": 54, "realiti": 9, "realiz": [169, 231, 251], "realli": [9, 39, 53, 54, 81, 171, 251], "reason": [9, 10, 39, 54, 70, 159, 198, 202, 238, 251, 260, 265], "reassign": 37, "recal": [171, 237, 238, 251], "recap": [73, 217], "recarrai": [38, 73], "receiv": [8, 10], "recent": [1, 8, 9, 10, 39, 56, 76, 79, 81, 175, 267], "recip": 74, "recogn": [85, 202, 251], "recommend": [10, 65, 76, 159, 175, 202, 251, 265], "reconstruct": [30, 37, 181, 201, 202], "reconstruct_fin": 37, "reconstruct_img": 37, "record": [54, 159, 208, 210, 215, 251], "recov": 202, "rectangl": [9, 142, 233], "rectangular": 9, "recurs": [9, 86], "red": [8, 77, 81, 89, 91, 92, 93, 94, 95, 96, 97, 130, 157, 234, 237, 238, 251, 254], "red_eleph": 158, "redo": [159, 239], "redon": [1, 267], "reduc": [53, 203, 216, 238, 251, 265], "reduct": [54, 73, 75, 172, 174, 217], "ref": 202, "refcheck": 175, "refer": [2, 8, 38, 47, 53, 73, 74, 75, 77, 81, 86, 158, 174, 175, 202, 251, 267], "referenc": [70, 81, 175], "refin": [53, 202, 204, 214], "reflect": [215, 251], "reflex": 175, "refrain": 70, "reg": [253, 259, 265], "regexp": 158, "region": [13, 15, 37, 73, 166, 217], "regionprop": 231, "regist": [8, 9], "registr": [8, 37, 38, 73, 231], "registri": 9, "regr": [245, 249, 251], "regress": [73, 76, 202, 217, 232, 234, 249, 250, 252, 253, 254, 259, 260, 261, 263, 268], "regressor": [235, 251], "regular": [37, 73, 74, 75, 150, 217, 232, 250, 253, 268], "regularli": [37, 77, 202], "reinstal": 8, "reinvent": 76, "rel": [65, 172, 238, 251], "relabel_from_on": 231, "relat": [53, 86, 159, 202, 231, 252, 259, 260, 262, 264, 265, 268], "relationship": [248, 263, 265], "relax": [53, 265], "releas": [8, 9, 73, 84], "relev": [99, 157, 251, 258, 265], "reli": [46, 53], "reliabl": [10, 54, 216], "reload": [85, 202], "remain": [39, 238], "remaind": [85, 157, 175], "remark": [175, 215], "rememb": [77, 172, 216, 251], "remind": [8, 77, 159, 172, 251], "remot": [10, 215], "remov": [1, 8, 15, 37, 38, 73, 76, 77, 81, 86, 172, 180, 198, 201, 202, 203, 204, 214, 231, 253, 263, 265, 267], "remove_pixel": [22, 28, 37], "remove_small_object": 231, "remove_small_sand": 204, "renam": [1, 86, 253, 267], "render": [1, 70, 157, 238, 244, 267], "repeat": [8, 10, 39, 55, 59, 73, 77, 159, 217, 251], "repeatedli": [9, 251], "repetit": 80, "replac": [1, 37, 38, 70, 73, 77, 201, 202, 231, 251, 265, 267], "replacing_decorator_class": 9, "replacing_decorator_with_arg": 9, "repli": 8, "report": [10, 38, 73, 76, 237, 238, 251], "repositori": [54, 70, 251], "repr": 110, "repres": [8, 159, 202, 215, 216, 231, 251, 265, 266], "represent": [1, 10, 73, 217, 237, 238, 244, 251, 267], "reproduc": [8, 10, 157, 159, 179, 257, 258], "request": [2, 9, 39, 70, 253, 259, 260, 267], "requir": [1, 8, 9, 39, 53, 81, 157, 159, 171, 202, 216, 227, 238, 257, 258, 266], "rerais": 79, "rerun": [238, 244], "res_glob": 177, "res_loc": 177, "res_max": 196, "res_min": 196, "resampl": [176, 194, 202, 268], "research": 238, "resembl": 265, "reset": 265, "reset_compiler_flag": 76, "reset_index": 253, "reshap": [8, 12, 23, 37, 39, 47, 55, 59, 65, 73, 75, 172, 174, 204, 237, 238, 239, 247], "resid": [39, 251], "residu": [65, 209, 211, 215, 251, 253, 254, 257, 258, 260, 263, 265], "resiz": [47, 73, 75, 174], "resolut": [157, 201, 202, 266], "resolv": [85, 86, 266], "resort": [54, 251], "resourc": [9, 70, 79, 157, 238], "resp": [77, 201, 202, 231], "respect": [8, 39, 70, 74, 78, 80, 85, 216, 251, 263, 266], "respond": 39, "respons": 202, "rest": [8, 9, 54, 85, 157, 175, 203], "restart": [10, 53], "restor": [9, 20, 225, 231, 259], "restrict": [76, 85, 202], "restructur": [1, 70, 267], "restyp": 39, "result": [8, 9, 37, 39, 41, 42, 46, 53, 54, 65, 74, 76, 85, 90, 154, 157, 159, 169, 172, 175, 179, 197, 202, 203, 205, 207, 213, 215, 216, 231, 239, 242, 243, 251, 253, 254, 257, 258, 260, 263, 265, 268], "resum": 9, "ret": 39, "retain": [48, 175, 251], "rethrown": 9, "retriev": [37, 77, 251, 257, 258, 265], "return": [8, 9, 10, 24, 37, 39, 41, 43, 45, 46, 47, 48, 49, 50, 53, 54, 65, 73, 74, 75, 76, 77, 78, 79, 84, 117, 123, 127, 144, 146, 157, 159, 166, 172, 175, 177, 179, 181, 187, 188, 190, 191, 196, 202, 203, 207, 209, 211, 215, 231, 234, 247, 251, 265, 266], "retval": 10, "reus": [9, 73, 75, 76, 83, 84], "reusabl": [76, 85], "reusing_cod": 86, "reverland": [0, 267], "revers": [9, 42, 74, 77, 157, 159, 202], "reverseiter": 9, "review": [38, 73, 157], "rewamp": [1, 267], "rework": [1, 267], "rewrit": [9, 175], "rewritten": 53, "rf": [206, 207], "rgb": [158, 231], "rgb2hsv": 231, "rgba": 8, "rgbcmykw": [244, 251], "rh": 65, "rho": [139, 154], "rho_1": [139, 154], "rhyme": 81, "rich": [76, 238, 265], "richer": 54, "rid": [85, 198], "ridder": 10, "ridg": [241, 249, 251], "ridgecv": [232, 250, 251, 268], "riehl": [0, 267], "riff": 8, "right": [9, 10, 12, 14, 15, 16, 17, 19, 20, 21, 23, 24, 25, 26, 27, 28, 30, 33, 34, 35, 48, 53, 54, 65, 70, 74, 77, 79, 81, 89, 95, 96, 97, 99, 105, 117, 128, 139, 154, 156, 157, 159, 175, 178, 182, 183, 185, 201, 202, 204, 214, 215, 233, 234, 237, 238, 251, 265, 268], "rightarrow": [8, 266], "rijn": [1, 267], "rippl": 202, "risch": 266, "rlm": [253, 265], "rlock": 9, "rm": [39, 76, 175, 235, 251], "rmdir": 86, "rmtree": 86, "rng": [8, 10, 12, 15, 16, 19, 20, 21, 22, 24, 25, 26, 28, 30, 33, 34, 37, 45, 47, 49, 53, 54, 63, 65, 111, 113, 122, 133, 135, 139, 143, 151, 153, 154, 157, 158, 159, 162, 163, 167, 169, 175, 179, 180, 181, 182, 184, 193, 201, 202, 226, 231, 234, 242, 245, 247, 249, 251, 257, 258, 265], "ro": 196, "robert": [0, 1, 61, 267], "robust": [39, 53, 85, 202, 253], "roi": [0, 22, 37, 267], "role": 216, "ronald": 251, "room": 251, "root": [10, 53, 54, 73, 75, 158, 169, 175, 176, 194, 268], "root2": 188, "root_scalar": 202, "rosenbrock": [42, 48, 53], "rosenbrock_hessian": 48, "rosenbrock_prim": 48, "ross": [0, 1, 267], "rossum": 9, "rotat": [21, 23, 37, 105, 108, 110, 183, 201, 202, 224, 231, 233], "rotate_fac": [23, 37], "rotate_face_noreshap": [23, 37], "rotated_fac": [183, 201, 202], "rother": [0, 1, 267], "rough": 251, "roughli": [39, 54], "rougier": [0, 1, 70, 157, 267], "round": [9, 63, 106, 107, 115, 116, 171], "rout": [39, 175], "routin": [37, 76, 158, 175, 202, 231], "row": [8, 38, 54, 56, 57, 59, 60, 61, 63, 66, 73, 74, 157, 158, 159, 172, 175, 197, 202, 251, 265], "rr": 8, "rseed": 247, "rst": [2, 3, 10, 70, 86, 206, 267], "rstride": [131, 149, 157, 177, 258], "rtol": 202, "rubric": 251, "rule": [8, 9, 39, 77, 81, 85, 159, 171, 172, 202, 251], "run": [6, 8, 9, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 38, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 68, 73, 75, 76, 78, 85, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 159, 161, 162, 163, 164, 165, 166, 167, 168, 169, 171, 172, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 206, 207, 208, 209, 210, 211, 212, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 251, 253, 254, 255, 256, 257, 258, 259, 260, 263], "runner": [1, 48, 85, 86, 144, 183, 199, 238, 253, 260, 267], "runsnakerun": 54, "runtim": 10, "runtimewarn": [10, 48, 54, 199], "rutzmos": [0, 267], "rv": [10, 186, 202], "rx": [41, 48], "s1": 8, "s2": 8, "s4": [8, 171], "s_1": 8, "s_2": 8, "s_j": 8, "s_n": 8, "sa": 65, "safe": [8, 78, 86], "sai": [8, 9, 76, 77, 199, 251], "said": [9, 39], "saiguhan": [1, 267], "saint": 175, "sake": [9, 81], "sale": 259, "salmon": [1, 267], "same": [8, 9, 10, 39, 53, 66, 70, 73, 76, 77, 78, 81, 83, 84, 85, 157, 159, 171, 175, 198, 202, 217, 251, 263, 266], "sampl": [8, 70, 73, 75, 171, 176, 186, 194, 214, 234, 237, 251, 268], "sample_freq": 181, "sample_r": 8, "samples1": 193, "samples2": 193, "san": [132, 146], "sand": [204, 214], "sand_area": 204, "sand_label": 204, "sand_nb": 204, "sand_op": 204, "sander": [0, 1, 267], "santa": 175, "santo": [0, 267], "sarah": 251, "satisfi": [48, 159, 215, 265, 266], "satur": 37, "save": [8, 9, 37, 54, 62, 157, 158, 159, 172, 202, 216, 231], "savefig": [157, 158, 172], "savemat": [158, 202], "savetxt": [158, 202], "saw": 251, "scalar": [8, 53, 55, 77, 159, 175, 202], "scalar_search_wolfe2": 48, "scale": [53, 65, 157, 184, 186, 202, 224, 231, 238, 249, 251, 253], "scan": [159, 214], "scatter": [73, 75, 89, 97, 99, 141, 155, 156, 177, 179, 215, 217, 234, 235, 237, 239, 240, 242, 243, 244, 245, 246, 247, 248, 251, 253, 254, 256, 259, 263, 268], "scatter_matrix": [254, 256, 263, 265], "scene": [256, 265], "scheme": [38, 59, 61, 73, 251], "scienc": [202, 251], "scientif": [1, 2, 8, 10, 37, 38, 39, 48, 70, 74, 75, 78, 80, 81, 85, 86, 144, 157, 159, 175, 199, 217, 253, 260, 265], "scientificpythonlectur": 73, "scientist": [73, 75, 202], "scikit": [1, 2, 31, 37, 53, 54, 65, 73, 76, 217, 225, 230, 233, 238, 250, 267, 268], "scikit_learn_data": 238, "scilab": [73, 75], "scipi": [1, 2, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 38, 41, 43, 45, 46, 47, 48, 50, 54, 62, 65, 66, 73, 74, 75, 76, 81, 84, 85, 157, 158, 172, 175, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 190, 191, 192, 194, 196, 199, 200, 201, 204, 206, 207, 209, 211, 213, 215, 216, 227, 231, 251, 265, 267, 268], "scipy_2009_tutori": 85, "scope": [37, 70, 202], "score": [237, 238, 241, 251], "scoreatpercentil": 37, "scott": [0, 1, 267], "scratch": [38, 73, 157, 202], "screen": [2, 70, 90, 157, 267], "screenshot": 157, "script": [6, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 54, 68, 70, 73, 75, 78, 84, 86, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 158, 159, 161, 162, 163, 164, 165, 166, 167, 168, 169, 172, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 203, 206, 207, 208, 209, 210, 211, 212, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 253, 254, 255, 256, 257, 258, 259, 260, 263], "script_id": 10, "seaborn": [2, 73, 76, 217, 253, 259, 260, 267], "seamless": 8, "search": [38, 48, 73, 74, 77, 85, 86, 157, 175, 202], "searchsort": [22, 28, 37], "sebastian": [0, 1, 77, 267], "sec": 266, "second": [6, 8, 9, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 54, 68, 74, 77, 80, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 159, 161, 162, 163, 164, 165, 166, 167, 168, 169, 175, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 202, 206, 207, 208, 209, 210, 211, 212, 216, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 253, 254, 255, 256, 257, 258, 259, 260, 263, 265, 266], "section": [1, 2, 8, 9, 10, 37, 39, 76, 81, 86, 157, 202, 206, 216, 251, 265, 267], "sector": 259, "see": [2, 3, 8, 9, 10, 37, 39, 48, 53, 54, 65, 74, 77, 79, 81, 84, 85, 157, 158, 159, 171, 172, 175, 201, 202, 215, 231, 238, 248, 249, 251, 256, 265, 266, 267], "seed": [159, 179, 181, 185, 192, 227, 247, 249, 251, 257, 258], "seek": [10, 202, 251], "seem": [8, 10, 175, 216, 238, 251, 260, 265], "seemingli": 251, "seen": [47, 53, 77, 81, 175, 251, 265], "segfault": 10, "segment": [11, 36, 38, 39, 53, 73, 217, 218, 230, 268], "select": [2, 39, 73, 81, 203, 217, 265, 267], "selector": 265, "self": [2, 9, 10, 39, 66, 75, 76, 78, 83, 231, 267], "semant": [9, 81], "semaphor": 9, "semi": [10, 157], "semilogi": [41, 42, 48], "semilogx": 192, "send": [8, 9], "sens": [9, 39, 53, 80, 202, 215, 251], "sensit": [53, 265], "sensor": 54, "sensor_cod": 171, "sentenc": [70, 81], "sep": [76, 86, 253, 255, 256, 259, 260, 263, 265], "sepal": [239, 251, 252, 261, 265, 268], "sepal_width": [254, 265], "separ": [9, 12, 35, 37, 54, 73, 74, 77, 175, 202, 217, 227, 231, 246, 247, 248, 253, 256, 260, 266], "seq": 81, "sequenc": [9, 73, 75, 85, 159], "sequenti": [9, 53], "sergio": [0, 1, 267], "seri": [73, 217, 265], "serial": 76, "serv": 39, "server": 76, "servic": [85, 86, 259], "session": [85, 157], "set": [1, 2, 8, 9, 10, 37, 39, 53, 66, 73, 75, 76, 77, 78, 79, 85, 90, 159, 160, 170, 173, 174, 176, 194, 197, 201, 202, 217, 231, 232, 234, 236, 237, 238, 243, 250, 266, 267, 268], "set_ag": 83, "set_alpha": [101, 102, 103, 104, 106, 107, 109, 111, 112, 113, 114, 115, 116, 117, 133, 151, 157], "set_bbox": [89, 157], "set_color": [89, 95, 96, 97, 117, 157], "set_facecolor": [133, 151, 157], "set_fonts": [89, 157], "set_major": 83, "set_major_loc": [117, 125, 145, 157], "set_minor_loc": [117, 125, 145], "set_posit": [89, 95, 96, 97, 117, 157], "set_someth": 157, "set_ticks_posit": [89, 95, 96, 97, 117, 157], "set_titl": [177, 234, 238], "set_trac": 10, "set_xlabel": [177, 188, 234, 242, 258], "set_xlim": [125, 145, 157, 233, 234], "set_xticklabel": [125, 133, 145, 147, 151, 157], "set_ylabel": [177, 188, 234, 242, 258], "set_ylim": [125, 145, 157, 233, 234], "set_yticklabel": [125, 133, 145, 147, 151, 157], "set_zlabel": [177, 258], "set_zlim": [131, 149], "set_ztick": [132, 149], "setchel": [0, 1, 267], "setdiag": 65, "seterr": 10, "setitem": 8, "setosa": [251, 254], "setp": [157, 181], "setter": 9, "setup": [9, 39, 85, 216], "setuptool": 39, "setx": 81, "seven": 66, "sever": [8, 10, 37, 70, 76, 77, 83, 85, 147, 157, 159, 202, 225, 231, 238, 251, 266], "sex": [251, 259, 260, 265], "sfepi": 202, "sgdclassifi": 246, "sh": 86, "shadow": 157, "shallow": 159, "shanno": 53, "shape": [8, 10, 12, 13, 15, 16, 19, 20, 21, 23, 24, 26, 29, 31, 33, 37, 39, 47, 53, 55, 56, 57, 58, 59, 60, 63, 65, 66, 73, 75, 158, 159, 171, 172, 174, 182, 183, 185, 197, 198, 199, 201, 202, 204, 206, 216, 231, 238, 239, 241, 242, 246, 247, 249, 251, 257, 258, 265], "share": [9, 38, 39, 73, 159, 202], "sharp": 53, "sharpen": [11, 36, 38, 73, 231, 268], "shear": [224, 231], "sheet": 76, "shell": [10, 74, 76, 77, 78, 80, 85, 86], "sherwood": [0, 267], "shift": [10, 76, 183, 201, 202], "shifted_fac": [183, 201, 202], "shifted_face2": [183, 201, 202], "ship": [39, 76, 231], "shoeboxam": [0, 267], "shoot": [38, 73], "short": [9, 10, 70, 76, 77, 215, 251], "short_nam": 259, "shortcom": 39, "shortcut": 8, "shorten": [1, 267], "shorter": 9, "shortest": 231, "shorthand": [8, 85], "should": [2, 9, 10, 39, 53, 54, 65, 70, 76, 80, 85, 157, 159, 181, 202, 215, 216, 231, 251, 258, 267], "show": [6, 8, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 39, 41, 42, 43, 44, 45, 46, 47, 49, 50, 51, 65, 68, 70, 74, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 158, 159, 161, 162, 163, 164, 165, 166, 167, 168, 169, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 202, 207, 208, 209, 210, 211, 214, 215, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 233, 234, 235, 237, 238, 239, 240, 241, 242, 244, 245, 246, 247, 248, 249, 251, 253, 254, 255, 256, 257, 258, 259, 260, 263], "shown": [8, 9, 76, 157, 159, 202, 215, 238], "shrink": [127, 249, 251], "shrinkag": [249, 251], "shuffl": [73, 75, 174], "shufflesplit": 251, "shutil": [73, 75, 84], "sibl": [38, 73, 171], "side": [9, 53, 65, 73, 77, 78, 202, 251], "sidebar": [1, 267], "sig": [178, 181, 192, 201, 202], "sig_fft": [181, 202], "sight": 159, "sigma": [12, 14, 15, 22, 24, 26, 28, 34, 37, 182, 201, 202, 215, 225, 226, 231], "sigma_2": [139, 154], "sign": [8, 41, 76, 78, 171, 215, 231, 265], "signal": [10, 37, 54, 73, 75, 76, 85, 159, 176, 182, 194, 201, 215, 268], "signatur": [8, 9, 39, 76, 81, 85, 157], "signific": [8, 175, 215, 265], "significantli": [253, 265], "sigsegv": 10, "silver": 10, "similar": [9, 39, 53, 54, 83, 157, 159, 202, 231, 251], "similarli": [8, 9, 10, 53, 159, 197, 202], "simon": [0, 267], "simpl": [8, 9, 10, 23, 24, 26, 30, 34, 37, 39, 54, 59, 67, 69, 70, 73, 75, 76, 77, 85, 99, 129, 130, 131, 133, 134, 135, 156, 172, 175, 176, 177, 179, 194, 195, 200, 202, 217, 218, 222, 230, 231, 232, 234, 238, 240, 250, 252, 259, 260, 261, 266, 268], "simple_decor": 9, "simplefilt": 166, "simpler": [9, 39, 73, 216, 238, 245, 265, 266], "simplest": [9, 10, 21, 73, 217, 251], "simplex": [38, 73], "simpli": [9, 10, 39, 47, 54, 76, 159, 202, 251], "simplic": [54, 238, 251], "simplif": 266, "simplifi": [1, 9, 10, 39, 73, 217, 265, 267], "simplist": 251, "simul": [76, 159, 175, 265], "sin": [10, 39, 68, 70, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 121, 124, 130, 131, 134, 140, 149, 150, 152, 157, 175, 178, 179, 181, 184, 187, 188, 189, 192, 201, 202, 247, 265, 266], "sin_t": 265, "sinc": [8, 9, 33, 39, 81, 82, 85, 157, 202, 251, 266], "sine": [89, 90, 96, 97, 157, 179, 202], "singl": [8, 9, 10, 39, 65, 76, 77, 202, 203, 215, 239, 251, 260, 263, 265], "singular": [54, 175, 202, 251], "sinh": 266, "sinusoid": 202, "sit": 53, "site": [10, 39, 48, 76, 85, 86, 181, 203, 236, 253], "situat": [8, 10, 32, 39, 53, 249, 251], "six": [177, 202], "sixhump": 177, "size": [1, 8, 10, 12, 14, 15, 16, 22, 24, 25, 26, 28, 33, 37, 39, 41, 42, 43, 44, 45, 47, 48, 49, 50, 51, 53, 54, 55, 62, 66, 73, 75, 77, 90, 99, 100, 101, 102, 103, 104, 106, 107, 108, 109, 110, 111, 112, 113, 115, 116, 117, 118, 119, 120, 126, 132, 136, 137, 138, 139, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 159, 174, 175, 180, 181, 182, 184, 186, 193, 198, 201, 202, 204, 214, 216, 231, 233, 234, 235, 237, 238, 242, 245, 249, 251, 252, 257, 258, 261, 263, 265, 267, 268], "size_in": 39, "size_out": 39, "sizeof": 39, "skeleton": 231, "skew": [253, 254, 257, 258, 260, 263, 265], "ski": 231, "skim": 159, "skimag": [20, 35, 37, 219, 220, 221, 223, 224, 225, 226, 227, 228, 229, 231], "skip": [8, 9, 82, 85, 157, 159, 175, 215], "skip_hidden": 10, "skip_pred": 10, "skipfoot": [259, 260], "skiprow": [259, 260], "sklearn": [12, 33, 37, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 251], "sky": 231, "sl": [178, 201, 202], "slice": [37, 38, 56, 57, 58, 59, 60, 63, 73, 75, 77, 81, 157, 174, 175, 201, 202, 222, 231, 239], "slice_i": [22, 37], "slice_x": [22, 37], "slicer": 81, "slightli": [1, 157, 204, 214, 216, 251, 267], "slope": [253, 260, 265], "slow": [39, 47, 57, 58, 60, 62, 63, 66], "slower": 53, "slowli": 8, "slsqp": 50, "sm": [253, 260, 265], "small": [8, 10, 15, 18, 37, 39, 43, 53, 54, 62, 76, 83, 159, 192, 201, 202, 215, 231, 234, 238, 253], "small_arrai": 10, "smaller": [8, 37, 54, 157, 158, 201, 202, 204, 214, 231, 249, 251, 255], "smallest": 251, "smith": 65, "smooth": [38, 40, 49, 52, 65, 73, 76, 176, 184, 194, 201, 202, 231, 268], "smooth_result": [184, 202], "smoothed_aggregation_solv": 65, "smoother": [158, 251], "smoothing_splin": [184, 202], "snap": [85, 86], "snippet": [8, 10, 76], "so": [8, 9, 10, 39, 53, 54, 74, 76, 80, 85, 157, 159, 172, 175, 198, 202, 204, 214, 215, 216, 231, 238, 251, 260, 266], "sob": [21, 37], "sobel": [11, 36, 37, 218, 230, 231, 268], "sobel_h": [228, 231], "socket": [85, 86], "softwar": [1, 39, 53, 76, 84, 215, 267], "solarjo": [0, 267], "solid": [99, 100, 118, 157, 246, 247, 268], "solid_capstyl": [115, 157], "solid_joinstyl": [116, 157], "solut": [38, 39, 46, 47, 53, 62, 65, 73, 75, 85, 86, 88, 157, 172, 191, 199, 200, 216, 217, 248, 251, 264, 266, 268], "solv": [9, 53, 54, 59, 65, 73, 74, 175, 191, 202, 217], "solve_ivp": [190, 191, 202], "solve_triangular": 202, "solver": [33, 38, 48, 53, 57, 58, 59, 61, 64, 66, 73, 202], "solveset": 266, "some": [2, 8, 9, 10, 23, 37, 38, 39, 46, 47, 54, 59, 65, 66, 70, 73, 74, 75, 76, 80, 82, 84, 85, 124, 151, 158, 159, 171, 174, 175, 178, 179, 182, 183, 185, 202, 214, 215, 231, 251, 265, 266, 267], "some_gener": 9, "some_other_gener": 9, "some_result": 172, "some_threshold": [166, 172], "somebodi": 158, "somehow": [8, 251], "someth": [8, 9, 39, 159, 251], "sometim": [85, 171, 202, 251], "somewhat": [39, 81, 266], "somewher": [85, 175], "sonam": 39, "soon": 175, "sophist": [158, 251], "sort": [37, 42, 63, 73, 75, 77, 78, 79, 105, 174, 203, 206, 207, 216, 251], "sortabl": 175, "sorted_file_list": 203, "sorted_max_spe": [206, 207, 216], "sound": [8, 9, 159, 251], "sourc": [5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 54, 67, 68, 70, 73, 74, 76, 84, 85, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 99, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 172, 173, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 202, 205, 206, 207, 208, 209, 210, 211, 212, 216, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 263, 265], "sourceforg": [64, 260], "south": [259, 265], "sp": [10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 37, 41, 43, 45, 46, 47, 48, 50, 53, 54, 55, 56, 57, 58, 59, 60, 63, 65, 66, 85, 172, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 196, 197, 198, 199, 201, 202, 204, 206, 207, 209, 211, 215, 216, 227, 231, 265], "space": [37, 53, 59, 76, 77, 78, 85, 157, 159, 171, 175, 181, 202, 231, 248, 251, 253], "span": [70, 77, 85], "sparrai": 66, "spars": [8, 38, 54, 55, 56, 59, 60, 63, 64, 73, 85, 202, 251], "sparsetool": [55, 56, 57, 58, 59, 66], "sparsiti": [38, 57, 58, 60, 61, 63, 73], "spatial": [37, 85, 202, 251], "spdiag": 65, "speak": [39, 157], "speci": [172, 251, 265], "special": [8, 9, 10, 38, 59, 66, 73, 75, 76, 77, 81, 83, 85, 157, 171, 265, 266], "specif": [8, 10, 37, 38, 39, 53, 65, 70, 73, 74, 75, 76, 84, 157, 202, 238, 251], "specifi": [9, 39, 53, 65, 73, 74, 81, 85, 86, 157, 159, 172, 202, 217, 253, 254, 257, 258, 260, 263], "spectral": [11, 36, 37, 176, 194, 202, 268], "spectral_clust": [33, 37], "spectrogram": [176, 194, 202, 268], "spectrum": [37, 192, 197, 202], "speed": [39, 54, 73, 75, 202, 205, 207, 212, 213, 231, 251, 268], "speed_splin": [206, 207], "spell": [38, 73], "spend": 54, "spent": [54, 76], "sphinx": [1, 2, 5, 6, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 67, 68, 70, 86, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 99, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 173, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 202, 205, 206, 207, 208, 209, 210, 211, 212, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 263, 265, 267], "sphinxcontrib": [2, 267], "sphx_glr_plot_simple_001": 70, "spilu": 65, "spine": [73, 75, 89, 95, 96, 97, 117], "splev": 216, "spline": [184, 202, 216], "split": [78, 81, 85, 86, 203, 234, 237, 238, 251, 259, 265], "splitext": 86, "splrep": 216, "spoiler": 8, "spot": [54, 70, 251], "spread": [76, 255], "spreadsheet": 265, "spring": [176, 194, 202, 268], "springfield": 175, "sprint": [1, 267], "sprog": [207, 212, 216], "sprog\u00f8": [73, 75, 202], "spsolv": 65, "spuriou": [249, 251], "spy": [62, 65], "spyder": 76, "sq_distanc": [169, 175], "sql": 265, "sqrt": [43, 46, 47, 50, 51, 53, 54, 89, 97, 131, 134, 139, 149, 152, 154, 157, 159, 164, 169, 171, 175, 190, 202, 235, 251, 266], "squar": [21, 25, 30, 37, 38, 65, 73, 74, 75, 142, 143, 144, 145, 146, 147, 148, 150, 152, 153, 154, 169, 175, 182, 201, 202, 231, 251, 253, 254, 257, 258, 260, 263, 265], "squared_hing": 236, "squeez": 8, "src": [10, 81, 85], "ssmiller": [0, 267], "stabil": 65, "stabl": [2, 8, 54, 74, 76, 158, 231, 256, 260, 267], "stack": [2, 8, 9, 10, 80, 267], "stage": 39, "stai": 8, "stan": 86, "stand": [8, 9, 157], "standalon": 85, "standard": [38, 39, 73, 74, 75, 76, 81, 84, 175, 186, 202, 204, 214, 253, 254, 257, 258, 259, 260, 263, 265], "standard_librari": 86, "standard_norm": [37, 159, 182, 185, 201, 202], "staniewicz": [0, 1, 267], "star": [85, 251], "start": [8, 9, 38, 39, 46, 57, 58, 65, 70, 73, 77, 80, 81, 84, 157, 159, 172, 175, 202, 231, 238, 251], "startup": [85, 157], "stat": [37, 73, 75, 85, 186, 253, 257, 258, 259, 260, 265], "state": [9, 172, 191, 202, 215], "statement": [9, 10, 39, 73, 75, 77, 79, 84, 85, 159], "static": [9, 38, 39, 73, 85], "staticmethod": 9, "station": [73, 75, 202], "stationari": 172, "statist": [1, 5, 7, 38, 53, 73, 75, 76, 174, 175, 217, 240, 251, 252, 253, 254, 257, 258, 259, 260, 261, 263, 264, 267, 268], "statlib": 251, "statmodel": [2, 267], "statsmodel": [1, 2, 76, 253, 254, 257, 258, 260, 263, 265, 267], "statu": [8, 53, 187, 202], "std": [8, 19, 20, 33, 37, 54, 76, 159, 171, 172, 175, 182, 201, 202, 251, 253, 254, 257, 258, 260, 263, 265], "stderr": 9, "stdin": [8, 9, 175], "stdlib": 9, "stdout": 76, "stdtype": 77, "steep": 39, "steepest": 53, "stem": [201, 202], "step": [8, 37, 38, 48, 54, 65, 73, 75, 76, 77, 81, 84, 157, 159, 169, 172, 175, 201, 202, 216, 217, 234, 238, 251], "stiff": 202, "still": [9, 39, 53, 70, 76, 171, 198], "stokesflow": 83, "stop": [9, 65, 77, 81], "stopiter": [9, 79], "storag": [38, 61, 73], "store": [8, 9, 39, 43, 48, 50, 55, 56, 57, 58, 59, 60, 62, 63, 66, 77, 86, 159, 203, 216, 251, 265], "stori": 175, "storm": 216, "str": [8, 41, 76, 77, 79, 80, 86, 237], "straight": [37, 157, 251], "straightforward": [2, 8, 9, 251, 267], "strang": 76, "strategi": [10, 54, 251, 265], "stream": [76, 86], "streamlin": 8, "strength": [73, 75, 241, 251], "stretch": 9, "strict": [39, 42, 85, 122, 133, 151, 244, 248], "strictli": [9, 39, 157], "stride": [10, 37, 38, 39, 54, 73, 77], "stride_trick": [8, 10], "strideptr": 39, "string": [10, 38, 39, 73, 75, 76, 78, 80, 81, 82, 85, 86, 159, 171, 203, 260], "strive": [38, 251], "strong": [53, 253, 263], "strpeter": [0, 267], "struct": [8, 24, 37, 39], "structur": [8, 9, 24, 25, 37, 38, 53, 54, 57, 58, 60, 61, 63, 73, 75, 76, 85, 174, 201, 202, 231, 251], "stuart": [0, 1, 267], "student": [73, 76, 83, 217], "studi": [253, 265], "studio": [8, 10, 76], "stuff": [8, 172, 198], "stupid": 10, "style": [2, 8, 9, 10, 70, 73, 75, 78, 85, 99, 100, 108, 118, 127, 132, 147, 148, 171, 259, 265, 267, 268], "st\u00e9fan": [0, 79, 267], "sub": [8, 55, 159, 175, 202, 265], "subclass": [8, 55, 56, 57, 58, 59, 60, 66], "subdir": 203, "subfield": 251, "subgen": 9, "subgener": 9, "subject": [255, 265], "sublist": 77, "submit": 39, "submodul": [37, 65, 85, 202, 231, 251], "subok": 159, "suboptim": 181, "subpackag": 231, "subplot": [12, 14, 15, 16, 17, 19, 20, 21, 23, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 65, 73, 75, 89, 90, 91, 92, 93, 94, 95, 96, 97, 99, 105, 117, 126, 143, 145, 147, 151, 156, 178, 182, 183, 185, 201, 202, 208, 209, 210, 211, 215, 219, 221, 223, 225, 226, 227, 228, 229, 247, 268], "subplots_adjust": [12, 14, 15, 16, 17, 19, 20, 21, 23, 24, 25, 26, 27, 28, 30, 33, 34, 35, 105, 117, 128, 178, 182, 183, 185, 234, 237, 253], "subroutin": [65, 202, 216], "subscrib": 8, "subscript": 8, "subsect": [2, 9, 267], "subsequ": [2, 267], "subset": [175, 238, 251, 265], "substanti": 39, "substitut": 9, "subtl": 81, "subtleti": 251, "subtract": 8, "success": [41, 53, 169, 187, 202, 251], "successfulli": [9, 53, 187, 202], "suffer": 251, "suffic": 9, "suffici": [9, 175, 238, 251], "suggest": [1, 9, 70, 159, 265, 267], "suit": [10, 80, 85, 158], "suitabl": 66, "suitespars": 65, "sum": [8, 9, 10, 22, 24, 28, 37, 47, 50, 53, 54, 56, 73, 75, 169, 172, 174, 201, 202, 203, 204, 214, 215, 237, 251, 265], "sum_sq": [257, 258], "summar": 39, "summari": [38, 61, 73, 75, 81, 159, 174, 201, 213, 215, 216, 217, 253, 254, 257, 258, 260, 263, 265, 268], "sun": [253, 254, 257, 258, 260, 263], "super": 8, "super_fmt": 48, "superlu": 65, "superset": 39, "supervis": [73, 217, 233, 238], "suppli": [8, 65], "support": [1, 8, 9, 38, 53, 54, 57, 58, 73, 76, 77, 83, 85, 158, 159, 202, 231, 237, 247, 251, 260, 265, 266, 267], "support_vectors_": 247, "suppos": [8, 9, 83, 85, 202, 216, 231, 251, 266], "suppress": [1, 166, 267], "suptitl": [254, 259, 263], "sure": [9, 10, 39, 54, 65, 70, 85, 157, 175], "surf": [177, 258], "surfac": [202, 215], "surfer190": [0, 267], "surpris": [54, 159, 171, 202], "surprisingli": 251, "suspend": 9, "svc": [236, 238, 247], "svcifittedsvc": 238, "svd": [38, 73, 202], "svg": [2, 267], "svm": [232, 236, 247, 250, 251, 268], "swallow": 9, "swap": [8, 10, 39], "sweet": 251, "sweeter": 9, "swig": [38, 73], "swig_file_with_init": 39, "swig_numpi": 39, "switch": [8, 54, 202, 251, 265], "sx": [13, 21, 31, 37, 172], "sy": [9, 13, 21, 31, 37, 42, 48, 73, 75, 76, 84, 85, 172, 203], "sym": 266, "symbol": [9, 42, 53, 73, 76, 85, 157, 217], "symlink": [2, 267], "symmetr": [54, 65, 202], "sympi": [1, 2, 53, 73, 76, 217, 267], "syntast": 10, "syntax": [9, 10, 76, 77, 78, 81, 84, 85, 171, 172, 265, 266], "syntaxerror": [76, 77], "synthet": [11, 36, 37, 38, 73, 201, 202, 231, 246, 268], "system": [2, 10, 38, 39, 54, 61, 70, 73, 75, 76, 84, 157, 175, 202, 205, 213, 215, 251, 267, 268], "systemat": [251, 255, 265], "systemd": [85, 86], "szmek": [0, 1, 9, 267], "t": [8, 9, 10, 35, 39, 43, 45, 46, 47, 48, 50, 53, 54, 66, 73, 74, 76, 77, 78, 79, 80, 81, 83, 85, 89, 97, 134, 135, 139, 152, 153, 154, 157, 158, 166, 167, 168, 169, 171, 172, 175, 180, 184, 189, 190, 191, 197, 198, 202, 208, 209, 210, 211, 215, 217, 227, 231, 245, 249, 251, 253, 254, 257, 258, 260, 263], "t0": 47, "t_0": 202, "t_eval": [190, 191, 202], "t_f": 202, "t_max": [169, 175], "t_span": [190, 191, 202], "tab": [74, 76, 77, 85, 202, 265], "tabl": [39, 70, 73, 77, 81, 157, 217, 251], "tackl": 38, "tailor": 10, "take": [2, 8, 9, 10, 33, 37, 39, 54, 85, 157, 159, 171, 172, 175, 198, 203, 215, 231, 238, 239, 248, 251, 266, 267], "taken": [9, 53, 104, 202, 231, 265], "talk": 8, "tan": [10, 266], "tangent": [44, 53], "tanh": 10, "tarbal": 8, "tarek": [0, 267], "tarfil": 9, "target": [10, 70, 215, 235, 236, 237, 238, 239, 240, 241, 243, 244, 248, 251], "target_id": [244, 248, 251], "target_nam": [240, 244, 248, 251], "task": [10, 37, 53, 66, 78, 202, 231, 251, 266], "tau": 171, "taught": 70, "taylor": [0, 266, 267], "tbreak": 10, "tcg": 53, "teach": 70, "technic": [70, 157, 265], "techniqu": [39, 54, 73, 202, 238, 251], "technologi": 39, "tediou": [10, 53], "tel": 77, "telenczuk": [0, 1, 267], "telescop": 251, "tele\u0144czuk": [1, 267], "tell": [39, 54, 85, 202, 266], "temp": [39, 85, 86], "temp_max": 196, "temp_min": 196, "temperatur": [176, 195, 200, 268], "tempfil": 9, "temporari": 9, "temporarili": [9, 166], "tempt": 76, "tend": [39, 53, 202, 231, 251, 265], "tendenc": 202, "tensor": 8, "tensordot": 8, "tep": 10, "term": [39, 47, 53, 70, 76, 81, 202, 203, 251, 265, 266], "termin": [8, 53, 65, 80, 85, 187, 202], "test": [1, 2, 8, 9, 10, 39, 45, 53, 54, 73, 75, 76, 77, 78, 81, 82, 85, 86, 203, 217, 231, 234, 236, 237, 238, 243, 252, 253, 254, 261, 263, 267, 268], "test2": 8, "test_cos_doubl": 39, "test_func": 179, "test_siz": [234, 236, 251], "testcas": 9, "tex": [2, 10, 267], "texliv": [2, 267], "text": [1, 9, 10, 12, 26, 41, 43, 44, 50, 51, 62, 63, 70, 73, 75, 85, 99, 101, 103, 105, 108, 110, 117, 119, 120, 122, 126, 136, 137, 138, 141, 142, 143, 144, 145, 146, 147, 148, 150, 151, 152, 153, 155, 156, 174, 175, 177, 196, 197, 202, 206, 207, 212, 228, 231, 233, 237, 245, 251, 254, 258, 259, 265, 267, 268], "text2d": [132, 149], "textcoord": [89, 97, 157], "textiowrapp": 82, "textit": 265, "textmat": 10, "textur": 231, "tform": [224, 231], "th": [57, 58, 74], "than": [8, 9, 10, 37, 48, 53, 54, 55, 70, 73, 74, 75, 76, 77, 85, 159, 175, 201, 202, 204, 214, 215, 231, 251, 255, 260, 265], "thank": [9, 79, 83, 256], "thei": [9, 10, 38, 39, 53, 73, 74, 76, 77, 81, 157, 159, 172, 175, 202, 215, 216, 251, 259, 260, 265, 266], "them": [8, 9, 10, 39, 53, 54, 70, 74, 76, 77, 81, 130, 157, 159, 171, 175, 202, 215, 216, 231, 246, 248, 249, 251, 265, 266], "themselv": 85, "theofilo": [0, 267], "theophil": 74, "theorem": 265, "theoret": [54, 169, 231], "theori": [9, 62, 201, 202], "therefor": [8, 9, 77, 85, 157, 201, 202, 215], "theta": [133, 151, 157, 247], "thi": [1, 8, 9, 10, 12, 16, 19, 20, 22, 23, 24, 25, 26, 28, 29, 30, 31, 32, 33, 35, 37, 38, 39, 41, 46, 47, 48, 53, 54, 57, 58, 65, 70, 73, 74, 75, 76, 77, 78, 81, 82, 85, 86, 99, 101, 102, 119, 120, 158, 159, 169, 172, 174, 175, 181, 196, 197, 198, 199, 201, 202, 214, 215, 216, 217, 222, 225, 226, 227, 228, 229, 231, 233, 238, 239, 240, 243, 244, 245, 246, 247, 249, 251, 253, 255, 256, 258, 259, 260, 263, 266, 267], "thicker": 157, "thing": [8, 9, 10, 39, 54, 77, 238, 251], "think": [9, 54, 62, 76, 251, 265], "third": [8, 9, 159], "this_bench": 42, "this_x": 41, "thisfil": 10, "thoma": [257, 258], "those": [9, 39, 54, 202, 216, 251], "though": [8, 251], "thought": 76, "thoui": [0, 1, 267], "thousand": 251, "thread": [9, 10], "threadpoolexecutor": 9, "three": [8, 9, 39, 55, 56, 57, 58, 70, 77, 81, 159, 204, 214, 215, 251, 265, 266], "threshold": [12, 73, 204, 214, 218, 230, 268], "threshold_otsu": [219, 229, 231], "through": [9, 10, 39, 48, 54, 77, 84, 85, 157, 159, 175, 202, 204, 214, 216, 251], "throughout": 74, "throw": 9, "throwflag": 10, "thrown": [9, 76], "thu": [10, 39, 46, 47, 53, 54, 70, 76, 78, 85, 159, 175, 216, 251, 265], "thumb": [85, 251], "tiago": [0, 267], "tick": [1, 37, 73, 75, 90, 99, 100, 118, 145, 240, 267, 268], "ticker": [117, 125, 145, 157, 240], "ticket": 8, "ticklin": 117, "tidi": 159, "tiff": 37, "tight": [10, 50, 157, 202, 212, 235, 239, 242, 243, 245, 246], "tight_layout": [32, 41, 42, 44, 48, 49, 51, 126, 136, 137, 138, 169, 175, 191, 192, 219, 220, 221, 223, 226, 227, 228, 229, 234, 235, 240, 241, 243], "tild": 197, "tile": 175, "tim": [0, 1, 267], "time": [2, 6, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 54, 65, 68, 76, 80, 85, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 159, 161, 162, 163, 164, 165, 166, 167, 168, 169, 175, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 202, 206, 207, 208, 209, 210, 211, 212, 215, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 231, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 251, 253, 254, 255, 256, 257, 258, 259, 260, 263, 265, 267], "time_offset": 196, "time_step": [181, 192, 202], "time_vec": [181, 192], "timeit": [8, 38, 39, 73, 76, 159, 171, 175], "timer": 54, "tiny_eleph": 158, "tip": [8, 70, 73, 75], "titl": [1, 8, 10, 16, 19, 20, 21, 65, 70, 73, 75, 105, 142, 143, 144, 145, 146, 147, 148, 150, 152, 153, 154, 178, 181, 182, 185, 191, 192, 197, 202, 225, 227, 234, 245, 253, 267], "tm_pycheck": 10, "tmp": [9, 37, 76, 85, 86, 158, 203], "to_byt": 76, "to_debug": 10, "toarrai": [55, 56, 57, 58, 59, 60, 63, 65, 66], "tobyt": 8, "toc": [1, 267], "tocsr": 65, "todo": 8, "toeplitz": 202, "tofil": 37, "togeth": [56, 169, 175, 266], "toggl": 10, "toi": [48, 53], "tol": [41, 46, 53, 65], "toler": [53, 65, 172], "tommyod": [0, 1, 267], "too": [9, 10, 39, 43, 48, 53, 76, 85, 157, 215, 234, 243, 251], "took": 53, "tool": [8, 10, 37, 39, 53, 54, 73, 74, 76, 85, 174, 202, 251, 256, 265], "toolbox": [76, 172, 202], "toolkit": 231, "top": [9, 12, 14, 15, 16, 17, 19, 20, 21, 23, 24, 25, 26, 27, 28, 30, 33, 34, 35, 70, 89, 95, 96, 97, 105, 117, 122, 128, 132, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 172, 178, 182, 183, 185, 198, 215, 233, 234, 237, 238, 251], "tophat": [37, 231], "topic": [2, 10, 70, 73, 74, 76, 171, 267], "topograph": [73, 75, 202], "topographi": 215, "total": [6, 7, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 68, 69, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 196, 197, 198, 199, 200, 206, 207, 208, 209, 210, 211, 212, 213, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 253, 254, 255, 256, 257, 258, 259, 260, 261, 263, 264, 268], "total_ord": 9, "tottim": 54, "toward": [202, 215, 251], "tp_as_buff": 8, "trace": [8, 48], "traceback": [8, 9, 10, 39, 56, 79, 81, 175], "track": [39, 54, 73, 75, 85], "tracker": 8, "trade": [54, 73], "tradeof": 251, "tradeoff": [73, 217], "tradit": 8, "trail": 159, "train": [76, 233, 234, 237, 238, 239, 243, 251], "train_scor": [234, 251], "train_siz": [234, 251], "train_test_split": [234, 235, 236, 237, 238, 251], "trait": [1, 251, 267], "transax": [12, 26, 132, 139, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154], "transcendent": [175, 266], "transfer": [8, 54], "transform": [11, 12, 26, 36, 38, 54, 70, 73, 75, 76, 132, 139, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 175, 176, 181, 194, 197, 198, 218, 230, 231, 233, 238, 244, 248, 251, 253, 259, 260, 266, 268], "transit": 172, "translat": [224, 231], "transpar": [1, 9, 99, 100, 118, 157, 231, 263, 267, 268], "transplant": 9, "transpos": [1, 8, 54, 66, 175, 267], "transposit": [8, 175], "trapezoid": 198, "travel": 253, "treat": [265, 266], "tree": [86, 215, 232, 235, 250, 268], "trend": [180, 202, 259], "tri": 53, "triangl": 53, "triangular": 202, "trick": [29, 37, 38, 53, 54, 70, 73, 75, 172, 175, 202], "tricki": [39, 157, 197], "trig": 266, "trigger": 10, "trigonometr": 266, "trigsimp": 266, "tril": 175, "trip": 253, "tripl": 77, "triplet": [56, 66], "triu": [175, 202], "trivial": [9, 10, 39], "troubl": [38, 73, 202, 251], "troubleshoot": 157, "true": [8, 9, 10, 13, 14, 17, 19, 20, 23, 27, 29, 31, 32, 35, 37, 39, 42, 48, 53, 65, 74, 77, 78, 79, 86, 95, 96, 97, 103, 122, 133, 139, 151, 154, 157, 159, 171, 172, 175, 182, 183, 186, 187, 193, 201, 202, 227, 231, 233, 235, 238, 243, 244, 246, 248, 251, 253, 265, 266], "true_": [171, 175, 202], "truecolor": 86, "truncat": [171, 197, 202, 251], "trust": [238, 244, 251], "truth": [245, 251, 265], "try": [8, 9, 10, 37, 39, 53, 54, 65, 70, 73, 75, 76, 157, 158, 159, 175, 198, 202, 203, 215, 238, 244, 251, 254, 265, 266], "try_to_modifi": 81, "tsne": [73, 217, 232, 250, 268], "ttest_1samp": 265, "ttest_ind": 265, "ttest_rel": 265, "ttestresult": 265, "tulsa": 175, "tunabl": 251, "tune": [8, 157, 251], "tupl": [1, 8, 35, 55, 56, 57, 58, 59, 60, 63, 66, 77, 78, 81, 159, 227, 231, 266, 267], "turbulentflow": 83, "turn": [8, 9, 10, 53, 157], "turner": [0, 267], "tutori": [1, 2, 8, 37, 70, 73, 74, 75, 77, 79, 82, 84, 85, 202, 215, 232, 238, 247, 250, 251, 265, 267, 268], "tv": [20, 225], "tv_coin": 231, "tv_denois": 20, "tv_filter_coin": 225, "tweak": [2, 38, 73, 121, 144, 145, 267], "twice": [10, 78, 157], "twinx": 42, "twister": 159, "two": [8, 9, 16, 35, 37, 39, 53, 54, 65, 70, 73, 74, 80, 81, 85, 159, 171, 175, 176, 194, 198, 202, 215, 217, 227, 231, 235, 238, 239, 251, 255, 266, 268], "twodim_bas": 54, "txt": [2, 6, 8, 67, 77, 85, 86, 158, 168, 172, 199, 203, 253, 259, 260, 267], "type": [2, 6, 9, 37, 38, 39, 42, 43, 46, 47, 50, 53, 66, 73, 74, 75, 76, 78, 79, 80, 81, 82, 84, 85, 86, 172, 174, 177, 193, 217, 235, 238, 251, 253, 254, 257, 258, 260, 263, 265, 266, 267], "typedef": 8, "typeerror": [39, 56, 79, 81], "typemap": 39, "typestr": 8, "typic": [38, 61, 73, 78, 175, 202, 214, 238, 251, 259, 260], "typo": [1, 10, 70, 79, 267], "t\u00f6r\u00f6k": [0, 267], "u": [8, 9, 10, 39, 42, 43, 54, 77, 78, 85, 134, 139, 152, 154, 157, 159, 171, 175, 198, 201, 202, 251, 254, 263, 265, 266], "u1": 8, "u2": 8, "u4": 8, "u5": 8, "u7": 159, "u_": [81, 203], "u_0": 203, "u_1": 203, "u_n": 203, "ubiquit": 251, "ubuntu": [2, 265, 267], "uchida": [0, 267], "ufl": 253, "ufunc": [38, 73], "ufunc_loop": 8, "ugli": [9, 140, 239], "uint16": [8, 171, 231], "uint32": [8, 159, 171], "uint64": [159, 171], "uint8": [8, 37, 158, 171, 231], "ultim": 8, "umfpack": 65, "unabl": [238, 244], "unalia": 10, "unambigu": 10, "unambigusouli": 227, "uncaught": 10, "unchang": 159, "unclear": 70, "uncom": 54, "uncommon": 54, "undefin": [85, 266], "under": [3, 9, 10, 53, 70, 73, 84, 217, 234, 249, 265, 267], "underfit": [234, 251], "underflow": 202, "underli": [184, 202, 265], "underlin": 9, "underneath": 9, "underperform": 251, "underscor": 251, "understand": [8, 9, 10, 39, 54, 76, 77, 85, 175, 203, 251, 265], "understood": 39, "undisplai": 10, "undocu": 10, "unexpect": 85, "unfortun": 9, "unicod": [8, 9, 77], "unicodeencodeerror": 79, "unicodeerror": 79, "uniform": [37, 111, 113, 122, 139, 142, 154, 157, 159, 223, 231, 251], "uniform_filt": [14, 37], "uniniti": 159, "union": [259, 265], "uniqu": [22, 28, 37, 39, 53, 77, 175], "unit": [9, 54, 202, 251, 263, 265], "unittest": 9, "univari": [73, 217], "univariatesplin": [73, 75, 206, 207], "univers": [38, 73, 76], "unix": [76, 84, 85, 86], "unknown": [48, 202, 251, 266], "unlabel": 251, "unless": [53, 70, 81, 159, 171], "unlik": [9, 66, 76, 265, 266], "unlock": 9, "unmaintain": 202, "unmarri": 259, "unmix": 54, "unmolten": [73, 75, 201, 202], "unnam": 265, "unnecessari": [8, 39], "unord": [9, 77], "unpredict": 9, "unread": 9, "unreli": 46, "unrol": 54, "unseen": 251, "unselect": [1, 267], "unsign": [8, 171, 231], "unspecifi": [159, 175], "unstabl": [33, 53, 202], "unsuccess": 251, "unsupervis": [54, 73, 217, 233, 238], "unsupport": 79, "unsur": 8, "unt": 10, "untermin": 77, "until": [8, 9, 10, 48, 157, 202, 216, 251, 265], "unus": 8, "unusu": 202, "up": [1, 2, 8, 9, 23, 37, 39, 46, 54, 70, 76, 77, 159, 169, 172, 202, 238, 251, 267], "upadhyai": [0, 267], "upcast": 159, "updat": [1, 9, 39, 74], "upgrad": [1, 267], "upon": 265, "upper": [8, 10, 48, 89, 96, 97, 157, 169, 198, 202, 204, 214, 216], "url": [1, 231, 260, 267], "urllib": 260, "urlopen": 260, "us": [1, 2, 8, 13, 18, 29, 33, 38, 39, 43, 46, 48, 50, 54, 55, 56, 57, 58, 59, 60, 63, 65, 66, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 90, 102, 121, 124, 140, 144, 151, 157, 158, 171, 172, 174, 181, 189, 197, 198, 201, 202, 203, 204, 214, 215, 216, 217, 226, 227, 228, 231, 232, 233, 237, 238, 239, 248, 249, 250, 253, 256, 257, 258, 259, 260, 263, 265, 267, 268], "usabl": 39, "usag": [1, 38, 39, 54, 76, 119, 157, 267], "use_solv": 65, "use_umfpack": 65, "use_unicod": 266, "usecol": 260, "usefulli": 85, "useless": [9, 10, 54, 76], "user": [8, 9, 10, 54, 65, 66, 74, 76, 85, 157, 202, 231, 253], "user_defined_modul": 85, "userwarn": 144, "usetex": 105, "usr": [10, 85], "usual": [2, 8, 9, 39, 53, 56, 62, 66, 159, 171, 251, 267], "util": [39, 85, 202, 231], "utkarsh": [0, 267], "v": [1, 9, 10, 38, 40, 49, 52, 53, 54, 61, 65, 73, 77, 108, 110, 134, 139, 152, 154, 159, 231, 251, 267, 268], "v0": 215, "v3": [18, 37, 158], "v_": [206, 207], "va": [81, 101, 103, 105, 108, 110, 119, 120, 122, 126, 136, 137, 138, 139, 154, 157, 233], "vacat": 251, "vagu": 266, "vahtra": [0, 1, 267], "val": [78, 181, 229, 231, 246], "valentin": [0, 1, 39, 76, 267], "valid": [73, 79, 217, 234, 237, 241, 243], "validation_curv": [234, 251], "validation_scor": [234, 251], "vallei": 53, "valu": [8, 9, 10, 33, 37, 39, 42, 48, 53, 54, 55, 56, 57, 58, 59, 60, 62, 63, 65, 66, 73, 74, 75, 76, 77, 78, 80, 84, 157, 159, 166, 171, 172, 175, 181, 186, 191, 198, 201, 203, 215, 216, 231, 237, 251, 257, 258, 260, 263, 266], "valueerror": [79, 159, 175], "van": [0, 1, 9, 54, 74, 267], "vandenbergh": 53, "vander": 74, "vandermond": 74, "vanderpla": 251, "var": [6, 9, 70, 81, 202, 203, 253, 259, 265, 266], "vari": [8, 9, 39, 74, 231, 234, 251], "variabl": [8, 9, 10, 39, 53, 54, 73, 75, 76, 80, 83, 84, 85, 157, 171, 172, 186, 202, 215, 251, 253, 254, 257, 258, 260, 263, 266], "variable_arg": 81, "varianc": [54, 73, 202, 217, 232, 250, 257, 258, 268], "variant": [8, 202, 216], "variat": [10, 11, 36, 37, 83, 186, 202, 225, 265, 268], "varieti": [39, 76, 84, 182, 183, 201, 202, 236, 265], "variou": [1, 8, 9, 14, 28, 38, 39, 70, 74, 76, 84, 104, 109, 120, 159, 175, 187, 202, 217, 218, 230, 231, 259, 265, 266, 267, 268], "varoquau": [10, 85], "varoquaux": [0, 1, 10, 37, 39, 53, 54, 76, 84, 157, 174, 202, 251, 265, 267], "vast": 265, "vastli": 251, "ve": [81, 157, 251], "vec": [59, 139, 154, 233], "vector": [9, 38, 45, 54, 55, 56, 57, 58, 59, 65, 66, 73, 74, 99, 156, 157, 175, 202, 246, 247, 248, 251, 265, 268], "vectori": 53, "venv": [76, 85], "verb": 9, "verbos": [76, 84], "verdier": [0, 267], "veri": [8, 9, 39, 46, 47, 53, 56, 59, 65, 70, 74, 76, 77, 81, 84, 85, 157, 159, 175, 181, 202, 215, 216, 249, 251, 255], "verif": 175, "verifi": [8, 175, 253], "versa": 85, "versicolor": [251, 254, 265], "versicolour": 251, "version": [1, 8, 9, 10, 39, 46, 53, 54, 70, 76, 85, 86, 171, 253, 265, 267], "version_info": 42, "versionad": [74, 159], "versu": [38, 51, 73, 99, 100, 118, 153, 157, 216, 268], "vertic": [99, 156, 157, 268], "verticalalign": [132, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154], "very_blur": [14, 37], "vf": 39, "vh": 202, "via": [9, 39, 53, 66, 73, 76, 159, 197, 217, 265, 266], "vibrant": [74, 76], "vicin": 202, "video": [231, 251], "view": [9, 10, 38, 54, 73, 75, 76, 174, 175, 232, 250, 251, 265, 268], "view_init": 258, "viewer": 231, "vignett": [99, 141, 155, 157, 268], "vim": 10, "vimrc": 10, "vinc": [0, 1, 267], "violat": [9, 10, 265], "violet": 150, "viq": [256, 263, 265], "virgil": [1, 267], "virgilefritsch": [0, 267], "virginica": [251, 254, 265], "viridi": 177, "virtanen": [0, 1, 8, 174, 267], "virtu": 39, "virtual": [2, 9, 267], "vise": 85, "visibl": 157, "vision": [73, 217, 238], "visual": [8, 10, 38, 40, 52, 53, 54, 61, 73, 75, 76, 157, 174, 177, 202, 217, 219, 232, 238, 240, 244, 250, 252, 254, 256, 261, 268], "visualis": 202, "vital": 251, "vmax": [16, 17, 19, 20, 28, 37, 48], "vmin": [16, 17, 19, 20, 37, 197], "void": [8, 39, 171, 204], "volum": 172, "voronoi": [33, 37], "vowel": 78, "w": [8, 9, 10, 47, 54, 65, 82, 86, 111, 112, 114, 139, 148, 154, 233, 248], "wa": [9, 39, 53, 76, 79, 80, 198, 201, 202, 216, 251, 263], "wage": [252, 261, 265, 268], "wagner": 65, "wai": [8, 9, 21, 38, 39, 41, 54, 70, 73, 74, 76, 85, 86, 157, 159, 175, 181, 202, 215, 238, 251, 266], "wakeham": [0, 267], "walk": [10, 73, 75, 160, 170, 173, 268], "walker": [73, 175, 218, 230, 268], "wall": 39, "walli": 78, "walt": [0, 54, 267], "want": [8, 9, 10, 35, 39, 53, 54, 70, 74, 76, 79, 81, 83, 85, 157, 159, 172, 175, 215, 216, 227, 231, 248, 251, 253, 265], "warm": 53, "warn": [1, 9, 10, 39, 48, 66, 70, 166, 236, 260, 267], "warp": [224, 231], "wast": [9, 59, 62, 251], "watch": 251, "watersh": [11, 36, 37, 73, 218, 230, 268], "watson": [253, 254, 257, 258, 260, 263, 265], "wav": [38, 73], "wav_head": 8, "wav_header_dtyp": 8, "wave": [8, 53, 159], "waveform": [73, 75, 209, 211], "waveform_1": [210, 211, 215], "waveform_2": [208, 209, 215], "wavelet": 37, "wavfil": 8, "wavread": 8, "wb": [86, 253, 259, 260], "we": [0, 2, 8, 9, 10, 22, 33, 35, 37, 39, 43, 46, 53, 54, 70, 76, 78, 80, 82, 83, 84, 85, 157, 159, 169, 172, 175, 177, 181, 196, 197, 198, 202, 203, 214, 215, 227, 231, 235, 238, 239, 240, 241, 243, 245, 246, 248, 249, 251, 253, 258, 259, 260, 263, 265, 266, 267], "weakli": [33, 37], "weakreflist": 8, "wealth": 76, "web": [76, 84, 159], "webpag": 81, "websit": [74, 76, 231], "week": 8, "weight": [20, 37, 202, 216, 225, 231, 233, 237, 238, 251, 256, 263, 265], "welch": [192, 202], "welcom": [2, 8, 267], "well": [8, 9, 10, 37, 39, 46, 53, 65, 70, 73, 74, 75, 76, 78, 85, 157, 159, 174, 175, 231, 238, 251, 266], "were": [8, 9, 39, 144, 157, 215, 251, 265], "weslei": [86, 265], "what": [9, 10, 38, 39, 53, 54, 73, 75, 76, 77, 81, 157, 158, 171, 172, 174, 175, 202, 215, 217, 238, 253, 263, 265, 266], "whatev": [8, 9, 251], "whati": 10, "wheel": [76, 202], "when": [8, 9, 37, 38, 39, 53, 54, 56, 59, 60, 63, 70, 73, 74, 76, 79, 80, 81, 85, 157, 159, 172, 175, 202, 215, 221, 231, 243, 251, 265], "whenev": 266, "where": [8, 9, 10, 39, 54, 57, 58, 65, 76, 85, 86, 157, 159, 169, 175, 181, 202, 215, 231, 249, 251, 265], "wherea": [202, 251], "whether": [76, 81, 85, 202, 251, 265], "which": [8, 9, 10, 37, 39, 53, 54, 62, 65, 70, 76, 77, 78, 80, 81, 83, 84, 85, 86, 125, 145, 158, 159, 171, 172, 175, 191, 202, 204, 214, 215, 216, 238, 243, 247, 251, 253, 263, 265, 266], "while": [10, 38, 39, 53, 70, 73, 75, 76, 79, 84, 85, 157, 171, 201, 202, 203, 234, 238, 251, 255, 265, 266], "whisker": 143, "white": [15, 37, 77, 89, 122, 132, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 201, 202, 259], "whiten": [54, 238, 244, 251], "whitespac": 85, "whitnei": 265, "who": [76, 85], "whole": [8, 9, 37, 65, 157, 265], "whose": [8, 159, 175, 215], "why": [9, 38, 39, 53, 54, 61, 73, 75, 159, 202, 216, 217, 265], "wide": [2, 76, 238, 267], "width": [73, 75, 90, 99, 100, 118, 133, 142, 143, 144, 145, 146, 147, 148, 150, 151, 152, 153, 154, 215, 233, 239, 251, 254, 265, 268], "wiener": [10, 37, 182, 201, 202], "wiener_fac": [182, 201, 202], "wiener_filt": 10, "wieser": [1, 267], "wiki": [8, 9, 74], "wikipedia": [37, 81, 203, 231], "wilcoxon": 265, "wilcoxonresult": 265, "wild": 238, "willerman": 265, "win": 171, "wind": [73, 75, 202, 205, 207, 212, 213, 268], "windll": 39, "window": [8, 39, 74, 80, 82, 84, 85, 157, 159, 192, 202], "window_s": [224, 231], "windspe": [207, 212, 216], "wing": 157, "winner": 253, "winpython": 76, "winter": 263, "wise": [53, 56, 59, 66, 74, 175], "wish": [39, 54, 202, 214, 251, 265], "within": [10, 46, 53, 65, 76, 81, 85, 157, 202, 251], "without": [8, 9, 43, 53, 78, 157, 172, 175, 216, 249, 251], "wl": 39, "wolf": 48, "won": [46, 83, 85], "word": [1, 2, 9, 62, 70, 73, 78, 85, 217, 267], "wordprocessor": 9, "work": [2, 8, 9, 10, 37, 39, 48, 53, 54, 65, 66, 73, 75, 77, 81, 85, 86, 144, 157, 171, 172, 199, 202, 221, 231, 238, 251, 253, 259, 260, 265, 267], "workaround": 39, "workfil": 82, "workflow": [38, 70, 73, 75, 157], "world": [76, 77, 80, 251], "wors": 251, "worst": 9, "worth": [9, 39, 53, 54, 202], "would": [8, 9, 10, 39, 54, 70, 76, 157, 196, 198, 201, 202, 238, 251, 259, 263, 266], "wouldn": 253, "wrap": [8, 39, 198, 202], "wrap_lin": 266, "wrapper": [39, 65, 251], "wright": 53, "write": [8, 9, 10, 38, 39, 70, 73, 74, 76, 80, 81, 82, 85, 86, 157, 158, 160, 170, 171, 172, 173, 202, 203, 204, 214, 215, 253, 259, 260, 265, 268], "writeabl": 8, "writebackifcopi": 8, "written": [1, 9, 10, 39, 53, 76, 77, 85, 266, 267], "wrong": [8, 9, 10, 39], "wrote": 54, "wspace": [12, 14, 15, 16, 17, 19, 20, 21, 23, 24, 25, 26, 27, 28, 30, 33, 34, 35, 178, 182, 183, 185, 234, 237], "wspeed": [207, 212], "wstrict": 39, "wvtxfh": [85, 86], "www": [8, 10, 84, 85, 86, 251, 265, 266], "x": [8, 10, 13, 21, 24, 25, 29, 30, 31, 33, 35, 37, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 62, 65, 68, 70, 74, 76, 79, 80, 81, 84, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 108, 110, 121, 122, 123, 124, 125, 127, 130, 131, 132, 134, 135, 139, 140, 142, 143, 144, 145, 146, 148, 149, 150, 152, 153, 154, 157, 158, 159, 161, 163, 164, 166, 167, 169, 171, 172, 175, 177, 178, 179, 180, 181, 186, 187, 188, 189, 201, 202, 203, 209, 211, 215, 227, 231, 233, 234, 236, 239, 241, 242, 244, 245, 246, 247, 248, 249, 251, 253, 257, 258, 259, 260, 265, 266], "x0": [46, 48, 53, 65, 177, 187, 202, 209, 211, 215], "x00": 8, "x01": 8, "x02": 8, "x03": 8, "x04": 8, "x05": 8, "x06": 8, "x07": 8, "x08": 8, "x1": [35, 227, 231, 246, 247], "x11": [85, 86], "x2": [8, 35, 39, 157, 227, 231, 246, 247], "x64": [48, 85, 86, 181, 236], "x86": 8, "x86_64": 39, "x_": 49, "x_0": [41, 202], "x_1": [43, 50, 53, 202], "x_2": [43, 50, 53], "x_2d": [39, 248, 251], "x_bfg": 47, "x_data": 179, "x_detrend": [180, 202], "x_diag": 8, "x_empti": 39, "x_i": 48, "x_incorrect_dtyp": 39, "x_index": 240, "x_l_bfg": 47, "x_max": [48, 239, 247], "x_min": [46, 48, 53, 239, 247], "x_new": [233, 242, 251], "x_newton": 47, "x_not_native_byteord": 39, "x_pca": [244, 251], "x_ref": 47, "x_resampl": [189, 202], "x_test": [234, 235, 236, 237, 238, 245, 249, 251], "x_test_pca": 238, "x_train": [234, 235, 236, 237, 238, 251], "x_train_pca": 238, "xaxi": [89, 95, 96, 97, 117, 125, 145, 157], "xe9": 79, "xg": 177, "xim": [85, 86], "xk": 65, "xlabel": [41, 62, 169, 175, 181, 191, 192, 196, 199, 202, 206, 207, 208, 209, 210, 211, 212, 215, 234, 235, 239, 240, 241, 243, 257, 265], "xlim": [42, 48, 89, 90, 91, 92, 93, 94, 95, 96, 97, 101, 102, 103, 104, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 122, 130, 134, 135, 142, 148, 150, 152, 153, 157, 177, 199], "xlog1pi": 202, "xmin": 188, "xmin_glob": 188, "xmin_loc": 188, "xtest": 251, "xtick": [42, 48, 89, 90, 91, 93, 94, 95, 96, 97, 101, 102, 103, 104, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 119, 120, 121, 122, 123, 126, 127, 128, 129, 130, 132, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 146, 148, 149, 150, 152, 153, 154, 157, 233, 234, 237, 238, 247, 251, 255], "xtol": 48, "xtrain": 251, "xx": [142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 239, 246], "xxx": 70, "xxxxx": 8, "xy": [89, 97, 157, 202], "xycoord": [89, 97, 157], "xytext": [89, 97, 157], "y": [8, 13, 24, 25, 29, 30, 31, 33, 35, 37, 39, 43, 45, 46, 47, 48, 50, 53, 68, 70, 80, 81, 90, 108, 110, 121, 122, 123, 124, 125, 127, 130, 131, 132, 134, 135, 139, 140, 143, 144, 145, 146, 149, 150, 152, 153, 154, 157, 158, 159, 161, 163, 164, 166, 167, 169, 171, 172, 175, 177, 178, 190, 191, 201, 202, 203, 206, 207, 209, 211, 215, 227, 231, 233, 234, 236, 239, 241, 242, 244, 245, 246, 247, 248, 249, 251, 253, 257, 258, 259, 260, 265, 266], "y0": [191, 202], "y1": [35, 122, 142, 157, 227, 231], "y2": [8, 35, 122, 142, 157, 227, 231], "y_2d": 39, "y_data": 179, "y_empti": 39, "y_i": 48, "y_index": 240, "y_max": [48, 239, 247], "y_min": [48, 239, 247], "y_new": [233, 242, 251], "y_not_native_byteord": 39, "y_pred": [236, 238, 251], "y_test": [234, 235, 236, 237, 238, 251], "y_train": [234, 235, 236, 237, 238, 251], "yasutomo57jp": [0, 267], "yaxi": [89, 95, 96, 97, 117, 125, 145, 157], "ye": [10, 66, 85], "year": [6, 8, 158, 168, 172, 176, 195, 199, 200, 202, 212, 216, 251, 253, 259, 260, 268], "yearli": 196, "yearly_temp": 196, "years_nb": [206, 207, 212, 216], "yellow": 77, "yep": 54, "yet": [9, 10, 70, 76, 251, 253], "yg": 177, "yield": [9, 10, 54], "ylabel": [41, 42, 48, 62, 169, 175, 181, 191, 192, 196, 199, 202, 206, 207, 208, 209, 210, 211, 212, 215, 234, 235, 239, 240, 241, 243, 257, 265], "ylim": [41, 44, 48, 49, 51, 89, 90, 91, 92, 93, 94, 95, 96, 97, 101, 103, 107, 109, 116, 117, 122, 124, 130, 134, 135, 142, 148, 150, 152, 153, 157, 177, 234], "ymax": [41, 234], "ymin": [41, 44, 49, 51, 234], "yosh": [0, 267], "you": [2, 8, 10, 37, 39, 53, 54, 70, 74, 76, 77, 78, 79, 80, 81, 82, 85, 86, 157, 158, 159, 171, 172, 175, 198, 202, 215, 216, 231, 251, 260, 265, 266, 267], "young": 76, "your": [8, 9, 10, 37, 38, 39, 54, 70, 73, 75, 76, 77, 78, 79, 80, 81, 84, 86, 157, 159, 172, 203, 231, 251, 265], "yourself": [10, 39, 80, 85], "ytest": 251, "ytick": [12, 26, 42, 48, 89, 90, 91, 93, 94, 95, 96, 97, 101, 102, 103, 104, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 126, 127, 128, 129, 130, 132, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 146, 148, 149, 150, 152, 153, 154, 157, 181, 233, 234, 237, 238, 247, 251], "ytrain": 251, "yy": [239, 246], "z": [8, 47, 48, 77, 78, 81, 127, 129, 131, 132, 143, 146, 149, 157, 159, 166, 172, 175, 190, 202, 239, 246, 247, 253, 258, 265], "z0": [8, 190, 202], "z_0": 202, "z_1": 202, "z_in": 8, "z_out": 8, "zachari": [0, 1, 267], "zbigniew": [0, 1, 9, 267], "zdir": [131, 149], "zero": [1, 8, 10, 12, 15, 16, 21, 22, 24, 25, 26, 28, 30, 34, 37, 39, 46, 47, 53, 54, 60, 62, 63, 78, 79, 117, 143, 159, 171, 175, 185, 197, 198, 199, 201, 202, 222, 226, 231, 238, 249, 251, 253, 265, 267], "zerodivisionerror": 79, "zeros_lik": [35, 159, 227, 231], "zeta": [190, 202], "zip": [5, 6, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 67, 68, 85, 86, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 99, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 157, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 173, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 202, 205, 206, 207, 208, 209, 210, 211, 212, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 263, 265], "zipfil": 9, "zoom": [37, 183, 201, 202], "zoomed_fac": [183, 201, 202], "zorder": [142, 143, 144, 145, 146, 147, 148, 150, 152, 153, 154, 233, 247], "\u00e7a\u011flayan": [0, 1, 267], "\u00f3scar": [1, 267], "\u2460": 9, "\u2461": 9}, "titles": ["4.1.1. Authors", "What\u2019s new", "Contributing", "License", "4. About the Scientific Python Lectures", "Examples for the advanced NumPy chapter", "Example: Masked statistics", "Computation times", "2.2. Advanced NumPy", "2.1. Advanced Python Constructs", "2.3. Debugging code", "Examples for the image processing chapter", "2.6.8.21. Segmentation with Gaussian mixture models", "2.6.8.3. Plot the block mean of an image", "2.6.8.8. Blurring of images", "2.6.8.20. Cleaning segmentation with mathematical morphology", "2.6.8.16. Denoising an image with the median filter", "2.6.8.6. Display a Raccoon Face", "2.6.8.1. Displaying a Raccoon Face", "2.6.8.11. Image denoising", "2.6.8.13. Total Variation denoising", "2.6.8.19. Finding edges with Sobel filters", "2.6.8.15. Find the bounding box of an object", "2.6.8.12. Geometrical transformations", "2.6.8.23. Granulometry", "2.6.8.18. Greyscale dilation", "2.6.8.17. Histogram segmentation", "2.6.8.2. Image interpolation", "2.6.8.14. Measurements from images", "2.6.8.4. Image manipulation and NumPy arrays", "2.6.8.10. Opening, erosion, and propagation", "2.6.8.5. Radial mean", "2.6.8.7. Image sharpening", "2.6.8.24. Segmentation with spectral clustering", "2.6.8.9. Synthetic data", "2.6.8.22. Watershed segmentation", "Computation times", "2.6. Image manipulation and processing using NumPy and SciPy", "2. Advanced topics", "2.8. Interfacing with C", "Examples for the mathematical optimization chapter", "2.7.4.7. Brent\u2019s method", "2.7.4.10. Plotting the comparison of optimizers", "2.7.4.8. Constraint optimization: visualizing the geometry", "2.7.4.4. Convex function", "2.7.4.3. Curve fitting", "2.7.4.5. Finding a minimum in a flat neighborhood", "2.7.4.9. Alternating optimization", "2.7.4.11. Gradient descent", "2.7.4.1. Noisy optimization problem", "2.7.4.6. Optimization with constraints", "2.7.4.2. Smooth vs non-smooth", "Computation times", "2.7. Mathematical optimization: finding minima of functions", "2.4. Optimizing code", "Block Compressed Row Format (BSR)", "Coordinate Format (COO)", "Compressed Sparse Column Format (CSC)", "Compressed Sparse Row Format (CSR)", "Diagonal Format (DIA)", "Dictionary of Keys Format (DOK)", "2.5. Sparse Arrays in SciPy", "2.5.1. Introduction", "List of Lists Format (LIL)", "2.5.4. Other Interesting Packages", "2.5.3. Linear System Solvers", "2.5.2. Storage Schemes", "Examples for the contribution guide", "A simple example", "Computation times", "How to contribute", "<no title>", "<no title>", "Scientific Python Lectures", "1.6. Getting help and finding documentation", "1. Getting started with Python for science", "1.1. Python scientific computing ecosystem", "1.2.2. Basic types", "1.2.3. Control Flow", "1.2.8. Exception handling in Python", "1.2.1. First steps", "1.2.4. Defining functions", "1.2.6. Input and Output", "1.2.9. Object-oriented programming (OOP)", "1.2. The Python language", "1.2.5. Reusing code: scripts and modules", "1.2.7. Standard Library", "Code for the chapter\u2019s exercises", "Exercise 1", "Exercise", "Exercise 2", "Exercise 3", "Exercise 4", "Exercise 5", "Exercise 6", "Exercise 7", "Exercise 8", "Exercise 9", "Computation times", "Code samples for Matplotlib", "Example demoing choices for an option", "Aliased versus anti-aliased", "Alpha: transparency", "Aliased versus anti-aliased", "The colors matplotlib line plots", "Colormaps", "Dash capstyle", "Dash join style", "Linestyles", "Linewidth", "Markers", "Marker edge color", "Marker edge width", "Marker face color", "Marker size", "Solid cap style", "Solid joint style", "Locators for tick on axis", "Computation times", "Simple axes example", "Axes", "A simple plotting example", "Bar plots", "Displaying the contours of a function", "A simple, good-looking plot", "Grid", "GridSpec", "Imshow elaborate", "Subplots", "Pie chart", "Plot and filled plots", "3D plotting", "3D plotting", "Plotting in polar coordinates", "Plotting a vector field: quiver", "Plotting a scatter of points", "Subplot grid", "Horizontal arrangement of subplots", "Subplot plot arrangement vertical", "Demo text printing", "A example of plotting not quite right", "Code generating the summary figures with a title", "Bar plot advanced", "Boxplot with matplotlib", "Display the contours of a function", "Grid elaborate", "Imshow demo", "Multiple plots vignette", "Pie chart vignette", "3D plotting vignette", "Plot example vignette", "Plotting in polar, decorated", "Plotting quiver decorated", "Plot scatter decorated", "Text printing decorated", "Computation times", "Computation times", "1.4. Matplotlib: plotting", "1.3.4. Advanced operations", "1.3.1. The NumPy array object", "Full code examples for the numpy chapter", "1D plotting", "2D plotting", "Fitting in Chebyshev basis", "Distances exercise", "Reading and writing an elephant", "Mandelbrot set", "Fitting to polynomial", "Population exercise", "Random walk exercise", "Computation times", "1.3.3. More elaborate arrays", "1.3.5. Some exercises", "1.3.6. Full code examples", "1.3. NumPy: creating and manipulating numerical data", "1.3.2. Numerical operations on arrays", "Full code examples for the SciPy chapter", "1.5.12.15. Optimization of a two-parameter function", "1.5.12.12. Demo connected components", "1.5.12.8. Curve fitting", "1.5.12.3. Detrending a signal", "1.5.12.16. Plotting and manipulating FFTs for filtering", "1.5.12.14. Plot filtering on images", "1.5.12.11. Plot geometrical transformations on images", "1.5.12.17. A demo of 1D interpolation", "1.5.12.10. Demo mathematical morphology", "1.5.12.5. Normal distribution: histogram and PDF", "1.5.12.1. Finding the minimum of a smooth function", "1.5.12.13. Minima and roots of a function", "1.5.12.2. Resample a signal with scipy.signal.resample", "1.5.12.6. Integrate the Damped spring-mass oscillator", "1.5.12.4. Integrating a simple ODE", "1.5.12.9. Spectrogram, power spectral density", "1.5.12.7. Comparing 2 sets of samples from Gaussians", "Computation times", "Solutions of the exercises for SciPy", "Curve fitting: temperature as a function of month of the year", "Image denoising by FFT", "Simple image blur by convolution with a Gaussian kernel", "Crude periodicity finding", "Computation times", "Geometrical transformations on images", "1.5. SciPy : high-level scientific computing", "Solutions", "1.5.11.4. Example of solution for the image processing exercise: unmolten grains in glass", "Examples for the summary excercices", "Cumulative wind speed prediction", "The Gumbell distribution", "The lidar system, data (2 of 2 datasets)", "The lidar system, data and fit (2 of 2 datasets)", "The lidar system, data (1 of 2 datasets)", "The lidar system, data and fit (1 of 2 datasets)", "The Gumbell distribution, results", "Computation times", "1.5.11.3. Image processing application: counting bubbles and unmolten grains", "1.5.11.2. Non linear least squares curve fitting: application to point extraction in topographical lidar data", "1.5.11.1. Maximum wind speed prediction at the Sprog\u00f8 station", "3. Packages and applications", "Examples for the scikit-image chapter", "3.3.11.6. Segmentation contours", "3.3.11.2. Displaying a simple image", "3.3.11.3. Integers can overflow", "3.3.11.1. Creating an image", "3.3.11.4. Equalizing the histogram of an image", "3.3.11.8. Affine transform", "3.3.11.10. Various denoising filters", "3.3.11.9. Labelling connected components of an image", "3.3.11.11. Watershed and random walker for segmentation", "3.3.11.5. Computing horizontal gradients with the Sobel filter", "3.3.11.7. Otsu thresholding", "Computation times", "3.3. scikit-image: image processing", "Examples for the scikit-learn chapter", "3.4.8.17. Tutorial Diagrams", "3.4.8.16. Bias and variance of polynomial fit", "3.4.8.11. A simple regression analysis on the California housing data", "3.4.8.9. Compare classifiers on the digits data", "3.4.8.13. Simple visualization and classification of the digits dataset", "3.4.8.14. The eigenfaces example: chaining PCA and SVMs", "3.4.8.12. Nearest-neighbor prediction on iris", "3.4.8.4. Plot 2D views of the iris dataset", "3.4.8.6. Use the RidgeCV and LassoCV to set the regularization parameter", "3.4.8.3. A simple linear regression", "3.4.8.2. Measuring Decision Tree performance", "3.4.8.1. Demo PCA in 2D", "3.4.8.10. Plot fitting a 9th order polynomial", "3.4.8.8. Simple picture of the formal problem of machine learning", "3.4.8.15. Example of linear and non-linear models", "3.4.8.5. tSNE to visualize digits", "3.4.8.7. Plot variance and regularization in linear models", "Computation times", "3.4. scikit-learn: machine learning in Python", "Full code for the figures", "3.1.6.8. Air fares before and after 9/11", "3.1.6.3. Analysis of Iris petal and sepal sizes", "3.1.6.1. Boxplots and paired differences", "3.1.6.2. Plotting simple quantities of a pandas dataframe", "3.1.6.4. Simple Regression", "3.1.6.5. Multiple Regression", "3.1.6.7. Visualizing factors influencing wages", "3.1.6.6. Test for an education/gender interaction in wages", "Computation times", "3.1.7.1. Solutions to this chapter\u2019s exercises", "Relating Gender and IQ", "Computation times", "3.1. Statistics in Python", "3.2. Sympy : Symbolic Mathematics in Python", "About the Scientific Python Lectures", "Computation times"], "titleterms": {"": [1, 8, 41, 53, 76, 87, 99, 157, 158, 251, 252, 262, 265, 267], "0": [1, 267], "1": [1, 88, 210, 211, 267], "10": [1, 267], "11": 253, "16": [1, 267], "1d": [53, 161, 184], "2": [1, 37, 90, 193, 202, 208, 209, 210, 211, 237, 267], "20": [1, 267], "2011": [1, 267], "2012": [1, 267], "2013": [1, 267], "2015": [1, 267], "2016": [1, 267], "2017": [1, 267], "2018": [1, 267], "2019": [1, 267], "2020": [1, 267], "2022": [1, 267], "2024": [1, 267], "21": [1, 267], "22": [1, 267], "26": [1, 267], "2d": [162, 177, 197, 240, 244], "2nd": 53, "3": [1, 53, 91, 267], "3d": [131, 132, 149, 157, 177, 231], "4": 92, "5": 93, "6": 94, "7": 95, "8": 96, "9": [97, 253], "9th": 245, "A": [9, 10, 53, 65, 68, 121, 124, 140, 177, 184, 198, 235, 238, 242, 251, 265], "It": 8, "No": 54, "One": [73, 265], "The": [8, 65, 76, 84, 104, 159, 196, 198, 203, 207, 208, 209, 210, 211, 212, 238, 251, 265], "__main__": 85, "about": [53, 267], "acknowledg": 251, "across": 265, "ad": [157, 175], "adapt": 53, "addit": [0, 54, 267], "admonit": 70, "advanc": [5, 8, 9, 38, 78, 142, 158], "affin": 224, "after": 253, "air": 253, "algebra": [54, 202, 266], "algorithm": [53, 54, 175], "alias": [101, 103], "all": 181, "alpha": 102, "altern": [10, 47], "an": [8, 13, 16, 22, 76, 86, 99, 100, 157, 159, 165, 198, 222, 223, 226, 260], "analysi": [10, 235, 238, 254, 265], "ani": 78, "annot": 157, "anova": 265, "anti": [101, 103], "api": 39, "applic": [62, 214, 215, 217, 251], "approach": [216, 251], "approxim": [53, 172], "apr": [1, 267], "april": [1, 267], "ar": [8, 81, 85, 159], "arrai": [8, 29, 37, 61, 66, 159, 171, 172, 175, 265], "arrang": [137, 138], "ask": 79, "assign": 77, "attribut": 9, "august": [1, 267], "author": [0, 267], "automat": 251, "avoid": [10, 53], "awar": 8, "ax": [119, 120, 157], "axi": [117, 157, 237], "background": 231, "bar": [122, 142, 157], "base": [53, 158, 231], "basi": 163, "basic": [37, 77, 159, 175, 251], "bay": [237, 251], "befor": [76, 253], "best": 10, "better": 197, "between": 265, "beyond": 157, "bia": [234, 251], "bidirect": 9, "binari": 231, "block": [8, 13, 55], "blur": [14, 37, 198], "boolean": 159, "boost": 251, "bound": [22, 53], "box": [22, 53], "boxplot": [143, 255], "break": 78, "brent": [41, 53], "brian": 10, "broadcast": [8, 175], "brute": 53, "bsr": 55, "bubbl": 214, "buffer": 8, "bug": [8, 10], "build": [2, 8, 267], "built": 251, "c": [8, 39, 76], "cach": 8, "calcul": 266, "calculu": 266, "california": 235, "can": 221, "cap": 115, "capstyl": 106, "case": 53, "cast": [8, 171], "catch": [9, 79], "categor": 265, "categori": 265, "caution": 251, "chain": [9, 172, 238], "chang": 157, "channel": 165, "chapter": [0, 2, 5, 8, 9, 10, 11, 37, 39, 40, 53, 54, 70, 87, 99, 157, 160, 173, 176, 202, 218, 231, 232, 251, 252, 262, 265, 266, 267], "chararrai": 8, "chart": [129, 148, 157], "chebyshev": 163, "checker": 10, "chirp": 192, "choic": [2, 99, 100, 157, 267], "choos": 53, "class": [9, 65, 66], "classif": [237, 251], "classifi": [236, 237, 251], "clean": 15, "clear": 70, "cluster": 33, "code": [10, 37, 53, 54, 70, 85, 87, 99, 141, 157, 160, 173, 176, 202, 231, 251, 252, 265], "collaps": 70, "color": [104, 111, 113, 157], "colormap": [105, 157], "colorspac": 231, "column": 57, "command": [10, 86], "common": [65, 66], "commun": 9, "compar": [76, 193, 236, 265], "comparison": [42, 231], "compil": 76, "complex": 251, "compon": [178, 201, 202, 226, 231, 238, 251], "comprehens": 78, "compress": [55, 57, 58], "comput": [7, 36, 52, 53, 54, 69, 76, 84, 98, 118, 155, 156, 170, 175, 181, 192, 194, 197, 200, 202, 213, 216, 228, 230, 231, 250, 261, 264, 268], "concept": 231, "concis": 70, "condit": [53, 78], "conjug": 53, "connect": [178, 201, 202, 226, 231], "constraint": [43, 50, 53], "construct": [9, 159], "contain": 77, "content": [8, 9, 10, 37, 39, 53, 54, 70, 157, 158, 159, 171, 175, 202, 231, 251, 265, 266], "context": 9, "continu": [78, 231], "contour": [123, 144, 157, 219], "contribut": [0, 2, 8, 67, 70, 267], "control": 78, "conveni": 8, "convent": 159, "converg": 53, "convert": 265, "convex": [44, 53], "convolut": 198, "coo": 56, "coordin": [56, 133], "copi": [9, 159], "correct": 251, "cost": 53, "count": 214, "cover": [2, 267], "cprofil": 54, "cpu": 8, "creat": [85, 159, 174, 222, 265], "creation": 159, "cross": 251, "crude": [172, 199], "csc": 57, "csr": 58, "ctype": 39, "cumul": [206, 216], "current": 10, "curv": [45, 53, 179, 196, 202, 215, 234, 251], "cython": 39, "d": [37, 202], "damp": 190, "dash": [106, 107], "data": [8, 34, 73, 158, 159, 171, 172, 174, 175, 196, 199, 202, 203, 208, 209, 210, 211, 215, 231, 235, 236, 237, 251, 265], "datafram": [256, 265], "dataset": [208, 209, 210, 211, 237, 240, 251], "deal": 171, "debug": 10, "debugg": 10, "decis": 243, "decor": [9, 151, 152, 153, 154], "default": 157, "defin": [9, 81, 188], "definit": 81, "demo": [99, 100, 139, 146, 157, 178, 184, 185, 244], "denois": [16, 19, 20, 37, 197, 202, 225, 231], "densiti": 192, "deprec": 9, "descent": [48, 53], "descriptor": 8, "design": [2, 267], "detail": 157, "detect": 37, "detrend": 180, "devil": 157, "dia": 59, "diagon": [8, 59], "diagram": 233, "dictionari": [60, 77, 78], "differ": [53, 171, 255, 265], "differenti": [53, 266], "diffus": 175, "digit": [236, 237, 248, 251], "dilat": 25, "dimens": [8, 175, 251], "dimension": [53, 251], "direct": 65, "directori": [86, 203], "discov": 77, "discret": 231, "displai": [17, 18, 37, 123, 144, 165, 220], "dissect": 8, "distanc": 164, "distribut": [186, 202, 207, 212, 216], "do": [198, 238], "docstr": [9, 81], "document": [8, 70, 73, 74, 157, 159], "doe": 76, "dok": 60, "domain": 8, "donald": 54, "download": 73, "earlier": 231, "easi": 86, "easier": [8, 79, 197], "ecosystem": [76, 231], "edg": [21, 37, 111, 112], "edit": 10, "editor": [0, 76, 267], "educ": 260, "effect": 8, "eigen": 65, "eigenfac": 238, "eigenvalu": 65, "elabor": [76, 127, 145, 171], "elementwis": 175, "eleph": 165, "elif": 78, "els": 78, "embed": 251, "enhanc": 231, "enumer": 78, "environ": [76, 86], "equal": 223, "equat": 266, "eros": 30, "error": 10, "estim": 251, "etc": 76, "exact": 53, "exampl": [2, 5, 6, 8, 9, 11, 37, 39, 40, 53, 54, 55, 56, 57, 58, 59, 60, 63, 65, 67, 68, 70, 99, 100, 119, 121, 140, 150, 157, 159, 160, 173, 175, 176, 202, 204, 205, 218, 231, 232, 238, 247, 251, 267], "except": [9, 10, 79], "excercic": 205, "execut": 10, "exercis": [8, 10, 37, 39, 53, 78, 81, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 99, 157, 158, 159, 164, 168, 169, 172, 175, 176, 195, 201, 202, 204, 216, 231, 251, 252, 262, 265, 266], "expand": 266, "expans": 266, "explor": 265, "express": [9, 78], "extern": 86, "extract": [37, 215, 231], "face": [17, 18, 113, 172], "facial": 238, "fact": 53, "factor": [259, 265], "fake": 8, "fanci": 159, "fare": 253, "fast": [10, 202], "faster": [53, 54], "fault": 10, "featur": [8, 37, 231], "feb": [1, 267], "feel": 265, "few": 65, "fft": [181, 197, 198, 202], "fftconvolv": 198, "fibonacci": [81, 203], "field": 134, "figur": [70, 99, 141, 157, 165, 252, 265], "file": [8, 10, 37, 82, 86, 158, 202, 203, 265], "filesystem": 158, "fill": 130, "filter": [16, 21, 37, 181, 182, 197, 201, 202, 225, 228, 231], "final": [79, 197], "find": [8, 21, 22, 46, 53, 74, 177, 187, 188, 199, 202], "first": [80, 237, 266], "fit": [45, 53, 163, 167, 179, 196, 202, 209, 211, 215, 234, 245, 251], "fit_transform": 251, "fix": 53, "flat": [46, 53], "flatten": 175, "float": 70, "flow": 78, "fly": 53, "forc": 53, "foreground": 231, "foreword": 70, "forgiv": 79, "formal": 246, "format": [55, 56, 57, 58, 59, 60, 63, 158], "formula": 265, "fortran": [8, 76], "found": 85, "fourier": 202, "frame": [172, 265], "frequenc": 181, "from": [8, 28, 76, 85, 193], "frozen": 202, "fsiq": 265, "full": [37, 53, 157, 160, 173, 176, 202, 231, 252, 265], "function": [8, 9, 44, 53, 76, 81, 86, 123, 144, 159, 177, 187, 188, 196, 198, 202], "functool": 9, "further": [39, 215], "galleri": 157, "gaussian": [12, 193, 198, 215, 237, 251], "gaussian_filt": 197, "gdb": 10, "gender": [260, 263], "gener": [8, 9, 53, 99, 141, 157, 181, 192], "geometr": [23, 37, 183, 201, 202], "geometri": 43, "get": [10, 53, 74, 75, 76], "github": 70, "glass": 204, "glob": 86, "global": [53, 81], "go": [10, 54, 215], "good": [8, 85, 124, 171], "gradient": [48, 53, 228, 251], "grain": [204, 214], "granulometri": 24, "graphic": 10, "grayscal": 231, "grei": 165, "greyscal": 25, "grid": [53, 125, 136, 145, 157, 251], "gridspec": 126, "group": 265, "guid": [2, 53, 67, 267], "gumbel": [207, 212, 216], "handl": 79, "handwritten": 251, "help": [8, 10, 74, 76], "hessian": 53, "high": [86, 181, 202, 251], "histogram": [26, 186, 223, 231], "hoc": 265, "home": [53, 251, 265], "horizont": [137, 228], "hous": [235, 251], "how": [8, 70, 76, 85], "hyperparamet": 251, "hypothesi": [202, 265], "i": [53, 157, 203, 231, 251], "idl": 76, "illustr": 251, "imag": [11, 13, 14, 16, 19, 27, 28, 29, 32, 37, 158, 177, 182, 183, 197, 198, 201, 202, 204, 214, 218, 220, 222, 223, 226, 231, 237], "implement": [9, 198], "import": [85, 159, 231], "imshow": [127, 146, 157], "includ": [231, 265], "index": [8, 159], "individu": 265, "influenc": 259, "inform": [37, 86], "initi": [202, 215], "input": [82, 197, 202, 231], "instal": 76, "instanti": 157, "instruct": [2, 267], "integ": [8, 159, 221], "integr": [10, 172, 190, 191, 202, 266], "interact": [10, 76, 231, 260, 265], "interest": 64, "interfac": [8, 39, 251], "intern": 158, "interoper": 8, "interpol": [27, 184, 202], "interpret": 8, "introduc": 251, "introduct": [39, 62, 157, 215, 231, 251], "intuit": 53, "invok": 10, "io": 202, "ipython": [10, 54, 76, 157, 158], "iq": 263, "iri": [239, 240, 251, 254], "iter": [9, 53, 65, 78, 82], "its": [199, 251], "join": 107, "joint": 116, "julia": 76, "jun": [1, 267], "jupyt": [76, 157], "k": 251, "keep": [70, 78], "kei": 60, "kernel": 198, "kernighan": 10, "know": 53, "known": 158, "knuth": 54, "label": [157, 226, 231], "lagrang": 53, "land": 202, "languag": [76, 84], "lassocv": 241, "last": 251, "learn": [73, 232, 234, 238, 246, 251], "least": [53, 215], "lectur": [2, 73, 267], "legend": 157, "less": 53, "level": [86, 202], "librari": [9, 86], "licens": [3, 267], "lidar": [208, 209, 210, 211, 215], "life": 8, "like": 10, "lil": 63, "limit": [157, 266], "linalg": 202, "line": [54, 104, 157], "linear": [53, 54, 65, 202, 215, 242, 247, 249, 251, 265, 266], "linearoper": 65, "linestyl": 108, "linewidth": 109, "link": [54, 70, 265], "list": [63, 77, 78, 157, 203], "lmplot": 265, "load": [85, 158, 199, 215, 251], "local": [53, 231], "locat": [117, 157], "look": [124, 251, 265], "loop": [9, 78], "lower": 165, "luck": 53, "machin": [238, 246, 251], "mai": [1, 267], "mail": 157, "main": 8, "make": [8, 53, 54], "manag": 9, "mandelbrot": [166, 172], "manipul": [29, 37, 86, 172, 174, 175, 181, 202, 265, 266], "manual": 159, "march": [1, 267], "marker": [110, 111, 112, 113, 114, 157, 231], "markov": 172, "markup": 70, "mask": [6, 8, 159], "masked_arrai": 8, "maskedarrai": [8, 171], "mass": 190, "match": 86, "mathemat": [15, 37, 40, 53, 185, 201, 202, 231, 266], "matlab": 76, "matplotlib": [99, 104, 143, 157, 265], "matric": [62, 265, 266], "matrix": [62, 251], "matter": 53, "maxim": 202, "maximum": 216, "mead": 53, "mean": [13, 31, 265], "measur": [28, 37, 54, 201, 202, 231, 243, 251, 265], "median": 16, "memori": 8, "messag": [53, 265], "method": [41, 53, 66, 77, 81, 231], "minim": [53, 202], "minima": [53, 177, 188], "minimum": [46, 53, 187], "miss": [8, 171], "mixtur": 12, "mode": [82, 157], "model": [12, 215, 247, 249, 251, 265], "modul": [65, 85, 86], "month": 196, "moon": 202, "more": [8, 77, 158, 171, 265], "morphologi": [15, 37, 185, 201, 202, 231], "mortem": 10, "move": 157, "multi": 157, "multidimension": 8, "multipl": [147, 258, 265], "multipli": 53, "naiv": [237, 251], "natur": 251, "navig": 158, "ndarrai": 8, "ndimag": [37, 197, 202], "nearest": 239, "necessari": 251, "need": 76, "neighbor": [239, 251], "neighborhood": 46, "nelder": 53, "nest": 251, "new": [1, 267], "newton": 53, "noisi": [49, 53], "non": [51, 53, 215, 231, 247, 251], "norm": 53, "normal": 186, "note": [53, 65, 238], "notebook": [76, 251], "nov": [1, 267], "novemb": [1, 267], "number": [53, 78, 81, 159, 202], "numer": [10, 37, 54, 73, 77, 174, 175, 202], "numpi": [5, 8, 29, 37, 39, 158, 159, 160, 173, 174, 202], "o": [86, 203], "object": [2, 9, 22, 37, 77, 81, 83, 85, 159, 202, 251, 266, 267], "obscur": 158, "oct": [1, 267], "octav": 76, "octob": [1, 267], "od": 191, "off": 251, "old": [8, 251], "oop": 83, "open": [30, 37], "oper": [8, 77, 86, 158, 175, 202], "optim": [40, 42, 43, 47, 49, 50, 53, 54, 177, 202, 251], "option": [99, 100, 157], "order": [8, 245], "organ": 85, "orient": [77, 83], "origin": [9, 165, 198], "oscil": 190, "other": [9, 10, 64, 76, 157, 175, 251], "otsu": [229, 231], "output": [82, 202, 231], "outsid": 54, "over": [78, 82, 251], "overflow": 221, "own": 158, "packag": [64, 70, 85, 217], "pair": [255, 265], "pairplot": 265, "panda": [256, 265], "paragraph": 70, "paramet": [65, 81, 177, 241, 251], "part": 8, "pass": 81, "path": 86, "pattern": 86, "pca": [238, 244, 251], "pdf": 186, "perform": [237, 243, 251], "period": [196, 199], "permiss": 79, "persist": 86, "petal": 254, "pi": 203, "pickl": 86, "pictur": [172, 246], "pie": [129, 148, 157], "pipelin": 238, "piq": 265, "plot": [13, 42, 104, 121, 122, 124, 130, 131, 132, 133, 134, 135, 138, 140, 142, 147, 149, 150, 151, 152, 153, 157, 161, 162, 177, 181, 182, 183, 188, 192, 196, 197, 199, 237, 240, 245, 249, 256, 265], "plugin": 9, "point": [8, 135, 157, 215], "polar": [133, 151, 157], "polynomi": [158, 167, 234, 245, 251], "popul": [168, 265], "post": [10, 265], "postmortem": 10, "postprocess": 231, "powel": 53, "power": [181, 192], "practic": [10, 53, 85, 171], "precondit": [53, 65], "predict": [206, 216, 239, 251], "prefer": 251, "prepar": 198, "preprocess": [231, 238], "prerequisit": [8, 10, 53, 54, 62, 251], "price": 251, "prime": 159, "princip": [237, 238, 251], "principl": 251, "print": [10, 139, 154, 266], "probabl": [202, 216], "problem": [49, 53, 65, 202, 214, 246, 251], "process": [11, 37, 202, 204, 214, 231], "profil": 54, "program": [77, 83], "project": 237, "propag": [30, 171], "properti": [37, 157, 231], "protocol": 8, "psd": 192, "pure": 8, "pyflak": 10, "pyplot": 157, "python": [9, 10, 39, 54, 73, 75, 76, 79, 84, 231, 251, 265, 266, 267], "pythonpath": 203, "quadrat": 53, "quadratur": 202, "quantifi": 237, "quantit": 251, "quantiti": 256, "quasi": 53, "question": 251, "quick": [85, 157, 175, 251], "quicksort": [81, 203], "quit": 140, "quiver": [134, 152, 157], "r": 76, "raccoon": [17, 18], "radial": 31, "rais": [10, 79], "random": [169, 175, 202, 227, 231], "rang": 78, "re": 8, "read": [8, 39, 85, 157, 165, 175, 197, 265], "recap": 251, "recarrai": 8, "recognit": 238, "reconstruct": 197, "red": 165, "reduct": [175, 251], "refer": [39, 70, 157, 159], "region": 231, "registr": 9, "regress": [235, 242, 251, 257, 258, 265], "regular": [157, 241, 249, 251], "relat": 263, "releas": [1, 267], "remind": 158, "remov": [9, 181], "repeat": 265, "replac": 9, "report": 8, "represent": 265, "requir": [2, 265, 267], "resampl": 189, "reshap": 175, "resiz": 175, "resolut": 165, "result": 212, "return": 81, "reus": 85, "review": 53, "ridgecv": 241, "right": 140, "robust": 265, "root": [188, 202], "row": [55, 58], "run": [10, 54, 86], "same": 265, "sampl": [99, 157, 193, 202, 265], "scatter": [135, 153, 157, 265], "scheme": [8, 62, 66], "scienc": [73, 75], "scientif": [73, 76, 84, 202, 231, 267], "scientist": 76, "scikit": [218, 231, 232, 251], "scilab": 76, "scipi": [8, 37, 53, 61, 176, 189, 195, 197, 198, 202], "scratch": 8, "script": [76, 85], "seaborn": 265, "search": [53, 203, 251], "section": [70, 158, 159, 171, 175], "segment": [10, 12, 15, 26, 33, 35, 37, 219, 227, 231], "select": 251, "sepal": 254, "separ": [251, 265], "sept": [1, 267], "septemb": [1, 267], "sequenc": [78, 81, 203], "seri": 266, "set": [157, 166, 172, 193, 241, 251, 265], "shape": 175, "share": 8, "sharpen": [32, 37], "shoot": 53, "shuffl": 175, "shutil": 86, "sibl": 8, "siev": 159, "signal": [180, 181, 189, 192, 198, 202], "simpl": [53, 68, 119, 121, 124, 157, 159, 191, 198, 215, 220, 235, 237, 242, 246, 251, 256, 257, 265], "simpler": 251, "simplest": 265, "simplex": 53, "simplic": 9, "simplifi": 266, "size": [114, 171, 254], "slice": [8, 159], "smaller": 171, "smooth": [37, 51, 53, 187], "sobel": [21, 228], "solid": [115, 116], "solut": [8, 76, 176, 195, 202, 203, 204, 215, 252, 262, 265], "solv": 266, "solver": 65, "some": [53, 157, 172], "sort": 175, "spars": [57, 58, 61, 62, 65, 66], "sparsiti": 62, "special": [53, 202], "specif": 86, "specifi": 265, "spectral": [33, 192], "spectrogram": 192, "speed": [206, 216], "spell": 10, "spine": 157, "spring": 190, "sprog\u00f8": 216, "squar": [53, 215], "standard": [9, 86], "start": [10, 53, 75, 76], "stat": 202, "statement": [81, 214], "static": 10, "station": 216, "statist": [6, 8, 37, 172, 202, 216, 265], "step": [10, 53, 80, 266], "storag": [62, 66], "strength": 76, "stride": 8, "string": [8, 77], "structur": [62, 171], "student": 265, "style": [107, 115, 116, 157], "subplot": [128, 136, 137, 138, 157], "subsect": 70, "sum": 175, "summari": [8, 9, 39, 66, 99, 141, 157, 175, 202, 205, 251], "supervis": 251, "support": [39, 238], "surfac": 177, "svd": 54, "svm": 238, "swig": 39, "sy": 86, "symbol": 266, "sympi": 266, "synthet": [34, 53], "system": [9, 65, 86, 208, 209, 210, 211, 266], "t": 265, "tabl": 265, "take": [53, 265], "temperatur": [196, 202], "terminologi": 265, "test": [202, 251, 260, 265], "text": [76, 139, 154, 157, 158], "than": 79, "thank": 157, "thei": 8, "thi": [157, 252, 262, 265], "threshold": [229, 231], "tick": [117, 157], "tile": 159, "time": [7, 36, 52, 69, 98, 118, 155, 156, 170, 194, 200, 213, 230, 250, 261, 264, 268], "timeit": 54, "tip": [76, 265], "titl": [99, 141, 157], "topic": 38, "topograph": 215, "total": 20, "track": 78, "trade": 251, "tradeoff": 251, "transform": [23, 37, 183, 201, 202, 224], "transpar": 102, "tree": [243, 251], "trick": [8, 76], "troubl": 10, "try": 79, "tsne": [248, 251], "tutori": [157, 233], "tweak": 9, "two": [177, 265], "type": [8, 10, 77, 157, 159, 171, 231], "typic": 62, "ufunc": 8, "under": [76, 251], "univari": 265, "univariatesplin": 216, "univers": 8, "unmolten": [204, 214], "unsupervis": 251, "up": 10, "updat": [2, 267], "update_wrapp": 9, "us": [9, 10, 37, 53, 70, 159, 175, 241, 251, 266], "v": [51, 62], "valid": 251, "valu": [81, 202, 265], "variabl": [81, 86, 265], "varianc": [234, 249, 251, 265], "variat": 20, "variou": 225, "vector": [8, 53, 134, 238], "version": [231, 251], "versu": [53, 101, 103, 251], "vertic": 138, "via": [198, 251], "view": [8, 159, 240], "vignett": [147, 148, 149, 150], "vision": 231, "visual": [43, 62, 159, 215, 231, 237, 248, 251, 259, 265], "wage": [259, 260], "wai": 10, "walk": [86, 169, 175], "walker": [227, 231], "walli": 203, "watersh": [35, 227, 231], "wav": 8, "waveform": 215, "well": 158, "what": [1, 8, 159, 231, 251, 267], "when": 10, "while": [9, 78], "why": [8, 62, 76, 251], "width": [112, 157], "wind": [206, 216], "without": [10, 54], "word": 251, "work": [76, 159, 175], "workflow": [10, 54, 76], "wrap": [9, 10], "wrapper": 9, "write": [37, 54, 165], "year": 196, "your": [53, 85]}}) \ No newline at end of file diff --git a/sg_execution_times.html b/sg_execution_times.html new file mode 100644 index 000000000..66f2a3688 --- /dev/null +++ b/sg_execution_times.html @@ -0,0 +1,894 @@ + + + + + + + + Computation times — Scientific Python Lectures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Computation times

+

01:11.364 total execution time for 173 files from all galleries:

+
+ + + + + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Example

Time

Mem (MB)

Visualizing factors influencing wages (packages/statistics/examples/plot_wage_data.py)

00:09.494

0.0

Air fares before and after 9/11 (packages/statistics/examples/plot_airfare.py)

00:07.718

0.0

Gradient descent (advanced/mathematical_optimization/examples/plot_gradient_descent.py)

00:06.858

0.0

Affine transform (packages/scikit-image/examples/plot_features.py)

00:05.704

0.0

A simple regression analysis on the California housing data (packages/scikit-learn/examples/plot_california_prediction.py)

00:04.717

0.0

The eigenfaces example: chaining PCA and SVMs (packages/scikit-learn/examples/plot_eigenfaces.py)

00:04.145

0.0

Colormaps (intro/matplotlib/examples/options/plot_colormaps.py)

00:01.807

0.0

Simple visualization and classification of the digits dataset (packages/scikit-learn/examples/plot_digits_simple_classif.py)

00:01.749

0.0

Bias and variance of polynomial fit (packages/scikit-learn/examples/plot_bias_variance.py)

00:01.391

0.0

Measuring Decision Tree performance (packages/scikit-learn/examples/plot_measuring_performance.py)

00:01.300

0.0

Alternating optimization (advanced/mathematical_optimization/examples/plot_exercise_ill_conditioned.py)

00:01.296

0.0

tSNE to visualize digits (packages/scikit-learn/examples/plot_tsne.py)

00:01.216

0.0

Plot geometrical transformations on images (intro/scipy/examples/plot_image_transform.py)

00:00.975

0.0

Locators for tick on axis (intro/matplotlib/examples/options/plot_ticks.py)

00:00.923

0.0

Nearest-neighbor prediction on iris (packages/scikit-learn/examples/plot_iris_knn.py)

00:00.795

0.0

Image denoising by FFT (intro/scipy/examples/solutions/plot_fft_image_denoise.py)

00:00.782

0.0

Segmentation with Gaussian mixture models (advanced/image_processing/examples/plot_GMM.py)

00:00.780

0.0

Demo text printing (intro/matplotlib/examples/plot_text.py)

00:00.730

0.0

Text printing decorated (intro/matplotlib/examples/pretty_plots/plot_text_ext.py)

00:00.714

0.0

Plotting the comparison of optimizers (advanced/mathematical_optimization/examples/plot_compare_optimizers.py)

00:00.569

0.0

Plotting simple quantities of a pandas dataframe (packages/statistics/examples/plot_pandas.py)

00:00.536

0.0

Displaying a Raccoon Face (advanced/image_processing/examples/plot_face.py)

00:00.533

0.0

Test for an education/gender interaction in wages (packages/statistics/examples/plot_wage_education_gender.py)

00:00.520

0.0

Geometrical transformations (advanced/image_processing/examples/plot_geom_face.py)

00:00.468

0.0

Plot filtering on images (intro/scipy/examples/plot_image_filters.py)

00:00.458

0.0

Analysis of Iris petal and sepal sizes (packages/statistics/examples/plot_iris_analysis.py)

00:00.427

0.0

Image sharpening (advanced/image_processing/examples/plot_sharpen.py)

00:00.419

0.0

Use the RidgeCV and LassoCV to set the regularization parameter (packages/scikit-learn/examples/plot_linear_model_cv.py)

00:00.391

0.0

Spectrogram, power spectral density (intro/scipy/examples/plot_spectrogram.py)

00:00.350

0.0

Display a Raccoon Face (advanced/image_processing/examples/plot_display_face.py)

00:00.341

0.0

Optimization of a two-parameter function (intro/scipy/examples/plot_2d_minimization.py)

00:00.324

0.0

Simple image blur by convolution with a Gaussian kernel (intro/scipy/examples/solutions/plot_image_blur.py)

00:00.321

0.0

The lidar system, data and fit (1 of 2 datasets) (intro/scipy/summary-exercises/examples/plot_optimize_lidar_data_fit.py)

00:00.296

0.0

Blurring of images (advanced/image_processing/examples/plot_blur.py)

00:00.282

0.0

Compare classifiers on the digits data (packages/scikit-learn/examples/plot_compare_classifiers.py)

00:00.258

0.0

Reading and writing an elephant (intro/numpy/examples/plot_elephant.py)

00:00.256

0.0

Granulometry (advanced/image_processing/examples/plot_granulo.py)

00:00.250

0.0

Resample a signal with scipy.signal.resample (intro/scipy/examples/plot_resample.py)

00:00.246

0.0

The Gumbell distribution, results (intro/scipy/summary-exercises/examples/plot_sprog_annual_maxima.py)

00:00.240

0.0

Relating Gender and IQ (packages/statistics/examples/solutions/plot_brain_size.py)

00:00.236

0.0

Brent’s method (advanced/mathematical_optimization/examples/plot_1d_optim.py)

00:00.231

0.0

Total Variation denoising (advanced/image_processing/examples/plot_face_tv_denoise.py)

00:00.215

0.0

Tutorial Diagrams (packages/scikit-learn/examples/plot_ML_flow_chart.py)

00:00.214

0.0

Plotting and manipulating FFTs for filtering (intro/scipy/examples/plot_fftpack.py)

00:00.203

0.0

Finding edges with Sobel filters (advanced/image_processing/examples/plot_find_edges.py)

00:00.203

0.0

A demo of 1D interpolation (intro/scipy/examples/plot_interpolation.py)

00:00.202

0.0

Image denoising (advanced/image_processing/examples/plot_face_denoise.py)

00:00.201

0.0

Plot the block mean of an image (advanced/image_processing/examples/plot_block_mean.py)

00:00.190

0.0

Segmentation with spectral clustering (advanced/image_processing/examples/plot_spectral_clustering.py)

00:00.182

0.0

Radial mean (advanced/image_processing/examples/plot_radial_mean.py)

00:00.176

0.0

Plot fitting a 9th order polynomial (packages/scikit-learn/examples/plot_polynomial_regression.py)

00:00.175

0.0

Watershed and random walker for segmentation (packages/scikit-image/examples/plot_segmentations.py)

00:00.164

0.0

Image manipulation and NumPy arrays (advanced/image_processing/examples/plot_numpy_array.py)

00:00.162

0.0

Image interpolation (advanced/image_processing/examples/plot_interpolation_face.py)

00:00.157

0.0

Various denoising filters (packages/scikit-image/examples/plot_filter_coins.py)

00:00.154

0.0

Crude periodicity finding (intro/scipy/examples/solutions/plot_periodicity_finder.py)

00:00.141

0.0

Denoising an image with the median filter (advanced/image_processing/examples/plot_denoising.py)

00:00.131

0.0

Imshow elaborate (intro/matplotlib/examples/plot_imshow.py)

00:00.122

0.0

Finding a minimum in a flat neighborhood (advanced/mathematical_optimization/examples/plot_exercise_flat_minimum.py)

00:00.117

0.0

Integers can overflow (packages/scikit-image/examples/plot_camera_uint.py)

00:00.116

0.0

Otsu thresholding (packages/scikit-image/examples/plot_threshold.py)

00:00.116

0.0

Demo connected components (intro/scipy/examples/plot_connect_measurements.py)

00:00.114

0.0

Curve fitting (intro/scipy/examples/plot_curve_fit.py)

00:00.114

0.0

Histogram segmentation (advanced/image_processing/examples/plot_histo_segmentation.py)

00:00.110

0.0

Plotting in polar, decorated (intro/matplotlib/examples/pretty_plots/plot_polar_ext.py)

00:00.110

0.0

Curve fitting: temperature as a function of month of the year (intro/scipy/examples/solutions/plot_curvefit_temperature_data.py)

00:00.108

0.0

Grid elaborate (intro/matplotlib/examples/pretty_plots/plot_grid_ext.py)

00:00.107

0.0

Plot variance and regularization in linear models (packages/scikit-learn/examples/plot_variance_linear_regr.py)

00:00.107

0.0

Simple Regression (packages/statistics/examples/plot_regression.py)

00:00.107

0.0

3D plotting (intro/matplotlib/examples/plot_plot3d.py)

00:00.106

0.0

Grid (intro/matplotlib/examples/plot_grid.py)

00:00.106

0.0

Exercise 9 (intro/matplotlib/examples/exercises/plot_exercise_9.py)

00:00.104

0.0

Comparing 2 sets of samples from Gaussians (intro/scipy/examples/plot_t_test.py)

00:00.104

0.0

Exercise (intro/matplotlib/examples/exercises/plot_exercise_10.py)

00:00.102

0.0

Normal distribution: histogram and PDF (intro/scipy/examples/plot_normal_distribution.py)

00:00.101

0.0

Segmentation contours (packages/scikit-image/examples/plot_boundaries.py)

00:00.099

0.0

Computing horizontal gradients with the Sobel filter (packages/scikit-image/examples/plot_sobel.py)

00:00.099

0.0

Demo PCA in 2D (packages/scikit-learn/examples/plot_pca.py)

00:00.099

0.0

Demo mathematical morphology (intro/scipy/examples/plot_mathematical_morpho.py)

00:00.098

0.0

Plotting in polar coordinates (intro/matplotlib/examples/plot_polar.py)

00:00.096

0.0

Fitting in Chebyshev basis (intro/numpy/examples/plot_chebyfit.py)

00:00.095

0.0

Multiple Regression (packages/statistics/examples/plot_regression_3d.py)

00:00.093

0.0

Plot 2D views of the iris dataset (packages/scikit-learn/examples/plot_iris_scatter.py)

00:00.093

0.0

Equalizing the histogram of an image (packages/scikit-image/examples/plot_equalize_hist.py)

00:00.089

0.0

Constraint optimization: visualizing the geometry (advanced/mathematical_optimization/examples/plot_constraints.py)

00:00.089

0.0

Cleaning segmentation with mathematical morphology (advanced/image_processing/examples/plot_clean_morpho.py)

00:00.087

0.0

A simple plotting example (intro/matplotlib/examples/plot_bad.py)

00:00.086

0.0

GridSpec (intro/matplotlib/examples/plot_gridspec.py)

00:00.086

0.0

The lidar system, data (2 of 2 datasets) (intro/scipy/summary-exercises/examples/plot_optimize_lidar_complex_data.py)

00:00.082

0.0

Multiple plots vignette (intro/matplotlib/examples/pretty_plots/plot_multiplot_ext.py)

00:00.081

0.0

Synthetic data (advanced/image_processing/examples/plot_synthetic_data.py)

00:00.081

0.0

Display the contours of a function (intro/matplotlib/examples/pretty_plots/plot_contour_ext.py)

00:00.080

0.0

Integrating a simple ODE (intro/scipy/examples/plot_solve_ivp_simple.py)

00:00.080

0.0

Displaying the contours of a function (intro/matplotlib/examples/plot_contour.py)

00:00.079

0.0

Mandelbrot set (intro/numpy/examples/plot_mandelbrot.py)

00:00.079

0.0

Random walk exercise (intro/numpy/examples/plot_randomwalk.py)

00:00.077

0.0

The lidar system, data and fit (2 of 2 datasets) (intro/scipy/summary-exercises/examples/plot_optimize_lidar_complex_data_fit.py)

00:00.077

0.0

Cumulative wind speed prediction (intro/scipy/summary-exercises/examples/plot_cumulative_wind_speed_prediction.py)

00:00.077

0.0

2D plotting (intro/numpy/examples/plot_basic2dplot.py)

00:00.075

0.0

Labelling connected components of an image (packages/scikit-image/examples/plot_labels.py)

00:00.074

0.0

Markers (intro/matplotlib/examples/options/plot_markers.py)

00:00.073

0.0

Displaying a simple image (packages/scikit-image/examples/plot_camera.py)

00:00.073

0.0

Subplot grid (intro/matplotlib/examples/plot_subplot-grid.py)

00:00.072

0.0

Boxplots and paired differences (packages/statistics/examples/plot_paired_boxplots.py)

00:00.072

0.0

Minima and roots of a function (intro/scipy/examples/plot_optimize_example2.py)

00:00.070

0.0

Distances exercise (intro/numpy/examples/plot_distances.py)

00:00.069

0.0

Example of linear and non-linear models (packages/scikit-learn/examples/plot_svm_non_linear.py)

00:00.068

0.0

The Gumbell distribution (intro/scipy/summary-exercises/examples/plot_gumbell_wind_speed_prediction.py)

00:00.068

0.0

The lidar system, data (1 of 2 datasets) (intro/scipy/summary-exercises/examples/plot_optimize_lidar_data.py)

00:00.066

0.0

Watershed segmentation (advanced/image_processing/examples/plot_watershed_segmentation.py)

00:00.064

0.0

Population exercise (intro/numpy/examples/plot_populations.py)

00:00.063

0.0

Plot scatter decorated (intro/matplotlib/examples/pretty_plots/plot_scatter_ext.py)

00:00.062

0.0

Example: Masked statistics (advanced/advanced_numpy/examples/plots/plot_maskedstats.py)

00:00.062

0.0

Exercise 8 (intro/matplotlib/examples/exercises/plot_exercise_8.py)

00:00.061

0.0

Greyscale dilation (advanced/image_processing/examples/plot_greyscale_dilation.py)

00:00.060

0.0

Plotting a scatter of points (intro/matplotlib/examples/plot_scatter.py)

00:00.060

0.0

Creating an image (packages/scikit-image/examples/plot_check.py)

00:00.059

0.0

Pie chart (intro/matplotlib/examples/plot_pie.py)

00:00.059

0.0

Exercise 1 (intro/matplotlib/examples/exercises/plot_exercise_1.py)

00:00.059

0.0

Pie chart vignette (intro/matplotlib/examples/pretty_plots/plot_pie_ext.py)

00:00.058

0.0

Axes (intro/matplotlib/examples/plot_axes-2.py)

00:00.058

0.0

Exercise 4 (intro/matplotlib/examples/exercises/plot_exercise_4.py)

00:00.056

0.0

Bar plots (intro/matplotlib/examples/plot_bar.py)

00:00.056

0.0

Exercise 7 (intro/matplotlib/examples/exercises/plot_exercise_7.py)

00:00.055

0.0

Detrending a signal (intro/scipy/examples/plot_detrend.py)

00:00.055

0.0

A simple, good-looking plot (intro/matplotlib/examples/plot_good.py)

00:00.053

0.0

3D plotting (intro/matplotlib/examples/plot_plot3d-2.py)

00:00.053

0.0

Curve fitting (advanced/mathematical_optimization/examples/plot_curve_fitting.py)

00:00.053

0.0

Integrate the Damped spring-mass oscillator (intro/scipy/examples/plot_solve_ivp_damped_spring_mass.py)

00:00.052

0.0

A simple example (guide/examples/plot_simple.py)

00:00.052

0.0

Simple picture of the formal problem of machine learning (packages/scikit-learn/examples/plot_separator.py)

00:00.051

0.0

Exercise 2 (intro/matplotlib/examples/exercises/plot_exercise_2.py)

00:00.051

0.0

Plotting quiver decorated (intro/matplotlib/examples/pretty_plots/plot_quiver_ext.py)

00:00.051

0.0

Bar plot advanced (intro/matplotlib/examples/pretty_plots/plot_bar_ext.py)

00:00.051

0.0

Horizontal arrangement of subplots (intro/matplotlib/examples/plot_subplot-horizontal.py)

00:00.050

0.0

1D plotting (intro/numpy/examples/plot_basic1dplot.py)

00:00.049

0.0

Exercise 6 (intro/matplotlib/examples/exercises/plot_exercise_6.py)

00:00.049

0.0

Optimization with constraints (advanced/mathematical_optimization/examples/plot_non_bounds_constraints.py)

00:00.049

0.0

Subplots (intro/matplotlib/examples/plot_multiplot.py)

00:00.049

0.0

Simple axes example (intro/matplotlib/examples/plot_axes.py)

00:00.048

0.0

Finding the minimum of a smooth function (intro/scipy/examples/plot_optimize_example1.py)

00:00.048

0.0

Fitting to polynomial (intro/numpy/examples/plot_polyfit.py)

00:00.048

0.0

Exercise 3 (intro/matplotlib/examples/exercises/plot_exercise_3.py)

00:00.048

0.0

A simple linear regression (packages/scikit-learn/examples/plot_linear_regression.py)

00:00.047

0.0

Convex function (advanced/mathematical_optimization/examples/plot_convex.py)

00:00.047

0.0

Opening, erosion, and propagation (advanced/image_processing/examples/plot_propagation.py)

00:00.045

0.0

Linestyles (intro/matplotlib/examples/options/plot_linestyles.py)

00:00.044

0.0

Measurements from images (advanced/image_processing/examples/plot_measure_data.py)

00:00.044

0.0

Boxplot with matplotlib (intro/matplotlib/examples/pretty_plots/plot_boxplot_ext.py)

00:00.044

0.0

Subplot plot arrangement vertical (intro/matplotlib/examples/plot_subplot-vertical.py)

00:00.041

0.0

Smooth vs non-smooth (advanced/mathematical_optimization/examples/plot_smooth.py)

00:00.041

0.0

Imshow demo (intro/matplotlib/examples/pretty_plots/plot_imshow_ext.py)

00:00.040

0.0

Exercise 5 (intro/matplotlib/examples/exercises/plot_exercise_5.py)

00:00.039

0.0

3D plotting vignette (intro/matplotlib/examples/pretty_plots/plot_plot3d_ext.py)

00:00.038

0.0

A example of plotting not quite right (intro/matplotlib/examples/plot_ugly.py)

00:00.036

0.0

Plotting a vector field: quiver (intro/matplotlib/examples/plot_quiver.py)

00:00.034

0.0

Plot and filled plots (intro/matplotlib/examples/plot_plot.py)

00:00.033

0.0

Plot example vignette (intro/matplotlib/examples/pretty_plots/plot_plot_ext.py)

00:00.031

0.0

Find the bounding box of an object (advanced/image_processing/examples/plot_find_object.py)

00:00.020

0.0

Linewidth (intro/matplotlib/examples/options/plot_linewidth.py)

00:00.020

0.0

Alpha: transparency (intro/matplotlib/examples/options/plot_alpha.py)

00:00.019

0.0

The colors matplotlib line plots (intro/matplotlib/examples/options/plot_color.py)

00:00.018

0.0

Marker edge color (intro/matplotlib/examples/options/plot_mec.py)

00:00.017

0.0

Noisy optimization problem (advanced/mathematical_optimization/examples/plot_noisy.py)

00:00.017

0.0

Marker face color (intro/matplotlib/examples/options/plot_mfc.py)

00:00.017

0.0

Marker size (intro/matplotlib/examples/options/plot_ms.py)

00:00.017

0.0

Marker edge width (intro/matplotlib/examples/options/plot_mew.py)

00:00.017

0.0

Solid joint style (intro/matplotlib/examples/options/plot_solid_joinstyle.py)

00:00.014

0.0

Dash join style (intro/matplotlib/examples/options/plot_dash_joinstyle.py)

00:00.014

0.0

Dash capstyle (intro/matplotlib/examples/options/plot_dash_capstyle.py)

00:00.014

0.0

Solid cap style (intro/matplotlib/examples/options/plot_solid_capstyle.py)

00:00.013

0.0

Aliased versus anti-aliased (intro/matplotlib/examples/options/plot_antialiased.py)

00:00.013

0.0

Aliased versus anti-aliased (intro/matplotlib/examples/options/plot_aliased.py)

00:00.012

0.0

+
+

+
+ + +
+
+
+
+ +
+
+ + + + \ No newline at end of file