├── .circleci └── config.yml ├── .git-blame-ignore-revs ├── .github ├── dependabot.yml └── workflows │ ├── circleci.yml │ ├── lint.yml │ ├── pages.yml │ └── test.yml ├── .gitignore ├── .mailmap ├── .pre-commit-config.yaml ├── AUTHORS.rst ├── CHANGES.rst ├── CONTRIBUTING.rst ├── LICENSE.rst ├── Makefile ├── PRESENTING.txt ├── README.rst ├── about.rst ├── advanced ├── advanced_numpy │ ├── cpu-cacheline.png │ ├── cpu-cacheline.svg │ ├── examples │ │ ├── Makefile │ │ ├── README.txt │ │ ├── mandel-answer.pyx │ │ ├── mandel.pyx │ │ ├── mandelplot.py │ │ ├── myobject-answer.c │ │ ├── myobject.c │ │ ├── myobject_test.py │ │ ├── pilbuffer-answer.py │ │ ├── pilbuffer.py │ │ ├── plots │ │ │ ├── README.txt │ │ │ └── plot_maskedstats.py │ │ ├── setup.py │ │ ├── setup_myobject.py │ │ ├── stride-diagonals-answer.py │ │ ├── stride-diagonals.py │ │ ├── stride-fakedims.py │ │ ├── test.png │ │ ├── view-colors.py │ │ └── wavreader.py │ ├── index.rst │ ├── mandelbrot.png │ ├── test.png │ ├── test2.png │ └── threefundamental.png ├── advanced_python │ └── index.rst ├── debugging │ ├── debug_file.py │ ├── gdbinit │ ├── index.rst │ ├── index_error.py │ ├── segfault.py │ ├── to_debug.py │ ├── to_debug_solution.py │ ├── vim_pyflakes.png │ ├── vim_syntastic.png │ └── wiener_filtering.py ├── image_processing │ ├── axis_convention.png │ ├── coins.png │ ├── diamond_kernel.png │ ├── examples │ │ ├── README.txt │ │ ├── plot_GMM.py │ │ ├── plot_block_mean.py │ │ ├── plot_blur.py │ │ ├── plot_clean_morpho.py │ │ ├── plot_denoising.py │ │ ├── plot_display_face.py │ │ ├── plot_face.py │ │ ├── plot_face_denoise.py │ │ ├── plot_face_tv_denoise.py │ │ ├── plot_find_edges.py │ │ ├── plot_find_object.py │ │ ├── plot_geom_face.py │ │ ├── plot_granulo.py │ │ ├── plot_greyscale_dilation.py │ │ ├── plot_histo_segmentation.py │ │ ├── plot_interpolation_face.py │ │ ├── plot_measure_data.py │ │ ├── plot_numpy_array.py │ │ ├── plot_propagation.py │ │ ├── plot_radial_mean.py │ │ ├── plot_sharpen.py │ │ ├── plot_spectral_clustering.py │ │ ├── plot_synthetic_data.py │ │ └── plot_watershed_segmentation.py │ ├── image_GMM.png │ ├── image_spectral_clustering.png │ ├── index.rst │ ├── kernels.png │ ├── morpho_mat.png │ └── scikit_image_logo.png ├── index.rst ├── interfacing_with_c │ ├── ctypes │ │ └── cos_module.py │ ├── ctypes_numpy │ │ ├── cos_doubles.c │ │ ├── cos_doubles.h │ │ ├── cos_doubles.py │ │ ├── makefile │ │ ├── test_cos_doubles.png │ │ └── test_cos_doubles.py │ ├── cython │ │ ├── cos_module.pyx │ │ └── setup.py │ ├── cython_numpy │ │ ├── _cos_doubles.pyx │ │ ├── cos_doubles.c │ │ ├── cos_doubles.h │ │ ├── setup.py │ │ ├── test_cos_doubles.png │ │ └── test_cos_doubles.py │ ├── cython_simple │ │ ├── cos_module.pyx │ │ └── setup.py │ ├── interfacing_with_c.rst │ ├── numpy_c_api │ │ ├── cos_module_np.c │ │ ├── setup.py │ │ ├── test_cos_module_np.png │ │ └── test_cos_module_np.py │ ├── numpy_shared │ │ ├── cos_doubles.c │ │ ├── cos_doubles.h │ │ ├── test_cos_doubles.png │ │ └── test_cos_doubles.py │ ├── python_c_api │ │ ├── cos_module.c │ │ └── setup.py │ ├── swig │ │ ├── cos_module.c │ │ ├── cos_module.h │ │ ├── cos_module.i │ │ └── setup.py │ └── swig_numpy │ │ ├── cos_doubles.c │ │ ├── cos_doubles.h │ │ ├── cos_doubles.i │ │ ├── numpy.i │ │ ├── setup.py │ │ ├── test_cos_doubles.png │ │ └── test_cos_doubles.py ├── mathematical_optimization │ ├── examples │ │ ├── README.txt │ │ ├── helper │ │ │ ├── compare_optimizers.py │ │ │ ├── compare_optimizers_py2.pkl │ │ │ ├── compare_optimizers_py3.pkl │ │ │ └── cost_functions.py │ │ ├── plot_1d_optim.py │ │ ├── plot_compare_optimizers.py │ │ ├── plot_constraints.py │ │ ├── plot_convex.py │ │ ├── plot_curve_fitting.py │ │ ├── plot_exercise_flat_minimum.py │ │ ├── plot_exercise_ill_conditioned.py │ │ ├── plot_gradient_descent.py │ │ ├── plot_noisy.py │ │ ├── plot_non_bounds_constraints.py │ │ └── plot_smooth.py │ └── index.rst ├── optimizing │ ├── demo-prof.png │ ├── demo.py │ ├── demo_opt.py │ ├── ica.py │ └── index.rst └── scipy_sparse │ ├── bsr_array.rst │ ├── coo_array.rst │ ├── csc_array.rst │ ├── csr_array.rst │ ├── dia_array.rst │ ├── dok_array.rst │ ├── examples │ ├── README.txt │ ├── direct_solve.py │ ├── lobpcg_sakurai.py │ └── pyamg_with_lobpcg.py │ ├── figures │ ├── graph.png │ ├── graph_g.png │ ├── graph_rcm.png │ └── lobpcg_eigenvalues.png │ ├── index.rst │ ├── introduction.rst │ ├── lil_array.rst │ ├── other_packages.rst │ ├── solvers.rst │ └── storage_schemes.rst ├── conf.py ├── data ├── LICENCE.txt ├── MV_HFV_012.jpg ├── elephant.png ├── moonlanding.png ├── organisms.txt ├── populations.txt ├── species.txt ├── test.wav ├── waveform_1.npy ├── waveform_2.npy └── women_percentage.txt ├── docutils.conf ├── guide ├── examples │ ├── README.txt │ └── plot_simple.py └── index.rst ├── images ├── cover-2020.pdf ├── cover-2025.pdf ├── cover-2025.svg ├── cover.pdf ├── favicon.ico ├── icon-archive.svg ├── icon-github.svg ├── icon-pdf.svg ├── logo.pdf ├── logo.svg ├── logo_small.svg └── no_image.png ├── includes ├── big_toc_css.rst └── bigger_toc_css.rst ├── index.rst ├── intro ├── help │ └── help.rst ├── index.rst ├── intro.rst ├── language │ ├── basic_types.rst │ ├── control_flow.rst │ ├── demo.py │ ├── demo2.py │ ├── exceptions.rst │ ├── first_steps.rst │ ├── functions.rst │ ├── io.rst │ ├── oop.rst │ ├── python-logo.png │ ├── python_language.rst │ ├── reusing_code.rst │ └── standard_library.rst ├── matplotlib │ ├── examples │ │ ├── README.txt │ │ ├── exercises │ │ │ ├── README.txt │ │ │ ├── plot_exercise_1.py │ │ │ ├── plot_exercise_10.py │ │ │ ├── plot_exercise_2.py │ │ │ ├── plot_exercise_3.py │ │ │ ├── plot_exercise_4.py │ │ │ ├── plot_exercise_5.py │ │ │ ├── plot_exercise_6.py │ │ │ ├── plot_exercise_7.py │ │ │ ├── plot_exercise_8.py │ │ │ └── plot_exercise_9.py │ │ ├── options │ │ │ ├── README.txt │ │ │ ├── plot_aliased.py │ │ │ ├── plot_alpha.py │ │ │ ├── plot_antialiased.py │ │ │ ├── plot_color.py │ │ │ ├── plot_colormaps.py │ │ │ ├── plot_dash_capstyle.py │ │ │ ├── plot_dash_joinstyle.py │ │ │ ├── plot_linestyles.py │ │ │ ├── plot_linewidth.py │ │ │ ├── plot_markers.py │ │ │ ├── plot_mec.py │ │ │ ├── plot_mew.py │ │ │ ├── plot_mfc.py │ │ │ ├── plot_ms.py │ │ │ ├── plot_solid_capstyle.py │ │ │ ├── plot_solid_joinstyle.py │ │ │ └── plot_ticks.py │ │ ├── plot_axes-2.py │ │ ├── plot_axes.py │ │ ├── plot_bad.py │ │ ├── plot_bar.py │ │ ├── plot_contour.py │ │ ├── plot_good.py │ │ ├── plot_grid.py │ │ ├── plot_gridspec.py │ │ ├── plot_imshow.py │ │ ├── plot_multiplot.py │ │ ├── plot_pie.py │ │ ├── plot_plot.py │ │ ├── plot_plot3d-2.py │ │ ├── plot_plot3d.py │ │ ├── plot_polar.py │ │ ├── plot_quiver.py │ │ ├── plot_scatter.py │ │ ├── plot_subplot-grid.py │ │ ├── plot_subplot-horizontal.py │ │ ├── plot_subplot-vertical.py │ │ ├── plot_text.py │ │ ├── plot_ugly.py │ │ └── pretty_plots │ │ │ ├── README.txt │ │ │ ├── plot_bar_ext.py │ │ │ ├── plot_boxplot_ext.py │ │ │ ├── plot_contour_ext.py │ │ │ ├── plot_grid_ext.py │ │ │ ├── plot_imshow_ext.py │ │ │ ├── plot_multiplot_ext.py │ │ │ ├── plot_pie_ext.py │ │ │ ├── plot_plot3d_ext.py │ │ │ ├── plot_plot_ext.py │ │ │ ├── plot_polar_ext.py │ │ │ ├── plot_quiver_ext.py │ │ │ ├── plot_scatter_ext.py │ │ │ └── plot_text_ext.py │ └── index.rst ├── numpy │ ├── advanced_operations.rst │ ├── array_object.rst │ ├── data │ ├── elaborate_arrays.rst │ ├── examples │ │ ├── README.txt │ │ ├── plot_basic1dplot.py │ │ ├── plot_basic2dplot.py │ │ ├── plot_chebyfit.py │ │ ├── plot_distances.py │ │ ├── plot_elephant.py │ │ ├── plot_mandelbrot.py │ │ ├── plot_polyfit.py │ │ ├── plot_populations.py │ │ └── plot_randomwalk.py │ ├── exercises.rst │ ├── gallery.rst │ ├── images │ │ ├── cpu-cacheline.png │ │ ├── cpu-cacheline.svg │ │ ├── faces.png │ │ ├── markov-chain.png │ │ ├── markov-chain.svg │ │ ├── numpy_broadcasting.png │ │ ├── numpy_fancy_indexing.png │ │ ├── numpy_indexing.png │ │ ├── numpy_indexing.svg │ │ ├── prime-sieve.png │ │ ├── prime-sieve.svg │ │ ├── random_walk.png │ │ ├── random_walk_schema.png │ │ ├── reductions.png │ │ ├── reductions.svg │ │ ├── route66.png │ │ ├── surf.png │ │ └── threefundamental.png │ ├── index.rst │ ├── operations.rst │ ├── random_walk.png │ ├── random_walk_schema.png │ └── solutions │ │ ├── 1_0_prime_sieve.py │ │ ├── 1_1_array_creation.py │ │ ├── 1_2_text_data.py │ │ ├── 1_3_tiling.py │ │ ├── 2_1_matrix_manipulations.py │ │ ├── 2_2_data_statistics.py │ │ ├── 2_3_crude_integration.py │ │ ├── 2_4_mandelbrot.py │ │ ├── 2_5_markov_chain.py │ │ ├── 2_a_call_fortran.py │ │ └── 2_a_fortran_module.f90 └── scipy │ ├── examples │ ├── README.txt │ ├── plot_2d_minimization.py │ ├── plot_connect_measurements.py │ ├── plot_curve_fit.py │ ├── plot_detrend.py │ ├── plot_fftpack.py │ ├── plot_image_filters.py │ ├── plot_image_transform.py │ ├── plot_interpolation.py │ ├── plot_mathematical_morpho.py │ ├── plot_normal_distribution.py │ ├── plot_optimize_example1.py │ ├── plot_optimize_example2.py │ ├── plot_resample.py │ ├── plot_solve_ivp_damped_spring_mass.py │ ├── plot_solve_ivp_simple.py │ ├── plot_spectrogram.py │ ├── plot_t_test.py │ └── solutions │ │ ├── README.txt │ │ ├── plot_curvefit_temperature_data.py │ │ ├── plot_fft_image_denoise.py │ │ ├── plot_image_blur.py │ │ └── plot_periodicity_finder.py │ ├── image_processing │ ├── MV_HFV_012.jpg │ ├── exo_histos.png │ ├── image_processing.rst │ ├── morpho_mat.png │ ├── sands.png │ └── three_phases.png │ ├── index.rst │ ├── solutions.rst │ ├── solutions │ ├── data.txt │ ├── data_file.py │ ├── dir_sort.py │ ├── path_site.py │ ├── pi_wallis.py │ ├── quick_sort.py │ └── test_dir_sort.py │ └── summary-exercises │ ├── README.txt │ ├── answers_image_processing.rst │ ├── examples │ ├── README.txt │ ├── max-speeds.npy │ ├── plot_cumulative_wind_speed_prediction.py │ ├── plot_gumbell_wind_speed_prediction.py │ ├── plot_optimize_lidar_complex_data.py │ ├── plot_optimize_lidar_complex_data_fit.py │ ├── plot_optimize_lidar_data.py │ ├── plot_optimize_lidar_data_fit.py │ ├── plot_sprog_annual_maxima.py │ ├── sprog-windspeeds.npy │ ├── waveform_1.npy │ └── waveform_2.npy │ ├── image-processing.rst │ ├── optimize-fit.rst │ └── stats-interpolate.rst ├── matplotlibrc ├── misc └── yeahconsole ├── packages ├── index.rst ├── scikit-image │ ├── examples │ │ ├── README.txt │ │ ├── plot_boundaries.py │ │ ├── plot_camera.py │ │ ├── plot_camera_uint.py │ │ ├── plot_check.py │ │ ├── plot_equalize_hist.py │ │ ├── plot_features.py │ │ ├── plot_filter_coins.py │ │ ├── plot_labels.py │ │ ├── plot_segmentations.py │ │ ├── plot_sobel.py │ │ └── plot_threshold.py │ ├── index.rst │ └── viewer.png ├── scikit-learn │ ├── examples │ │ ├── README.txt │ │ ├── plot_ML_flow_chart.py │ │ ├── plot_bias_variance.py │ │ ├── plot_california_prediction.py │ │ ├── plot_compare_classifiers.py │ │ ├── plot_digits_simple_classif.py │ │ ├── plot_eigenfaces.py │ │ ├── plot_iris_knn.py │ │ ├── plot_iris_scatter.py │ │ ├── plot_linear_model_cv.py │ │ ├── plot_linear_regression.py │ │ ├── plot_measuring_performance.py │ │ ├── plot_pca.py │ │ ├── plot_polynomial_regression.py │ │ ├── plot_separator.py │ │ ├── plot_svm_non_linear.py │ │ ├── plot_tsne.py │ │ └── plot_variance_linear_regr.py │ ├── images │ │ ├── Virginia_Iris.png │ │ ├── iris_setosa.jpg │ │ ├── iris_versicolor.jpg │ │ ├── iris_virginica.jpg │ │ └── scikit-learn-logo.png │ └── index.rst ├── statistics │ ├── examples │ │ ├── README.txt │ │ ├── airfares.txt │ │ ├── brain_size.csv │ │ ├── iris.csv │ │ ├── plot_airfare.py │ │ ├── plot_iris_analysis.py │ │ ├── plot_paired_boxplots.py │ │ ├── plot_pandas.py │ │ ├── plot_regression.py │ │ ├── plot_regression_3d.py │ │ ├── plot_wage_data.py │ │ ├── plot_wage_education_gender.py │ │ ├── solutions │ │ │ ├── README.txt │ │ │ └── plot_brain_size.py │ │ └── wages.txt │ ├── index.rst │ └── two_sided.png └── sympy.rst ├── preface.rst ├── pyproject.toml ├── pyximages ├── README.md ├── numpy_fancy_indexing.pdf ├── numpy_fancy_indexing.png ├── numpy_fancy_indexing.py ├── numpy_indexing.pdf ├── numpy_indexing.png └── numpy_indexing.py ├── requirements.txt └── themes ├── plusBox.png └── scientific_python_lectures ├── layout.html ├── static ├── foldable_toc.css ├── foldable_toc.js ├── nature.css_t └── scroll_highlight_toc.js └── theme.conf /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | 3 | jobs: 4 | build: 5 | docker: 6 | - image: cimg/python:3.12 7 | 8 | steps: 9 | - checkout 10 | 11 | - run: 12 | name: Install TeX 13 | command: | 14 | sudo apt update 15 | sudo apt install -y \ 16 | dvipng \ 17 | latexmk \ 18 | texlive-latex-extra \ 19 | texlive-fonts-extra \ 20 | texlive-extra-utils 21 | 22 | - restore_cache: 23 | keys: 24 | - pip-cache-v1 25 | 26 | - run: 27 | name: Install Python dependencies 28 | command: | 29 | pip install --upgrade --user pip 30 | pip install --user -r requirements.txt 31 | pip list 32 | 33 | - save_cache: 34 | key: pip-cache-v1 35 | paths: 36 | - ~/.cache/pip 37 | 38 | - run: 39 | name: Build docs 40 | command: | 41 | # NOTE: bad interaction w/ blas multithreading on circleci 42 | export OMP_NUM_THREADS=1 43 | make pdf 44 | make html # FIX: check that failing examples produce failure 45 | cp \ 46 | ScientificPythonLectures.pdf \ 47 | ScientificPythonLectures-simple.pdf \ 48 | build/html/_downloads/ 49 | 50 | - store_artifacts: 51 | path: build/html 52 | -------------------------------------------------------------------------------- /.git-blame-ignore-revs: -------------------------------------------------------------------------------- 1 | bb473f6ff4a23e4fd5205eacdef713db15decadf 2 | 884e2507e482b1ffb471dfa52ee36be8be6f9e35 3 | 87566f51031ddd54e2f3020bb62d7bf85289e408 4 | 7cb7b365c51ab20d92745e5eefb95690e3ba2e14 5 | 67c4efab4e3ec1dc16c18b9ab8c5cd5f375040e0 6 | 8d00b416689c428b2bafdaad61ed3ec660ca06c2 7 | d6b447cab8c40aa47dc675a0f4349ae254e8b3ce 8 | d8966d848af75751823e825eb76c5bbff58f5c07 9 | 4902d468c9606836b26b393379df4f49208ea847 10 | 1fd0ce6759be32be38bbfab32e83d157a82dfe25 11 | 406488494019fb199474fea7f1694e9f0d0347bc 12 | 968df447681ba7d33c9088d4446b8a92ec0a1389 13 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "github-actions" 4 | directory: "/" 5 | schedule: 6 | interval: "monthly" 7 | groups: 8 | actions: 9 | patterns: 10 | - "*" 11 | - package-ecosystem: "pip" 12 | directory: "/" 13 | schedule: 14 | interval: "monthly" 15 | groups: 16 | actions: 17 | patterns: 18 | - "*" 19 | -------------------------------------------------------------------------------- /.github/workflows/circleci.yml: -------------------------------------------------------------------------------- 1 | name: circleci 2 | 3 | on: [status] 4 | jobs: 5 | documentation: 6 | runs-on: ubuntu-latest 7 | name: Run CircleCI documentation artifact redirector 8 | steps: 9 | - name: GitHub Action step 10 | uses: scientific-python/circleci-artifacts-redirector-action@4e13a10d89177f4bfc8007a7064bdbeda848d8d1 # v1.0.0 11 | with: 12 | repo-token: ${{ secrets.GITHUB_TOKEN }} 13 | api-token: ${{ secrets.CIRCLECI_TOKEN }} 14 | artifact-path: 0/build/html/index.html 15 | circleci-jobs: build 16 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: style 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | 11 | jobs: 12 | pre-commit: 13 | name: Lint 14 | runs-on: ubuntu-latest 15 | strategy: 16 | matrix: 17 | python-version: ["3.12"] 18 | 19 | steps: 20 | - uses: actions/checkout@v4 21 | 22 | - name: Set up Python ${{ matrix.python-version }} 23 | uses: actions/setup-python@v5 24 | with: 25 | python-version: ${{ matrix.python-version }} 26 | 27 | - name: Install packages 28 | run: | 29 | pip install --upgrade pip wheel setuptools 30 | pip install -r requirements.txt 31 | pip list 32 | 33 | - name: Lint 34 | run: pre-commit run --all-files --show-diff-on-failure --color always 35 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: test 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | 11 | concurrency: 12 | group: ${{ github.workflow }}-${{ github.ref }} 13 | cancel-in-progress: true 14 | 15 | jobs: 16 | default: 17 | runs-on: ${{ matrix.os }}-latest 18 | strategy: 19 | matrix: 20 | os: [ubuntu, macos] 21 | python-version: ["3.11", "3.12", "3.13"] 22 | steps: 23 | - uses: actions/checkout@v4 24 | - name: Set up Python ${{ matrix.python-version }} 25 | uses: actions/setup-python@v5 26 | with: 27 | python-version: ${{ matrix.python-version }} 28 | 29 | - name: Install packages 30 | run: | 31 | python -m pip install --upgrade pip wheel setuptools 32 | python -m pip install -r requirements.txt 33 | python -m pip list 34 | 35 | - name: Test lectures 36 | run: make test 37 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | \#* 2 | *.pyc 3 | *~ 4 | *.swp 5 | *.so 6 | *.bak 7 | build 8 | _build 9 | /euroscipy2010_tutorials/source/advanced_numpy/examples/mandel.c 10 | PythonScientific-simple.pdf 11 | PythonScientific.pdf 12 | */auto_examples 13 | */*/auto_examples 14 | */*/*/auto_examples 15 | advanced/image_processing/examples/face.png 16 | .cache 17 | .pytest_cache 18 | data/test.png 19 | face.png 20 | face.raw 21 | file.mat 22 | fname.png 23 | local_logo.png 24 | mandelbrot.png 25 | output.txt 26 | output2.txt 27 | plot.png 28 | pop.npy 29 | pop2.txt 30 | random_00.png 31 | random_01.png 32 | random_02.png 33 | random_03.png 34 | random_04.png 35 | random_05.png 36 | random_06.png 37 | random_07.png 38 | random_08.png 39 | random_09.png 40 | red_elephant.png 41 | test.png 42 | tiny_elephant.png 43 | workfile 44 | airfares.txt 45 | wages.txt 46 | ScientificPythonLectures-simple.pdf 47 | ScientificPythonLectures.pdf 48 | -------------------------------------------------------------------------------- /.mailmap: -------------------------------------------------------------------------------- 1 | Gael Varoquaux 2 | Emmanuelle Gouillart 3 | Emmanuelle Gouillart 4 | Emmanuelle Gouillart 5 | Emmanuelle Gouillart 6 | Emmanuelle Gouillart 7 | Gert-Ludwig Ingold 8 | Lars Buitinck 9 | Maximilien Riehl 10 | Nicola Masarone 11 | Bartosz Telenczuk 12 | -------------------------------------------------------------------------------- /LICENSE.rst: -------------------------------------------------------------------------------- 1 | License 2 | ======== 3 | 4 | All code and material is licensed under a 5 | 6 | Creative Commons Attribution 4.0 International License (CC-by) 7 | 8 | https://creativecommons.org/licenses/by/4.0/ 9 | 10 | See the AUTHORS.rst file for a list of contributors. 11 | -------------------------------------------------------------------------------- /PRESENTING.txt: -------------------------------------------------------------------------------- 1 | 2 | Here is the way I (Gael) tend to present these course is to use the html 3 | output created by Sphinx and display it in a fullscreen browser. On top 4 | of that I use 'yeahconsole' to type in the examples (it stays nicely on 5 | top of the browser, in an area where everybody can see it, even in a 6 | crowded room). I use the accompanying shell script to start yeahconsole: 7 | it defines the right font size, and 'Ctr-Alt-Y' to show/hide the console. 8 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | .. image:: https://zenodo.org/badge/doi/10.5281/zenodo.594102.svg 2 | :target: https://dx.doi.org/10.5281/zenodo.594102 3 | 4 | .. image:: https://github.com/scipy-lectures/scientific-python-lectures/workflows/test/badge.svg?branch=main 5 | :target: https://github.com/scipy-lectures/scientific-python-lectures/actions?query=workflow%3A%22test%22 6 | 7 | ========================== 8 | Scientific Python Lectures 9 | ========================== 10 | 11 | This repository gathers some lectures on the scientific Python 12 | ecosystem that can be used for a full course of scientific computing with 13 | Python. 14 | 15 | These documents are written with the rest markup language (``.rst`` 16 | extension) and built using `Sphinx `_. 17 | 18 | You can view the online version at: https://lectures.scientific-python.org/ 19 | 20 | Reusing and distributing 21 | ------------------------- 22 | 23 | As stated in the ``LICENSE.rst`` file, this material comes with no strings 24 | attached. Feel free to reuse and modify for your own teaching purposes. 25 | 26 | However, we would like this reference material to be improved over time, 27 | thus we encourage people to contribute back changes. These will be 28 | reviewed and edited by the original authors and the editors. 29 | 30 | Building and contributing 31 | -------------------------- 32 | 33 | The file ``CONTRIBUTING.rst`` contains instructions to build from source 34 | and to contribute. 35 | -------------------------------------------------------------------------------- /about.rst: -------------------------------------------------------------------------------- 1 | .. only:: latex 2 | 3 | ==================================== 4 | About the Scientific Python Lectures 5 | ==================================== 6 | 7 | 8 | About the Scientific Python Lectures 9 | ==================================== 10 | 11 | Release: |release| 12 | 13 | The lectures are archived on zenodo: http://dx.doi.org/10.5281/zenodo.594102 14 | 15 | All code and material is licensed under a 16 | Creative Commons Attribution 4.0 International License (CC-by) 17 | http://creativecommons.org/licenses/by/4.0/ 18 | 19 | .. raw:: latex 20 | 21 | \begin{multicols}{2} 22 | 23 | .. toctree:: 24 | 25 | AUTHORS.rst 26 | 27 | .. raw:: latex 28 | 29 | \end{multicols} 30 | -------------------------------------------------------------------------------- /advanced/advanced_numpy/cpu-cacheline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/advanced_numpy/cpu-cacheline.png -------------------------------------------------------------------------------- /advanced/advanced_numpy/examples/Makefile: -------------------------------------------------------------------------------- 1 | dist: 2 | rm -f advnumpy-ex.zip 3 | zip advnumpy-ex.zip \ 4 | mandel.pyx mandel-answer.pyx test.wav wavreader.py \ 5 | mandelplot.py stride-diagonals.py stride-fakedims.py \ 6 | setup.py test.png pilbuffer.py pilbuffer-answer.py \ 7 | myobject.c myobject_test.py setup_myobject.py \ 8 | view-colors.py myobject-answer.c 9 | 10 | upload: dist 11 | suncomet scp advnumpy-ex.zip R:public_html/tmp/advnumpy-ex.zip 12 | -------------------------------------------------------------------------------- /advanced/advanced_numpy/examples/README.txt: -------------------------------------------------------------------------------- 1 | Examples for the advanced NumPy chapter 2 | ======================================= 3 | -------------------------------------------------------------------------------- /advanced/advanced_numpy/examples/mandelplot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plot Mandelbrot 3 | ================ 4 | 5 | Plot the Mandelbrot ensemble. 6 | 7 | """ 8 | 9 | import numpy as np 10 | import mandel 11 | 12 | x = np.linspace(-1.7, 0.6, 1000) 13 | y = np.linspace(-1.4, 1.4, 1000) 14 | c = x[None, :] + 1j * y[:, None] 15 | z = mandel.mandel(c, c) 16 | 17 | import matplotlib.pyplot as plt 18 | 19 | plt.imshow(abs(z) ** 2 < 1000, extent=[-1.7, 0.6, -1.4, 1.4]) 20 | plt.gray() 21 | plt.show() 22 | -------------------------------------------------------------------------------- /advanced/advanced_numpy/examples/myobject_test.py: -------------------------------------------------------------------------------- 1 | """ 2 | Importing the compiled module 3 | ============================== 4 | 5 | Playing with the module defined in myobject.c 6 | """ 7 | 8 | # 9 | # Compile myobject.c first with 10 | # 11 | # python3 setup_myobject.py build_ext -i 12 | # 13 | # If you are interested, play a bit with changing things in ``myobject.c`` 14 | # 15 | 16 | import myobject 17 | 18 | obj = myobject.MyObject() 19 | view = memoryview(obj) 20 | 21 | print("shape", view.shape) 22 | print("strides", view.strides) 23 | print("format", view.format) 24 | 25 | 26 | # 27 | # If you also have NumPy for Python 3 ... 28 | # 29 | 30 | import numpy as np 31 | 32 | x = np.asarray(obj) 33 | print(x) 34 | 35 | # this prints 36 | # 37 | # [[1 2] 38 | # [3 4]] 39 | -------------------------------------------------------------------------------- /advanced/advanced_numpy/examples/pilbuffer-answer.py: -------------------------------------------------------------------------------- 1 | """ 2 | From buffer 3 | ============ 4 | 5 | Show how to exchange data between numpy and a library that only knows 6 | the buffer interface. 7 | """ 8 | 9 | import numpy as np 10 | from PIL import Image 11 | 12 | # Let's make a sample image, RGBA format 13 | 14 | x = np.zeros((200, 200, 4), dtype=np.uint8) 15 | 16 | x[:, :, 0] = 255 # red 17 | x[:, :, 3] = 255 # opaque 18 | 19 | data = x.view(np.int32) # Check that you understand why this is OK! 20 | 21 | img = Image.frombuffer("RGBA", (200, 200), data) 22 | img.save("test.png") 23 | 24 | # Modify the original data, and save again. 25 | 26 | x[:, :, 1] = 255 27 | img.save("test2.png") 28 | -------------------------------------------------------------------------------- /advanced/advanced_numpy/examples/pilbuffer.py: -------------------------------------------------------------------------------- 1 | """ 2 | Exercise: using the buffer protocol 3 | =================================== 4 | 5 | Skeleton of the code to do an exercise using the buffer protocole. 6 | """ 7 | 8 | import numpy as np 9 | from PIL import Image 10 | 11 | # Let's make a sample image, RGBA format 12 | 13 | x = np.zeros((200, 200, 4), dtype=np.uint8) 14 | 15 | # TODO: fill `data` with fully opaque red [255, 0, 0, 255] 16 | 17 | # TODO: `x` is an array of bytes (8-bit integers) 18 | # What we need for PIL to understand this data is RGBA array, 19 | # where each element is a 32-bit integer, with bytes [RR,GG,BB,AA]. 20 | # How do we convert `x` to such an array, called `data`? 21 | 22 | data = ... 23 | 24 | img = Image.frombuffer("RGBA", (200, 200), data) 25 | img.save("test.png") 26 | 27 | # 28 | # Mini-exercise 29 | # 30 | # 1. Now, modify ``x`` and img.save() again. What happens? 31 | # 32 | -------------------------------------------------------------------------------- /advanced/advanced_numpy/examples/plots/README.txt: -------------------------------------------------------------------------------- 1 | Examples for the advanced NumPy chapter 2 | ======================================= 3 | -------------------------------------------------------------------------------- /advanced/advanced_numpy/examples/plots/plot_maskedstats.py: -------------------------------------------------------------------------------- 1 | """ 2 | Example: Masked statistics 3 | ========================== 4 | 5 | Plot a masked statistics 6 | 7 | """ 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | 12 | data = np.loadtxt("../../../../data/populations.txt") 13 | populations = np.ma.masked_array(data[:, 1:]) # type: ignore[var-annotated] 14 | year = data[:, 0] 15 | 16 | bad_years = ((year >= 1903) & (year <= 1910)) | ((year >= 1917) & (year <= 1918)) 17 | populations[bad_years, 0] = np.ma.masked 18 | populations[bad_years, 1] = np.ma.masked 19 | 20 | plt.plot(year, populations, "o-") 21 | plt.show() 22 | -------------------------------------------------------------------------------- /advanced/advanced_numpy/examples/setup.py: -------------------------------------------------------------------------------- 1 | """ 2 | Building the mandel C-Python extension 3 | ======================================= 4 | 5 | The "setup.py" script that builds the mandel.so extension from the 6 | C sources. 7 | """ 8 | 9 | from setuptools import setup, Extension 10 | from Cython.Build import cythonize 11 | import numpy 12 | 13 | extensions = [ 14 | Extension("mandel", sources=["mandel.pyx"], include_dirs=[numpy.get_include()]) 15 | ] 16 | 17 | setup(ext_modules=cythonize(extensions)) 18 | -------------------------------------------------------------------------------- /advanced/advanced_numpy/examples/setup_myobject.py: -------------------------------------------------------------------------------- 1 | """ 2 | Building the extension 3 | ======================= 4 | 5 | The script to build the extension 6 | 7 | """ 8 | 9 | from setuptools import setup, Extension 10 | 11 | setup( 12 | name="myobject", 13 | version="1.0", 14 | ext_modules=[Extension("myobject", ["myobject.c"])], 15 | ) 16 | -------------------------------------------------------------------------------- /advanced/advanced_numpy/examples/stride-diagonals.py: -------------------------------------------------------------------------------- 1 | """ 2 | Exercise: stride in diagonal 3 | ============================== 4 | 5 | A small striding exercise 6 | """ 7 | 8 | import numpy as np 9 | from numpy.lib.stride_tricks import as_strided 10 | 11 | # 12 | # Part 1 13 | # 14 | 15 | x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.int32) 16 | 17 | x_diag = as_strided(x, shape=(3,), strides=(TODO,)) 18 | x_supdiag = TODO 19 | x_subdiag = TODO 20 | 21 | # 22 | # Mini-exercise: (assume C memory order) 23 | # 24 | # 0. How to pick diagonal entries of the matrix 25 | # 26 | # 1. How to pick the super-diagonal entries [2, 6] 27 | # 28 | # 2. The sub-diagonal entries [4, 8] 29 | # 30 | # 99. Can you generalize this for any stride and shape combinations 31 | # in the initial array? 32 | # 33 | # If you can, tell me, and maybe numpy.trace can be made faster :) 34 | # 35 | 36 | 37 | # 38 | # Part 2 39 | # 40 | 41 | # Compute the tensor trace 42 | 43 | x = np.arange(5 * 5 * 5 * 5).reshape(5, 5, 5, 5) 44 | 45 | s = 0 46 | for i in range(5): 47 | for j in range(5): 48 | s += x[j, i, j, i] 49 | 50 | # by striding and using .sum() 51 | 52 | y = as_strided(x, shape=(5, 5), strides=(TODO, TODO)) 53 | s2 = ... 54 | 55 | assert s == s2 56 | -------------------------------------------------------------------------------- /advanced/advanced_numpy/examples/stride-fakedims.py: -------------------------------------------------------------------------------- 1 | """ 2 | Exercise: using strides to create fake dimensions 3 | ================================================== 4 | 5 | Use strides to create fake dimensions. 6 | 7 | """ 8 | 9 | import numpy as np 10 | from numpy.lib.stride_tricks import as_strided 11 | 12 | x = np.array([1, 2, 3, 4], dtype=np.int8) 13 | 14 | # 15 | # Mini-exercise: 16 | # 17 | # 1. How to create a new array that shares the data, but looks like 18 | # 19 | # array([[1, 2, 3, 4], 20 | # [1, 2, 3, 4], 21 | # [1, 2, 3, 4]], dtype=int8) 22 | # 23 | -------------------------------------------------------------------------------- /advanced/advanced_numpy/examples/test.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/advanced_numpy/examples/test.png -------------------------------------------------------------------------------- /advanced/advanced_numpy/examples/view-colors.py: -------------------------------------------------------------------------------- 1 | """ 2 | Structured array exercise 3 | ========================== 4 | 5 | Creating a structured array. 6 | """ 7 | 8 | import numpy as np 9 | 10 | x = np.zeros((10, 10, 4), dtype=np.int8) 11 | x[:, :, 0] = 1 12 | x[:, :, 1] = 2 13 | x[:, :, 2] = 3 14 | x[:, :, 3] = 4 15 | 16 | # How to make a (10, 10) structured array with fields 'r', 'g', 'b', 'a', 17 | # without copying? 18 | 19 | # y = ... 20 | 21 | assert (y["r"] == 1).all() 22 | assert (y["g"] == 2).all() 23 | assert (y["b"] == 3).all() 24 | assert (y["a"] == 4).all() 25 | -------------------------------------------------------------------------------- /advanced/advanced_numpy/mandelbrot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/advanced_numpy/mandelbrot.png -------------------------------------------------------------------------------- /advanced/advanced_numpy/test.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/advanced_numpy/test.png -------------------------------------------------------------------------------- /advanced/advanced_numpy/test2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/advanced_numpy/test2.png -------------------------------------------------------------------------------- /advanced/advanced_numpy/threefundamental.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/advanced_numpy/threefundamental.png -------------------------------------------------------------------------------- /advanced/debugging/debug_file.py: -------------------------------------------------------------------------------- 1 | """Script to read in a column of numbers and calculate the min, max and sum. 2 | 3 | Data is stored in data.txt. 4 | """ 5 | 6 | 7 | def parse_data(data_string): 8 | data = [] 9 | for x in data_string.split("."): 10 | data.append(x) 11 | return data 12 | 13 | 14 | def load_data(filename): 15 | fp = open(filename) 16 | data_string = fp.read() 17 | fp.close() 18 | return parse_data(data_string) 19 | 20 | 21 | if __name__ == "__main__": 22 | data = load_data("exercises/data.txt") 23 | print(f"min: {min(data):f}") # 10.20 24 | print(f"max: {max(data):f}") # 61.30 25 | -------------------------------------------------------------------------------- /advanced/debugging/index_error.py: -------------------------------------------------------------------------------- 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() 11 | -------------------------------------------------------------------------------- /advanced/debugging/segfault.py: -------------------------------------------------------------------------------- 1 | """Simple code that creates a segfault using numpy. Used to learn 2 | debugging segfaults with GDB. 3 | """ 4 | 5 | import numpy as np 6 | from numpy.lib import stride_tricks 7 | 8 | 9 | def make_big_array(small_array): 10 | big_array = stride_tricks.as_strided( 11 | small_array, shape=(int(2e6), int(2e6)), strides=(32, 32) 12 | ) 13 | return big_array 14 | 15 | 16 | def print_big_array(small_array): 17 | big_array = make_big_array(small_array) 18 | print(big_array[-10:]) 19 | return big_array 20 | 21 | 22 | l = [] 23 | for i in range(10): 24 | a = np.arange(8) 25 | l.append(print_big_array(a)) 26 | -------------------------------------------------------------------------------- /advanced/debugging/vim_pyflakes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/debugging/vim_pyflakes.png -------------------------------------------------------------------------------- /advanced/debugging/vim_syntastic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/debugging/vim_syntastic.png -------------------------------------------------------------------------------- /advanced/image_processing/axis_convention.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/image_processing/axis_convention.png -------------------------------------------------------------------------------- /advanced/image_processing/coins.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/image_processing/coins.png -------------------------------------------------------------------------------- /advanced/image_processing/diamond_kernel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/image_processing/diamond_kernel.png -------------------------------------------------------------------------------- /advanced/image_processing/examples/README.txt: -------------------------------------------------------------------------------- 1 | Examples for the image processing chapter 2 | ========================================= 3 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_block_mean.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plot the block mean of an image 3 | ================================ 4 | 5 | An example showing how to use broad-casting to plot the mean of 6 | blocks of an image. 7 | """ 8 | 9 | import numpy as np 10 | import scipy as sp 11 | import matplotlib.pyplot as plt 12 | 13 | f = sp.datasets.face(gray=True) 14 | sx, sy = f.shape 15 | X, Y = np.ogrid[0:sx, 0:sy] 16 | 17 | regions = sy // 6 * (X // 4) + Y // 6 18 | block_mean = sp.ndimage.mean(f, labels=regions, index=np.arange(1, regions.max() + 1)) 19 | block_mean.shape = (sx // 4, sy // 6) 20 | 21 | plt.figure(figsize=(5, 5)) 22 | plt.imshow(block_mean, cmap="gray") 23 | plt.axis("off") 24 | 25 | plt.show() 26 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_blur.py: -------------------------------------------------------------------------------- 1 | """ 2 | Blurring of images 3 | =================== 4 | 5 | An example showing various processes that blur an image. 6 | """ 7 | 8 | import scipy as sp 9 | import matplotlib.pyplot as plt 10 | 11 | face = sp.datasets.face(gray=True) 12 | blurred_face = sp.ndimage.gaussian_filter(face, sigma=3) 13 | very_blurred = sp.ndimage.gaussian_filter(face, sigma=5) 14 | local_mean = sp.ndimage.uniform_filter(face, size=11) 15 | 16 | plt.figure(figsize=(9, 3)) 17 | plt.subplot(131) 18 | plt.imshow(blurred_face, cmap="gray") 19 | plt.axis("off") 20 | plt.subplot(132) 21 | plt.imshow(very_blurred, cmap="gray") 22 | plt.axis("off") 23 | plt.subplot(133) 24 | plt.imshow(local_mean, cmap="gray") 25 | plt.axis("off") 26 | 27 | plt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.01, right=0.99) 28 | 29 | plt.show() 30 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_clean_morpho.py: -------------------------------------------------------------------------------- 1 | """ 2 | Cleaning segmentation with mathematical morphology 3 | =================================================== 4 | 5 | An example showing how to clean segmentation with mathematical 6 | morphology: removing small regions and holes. 7 | 8 | """ 9 | 10 | import numpy as np 11 | import scipy as sp 12 | import matplotlib.pyplot as plt 13 | 14 | rng = np.random.default_rng(27446968) 15 | n = 10 16 | l = 256 17 | im = np.zeros((l, l)) 18 | points = l * rng.random((2, n**2)) 19 | im[(points[0]).astype(int), (points[1]).astype(int)] = 1 20 | im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) 21 | 22 | mask = (im > im.mean()).astype(float) 23 | 24 | 25 | img = mask + 0.3 * rng.normal(size=mask.shape) 26 | 27 | binary_img = img > 0.5 28 | 29 | # Remove small white regions 30 | open_img = sp.ndimage.binary_opening(binary_img) 31 | # Remove small black hole 32 | close_img = sp.ndimage.binary_closing(open_img) 33 | 34 | plt.figure(figsize=(12, 3)) 35 | 36 | l = 128 37 | 38 | plt.subplot(141) 39 | plt.imshow(binary_img[:l, :l], cmap="gray") 40 | plt.axis("off") 41 | plt.subplot(142) 42 | plt.imshow(open_img[:l, :l], cmap="gray") 43 | plt.axis("off") 44 | plt.subplot(143) 45 | plt.imshow(close_img[:l, :l], cmap="gray") 46 | plt.axis("off") 47 | plt.subplot(144) 48 | plt.imshow(mask[:l, :l], cmap="gray") 49 | plt.contour(close_img[:l, :l], [0.5], linewidths=2, colors="r") 50 | plt.axis("off") 51 | 52 | plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) 53 | 54 | plt.show() 55 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_denoising.py: -------------------------------------------------------------------------------- 1 | """ 2 | Denoising an image with the median filter 3 | ========================================== 4 | 5 | This example shows the original image, the noisy image, the denoised 6 | one (with the median filter) and the difference between the two. 7 | """ 8 | 9 | import numpy as np 10 | import scipy as sp 11 | import matplotlib.pyplot as plt 12 | 13 | rng = np.random.default_rng(27446968) 14 | 15 | im = np.zeros((20, 20)) 16 | im[5:-5, 5:-5] = 1 17 | im = sp.ndimage.distance_transform_bf(im) 18 | im_noise = im + 0.2 * rng.normal(size=im.shape) 19 | 20 | im_med = sp.ndimage.median_filter(im_noise, 3) 21 | 22 | plt.figure(figsize=(16, 5)) 23 | 24 | plt.subplot(141) 25 | plt.imshow(im, interpolation="nearest") 26 | plt.axis("off") 27 | plt.title("Original image", fontsize=20) 28 | plt.subplot(142) 29 | plt.imshow(im_noise, interpolation="nearest", vmin=0, vmax=5) 30 | plt.axis("off") 31 | plt.title("Noisy image", fontsize=20) 32 | plt.subplot(143) 33 | plt.imshow(im_med, interpolation="nearest", vmin=0, vmax=5) 34 | plt.axis("off") 35 | plt.title("Median filter", fontsize=20) 36 | plt.subplot(144) 37 | plt.imshow(np.abs(im - im_med), cmap="hot", interpolation="nearest") 38 | plt.axis("off") 39 | plt.title("Error", fontsize=20) 40 | 41 | 42 | plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1) 43 | 44 | plt.show() 45 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_display_face.py: -------------------------------------------------------------------------------- 1 | """ 2 | Display a Raccoon Face 3 | ====================== 4 | 5 | An example that displays a raccoon face with matplotlib. 6 | """ 7 | 8 | import scipy as sp 9 | import matplotlib.pyplot as plt 10 | 11 | f = sp.datasets.face(gray=True) 12 | 13 | plt.figure(figsize=(10, 3.6)) 14 | 15 | plt.subplot(131) 16 | plt.imshow(f, cmap="gray") 17 | 18 | plt.subplot(132) 19 | plt.imshow(f, cmap="gray", vmin=30, vmax=200) 20 | plt.axis("off") 21 | 22 | plt.subplot(133) 23 | plt.imshow(f, cmap="gray") 24 | plt.contour(f, [50, 200]) 25 | plt.axis("off") 26 | 27 | plt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.05, right=0.99) 28 | plt.show() 29 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_face.py: -------------------------------------------------------------------------------- 1 | """ 2 | Displaying a Raccoon Face 3 | ========================= 4 | 5 | Small example to plot a raccoon face. 6 | """ 7 | 8 | import scipy as sp 9 | import imageio.v3 as iio 10 | 11 | f = sp.datasets.face() 12 | iio.imwrite("face.png", f) # uses the Image module (PIL) 13 | 14 | import matplotlib.pyplot as plt 15 | 16 | plt.imshow(f) 17 | plt.show() 18 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_face_denoise.py: -------------------------------------------------------------------------------- 1 | """ 2 | Image denoising 3 | ================ 4 | 5 | This example demoes image denoising on a Raccoon face. 6 | """ 7 | 8 | import numpy as np 9 | import scipy as sp 10 | import matplotlib.pyplot as plt 11 | 12 | rng = np.random.default_rng(27446968) 13 | 14 | f = sp.datasets.face(gray=True) 15 | f = f[230:290, 220:320] 16 | 17 | noisy = f + 0.4 * f.std() * rng.random(f.shape) 18 | 19 | gauss_denoised = sp.ndimage.gaussian_filter(noisy, 2) 20 | med_denoised = sp.ndimage.median_filter(noisy, 3) 21 | 22 | 23 | plt.figure(figsize=(12, 2.8)) 24 | 25 | plt.subplot(131) 26 | plt.imshow(noisy, cmap="gray", vmin=40, vmax=220) 27 | plt.axis("off") 28 | plt.title("noisy", fontsize=20) 29 | plt.subplot(132) 30 | plt.imshow(gauss_denoised, cmap="gray", vmin=40, vmax=220) 31 | plt.axis("off") 32 | plt.title("Gaussian filter", fontsize=20) 33 | plt.subplot(133) 34 | plt.imshow(med_denoised, cmap="gray", vmin=40, vmax=220) 35 | plt.axis("off") 36 | plt.title("Median filter", fontsize=20) 37 | 38 | plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1) 39 | plt.show() 40 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_face_tv_denoise.py: -------------------------------------------------------------------------------- 1 | """ 2 | Total Variation denoising 3 | =========================== 4 | 5 | This example demoes Total-Variation (TV) denoising on a Raccoon face. 6 | """ 7 | 8 | import numpy as np 9 | import scipy as sp 10 | import matplotlib.pyplot as plt 11 | 12 | from skimage.restoration import denoise_tv_chambolle 13 | 14 | rng = np.random.default_rng(27446968) 15 | 16 | f = sp.datasets.face(gray=True) 17 | f = f[230:290, 220:320] 18 | 19 | noisy = f + 0.4 * f.std() * rng.random(f.shape) 20 | 21 | tv_denoised = denoise_tv_chambolle(noisy, weight=10) 22 | 23 | 24 | plt.figure(figsize=(12, 2.8)) 25 | 26 | plt.subplot(131) 27 | plt.imshow(noisy, cmap="gray", vmin=40, vmax=220) 28 | plt.axis("off") 29 | plt.title("noisy", fontsize=20) 30 | plt.subplot(132) 31 | plt.imshow(tv_denoised, cmap="gray", vmin=40, vmax=220) 32 | plt.axis("off") 33 | plt.title("TV denoising", fontsize=20) 34 | 35 | tv_denoised = denoise_tv_chambolle(noisy, weight=50) 36 | plt.subplot(133) 37 | plt.imshow(tv_denoised, cmap="gray", vmin=40, vmax=220) 38 | plt.axis("off") 39 | plt.title("(more) TV denoising", fontsize=20) 40 | 41 | plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1) 42 | plt.show() 43 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_find_edges.py: -------------------------------------------------------------------------------- 1 | """ 2 | Finding edges with Sobel filters 3 | ================================== 4 | 5 | The Sobel filter is one of the simplest way of finding edges. 6 | """ 7 | 8 | import numpy as np 9 | import scipy as sp 10 | import matplotlib.pyplot as plt 11 | 12 | rng = np.random.default_rng(27446968) 13 | 14 | im = np.zeros((256, 256)) 15 | im[64:-64, 64:-64] = 1 16 | 17 | im = sp.ndimage.rotate(im, 15, mode="constant") 18 | im = sp.ndimage.gaussian_filter(im, 8) 19 | 20 | sx = sp.ndimage.sobel(im, axis=0, mode="constant") 21 | sy = sp.ndimage.sobel(im, axis=1, mode="constant") 22 | sob = np.hypot(sx, sy) 23 | 24 | plt.figure(figsize=(16, 5)) 25 | plt.subplot(141) 26 | plt.imshow(im, cmap="gray") 27 | plt.axis("off") 28 | plt.title("square", fontsize=20) 29 | plt.subplot(142) 30 | plt.imshow(sx) 31 | plt.axis("off") 32 | plt.title("Sobel (x direction)", fontsize=20) 33 | plt.subplot(143) 34 | plt.imshow(sob) 35 | plt.axis("off") 36 | plt.title("Sobel filter", fontsize=20) 37 | 38 | im += 0.07 * rng.random(im.shape) 39 | 40 | sx = sp.ndimage.sobel(im, axis=0, mode="constant") 41 | sy = sp.ndimage.sobel(im, axis=1, mode="constant") 42 | sob = np.hypot(sx, sy) 43 | 44 | plt.subplot(144) 45 | plt.imshow(sob) 46 | plt.axis("off") 47 | plt.title("Sobel for noisy image", fontsize=20) 48 | 49 | 50 | plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=0.9) 51 | 52 | plt.show() 53 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_find_object.py: -------------------------------------------------------------------------------- 1 | """ 2 | Find the bounding box of an object 3 | =================================== 4 | 5 | This example shows how to extract the bounding box of the largest object 6 | 7 | """ 8 | 9 | import numpy as np 10 | import scipy as sp 11 | import matplotlib.pyplot as plt 12 | 13 | rng = np.random.default_rng(27446968) 14 | n = 10 15 | l = 256 16 | im = np.zeros((l, l)) 17 | points = l * rng.random((2, n**2)) 18 | im[(points[0]).astype(int), (points[1]).astype(int)] = 1 19 | im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) 20 | 21 | mask = im > im.mean() 22 | 23 | label_im, nb_labels = sp.ndimage.label(mask) 24 | 25 | # Find the largest connected component 26 | sizes = sp.ndimage.sum(mask, label_im, range(nb_labels + 1)) 27 | mask_size = sizes < 1000 28 | remove_pixel = mask_size[label_im] 29 | label_im[remove_pixel] = 0 30 | labels = np.unique(label_im) 31 | label_im = np.searchsorted(labels, label_im) 32 | 33 | # Now that we have only one connected component, extract it's bounding box 34 | slice_x, slice_y = sp.ndimage.find_objects(label_im == 4)[0] 35 | roi = im[slice_x, slice_y] 36 | 37 | plt.figure(figsize=(4, 2)) 38 | plt.axes((0, 0, 1, 1)) 39 | plt.imshow(roi) 40 | plt.axis("off") 41 | 42 | plt.show() 43 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_geom_face.py: -------------------------------------------------------------------------------- 1 | """ 2 | Geometrical transformations 3 | ============================== 4 | 5 | This examples demos some simple geometrical transformations on a Raccoon face. 6 | """ 7 | 8 | import numpy as np 9 | import scipy as sp 10 | import matplotlib.pyplot as plt 11 | 12 | face = sp.datasets.face(gray=True) 13 | lx, ly = face.shape 14 | # Cropping 15 | crop_face = face[lx // 4 : -lx // 4, ly // 4 : -ly // 4] 16 | # up <-> down flip 17 | flip_ud_face = np.flipud(face) 18 | # rotation 19 | rotate_face = sp.ndimage.rotate(face, 45) 20 | rotate_face_noreshape = sp.ndimage.rotate(face, 45, reshape=False) 21 | 22 | plt.figure(figsize=(12.5, 2.5)) 23 | 24 | 25 | plt.subplot(151) 26 | plt.imshow(face, cmap="gray") 27 | plt.axis("off") 28 | plt.subplot(152) 29 | plt.imshow(crop_face, cmap="gray") 30 | plt.axis("off") 31 | plt.subplot(153) 32 | plt.imshow(flip_ud_face, cmap="gray") 33 | plt.axis("off") 34 | plt.subplot(154) 35 | plt.imshow(rotate_face, cmap="gray") 36 | plt.axis("off") 37 | plt.subplot(155) 38 | plt.imshow(rotate_face_noreshape, cmap="gray") 39 | plt.axis("off") 40 | 41 | plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) 42 | 43 | plt.show() 44 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_greyscale_dilation.py: -------------------------------------------------------------------------------- 1 | """ 2 | Greyscale dilation 3 | ==================== 4 | 5 | This example illustrates greyscale mathematical morphology. 6 | """ 7 | 8 | import numpy as np 9 | import scipy as sp 10 | import matplotlib.pyplot as plt 11 | 12 | im = np.zeros((64, 64)) 13 | rng = np.random.default_rng(27446968) 14 | x, y = (63 * rng.random((2, 8))).astype(int) 15 | im[x, y] = np.arange(8) 16 | 17 | bigger_points = sp.ndimage.grey_dilation(im, size=(5, 5), structure=np.ones((5, 5))) 18 | 19 | square = np.zeros((16, 16)) 20 | square[4:-4, 4:-4] = 1 21 | dist = sp.ndimage.distance_transform_bf(square) 22 | dilate_dist = sp.ndimage.grey_dilation(dist, size=(3, 3), structure=np.ones((3, 3))) 23 | 24 | plt.figure(figsize=(12.5, 3)) 25 | plt.subplot(141) 26 | plt.imshow(im, interpolation="nearest", cmap="nipy_spectral") 27 | plt.axis("off") 28 | plt.subplot(142) 29 | plt.imshow(bigger_points, interpolation="nearest", cmap="nipy_spectral") 30 | plt.axis("off") 31 | plt.subplot(143) 32 | plt.imshow(dist, interpolation="nearest", cmap="nipy_spectral") 33 | plt.axis("off") 34 | plt.subplot(144) 35 | plt.imshow(dilate_dist, interpolation="nearest", cmap="nipy_spectral") 36 | plt.axis("off") 37 | 38 | plt.subplots_adjust(wspace=0, hspace=0.02, top=0.99, bottom=0.01, left=0.01, right=0.99) 39 | plt.show() 40 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_histo_segmentation.py: -------------------------------------------------------------------------------- 1 | """ 2 | Histogram segmentation 3 | ====================== 4 | 5 | This example does simple histogram analysis to perform segmentation. 6 | """ 7 | 8 | import numpy as np 9 | import scipy as sp 10 | import matplotlib.pyplot as plt 11 | 12 | rng = np.random.default_rng(27446968) 13 | n = 10 14 | l = 256 15 | im = np.zeros((l, l)) 16 | points = l * rng.random((2, n**2)) 17 | im[(points[0]).astype(int), (points[1]).astype(int)] = 1 18 | im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) 19 | 20 | mask = (im > im.mean()).astype(float) 21 | 22 | mask += 0.1 * im 23 | 24 | img = mask + 0.2 * rng.normal(size=mask.shape) 25 | 26 | hist, bin_edges = np.histogram(img, bins=60) 27 | bin_centers = 0.5 * (bin_edges[:-1] + bin_edges[1:]) 28 | 29 | binary_img = img > 0.5 30 | 31 | plt.figure(figsize=(11, 4)) 32 | 33 | plt.subplot(131) 34 | plt.imshow(img) 35 | plt.axis("off") 36 | plt.subplot(132) 37 | plt.plot(bin_centers, hist, lw=2) 38 | plt.axvline(0.5, color="r", ls="--", lw=2) 39 | plt.text(0.57, 0.8, "histogram", fontsize=20, transform=plt.gca().transAxes) 40 | plt.yticks([]) 41 | plt.subplot(133) 42 | plt.imshow(binary_img, cmap="gray", interpolation="nearest") 43 | plt.axis("off") 44 | 45 | plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) 46 | plt.show() 47 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_interpolation_face.py: -------------------------------------------------------------------------------- 1 | """ 2 | Image interpolation 3 | ===================== 4 | 5 | The example demonstrates image interpolation on a Raccoon face. 6 | """ 7 | 8 | import scipy as sp 9 | import matplotlib.pyplot as plt 10 | 11 | f = sp.datasets.face(gray=True) 12 | 13 | plt.figure(figsize=(8, 4)) 14 | 15 | plt.subplot(1, 2, 1) 16 | plt.imshow(f[320:340, 510:530], cmap="gray") 17 | plt.axis("off") 18 | 19 | plt.subplot(1, 2, 2) 20 | plt.imshow(f[320:340, 510:530], cmap="gray", interpolation="nearest") 21 | plt.axis("off") 22 | 23 | plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1) 24 | plt.show() 25 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_measure_data.py: -------------------------------------------------------------------------------- 1 | """ 2 | Measurements from images 3 | ========================== 4 | 5 | This examples shows how to measure quantities from various images. 6 | 7 | """ 8 | 9 | import numpy as np 10 | import scipy as sp 11 | import matplotlib.pyplot as plt 12 | 13 | rng = np.random.default_rng(27446968) 14 | n = 10 15 | l = 256 16 | im = np.zeros((l, l)) 17 | points = l * rng.random((2, n**2)) 18 | im[(points[0]).astype(int), (points[1]).astype(int)] = 1 19 | im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) 20 | 21 | mask = im > im.mean() 22 | 23 | label_im, nb_labels = sp.ndimage.label(mask) 24 | 25 | sizes = sp.ndimage.sum(mask, label_im, range(nb_labels + 1)) 26 | mask_size = sizes < 1000 27 | remove_pixel = mask_size[label_im] 28 | label_im[remove_pixel] = 0 29 | labels = np.unique(label_im) 30 | label_clean = np.searchsorted(labels, label_im) 31 | 32 | 33 | plt.figure(figsize=(6, 3)) 34 | 35 | plt.subplot(121) 36 | plt.imshow(label_im, cmap="nipy_spectral") 37 | plt.axis("off") 38 | plt.subplot(122) 39 | plt.imshow(label_clean, vmax=nb_labels, cmap="nipy_spectral") 40 | plt.axis("off") 41 | 42 | plt.subplots_adjust(wspace=0.01, hspace=0.01, top=1, bottom=0, left=0, right=1) 43 | plt.show() 44 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_numpy_array.py: -------------------------------------------------------------------------------- 1 | """ 2 | Image manipulation and NumPy arrays 3 | ==================================== 4 | 5 | This example shows how to do image manipulation using common NumPy arrays 6 | tricks. 7 | 8 | """ 9 | 10 | import numpy as np 11 | import scipy as sp 12 | import matplotlib.pyplot as plt 13 | 14 | face = sp.datasets.face(gray=True) 15 | face[10:13, 20:23] 16 | face[100:120] = 255 17 | 18 | lx, ly = face.shape 19 | X, Y = np.ogrid[0:lx, 0:ly] 20 | mask = (X - lx / 2) ** 2 + (Y - ly / 2) ** 2 > lx * ly / 4 21 | face[mask] = 0 22 | face[range(400), range(400)] = 255 23 | 24 | plt.figure(figsize=(3, 3)) 25 | plt.axes((0, 0, 1, 1)) 26 | plt.imshow(face, cmap="gray") 27 | plt.axis("off") 28 | 29 | plt.show() 30 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_propagation.py: -------------------------------------------------------------------------------- 1 | """ 2 | Opening, erosion, and propagation 3 | ================================== 4 | 5 | This example shows simple operations of mathematical morphology. 6 | """ 7 | 8 | import numpy as np 9 | import scipy as sp 10 | import matplotlib.pyplot as plt 11 | 12 | square = np.zeros((32, 32)) 13 | square[10:-10, 10:-10] = 1 14 | rng = np.random.default_rng(27446968) 15 | x, y = (32 * rng.random((2, 20))).astype(int) 16 | square[x, y] = 1 17 | 18 | open_square = sp.ndimage.binary_opening(square) 19 | 20 | eroded_square = sp.ndimage.binary_erosion(square) 21 | reconstruction = sp.ndimage.binary_propagation(eroded_square, mask=square) 22 | 23 | plt.figure(figsize=(9.5, 3)) 24 | plt.subplot(131) 25 | plt.imshow(square, cmap="gray", interpolation="nearest") 26 | plt.axis("off") 27 | plt.subplot(132) 28 | plt.imshow(open_square, cmap="gray", interpolation="nearest") 29 | plt.axis("off") 30 | plt.subplot(133) 31 | plt.imshow(reconstruction, cmap="gray", interpolation="nearest") 32 | plt.axis("off") 33 | 34 | plt.subplots_adjust(wspace=0, hspace=0.02, top=0.99, bottom=0.01, left=0.01, right=0.99) 35 | plt.show() 36 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_radial_mean.py: -------------------------------------------------------------------------------- 1 | """ 2 | Radial mean 3 | ============ 4 | 5 | This example shows how to do a radial mean with scikit-image. 6 | """ 7 | 8 | import numpy as np 9 | import scipy as sp 10 | import matplotlib.pyplot as plt 11 | 12 | f = sp.datasets.face(gray=True) 13 | sx, sy = f.shape 14 | X, Y = np.ogrid[0:sx, 0:sy] 15 | 16 | 17 | r = np.hypot(X - sx / 2, Y - sy / 2) 18 | 19 | rbin = (20 * r / r.max()).astype(int) 20 | radial_mean = sp.ndimage.mean(f, labels=rbin, index=np.arange(1, rbin.max() + 1)) 21 | 22 | plt.figure(figsize=(5, 5)) 23 | plt.axes((0, 0, 1, 1)) 24 | plt.imshow(rbin, cmap="nipy_spectral") 25 | plt.axis("off") 26 | 27 | plt.show() 28 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_sharpen.py: -------------------------------------------------------------------------------- 1 | """ 2 | Image sharpening 3 | ================= 4 | 5 | This example shows how to sharpen an image in noiseless situation by 6 | applying the filter inverse to the blur. 7 | """ 8 | 9 | import scipy as sp 10 | import matplotlib.pyplot as plt 11 | 12 | f = sp.datasets.face(gray=True).astype(float) 13 | blurred_f = sp.ndimage.gaussian_filter(f, 3) 14 | 15 | filter_blurred_f = sp.ndimage.gaussian_filter(blurred_f, 1) 16 | 17 | alpha = 30 18 | sharpened = blurred_f + alpha * (blurred_f - filter_blurred_f) 19 | 20 | plt.figure(figsize=(12, 4)) 21 | 22 | plt.subplot(131) 23 | plt.imshow(f, cmap="gray") 24 | plt.axis("off") 25 | plt.subplot(132) 26 | plt.imshow(blurred_f, cmap="gray") 27 | plt.axis("off") 28 | plt.subplot(133) 29 | plt.imshow(sharpened, cmap="gray") 30 | plt.axis("off") 31 | 32 | plt.tight_layout() 33 | plt.show() 34 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_synthetic_data.py: -------------------------------------------------------------------------------- 1 | """ 2 | Synthetic data 3 | =============== 4 | 5 | The example generates and displays simple synthetic data. 6 | """ 7 | 8 | import numpy as np 9 | import scipy as sp 10 | import matplotlib.pyplot as plt 11 | 12 | rng = np.random.default_rng(27446968) 13 | n = 10 14 | l = 256 15 | im = np.zeros((l, l)) 16 | points = l * rng.random((2, n**2)) 17 | im[(points[0]).astype(int), (points[1]).astype(int)] = 1 18 | im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) 19 | 20 | mask = im > im.mean() 21 | 22 | label_im, nb_labels = sp.ndimage.label(mask) 23 | 24 | plt.figure(figsize=(9, 3)) 25 | 26 | plt.subplot(131) 27 | plt.imshow(im) 28 | plt.axis("off") 29 | plt.subplot(132) 30 | plt.imshow(mask, cmap="gray") 31 | plt.axis("off") 32 | plt.subplot(133) 33 | plt.imshow(label_im, cmap="nipy_spectral") 34 | plt.axis("off") 35 | 36 | plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1) 37 | plt.show() 38 | -------------------------------------------------------------------------------- /advanced/image_processing/image_GMM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/image_processing/image_GMM.png -------------------------------------------------------------------------------- /advanced/image_processing/image_spectral_clustering.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/image_processing/image_spectral_clustering.png -------------------------------------------------------------------------------- /advanced/image_processing/kernels.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/image_processing/kernels.png -------------------------------------------------------------------------------- /advanced/image_processing/morpho_mat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/image_processing/morpho_mat.png -------------------------------------------------------------------------------- /advanced/image_processing/scikit_image_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/image_processing/scikit_image_logo.png -------------------------------------------------------------------------------- /advanced/index.rst: -------------------------------------------------------------------------------- 1 | .. _advanced_topics_part: 2 | 3 | Advanced topics 4 | ================ 5 | 6 | This part of the *Scientific Python Lectures* is dedicated to advanced usage. 7 | It strives to educate the proficient Python coder to be an expert and 8 | tackles various specific topics. 9 | 10 | | 11 | 12 | .. include:: ../includes/big_toc_css.rst 13 | :start-line: 1 14 | 15 | .. rst-class:: tune 16 | 17 | .. toctree:: 18 | 19 | advanced_python/index.rst 20 | advanced_numpy/index.rst 21 | debugging/index.rst 22 | optimizing/index.rst 23 | scipy_sparse/index.rst 24 | image_processing/index.rst 25 | mathematical_optimization/index.rst 26 | interfacing_with_c/interfacing_with_c.rst 27 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/ctypes/cos_module.py: -------------------------------------------------------------------------------- 1 | """Example of wrapping cos function from math.h using ctypes.""" 2 | 3 | import ctypes 4 | 5 | # find and load the library 6 | 7 | # OSX or linux 8 | from ctypes.util import find_library 9 | 10 | libm_name = find_library("m") 11 | assert libm_name is not None, "Cannot find libm (math) on this system :/ That's bad." 12 | 13 | libm = ctypes.cdll.LoadLibrary(libm_name) 14 | 15 | # Windows 16 | # from ctypes import windll 17 | # libm = cdll.msvcrt 18 | 19 | 20 | # set the argument type 21 | libm.cos.argtypes = [ctypes.c_double] 22 | # set the return type 23 | libm.cos.restype = ctypes.c_double 24 | 25 | 26 | def cos_func(arg): 27 | """Wrapper for cos from math.h""" 28 | return libm.cos(arg) 29 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/ctypes_numpy/cos_doubles.c: -------------------------------------------------------------------------------- 1 | ../numpy_shared/cos_doubles.c -------------------------------------------------------------------------------- /advanced/interfacing_with_c/ctypes_numpy/cos_doubles.h: -------------------------------------------------------------------------------- 1 | ../numpy_shared/cos_doubles.h -------------------------------------------------------------------------------- /advanced/interfacing_with_c/ctypes_numpy/cos_doubles.py: -------------------------------------------------------------------------------- 1 | """Example of wrapping a C library function that accepts a C double array as 2 | input using the numpy.ctypeslib.""" 3 | 4 | import numpy as np 5 | import numpy.ctypeslib as npct 6 | from ctypes import c_int 7 | 8 | # input type for the cos_doubles function 9 | # must be a double array, with single dimension that is contiguous 10 | array_1d_double = npct.ndpointer(dtype=np.double, ndim=1, flags="CONTIGUOUS") 11 | 12 | # load the library, using NumPy mechanisms 13 | libcd = npct.load_library("libcos_doubles", ".") 14 | 15 | # setup the return types and argument types 16 | libcd.cos_doubles.restype = None 17 | libcd.cos_doubles.argtypes = [array_1d_double, array_1d_double, c_int] 18 | 19 | 20 | def cos_doubles_func(in_array, out_array): 21 | return libcd.cos_doubles(in_array, out_array, len(in_array)) 22 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/ctypes_numpy/makefile: -------------------------------------------------------------------------------- 1 | m.PHONY : clean 2 | 3 | libcos_doubles.so : cos_doubles.o 4 | gcc -shared -Wl,-soname,libcos_doubles.so -o libcos_doubles.so cos_doubles.o 5 | 6 | cos_doubles.o : cos_doubles.c 7 | gcc -c -fPIC cos_doubles.c -o cos_doubles.o 8 | 9 | clean : 10 | -rm -vf libcos_doubles.so cos_doubles.o cos_doubles.pyc 11 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/ctypes_numpy/test_cos_doubles.png: -------------------------------------------------------------------------------- 1 | ../numpy_shared/test_cos_doubles.png -------------------------------------------------------------------------------- /advanced/interfacing_with_c/ctypes_numpy/test_cos_doubles.py: -------------------------------------------------------------------------------- 1 | ../numpy_shared/test_cos_doubles.py -------------------------------------------------------------------------------- /advanced/interfacing_with_c/cython/cos_module.pyx: -------------------------------------------------------------------------------- 1 | """ Example of wrapping cos function from math.h using Cython. """ 2 | 3 | cdef extern from "math.h": 4 | double cos(double arg) 5 | 6 | def cos_func(arg): 7 | return cos(arg) 8 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/cython/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, Extension 2 | from Cython.Build import cythonize 3 | 4 | 5 | extensions = [Extension("cos_module", sources=["cos_module.pyx"])] 6 | 7 | setup(ext_modules=cythonize(extensions)) 8 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/cython_numpy/_cos_doubles.pyx: -------------------------------------------------------------------------------- 1 | """ Example of wrapping a C function that takes C double arrays as input using 2 | the NumPy declarations from Cython """ 3 | 4 | # cimport the Cython declarations for NumPy 5 | cimport numpy as np 6 | 7 | # if you want to use the NumPy-C-API from Cython 8 | # (not strictly necessary for this example, but good practice) 9 | np.import_array() 10 | 11 | # cdefine the signature of our c function 12 | cdef extern from "cos_doubles.h": 13 | void cos_doubles (double * in_array, double * out_array, int size) 14 | 15 | # create the wrapper code, with NumPy type annotations 16 | def cos_doubles_func(np.ndarray[double, ndim=1, mode="c"] in_array not None, 17 | np.ndarray[double, ndim=1, mode="c"] out_array not None): 18 | cos_doubles( np.PyArray_DATA(in_array), 19 | np.PyArray_DATA(out_array), 20 | in_array.shape[0]) 21 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/cython_numpy/cos_doubles.c: -------------------------------------------------------------------------------- 1 | ../numpy_shared/cos_doubles.c -------------------------------------------------------------------------------- /advanced/interfacing_with_c/cython_numpy/cos_doubles.h: -------------------------------------------------------------------------------- 1 | ../numpy_shared/cos_doubles.h -------------------------------------------------------------------------------- /advanced/interfacing_with_c/cython_numpy/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, Extension 2 | from Cython.Build import cythonize 3 | import numpy 4 | 5 | 6 | extensions = [ 7 | Extension( 8 | "cos_doubles", 9 | sources=["_cos_doubles.pyx", "cos_doubles.c"], 10 | include_dirs=[numpy.get_include()], 11 | ) 12 | ] 13 | 14 | setup(ext_modules=cythonize(extensions)) 15 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/cython_numpy/test_cos_doubles.png: -------------------------------------------------------------------------------- 1 | ../numpy_shared/test_cos_doubles.png -------------------------------------------------------------------------------- /advanced/interfacing_with_c/cython_numpy/test_cos_doubles.py: -------------------------------------------------------------------------------- 1 | ../numpy_shared/test_cos_doubles.py -------------------------------------------------------------------------------- /advanced/interfacing_with_c/cython_simple/cos_module.pyx: -------------------------------------------------------------------------------- 1 | """ Simpler example of wrapping cos function from math.h using Cython. """ 2 | 3 | from libc.math cimport cos 4 | 5 | def cos_func(arg): 6 | return cos(arg) 7 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/cython_simple/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, Extension 2 | from Cython.Build import cythonize 3 | 4 | 5 | extensions = [Extension("cos_module", sources=["cos_module.pyx"])] 6 | 7 | setup(ext_modules=cythonize(extensions)) 8 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/numpy_c_api/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, Extension 2 | import numpy 3 | 4 | 5 | # define the extension module 6 | cos_module_np = Extension( 7 | "cos_module_np", sources=["cos_module_np.c"], include_dirs=[numpy.get_include()] 8 | ) 9 | 10 | # run the setup 11 | setup(ext_modules=[cos_module_np]) 12 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/numpy_c_api/test_cos_module_np.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/interfacing_with_c/numpy_c_api/test_cos_module_np.png -------------------------------------------------------------------------------- /advanced/interfacing_with_c/numpy_shared/cos_doubles.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* Compute the cosine of each element in in_array, storing the result in 4 | * out_array. */ 5 | void cos_doubles(double * in_array, double * out_array, int size){ 6 | int i; 7 | for(i=0;i 2 | 3 | double cos_func(double arg){ 4 | return cos(arg); 5 | } 6 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/swig/cos_module.h: -------------------------------------------------------------------------------- 1 | double cos_func(double arg); 2 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/swig/cos_module.i: -------------------------------------------------------------------------------- 1 | /* Example of wrapping cos function from math.h using SWIG. */ 2 | 3 | %module cos_module 4 | %{ 5 | /* the resulting C file should be built as a python extension */ 6 | #define SWIG_FILE_WITH_INIT 7 | /* Includes the header in the wrapper code */ 8 | #include "cos_module.h" 9 | %} 10 | /* Parse the header file to generate wrappers */ 11 | %include "cos_module.h" 12 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/swig/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, Extension 2 | 3 | 4 | setup(ext_modules=[Extension("_cos_module", sources=["cos_module.c", "cos_module.i"])]) 5 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/swig_numpy/cos_doubles.c: -------------------------------------------------------------------------------- 1 | ../numpy_shared/cos_doubles.c -------------------------------------------------------------------------------- /advanced/interfacing_with_c/swig_numpy/cos_doubles.h: -------------------------------------------------------------------------------- 1 | ../numpy_shared/cos_doubles.h -------------------------------------------------------------------------------- /advanced/interfacing_with_c/swig_numpy/cos_doubles.i: -------------------------------------------------------------------------------- 1 | /* Example of wrapping a C function that takes a C double array as input using 2 | * NumPy typemaps for SWIG. */ 3 | 4 | %module cos_doubles 5 | %{ 6 | /* the resulting C file should be built as a python extension */ 7 | #define SWIG_FILE_WITH_INIT 8 | /* Includes the header in the wrapper code */ 9 | #include "cos_doubles.h" 10 | %} 11 | 12 | /* include the NumPy typemaps */ 13 | %include "numpy.i" 14 | /* need this for correct module initialization */ 15 | %init %{ 16 | import_array(); 17 | %} 18 | 19 | /* typemaps for the two arrays, the second will be modified in-place */ 20 | %apply (double* IN_ARRAY1, int DIM1) {(double * in_array, int size_in)} 21 | %apply (double* INPLACE_ARRAY1, int DIM1) {(double * out_array, int size_out)} 22 | 23 | /* Wrapper for cos_doubles that massages the types */ 24 | %inline %{ 25 | /* takes as input two NumPy arrays */ 26 | void cos_doubles_func(double * in_array, int size_in, double * out_array, int size_out) { 27 | /* calls the original function, providing only the size of the first */ 28 | cos_doubles(in_array, out_array, size_in); 29 | } 30 | %} 31 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/swig_numpy/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, Extension 2 | import numpy 3 | 4 | 5 | setup( 6 | ext_modules=[ 7 | Extension( 8 | "_cos_doubles", 9 | sources=["cos_doubles.c", "cos_doubles.i"], 10 | include_dirs=[numpy.get_include()], 11 | ) 12 | ] 13 | ) 14 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/swig_numpy/test_cos_doubles.png: -------------------------------------------------------------------------------- 1 | ../numpy_shared/test_cos_doubles.png -------------------------------------------------------------------------------- /advanced/interfacing_with_c/swig_numpy/test_cos_doubles.py: -------------------------------------------------------------------------------- 1 | ../numpy_shared/test_cos_doubles.py -------------------------------------------------------------------------------- /advanced/mathematical_optimization/examples/README.txt: -------------------------------------------------------------------------------- 1 | Examples for the mathematical optimization chapter 2 | ================================================== 3 | -------------------------------------------------------------------------------- /advanced/mathematical_optimization/examples/helper/compare_optimizers_py3.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/mathematical_optimization/examples/helper/compare_optimizers_py3.pkl -------------------------------------------------------------------------------- /advanced/mathematical_optimization/examples/plot_convex.py: -------------------------------------------------------------------------------- 1 | """ 2 | Convex function 3 | ================ 4 | 5 | A figure showing the definition of a convex function 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | x = np.linspace(-1, 2) 12 | 13 | plt.figure(1, figsize=(3, 2.5)) 14 | plt.clf() 15 | 16 | # A convex function 17 | plt.plot(x, x**2, linewidth=2) 18 | plt.text(-0.7, -(0.6**2), "$f$", size=20) 19 | 20 | # The tangent in one point 21 | plt.plot(x, 2 * x - 1) 22 | plt.plot(1, 1, "k+") 23 | plt.text(0.3, -0.75, "Tangent to $f$", size=15) 24 | plt.text(1, 1 - 0.5, "C", size=15) 25 | 26 | # Convexity as barycenter 27 | plt.plot([0.35, 1.85], [0.35**2, 1.85**2]) 28 | plt.plot([0.35, 1.85], [0.35**2, 1.85**2], "k+") 29 | plt.text(0.35 - 0.2, 0.35**2 + 0.1, "A", size=15) 30 | plt.text(1.85 - 0.2, 1.85**2, "B", size=15) 31 | 32 | plt.ylim(ymin=-1) 33 | plt.axis("off") 34 | plt.tight_layout() 35 | 36 | # Convexity as barycenter 37 | plt.figure(2, figsize=(3, 2.5)) 38 | plt.clf() 39 | plt.plot(x, x**2 + np.exp(-5 * (x - 0.5) ** 2), linewidth=2) 40 | plt.text(-0.7, -(0.6**2), "$f$", size=20) 41 | 42 | plt.ylim(ymin=-1) 43 | plt.axis("off") 44 | plt.tight_layout() 45 | plt.show() 46 | -------------------------------------------------------------------------------- /advanced/mathematical_optimization/examples/plot_curve_fitting.py: -------------------------------------------------------------------------------- 1 | """ 2 | Curve fitting 3 | ============= 4 | 5 | A curve fitting example 6 | """ 7 | 8 | import numpy as np 9 | import scipy as sp 10 | import matplotlib.pyplot as plt 11 | 12 | rng = np.random.default_rng(27446968) 13 | 14 | 15 | # Our test function 16 | def f(t, omega, phi): 17 | return np.cos(omega * t + phi) 18 | 19 | 20 | # Our x and y data 21 | x = np.linspace(0, 3, 50) 22 | y = f(x, 1.5, 1) + 0.1 * np.random.normal(size=50) 23 | 24 | # Fit the model: the parameters omega and phi can be found in the 25 | # `params` vector 26 | params, params_cov = sp.optimize.curve_fit(f, x, y) 27 | 28 | # plot the data and the fitted curve 29 | t = np.linspace(0, 3, 1000) 30 | 31 | plt.figure(1) 32 | plt.clf() 33 | plt.plot(x, y, "bx") 34 | plt.plot(t, f(t, *params), "r-") 35 | plt.show() 36 | -------------------------------------------------------------------------------- /advanced/mathematical_optimization/examples/plot_noisy.py: -------------------------------------------------------------------------------- 1 | """ 2 | Noisy optimization problem 3 | =========================== 4 | 5 | Draws a figure explaining noisy vs non-noisy optimization 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | rng = np.random.default_rng(27446968) 12 | 13 | x = np.linspace(-5, 5, 101) 14 | x_ = np.linspace(-5, 5, 31) 15 | 16 | 17 | def f(x): 18 | return -np.exp(-(x**2)) 19 | 20 | 21 | # A smooth function 22 | plt.figure(1, figsize=(3, 2.5)) 23 | plt.clf() 24 | 25 | plt.plot(x_, f(x_) + 0.2 * np.random.normal(size=31), linewidth=2) 26 | plt.plot(x, f(x), linewidth=2) 27 | 28 | plt.ylim(ymin=-1.3) 29 | plt.axis("off") 30 | plt.tight_layout() 31 | plt.show() 32 | -------------------------------------------------------------------------------- /advanced/mathematical_optimization/examples/plot_smooth.py: -------------------------------------------------------------------------------- 1 | """ 2 | Smooth vs non-smooth 3 | ===================== 4 | 5 | Draws a figure to explain smooth versus non smooth optimization. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | x = np.linspace(-1.5, 1.5, 101) 12 | 13 | # A smooth function 14 | plt.figure(1, figsize=(3, 2.5)) 15 | plt.clf() 16 | 17 | plt.plot(x, np.sqrt(0.2 + x**2), linewidth=2) 18 | plt.text(-1, 0, "$f$", size=20) 19 | 20 | plt.ylim(ymin=-0.2) 21 | plt.axis("off") 22 | plt.tight_layout() 23 | 24 | # A non-smooth function 25 | plt.figure(2, figsize=(3, 2.5)) 26 | plt.clf() 27 | plt.plot(x, np.abs(x), linewidth=2) 28 | plt.text(-1, 0, "$f$", size=20) 29 | 30 | plt.ylim(ymin=-0.2) 31 | plt.axis("off") 32 | plt.tight_layout() 33 | plt.show() 34 | -------------------------------------------------------------------------------- /advanced/optimizing/demo-prof.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/optimizing/demo-prof.png -------------------------------------------------------------------------------- /advanced/optimizing/demo.py: -------------------------------------------------------------------------------- 1 | # For this example to run, you also need the 'ica.py' file 2 | 3 | import numpy as np 4 | import scipy as sp 5 | 6 | from ica import fastica 7 | 8 | 9 | # @profile # uncomment this line to run with line_profiler 10 | def test(): 11 | rng = np.random.default_rng() 12 | data = rng.random((5000, 100)) 13 | u, s, v = sp.linalg.svd(data) 14 | pca = u[:, :10].T @ data 15 | results = fastica(pca.T, whiten=False) 16 | 17 | 18 | if __name__ == "__main__": 19 | test() 20 | -------------------------------------------------------------------------------- /advanced/optimizing/demo_opt.py: -------------------------------------------------------------------------------- 1 | # For this example to run, you also need the 'ica.py' file 2 | 3 | import numpy as np 4 | import scipy as sp 5 | 6 | from ica import fastica 7 | 8 | 9 | def test(): 10 | rng = np.random.default_rng() 11 | data = rng.random((5000, 100)) 12 | u, s, v = sp.linalg.svd(data, full_matrices=False) 13 | pca = u[:, :10].T @ data 14 | results = fastica(pca.T, whiten=False) 15 | 16 | 17 | if __name__ == "__main__": 18 | test() 19 | -------------------------------------------------------------------------------- /advanced/scipy_sparse/examples/README.txt: -------------------------------------------------------------------------------- 1 | Examples for the SciPy sparse array chapter 2 | ============================================ 3 | -------------------------------------------------------------------------------- /advanced/scipy_sparse/examples/direct_solve.py: -------------------------------------------------------------------------------- 1 | """ 2 | Solve a linear system 3 | ======================= 4 | 5 | Construct a 1000x1000 lil_array and add some values to it, convert it 6 | to CSR format and solve A x = b for x:and solve a linear system with a 7 | direct solver. 8 | """ 9 | 10 | import numpy as np 11 | import scipy as sp 12 | import matplotlib.pyplot as plt 13 | 14 | rng = np.random.default_rng(27446968) 15 | 16 | mtx = sp.sparse.lil_array((1000, 1000), dtype=np.float64) 17 | mtx[0, :100] = rng.random(100) 18 | mtx[1, 100:200] = mtx[[0], :100] 19 | mtx.setdiag(rng.random(1000)) 20 | 21 | plt.clf() 22 | plt.spy(mtx, marker=".", markersize=2) 23 | plt.show() 24 | 25 | mtx = mtx.tocsr() 26 | rhs = rng.random(1000) 27 | 28 | x = sp.sparse.linalg.spsolve(mtx, rhs) 29 | 30 | print(f"residual: {np.linalg.norm(mtx @ x - rhs)!r}") 31 | -------------------------------------------------------------------------------- /advanced/scipy_sparse/examples/pyamg_with_lobpcg.py: -------------------------------------------------------------------------------- 1 | """ 2 | Compute eigenvectors and eigenvalues using a preconditioned eigensolver 3 | ======================================================================= 4 | 5 | In this example Smoothed Aggregation (SA) is used to precondition 6 | the LOBPCG eigensolver on a two-dimensional Poisson problem with 7 | Dirichlet boundary conditions. 8 | """ 9 | 10 | import numpy as np 11 | import scipy as sp 12 | import matplotlib.pyplot as plt 13 | 14 | from pyamg import smoothed_aggregation_solver 15 | from pyamg.gallery import poisson 16 | 17 | N = 100 18 | K = 9 19 | A = poisson((N, N), format="csr") 20 | 21 | # create the AMG hierarchy 22 | ml = smoothed_aggregation_solver(A) 23 | 24 | # initial approximation to the K eigenvectors 25 | X = np.random.random((A.shape[0], K)) 26 | 27 | # preconditioner based on ml 28 | M = ml.aspreconditioner() 29 | 30 | # compute eigenvalues and eigenvectors with LOBPCG 31 | W, V = sp.sparse.linalg.lobpcg(A, X, M=M, tol=1e-8, largest=False) 32 | 33 | 34 | # plot the eigenvectors 35 | plt.figure(figsize=(9, 9)) 36 | 37 | for i in range(K): 38 | plt.subplot(3, 3, i + 1) 39 | plt.title(f"Eigenvector {i}") 40 | plt.pcolor(V[:, i].reshape(N, N)) 41 | plt.axis("equal") 42 | plt.axis("off") 43 | plt.show() 44 | -------------------------------------------------------------------------------- /advanced/scipy_sparse/figures/graph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/scipy_sparse/figures/graph.png -------------------------------------------------------------------------------- /advanced/scipy_sparse/figures/graph_g.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/scipy_sparse/figures/graph_g.png -------------------------------------------------------------------------------- /advanced/scipy_sparse/figures/graph_rcm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/scipy_sparse/figures/graph_rcm.png -------------------------------------------------------------------------------- /advanced/scipy_sparse/figures/lobpcg_eigenvalues.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/advanced/scipy_sparse/figures/lobpcg_eigenvalues.png -------------------------------------------------------------------------------- /advanced/scipy_sparse/index.rst: -------------------------------------------------------------------------------- 1 | Sparse Arrays in SciPy 2 | ====================== 3 | 4 | **Author**: *Robert Cimrman* 5 | 6 | | 7 | 8 | .. toctree:: 9 | :maxdepth: 3 10 | 11 | introduction 12 | storage_schemes 13 | solvers 14 | other_packages 15 | -------------------------------------------------------------------------------- /advanced/scipy_sparse/other_packages.rst: -------------------------------------------------------------------------------- 1 | Other Interesting Packages 2 | ========================== 3 | 4 | * PyAMG 5 | * algebraic multigrid solvers 6 | * https://github.com/pyamg/pyamg 7 | * Pysparse 8 | * own sparse matrix classes 9 | * matrix and eigenvalue problem solvers 10 | * https://pysparse.sourceforge.net/ 11 | -------------------------------------------------------------------------------- /data/LICENCE.txt: -------------------------------------------------------------------------------- 1 | The files listed below have licences differing from the original. 2 | 3 | -------------------------------------------------------------------------- 4 | elephant.png, elephant.ppm.gz: 5 | 6 | Copyright (c) Muhammad Mahdi Karim 7 | 8 | Permission is granted to copy, distribute and/or modify this document 9 | under the terms of the GNU Free Documentation License, Version 1.2 10 | only as published by the Free Software Foundation; with no Invariant 11 | Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the 12 | license is included in the section entitled GNU Free Documentation 13 | License. 14 | -------------------------------------------------------------------------------- /data/MV_HFV_012.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/data/MV_HFV_012.jpg -------------------------------------------------------------------------------- /data/elephant.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/data/elephant.png -------------------------------------------------------------------------------- /data/moonlanding.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/data/moonlanding.png -------------------------------------------------------------------------------- /data/organisms.txt: -------------------------------------------------------------------------------- 1 | ADEME 2 | BRGM 3 | CEA 4 | CEMAGREF 5 | CIRAD 6 | CNES 7 | CNRS 8 | CSTB 9 | IFREMER 10 | INED 11 | INERIS 12 | INRA 13 | INRETS 14 | INRIA 15 | INSERM 16 | IRD 17 | IRSN 18 | LCPC 19 | ONERA 20 | Pasteur 21 | Universites 22 | -------------------------------------------------------------------------------- /data/populations.txt: -------------------------------------------------------------------------------- 1 | # year hare lynx carrot 2 | 1900 30e3 4e3 48300 3 | 1901 47.2e3 6.1e3 48200 4 | 1902 70.2e3 9.8e3 41500 5 | 1903 77.4e3 35.2e3 38200 6 | 1904 36.3e3 59.4e3 40600 7 | 1905 20.6e3 41.7e3 39800 8 | 1906 18.1e3 19e3 38600 9 | 1907 21.4e3 13e3 42300 10 | 1908 22e3 8.3e3 44500 11 | 1909 25.4e3 9.1e3 42100 12 | 1910 27.1e3 7.4e3 46000 13 | 1911 40.3e3 8e3 46800 14 | 1912 57e3 12.3e3 43800 15 | 1913 76.6e3 19.5e3 40900 16 | 1914 52.3e3 45.7e3 39400 17 | 1915 19.5e3 51.1e3 39000 18 | 1916 11.2e3 29.7e3 36700 19 | 1917 7.6e3 15.8e3 41800 20 | 1918 14.6e3 9.7e3 43300 21 | 1919 16.2e3 10.1e3 41300 22 | 1920 24.7e3 8.6e3 47300 23 | -------------------------------------------------------------------------------- /data/species.txt: -------------------------------------------------------------------------------- 1 | # The species in columns of populations.txt 2 | Hare 3 | Lynx 4 | Carrot 5 | -------------------------------------------------------------------------------- /data/test.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/data/test.wav -------------------------------------------------------------------------------- /data/waveform_1.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/data/waveform_1.npy -------------------------------------------------------------------------------- /data/waveform_2.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/data/waveform_2.npy -------------------------------------------------------------------------------- /data/women_percentage.txt: -------------------------------------------------------------------------------- 1 | #2006 2005 2004 2003 2002 2001 2 | 38.2 37.1 37.1 38.1 36.7 39.6 3 | 26.9 18.3 24.4 24.3 24.2 20.9 4 | 26.2 26.2 25.6 24.9 24.4 23.6 5 | 27.4 25.7 25.6 23.9 23.0 21.5 6 | 28.0 26.3 24.4 23.5 22.3 21.8 7 | 28.0 27.0 25.2 24.7 24.5 23.4 8 | 31.9 31.0 30.9 31.0 30.6 29.9 9 | 23.5 23.6 23.6 23.6 23.6 22.3 10 | 26.6 26.1 25.7 23.5 24.8 23.8 11 | 52.9 53.6 53.6 56.3 54.7 44.1 12 | 41.0 27.0 27.0 32.0 31.4 17.6 13 | 40.4 39.7 38.7 36.6 35.7 34.4 14 | 32.1 32.3 32.3 32.2 31.7 30.6 15 | 17.4 18.2 19.1 17.9 18.2 18.5 16 | 50.1 49.8 49.9 50.0 50.6 50.6 17 | 25.2 23.5 24.3 24.3 22.3 19.8 18 | 37.8 34.5 34.1 33.3 30.5 30.5 19 | 16.3 15.7 15.6 15.3 15.1 13.1 20 | 14.8 14.9 14.6 13.7 14.1 14 21 | 51.4 50.2 50.0 47.5 49.2 50.9 22 | 33.5 37.1 32.9 32.6 32.3 32.1 23 | -------------------------------------------------------------------------------- /docutils.conf: -------------------------------------------------------------------------------- 1 | [html writers] 2 | table_style: colwidths-grid 3 | -------------------------------------------------------------------------------- /guide/examples/README.txt: -------------------------------------------------------------------------------- 1 | Examples for the contribution guide 2 | ==================================== 3 | 4 | Note that every example directory needs to have a README.txt 5 | -------------------------------------------------------------------------------- /guide/examples/plot_simple.py: -------------------------------------------------------------------------------- 1 | """ 2 | A simple example 3 | ================= 4 | 5 | """ 6 | 7 | import numpy as np 8 | import matplotlib.pyplot as plt 9 | 10 | X = np.linspace(-np.pi, np.pi, 100) 11 | Y = np.sin(X) 12 | 13 | plt.plot(X, Y, linewidth=2) 14 | plt.show() 15 | -------------------------------------------------------------------------------- /images/cover-2020.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/images/cover-2020.pdf -------------------------------------------------------------------------------- /images/cover-2025.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/images/cover-2025.pdf -------------------------------------------------------------------------------- /images/cover.pdf: -------------------------------------------------------------------------------- 1 | cover-2025.pdf -------------------------------------------------------------------------------- /images/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/images/favicon.ico -------------------------------------------------------------------------------- /images/icon-archive.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /images/icon-github.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /images/icon-pdf.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /images/logo.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/images/logo.pdf -------------------------------------------------------------------------------- /images/no_image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/images/no_image.png -------------------------------------------------------------------------------- /includes/big_toc_css.rst: -------------------------------------------------------------------------------- 1 | :orphan: 2 | 3 | .. 4 | File to ..include in a document with a big table of content, to give 5 | it 'style' 6 | 7 | .. raw:: html 8 | 9 | 44 | -------------------------------------------------------------------------------- /includes/bigger_toc_css.rst: -------------------------------------------------------------------------------- 1 | :orphan: 2 | 3 | .. 4 | File to ..include in a document with a very big table of content, to 5 | give it 'style' 6 | 7 | .. raw:: html 8 | 9 | 60 | -------------------------------------------------------------------------------- /intro/index.rst: -------------------------------------------------------------------------------- 1 | Getting started with Python for science 2 | ======================================= 3 | 4 | This part of the *Scientific Python Lectures* is a self-contained 5 | introduction to everything that is needed to use Python for science, 6 | from the language itself, to numerical computing or plotting. 7 | 8 | | 9 | 10 | 11 | .. include:: ../includes/big_toc_css.rst 12 | :start-line: 1 13 | 14 | .. rst-class:: tune 15 | 16 | .. toctree:: 17 | 18 | intro.rst 19 | language/python_language.rst 20 | numpy/index.rst 21 | matplotlib/index.rst 22 | scipy/index.rst 23 | help/help.rst 24 | -------------------------------------------------------------------------------- /intro/language/demo.py: -------------------------------------------------------------------------------- 1 | "A demo module." 2 | 3 | 4 | def print_b(): 5 | "Prints b." 6 | print("b") 7 | 8 | 9 | def print_a(): 10 | "Prints a." 11 | print("a") 12 | 13 | 14 | c = 2 15 | d = 2 16 | -------------------------------------------------------------------------------- /intro/language/demo2.py: -------------------------------------------------------------------------------- 1 | def print_b(): 2 | "Prints b." 3 | print("b") 4 | 5 | 6 | def print_a(): 7 | "Prints a." 8 | print("a") 9 | 10 | 11 | # print_b() runs on import 12 | print_b() 13 | 14 | if __name__ == "__main__": 15 | # print_a() is only executed when the module is run directly. 16 | print_a() 17 | -------------------------------------------------------------------------------- /intro/language/python-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/language/python-logo.png -------------------------------------------------------------------------------- /intro/matplotlib/examples/README.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | Code samples for Matplotlib 4 | ---------------------------- 5 | 6 | The examples here are only examples relevant to the points raised in this 7 | chapter. The matplotlib documentation comes with a much more exhaustive 8 | `gallery `__. 9 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/exercises/README.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | Code for the chapter's exercises 4 | -------------------------------- 5 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/exercises/plot_exercise_1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Exercise 1 3 | =========== 4 | 5 | Solution of the exercise 1 with matplotlib. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | n = 256 12 | X = np.linspace(-np.pi, np.pi, 256) 13 | C, S = np.cos(X), np.sin(X) 14 | plt.plot(X, C) 15 | plt.plot(X, S) 16 | 17 | plt.show() 18 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/exercises/plot_exercise_2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Exercise 2 3 | =========== 4 | 5 | Exercise 2 with matplotlib. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | # Create a new figure of size 8x6 points, using 100 dots per inch 12 | plt.figure(figsize=(8, 6), dpi=80) 13 | 14 | # Create a new subplot from a grid of 1x1 15 | plt.subplot(111) 16 | 17 | X = np.linspace(-np.pi, np.pi, 256) 18 | C, S = np.cos(X), np.sin(X) 19 | 20 | # Plot cosine using blue color with a continuous line of width 1 (pixels) 21 | plt.plot(X, C, color="blue", linewidth=1.0, linestyle="-") 22 | 23 | # Plot sine using green color with a continuous line of width 1 (pixels) 24 | plt.plot(X, S, color="green", linewidth=1.0, linestyle="-") 25 | 26 | # Set x limits 27 | plt.xlim(-4.0, 4.0) 28 | 29 | # Set x ticks 30 | plt.xticks(np.linspace(-4, 4, 9)) 31 | 32 | # Set y limits 33 | plt.ylim(-1.0, 1.0) 34 | 35 | # Set y ticks 36 | plt.yticks(np.linspace(-1, 1, 5)) 37 | 38 | # Show result on screen 39 | plt.show() 40 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/exercises/plot_exercise_3.py: -------------------------------------------------------------------------------- 1 | """ 2 | Exercise 3 3 | ========== 4 | 5 | Exercise 3 with matplotlib. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | plt.figure(figsize=(8, 5), dpi=80) 12 | plt.subplot(111) 13 | 14 | X = np.linspace(-np.pi, np.pi, 256) 15 | C, S = np.cos(X), np.sin(X) 16 | 17 | plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") 18 | plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") 19 | 20 | plt.xlim(-4.0, 4.0) 21 | plt.xticks(np.linspace(-4, 4, 9)) 22 | 23 | plt.ylim(-1.0, 1.0) 24 | plt.yticks(np.linspace(-1, 1, 5)) 25 | 26 | plt.show() 27 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/exercises/plot_exercise_4.py: -------------------------------------------------------------------------------- 1 | """ 2 | Exercise 4 3 | =========== 4 | 5 | Exercise 4 with matplotlib. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | plt.figure(figsize=(8, 5), dpi=80) 12 | plt.subplot(111) 13 | 14 | X = np.linspace(-np.pi, np.pi, 256) 15 | S = np.sin(X) 16 | C = np.cos(X) 17 | 18 | plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") 19 | plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") 20 | 21 | plt.xlim(X.min() * 1.1, X.max() * 1.1) 22 | plt.ylim(C.min() * 1.1, C.max() * 1.1) 23 | 24 | plt.show() 25 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/exercises/plot_exercise_5.py: -------------------------------------------------------------------------------- 1 | """ 2 | Exercise 5 3 | =========== 4 | 5 | Exercise 5 with matplotlib. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | plt.figure(figsize=(8, 5), dpi=80) 12 | plt.subplot(111) 13 | 14 | X = np.linspace(-np.pi, np.pi, 256) 15 | S = np.sin(X) 16 | C = np.cos(X) 17 | 18 | plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") 19 | plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") 20 | 21 | plt.xlim(X.min() * 1.1, X.max() * 1.1) 22 | plt.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi]) 23 | 24 | plt.ylim(C.min() * 1.1, C.max() * 1.1) 25 | plt.yticks([-1, 0, +1]) 26 | 27 | plt.show() 28 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/exercises/plot_exercise_6.py: -------------------------------------------------------------------------------- 1 | """ 2 | Exercise 6 3 | =========== 4 | 5 | Exercise 6 with matplotlib. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | plt.figure(figsize=(8, 5), dpi=80) 12 | plt.subplot(111) 13 | 14 | X = np.linspace(-np.pi, np.pi, 256) 15 | C = np.cos(X) 16 | S = np.sin(X) 17 | 18 | plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") 19 | plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") 20 | 21 | plt.xlim(X.min() * 1.1, X.max() * 1.1) 22 | plt.xticks( 23 | [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], 24 | [r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"], 25 | ) 26 | 27 | plt.ylim(C.min() * 1.1, C.max() * 1.1) 28 | plt.yticks([-1, 0, +1], [r"$-1$", r"$0$", r"$+1$"]) 29 | 30 | plt.show() 31 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/exercises/plot_exercise_7.py: -------------------------------------------------------------------------------- 1 | """ 2 | Exercise 7 3 | =========== 4 | 5 | Exercise 7 with matplotlib 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | plt.figure(figsize=(8, 5), dpi=80) 12 | plt.subplot(111) 13 | 14 | X = np.linspace(-np.pi, np.pi, 256, endpoint=True) 15 | C = np.cos(X) 16 | S = np.sin(X) 17 | 18 | plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") 19 | plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") 20 | 21 | ax = plt.gca() 22 | ax.spines["right"].set_color("none") 23 | ax.spines["top"].set_color("none") 24 | ax.xaxis.set_ticks_position("bottom") 25 | ax.spines["bottom"].set_position(("data", 0)) 26 | ax.yaxis.set_ticks_position("left") 27 | ax.spines["left"].set_position(("data", 0)) 28 | 29 | plt.xlim(X.min() * 1.1, X.max() * 1.1) 30 | plt.xticks( 31 | [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], 32 | [r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"], 33 | ) 34 | 35 | plt.ylim(C.min() * 1.1, C.max() * 1.1) 36 | plt.yticks([-1, 0, +1], [r"$-1$", r"$0$", r"$+1$"]) 37 | 38 | plt.show() 39 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/exercises/plot_exercise_8.py: -------------------------------------------------------------------------------- 1 | """ 2 | Exercise 8 3 | ========== 4 | 5 | Exercise 8 with matplotlib. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | plt.figure(figsize=(8, 5), dpi=80) 12 | plt.subplot(111) 13 | 14 | X = np.linspace(-np.pi, np.pi, 256, endpoint=True) 15 | C = np.cos(X) 16 | S = np.sin(X) 17 | 18 | plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine") 19 | plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine") 20 | 21 | ax = plt.gca() 22 | ax.spines["right"].set_color("none") 23 | ax.spines["top"].set_color("none") 24 | ax.xaxis.set_ticks_position("bottom") 25 | ax.spines["bottom"].set_position(("data", 0)) 26 | ax.yaxis.set_ticks_position("left") 27 | ax.spines["left"].set_position(("data", 0)) 28 | 29 | plt.xlim(X.min() * 1.1, X.max() * 1.1) 30 | plt.xticks( 31 | [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], 32 | [r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"], 33 | ) 34 | 35 | plt.ylim(C.min() * 1.1, C.max() * 1.1) 36 | plt.yticks([-1, +1], [r"$-1$", r"$+1$"]) 37 | 38 | plt.legend(loc="upper left") 39 | 40 | plt.show() 41 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/options/README.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | Example demoing choices for an option 4 | -------------------------------------- 5 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/options/plot_aliased.py: -------------------------------------------------------------------------------- 1 | """ 2 | Aliased versus anti-aliased 3 | ============================= 4 | 5 | This example demonstrates aliased versus anti-aliased text. 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | 10 | size = 128, 16 11 | dpi = 72.0 12 | figsize = size[0] / float(dpi), size[1] / float(dpi) 13 | fig = plt.figure(figsize=figsize, dpi=dpi) 14 | fig.patch.set_alpha(0) 15 | 16 | plt.axes((0, 0, 1, 1), frameon=False) 17 | 18 | plt.rcParams["text.antialiased"] = False 19 | plt.text(0.5, 0.5, "Aliased", ha="center", va="center") 20 | 21 | plt.xlim(0, 1) 22 | plt.ylim(0, 1) 23 | plt.xticks([]) 24 | plt.yticks([]) 25 | 26 | plt.show() 27 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/options/plot_alpha.py: -------------------------------------------------------------------------------- 1 | """ 2 | Alpha: transparency 3 | =================== 4 | 5 | This example demonstrates using alpha for transparency. 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | 10 | size = 256, 16 11 | dpi = 72.0 12 | figsize = size[0] / float(dpi), size[1] / float(dpi) 13 | fig = plt.figure(figsize=figsize, dpi=dpi) 14 | fig.patch.set_alpha(0) 15 | plt.axes((0, 0.1, 1, 0.8), frameon=False) 16 | 17 | for i in range(1, 11): 18 | plt.axvline(i, linewidth=1, color="blue", alpha=0.25 + 0.75 * i / 10.0) 19 | 20 | plt.xlim(0, 11) 21 | plt.xticks([]) 22 | plt.yticks([]) 23 | plt.show() 24 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/options/plot_antialiased.py: -------------------------------------------------------------------------------- 1 | """ 2 | Aliased versus anti-aliased 3 | ============================= 4 | 5 | The example shows aliased versus anti-aliased text. 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | 10 | size = 128, 16 11 | dpi = 72.0 12 | figsize = size[0] / float(dpi), size[1] / float(dpi) 13 | fig = plt.figure(figsize=figsize, dpi=dpi) 14 | fig.patch.set_alpha(0) 15 | plt.axes((0, 0, 1, 1), frameon=False) 16 | 17 | plt.rcParams["text.antialiased"] = True 18 | plt.text(0.5, 0.5, "Anti-aliased", ha="center", va="center") 19 | 20 | plt.xlim(0, 1) 21 | plt.ylim(0, 1) 22 | plt.xticks([]) 23 | plt.yticks([]) 24 | 25 | plt.show() 26 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/options/plot_color.py: -------------------------------------------------------------------------------- 1 | """ 2 | The colors matplotlib line plots 3 | ================================== 4 | 5 | An example demoing the various colors taken by matplotlib's plot. 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | 10 | size = 256, 16 11 | dpi = 72.0 12 | figsize = size[0] / float(dpi), size[1] / float(dpi) 13 | fig = plt.figure(figsize=figsize, dpi=dpi) 14 | fig.patch.set_alpha(0) 15 | plt.axes((0, 0.1, 1, 0.8), frameon=False) 16 | 17 | for i in range(1, 11): 18 | plt.plot([i, i], [0, 1], lw=1.5) 19 | 20 | plt.xlim(0, 11) 21 | plt.xticks([]) 22 | plt.yticks([]) 23 | plt.show() 24 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/options/plot_colormaps.py: -------------------------------------------------------------------------------- 1 | """ 2 | Colormaps 3 | ========= 4 | 5 | An example plotting the matplotlib colormaps. 6 | """ 7 | 8 | import numpy as np 9 | 10 | import matplotlib 11 | import matplotlib.pyplot as plt 12 | 13 | 14 | plt.rc("text", usetex=False) 15 | a = np.outer(np.arange(0, 1, 0.01), np.ones(10)) 16 | 17 | plt.figure(figsize=(10, 5)) 18 | plt.subplots_adjust(top=0.8, bottom=0.05, left=0.01, right=0.99) 19 | maps = [m for m in matplotlib.colormaps if not m.endswith("_r")] 20 | maps.sort() 21 | l = len(maps) + 1 22 | 23 | for i, m in enumerate(maps): 24 | plt.subplot(1, l, i + 1) 25 | plt.axis("off") 26 | plt.imshow(a, aspect="auto", cmap=plt.get_cmap(m), origin="lower") 27 | plt.title(m, rotation=90, fontsize=10, va="bottom") 28 | 29 | plt.show() 30 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/options/plot_dash_capstyle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Dash capstyle 3 | ============= 4 | 5 | An example demoing the dash capstyle. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | size = 256, 16 12 | dpi = 72.0 13 | figsize = size[0] / float(dpi), size[1] / float(dpi) 14 | fig = plt.figure(figsize=figsize, dpi=dpi) 15 | fig.patch.set_alpha(0) 16 | plt.axes((0, 0, 1, 1), frameon=False) 17 | 18 | plt.plot( 19 | np.arange(4), 20 | np.ones(4), 21 | color="blue", 22 | dashes=[15, 15], 23 | linewidth=8, 24 | dash_capstyle="butt", 25 | ) 26 | 27 | plt.plot( 28 | 5 + np.arange(4), 29 | np.ones(4), 30 | color="blue", 31 | dashes=[15, 15], 32 | linewidth=8, 33 | dash_capstyle="round", 34 | ) 35 | 36 | plt.plot( 37 | 10 + np.arange(4), 38 | np.ones(4), 39 | color="blue", 40 | dashes=[15, 15], 41 | linewidth=8, 42 | dash_capstyle="projecting", 43 | ) 44 | 45 | plt.xlim(0, 14) 46 | plt.xticks([]) 47 | plt.yticks([]) 48 | 49 | plt.show() 50 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/options/plot_dash_joinstyle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Dash join style 3 | ================ 4 | 5 | Example demoing the dash join style. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | size = 256, 16 12 | dpi = 72.0 13 | figsize = size[0] / float(dpi), size[1] / float(dpi) 14 | fig = plt.figure(figsize=figsize, dpi=dpi) 15 | fig.patch.set_alpha(0) 16 | plt.axes((0, 0, 1, 1), frameon=False) 17 | 18 | plt.plot( 19 | np.arange(3), 20 | [0, 1, 0], 21 | color="blue", 22 | dashes=[12, 5], 23 | linewidth=8, 24 | dash_joinstyle="miter", 25 | ) 26 | plt.plot( 27 | 4 + np.arange(3), 28 | [0, 1, 0], 29 | color="blue", 30 | dashes=[12, 5], 31 | linewidth=8, 32 | dash_joinstyle="bevel", 33 | ) 34 | plt.plot( 35 | 8 + np.arange(3), 36 | [0, 1, 0], 37 | color="blue", 38 | dashes=[12, 5], 39 | linewidth=8, 40 | dash_joinstyle="round", 41 | ) 42 | 43 | plt.xlim(0, 12) 44 | plt.ylim(-1, 2) 45 | plt.xticks([]) 46 | plt.yticks([]) 47 | 48 | plt.show() 49 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/options/plot_linestyles.py: -------------------------------------------------------------------------------- 1 | """ 2 | Linestyles 3 | ========== 4 | 5 | Plot the different line styles. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | 12 | def linestyle(ls, i): 13 | X = i * 0.5 * np.ones(11) 14 | Y = np.arange(11) 15 | plt.plot( 16 | X, 17 | Y, 18 | ls, 19 | color=(0.0, 0.0, 1, 1), 20 | lw=3, 21 | ms=8, 22 | mfc=(0.75, 0.75, 1, 1), 23 | mec=(0, 0, 1, 1), 24 | ) 25 | plt.text(0.5 * i, 10.25, ls, rotation=90, fontsize=15, va="bottom") 26 | 27 | 28 | linestyles = [ 29 | "-", 30 | "--", 31 | ":", 32 | "-.", 33 | ".", 34 | ",", 35 | "o", 36 | "^", 37 | "v", 38 | "<", 39 | ">", 40 | "s", 41 | "+", 42 | "x", 43 | "d", 44 | "1", 45 | "2", 46 | "3", 47 | "4", 48 | "h", 49 | "p", 50 | "|", 51 | "_", 52 | "D", 53 | "H", 54 | ] 55 | n_lines = len(linestyles) 56 | 57 | size = 20 * n_lines, 300 58 | dpi = 72.0 59 | figsize = size[0] / float(dpi), size[1] / float(dpi) 60 | fig = plt.figure(figsize=figsize, dpi=dpi) 61 | plt.axes((0, 0.01, 1, 0.9), frameon=False) 62 | 63 | for i, ls in enumerate(linestyles): 64 | linestyle(ls, i) 65 | 66 | plt.xlim(-0.2, 0.2 + 0.5 * n_lines) 67 | plt.xticks([]) 68 | plt.yticks([]) 69 | 70 | plt.show() 71 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/options/plot_linewidth.py: -------------------------------------------------------------------------------- 1 | """ 2 | Linewidth 3 | ========= 4 | 5 | Plot various linewidth with matplotlib. 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | 10 | size = 256, 16 11 | dpi = 72.0 12 | figsize = size[0] / float(dpi), size[1] / float(dpi) 13 | fig = plt.figure(figsize=figsize, dpi=dpi) 14 | fig.patch.set_alpha(0) 15 | plt.axes((0, 0.1, 1, 0.8), frameon=False) 16 | 17 | for i in range(1, 11): 18 | plt.plot([i, i], [0, 1], color="b", lw=i / 2.0) 19 | 20 | plt.xlim(0, 11) 21 | plt.ylim(0, 1) 22 | plt.xticks([]) 23 | plt.yticks([]) 24 | 25 | plt.show() 26 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/options/plot_markers.py: -------------------------------------------------------------------------------- 1 | """ 2 | Markers 3 | ======= 4 | 5 | Show the different markers of matplotlib. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | 12 | def marker(m, i): 13 | X = i * 0.5 * np.ones(11) 14 | Y = np.arange(11) 15 | 16 | plt.plot(X, Y, lw=1, marker=m, ms=10, mfc=(0.75, 0.75, 1, 1), mec=(0, 0, 1, 1)) 17 | plt.text(0.5 * i, 10.25, repr(m), rotation=90, fontsize=15, va="bottom") 18 | 19 | 20 | markers = [ 21 | 0, 22 | 1, 23 | 2, 24 | 3, 25 | 4, 26 | 5, 27 | 6, 28 | 7, 29 | "o", 30 | "h", 31 | "_", 32 | "1", 33 | "2", 34 | "3", 35 | "4", 36 | "8", 37 | "p", 38 | "^", 39 | "v", 40 | "<", 41 | ">", 42 | "|", 43 | "d", 44 | ",", 45 | "+", 46 | "s", 47 | "*", 48 | "|", 49 | "x", 50 | "D", 51 | "H", 52 | ".", 53 | ] 54 | 55 | n_markers = len(markers) 56 | 57 | size = 20 * n_markers, 300 58 | dpi = 72.0 59 | figsize = size[0] / float(dpi), size[1] / float(dpi) 60 | fig = plt.figure(figsize=figsize, dpi=dpi) 61 | plt.axes((0, 0.01, 1, 0.9), frameon=False) 62 | 63 | for i, m in enumerate(markers): 64 | marker(m, i) 65 | 66 | plt.xlim(-0.2, 0.2 + 0.5 * n_markers) 67 | plt.xticks([]) 68 | plt.yticks([]) 69 | 70 | plt.show() 71 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/options/plot_mec.py: -------------------------------------------------------------------------------- 1 | """ 2 | Marker edge color 3 | ================== 4 | 5 | Demo the marker edge color of matplotlib's markers. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | size = 256, 16 12 | dpi = 72.0 13 | figsize = size[0] / float(dpi), size[1] / float(dpi) 14 | fig = plt.figure(figsize=figsize, dpi=dpi) 15 | fig.patch.set_alpha(0) 16 | plt.axes((0, 0, 1, 1), frameon=False) 17 | 18 | rng = np.random.default_rng() 19 | 20 | for i in range(1, 11): 21 | r, g, b = np.random.uniform(0, 1, 3) 22 | plt.plot( 23 | [ 24 | i, 25 | ], 26 | [ 27 | 1, 28 | ], 29 | "s", 30 | markersize=5, 31 | markerfacecolor="w", 32 | markeredgewidth=1.5, 33 | markeredgecolor=(r, g, b, 1), 34 | ) 35 | 36 | plt.xlim(0, 11) 37 | plt.xticks([]) 38 | plt.yticks([]) 39 | 40 | plt.show() 41 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/options/plot_mew.py: -------------------------------------------------------------------------------- 1 | """ 2 | Marker edge width 3 | ================= 4 | 5 | Demo the marker edge widths of matplotlib's markers. 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | 10 | size = 256, 16 11 | dpi = 72.0 12 | figsize = size[0] / float(dpi), size[1] / float(dpi) 13 | fig = plt.figure(figsize=figsize, dpi=dpi) 14 | fig.patch.set_alpha(0) 15 | plt.axes((0, 0, 1, 1), frameon=False) 16 | 17 | for i in range(1, 11): 18 | plt.plot( 19 | [ 20 | i, 21 | ], 22 | [ 23 | 1, 24 | ], 25 | "s", 26 | markersize=5, 27 | markeredgewidth=1 + i / 10.0, 28 | markeredgecolor="k", 29 | markerfacecolor="w", 30 | ) 31 | plt.xlim(0, 11) 32 | plt.xticks([]) 33 | plt.yticks([]) 34 | 35 | plt.show() 36 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/options/plot_mfc.py: -------------------------------------------------------------------------------- 1 | """ 2 | Marker face color 3 | ================== 4 | 5 | Demo the marker face color of matplotlib's markers. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | size = 256, 16 12 | dpi = 72.0 13 | figsize = size[0] / float(dpi), size[1] / float(dpi) 14 | fig = plt.figure(figsize=figsize, dpi=dpi) 15 | fig.patch.set_alpha(0) 16 | plt.axes((0, 0, 1, 1), frameon=False) 17 | 18 | rng = np.random.default_rng() 19 | 20 | for i in range(1, 11): 21 | r, g, b = np.random.uniform(0, 1, 3) 22 | plt.plot( 23 | [ 24 | i, 25 | ], 26 | [ 27 | 1, 28 | ], 29 | "s", 30 | markersize=8, 31 | markerfacecolor=(r, g, b, 1), 32 | markeredgewidth=0.1, 33 | markeredgecolor=(0, 0, 0, 0.5), 34 | ) 35 | plt.xlim(0, 11) 36 | plt.xticks([]) 37 | plt.yticks([]) 38 | plt.show() 39 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/options/plot_ms.py: -------------------------------------------------------------------------------- 1 | """ 2 | Marker size 3 | =========== 4 | 5 | Demo the marker size control in matplotlib. 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | 10 | size = 256, 16 11 | dpi = 72.0 12 | figsize = size[0] / float(dpi), size[1] / float(dpi) 13 | fig = plt.figure(figsize=figsize, dpi=dpi) 14 | fig.patch.set_alpha(0) 15 | plt.axes((0, 0, 1, 1), frameon=False) 16 | 17 | for i in range(1, 11): 18 | plt.plot( 19 | [ 20 | i, 21 | ], 22 | [ 23 | 1, 24 | ], 25 | "s", 26 | markersize=i, 27 | markerfacecolor="w", 28 | markeredgewidth=0.5, 29 | markeredgecolor="k", 30 | ) 31 | 32 | plt.xlim(0, 11) 33 | plt.xticks([]) 34 | plt.yticks([]) 35 | 36 | plt.show() 37 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/options/plot_solid_capstyle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Solid cap style 3 | ================ 4 | 5 | An example demoing the solide cap style in matplotlib. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | size = 256, 16 12 | dpi = 72.0 13 | figsize = size[0] / float(dpi), size[1] / float(dpi) 14 | fig = plt.figure(figsize=figsize, dpi=dpi) 15 | fig.patch.set_alpha(0) 16 | plt.axes((0, 0, 1, 1), frameon=False) 17 | 18 | plt.plot(np.arange(4), np.ones(4), color="blue", linewidth=8, solid_capstyle="butt") 19 | 20 | plt.plot( 21 | 5 + np.arange(4), np.ones(4), color="blue", linewidth=8, solid_capstyle="round" 22 | ) 23 | 24 | plt.plot( 25 | 10 + np.arange(4), 26 | np.ones(4), 27 | color="blue", 28 | linewidth=8, 29 | solid_capstyle="projecting", 30 | ) 31 | 32 | plt.xlim(0, 14) 33 | plt.xticks([]) 34 | plt.yticks([]) 35 | 36 | plt.show() 37 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/options/plot_solid_joinstyle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Solid joint style 3 | ================== 4 | 5 | An example showing the different solid joint styles in matplotlib. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | size = 256, 16 12 | dpi = 72.0 13 | figsize = size[0] / float(dpi), size[1] / float(dpi) 14 | fig = plt.figure(figsize=figsize, dpi=dpi) 15 | fig.patch.set_alpha(0) 16 | plt.axes((0, 0, 1, 1), frameon=False) 17 | 18 | plt.plot(np.arange(3), [0, 1, 0], color="blue", linewidth=8, solid_joinstyle="miter") 19 | plt.plot( 20 | 4 + np.arange(3), [0, 1, 0], color="blue", linewidth=8, solid_joinstyle="bevel" 21 | ) 22 | plt.plot( 23 | 8 + np.arange(3), [0, 1, 0], color="blue", linewidth=8, solid_joinstyle="round" 24 | ) 25 | 26 | plt.xlim(0, 12) 27 | plt.ylim(-1, 2) 28 | plt.xticks([]) 29 | plt.yticks([]) 30 | 31 | plt.show() 32 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_axes-2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Axes 3 | ==== 4 | 5 | This example shows various axes command to position matplotlib axes. 6 | 7 | """ 8 | 9 | import matplotlib.pyplot as plt 10 | 11 | plt.axes((0.1, 0.1, 0.5, 0.5)) 12 | plt.xticks([]) 13 | plt.yticks([]) 14 | plt.text( 15 | 0.1, 0.1, "axes((0.1, 0.1, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5 16 | ) 17 | 18 | plt.axes((0.2, 0.2, 0.5, 0.5)) 19 | plt.xticks([]) 20 | plt.yticks([]) 21 | plt.text( 22 | 0.1, 0.1, "axes((0.2, 0.2, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5 23 | ) 24 | 25 | plt.axes((0.3, 0.3, 0.5, 0.5)) 26 | plt.xticks([]) 27 | plt.yticks([]) 28 | plt.text( 29 | 0.1, 0.1, "axes((0.3, 0.3, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5 30 | ) 31 | 32 | plt.axes((0.4, 0.4, 0.5, 0.5)) 33 | plt.xticks([]) 34 | plt.yticks([]) 35 | plt.text( 36 | 0.1, 0.1, "axes((0.4, 0.4, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5 37 | ) 38 | 39 | plt.show() 40 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_axes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Simple axes example 3 | ==================== 4 | 5 | This example shows a couple of simple usage of axes. 6 | 7 | """ 8 | 9 | import matplotlib.pyplot as plt 10 | 11 | plt.axes((0.1, 0.1, 0.8, 0.8)) 12 | plt.xticks([]) 13 | plt.yticks([]) 14 | plt.text( 15 | 0.6, 0.6, "axes([0.1, 0.1, 0.8, 0.8])", ha="center", va="center", size=20, alpha=0.5 16 | ) 17 | 18 | plt.axes((0.2, 0.2, 0.3, 0.3)) 19 | plt.xticks([]) 20 | plt.yticks([]) 21 | plt.text( 22 | 0.5, 0.5, "axes([0.2, 0.2, 0.3, 0.3])", ha="center", va="center", size=16, alpha=0.5 23 | ) 24 | 25 | plt.show() 26 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_bad.py: -------------------------------------------------------------------------------- 1 | """ 2 | A simple plotting example 3 | ========================== 4 | 5 | A plotting example with a few simple tweaks 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib 10 | 11 | matplotlib.use("Agg") 12 | import matplotlib.pyplot as plt 13 | 14 | fig = plt.figure(figsize=(5, 4), dpi=72) 15 | axes = fig.add_axes((0.01, 0.01, 0.98, 0.98)) 16 | x = np.linspace(0, 2, 200) 17 | y = np.sin(2 * np.pi * x) 18 | plt.plot(x, y, lw=0.25, c="k") 19 | plt.xticks(np.arange(0.0, 2.0, 0.1)) 20 | plt.yticks(np.arange(-1.0, 1.0, 0.1)) 21 | plt.grid() 22 | plt.show() 23 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_bar.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bar plots 3 | ========== 4 | 5 | An example of bar plots with matplotlib. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | n = 12 12 | X = np.arange(n) 13 | rng = np.random.default_rng() 14 | Y1 = (1 - X / n) * rng.uniform(0.5, 1.0, n) 15 | Y2 = (1 - X / n) * rng.uniform(0.5, 1.0, n) 16 | 17 | plt.axes((0.025, 0.025, 0.95, 0.95)) 18 | plt.bar(X, +Y1, facecolor="#9999ff", edgecolor="white") 19 | plt.bar(X, -Y2, facecolor="#ff9999", edgecolor="white") 20 | 21 | for x, y in zip(X, Y1): 22 | plt.text(x, y + 0.05, f"{y:.2f}", ha="center", va="bottom") 23 | 24 | for x, y in zip(X, Y2): 25 | plt.text(x, -y - 0.05, f"{y:.2f}", ha="center", va="top") 26 | 27 | plt.xlim(-0.5, n) 28 | plt.xticks([]) 29 | plt.ylim(-1.25, 1.25) 30 | plt.yticks([]) 31 | 32 | plt.show() 33 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_contour.py: -------------------------------------------------------------------------------- 1 | """ 2 | Displaying the contours of a function 3 | ====================================== 4 | 5 | An example showing how to display the contours of a function with 6 | matplotlib. 7 | """ 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | 12 | 13 | def f(x, y): 14 | return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2) 15 | 16 | 17 | n = 256 18 | x = np.linspace(-3, 3, n) 19 | y = np.linspace(-3, 3, n) 20 | X, Y = np.meshgrid(x, y) 21 | 22 | plt.axes((0.025, 0.025, 0.95, 0.95)) 23 | 24 | plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap="hot") 25 | C = plt.contour(X, Y, f(X, Y), 8, colors="black", linewidths=0.5) 26 | plt.clabel(C, inline=1, fontsize=10) 27 | 28 | plt.xticks([]) 29 | plt.yticks([]) 30 | plt.show() 31 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_good.py: -------------------------------------------------------------------------------- 1 | """ 2 | A simple, good-looking plot 3 | =========================== 4 | 5 | Demoing some simple features of matplotlib 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib 10 | 11 | matplotlib.use("Agg") 12 | import matplotlib.pyplot as plt 13 | 14 | fig = plt.figure(figsize=(5, 4), dpi=72) 15 | axes = fig.add_axes((0.01, 0.01, 0.98, 0.98)) 16 | X = np.linspace(0, 2, 200) 17 | Y = np.sin(2 * np.pi * X) 18 | plt.plot(X, Y, lw=2) 19 | plt.ylim(-1.1, 1.1) 20 | plt.grid() 21 | 22 | plt.show() 23 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_grid.py: -------------------------------------------------------------------------------- 1 | """ 2 | Grid 3 | ==== 4 | 5 | Displaying a grid on the axes in matploblib. 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | from matplotlib import ticker 10 | 11 | ax = plt.axes((0.025, 0.025, 0.95, 0.95)) 12 | 13 | ax.set_xlim(0, 4) 14 | ax.set_ylim(0, 3) 15 | ax.xaxis.set_major_locator(ticker.MultipleLocator(1.0)) 16 | ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.1)) 17 | ax.yaxis.set_major_locator(ticker.MultipleLocator(1.0)) 18 | ax.yaxis.set_minor_locator(ticker.MultipleLocator(0.1)) 19 | ax.grid(which="major", axis="x", linewidth=0.75, linestyle="-", color="0.75") 20 | ax.grid(which="minor", axis="x", linewidth=0.25, linestyle="-", color="0.75") 21 | ax.grid(which="major", axis="y", linewidth=0.75, linestyle="-", color="0.75") 22 | ax.grid(which="minor", axis="y", linewidth=0.25, linestyle="-", color="0.75") 23 | ax.set_xticklabels([]) 24 | ax.set_yticklabels([]) 25 | 26 | plt.show() 27 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_gridspec.py: -------------------------------------------------------------------------------- 1 | """ 2 | GridSpec 3 | ========= 4 | 5 | An example demoing gridspec 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | from matplotlib import gridspec 10 | 11 | plt.figure(figsize=(6, 4)) 12 | G = gridspec.GridSpec(3, 3) 13 | 14 | axes_1 = plt.subplot(G[0, :]) 15 | plt.xticks([]) 16 | plt.yticks([]) 17 | plt.text(0.5, 0.5, "Axes 1", ha="center", va="center", size=24, alpha=0.5) 18 | 19 | axes_2 = plt.subplot(G[1, :-1]) 20 | plt.xticks([]) 21 | plt.yticks([]) 22 | plt.text(0.5, 0.5, "Axes 2", ha="center", va="center", size=24, alpha=0.5) 23 | 24 | axes_3 = plt.subplot(G[1:, -1]) 25 | plt.xticks([]) 26 | plt.yticks([]) 27 | plt.text(0.5, 0.5, "Axes 3", ha="center", va="center", size=24, alpha=0.5) 28 | 29 | axes_4 = plt.subplot(G[-1, 0]) 30 | plt.xticks([]) 31 | plt.yticks([]) 32 | plt.text(0.5, 0.5, "Axes 4", ha="center", va="center", size=24, alpha=0.5) 33 | 34 | axes_5 = plt.subplot(G[-1, -2]) 35 | plt.xticks([]) 36 | plt.yticks([]) 37 | plt.text(0.5, 0.5, "Axes 5", ha="center", va="center", size=24, alpha=0.5) 38 | 39 | plt.tight_layout() 40 | plt.show() 41 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_imshow.py: -------------------------------------------------------------------------------- 1 | """ 2 | Imshow elaborate 3 | ================= 4 | 5 | An example demoing imshow and styling the figure. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | 12 | def f(x, y): 13 | return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2) 14 | 15 | 16 | n = 10 17 | x = np.linspace(-3, 3, int(3.5 * n)) 18 | y = np.linspace(-3, 3, int(3.0 * n)) 19 | X, Y = np.meshgrid(x, y) 20 | Z = f(X, Y) 21 | 22 | plt.axes((0.025, 0.025, 0.95, 0.95)) 23 | plt.imshow(Z, interpolation="nearest", cmap="bone", origin="lower") 24 | plt.colorbar(shrink=0.92) 25 | 26 | plt.xticks([]) 27 | plt.yticks([]) 28 | plt.show() 29 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_multiplot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Subplots 3 | ========= 4 | 5 | Show multiple subplots in matplotlib. 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | 10 | fig = plt.figure() 11 | fig.subplots_adjust(bottom=0.025, left=0.025, top=0.975, right=0.975) 12 | 13 | plt.subplot(2, 1, 1) 14 | plt.xticks([]), plt.yticks([]) 15 | 16 | plt.subplot(2, 3, 4) 17 | plt.xticks([]) 18 | plt.yticks([]) 19 | 20 | plt.subplot(2, 3, 5) 21 | plt.xticks([]) 22 | plt.yticks([]) 23 | 24 | plt.subplot(2, 3, 6) 25 | plt.xticks([]) 26 | plt.yticks([]) 27 | 28 | plt.show() 29 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_pie.py: -------------------------------------------------------------------------------- 1 | """ 2 | Pie chart 3 | ========= 4 | 5 | A simple pie chart example with matplotlib. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | n = 20 12 | Z = np.ones(n) 13 | Z[-1] *= 2 14 | 15 | plt.axes((0.025, 0.025, 0.95, 0.95)) 16 | 17 | plt.pie(Z, explode=Z * 0.05, colors=[f"{i / float(n):f}" for i in range(n)]) 18 | plt.axis("equal") 19 | plt.xticks([]) 20 | plt.yticks() 21 | 22 | plt.show() 23 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_plot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plot and filled plots 3 | ===================== 4 | 5 | Simple example of plots and filling between them with matplotlib. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | n = 256 12 | X = np.linspace(-np.pi, np.pi, n) 13 | Y = np.sin(2 * X) 14 | 15 | plt.axes((0.025, 0.025, 0.95, 0.95)) 16 | 17 | plt.plot(X, Y + 1, color="blue", alpha=1.00) 18 | plt.fill_between(X, 1, Y + 1, color="blue", alpha=0.25) 19 | 20 | plt.plot(X, Y - 1, color="blue", alpha=1.00) 21 | plt.fill_between(X, -1, Y - 1, (Y - 1) > -1, color="blue", alpha=0.25) 22 | plt.fill_between(X, -1, Y - 1, (Y - 1) < -1, color="red", alpha=0.25) 23 | 24 | plt.xlim(-np.pi, np.pi) 25 | plt.xticks([]) 26 | plt.ylim(-2.5, 2.5) 27 | plt.yticks([]) 28 | 29 | plt.show() 30 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_plot3d-2.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3D plotting 3 | ============ 4 | 5 | Demo 3D plotting with matplotlib and style the figure. 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | from mpl_toolkits.mplot3d.axes3d import Axes3D, get_test_data 10 | 11 | ax: Axes3D = plt.figure().add_subplot(projection="3d") 12 | X, Y, Z = get_test_data(0.05) 13 | cset = ax.contourf(X, Y, Z) 14 | ax.clabel(cset, fontsize=9, inline=1) 15 | 16 | plt.xticks([]) 17 | plt.yticks([]) 18 | ax.set_zticks([]) 19 | 20 | 21 | ax.text2D( 22 | -0.05, 23 | 1.05, 24 | " 3D plots \n", 25 | horizontalalignment="left", 26 | verticalalignment="top", 27 | bbox={"facecolor": "white", "alpha": 1.0}, 28 | family="DejaVu Sans", 29 | size="x-large", 30 | transform=plt.gca().transAxes, 31 | ) 32 | 33 | ax.text2D( 34 | -0.05, 35 | 0.975, 36 | " Plot 2D or 3D data", 37 | horizontalalignment="left", 38 | verticalalignment="top", 39 | family="DejaVu Sans", 40 | size="medium", 41 | transform=plt.gca().transAxes, 42 | ) 43 | 44 | plt.show() 45 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_plot3d.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3D plotting 3 | =========== 4 | 5 | A simple example of 3D plotting. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | from mpl_toolkits.mplot3d import Axes3D 11 | 12 | ax: Axes3D = plt.figure().add_subplot(projection="3d") 13 | x = np.arange(-4, 4, 0.25) 14 | y = np.arange(-4, 4, 0.25) 15 | X, Y = np.meshgrid(x, y) 16 | R = np.sqrt(X**2 + Y**2) 17 | Z = np.sin(R) 18 | 19 | ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap="hot") 20 | ax.contourf(X, Y, Z, zdir="z", offset=-2, cmap="hot") 21 | ax.set_zlim(-2, 2) 22 | 23 | plt.show() 24 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_polar.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plotting in polar coordinates 3 | ============================= 4 | 5 | A simple example showing how to plot in polar coordinates with 6 | matplotlib. 7 | """ 8 | 9 | import numpy as np 10 | 11 | import matplotlib 12 | import matplotlib.pyplot as plt 13 | 14 | 15 | jet = matplotlib.colormaps["jet"] 16 | 17 | ax = plt.axes((0.025, 0.025, 0.95, 0.95), polar=True) 18 | 19 | N = 20 20 | theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N) 21 | rng = np.random.default_rng() 22 | radii = 10 * rng.random(N) 23 | width = np.pi / 4 * rng.random(N) 24 | bars = plt.bar(theta, radii, width=width, bottom=0.0) 25 | 26 | for r, bar in zip(radii, bars, strict=True): 27 | bar.set_facecolor(jet(r / 10.0)) 28 | bar.set_alpha(0.5) 29 | 30 | ax.set_xticklabels([]) 31 | ax.set_yticklabels([]) 32 | plt.show() 33 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_quiver.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plotting a vector field: quiver 3 | ================================ 4 | 5 | A simple example showing how to plot a vector field (quiver) with 6 | matplotlib. 7 | """ 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | 12 | n = 8 13 | X, Y = np.mgrid[0:n, 0:n] 14 | T = np.arctan2(Y - n / 2.0, X - n / 2.0) 15 | R = 10 + np.sqrt((Y - n / 2.0) ** 2 + (X - n / 2.0) ** 2) 16 | U, V = R * np.cos(T), R * np.sin(T) 17 | 18 | plt.axes((0.025, 0.025, 0.95, 0.95)) 19 | plt.quiver(X, Y, U, V, R, alpha=0.5) 20 | plt.quiver(X, Y, U, V, edgecolor="k", facecolor="None", linewidth=0.5) 21 | 22 | plt.xlim(-1, n) 23 | plt.xticks([]) 24 | plt.ylim(-1, n) 25 | plt.yticks([]) 26 | 27 | plt.show() 28 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_scatter.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plotting a scatter of points 3 | ============================== 4 | 5 | A simple example showing how to plot a scatter of points with matplotlib. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | n = 1024 12 | rng = np.random.default_rng() 13 | X = rng.normal(0, 1, n) 14 | Y = rng.normal(0, 1, n) 15 | T = np.arctan2(Y, X) 16 | 17 | plt.axes((0.025, 0.025, 0.95, 0.95)) 18 | plt.scatter(X, Y, s=75, c=T, alpha=0.5) 19 | 20 | plt.xlim(-1.5, 1.5) 21 | plt.xticks([]) 22 | plt.ylim(-1.5, 1.5) 23 | plt.yticks([]) 24 | 25 | plt.show() 26 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_subplot-grid.py: -------------------------------------------------------------------------------- 1 | """ 2 | Subplot grid 3 | ============= 4 | 5 | An example showing the subplot grid in matplotlib. 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | 10 | plt.figure(figsize=(6, 4)) 11 | plt.subplot(2, 2, 1) 12 | plt.xticks([]) 13 | plt.yticks([]) 14 | plt.text(0.5, 0.5, "subplot(2,2,1)", ha="center", va="center", size=20, alpha=0.5) 15 | 16 | plt.subplot(2, 2, 2) 17 | plt.xticks([]) 18 | plt.yticks([]) 19 | plt.text(0.5, 0.5, "subplot(2,2,2)", ha="center", va="center", size=20, alpha=0.5) 20 | 21 | plt.subplot(2, 2, 3) 22 | plt.xticks([]) 23 | plt.yticks([]) 24 | 25 | plt.text(0.5, 0.5, "subplot(2,2,3)", ha="center", va="center", size=20, alpha=0.5) 26 | 27 | plt.subplot(2, 2, 4) 28 | plt.xticks([]) 29 | plt.yticks([]) 30 | plt.text(0.5, 0.5, "subplot(2,2,4)", ha="center", va="center", size=20, alpha=0.5) 31 | 32 | plt.tight_layout() 33 | plt.show() 34 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_subplot-horizontal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Horizontal arrangement of subplots 3 | ================================== 4 | 5 | An example showing horizontal arrangement of subplots with matplotlib. 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | 10 | plt.figure(figsize=(6, 4)) 11 | plt.subplot(2, 1, 1) 12 | plt.xticks([]) 13 | plt.yticks([]) 14 | plt.text(0.5, 0.5, "subplot(2,1,1)", ha="center", va="center", size=24, alpha=0.5) 15 | 16 | plt.subplot(2, 1, 2) 17 | plt.xticks([]) 18 | plt.yticks([]) 19 | plt.text(0.5, 0.5, "subplot(2,1,2)", ha="center", va="center", size=24, alpha=0.5) 20 | 21 | plt.tight_layout() 22 | plt.show() 23 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_subplot-vertical.py: -------------------------------------------------------------------------------- 1 | """ 2 | Subplot plot arrangement vertical 3 | ================================== 4 | 5 | An example showing vertical arrangement of subplots with matplotlib. 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | 10 | 11 | plt.figure(figsize=(6, 4)) 12 | plt.subplot(1, 2, 1) 13 | plt.xticks([]) 14 | plt.yticks([]) 15 | plt.text(0.5, 0.5, "subplot(1,2,1)", ha="center", va="center", size=24, alpha=0.5) 16 | 17 | plt.subplot(1, 2, 2) 18 | plt.xticks([]) 19 | plt.yticks([]) 20 | plt.text(0.5, 0.5, "subplot(1,2,2)", ha="center", va="center", size=24, alpha=0.5) 21 | 22 | plt.tight_layout() 23 | plt.show() 24 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_text.py: -------------------------------------------------------------------------------- 1 | """ 2 | Demo text printing 3 | =================== 4 | 5 | A example showing off elaborate text printing with matplotlib. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | 12 | eqs = [] 13 | eqs.append( 14 | 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]$" 15 | ) 16 | eqs.append( 17 | r"$\frac{d\rho}{d t} + \rho \vec{v}\cdot\nabla\vec{v} = -\nabla p + \mu\nabla^2 \vec{v} + \rho \vec{g}$" 18 | ) 19 | eqs.append(r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$") 20 | eqs.append(r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$") 21 | eqs.append(r"$F_G = G\frac{m_1m_2}{r^2}$") 22 | 23 | plt.axes((0.025, 0.025, 0.95, 0.95)) 24 | 25 | rng = np.random.default_rng() 26 | 27 | for i in range(24): 28 | index = rng.integers(0, len(eqs)) 29 | eq = eqs[index] 30 | size = np.random.uniform(12, 32) 31 | x, y = np.random.uniform(0, 1, 2) 32 | alpha = np.random.uniform(0.25, 0.75) 33 | plt.text( 34 | x, 35 | y, 36 | eq, 37 | ha="center", 38 | va="center", 39 | color="#11557c", 40 | alpha=alpha, 41 | transform=plt.gca().transAxes, 42 | fontsize=size, 43 | clip_on=True, 44 | ) 45 | plt.xticks([]) 46 | plt.yticks([]) 47 | 48 | plt.show() 49 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_ugly.py: -------------------------------------------------------------------------------- 1 | """ 2 | A example of plotting not quite right 3 | ====================================== 4 | 5 | An "ugly" example of plotting. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib 10 | 11 | matplotlib.use("Agg") 12 | import matplotlib.pyplot as plt 13 | 14 | matplotlib.rc("grid", color="black", linestyle="-", linewidth=1) 15 | 16 | fig = plt.figure(figsize=(5, 4), dpi=72) 17 | axes = fig.add_axes((0.01, 0.01, 0.98, 0.98), facecolor=".75") 18 | X = np.linspace(0, 2, 40) 19 | Y = np.sin(2 * np.pi * X) 20 | plt.plot(X, Y, lw=0.05, c="b", antialiased=False) 21 | 22 | plt.xticks([]) 23 | plt.yticks(np.arange(-1.0, 1.0, 0.2)) 24 | plt.grid() 25 | ax = plt.gca() 26 | 27 | plt.show() 28 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/pretty_plots/README.txt: -------------------------------------------------------------------------------- 1 | 2 | Code generating the summary figures with a title 3 | ------------------------------------------------- 4 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/pretty_plots/plot_bar_ext.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bar plot advanced 3 | ================== 4 | 5 | An more elaborate bar plot example 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | n = 16 12 | X = np.arange(n) 13 | Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n) 14 | Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n) 15 | plt.bar(X, Y1, facecolor="#9999ff", edgecolor="white") 16 | plt.bar(X, -Y2, facecolor="#ff9999", edgecolor="white") 17 | plt.xlim(-0.5, n) 18 | plt.xticks([]) 19 | plt.ylim(-1, 1) 20 | plt.yticks([]) 21 | 22 | 23 | # Add a title and a box around it 24 | from matplotlib.patches import FancyBboxPatch 25 | 26 | ax = plt.gca() 27 | ax.add_patch( 28 | FancyBboxPatch( 29 | (-0.05, 0.87), 30 | width=0.66, 31 | height=0.165, 32 | clip_on=False, 33 | boxstyle="square,pad=0", 34 | zorder=3, 35 | facecolor="white", 36 | alpha=1.0, 37 | transform=plt.gca().transAxes, 38 | ) 39 | ) 40 | 41 | plt.text( 42 | -0.05, 43 | 1.02, 44 | " Bar Plot: plt.bar(...)\n", 45 | horizontalalignment="left", 46 | verticalalignment="top", 47 | size="xx-large", 48 | transform=plt.gca().transAxes, 49 | ) 50 | 51 | plt.text( 52 | -0.05, 53 | 1.01, 54 | "\n\n Make a bar plot with rectangles ", 55 | horizontalalignment="left", 56 | verticalalignment="top", 57 | size="large", 58 | transform=plt.gca().transAxes, 59 | ) 60 | 61 | plt.show() 62 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/pretty_plots/plot_boxplot_ext.py: -------------------------------------------------------------------------------- 1 | """ 2 | Boxplot with matplotlib 3 | ======================= 4 | 5 | An example of doing box plots with matplotlib 6 | 7 | """ 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | 12 | 13 | fig = plt.figure(figsize=(8, 5)) 14 | axes = plt.subplot(111) 15 | 16 | n = 5 17 | Z = np.zeros((n, 4)) 18 | X = np.linspace(0, 2, n) 19 | rng = np.random.default_rng() 20 | Y = rng.random((n, 4)) 21 | plt.boxplot(Y) 22 | 23 | plt.xticks([]) 24 | plt.yticks([]) 25 | 26 | 27 | # Add a title and a box around it 28 | from matplotlib.patches import FancyBboxPatch 29 | 30 | ax = plt.gca() 31 | ax.add_patch( 32 | FancyBboxPatch( 33 | (-0.05, 0.87), 34 | width=0.66, 35 | height=0.165, 36 | clip_on=False, 37 | boxstyle="square,pad=0", 38 | zorder=3, 39 | facecolor="white", 40 | alpha=1.0, 41 | transform=plt.gca().transAxes, 42 | ) 43 | ) 44 | 45 | plt.text( 46 | -0.05, 47 | 1.02, 48 | " Box Plot: plt.boxplot(...)\n ", 49 | horizontalalignment="left", 50 | verticalalignment="top", 51 | size="xx-large", 52 | transform=axes.transAxes, 53 | ) 54 | 55 | plt.text( 56 | -0.04, 57 | 0.98, 58 | "\n Make a box and whisker plot ", 59 | horizontalalignment="left", 60 | verticalalignment="top", 61 | size="large", 62 | transform=axes.transAxes, 63 | ) 64 | 65 | plt.show() 66 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/pretty_plots/plot_imshow_ext.py: -------------------------------------------------------------------------------- 1 | """ 2 | Imshow demo 3 | ============ 4 | 5 | Demoing imshow 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | 12 | def f(x, y): 13 | return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2) 14 | 15 | 16 | n = 10 17 | x = np.linspace(-3, 3, 8 * n) 18 | y = np.linspace(-3, 3, 6 * n) 19 | X, Y = np.meshgrid(x, y) 20 | Z = f(X, Y) 21 | plt.imshow(Z, interpolation="nearest", cmap="bone", origin="lower") 22 | plt.xticks([]) 23 | plt.yticks([]) 24 | 25 | 26 | # Add a title and a box around it 27 | from matplotlib.patches import FancyBboxPatch 28 | 29 | ax = plt.gca() 30 | ax.add_patch( 31 | FancyBboxPatch( 32 | (-0.05, 0.87), 33 | width=0.66, 34 | height=0.165, 35 | clip_on=False, 36 | boxstyle="square,pad=0", 37 | zorder=3, 38 | facecolor="white", 39 | alpha=1.0, 40 | transform=plt.gca().transAxes, 41 | ) 42 | ) 43 | 44 | plt.text( 45 | -0.05, 46 | 1.02, 47 | " Imshow: plt.imshow(...)\n", 48 | horizontalalignment="left", 49 | verticalalignment="top", 50 | size="xx-large", 51 | transform=plt.gca().transAxes, 52 | ) 53 | 54 | plt.text( 55 | -0.05, 56 | 1.01, 57 | "\n\n Display an image to current axes ", 58 | horizontalalignment="left", 59 | verticalalignment="top", 60 | family="DejaVu Sans", 61 | size="large", 62 | transform=plt.gca().transAxes, 63 | ) 64 | 65 | plt.show() 66 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/pretty_plots/plot_multiplot_ext.py: -------------------------------------------------------------------------------- 1 | """ 2 | Multiple plots vignette 3 | ======================== 4 | 5 | Demo multiple plots and style the figure. 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | 10 | ax = plt.subplot(2, 1, 1) 11 | ax.set_xticklabels([]) 12 | ax.set_yticklabels([]) 13 | 14 | 15 | # Add a title and a box around it 16 | from matplotlib.patches import FancyBboxPatch 17 | 18 | ax = plt.gca() 19 | ax.add_patch( 20 | FancyBboxPatch( 21 | (-0.05, 0.72), 22 | width=0.66, 23 | height=0.34, 24 | clip_on=False, 25 | boxstyle="square,pad=0", 26 | zorder=3, 27 | facecolor="white", 28 | alpha=1.0, 29 | transform=plt.gca().transAxes, 30 | ) 31 | ) 32 | 33 | plt.text( 34 | -0.05, 35 | 1.02, 36 | " Multiplot: plt.subplot(...)\n", 37 | horizontalalignment="left", 38 | verticalalignment="top", 39 | size="xx-large", 40 | transform=ax.transAxes, 41 | ) 42 | plt.text( 43 | -0.05, 44 | 1.01, 45 | "\n\n Plot several plots at once ", 46 | horizontalalignment="left", 47 | verticalalignment="top", 48 | size="large", 49 | transform=ax.transAxes, 50 | ) 51 | 52 | ax = plt.subplot(2, 2, 3) 53 | ax.set_xticklabels([]) 54 | ax.set_yticklabels([]) 55 | 56 | ax = plt.subplot(2, 2, 4) 57 | ax.set_xticklabels([]) 58 | ax.set_yticklabels([]) 59 | 60 | plt.show() 61 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/pretty_plots/plot_pie_ext.py: -------------------------------------------------------------------------------- 1 | """ 2 | Pie chart vignette 3 | =================== 4 | 5 | Demo pie chart with matplotlib and style the figure. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | n = 20 12 | X = np.ones(n) 13 | X[-1] *= 2 14 | plt.pie(X, explode=X * 0.05, colors=[f"{i / float(n):f}" for i in range(n)]) 15 | 16 | fig = plt.gcf() 17 | w, h = fig.get_figwidth(), fig.get_figheight() 18 | r = h / float(w) 19 | 20 | plt.xlim(-1.5, 1.5) 21 | plt.ylim(-1.5 * r, 1.5 * r) 22 | plt.xticks([]) 23 | plt.yticks([]) 24 | 25 | 26 | # Add a title and a box around it 27 | from matplotlib.patches import FancyBboxPatch 28 | 29 | ax = plt.gca() 30 | ax.add_patch( 31 | FancyBboxPatch( 32 | (-0.05, 0.87), 33 | width=0.66, 34 | height=0.165, 35 | clip_on=False, 36 | boxstyle="square,pad=0", 37 | zorder=3, 38 | facecolor="white", 39 | alpha=1.0, 40 | transform=plt.gca().transAxes, 41 | ) 42 | ) 43 | 44 | plt.text( 45 | -0.05, 46 | 1.02, 47 | " Pie Chart: plt.pie(...)\n", 48 | horizontalalignment="left", 49 | verticalalignment="top", 50 | size="xx-large", 51 | transform=plt.gca().transAxes, 52 | ) 53 | 54 | plt.text( 55 | -0.05, 56 | 1.01, 57 | "\n\n Make a pie chart of an array ", 58 | horizontalalignment="left", 59 | verticalalignment="top", 60 | size="large", 61 | transform=plt.gca().transAxes, 62 | ) 63 | 64 | plt.show() 65 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/pretty_plots/plot_plot3d_ext.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3D plotting vignette 3 | ===================== 4 | 5 | Demo 3D plotting with matplotlib and decorate the figure. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | from mpl_toolkits.mplot3d import Axes3D 11 | 12 | x = np.arange(-4, 4, 0.25) 13 | y = np.arange(-4, 4, 0.25) 14 | X, Y = np.meshgrid(x, y) 15 | R = np.sqrt(X**2 + Y**2) 16 | Z = np.sin(R) 17 | 18 | fig = plt.figure() 19 | ax: Axes3D = fig.add_subplot(111, projection="3d") 20 | 21 | ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap="hot") 22 | ax.contourf(X, Y, Z, zdir="z", offset=-2, cmap="hot") 23 | 24 | ax.set_zlim(-2, 2) 25 | plt.xticks([]) 26 | plt.yticks([]) 27 | ax.set_zticks([]) 28 | 29 | ax.text2D( 30 | 0.05, 31 | 0.93, 32 | " 3D plots \n", 33 | horizontalalignment="left", 34 | verticalalignment="top", 35 | size="xx-large", 36 | bbox={"facecolor": "white", "alpha": 1.0}, 37 | transform=plt.gca().transAxes, 38 | ) 39 | 40 | ax.text2D( 41 | 0.05, 42 | 0.87, 43 | " Plot 2D or 3D data", 44 | horizontalalignment="left", 45 | verticalalignment="top", 46 | size="large", 47 | transform=plt.gca().transAxes, 48 | ) 49 | 50 | plt.show() 51 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/pretty_plots/plot_plot_ext.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plot example vignette 3 | ======================= 4 | 5 | An example of plots with matplotlib, and added annotations. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | n = 256 12 | X = np.linspace(0, 2, n) 13 | Y = np.sin(2 * np.pi * X) 14 | 15 | plt.plot(X, Y, lw=2, color="violet") 16 | plt.xlim(-0.2, 2.2) 17 | plt.xticks([]) 18 | plt.ylim(-1.2, 1.2) 19 | plt.yticks([]) 20 | 21 | 22 | # Add a title and a box around it 23 | from matplotlib.patches import FancyBboxPatch 24 | 25 | ax = plt.gca() 26 | ax.add_patch( 27 | FancyBboxPatch( 28 | (-0.05, 0.87), 29 | width=0.66, 30 | height=0.165, 31 | clip_on=False, 32 | boxstyle="square,pad=0", 33 | zorder=3, 34 | facecolor="white", 35 | alpha=1.0, 36 | transform=plt.gca().transAxes, 37 | ) 38 | ) 39 | 40 | plt.text( 41 | -0.05, 42 | 1.02, 43 | " Regular Plot: plt.plot(...)\n", 44 | horizontalalignment="left", 45 | verticalalignment="top", 46 | size="xx-large", 47 | transform=plt.gca().transAxes, 48 | ) 49 | 50 | plt.text( 51 | -0.05, 52 | 1.01, 53 | "\n\n Plot lines and/or markers ", 54 | horizontalalignment="left", 55 | verticalalignment="top", 56 | size="large", 57 | transform=plt.gca().transAxes, 58 | ) 59 | 60 | plt.show() 61 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/pretty_plots/plot_polar_ext.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plotting in polar, decorated 3 | ============================= 4 | 5 | An example showing how to plot in polar coordinate, and some 6 | decorations. 7 | """ 8 | 9 | import numpy as np 10 | 11 | import matplotlib 12 | import matplotlib.pyplot as plt 13 | 14 | 15 | plt.subplot(1, 1, 1, polar=True) 16 | 17 | N = 20 18 | theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N) 19 | rng = np.random.default_rng() 20 | radii = 10 * rng.random(N) 21 | width = np.pi / 4 * rng.random(N) 22 | bars = plt.bar(theta, radii, width=width, bottom=0.0) 23 | jet = matplotlib.colormaps["jet"] 24 | 25 | for r, bar in zip(radii, bars, strict=True): 26 | bar.set_facecolor(jet(r / 10.0)) 27 | bar.set_alpha(0.5) 28 | plt.gca().set_xticklabels([]) 29 | plt.gca().set_yticklabels([]) 30 | 31 | 32 | plt.text( 33 | -0.2, 34 | 1.02, 35 | " Polar Axis \n", 36 | horizontalalignment="left", 37 | verticalalignment="top", 38 | size="xx-large", 39 | bbox={"facecolor": "white", "alpha": 1.0}, 40 | transform=plt.gca().transAxes, 41 | ) 42 | 43 | plt.text( 44 | -0.2, 45 | 1.01, 46 | "\n\n Plot anything using polar axis ", 47 | horizontalalignment="left", 48 | verticalalignment="top", 49 | size="large", 50 | transform=plt.gca().transAxes, 51 | ) 52 | 53 | plt.show() 54 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/pretty_plots/plot_scatter_ext.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plot scatter decorated 3 | ======================= 4 | 5 | An example showing the scatter function, with decorations. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | n = 1024 12 | rng = np.random.default_rng() 13 | X = rng.normal(0, 1, n) 14 | Y = rng.normal(0, 1, n) 15 | 16 | T = np.arctan2(Y, X) 17 | 18 | plt.scatter(X, Y, s=75, c=T, alpha=0.5) 19 | plt.xlim(-1.5, 1.5) 20 | plt.xticks([]) 21 | plt.ylim(-1.5, 1.5) 22 | plt.yticks([]) 23 | 24 | 25 | # Add a title and a box around it 26 | from matplotlib.patches import FancyBboxPatch 27 | 28 | ax = plt.gca() 29 | ax.add_patch( 30 | FancyBboxPatch( 31 | (-0.05, 0.87), 32 | width=0.66, 33 | height=0.165, 34 | clip_on=False, 35 | boxstyle="square,pad=0", 36 | zorder=3, 37 | facecolor="white", 38 | alpha=1.0, 39 | transform=plt.gca().transAxes, 40 | ) 41 | ) 42 | 43 | plt.text( 44 | -0.05, 45 | 1.02, 46 | " Scatter Plot: plt.scatter(...)\n", 47 | horizontalalignment="left", 48 | verticalalignment="top", 49 | size="xx-large", 50 | transform=plt.gca().transAxes, 51 | ) 52 | 53 | plt.text( 54 | -0.05, 55 | 1.01, 56 | "\n\n Make a scatter plot of x versus y ", 57 | horizontalalignment="left", 58 | verticalalignment="top", 59 | size="large", 60 | transform=plt.gca().transAxes, 61 | ) 62 | 63 | plt.show() 64 | -------------------------------------------------------------------------------- /intro/numpy/data: -------------------------------------------------------------------------------- 1 | ../../data/ -------------------------------------------------------------------------------- /intro/numpy/examples/README.txt: -------------------------------------------------------------------------------- 1 | Full code examples for the numpy chapter 2 | ---------------------------------------- 3 | -------------------------------------------------------------------------------- /intro/numpy/examples/plot_basic1dplot.py: -------------------------------------------------------------------------------- 1 | """ 2 | 1D plotting 3 | =========== 4 | 5 | Plot a basic 1D figure 6 | 7 | """ 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | 12 | x = np.linspace(0, 3, 20) 13 | y = np.linspace(0, 9, 20) 14 | plt.plot(x, y) 15 | plt.plot(x, y, "o") 16 | plt.show() 17 | -------------------------------------------------------------------------------- /intro/numpy/examples/plot_basic2dplot.py: -------------------------------------------------------------------------------- 1 | """ 2 | 2D plotting 3 | =========== 4 | 5 | Plot a basic 2D figure 6 | 7 | """ 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | 12 | rng = np.random.default_rng() 13 | image = rng.random((30, 30)) 14 | plt.imshow(image, cmap="hot") 15 | plt.colorbar() 16 | plt.show() 17 | -------------------------------------------------------------------------------- /intro/numpy/examples/plot_chebyfit.py: -------------------------------------------------------------------------------- 1 | """ 2 | Fitting in Chebyshev basis 3 | ========================== 4 | 5 | Plot noisy data and their polynomial fit in a Chebyshev basis 6 | 7 | """ 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | 12 | rng = np.random.default_rng(27446968) 13 | 14 | x = np.linspace(-1, 1, 2000) 15 | y = np.cos(x) + 0.3 * rng.random(2000) 16 | p = np.polynomial.Chebyshev.fit(x, y, 90) 17 | 18 | plt.plot(x, y, "r.") 19 | plt.plot(x, p(x), "k-", lw=3) 20 | plt.show() 21 | -------------------------------------------------------------------------------- /intro/numpy/examples/plot_distances.py: -------------------------------------------------------------------------------- 1 | """ 2 | Distances exercise 3 | ================== 4 | 5 | Plot distances in a grid 6 | 7 | """ 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | 12 | x, y = np.arange(5), np.arange(5)[:, np.newaxis] 13 | distance = np.sqrt(x**2 + y**2) 14 | plt.pcolor(distance) 15 | plt.colorbar() 16 | plt.show() 17 | -------------------------------------------------------------------------------- /intro/numpy/examples/plot_elephant.py: -------------------------------------------------------------------------------- 1 | """ 2 | Reading and writing an elephant 3 | =============================== 4 | 5 | Read and write images 6 | 7 | """ 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | 12 | ################################# 13 | # original figure 14 | ################################# 15 | 16 | plt.figure() 17 | img = plt.imread("../../../data/elephant.png") 18 | plt.imshow(img) 19 | 20 | ################################# 21 | # red channel displayed in grey 22 | ################################# 23 | 24 | plt.figure() 25 | img_red = img[:, :, 0] 26 | plt.imshow(img_red, cmap="gray") 27 | 28 | ################################# 29 | # lower resolution 30 | ################################# 31 | 32 | plt.figure() 33 | img_tiny = img[::6, ::6] 34 | plt.imshow(img_tiny, interpolation="nearest") 35 | 36 | plt.show() 37 | -------------------------------------------------------------------------------- /intro/numpy/examples/plot_mandelbrot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Mandelbrot set 3 | ============== 4 | 5 | Compute the Mandelbrot fractal and plot it 6 | 7 | """ 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | from numpy import newaxis 12 | import warnings 13 | 14 | 15 | def compute_mandelbrot(N_max, some_threshold, nx, ny): 16 | # A grid of c-values 17 | x = np.linspace(-2, 1, nx) 18 | y = np.linspace(-1.5, 1.5, ny) 19 | 20 | c = x[:, newaxis] + 1j * y[newaxis, :] 21 | 22 | # Mandelbrot iteration 23 | 24 | z = c 25 | 26 | # The code below overflows in many regions of the x-y grid, suppress 27 | # warnings temporarily 28 | with warnings.catch_warnings(): 29 | warnings.simplefilter("ignore") 30 | for j in range(N_max): 31 | z = z**2 + c 32 | mandelbrot_set = abs(z) < some_threshold 33 | 34 | return mandelbrot_set 35 | 36 | 37 | mandelbrot_set = compute_mandelbrot(50, 50.0, 601, 401) 38 | 39 | plt.imshow(mandelbrot_set.T, extent=(-2, 1, -1.5, 1.5)) 40 | plt.gray() 41 | plt.show() 42 | -------------------------------------------------------------------------------- /intro/numpy/examples/plot_polyfit.py: -------------------------------------------------------------------------------- 1 | """ 2 | Fitting to polynomial 3 | ===================== 4 | 5 | Plot noisy data and their polynomial fit 6 | 7 | """ 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | 12 | rng = np.random.default_rng(27446968) 13 | 14 | x = np.linspace(0, 1, 20) 15 | y = np.cos(x) + 0.3 * rng.random(20) 16 | p = np.poly1d(np.polyfit(x, y, 3)) 17 | 18 | t = np.linspace(0, 1, 200) 19 | plt.plot(x, y, "o", t, p(t), "-") 20 | plt.show() 21 | -------------------------------------------------------------------------------- /intro/numpy/examples/plot_populations.py: -------------------------------------------------------------------------------- 1 | """ 2 | Population exercise 3 | =================== 4 | 5 | Plot populations of hares, lynxes, and carrots 6 | 7 | """ 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | 12 | data = np.loadtxt("../../../data/populations.txt") 13 | year, hares, lynxes, carrots = data.T 14 | 15 | plt.axes((0.2, 0.1, 0.5, 0.8)) 16 | plt.plot(year, hares, year, lynxes, year, carrots) 17 | plt.legend(("Hare", "Lynx", "Carrot"), loc=(1.05, 0.5)) 18 | plt.show() 19 | -------------------------------------------------------------------------------- /intro/numpy/examples/plot_randomwalk.py: -------------------------------------------------------------------------------- 1 | """ 2 | Random walk exercise 3 | ==================== 4 | 5 | Plot distance as a function of time for a random walk 6 | together with the theoretical result 7 | 8 | """ 9 | 10 | import numpy as np 11 | import matplotlib.pyplot as plt 12 | 13 | # We create 1000 realizations with 200 steps each 14 | n_stories = 1000 15 | t_max = 200 16 | 17 | t = np.arange(t_max) 18 | # Steps can be -1 or 1 (note that randint excludes the upper limit) 19 | rng = np.random.default_rng() 20 | steps = 2 * rng.integers(0, 1 + 1, (n_stories, t_max)) - 1 21 | 22 | # The time evolution of the position is obtained by successively 23 | # summing up individual steps. This is done for each of the 24 | # realizations, i.e. along axis 1. 25 | positions = np.cumsum(steps, axis=1) 26 | 27 | # Determine the time evolution of the mean square distance. 28 | sq_distance = positions**2 29 | mean_sq_distance = np.mean(sq_distance, axis=0) 30 | 31 | # Plot the distance d from the origin as a function of time and 32 | # compare with the theoretically expected result where d(t) 33 | # grows as a square root of time t. 34 | plt.figure(figsize=(4, 3)) 35 | plt.plot(t, np.sqrt(mean_sq_distance), "g.", t, np.sqrt(t), "y-") 36 | plt.xlabel(r"$t$") 37 | plt.ylabel(r"$\sqrt{\langle (\delta x)^2 \rangle}$") 38 | plt.tight_layout() 39 | plt.show() 40 | -------------------------------------------------------------------------------- /intro/numpy/gallery.rst: -------------------------------------------------------------------------------- 1 | Full code examples 2 | ================== 3 | 4 | .. include the gallery. Skip the first line to avoid the "orphan" 5 | declaration 6 | 7 | .. include:: auto_examples/index.rst 8 | :start-line: 1 9 | -------------------------------------------------------------------------------- /intro/numpy/images/cpu-cacheline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/numpy/images/cpu-cacheline.png -------------------------------------------------------------------------------- /intro/numpy/images/faces.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/numpy/images/faces.png -------------------------------------------------------------------------------- /intro/numpy/images/markov-chain.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/numpy/images/markov-chain.png -------------------------------------------------------------------------------- /intro/numpy/images/numpy_broadcasting.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/numpy/images/numpy_broadcasting.png -------------------------------------------------------------------------------- /intro/numpy/images/numpy_fancy_indexing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/numpy/images/numpy_fancy_indexing.png -------------------------------------------------------------------------------- /intro/numpy/images/numpy_indexing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/numpy/images/numpy_indexing.png -------------------------------------------------------------------------------- /intro/numpy/images/prime-sieve.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/numpy/images/prime-sieve.png -------------------------------------------------------------------------------- /intro/numpy/images/random_walk.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/numpy/images/random_walk.png -------------------------------------------------------------------------------- /intro/numpy/images/random_walk_schema.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/numpy/images/random_walk_schema.png -------------------------------------------------------------------------------- /intro/numpy/images/reductions.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/numpy/images/reductions.png -------------------------------------------------------------------------------- /intro/numpy/images/route66.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/numpy/images/route66.png -------------------------------------------------------------------------------- /intro/numpy/images/surf.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/numpy/images/surf.png -------------------------------------------------------------------------------- /intro/numpy/images/threefundamental.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/numpy/images/threefundamental.png -------------------------------------------------------------------------------- /intro/numpy/index.rst: -------------------------------------------------------------------------------- 1 | .. _numpy: 2 | 3 | *********************************************** 4 | NumPy: creating and manipulating numerical data 5 | *********************************************** 6 | 7 | **Authors**: *Emmanuelle Gouillart, Didrik Pinte, Gaël Varoquaux, and 8 | Pauli Virtanen* 9 | 10 | .. .. contents:: Chapters contents 11 | :local: 12 | :depth: 4 13 | 14 | This chapter gives an overview of NumPy, the core tool for performant 15 | numerical computing with Python. 16 | 17 | ____ 18 | 19 | .. include:: ../../includes/big_toc_css.rst 20 | :start-line: 1 21 | 22 | .. toctree:: 23 | array_object.rst 24 | operations.rst 25 | elaborate_arrays.rst 26 | advanced_operations.rst 27 | exercises.rst 28 | gallery.rst 29 | -------------------------------------------------------------------------------- /intro/numpy/random_walk.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/numpy/random_walk.png -------------------------------------------------------------------------------- /intro/numpy/random_walk_schema.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/numpy/random_walk_schema.png -------------------------------------------------------------------------------- /intro/numpy/solutions/1_0_prime_sieve.py: -------------------------------------------------------------------------------- 1 | """ 2 | Computing prime numbers with the archimedean sieve. 3 | 4 | (Of course, this is not an optimal way for computing prime numbers...) 5 | 6 | """ 7 | 8 | import numpy as np 9 | 10 | eratosthenes = True 11 | 12 | # maximum number 13 | N = 10000 14 | 15 | # mask for prime numbers 16 | mask = np.ones([N], dtype=bool) 17 | 18 | if not eratosthenes: 19 | # simple prime sieve 20 | mask[:2] = False 21 | for j in range(2, int(np.sqrt(N)) + 1): 22 | mask[j * j :: j] = False 23 | 24 | else: 25 | # Eratosthenes sieve 26 | mask[:2] = False 27 | for j in range(2, int(np.sqrt(N)) + 1): 28 | if mask[j]: 29 | mask[j * j :: j] = False 30 | 31 | # print indices where mask is True 32 | print(np.nonzero(mask)[0]) 33 | -------------------------------------------------------------------------------- /intro/numpy/solutions/1_1_array_creation.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | a = np.ones((4, 4), dtype=int) 4 | a[3, 1] = 6 5 | a[2, 3] = 2 6 | 7 | b = np.zeros((6, 5)) 8 | b[1:] = np.diag(np.arange(2, 7)) 9 | 10 | print(a) 11 | print(b) 12 | -------------------------------------------------------------------------------- /intro/numpy/solutions/1_2_text_data.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | data = np.loadtxt("../../../data/populations.txt") 4 | reduced_data = data[5:, :-1] 5 | np.savetxt("pop2.txt", reduced_data) 6 | -------------------------------------------------------------------------------- /intro/numpy/solutions/1_3_tiling.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | block = np.array([[4, 3], [2, 1]]) 4 | a = np.tile(block, (2, 3)) 5 | 6 | print(a) 7 | -------------------------------------------------------------------------------- /intro/numpy/solutions/2_1_matrix_manipulations.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from numpy import newaxis 3 | 4 | # Part 1. 5 | 6 | a = np.arange(1, 16).reshape(3, -1).T 7 | print(a) 8 | 9 | # Part 2. 10 | -------------------------------------------------------------------------------- /intro/numpy/solutions/2_2_data_statistics.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | data = np.loadtxt("../../../data/populations.txt") 4 | year, hares, lynxes, carrots = data.T 5 | populations = data[:, 1:] 6 | 7 | print(" Hares, Lynxes, Carrots") 8 | print("Mean:", populations.mean(axis=0)) 9 | print("Std:", populations.std(axis=0)) 10 | 11 | j_max_years = np.argmax(populations, axis=0) 12 | print("Max. year:", year[j_max_years]) 13 | 14 | max_species = np.argmax(populations, axis=1) 15 | species = np.array(["Hare", "Lynx", "Carrot"]) 16 | print("Max species:") 17 | print(year) 18 | print(species[max_species]) 19 | 20 | above_50000 = np.any(populations > 50000, axis=1) 21 | print("Any above 50000:", year[above_50000]) 22 | 23 | j_top_2 = np.argsort(populations, axis=0)[:2] 24 | print("Top 2 years with lowest populations for each:") 25 | print(year[j_top_2]) 26 | 27 | hare_grad = np.gradient(hares, 1.0) 28 | print("diff(Hares) vs. Lynxes correlation", np.corrcoef(hare_grad, lynxes)[0, 1]) 29 | 30 | import matplotlib.pyplot as plt 31 | 32 | plt.plot(year, hare_grad, year, -lynxes) 33 | plt.savefig("plot.png") 34 | -------------------------------------------------------------------------------- /intro/numpy/solutions/2_3_crude_integration.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from numpy import newaxis 3 | 4 | 5 | def f(a, b, c): 6 | return a**b - c 7 | 8 | 9 | a = np.linspace(0, 1, 24) 10 | b = np.linspace(0, 1, 12) 11 | c = np.linspace(0, 1, 6) 12 | 13 | samples = f(a[:, newaxis, newaxis], b[newaxis, :, newaxis], c[newaxis, newaxis, :]) 14 | 15 | # or, 16 | # 17 | # a, b, c = np.ogrid[0:1:24j, 0:1:12j, 0:1:6j] 18 | # samples = f(a, b, c) 19 | 20 | integral = samples.mean() 21 | 22 | print("Approximation:", integral) 23 | print("Exact:", np.log(2) - 0.5) 24 | -------------------------------------------------------------------------------- /intro/numpy/solutions/2_4_mandelbrot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Compute the Mandelbrot fractal 3 | """ 4 | 5 | import numpy as np 6 | import matplotlib.pyplot as plt 7 | from numpy import newaxis 8 | 9 | 10 | def compute_mandelbrot(N_max, some_threshold, nx, ny): 11 | # A grid of c-values 12 | x = np.linspace(-2, 1, nx) 13 | y = np.linspace(-1.5, 1.5, ny) 14 | 15 | c = x[:, newaxis] + 1j * y[newaxis, :] 16 | 17 | # Mandelbrot iteration 18 | 19 | z = c 20 | for j in range(N_max): 21 | z = z**2 + c 22 | 23 | mandelbrot_set = abs(z) < some_threshold 24 | 25 | return mandelbrot_set 26 | 27 | 28 | # Save 29 | 30 | mandelbrot_set = compute_mandelbrot(50, 50.0, 601, 401) 31 | 32 | plt.imshow(mandelbrot_set.T, extent=[-2, 1, -1.5, 1.5]) # type: ignore[arg-type] 33 | plt.gray() 34 | plt.savefig("mandelbrot.png") 35 | -------------------------------------------------------------------------------- /intro/numpy/solutions/2_5_markov_chain.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | rng = np.random.default_rng(27446968) 4 | 5 | n_states = 5 6 | n_steps = 50 7 | tolerance = 1e-5 8 | 9 | # Random transition matrix and state vector 10 | P = rng.random(size=(n_states, n_states)) 11 | p = rng.random(n_states) 12 | 13 | # Normalize rows in P 14 | P /= P.sum(axis=1)[:, np.newaxis] 15 | 16 | # Normalize p 17 | p /= p.sum() 18 | 19 | # Take steps 20 | for k in range(n_steps): 21 | p = P.T @ p 22 | 23 | p_50 = p 24 | print(p_50) 25 | 26 | # Compute stationary state 27 | w, v = np.linalg.eig(P.T) 28 | 29 | j_stationary = np.argmin(abs(w - 1.0)) 30 | p_stationary = v[:, j_stationary].real 31 | p_stationary /= p_stationary.sum() 32 | print(p_stationary) 33 | 34 | # Compare 35 | if all(abs(p_50 - p_stationary) < tolerance): 36 | print("Tolerance satisfied in infty-norm") 37 | 38 | if np.linalg.norm(p_50 - p_stationary) < tolerance: 39 | print("Tolerance satisfied in 2-norm") 40 | -------------------------------------------------------------------------------- /intro/numpy/solutions/2_a_call_fortran.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import fortran_module 3 | 4 | 5 | def some_function(input): 6 | """ 7 | Call a Fortran routine, and preserve input shape 8 | """ 9 | input = np.asarray(input) 10 | # fortran_module.some_function() only accepts 1-D arrays! 11 | output = fortran_module.some_function(input.ravel()) 12 | return output.reshape(input.shape) 13 | 14 | 15 | print(some_function(np.array([1, 2, 3]))) 16 | print(some_function(np.array([[1, 2], [3, 4]]))) 17 | -------------------------------------------------------------------------------- /intro/numpy/solutions/2_a_fortran_module.f90: -------------------------------------------------------------------------------- 1 | subroutine some_function(n, a, b) 2 | integer :: n 3 | double precision, dimension(n), intent(in) :: a 4 | double precision, dimension(n), intent(out) :: b 5 | b = a + 1 6 | end subroutine some_function 7 | -------------------------------------------------------------------------------- /intro/scipy/examples/README.txt: -------------------------------------------------------------------------------- 1 | Full code examples for the SciPy chapter 2 | ---------------------------------------- 3 | -------------------------------------------------------------------------------- /intro/scipy/examples/plot_curve_fit.py: -------------------------------------------------------------------------------- 1 | """ 2 | =============== 3 | Curve fitting 4 | =============== 5 | 6 | Demos a simple curve fitting 7 | """ 8 | 9 | ############################################################ 10 | # First generate some data 11 | import numpy as np 12 | 13 | # Seed the random number generator for reproducibility 14 | rng = np.random.default_rng(27446968) 15 | 16 | x_data = np.linspace(-5, 5, num=50) 17 | noise = 0.01 * np.cos(100 * x_data) 18 | a, b = 2.9, 1.5 19 | y_data = a * np.cos(b * x_data) + noise 20 | 21 | # And plot it 22 | import matplotlib.pyplot as plt 23 | 24 | plt.figure(figsize=(6, 4)) 25 | plt.scatter(x_data, y_data) 26 | 27 | ############################################################ 28 | # Now fit a simple sine function to the data 29 | import scipy as sp 30 | 31 | 32 | def test_func(x, a, b, c): 33 | return a * np.sin(b * x + c) 34 | 35 | 36 | params, params_covariance = sp.optimize.curve_fit( 37 | test_func, x_data, y_data, p0=[2, 1, 3] 38 | ) 39 | 40 | print(params) 41 | 42 | ############################################################ 43 | # And plot the resulting curve on the data 44 | 45 | plt.figure(figsize=(6, 4)) 46 | plt.scatter(x_data, y_data, label="Data") 47 | plt.plot(x_data, test_func(x_data, *params), label="Fitted function") 48 | 49 | plt.legend(loc="best") 50 | 51 | plt.show() 52 | -------------------------------------------------------------------------------- /intro/scipy/examples/plot_detrend.py: -------------------------------------------------------------------------------- 1 | """ 2 | =================== 3 | Detrending a signal 4 | =================== 5 | 6 | :func:`scipy.signal.detrend` removes a linear trend. 7 | """ 8 | 9 | ############################################################ 10 | # Generate a random signal with a trend 11 | import numpy as np 12 | 13 | t = np.linspace(0, 5, 100) 14 | rng = np.random.default_rng() 15 | x = t + rng.normal(size=100) 16 | 17 | ############################################################ 18 | # Detrend 19 | import scipy as sp 20 | 21 | x_detrended = sp.signal.detrend(x) 22 | 23 | ############################################################ 24 | # Plot 25 | import matplotlib.pyplot as plt 26 | 27 | plt.figure(figsize=(5, 4)) 28 | plt.plot(t, x, label="x") 29 | plt.plot(t, x_detrended, label="x_detrended") 30 | plt.legend(loc="best") 31 | plt.show() 32 | -------------------------------------------------------------------------------- /intro/scipy/examples/plot_image_filters.py: -------------------------------------------------------------------------------- 1 | """ 2 | ========================= 3 | Plot filtering on images 4 | ========================= 5 | 6 | Demo filtering for denoising of images. 7 | """ 8 | 9 | # Load some data 10 | import scipy as sp 11 | 12 | face = sp.datasets.face(gray=True) 13 | face = face[:512, -512:] # crop out square on right 14 | 15 | # Apply a variety of filters 16 | import matplotlib.pyplot as plt 17 | 18 | import numpy as np 19 | 20 | noisy_face = np.copy(face).astype(float) 21 | rng = np.random.default_rng() 22 | noisy_face += face.std() * 0.5 * rng.standard_normal(face.shape) 23 | blurred_face = sp.ndimage.gaussian_filter(noisy_face, sigma=3) 24 | median_face = sp.ndimage.median_filter(noisy_face, size=5) 25 | wiener_face = sp.signal.wiener(noisy_face, (5, 5)) 26 | 27 | plt.figure(figsize=(12, 3.5)) 28 | plt.subplot(141) 29 | plt.imshow(noisy_face, cmap="gray") 30 | plt.axis("off") 31 | plt.title("noisy") 32 | 33 | plt.subplot(142) 34 | plt.imshow(blurred_face, cmap="gray") 35 | plt.axis("off") 36 | plt.title("Gaussian filter") 37 | 38 | plt.subplot(143) 39 | plt.imshow(median_face, cmap="gray") 40 | plt.axis("off") 41 | plt.title("median filter") 42 | 43 | plt.subplot(144) 44 | plt.imshow(wiener_face, cmap="gray") 45 | plt.title("Wiener filter") 46 | plt.axis("off") 47 | 48 | plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99) 49 | 50 | plt.show() 51 | -------------------------------------------------------------------------------- /intro/scipy/examples/plot_image_transform.py: -------------------------------------------------------------------------------- 1 | """ 2 | ============================================ 3 | Plot geometrical transformations on images 4 | ============================================ 5 | 6 | Demo geometrical transformations of images. 7 | """ 8 | 9 | # Load some data 10 | import scipy as sp 11 | 12 | face = sp.datasets.face(gray=True) 13 | 14 | # Apply a variety of transformations 15 | import matplotlib.pyplot as plt 16 | 17 | shifted_face = sp.ndimage.shift(face, (50, 50)) 18 | shifted_face2 = sp.ndimage.shift(face, (50, 50), mode="nearest") 19 | rotated_face = sp.ndimage.rotate(face, 30) 20 | cropped_face = face[50:-50, 50:-50] 21 | zoomed_face = sp.ndimage.zoom(face, 2) 22 | zoomed_face.shape 23 | 24 | plt.figure(figsize=(15, 3)) 25 | plt.subplot(151) 26 | plt.imshow(shifted_face, cmap="gray") 27 | plt.axis("off") 28 | 29 | plt.subplot(152) 30 | plt.imshow(shifted_face2, cmap="gray") 31 | plt.axis("off") 32 | 33 | plt.subplot(153) 34 | plt.imshow(rotated_face, cmap="gray") 35 | plt.axis("off") 36 | 37 | plt.subplot(154) 38 | plt.imshow(cropped_face, cmap="gray") 39 | plt.axis("off") 40 | 41 | plt.subplot(155) 42 | plt.imshow(zoomed_face, cmap="gray") 43 | plt.axis("off") 44 | 45 | plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99) 46 | 47 | plt.show() 48 | -------------------------------------------------------------------------------- /intro/scipy/examples/plot_mathematical_morpho.py: -------------------------------------------------------------------------------- 1 | """ 2 | ============================= 3 | Demo mathematical morphology 4 | ============================= 5 | 6 | A basic demo of binary opening and closing. 7 | """ 8 | 9 | # Generate some binary data 10 | import numpy as np 11 | 12 | np.random.seed(0) 13 | a = np.zeros((50, 50)) 14 | a[10:-10, 10:-10] = 1 15 | a += 0.25 * np.random.standard_normal(a.shape) 16 | mask = a >= 0.5 17 | 18 | # Apply mathematical morphology 19 | import scipy as sp 20 | 21 | opened_mask = sp.ndimage.binary_opening(mask) 22 | closed_mask = sp.ndimage.binary_closing(opened_mask) 23 | 24 | # Plot 25 | import matplotlib.pyplot as plt 26 | 27 | plt.figure(figsize=(12, 3.5)) 28 | plt.subplot(141) 29 | plt.imshow(a, cmap="gray") 30 | plt.axis("off") 31 | plt.title("a") 32 | 33 | plt.subplot(142) 34 | plt.imshow(mask, cmap="gray") 35 | plt.axis("off") 36 | plt.title("mask") 37 | 38 | plt.subplot(143) 39 | plt.imshow(opened_mask, cmap="gray") 40 | plt.axis("off") 41 | plt.title("opened_mask") 42 | 43 | plt.subplot(144) 44 | plt.imshow(closed_mask, cmap="gray") 45 | plt.title("closed_mask") 46 | plt.axis("off") 47 | 48 | plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99) 49 | 50 | plt.show() 51 | -------------------------------------------------------------------------------- /intro/scipy/examples/plot_normal_distribution.py: -------------------------------------------------------------------------------- 1 | """ 2 | ======================================= 3 | Normal distribution: histogram and PDF 4 | ======================================= 5 | 6 | Explore the normal distribution: a histogram built from samples and the 7 | PDF (probability density function). 8 | """ 9 | 10 | import numpy as np 11 | import scipy as sp 12 | import matplotlib.pyplot as plt 13 | 14 | dist = sp.stats.norm(loc=0, scale=1) # standard normal distribution 15 | sample = dist.rvs(size=100000) # "random variate sample" 16 | plt.hist( 17 | sample, 18 | bins=51, # group the observations into 50 bins 19 | density=True, # normalize the frequencies 20 | label="normalized histogram", 21 | ) 22 | 23 | x = np.linspace(-5, 5) # possible values of the random variable 24 | plt.plot(x, dist.pdf(x), label="PDF") 25 | plt.legend() 26 | plt.show() 27 | -------------------------------------------------------------------------------- /intro/scipy/examples/plot_optimize_example1.py: -------------------------------------------------------------------------------- 1 | """ 2 | ========================================= 3 | Finding the minimum of a smooth function 4 | ========================================= 5 | 6 | Demos various methods to find the minimum of a function. 7 | """ 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | 12 | 13 | def f(x): 14 | return x**2 + 10 * np.sin(x) 15 | 16 | 17 | x = np.arange(-5, 5, 0.1) 18 | plt.plot(x, f(x)) 19 | 20 | ############################################################ 21 | # Now find the minimum with a few methods 22 | import scipy as sp 23 | 24 | # The default (Nelder Mead) 25 | print(sp.optimize.minimize(f, x0=0)) 26 | 27 | ############################################################ 28 | 29 | plt.show() 30 | -------------------------------------------------------------------------------- /intro/scipy/examples/plot_resample.py: -------------------------------------------------------------------------------- 1 | """ 2 | Resample a signal with scipy.signal.resample 3 | ============================================= 4 | 5 | :func:`scipy.signal.resample` uses FFT to resample a 1D signal. 6 | """ 7 | 8 | ############################################################ 9 | # Generate a signal with 100 data point 10 | import numpy as np 11 | 12 | t = np.linspace(0, 5, 100) 13 | x = np.sin(t) 14 | 15 | ############################################################ 16 | # Downsample it by a factor of 4 17 | import scipy as sp 18 | 19 | x_resampled = sp.signal.resample(x, 25) 20 | 21 | ############################################################ 22 | # Plot 23 | import matplotlib.pyplot as plt 24 | 25 | plt.figure(figsize=(5, 4)) 26 | plt.plot(t, x, label="Original signal") 27 | plt.plot(t[::4], x_resampled, "ko", label="Resampled signal") 28 | 29 | plt.legend(loc="best") 30 | plt.show() 31 | -------------------------------------------------------------------------------- /intro/scipy/examples/plot_solve_ivp_damped_spring_mass.py: -------------------------------------------------------------------------------- 1 | """ 2 | ============================================ 3 | Integrate the Damped spring-mass oscillator 4 | ============================================ 5 | 6 | 7 | """ 8 | 9 | import numpy as np 10 | import scipy as sp 11 | import matplotlib.pyplot as plt 12 | 13 | m = 0.5 # kg 14 | k = 4 # N/m 15 | c = 0.4 # N s/m 16 | 17 | zeta = c / (2 * m * np.sqrt(k / m)) 18 | omega = np.sqrt(k / m) 19 | 20 | 21 | def f(t, z, zeta, omega): 22 | return (z[1], -zeta * omega * z[1] - omega**2 * z[0]) 23 | 24 | 25 | t_span = (0, 10) 26 | t_eval = np.linspace(*t_span, 100) 27 | z0 = [1, 0] 28 | res = sp.integrate.solve_ivp( 29 | f, t_span, z0, t_eval=t_eval, args=(zeta, omega), method="LSODA" 30 | ) 31 | 32 | plt.figure(figsize=(4, 3)) 33 | plt.plot(res.t, res.y[0], label="y") 34 | plt.plot(res.t, res.y[1], label="dy/dt") 35 | plt.legend(loc="best") 36 | plt.show() 37 | -------------------------------------------------------------------------------- /intro/scipy/examples/plot_solve_ivp_simple.py: -------------------------------------------------------------------------------- 1 | """ 2 | ========================= 3 | Integrating a simple ODE 4 | ========================= 5 | 6 | Solve the ODE dy/dt = -2y between t = 0..4, with the initial condition 7 | y(t=0) = 1. 8 | """ 9 | 10 | import numpy as np 11 | import scipy as sp 12 | import matplotlib.pyplot as plt 13 | 14 | 15 | def f(t, y): 16 | return -2 * y 17 | 18 | 19 | t_span = (0, 4) # time interval 20 | t_eval = np.linspace(*t_span) # times at which to evaluate `y` 21 | y0 = [ 22 | 1, 23 | ] # initial state 24 | res = sp.integrate.solve_ivp(f, t_span=t_span, y0=y0, t_eval=t_eval) 25 | 26 | plt.figure(figsize=(4, 3)) 27 | plt.plot(res.t, res.y[0]) 28 | plt.xlabel("t") 29 | plt.ylabel("y") 30 | plt.title("Solution of Initial Value Problem") 31 | plt.tight_layout() 32 | plt.show() 33 | -------------------------------------------------------------------------------- /intro/scipy/examples/plot_t_test.py: -------------------------------------------------------------------------------- 1 | """ 2 | ========================================== 3 | Comparing 2 sets of samples from Gaussians 4 | ========================================== 5 | 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | # Generates 2 sets of observations 12 | rng = np.random.default_rng(27446968) 13 | samples1 = rng.normal(0, size=1000) 14 | samples2 = rng.normal(1, size=1000) 15 | 16 | # Compute a histogram of the sample 17 | bins = np.linspace(-4, 4, 30) 18 | histogram1, bins = np.histogram(samples1, bins=bins, density=True) 19 | histogram2, bins = np.histogram(samples2, bins=bins, density=True) 20 | 21 | plt.figure(figsize=(6, 4)) 22 | plt.hist(samples1, bins=bins, density=True, label="Samples 1") # type: ignore[arg-type] 23 | plt.hist(samples2, bins=bins, density=True, label="Samples 2") # type: ignore[arg-type] 24 | plt.legend(loc="best") 25 | plt.show() 26 | -------------------------------------------------------------------------------- /intro/scipy/examples/solutions/README.txt: -------------------------------------------------------------------------------- 1 | Solutions of the exercises for SciPy 2 | .................................... 3 | -------------------------------------------------------------------------------- /intro/scipy/image_processing/MV_HFV_012.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/scipy/image_processing/MV_HFV_012.jpg -------------------------------------------------------------------------------- /intro/scipy/image_processing/exo_histos.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/scipy/image_processing/exo_histos.png -------------------------------------------------------------------------------- /intro/scipy/image_processing/morpho_mat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/scipy/image_processing/morpho_mat.png -------------------------------------------------------------------------------- /intro/scipy/image_processing/sands.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/scipy/image_processing/sands.png -------------------------------------------------------------------------------- /intro/scipy/image_processing/three_phases.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/scipy/image_processing/three_phases.png -------------------------------------------------------------------------------- /intro/scipy/solutions/data.txt: -------------------------------------------------------------------------------- 1 | 10.2 2 | 43.1 3 | 32.6 4 | 32.5 5 | 61.3 6 | 58.2 7 | -------------------------------------------------------------------------------- /intro/scipy/solutions/data_file.py: -------------------------------------------------------------------------------- 1 | """ 2 | =================== 3 | I/O script example 4 | =================== 5 | 6 | Script to read in a column of numbers and calculate the min, max and sum. 7 | 8 | Data is stored in data.txt. 9 | """ 10 | 11 | 12 | def load_data(filename): 13 | fp = open(filename) 14 | data_string = fp.read() 15 | fp.close() 16 | 17 | data = [] 18 | for x in data_string.split(): 19 | # Data is read in as a string. We need to convert it to floats 20 | data.append(float(x)) 21 | 22 | # Could instead use the following one line with list comprehensions! 23 | # data = [float(x) for x in data_string.split()] 24 | return data 25 | 26 | 27 | if __name__ == "__main__": 28 | data = load_data("data.txt") 29 | # Python provides these basic math functions 30 | print(f"min: {min(data):f}") 31 | print(f"max: {max(data):f}") 32 | print(f"sum: {sum(data):f}") 33 | -------------------------------------------------------------------------------- /intro/scipy/solutions/dir_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Script to list all the '.py' files in a directory, in the order of file 3 | name length. 4 | """ 5 | 6 | import os 7 | import sys 8 | 9 | 10 | def filter_and_sort(file_list): 11 | """Out of a list of file names, returns only the ones ending by 12 | '.py', ordered with increasing file name length. 13 | """ 14 | file_list = [filename for filename in file_list if filename.endswith(".py")] 15 | 16 | def key(item): 17 | return len(item) 18 | 19 | file_list.sort(key=key) 20 | return file_list 21 | 22 | 23 | if __name__ == "__main__": 24 | file_list = os.listdir(sys.argv[-1]) 25 | sorted_file_list = filter_and_sort(file_list) 26 | print(sorted_file_list) 27 | -------------------------------------------------------------------------------- /intro/scipy/solutions/path_site.py: -------------------------------------------------------------------------------- 1 | """Script to search the PYTHONPATH for the module site.py""" 2 | 3 | import os 4 | import sys 5 | import glob 6 | 7 | 8 | def find_module(module): 9 | result = [] 10 | # Loop over the list of paths in sys.path 11 | for subdir in sys.path: 12 | # Join the subdir path with the module we're searching for 13 | pth = os.path.join(subdir, module) 14 | # Use glob to test if the pth is exists 15 | res = glob.glob(pth) 16 | # glob returns a list, if it is not empty, the pth exists 17 | if len(res) > 0: 18 | result.append(res) 19 | return result 20 | 21 | 22 | if __name__ == "__main__": 23 | result = find_module("site.py") 24 | print(result) 25 | -------------------------------------------------------------------------------- /intro/scipy/solutions/pi_wallis.py: -------------------------------------------------------------------------------- 1 | """ 2 | The correction for the calculation of pi using the Wallis formula. 3 | """ 4 | 5 | from functools import reduce 6 | 7 | 8 | pi = 3.14159265358979312 9 | 10 | my_pi = 1.0 11 | 12 | for i in range(1, 100000): 13 | my_pi *= 4 * i**2 / (4 * i**2 - 1.0) 14 | 15 | my_pi *= 2 16 | 17 | print(pi) 18 | print(my_pi) 19 | print(abs(pi - my_pi)) 20 | 21 | ############################################################################### 22 | num = 1 23 | den = 1 24 | for i in range(1, 100000): 25 | tmp = 4 * i * i 26 | num *= tmp 27 | den *= tmp - 1 28 | 29 | better_pi = 2 * (num / den) 30 | 31 | print(pi) 32 | print(better_pi) 33 | print(abs(pi - better_pi)) 34 | print(abs(my_pi - better_pi)) 35 | 36 | ############################################################################### 37 | # Solution in a single line using more advanced constructs (reduce, lambda, 38 | # list comprehensions 39 | print( 40 | 2 41 | * reduce( 42 | lambda x, y: x * y, 43 | [float(4 * (i**2)) / ((4 * (i**2)) - 1) for i in range(1, 100000)], 44 | ) 45 | ) 46 | -------------------------------------------------------------------------------- /intro/scipy/solutions/quick_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implement the quick sort algorithm. 3 | """ 4 | 5 | 6 | def qsort(lst): 7 | """Quick sort: returns a sorted copy of the list.""" 8 | if len(lst) <= 1: 9 | return lst 10 | pivot, rest = lst[0], lst[1:] 11 | 12 | # Could use list comprehension: 13 | # less_than = [ lt for lt in rest if lt < pivot ] 14 | 15 | less_than = [] 16 | for lt in rest: 17 | if lt < pivot: 18 | less_than.append(lt) 19 | 20 | # Could use list comprehension: 21 | # greater_equal = [ ge for ge in rest if ge >= pivot ] 22 | 23 | greater_equal = [] 24 | for ge in rest: 25 | if ge >= pivot: 26 | greater_equal.append(ge) 27 | return qsort(less_than) + [pivot] + qsort(greater_equal) 28 | 29 | 30 | # And now check that qsort does sort: 31 | assert qsort(range(10)) == range(10) 32 | assert qsort(range(10)[::-1]) == range(10) 33 | assert qsort([1, 4, 2, 5, 3]) == sorted([1, 4, 2, 5, 3]) 34 | -------------------------------------------------------------------------------- /intro/scipy/solutions/test_dir_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Test the dir_sort logic. 3 | """ 4 | 5 | import dir_sort 6 | 7 | 8 | def test_filter_and_sort(): 9 | # Test that non '.py' files are not filtered. 10 | file_list = ["a", "aaa", "aa", "", "z", "zzzzz"] 11 | file_list2 = dir_sort.filter_and_sort(file_list) 12 | assert len(file_list2) == 0 13 | 14 | # Test that the otuput file list is ordered by length. 15 | file_list = [n + ".py" for n in file_list] 16 | file_list2 = dir_sort.filter_and_sort(file_list) 17 | name1 = file_list2.pop(0) 18 | for name in file_list2: 19 | assert len(name1) <= len(name) 20 | 21 | 22 | if __name__ == "__main__": 23 | test_filter_and_sort() 24 | -------------------------------------------------------------------------------- /intro/scipy/summary-exercises/README.txt: -------------------------------------------------------------------------------- 1 | Examples for the summary exercises 2 | ================================== 3 | -------------------------------------------------------------------------------- /intro/scipy/summary-exercises/examples/README.txt: -------------------------------------------------------------------------------- 1 | Examples for the summary excercices 2 | ==================================== 3 | -------------------------------------------------------------------------------- /intro/scipy/summary-exercises/examples/max-speeds.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/scipy/summary-exercises/examples/max-speeds.npy -------------------------------------------------------------------------------- /intro/scipy/summary-exercises/examples/plot_cumulative_wind_speed_prediction.py: -------------------------------------------------------------------------------- 1 | """ 2 | Cumulative wind speed prediction 3 | ================================ 4 | 5 | Generate the image cumulative-wind-speed-prediction.png 6 | for the interpolate section of scipy.rst. 7 | """ 8 | 9 | import numpy as np 10 | import scipy as sp 11 | import matplotlib.pyplot as plt 12 | 13 | max_speeds = np.load("max-speeds.npy") 14 | years_nb = max_speeds.shape[0] 15 | 16 | cprob = (np.arange(years_nb, dtype=np.float32) + 1) / (years_nb + 1) 17 | sorted_max_speeds = np.sort(max_speeds) 18 | speed_spline = sp.interpolate.UnivariateSpline(cprob, sorted_max_speeds) 19 | nprob = np.linspace(0, 1, 100) 20 | fitted_max_speeds = speed_spline(nprob) 21 | 22 | fifty_prob = 1.0 - 0.02 23 | fifty_wind = speed_spline(fifty_prob) 24 | 25 | plt.figure() 26 | plt.plot(sorted_max_speeds, cprob, "o") 27 | plt.plot(fitted_max_speeds, nprob, "g--") 28 | plt.plot([fifty_wind], [fifty_prob], "o", ms=8.0, mfc="y", mec="y") 29 | plt.text(30, 0.05, rf"$V_{{50}} = {fifty_wind:.2f} \, m/s$") 30 | plt.plot([fifty_wind, fifty_wind], [plt.axis()[2], fifty_prob], "k--") 31 | plt.xlabel("Annual wind speed maxima [$m/s$]") 32 | plt.ylabel("Cumulative probability") 33 | -------------------------------------------------------------------------------- /intro/scipy/summary-exercises/examples/plot_gumbell_wind_speed_prediction.py: -------------------------------------------------------------------------------- 1 | """ 2 | The Gumbell distribution 3 | ========================= 4 | 5 | Generate the exercise results on the Gumbell distribution 6 | """ 7 | 8 | import numpy as np 9 | import scipy as sp 10 | import matplotlib.pyplot as plt 11 | 12 | 13 | def gumbell_dist(arr): 14 | return -np.log(-np.log(arr)) 15 | 16 | 17 | years_nb = 21 18 | wspeeds = np.load("sprog-windspeeds.npy") 19 | max_speeds = np.array([arr.max() for arr in np.array_split(wspeeds, years_nb)]) 20 | sorted_max_speeds = np.sort(max_speeds) 21 | 22 | cprob = (np.arange(years_nb, dtype=np.float32) + 1) / (years_nb + 1) 23 | gprob = gumbell_dist(cprob) 24 | speed_spline = sp.interpolate.UnivariateSpline(gprob, sorted_max_speeds, k=1) 25 | nprob = gumbell_dist(np.linspace(1e-3, 1 - 1e-3, 100)) 26 | fitted_max_speeds = speed_spline(nprob) 27 | 28 | fifty_prob = gumbell_dist(49.0 / 50.0) 29 | fifty_wind = speed_spline(fifty_prob) 30 | 31 | plt.figure() 32 | plt.plot(sorted_max_speeds, gprob, "o") 33 | plt.plot(fitted_max_speeds, nprob, "g--") 34 | plt.plot([fifty_wind], [fifty_prob], "o", ms=8.0, mfc="y", mec="y") 35 | plt.plot([fifty_wind, fifty_wind], [plt.axis()[2], fifty_prob], "k--") 36 | plt.text(35, -1, rf"$V_{{50}} = {fifty_wind:.2f} \, m/s$") 37 | plt.xlabel("Annual wind speed maxima [$m/s$]") 38 | plt.ylabel("Gumbell cumulative probability") 39 | plt.show() 40 | -------------------------------------------------------------------------------- /intro/scipy/summary-exercises/examples/plot_optimize_lidar_complex_data.py: -------------------------------------------------------------------------------- 1 | """ 2 | The lidar system, data (2 of 2 datasets) 3 | ======================================== 4 | 5 | Generate a chart of more complex data recorded by the lidar system 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | waveform_2 = np.load("waveform_2.npy") 12 | 13 | t = np.arange(len(waveform_2)) 14 | 15 | fig, ax = plt.subplots(figsize=(8, 6)) 16 | plt.plot(t, waveform_2) 17 | plt.xlabel("Time [ns]") 18 | plt.ylabel("Amplitude [bins]") 19 | plt.show() 20 | -------------------------------------------------------------------------------- /intro/scipy/summary-exercises/examples/plot_optimize_lidar_complex_data_fit.py: -------------------------------------------------------------------------------- 1 | """ 2 | The lidar system, data and fit (2 of 2 datasets) 3 | ================================================ 4 | 5 | Generate a chart of the data fitted by Gaussian curve 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | import scipy as sp 11 | 12 | 13 | def model(t, coeffs): 14 | return ( 15 | coeffs[0] 16 | + coeffs[1] * np.exp(-(((t - coeffs[2]) / coeffs[3]) ** 2)) 17 | + coeffs[4] * np.exp(-(((t - coeffs[5]) / coeffs[6]) ** 2)) 18 | + coeffs[7] * np.exp(-(((t - coeffs[8]) / coeffs[9]) ** 2)) 19 | ) 20 | 21 | 22 | def residuals(coeffs, y, t): 23 | return y - model(t, coeffs) 24 | 25 | 26 | waveform_2 = np.load("waveform_2.npy") 27 | t = np.arange(len(waveform_2)) 28 | 29 | x0 = np.array([3, 30, 20, 1, 12, 25, 1, 8, 28, 1], dtype=float) 30 | x, flag = sp.optimize.leastsq(residuals, x0, args=(waveform_2, t)) 31 | 32 | fig, ax = plt.subplots(figsize=(8, 6)) 33 | plt.plot(t, waveform_2, t, model(t, x)) 34 | plt.xlabel("Time [ns]") 35 | plt.ylabel("Amplitude [bins]") 36 | plt.legend(["Waveform", "Model"]) 37 | plt.show() 38 | -------------------------------------------------------------------------------- /intro/scipy/summary-exercises/examples/plot_optimize_lidar_data.py: -------------------------------------------------------------------------------- 1 | """ 2 | The lidar system, data (1 of 2 datasets) 3 | ======================================== 4 | 5 | Generate a chart of the data recorded by the lidar system 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | waveform_1 = np.load("waveform_1.npy") 12 | 13 | t = np.arange(len(waveform_1)) 14 | 15 | fig, ax = plt.subplots(figsize=(8, 6)) 16 | plt.plot(t, waveform_1) 17 | plt.xlabel("Time [ns]") 18 | plt.ylabel("Amplitude [bins]") 19 | plt.show() 20 | -------------------------------------------------------------------------------- /intro/scipy/summary-exercises/examples/plot_optimize_lidar_data_fit.py: -------------------------------------------------------------------------------- 1 | """ 2 | The lidar system, data and fit (1 of 2 datasets) 3 | ================================================ 4 | 5 | Generate a chart of the data fitted by Gaussian curve 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | import scipy as sp 11 | 12 | 13 | def model(t, coeffs): 14 | return coeffs[0] + coeffs[1] * np.exp(-(((t - coeffs[2]) / coeffs[3]) ** 2)) 15 | 16 | 17 | def residuals(coeffs, y, t): 18 | return y - model(t, coeffs) 19 | 20 | 21 | waveform_1 = np.load("waveform_1.npy") 22 | t = np.arange(len(waveform_1)) 23 | 24 | x0 = np.array([3, 30, 15, 1], dtype=float) 25 | x, flag = sp.optimize.leastsq(residuals, x0, args=(waveform_1, t)) 26 | 27 | print(x) 28 | 29 | fig, ax = plt.subplots(figsize=(8, 6)) 30 | plt.plot(t, waveform_1, t, model(t, x)) 31 | plt.xlabel("Time [ns]") 32 | plt.ylabel("Amplitude [bins]") 33 | plt.legend(["Waveform", "Model"]) 34 | plt.show() 35 | -------------------------------------------------------------------------------- /intro/scipy/summary-exercises/examples/plot_sprog_annual_maxima.py: -------------------------------------------------------------------------------- 1 | """ 2 | The Gumbell distribution, results 3 | ================================= 4 | 5 | Generate the exercise results on the Gumbell distribution 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | years_nb = 21 12 | wspeeds = np.load("sprog-windspeeds.npy") 13 | max_speeds = np.array([arr.max() for arr in np.array_split(wspeeds, years_nb)]) 14 | 15 | plt.figure() 16 | plt.bar(np.arange(years_nb) + 1, max_speeds) 17 | plt.axis("tight") 18 | plt.xlabel("Year") 19 | plt.ylabel("Annual wind speed maxima [$m/s$]") 20 | -------------------------------------------------------------------------------- /intro/scipy/summary-exercises/examples/sprog-windspeeds.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/scipy/summary-exercises/examples/sprog-windspeeds.npy -------------------------------------------------------------------------------- /intro/scipy/summary-exercises/examples/waveform_1.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/scipy/summary-exercises/examples/waveform_1.npy -------------------------------------------------------------------------------- /intro/scipy/summary-exercises/examples/waveform_2.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/intro/scipy/summary-exercises/examples/waveform_2.npy -------------------------------------------------------------------------------- /matplotlibrc: -------------------------------------------------------------------------------- 1 | # This matplotlibrc file allows the tests to run without trying to access a 2 | # graphical environment 3 | # 4 | # The file is taken in account by matplotlib by setting the environment 5 | # variable MATPLOTLIBRC to this directory, see 6 | # https://matplotlib.org/stable/tutorials/introductory/customizing.html#the-matplotlibrc-file 7 | 8 | backend : Agg 9 | -------------------------------------------------------------------------------- /packages/index.rst: -------------------------------------------------------------------------------- 1 | .. _applications_part: 2 | 3 | Packages and applications 4 | ========================== 5 | 6 | This part of the *Scientific Python Lectures* is dedicated to various 7 | scientific packages useful for extended needs. 8 | 9 | | 10 | 11 | 12 | .. include:: ../includes/big_toc_css.rst 13 | :start-line: 1 14 | 15 | .. rst-class:: tune 16 | 17 | .. toctree:: 18 | :maxdepth: 3 19 | 20 | statistics/index.rst 21 | sympy.rst 22 | scikit-image/index.rst 23 | scikit-learn/index.rst 24 | -------------------------------------------------------------------------------- /packages/scikit-image/examples/README.txt: -------------------------------------------------------------------------------- 1 | Examples for the scikit-image chapter 2 | ====================================== 3 | -------------------------------------------------------------------------------- /packages/scikit-image/examples/plot_boundaries.py: -------------------------------------------------------------------------------- 1 | """ 2 | Segmentation contours 3 | ===================== 4 | 5 | Visualize segmentation contours on original grayscale image. 6 | """ 7 | 8 | from skimage import data, segmentation 9 | from skimage import filters 10 | import matplotlib.pyplot as plt 11 | import numpy as np 12 | 13 | coins = data.coins() 14 | mask = coins > filters.threshold_otsu(coins) 15 | clean_border = segmentation.clear_border(mask).astype(int) 16 | 17 | coins_edges = segmentation.mark_boundaries(coins, clean_border) 18 | 19 | plt.figure(figsize=(8, 3.5)) 20 | plt.subplot(121) 21 | plt.imshow(clean_border, cmap="gray") 22 | plt.axis("off") 23 | plt.subplot(122) 24 | plt.imshow(coins_edges) 25 | plt.axis("off") 26 | 27 | plt.tight_layout() 28 | plt.show() 29 | -------------------------------------------------------------------------------- /packages/scikit-image/examples/plot_camera.py: -------------------------------------------------------------------------------- 1 | """ 2 | Displaying a simple image 3 | ========================= 4 | 5 | Load and display an image 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | from skimage import data 10 | 11 | camera = data.camera() 12 | 13 | 14 | plt.figure(figsize=(4, 4)) 15 | plt.imshow(camera, cmap="gray", interpolation="nearest") 16 | plt.axis("off") 17 | 18 | plt.tight_layout() 19 | plt.show() 20 | -------------------------------------------------------------------------------- /packages/scikit-image/examples/plot_camera_uint.py: -------------------------------------------------------------------------------- 1 | """ 2 | Integers can overflow 3 | ====================== 4 | 5 | An illustration of overflow problem arising when working with integers 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | from skimage import data 10 | 11 | camera = data.camera() 12 | camera_multiply = 3 * camera 13 | 14 | plt.figure(figsize=(8, 4)) 15 | plt.subplot(121) 16 | plt.imshow(camera, cmap="gray", interpolation="nearest") 17 | plt.axis("off") 18 | plt.subplot(122) 19 | plt.imshow(camera_multiply, cmap="gray", interpolation="nearest") 20 | plt.axis("off") 21 | 22 | plt.tight_layout() 23 | plt.show() 24 | -------------------------------------------------------------------------------- /packages/scikit-image/examples/plot_check.py: -------------------------------------------------------------------------------- 1 | """ 2 | Creating an image 3 | ================== 4 | 5 | How to create an image with basic NumPy commands : ``np.zeros``, slicing... 6 | 7 | This examples show how to create a simple checkerboard. 8 | """ 9 | 10 | import numpy as np 11 | import matplotlib.pyplot as plt 12 | 13 | check = np.zeros((8, 8)) 14 | check[::2, 1::2] = 1 15 | check[1::2, ::2] = 1 16 | plt.matshow(check, cmap="gray") 17 | plt.show() 18 | -------------------------------------------------------------------------------- /packages/scikit-image/examples/plot_equalize_hist.py: -------------------------------------------------------------------------------- 1 | """ 2 | Equalizing the histogram of an image 3 | ===================================== 4 | 5 | Histogram equalizing makes images have a uniform histogram. 6 | """ 7 | 8 | from skimage import data, exposure 9 | import matplotlib.pyplot as plt 10 | 11 | camera = data.camera() 12 | camera_equalized = exposure.equalize_hist(camera) 13 | 14 | plt.figure(figsize=(7, 3)) 15 | 16 | plt.subplot(121) 17 | plt.imshow(camera, cmap="gray", interpolation="nearest") 18 | plt.axis("off") 19 | plt.subplot(122) 20 | plt.imshow(camera_equalized, cmap="gray", interpolation="nearest") 21 | plt.axis("off") 22 | plt.tight_layout() 23 | plt.show() 24 | -------------------------------------------------------------------------------- /packages/scikit-image/examples/plot_features.py: -------------------------------------------------------------------------------- 1 | """ 2 | Affine transform 3 | ================= 4 | 5 | Warping and affine transforms of images. 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | 10 | from skimage import data 11 | from skimage.feature import corner_harris, corner_subpix, corner_peaks 12 | from skimage.transform import warp, AffineTransform 13 | 14 | 15 | tform = AffineTransform(scale=(1.3, 1.1), rotation=1, shear=0.7, translation=(210, 50)) 16 | image = warp(data.checkerboard(), tform.inverse, output_shape=(350, 350)) 17 | 18 | coords = corner_peaks(corner_harris(image), min_distance=5) 19 | coords_subpix = corner_subpix(image, coords, window_size=13) 20 | 21 | plt.gray() 22 | plt.imshow(image, interpolation="nearest") 23 | plt.plot(coords_subpix[:, 1], coords_subpix[:, 0], "+r", markersize=15, mew=5) 24 | plt.plot(coords[:, 1], coords[:, 0], ".b", markersize=7) 25 | plt.axis("off") 26 | plt.show() 27 | -------------------------------------------------------------------------------- /packages/scikit-image/examples/plot_filter_coins.py: -------------------------------------------------------------------------------- 1 | """ 2 | Various denoising filters 3 | ========================= 4 | 5 | This example compares several denoising filters available in scikit-image: 6 | a Gaussian filter, a median filter, and total variation denoising. 7 | """ 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | from skimage import data 12 | from skimage import filters 13 | from skimage import restoration 14 | 15 | coins = data.coins() 16 | gaussian_filter_coins = filters.gaussian(coins, sigma=2) 17 | med_filter_coins = filters.median(coins, np.ones((3, 3))) 18 | tv_filter_coins = restoration.denoise_tv_chambolle(coins, weight=0.1) 19 | 20 | plt.figure(figsize=(16, 4)) 21 | plt.subplot(141) 22 | plt.imshow(coins[10:80, 300:370], cmap="gray", interpolation="nearest") 23 | plt.axis("off") 24 | plt.title("Image") 25 | plt.subplot(142) 26 | plt.imshow(gaussian_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest") 27 | plt.axis("off") 28 | plt.title("Gaussian filter") 29 | plt.subplot(143) 30 | plt.imshow(med_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest") 31 | plt.axis("off") 32 | plt.title("Median filter") 33 | plt.subplot(144) 34 | plt.imshow(tv_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest") 35 | plt.axis("off") 36 | plt.title("TV filter") 37 | plt.show() 38 | -------------------------------------------------------------------------------- /packages/scikit-image/examples/plot_labels.py: -------------------------------------------------------------------------------- 1 | """ 2 | Labelling connected components of an image 3 | =========================================== 4 | 5 | This example shows how to label connected components of a binary image, using 6 | the dedicated skimage.measure.label function. 7 | """ 8 | 9 | from skimage import measure 10 | from skimage import filters 11 | import matplotlib.pyplot as plt 12 | import numpy as np 13 | 14 | n = 12 15 | l = 256 16 | rng = np.random.default_rng(27446968) 17 | im = np.zeros((l, l)) 18 | points = l * rng.random((2, n**2)) 19 | im[(points[0]).astype(int), (points[1]).astype(int)] = 1 20 | im = filters.gaussian(im, sigma=l / (4.0 * n)) 21 | blobs = im > 0.7 * im.mean() 22 | 23 | all_labels = measure.label(blobs) 24 | blobs_labels = measure.label(blobs, background=0) 25 | 26 | plt.figure(figsize=(9, 3.5)) 27 | plt.subplot(131) 28 | plt.imshow(blobs, cmap="gray") 29 | plt.axis("off") 30 | plt.subplot(132) 31 | plt.imshow(all_labels, cmap="nipy_spectral") 32 | plt.axis("off") 33 | plt.subplot(133) 34 | plt.imshow(blobs_labels, cmap="nipy_spectral") 35 | plt.axis("off") 36 | 37 | plt.tight_layout() 38 | plt.show() 39 | -------------------------------------------------------------------------------- /packages/scikit-image/examples/plot_sobel.py: -------------------------------------------------------------------------------- 1 | """ 2 | Computing horizontal gradients with the Sobel filter 3 | ===================================================== 4 | 5 | This example illustrates the use of the horizontal Sobel filter, to compute 6 | horizontal gradients. 7 | """ 8 | 9 | from skimage import data 10 | from skimage import filters 11 | import matplotlib.pyplot as plt 12 | 13 | text = data.text() 14 | hsobel_text = filters.sobel_h(text) 15 | 16 | plt.figure(figsize=(12, 3)) 17 | 18 | plt.subplot(121) 19 | plt.imshow(text, cmap="gray", interpolation="nearest") 20 | plt.axis("off") 21 | plt.subplot(122) 22 | plt.imshow(hsobel_text, cmap="nipy_spectral", interpolation="nearest") 23 | plt.axis("off") 24 | plt.tight_layout() 25 | plt.show() 26 | -------------------------------------------------------------------------------- /packages/scikit-image/examples/plot_threshold.py: -------------------------------------------------------------------------------- 1 | """ 2 | Otsu thresholding 3 | ================== 4 | 5 | This example illustrates automatic Otsu thresholding. 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | from skimage import data 10 | from skimage import filters 11 | from skimage import exposure 12 | 13 | camera = data.camera() 14 | val = filters.threshold_otsu(camera) 15 | 16 | hist, bins_center = exposure.histogram(camera) 17 | 18 | plt.figure(figsize=(9, 4)) 19 | plt.subplot(131) 20 | plt.imshow(camera, cmap="gray", interpolation="nearest") 21 | plt.axis("off") 22 | plt.subplot(132) 23 | plt.imshow(camera < val, cmap="gray", interpolation="nearest") 24 | plt.axis("off") 25 | plt.subplot(133) 26 | plt.plot(bins_center, hist, lw=2) 27 | plt.axvline(val, color="k", ls="--") 28 | 29 | plt.tight_layout() 30 | plt.show() 31 | -------------------------------------------------------------------------------- /packages/scikit-image/viewer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/packages/scikit-image/viewer.png -------------------------------------------------------------------------------- /packages/scikit-learn/examples/README.txt: -------------------------------------------------------------------------------- 1 | Examples for the scikit-learn chapter 2 | ====================================== 3 | -------------------------------------------------------------------------------- /packages/scikit-learn/examples/plot_iris_scatter.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plot 2D views of the iris dataset 3 | ================================= 4 | 5 | Plot a simple scatter plot of 2 features of the iris dataset. 6 | 7 | Note that more elaborate visualization of this dataset is detailed 8 | in the :ref:`statistics` chapter. 9 | """ 10 | 11 | # Load the data 12 | from sklearn.datasets import load_iris 13 | 14 | iris = load_iris() 15 | 16 | from matplotlib import ticker 17 | import matplotlib.pyplot as plt 18 | 19 | # The indices of the features that we are plotting 20 | x_index = 0 21 | y_index = 1 22 | 23 | # this formatter will label the colorbar with the correct target names 24 | formatter = ticker.FuncFormatter(lambda i, *args: iris.target_names[int(i)]) 25 | 26 | plt.figure(figsize=(5, 4)) 27 | plt.scatter(iris.data[:, x_index], iris.data[:, y_index], c=iris.target) 28 | plt.colorbar(ticks=[0, 1, 2], format=formatter) 29 | plt.xlabel(iris.feature_names[x_index]) 30 | plt.ylabel(iris.feature_names[y_index]) 31 | 32 | plt.tight_layout() 33 | plt.show() 34 | -------------------------------------------------------------------------------- /packages/scikit-learn/examples/plot_linear_model_cv.py: -------------------------------------------------------------------------------- 1 | """ 2 | ================================================================ 3 | Use the RidgeCV and LassoCV to set the regularization parameter 4 | ================================================================ 5 | 6 | 7 | """ 8 | 9 | ############################################################ 10 | # Load the diabetes dataset 11 | from sklearn.datasets import load_diabetes 12 | 13 | data = load_diabetes() 14 | X, y = data.data, data.target 15 | print(X.shape) 16 | 17 | ############################################################ 18 | # Compute the cross-validation score with the default hyper-parameters 19 | from sklearn.model_selection import cross_val_score 20 | from sklearn.linear_model import Ridge, Lasso 21 | 22 | for Model in [Ridge, Lasso]: 23 | model = Model() 24 | print(f"{Model.__name__}: {cross_val_score(model, X, y).mean()}") 25 | 26 | ############################################################ 27 | # We compute the cross-validation score as a function of alpha, the 28 | # strength of the regularization for Lasso and Ridge 29 | import numpy as np 30 | import matplotlib.pyplot as plt 31 | 32 | alphas = np.logspace(-3, -1, 30) 33 | 34 | plt.figure(figsize=(5, 3)) 35 | 36 | for Model in [Lasso, Ridge]: 37 | scores = [cross_val_score(Model(alpha), X, y, cv=3).mean() for alpha in alphas] 38 | plt.plot(alphas, scores, label=Model.__name__) 39 | 40 | plt.legend(loc="lower left") 41 | plt.xlabel("alpha") 42 | plt.ylabel("cross validation score") 43 | plt.tight_layout() 44 | plt.show() 45 | -------------------------------------------------------------------------------- /packages/scikit-learn/examples/plot_linear_regression.py: -------------------------------------------------------------------------------- 1 | """ 2 | A simple linear regression 3 | =========================== 4 | 5 | """ 6 | 7 | import numpy as np 8 | import matplotlib.pyplot as plt 9 | from sklearn.linear_model import LinearRegression 10 | 11 | # x from 0 to 30 12 | rng = np.random.default_rng() 13 | x = 30 * rng.random((20, 1)) 14 | 15 | # y = a*x + b with noise 16 | y = 0.5 * x + 1.0 + rng.normal(size=x.shape) 17 | 18 | # create a linear regression model 19 | model = LinearRegression() 20 | model.fit(x, y) 21 | 22 | # predict y from the data 23 | x_new = np.linspace(0, 30, 100) 24 | y_new = model.predict(x_new[:, np.newaxis]) 25 | 26 | # plot the results 27 | plt.figure(figsize=(4, 3)) 28 | ax = plt.axes() 29 | ax.scatter(x, y) 30 | ax.plot(x_new, y_new) 31 | 32 | ax.set_xlabel("x") 33 | ax.set_ylabel("y") 34 | 35 | ax.axis("tight") 36 | 37 | 38 | plt.show() 39 | -------------------------------------------------------------------------------- /packages/scikit-learn/examples/plot_measuring_performance.py: -------------------------------------------------------------------------------- 1 | """ 2 | Measuring Decision Tree performance 3 | ==================================== 4 | 5 | Demonstrates overfit when testing on train set. 6 | """ 7 | 8 | ############################################################ 9 | # Get the data 10 | 11 | from sklearn.datasets import fetch_california_housing 12 | 13 | data = fetch_california_housing(as_frame=True) 14 | 15 | ############################################################ 16 | # Train and test a model 17 | from sklearn.tree import DecisionTreeRegressor 18 | 19 | clf = DecisionTreeRegressor().fit(data.data, data.target) 20 | 21 | predicted = clf.predict(data.data) 22 | expected = data.target 23 | 24 | ############################################################ 25 | # Plot predicted as a function of expected 26 | 27 | import matplotlib.pyplot as plt 28 | 29 | plt.figure(figsize=(4, 3)) 30 | plt.scatter(expected, predicted) 31 | plt.plot([0, 5], [0, 5], "--k") 32 | plt.axis("tight") 33 | plt.xlabel("True price ($100k)") 34 | plt.ylabel("Predicted price ($100k)") 35 | plt.tight_layout() 36 | 37 | ############################################################ 38 | # Pretty much no errors! 39 | # 40 | # This is too good to be true: we are testing the model on the train 41 | # data, which is not a measure of generalization. 42 | # 43 | # **The results are not valid** 44 | -------------------------------------------------------------------------------- /packages/scikit-learn/examples/plot_pca.py: -------------------------------------------------------------------------------- 1 | """ 2 | =============== 3 | Demo PCA in 2D 4 | =============== 5 | 6 | """ 7 | 8 | ############################################################ 9 | # Load the iris data 10 | from sklearn import datasets 11 | 12 | iris = datasets.load_iris() 13 | X = iris.data 14 | y = iris.target 15 | 16 | ############################################################ 17 | # Fit a PCA 18 | from sklearn.decomposition import PCA 19 | 20 | pca = PCA(n_components=2, whiten=True) 21 | pca.fit(X) 22 | 23 | ############################################################ 24 | # Project the data in 2D 25 | X_pca = pca.transform(X) 26 | 27 | ############################################################ 28 | # Visualize the data 29 | target_ids = range(len(iris.target_names)) 30 | 31 | import matplotlib.pyplot as plt 32 | 33 | plt.figure(figsize=(6, 5)) 34 | for i, c, label in zip(target_ids, "rgbcmykw", iris.target_names, strict=False): 35 | plt.scatter(X_pca[y == i, 0], X_pca[y == i, 1], c=c, label=label) 36 | plt.legend() 37 | plt.show() 38 | -------------------------------------------------------------------------------- /packages/scikit-learn/examples/plot_separator.py: -------------------------------------------------------------------------------- 1 | """ 2 | Simple picture of the formal problem of machine learning 3 | ========================================================= 4 | 5 | This example generates simple synthetic data points and shows a 6 | separating hyperplane on them. 7 | """ 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | from sklearn.linear_model import SGDClassifier 12 | from sklearn.datasets import make_blobs 13 | 14 | # we create 50 separable synthetic points 15 | X, Y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.60) 16 | 17 | # fit the model 18 | clf = SGDClassifier(loss="hinge", alpha=0.01, fit_intercept=True) 19 | clf.fit(X, Y) 20 | 21 | # plot the line, the points, and the nearest vectors to the plane 22 | xx = np.linspace(-1, 5, 10) 23 | yy = np.linspace(-1, 5, 10) 24 | 25 | X1, X2 = np.meshgrid(xx, yy) 26 | Z = np.empty(X1.shape) 27 | for (i, j), val in np.ndenumerate(X1): 28 | x1 = val 29 | x2 = X2[i, j] 30 | p = clf.decision_function([[x1, x2]]) 31 | Z[i, j] = p[0] 32 | 33 | plt.figure(figsize=(4, 3)) 34 | ax = plt.axes() 35 | ax.contour( 36 | X1, X2, Z, [-1.0, 0.0, 1.0], colors="k", linestyles=["dashed", "solid", "dashed"] 37 | ) 38 | ax.scatter(X[:, 0], X[:, 1], c=Y, cmap="Paired") 39 | 40 | ax.axis("tight") 41 | 42 | 43 | plt.show() 44 | -------------------------------------------------------------------------------- /packages/scikit-learn/images/Virginia_Iris.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/packages/scikit-learn/images/Virginia_Iris.png -------------------------------------------------------------------------------- /packages/scikit-learn/images/iris_setosa.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/packages/scikit-learn/images/iris_setosa.jpg -------------------------------------------------------------------------------- /packages/scikit-learn/images/iris_versicolor.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/packages/scikit-learn/images/iris_versicolor.jpg -------------------------------------------------------------------------------- /packages/scikit-learn/images/iris_virginica.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/packages/scikit-learn/images/iris_virginica.jpg -------------------------------------------------------------------------------- /packages/scikit-learn/images/scikit-learn-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/packages/scikit-learn/images/scikit-learn-logo.png -------------------------------------------------------------------------------- /packages/statistics/examples/README.txt: -------------------------------------------------------------------------------- 1 | Full code for the figures 2 | ========================== 3 | 4 | Code examples for the statistics chapter. 5 | -------------------------------------------------------------------------------- /packages/statistics/examples/plot_paired_boxplots.py: -------------------------------------------------------------------------------- 1 | """ 2 | Boxplots and paired differences 3 | ================================================= 4 | 5 | Plot boxplots for FSIQ, PIQ, and the paired difference between the two: 6 | while the spread (error bars) for FSIQ and PIQ are very large, there is a 7 | systematic (common) effect due to the subjects. This effect is cancelled 8 | out in the difference and the spread of the difference ("paired" by 9 | subject) is much smaller than the spread of the individual measures. 10 | 11 | """ 12 | 13 | import pandas 14 | 15 | import matplotlib.pyplot as plt 16 | 17 | data = pandas.read_csv("brain_size.csv", sep=";", na_values=".") 18 | 19 | # Box plot of FSIQ and PIQ (different measures od IQ) 20 | plt.figure(figsize=(4, 3)) 21 | data.boxplot(column=["FSIQ", "PIQ"]) 22 | 23 | # Boxplot of the difference 24 | plt.figure(figsize=(4, 3)) 25 | plt.boxplot(data["FSIQ"] - data["PIQ"]) 26 | plt.xticks((1,), ("FSIQ - PIQ",)) 27 | 28 | plt.show() 29 | -------------------------------------------------------------------------------- /packages/statistics/examples/plot_pandas.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plotting simple quantities of a pandas dataframe 3 | ================================================= 4 | 5 | This example loads from a CSV file data with mixed numerical and 6 | categorical entries, and plots a few quantities, separately for females 7 | and males, thanks to the pandas integrated plotting tool (that uses 8 | matplotlib behind the scene). 9 | 10 | See http://pandas.pydata.org/pandas-docs/stable/visualization.html 11 | """ 12 | 13 | import pandas 14 | 15 | data = pandas.read_csv("brain_size.csv", sep=";", na_values=".") 16 | 17 | # Box plots of different columns for each gender 18 | groupby_gender = data.groupby("Gender") 19 | groupby_gender.boxplot(column=["FSIQ", "VIQ", "PIQ"]) 20 | 21 | from pandas import plotting 22 | 23 | # Scatter matrices for different columns 24 | plotting.scatter_matrix(data[["Weight", "Height", "MRI_Count"]]) 25 | plotting.scatter_matrix(data[["PIQ", "VIQ", "FSIQ"]]) 26 | 27 | import matplotlib.pyplot as plt 28 | 29 | plt.show() 30 | -------------------------------------------------------------------------------- /packages/statistics/examples/solutions/README.txt: -------------------------------------------------------------------------------- 1 | Solutions to this chapter's exercises 2 | ====================================== 3 | -------------------------------------------------------------------------------- /packages/statistics/two_sided.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/packages/statistics/two_sided.png -------------------------------------------------------------------------------- /pyximages/README.md: -------------------------------------------------------------------------------- 1 | # Content of directory pyximages 2 | 3 | This directory contains files related to schematic drawings in the 4 | Scientific Python Lectures which cannot be produced by means of matplotlib in a simple way 5 | and for which no source exists in the repository so far. For each image, a 6 | Python source using PyX, a bitmap image for the HTML version, and a PDF 7 | image for the PDF version of the lectures are present. 8 | 9 | The Python source requires the pip installable PyX package and a TeX 10 | installation. The image sources should compile with PyX version 0.14+. Note 11 | that Python 3 requires at least PyX version 0.13. 12 | 13 | The source development of PyX is hosted on [Github](https://github.com/pyx-project/pyx) 14 | and the documentation can be found on the [PyX project page](https://pyx-project.org/). 15 | -------------------------------------------------------------------------------- /pyximages/numpy_fancy_indexing.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/pyximages/numpy_fancy_indexing.pdf -------------------------------------------------------------------------------- /pyximages/numpy_fancy_indexing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/pyximages/numpy_fancy_indexing.png -------------------------------------------------------------------------------- /pyximages/numpy_indexing.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/pyximages/numpy_indexing.pdf -------------------------------------------------------------------------------- /pyximages/numpy_indexing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/pyximages/numpy_indexing.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy==2.2.5 2 | scipy==1.15.2 3 | matplotlib==3.10.1 4 | pandas==2.2.3 5 | patsy==1.0.1 6 | pyarrow==20.0.0 7 | scikit-learn==1.6.1 8 | scikit-image==0.25.2 9 | sympy==1.14.0 10 | statsmodels==0.14.4 11 | seaborn==0.13.2 12 | pytest>=8.3 13 | sphinx>=8.2 14 | sphinx-gallery>=0.19 15 | sphinx-copybutton 16 | coverage>=7.6 17 | Pillow 18 | pooch 19 | ipython 20 | pickleshare 21 | pre-commit==4.2.0 22 | requests 23 | sphinxcontrib-jquery 24 | -------------------------------------------------------------------------------- /themes/plusBox.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scipy-lectures/scientific-python-lectures/5cbb60368da58b937b0f22fa101072525d7ab96b/themes/plusBox.png -------------------------------------------------------------------------------- /themes/scientific_python_lectures/static/scroll_highlight_toc.js: -------------------------------------------------------------------------------- 1 | // Highlight the table of content as we scroll 2 | 3 | $( document ).ready(function () { 4 | sections = {}, 5 | i = 0, 6 | url = document.URL.replace(/#.*$/, ""), 7 | current_section = 0; 8 | 9 | // Grab positions of our sections 10 | $('.headerlink').each(function(){ 11 | sections[this.href.replace(url, '')] = $(this).offset().top - 50; 12 | }); 13 | 14 | $(window).scroll(function(event) { 15 | var pos = $(window).scrollTop(); 16 | 17 | // Highlight the current section 18 | $('a.internal').parent().removeClass('active'); 19 | for(i in sections){ 20 | if(sections[i] > pos){ 21 | break; 22 | }; 23 | if($('a.internal[href$="' + i + '"]').is(':visible')){ 24 | current_section = i; 25 | }; 26 | } 27 | $('a.internal[href$="' + current_section + '"]').parent().addClass('active'); 28 | $('a.internal[href$="' + current_section + '"]').parent().parent().parent().addClass('active'); 29 | $('a.internal[href$="' + current_section + '"]').parent().parent().parent().parent().parent().addClass('active'); 30 | }); 31 | }); 32 | -------------------------------------------------------------------------------- /themes/scientific_python_lectures/theme.conf: -------------------------------------------------------------------------------- 1 | [theme] 2 | inherit = default 3 | stylesheet = nature.css 4 | pygments_style = tango 5 | --------------------------------------------------------------------------------