├── AUTHORS.rst ├── CHANGES.rst ├── CONTRIBUTING.rst ├── LICENSE.rst ├── Makefile ├── PRESENTING.txt ├── README.md ├── 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 │ │ ├── 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 │ │ ├── compare_optimizers.pkl │ │ ├── compare_optimizers.py │ │ ├── compare_optimizers_plot.py │ │ ├── cost_functions.py │ │ ├── plot_1d_optim.py │ │ ├── plot_constraints.py │ │ ├── plot_convex.py │ │ ├── plot_curve_fit.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 │ ├── conf.py │ ├── demo-prof.png │ ├── demo.py │ ├── demo_opt.py │ ├── ica.py │ └── index.rst └── scipy_sparse │ ├── bsr_matrix.rst │ ├── coo_matrix.rst │ ├── csc_matrix.rst │ ├── csr_matrix.rst │ ├── dia_matrix.rst │ ├── dok_matrix.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_matrix.rst │ ├── other_packages.rst │ ├── solvers.rst │ └── storage_schemes.rst ├── blank_image.png ├── conf.py ├── continuous_integration ├── install.sh └── show-python-packages-versions.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 ├── euroscipy2010.svg ├── euroscipy_simple.svg ├── guide ├── examples │ ├── README.txt │ └── plot_simple.py └── index.rst ├── images ├── cover-v2.pdf ├── cover-v2.svg ├── cover.pdf ├── cover.svg ├── favicon.ico ├── logo.pdf ├── logo.svg ├── logo_small.svg └── no_image.png ├── includes ├── big_toc_css.rst └── bigger_toc_css.rst ├── index.rst ├── intro ├── 1dPlotting.png ├── 2dPlotting.png ├── chap3.rst ├── example_surface_from_irregular_data.jpg ├── help │ ├── docwiki.png │ ├── help.rst │ ├── matplotlib.png │ ├── mayavi_website.png │ └── scipy_doc.png ├── image_processing │ ├── MV_HFV_012.jpg │ ├── exo_histos.png │ ├── face_transforms.png │ ├── filtered_face.png │ ├── image_processing.rst │ ├── measures.png │ ├── morpho.png │ ├── morpho_mat.png │ ├── sands.png │ └── three_phases.png ├── 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 │ │ ├── plot_aliased.py │ │ ├── plot_alpha.py │ │ ├── plot_antialiased.py │ │ ├── plot_axes-2.py │ │ ├── plot_axes.py │ │ ├── plot_bad.py │ │ ├── plot_bar.py │ │ ├── plot_bar_ex.py │ │ ├── plot_boxplot.py │ │ ├── plot_color.py │ │ ├── plot_colormaps.py │ │ ├── plot_contour.py │ │ ├── plot_contour_ex.py │ │ ├── plot_dash_capstyle.py │ │ ├── plot_dash_joinstyle.py │ │ ├── plot_exercice_1.py │ │ ├── plot_exercice_10.py │ │ ├── plot_exercice_2.py │ │ ├── plot_exercice_3.py │ │ ├── plot_exercice_4.py │ │ ├── plot_exercice_5.py │ │ ├── plot_exercice_6.py │ │ ├── plot_exercice_7.py │ │ ├── plot_exercice_8.py │ │ ├── plot_exercice_9.py │ │ ├── plot_good.py │ │ ├── plot_grid.py │ │ ├── plot_grid_ex.py │ │ ├── plot_gridspec.py │ │ ├── plot_imshow.py │ │ ├── plot_imshow_ex.py │ │ ├── plot_linestyles.py │ │ ├── plot_linewidth.py │ │ ├── plot_markers.py │ │ ├── plot_mec.py │ │ ├── plot_mew.py │ │ ├── plot_mfc.py │ │ ├── plot_ms.py │ │ ├── plot_multiplot.py │ │ ├── plot_multiplot_ex.py │ │ ├── plot_pie.py │ │ ├── plot_pie_ex.py │ │ ├── plot_plot.py │ │ ├── plot_plot3d-2.py │ │ ├── plot_plot3d.py │ │ ├── plot_plot3d_ex.py │ │ ├── plot_plot_ex.py │ │ ├── plot_polar.py │ │ ├── plot_polar_ex.py │ │ ├── plot_quiver.py │ │ ├── plot_quiver_ex.py │ │ ├── plot_scatter.py │ │ ├── plot_scatter_ex.py │ │ ├── plot_solid_capstyle.py │ │ ├── plot_solid_joinstyle.py │ │ ├── plot_subplot-grid.py │ │ ├── plot_subplot-horizontal.py │ │ ├── plot_subplot-vertical.py │ │ ├── plot_text.py │ │ ├── plot_text_ex.py │ │ ├── plot_ticks.py │ │ └── plot_ugly.py │ └── matplotlib.rst ├── numpy │ ├── advanced_operations.rst │ ├── array_object.rst │ ├── data │ ├── elaborate_arrays.rst │ ├── exercises.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 ├── phd053104s.png ├── random_c.jpg ├── scipy.rst ├── snapshot_ipython.png ├── solutions.rst ├── solutions │ ├── curvefit_temperature_data.py │ ├── data.txt │ ├── data_file.py │ ├── dir_sort.py │ ├── fft_image_denoise.py │ ├── image_blur.py │ ├── path_site.py │ ├── periodicity_finder.py │ ├── pi_wallis.py │ ├── quick_sort.py │ └── test_dir_sort.py └── summary-exercises │ ├── README.txt │ ├── answers_image_processing.rst │ ├── examples │ ├── README.rst │ ├── max-speeds.npy │ ├── plot_cumulative_wind_speed_prediction.py │ ├── plot_gumbell_wind_speed_prediction.py │ ├── plot_sprog_annual_maxima.py │ └── sprog-windspeeds.npy │ ├── image-processing.rst │ ├── optimize-fit.rst │ ├── stats-interpolate.rst │ ├── waveform_1.png │ └── waveform_2.png ├── misc └── yeahconsole ├── packages ├── 3d_plotting │ ├── conf.py │ ├── decorations.png │ ├── examples │ │ ├── README.txt │ │ ├── animate_data.py │ │ ├── coil_application.py │ │ ├── compute_field.py │ │ ├── contour3d.png │ │ ├── generate_figures.py │ │ ├── mesh.png │ │ ├── mlab_dialog.py │ │ ├── mlab_interactive_dialog.png │ │ ├── mlab_interactive_dialog.py │ │ ├── plot3d.png │ │ ├── points3d.png │ │ ├── simple_example.py │ │ ├── surf.png │ │ ├── visualize_field.png │ │ ├── visualize_field.py │ │ ├── viz_volume_structure.png │ │ ├── viz_volume_structure.py │ │ ├── viz_volume_unstructure.png │ │ └── viz_volume_unstructure.py │ ├── index.rst │ ├── interaction.rst │ ├── mayavi-logo.png │ ├── mlab_scripting_interface.rst │ ├── pipeline.png │ ├── polar_mesh.png │ └── simple_example.png ├── 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 │ ├── cluster_iris_truth.png │ ├── digits_first_image.png │ ├── digits_svm.py │ ├── face.png │ ├── face_compressed.png │ ├── faces.png │ ├── faces.py │ ├── images │ │ └── Virginia_Iris.png │ ├── index.rst │ ├── iris_knn.png │ ├── iris_svm.png │ ├── k_means_iris_3.png │ ├── k_means_iris_8.png │ ├── pca_3d_aligned.jpg │ ├── pca_3d_axis.jpg │ ├── pca_digits_spectrum.png │ ├── pca_iris.png │ ├── plot_compare_methods_1.png │ ├── plot_faces_decomposition_2.png │ ├── scikit-learn-logo.png │ ├── show_digit.py │ ├── show_ica.py │ ├── show_pca.py │ ├── svm_kernel_linear.png │ ├── svm_kernel_poly.png │ ├── svm_kernel_rbf.png │ ├── svm_margin.png │ └── svm_margin_no_penalty.png ├── 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 └── traits │ ├── ETS.jpg │ ├── index.rst │ ├── reservoir.py │ ├── reservoir_default_view.png │ ├── reservoir_evolution.png │ ├── reservoir_evolution.py │ ├── reservoir_simple_view.py │ ├── reservoir_state.py │ ├── reservoir_state_dynamic_listener.py │ ├── reservoir_state_event.py │ ├── reservoir_state_property.py │ ├── reservoir_state_property_ontraitchange.py │ ├── reservoir_state_property_view.py │ ├── reservoir_state_static_listener.py │ ├── reservoir_state_view.png │ ├── reservoir_turbine_prototype_from.py │ ├── reservoir_view.png │ ├── reservoir_with_irrigation.py │ └── reservoir_with_irrigation_listener.py ├── preface.rst ├── pyplots ├── demo_detrend.py ├── demo_resample.py ├── fftpack_frequency.py ├── fftpack_signals.py ├── normal_distribution.py ├── numpy_intro_1.py ├── numpy_intro_10.py ├── numpy_intro_2.py ├── numpy_intro_3.py ├── numpy_intro_4.py ├── numpy_intro_5.py ├── numpy_intro_6.py ├── numpy_intro_7.py ├── numpy_intro_8.py ├── numpy_intro_9.py ├── odeint_damped_spring_mass.py ├── odeint_introduction.py ├── scipy_interpolation.py ├── scipy_optimize_example1.py ├── scipy_optimize_example2.py └── scipy_optimize_sixhump.py ├── sphinxext ├── README.txt ├── __init__.py ├── gen_rst.py ├── ipython_console_highlighting.py ├── math_symbol_table.py ├── mathml.py ├── mathmpl.py ├── only_directives.py ├── plot_directive.py └── suites.py ├── testing.py ├── themes ├── plusBox.png └── scipy_lectures │ ├── layout.html │ ├── static │ ├── copybutton.js │ └── nature.css_t │ └── theme.conf └── tune_toc.rst /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | 帮助我们 2 | ============= 3 | 4 | 编译指南 5 | ---------------------- 6 | 7 | 8 | 编译HTML格式文件, 输入:: 9 | 10 | make html 11 | 12 | 生成的HTML文件保存在 ``build/html`` 目录下 13 | 14 | 首次编译耗时较长大致3~10分钟,这取决于编译平台的硬件配置及网络环境。由于第一次编译的信息缓存,随后的编译速度会稍快。 15 | 16 | 17 | 生成PDF文档:: 18 | 19 | make pdf 20 | 21 | 生成过程中可能产生一些TeX相关的错误. 细微调整 ``*.rst`` 文档的排版通常有助于改善这些错误. 22 | 23 | 24 | 环境需求 25 | ------------------ 26 | 27 | *可能不完全* 28 | 29 | * make 30 | * sphinx (>= 1.0) 31 | * pdflatex 32 | * pdfjam 33 | * matplotlib 34 | * scikit-learn (>= 0.8) 35 | * scikit-image 36 | * pandas 37 | * seaborn 38 | 39 | 40 | 在ubuntu14.04 LTS上编译HTML (我的编译环境) 41 | ------------------ 42 | 43 | 1. 安装anaconda for Python 2.7, Linux 64-bit . (其他版本未经测试) 44 | 2. 添加anaconda/bin/目录到系统PATH变量中 45 | 3. 安装seaborn包 pip install seaborn 46 | 4. 切换至scipy-lecture-notes-zh-CN/目录下, make html 47 | 5. 在build/html文件夹下打开index.html 48 | 49 | 50 | 51 | 在Fedora上编译 (原作者) 52 | ------------------ 53 | 54 | As root:: 55 | 56 | yum install python make python-matplotlib texlive-pdfjam texlive scipy \ 57 | texlive-framed texlive-threeparttable texlive-wrapfig texlive-multirow 58 | pip install Sphinx 59 | pip install Cython 60 | pip install scikit-learn 61 | pip install scikit-image 62 | 63 | 64 | 如何做出贡献 65 | --------------------------------------- 66 | 67 | 如果你对翻译此文档感兴趣,请fork此仓库,在作出翻译之后向我pull request。 感谢! 68 | 69 | -------------------------------------------------------------------------------- /LICENSE.rst: -------------------------------------------------------------------------------- 1 | 版权 2 | ======== 3 | 4 | All code and material is licensed under a 5 | 6 | Creative Commons Attribution 4.0 Internatonal License (CC-by) 7 | 8 | http://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 accompagning shell script to start yeahconsole: 7 | it defines the right font size, and 'Ctr-Alt-Y' to show/hide the console. 8 | 9 | -------------------------------------------------------------------------------- /advanced/advanced_numpy/cpu-cacheline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/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 | 4 | -------------------------------------------------------------------------------- /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 | x = np.linspace(-1.7, 0.6, 1000) 12 | y = np.linspace(-1.4, 1.4, 1000) 13 | c = x[None,:] + 1j*y[:,None] 14 | z = mandel.mandel(c, c) 15 | 16 | import matplotlib.pyplot as plt 17 | plt.imshow(abs(z)**2 < 1000, extent=[-1.7, 0.6, -1.4, 1.4]) 18 | plt.gray() 19 | plt.show() 20 | -------------------------------------------------------------------------------- /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 | import Image 11 | 12 | # Let's make a sample image, RGBA format 13 | 14 | x = np.zeros((200, 200, 4), dtype=np.int8) 15 | 16 | x[:,:,0] = 254 # 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 | # 25 | # Modify the original data, and save again. 26 | # 27 | # It turns out that PIL, which knows next to nothing about Numpy, 28 | # happily shares the same data. 29 | # 30 | 31 | x[:,:,1] = 254 32 | img.save('test2.png') 33 | -------------------------------------------------------------------------------- /advanced/advanced_numpy/examples/pilbuffer.py: -------------------------------------------------------------------------------- 1 | """ 2 | Exercise: using the buffer protocole 3 | ==================================== 4 | 5 | Skeletton of the code to do an exercise using the buffer protocole. 6 | """ 7 | 8 | import numpy as np 9 | import Image 10 | 11 | # Let's make a sample image, RGBA format 12 | 13 | x = np.zeros((200, 200, 4), dtype=np.int8) 14 | 15 | # TODO: fill `x` with fully opaque red [255, 0, 0, 255] 16 | 17 | # TODO: RGBA images consist of 32-bit integers whose bytes are [RR,GG,BB,AA] 18 | # How to get that from ``x``? 19 | 20 | data = ... 21 | 22 | img = Image.frombuffer("RGBA", (200, 200), data) 23 | img.save('test.png') 24 | 25 | # 26 | # Mini-exercise 27 | # 28 | # 1. Now, modify ``x`` and img.save() again. What happens? 29 | # 30 | -------------------------------------------------------------------------------- /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 | import os 10 | import sys 11 | from os.path import join 12 | from distutils.sysconfig import get_python_inc 13 | import numpy 14 | from numpy.distutils.misc_util import get_numpy_include_dirs 15 | 16 | def configuration(parent_package='',top_path=None): 17 | from numpy.distutils.misc_util import Configuration 18 | 19 | for filename in ['mandel.so']: 20 | # make sure we don't have stale files lying around 21 | if os.path.isfile(filename): 22 | os.unlink(filename) 23 | 24 | config = Configuration('', parent_package, top_path) 25 | config.add_extension('mandel', sources=['mandel.c']) 26 | return config 27 | 28 | if __name__ == '__main__': 29 | from numpy.distutils.core import setup 30 | setup(**configuration(top_path='').todict()) 31 | -------------------------------------------------------------------------------- /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 distutils.core import setup, Extension 10 | setup(name='myobject', 11 | version='1.0', 12 | ext_modules=[Extension('myobject', ['myobject.c'])], 13 | ) 14 | -------------------------------------------------------------------------------- /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], 16 | [4, 5, 6], 17 | [7, 8, 9]], dtype=np.int32) 18 | 19 | x_diag = as_strided(x, shape=(3,), strides=(TODO,)) 20 | x_supdiag = TODO 21 | x_subdiag = TODO 22 | 23 | # 24 | # Mini-exercise: (assume C memory order) 25 | # 26 | # 0. How to pick diagonal entries of the matrix 27 | # 28 | # 1. How to pick the super-diagonal entries [2, 6] 29 | # 30 | # 2. The sub-diagonal entries [4, 8] 31 | # 32 | # 99. Can you generalize this for any stride and shape combinations 33 | # in the initial array? 34 | # 35 | # If you can, tell me, and maybe numpy.trace can be made faster :) 36 | # 37 | 38 | 39 | # 40 | # Part 2 41 | # 42 | 43 | # Compute the tensor trace 44 | 45 | x = np.arange(5*5*5*5).reshape(5,5,5,5) 46 | 47 | s = 0 48 | for i in xrange(5): 49 | for j in xrange(5): 50 | s += x[j,i,j,i] 51 | 52 | # by striding and using .sum() 53 | 54 | y = as_strided(x, shape=(5, 5), strides=(TODO, TODO)) 55 | s2 = ... 56 | 57 | assert s == s2 58 | -------------------------------------------------------------------------------- /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/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/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 | x = np.zeros((10, 10, 4), dtype=np.int8) 10 | x[:,:,0] = 1 11 | x[:,:,1] = 2 12 | x[:,:,2] = 3 13 | x[:,:,3] = 4 14 | 15 | # How to make a (10, 10) structured array with fields 'r', 'g', 'b', 'a', 16 | # without copying? 17 | 18 | # y = ... 19 | 20 | assert (y['r'] == 1).all() 21 | assert (y['g'] == 2).all() 22 | assert (y['b'] == 3).all() 23 | assert (y['a'] == 4).all() 24 | -------------------------------------------------------------------------------- /advanced/advanced_numpy/mandelbrot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/advanced/advanced_numpy/mandelbrot.png -------------------------------------------------------------------------------- /advanced/advanced_numpy/test.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/advanced/advanced_numpy/test.png -------------------------------------------------------------------------------- /advanced/advanced_numpy/test2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/advanced/advanced_numpy/test2.png -------------------------------------------------------------------------------- /advanced/advanced_numpy/threefundamental.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/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 | def parse_data(data_string): 7 | data = [] 8 | for x in data_string.split('.'): 9 | data.append(x) 10 | return data 11 | 12 | def load_data(filename): 13 | fp = open(filename) 14 | data_string = fp.read() 15 | fp.close() 16 | return parse_data(data_string) 17 | 18 | if __name__ == '__main__': 19 | data = load_data('exercises/data.txt') 20 | print('min: %f' % min(data)) # 10.20 21 | print('max: %f' % max(data)) # 61.30 22 | -------------------------------------------------------------------------------- /advanced/debugging/index_error.py: -------------------------------------------------------------------------------- 1 | """Small snippet to raise an IndexError.""" 2 | 3 | def index_error(): 4 | lst = list('foobar') 5 | print lst[len(lst)] 6 | 7 | if __name__ == '__main__': 8 | index_error() 9 | 10 | -------------------------------------------------------------------------------- /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 | def make_big_array(small_array): 9 | big_array = stride_tricks.as_strided(small_array, 10 | shape=(2e6, 2e6), strides=(32, 32)) 11 | return big_array 12 | 13 | def print_big_array(small_array): 14 | big_array = make_big_array(small_array) 15 | print big_array[-10:] 16 | return big_array 17 | 18 | 19 | l = list() 20 | for i in range(10): 21 | a = np.arange(8) 22 | l.append(print_big_array(a)) 23 | -------------------------------------------------------------------------------- /advanced/debugging/vim_pyflakes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/advanced/debugging/vim_pyflakes.png -------------------------------------------------------------------------------- /advanced/debugging/vim_syntastic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/advanced/debugging/vim_syntastic.png -------------------------------------------------------------------------------- /advanced/image_processing/axis_convention.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/advanced/image_processing/axis_convention.png -------------------------------------------------------------------------------- /advanced/image_processing/coins.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/advanced/image_processing/coins.png -------------------------------------------------------------------------------- /advanced/image_processing/diamond_kernel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/advanced/image_processing/diamond_kernel.png -------------------------------------------------------------------------------- /advanced/image_processing/examples/README.txt: -------------------------------------------------------------------------------- 1 | Examples for the image processing chapter 2 | ========================================= 3 | 4 | -------------------------------------------------------------------------------- /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.misc 11 | from scipy import ndimage 12 | import matplotlib.pyplot as plt 13 | 14 | f = scipy.misc.face(gray=True) 15 | sx, sy = f.shape 16 | X, Y = np.ogrid[0:sx, 0:sy] 17 | 18 | regions = sy/6 * (X/4) + Y/6 19 | block_mean = ndimage.mean(f, labels=regions, 20 | index=np.arange(1, regions.max() +1)) 21 | block_mean.shape = (sx/4, sy/6) 22 | 23 | plt.figure(figsize=(5, 5)) 24 | plt.imshow(block_mean, cmap=plt.cm.gray) 25 | plt.axis('off') 26 | 27 | plt.show() 28 | 29 | -------------------------------------------------------------------------------- /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.misc 9 | from scipy import ndimage 10 | import matplotlib.pyplot as plt 11 | 12 | face = scipy.misc.face(gray=True) 13 | blurred_face = ndimage.gaussian_filter(face, sigma=3) 14 | very_blurred = ndimage.gaussian_filter(face, sigma=5) 15 | local_mean = ndimage.uniform_filter(face, size=11) 16 | 17 | plt.figure(figsize=(9, 3)) 18 | plt.subplot(131) 19 | plt.imshow(blurred_face, cmap=plt.cm.gray) 20 | plt.axis('off') 21 | plt.subplot(132) 22 | plt.imshow(very_blurred, cmap=plt.cm.gray) 23 | plt.axis('off') 24 | plt.subplot(133) 25 | plt.imshow(local_mean, cmap=plt.cm.gray) 26 | plt.axis('off') 27 | 28 | plt.subplots_adjust(wspace=0, hspace=0., top=0.99, bottom=0.01, 29 | left=0.01, right=0.99) 30 | 31 | plt.show() 32 | -------------------------------------------------------------------------------- /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 | from scipy import ndimage 11 | import matplotlib.pyplot as plt 12 | 13 | im = np.zeros((20, 20)) 14 | im[5:-5, 5:-5] = 1 15 | im = ndimage.distance_transform_bf(im) 16 | im_noise = im + 0.2*np.random.randn(*im.shape) 17 | 18 | im_med = ndimage.median_filter(im_noise, 3) 19 | 20 | plt.figure(figsize=(16, 5)) 21 | 22 | plt.subplot(141) 23 | plt.imshow(im, interpolation='nearest') 24 | plt.axis('off') 25 | plt.title('Original image', fontsize=20) 26 | plt.subplot(142) 27 | plt.imshow(im_noise, interpolation='nearest', vmin=0, vmax=5) 28 | plt.axis('off') 29 | plt.title('Noisy image', fontsize=20) 30 | plt.subplot(143) 31 | plt.imshow(im_med, interpolation='nearest', vmin=0, vmax=5) 32 | plt.axis('off') 33 | plt.title('Median filter', fontsize=20) 34 | plt.subplot(144) 35 | plt.imshow(np.abs(im - im_med), cmap=plt.cm.hot, interpolation='nearest') 36 | plt.axis('off') 37 | plt.title('Error', fontsize=20) 38 | 39 | 40 | plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, 41 | right=1) 42 | 43 | plt.show() 44 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_display_face.py: -------------------------------------------------------------------------------- 1 | """ 2 | Display a Racoon Face 3 | ===================== 4 | 5 | An example that displays a racoon face with matplotlib. 6 | """ 7 | import scipy.misc 8 | import matplotlib.pyplot as plt 9 | 10 | f = scipy.misc.face(gray=True) 11 | 12 | plt.figure(figsize=(10, 3.6)) 13 | 14 | plt.subplot(131) 15 | plt.imshow(f, cmap=plt.cm.gray) 16 | 17 | plt.subplot(132) 18 | plt.imshow(f, cmap=plt.cm.gray, vmin=30, vmax=200) 19 | plt.axis('off') 20 | 21 | plt.subplot(133) 22 | plt.imshow(f, cmap=plt.cm.gray) 23 | plt.contour(f, [50, 200]) 24 | plt.axis('off') 25 | 26 | plt.subplots_adjust(wspace=0, hspace=0., top=0.99, bottom=0.01, left=0.05, 27 | right=0.99) 28 | plt.show() 29 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_face.py: -------------------------------------------------------------------------------- 1 | """ 2 | Displaying a Racoon Face 3 | ======================== 4 | 5 | Small example to plot a racoon face. 6 | """ 7 | 8 | from scipy import misc 9 | f = misc.face() 10 | misc.imsave('face.png', f) # uses the Image module (PIL) 11 | 12 | import matplotlib.pyplot as plt 13 | plt.imshow(f) 14 | plt.show() 15 | -------------------------------------------------------------------------------- /advanced/image_processing/examples/plot_face_denoise.py: -------------------------------------------------------------------------------- 1 | """ 2 | Image denoising 3 | ================ 4 | 5 | This example demoes image denoising on a Racoon face. 6 | """ 7 | 8 | import numpy as np 9 | import scipy 10 | import scipy.misc 11 | from scipy import ndimage 12 | import matplotlib.pyplot as plt 13 | 14 | f = scipy.misc.face(gray=True) 15 | f = f[230:290, 220:320] 16 | 17 | noisy = f + 0.4*f.std()*np.random.random(f.shape) 18 | 19 | gauss_denoised = ndimage.gaussian_filter(noisy, 2) 20 | med_denoised = ndimage.median_filter(noisy, 3) 21 | 22 | 23 | plt.figure(figsize=(12,2.8)) 24 | 25 | plt.subplot(131) 26 | plt.imshow(noisy, cmap=plt.cm.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=plt.cm.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=plt.cm.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, 39 | right=1) 40 | plt.show() 41 | -------------------------------------------------------------------------------- /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 Racoon face. 6 | """ 7 | 8 | import numpy as np 9 | import scipy 10 | import scipy.misc 11 | import matplotlib.pyplot as plt 12 | from skimage.filter import denoise_tv_chambolle 13 | 14 | f = scipy.misc.face(gray=True) 15 | f = f[230:290, 220:320] 16 | 17 | noisy = f + 0.4*f.std()*np.random.random(f.shape) 18 | 19 | tv_denoised = denoise_tv_chambolle(noisy, weight=10) 20 | 21 | 22 | plt.figure(figsize=(12, 2.8)) 23 | 24 | plt.subplot(131) 25 | plt.imshow(noisy, cmap=plt.cm.gray, vmin=40, vmax=220) 26 | plt.axis('off') 27 | plt.title('noisy', fontsize=20) 28 | plt.subplot(132) 29 | plt.imshow(tv_denoised, cmap=plt.cm.gray, vmin=40, vmax=220) 30 | plt.axis('off') 31 | plt.title('TV denoising', fontsize=20) 32 | 33 | tv_denoised = denoise_tv_chambolle(noisy, weight=50) 34 | plt.subplot(133) 35 | plt.imshow(tv_denoised, cmap=plt.cm.gray, vmin=40, vmax=220) 36 | plt.axis('off') 37 | plt.title('(more) TV denoising', fontsize=20) 38 | 39 | plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, 40 | right=1) 41 | plt.show() 42 | -------------------------------------------------------------------------------- /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 | from scipy import ndimage 10 | import matplotlib.pyplot as plt 11 | 12 | im = np.zeros((256, 256)) 13 | im[64:-64, 64:-64] = 1 14 | 15 | im = ndimage.rotate(im, 15, mode='constant') 16 | im = ndimage.gaussian_filter(im, 8) 17 | 18 | sx = ndimage.sobel(im, axis=0, mode='constant') 19 | sy = ndimage.sobel(im, axis=1, mode='constant') 20 | sob = np.hypot(sx, sy) 21 | 22 | plt.figure(figsize=(16, 5)) 23 | plt.subplot(141) 24 | plt.imshow(im, cmap=plt.cm.gray) 25 | plt.axis('off') 26 | plt.title('square', fontsize=20) 27 | plt.subplot(142) 28 | plt.imshow(sx) 29 | plt.axis('off') 30 | plt.title('Sobel (x direction)', fontsize=20) 31 | plt.subplot(143) 32 | plt.imshow(sob) 33 | plt.axis('off') 34 | plt.title('Sobel filter', fontsize=20) 35 | 36 | im += 0.07*np.random.random(im.shape) 37 | 38 | sx = ndimage.sobel(im, axis=0, mode='constant') 39 | sy = ndimage.sobel(im, axis=1, mode='constant') 40 | sob = np.hypot(sx, sy) 41 | 42 | plt.subplot(144) 43 | plt.imshow(sob) 44 | plt.axis('off') 45 | plt.title('Sobel for noisy image', fontsize=20) 46 | 47 | 48 | 49 | plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=0.9) 50 | 51 | plt.show() 52 | -------------------------------------------------------------------------------- /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 | from scipy import ndimage 11 | import matplotlib.pyplot as plt 12 | 13 | np.random.seed(1) 14 | n = 10 15 | l = 256 16 | im = np.zeros((l, l)) 17 | points = l*np.random.random((2, n**2)) 18 | im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 19 | im = ndimage.gaussian_filter(im, sigma=l/(4.*n)) 20 | 21 | mask = im > im.mean() 22 | 23 | label_im, nb_labels = ndimage.label(mask) 24 | 25 | # Find the largest connect component 26 | sizes = 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 connect component, extract it's bounding box 34 | slice_x, slice_y = 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 Racoon face. 6 | """ 7 | 8 | import numpy as np 9 | import scipy.misc 10 | from scipy import ndimage 11 | import matplotlib.pyplot as plt 12 | 13 | face = scipy.misc.face(gray=True) 14 | lx, ly = face.shape 15 | # Cropping 16 | crop_face = face[lx/4:-lx/4, ly/4:-ly/4] 17 | # up <-> down flip 18 | flip_ud_face = np.flipud(face) 19 | # rotation 20 | rotate_face = ndimage.rotate(face, 45) 21 | rotate_face_noreshape = ndimage.rotate(face, 45, reshape=False) 22 | 23 | plt.figure(figsize=(12.5, 2.5)) 24 | 25 | 26 | plt.subplot(151) 27 | plt.imshow(face, cmap=plt.cm.gray) 28 | plt.axis('off') 29 | plt.subplot(152) 30 | plt.imshow(crop_face, cmap=plt.cm.gray) 31 | plt.axis('off') 32 | plt.subplot(153) 33 | plt.imshow(flip_ud_face, cmap=plt.cm.gray) 34 | plt.axis('off') 35 | plt.subplot(154) 36 | plt.imshow(rotate_face, cmap=plt.cm.gray) 37 | plt.axis('off') 38 | plt.subplot(155) 39 | plt.imshow(rotate_face_noreshape, cmap=plt.cm.gray) 40 | plt.axis('off') 41 | 42 | plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, 43 | right=1) 44 | 45 | plt.show() 46 | -------------------------------------------------------------------------------- /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 | from scipy import ndimage 10 | import matplotlib.pyplot as plt 11 | 12 | im = np.zeros((64, 64)) 13 | np.random.seed(2) 14 | x, y = (63*np.random.random((2, 8))).astype(np.int) 15 | im[x, y] = np.arange(8) 16 | 17 | bigger_points = 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 = ndimage.distance_transform_bf(square) 22 | dilate_dist = ndimage.grey_dilation(dist, size=(3, 3), \ 23 | structure=np.ones((3, 3))) 24 | 25 | plt.figure(figsize=(12.5, 3)) 26 | plt.subplot(141) 27 | plt.imshow(im, interpolation='nearest', cmap=plt.cm.spectral) 28 | plt.axis('off') 29 | plt.subplot(142) 30 | plt.imshow(bigger_points, interpolation='nearest', cmap=plt.cm.spectral) 31 | plt.axis('off') 32 | plt.subplot(143) 33 | plt.imshow(dist, interpolation='nearest', cmap=plt.cm.spectral) 34 | plt.axis('off') 35 | plt.subplot(144) 36 | plt.imshow(dilate_dist, interpolation='nearest', cmap=plt.cm.spectral) 37 | plt.axis('off') 38 | 39 | plt.subplots_adjust(wspace=0, hspace=0.02, top=0.99, bottom=0.01, left=0.01, right=0.99) 40 | plt.show() 41 | -------------------------------------------------------------------------------- /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 | from scipy import ndimage 10 | import matplotlib.pyplot as plt 11 | 12 | np.random.seed(1) 13 | n = 10 14 | l = 256 15 | im = np.zeros((l, l)) 16 | points = l*np.random.random((2, n**2)) 17 | im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 18 | im = ndimage.gaussian_filter(im, sigma=l/(4.*n)) 19 | 20 | mask = (im > im.mean()).astype(np.float) 21 | 22 | mask += 0.1 * im 23 | 24 | img = mask + 0.2*np.random.randn(*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=plt.cm.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 Racoon face. 6 | """ 7 | 8 | import scipy.misc 9 | import matplotlib.pyplot as plt 10 | 11 | f = scipy.misc.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=plt.cm.gray) 17 | plt.axis('off') 18 | 19 | plt.subplot(1, 2, 2) 20 | plt.imshow(f[320:340, 510:530], cmap=plt.cm.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 | from scipy import ndimage 11 | import matplotlib.pyplot as plt 12 | 13 | np.random.seed(1) 14 | n = 10 15 | l = 256 16 | im = np.zeros((l, l)) 17 | points = l*np.random.random((2, n**2)) 18 | im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 19 | im = ndimage.gaussian_filter(im, sigma=l/(4.*n)) 20 | 21 | mask = im > im.mean() 22 | 23 | label_im, nb_labels = ndimage.label(mask) 24 | 25 | sizes = 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=plt.cm.spectral) 37 | plt.axis('off') 38 | plt.subplot(122) 39 | plt.imshow(label_clean, vmax=nb_labels, cmap=plt.cm.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 12 | import scipy.misc 13 | import matplotlib.pyplot as plt 14 | 15 | face = scipy.misc.face(gray=True) 16 | face[10:13, 20:23] 17 | face[100:120] = 255 18 | 19 | lx, ly = face.shape 20 | X, Y = np.ogrid[0:lx, 0:ly] 21 | mask = (X - lx/2)**2 + (Y - ly/2)**2 > lx*ly/4 22 | face[mask] = 0 23 | face[range(400), range(400)] = 255 24 | 25 | plt.figure(figsize=(3, 3)) 26 | plt.axes([0, 0, 1, 1]) 27 | plt.imshow(face, cmap=plt.cm.gray) 28 | plt.axis('off') 29 | 30 | plt.show() 31 | -------------------------------------------------------------------------------- /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 | from scipy import ndimage 10 | import matplotlib.pyplot as plt 11 | 12 | square = np.zeros((32, 32)) 13 | square[10:-10, 10:-10] = 1 14 | np.random.seed(2) 15 | x, y = (32*np.random.random((2, 20))).astype(np.int) 16 | square[x, y] = 1 17 | 18 | open_square = ndimage.binary_opening(square) 19 | 20 | eroded_square = ndimage.binary_erosion(square) 21 | reconstruction = ndimage.binary_propagation(eroded_square, mask=square) 22 | 23 | plt.figure(figsize=(9.5, 3)) 24 | plt.subplot(131) 25 | plt.imshow(square, cmap=plt.cm.gray, interpolation='nearest') 26 | plt.axis('off') 27 | plt.subplot(132) 28 | plt.imshow(open_square, cmap=plt.cm.gray, interpolation='nearest') 29 | plt.axis('off') 30 | plt.subplot(133) 31 | plt.imshow(reconstruction, cmap=plt.cm.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 | 37 | 38 | -------------------------------------------------------------------------------- /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 10 | from scipy import ndimage 11 | import matplotlib.pyplot as plt 12 | 13 | f = scipy.misc.face(gray=True) 14 | sx, sy = f.shape 15 | X, Y = np.ogrid[0:sx, 0:sy] 16 | 17 | 18 | r = np.hypot(X - sx/2, Y - sy/2) 19 | 20 | rbin = (20* r/r.max()).astype(np.int) 21 | radial_mean = ndimage.mean(f, labels=rbin, index=np.arange(1, rbin.max() +1)) 22 | 23 | plt.figure(figsize=(5, 5)) 24 | plt.axes([0, 0, 1, 1]) 25 | plt.imshow(rbin, cmap=plt.cm.spectral) 26 | plt.axis('off') 27 | 28 | plt.show() 29 | -------------------------------------------------------------------------------- /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 10 | from scipy import ndimage 11 | import matplotlib.pyplot as plt 12 | 13 | f = scipy.misc.face(gray=True).astype(float) 14 | blurred_f = ndimage.gaussian_filter(f, 3) 15 | 16 | filter_blurred_f = ndimage.gaussian_filter(blurred_f, 1) 17 | 18 | alpha = 30 19 | sharpened = blurred_f + alpha * (blurred_f - filter_blurred_f) 20 | 21 | plt.figure(figsize=(12, 4)) 22 | 23 | plt.subplot(131) 24 | plt.imshow(f, cmap=plt.cm.gray) 25 | plt.axis('off') 26 | plt.subplot(132) 27 | plt.imshow(blurred_f, cmap=plt.cm.gray) 28 | plt.axis('off') 29 | plt.subplot(133) 30 | plt.imshow(sharpened, cmap=plt.cm.gray) 31 | plt.axis('off') 32 | 33 | plt.tight_layout() 34 | plt.show() 35 | -------------------------------------------------------------------------------- /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 | from scipy import ndimage 10 | import matplotlib.pyplot as plt 11 | 12 | np.random.seed(1) 13 | n = 10 14 | l = 256 15 | im = np.zeros((l, l)) 16 | points = l*np.random.random((2, n**2)) 17 | im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 18 | im = ndimage.gaussian_filter(im, sigma=l/(4.*n)) 19 | 20 | mask = im > im.mean() 21 | 22 | label_im, nb_labels = 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=plt.cm.gray) 31 | plt.axis('off') 32 | plt.subplot(133) 33 | plt.imshow(label_im, cmap=plt.cm.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/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/advanced/image_processing/image_GMM.png -------------------------------------------------------------------------------- /advanced/image_processing/image_spectral_clustering.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/advanced/image_processing/image_spectral_clustering.png -------------------------------------------------------------------------------- /advanced/image_processing/kernels.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/advanced/image_processing/kernels.png -------------------------------------------------------------------------------- /advanced/image_processing/morpho_mat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/advanced/image_processing/morpho_mat.png -------------------------------------------------------------------------------- /advanced/image_processing/scikit_image_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/advanced/image_processing/scikit_image_logo.png -------------------------------------------------------------------------------- /advanced/index.rst: -------------------------------------------------------------------------------- 1 | 进阶话题 2 | =================================================================== 3 | 4 | 这部分 *Scipy lecture notes* 旨在为熟练的Python程序员提供一些指导, 5 | 特别是解决一些特殊领域的问题。 6 | 7 | | 8 | 9 | .. include:: ../includes/big_toc_css.rst 10 | 11 | .. include:: ../tune_toc.rst 12 | 13 | .. rst-class:: tune 14 | 15 | .. toctree:: 16 | 17 | advanced_python/index.rst 18 | advanced_numpy/index.rst 19 | debugging/index.rst 20 | optimizing/index.rst 21 | scipy_sparse/index.rst 22 | image_processing/index.rst 23 | mathematical_optimization/index.rst 24 | interfacing_with_c/interfacing_with_c.rst 25 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/ctypes/cos_module.py: -------------------------------------------------------------------------------- 1 | """ Example of wrapping cos function from math.h using ctypes. """ 2 | 3 | import ctypes 4 | from ctypes.util import find_library 5 | 6 | # find and load the library 7 | libm = ctypes.cdll.LoadLibrary(find_library('m')) 8 | # set the argument type 9 | libm.cos.argtypes = [ctypes.c_double] 10 | # set the return type 11 | libm.cos.restype = ctypes.c_double 12 | 13 | 14 | def cos_func(arg): 15 | ''' Wrapper for cos from math.h ''' 16 | return libm.cos(arg) 17 | -------------------------------------------------------------------------------- /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 distutils.core import setup, Extension 2 | from Cython.Distutils import build_ext 3 | 4 | setup( 5 | cmdclass={'build_ext': build_ext}, 6 | ext_modules=[Extension("cos_module", ["cos_module.pyx"])] 7 | ) 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 distutils.core import setup, Extension 2 | import numpy 3 | from Cython.Distutils import build_ext 4 | 5 | setup( 6 | cmdclass={'build_ext': build_ext}, 7 | ext_modules=[Extension("cos_doubles", 8 | sources=["_cos_doubles.pyx", "cos_doubles.c"], 9 | include_dirs=[numpy.get_include()])], 10 | ) 11 | -------------------------------------------------------------------------------- /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 distutils.core import setup, Extension 2 | from Cython.Distutils import build_ext 3 | 4 | setup( 5 | cmdclass={'build_ext': build_ext}, 6 | ext_modules=[Extension("cos_module", ["cos_module.pyx"])] 7 | ) 8 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/numpy_c_api/setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup, Extension 2 | import numpy 3 | 4 | # define the extension module 5 | cos_module_np = Extension('cos_module_np', sources=['cos_module_np.c'], 6 | include_dirs=[numpy.get_include()]) 7 | 8 | # run the setup 9 | setup(ext_modules=[cos_module_np]) 10 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/numpy_c_api/test_cos_module_np.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/advanced/interfacing_with_c/numpy_c_api/test_cos_module_np.png -------------------------------------------------------------------------------- /advanced/interfacing_with_c/numpy_c_api/test_cos_module_np.py: -------------------------------------------------------------------------------- 1 | import cos_module_np 2 | import numpy as np 3 | import pylab 4 | 5 | x = np.arange(0, 2 * np.pi, 0.1) 6 | y = cos_module_np.cos_func_np(x) 7 | pylab.plot(x, y) 8 | pylab.show() 9 | -------------------------------------------------------------------------------- /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 4 | #include 5 | 6 | /* wrapped cosine function */ 7 | static PyObject* cos_func(PyObject* self, PyObject* args) 8 | { 9 | double value; 10 | double answer; 11 | 12 | /* parse the input, from python float to c double */ 13 | if (!PyArg_ParseTuple(args, "d", &value)) 14 | return NULL; 15 | /* if the above function returns -1, an appropriate Python exception will 16 | * have been set, and the function simply returns NULL 17 | */ 18 | 19 | /* call cos from libm */ 20 | answer = cos(value); 21 | 22 | /* construct the output from cos, from c double to python float */ 23 | return Py_BuildValue("f", answer); 24 | } 25 | 26 | /* define functions in module */ 27 | static PyMethodDef CosMethods[] = 28 | { 29 | {"cos_func", cos_func, METH_VARARGS, "evaluate the cosine"}, 30 | {NULL, NULL, 0, NULL} 31 | }; 32 | 33 | /* module initialization */ 34 | PyMODINIT_FUNC 35 | 36 | initcos_module(void) 37 | { 38 | (void) Py_InitModule("cos_module", CosMethods); 39 | } 40 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/python_c_api/setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup, Extension 2 | 3 | # define the extension module 4 | cos_module = Extension('cos_module', sources=['cos_module.c']) 5 | 6 | # run the setup 7 | setup(ext_modules=[cos_module]) 8 | -------------------------------------------------------------------------------- /advanced/interfacing_with_c/swig/cos_module.c: -------------------------------------------------------------------------------- 1 | #include 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 distutils.core import setup, Extension 2 | 3 | setup(ext_modules=[Extension("_cos_module", 4 | 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 funcion, 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 distutils.core import setup, Extension 2 | import numpy 3 | 4 | setup(ext_modules=[Extension("_cos_doubles", 5 | sources=["cos_doubles.c", "cos_doubles.i"], 6 | include_dirs=[numpy.get_include()])]) 7 | -------------------------------------------------------------------------------- /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 | 4 | -------------------------------------------------------------------------------- /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 pylab as pl 10 | 11 | x = np.linspace(-1, 2) 12 | 13 | pl.figure(1, figsize=(3, 2.5)) 14 | pl.clf() 15 | 16 | # A convex function 17 | pl.plot(x, x**2, linewidth=2) 18 | pl.text(-.7, -.6**2, '$f$', size=20) 19 | 20 | # The tangent in one point 21 | pl.plot(x, 2*x - 1) 22 | pl.plot(1, 1, 'k+') 23 | pl.text(.3, -.75, "Tangent to $f$", size=15) 24 | pl.text(1, 1 - .5, 'C', size=15) 25 | 26 | # Convexity as barycenter 27 | pl.plot([.35, 1.85], [.35**2, 1.85**2]) 28 | pl.plot([.35, 1.85], [.35**2, 1.85**2], 'k+') 29 | pl.text(.35 - .2, .35**2 + .1, 'A', size=15) 30 | pl.text(1.85 - .2, 1.85**2, 'B', size=15) 31 | 32 | pl.ylim(ymin=-1) 33 | pl.axis('off') 34 | pl.tight_layout() 35 | 36 | # Convexity as barycenter 37 | pl.figure(2, figsize=(3, 2.5)) 38 | pl.clf() 39 | pl.plot(x, x**2 + np.exp(-5*(x - .5)**2), linewidth=2) 40 | pl.text(-.7, -.6**2, '$f$', size=20) 41 | 42 | pl.ylim(ymin=-1) 43 | pl.axis('off') 44 | pl.tight_layout() 45 | pl.show() 46 | 47 | -------------------------------------------------------------------------------- /advanced/mathematical_optimization/examples/plot_curve_fit.py: -------------------------------------------------------------------------------- 1 | """ 2 | Curve fitting 3 | ============= 4 | 5 | A curve fitting example 6 | """ 7 | 8 | import numpy as np 9 | from scipy import optimize 10 | import pylab as pl 11 | 12 | np.random.seed(0) 13 | 14 | # Our test function 15 | def f(t, omega, phi): 16 | return np.cos(omega * t + phi) 17 | 18 | # Our x and y data 19 | x = np.linspace(0, 3, 50) 20 | y = f(x, 1.5, 1) + .1*np.random.normal(size=50) 21 | 22 | # Fit the model: the parameters omega and phi can be found in the 23 | # `params` vector 24 | params, params_cov = optimize.curve_fit(f, x, y) 25 | 26 | # plot the data and the fitted curve 27 | t = np.linspace(0, 3, 1000) 28 | 29 | pl.figure(1) 30 | pl.clf() 31 | pl.plot(x, y, 'bx') 32 | pl.plot(t, f(t, *params), 'r-') 33 | pl.show() 34 | 35 | -------------------------------------------------------------------------------- /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 | import numpy as np 8 | import pylab as pl 9 | 10 | np.random.seed(0) 11 | 12 | x = np.linspace(-5, 5, 101) 13 | x_ = np.linspace(-5, 5, 31) 14 | 15 | def f(x): 16 | return -np.exp(-x**2) 17 | 18 | # A smooth function 19 | pl.figure(1, figsize=(3, 2.5)) 20 | pl.clf() 21 | 22 | pl.plot(x_, f(x_) + .2*np.random.normal(size=31), linewidth=2) 23 | pl.plot(x, f(x), linewidth=2) 24 | 25 | pl.ylim(ymin=-1.3) 26 | pl.axis('off') 27 | pl.tight_layout() 28 | pl.show() 29 | 30 | -------------------------------------------------------------------------------- /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 | import numpy as np 8 | import pylab as pl 9 | 10 | x = np.linspace(-1.5, 1.5, 101) 11 | 12 | # A smooth function 13 | pl.figure(1, figsize=(3, 2.5)) 14 | pl.clf() 15 | 16 | pl.plot(x, np.sqrt(.2 + x**2), linewidth=2) 17 | pl.text(-1, 0, '$f$', size=20) 18 | 19 | pl.ylim(ymin=-.2) 20 | pl.axis('off') 21 | pl.tight_layout() 22 | 23 | # A non-smooth function 24 | pl.figure(2, figsize=(3, 2.5)) 25 | pl.clf() 26 | pl.plot(x, np.abs(x), linewidth=2) 27 | pl.text(-1, 0, '$f$', size=20) 28 | 29 | pl.ylim(ymin=-.2) 30 | pl.axis('off') 31 | pl.tight_layout() 32 | pl.show() 33 | 34 | -------------------------------------------------------------------------------- /advanced/optimizing/demo-prof.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/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 | from scipy import linalg 5 | 6 | from ica import fastica 7 | 8 | 9 | def test(): 10 | data = np.random.random((5000, 100)) 11 | u, s, v = linalg.svd(data) 12 | pca = np.dot(u[:, :10].T, data) 13 | results = fastica(pca.T, whiten=False) 14 | 15 | if __name__ == '__main__': 16 | test() 17 | -------------------------------------------------------------------------------- /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 | from scipy import linalg 5 | 6 | from ica import fastica 7 | 8 | 9 | def test(): 10 | data = np.random.random((5000, 100)) 11 | u, s, v = linalg.svd(data, full_matrices=False) 12 | pca = np.dot(u[:, :10].T, data) 13 | results = fastica(pca.T, whiten=False) 14 | 15 | if __name__ == '__main__': 16 | test() 17 | -------------------------------------------------------------------------------- /advanced/scipy_sparse/examples/README.txt: -------------------------------------------------------------------------------- 1 | Examples for the scipy sparse matrix chapter 2 | ============================================= 3 | 4 | -------------------------------------------------------------------------------- /advanced/scipy_sparse/examples/direct_solve.py: -------------------------------------------------------------------------------- 1 | """ 2 | Solve a linear system 3 | ======================= 4 | 5 | Construct a 1000x1000 lil_matrix 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 | import numpy as np 10 | import scipy.sparse as sps 11 | from matplotlib import pyplot as plt 12 | from scipy.sparse.linalg.dsolve import linsolve 13 | 14 | rand = np.random.rand 15 | 16 | mtx = sps.lil_matrix((1000, 1000), dtype=np.float64) 17 | mtx[0, :100] = rand(100) 18 | mtx[1, 100:200] = mtx[0, :100] 19 | mtx.setdiag(rand(1000)) 20 | 21 | plt.clf() 22 | plt.spy(mtx, marker='.', markersize=2) 23 | plt.show() 24 | 25 | mtx = mtx.tocsr() 26 | rhs = rand(1000) 27 | 28 | x = linsolve.spsolve(mtx, rhs) 29 | 30 | print('rezidual: %r' % np.linalg.norm(mtx * x - rhs)) 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 scipy 11 | from scipy.sparse.linalg import lobpcg 12 | 13 | from pyamg import smoothed_aggregation_solver 14 | from pyamg.gallery import poisson 15 | 16 | N = 100 17 | K = 9 18 | A = poisson((N,N), format='csr') 19 | 20 | # create the AMG hierarchy 21 | ml = smoothed_aggregation_solver(A) 22 | 23 | # initial approximation to the K eigenvectors 24 | X = scipy.rand(A.shape[0], K) 25 | 26 | # preconditioner based on ml 27 | M = ml.aspreconditioner() 28 | 29 | # compute eigenvalues and eigenvectors with LOBPCG 30 | W,V = lobpcg(A, X, M=M, tol=1e-8, largest=False) 31 | 32 | 33 | #plot the eigenvectors 34 | import pylab 35 | 36 | pylab.figure(figsize=(9,9)) 37 | 38 | for i in range(K): 39 | pylab.subplot(3, 3, i+1) 40 | pylab.title('Eigenvector %d' % i) 41 | pylab.pcolor(V[:,i].reshape(N,N)) 42 | pylab.axis('equal') 43 | pylab.axis('off') 44 | pylab.show() 45 | -------------------------------------------------------------------------------- /advanced/scipy_sparse/figures/graph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/advanced/scipy_sparse/figures/graph.png -------------------------------------------------------------------------------- /advanced/scipy_sparse/figures/graph_g.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/advanced/scipy_sparse/figures/graph_g.png -------------------------------------------------------------------------------- /advanced/scipy_sparse/figures/graph_rcm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/advanced/scipy_sparse/figures/graph_rcm.png -------------------------------------------------------------------------------- /advanced/scipy_sparse/figures/lobpcg_eigenvalues.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/advanced/scipy_sparse/figures/lobpcg_eigenvalues.png -------------------------------------------------------------------------------- /advanced/scipy_sparse/index.rst: -------------------------------------------------------------------------------- 1 | Sparse Matrices 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 | 16 | -------------------------------------------------------------------------------- /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 | * http://pysparse.sourceforge.net/ 11 | -------------------------------------------------------------------------------- /blank_image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/blank_image.png -------------------------------------------------------------------------------- /continuous_integration/show-python-packages-versions.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | DEPENDENCIES = ['numpy', 'scipy', 'sklearn', 'matplotlib'] 4 | 5 | 6 | def print_package_version(package_name, indent=' '): 7 | try: 8 | package = __import__(package_name) 9 | version = getattr(package, '__version__', None) 10 | package_file = getattr(package, '__file__', ) 11 | provenance_info = '{0} from {1}'.format(version, package_file) 12 | except ImportError: 13 | provenance_info = 'not installed' 14 | 15 | print('{0}{1}: {2}'.format(indent, package_name, provenance_info)) 16 | 17 | if __name__ == '__main__': 18 | print('=' * 120) 19 | print('Python %s' % str(sys.version)) 20 | print('from: %s\n' % sys.executable) 21 | 22 | print('Dependencies versions') 23 | for package_name in DEPENDENCIES: 24 | print_package_version(package_name) 25 | print('=' * 120) 26 | -------------------------------------------------------------------------------- /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/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/data/MV_HFV_012.jpg -------------------------------------------------------------------------------- /data/elephant.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/data/elephant.png -------------------------------------------------------------------------------- /data/moonlanding.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/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 | 23 | -------------------------------------------------------------------------------- /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/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/data/test.wav -------------------------------------------------------------------------------- /data/waveform_1.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/data/waveform_1.npy -------------------------------------------------------------------------------- /data/waveform_2.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/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 | 24 | -------------------------------------------------------------------------------- /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 | 6 | -------------------------------------------------------------------------------- /guide/examples/plot_simple.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | X = np.linspace(-np.pi,np.pi,100) 5 | Y = np.sin(X) 6 | plt.plot(X, Y, linewidth=2) 7 | plt.show() 8 | -------------------------------------------------------------------------------- /images/cover-v2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/images/cover-v2.pdf -------------------------------------------------------------------------------- /images/cover.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/images/cover.pdf -------------------------------------------------------------------------------- /images/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/images/favicon.ico -------------------------------------------------------------------------------- /images/logo.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/images/logo.pdf -------------------------------------------------------------------------------- /images/no_image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/images/no_image.png -------------------------------------------------------------------------------- /includes/big_toc_css.rst: -------------------------------------------------------------------------------- 1 | .. 2 | File to ..include in a document with a big table of content, to give 3 | it 'style' 4 | 5 | .. raw:: html 6 | 7 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /includes/bigger_toc_css.rst: -------------------------------------------------------------------------------- 1 | .. 2 | File to ..include in a document with a very big table of content, to 3 | give it 'style' 4 | 5 | .. raw:: html 6 | 7 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /intro/1dPlotting.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/1dPlotting.png -------------------------------------------------------------------------------- /intro/2dPlotting.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/2dPlotting.png -------------------------------------------------------------------------------- /intro/example_surface_from_irregular_data.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/example_surface_from_irregular_data.jpg -------------------------------------------------------------------------------- /intro/help/docwiki.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/help/docwiki.png -------------------------------------------------------------------------------- /intro/help/matplotlib.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/help/matplotlib.png -------------------------------------------------------------------------------- /intro/help/mayavi_website.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/help/mayavi_website.png -------------------------------------------------------------------------------- /intro/help/scipy_doc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/help/scipy_doc.png -------------------------------------------------------------------------------- /intro/image_processing/MV_HFV_012.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/image_processing/MV_HFV_012.jpg -------------------------------------------------------------------------------- /intro/image_processing/exo_histos.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/image_processing/exo_histos.png -------------------------------------------------------------------------------- /intro/image_processing/face_transforms.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/image_processing/face_transforms.png -------------------------------------------------------------------------------- /intro/image_processing/filtered_face.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/image_processing/filtered_face.png -------------------------------------------------------------------------------- /intro/image_processing/measures.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/image_processing/measures.png -------------------------------------------------------------------------------- /intro/image_processing/morpho.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/image_processing/morpho.png -------------------------------------------------------------------------------- /intro/image_processing/morpho_mat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/image_processing/morpho_mat.png -------------------------------------------------------------------------------- /intro/image_processing/sands.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/image_processing/sands.png -------------------------------------------------------------------------------- /intro/image_processing/three_phases.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/image_processing/three_phases.png -------------------------------------------------------------------------------- /intro/index.rst: -------------------------------------------------------------------------------- 1 | 基础教程 2 | =================================================================== 3 | 4 | 这一部分的*Scipy lecture notes*是一个关于Python科学计算的全面教程。它包含了使用Python进行科学计算的大部分知识,从Python语言本身,到数值计算和绘图。 5 | 6 | | 7 | 8 | 9 | .. include:: ../includes/big_toc_css.rst 10 | 11 | .. include:: ../tune_toc.rst 12 | 13 | .. rst-class:: tune 14 | 15 | .. toctree:: 16 | 17 | intro.rst 18 | language/python_language.rst 19 | numpy/index.rst 20 | matplotlib/matplotlib.rst 21 | scipy.rst 22 | help/help.rst 23 | 24 | 25 | -------------------------------------------------------------------------------- /intro/language/demo.py: -------------------------------------------------------------------------------- 1 | "A demo module." 2 | 3 | def print_b(): 4 | "Prints b." 5 | print 'b' 6 | 7 | def print_a(): 8 | "Prints a." 9 | print 'a' 10 | 11 | 12 | c = 2 13 | d = 2 14 | -------------------------------------------------------------------------------- /intro/language/demo2.py: -------------------------------------------------------------------------------- 1 | def print_b(): 2 | "Prints b." 3 | print 'b' 4 | 5 | def print_a(): 6 | "Prints a." 7 | print 'a' 8 | 9 | # print_b() runs on import 10 | print_b() 11 | 12 | if __name__ == '__main__': 13 | # print_a() is only executed when the module is run directly. 14 | print_a() 15 | -------------------------------------------------------------------------------- /intro/language/python-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/language/python-logo.png -------------------------------------------------------------------------------- /intro/language/python_language.rst: -------------------------------------------------------------------------------- 1 | Python 语言 2 | ===================================== 3 | 4 | **Authors**: *Chris Burns, Christophe Combelles, Emmanuelle Gouillart, 5 | Gaël Varoquaux* 6 | 7 | .. topic:: Python -- 科学计算 8 | 9 | 此处我们仅提供了有关Scipy和Numpy密切相关的部分知识.想要更加深入地学习,请参考官方文档 10 | https://docs.python.org/tutorial. 同时也有一些额外的书籍可以参考 http://www.diveintopython.net/. 11 | 12 | .. image:: python-logo.png 13 | :align: right 14 | 15 | .. tip:: 16 | 17 | Python 是一门 **编程语言**, 和 C, Fortran, BASIC, PHP, 18 | 等一样. 下面列出了一些Python的特性: 19 | 20 | * 它是一门 *解释语言* (同 *编译语言* 相对) . 与 C 和 Fortran 等语言相比 21 | Python代码执行之前不需要编译。除此之外,Python代码也可以 **交互式** 执行。 22 | 23 | * 它是一门 **open-source** 协议下的免费软件: Python可以免费地使用,分发, 24 | 甚至是用于商业目的。 25 | 26 | * **跨平台**: Python支持所有主流操作系统,如 Windows, Linux/Unix, MacOS X, most likely your mobile phone 27 | OS 等。 28 | 29 | * 简洁的,具有很高可读性的代码格式 30 | 31 | * 拥有很多的可用于各种用途的扩展包,从网站建设到科学计算。 32 | 33 | * 可以很方便地接入其它编程语言 C 和 C++ 。 34 | 35 | * 其他:Python是一门面向对象的动态语言。 36 | 37 | 38 | 详情参见 https://www.python.org/about/。 39 | 40 | _____ 41 | 42 | .. toctree:: 43 | :maxdepth: 2 44 | 45 | first_steps.rst 46 | basic_types.rst 47 | assignment.rst 48 | control_flow.rst 49 | functions.rst 50 | reusing_code.rst 51 | io.rst 52 | standard_library.rst 53 | exceptions.rst 54 | oop.rst 55 | 56 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/README.txt: -------------------------------------------------------------------------------- 1 | Examples for the the Matplotlib chapter 2 | ======================================== 3 | 4 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/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/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, .8], frameon=False) 16 | 17 | for i in range(1, 11): 18 | plt.axvline(i, linewidth=1, color='blue', alpha= .25 + .75 * i / 10.) 19 | 20 | plt.xlim(0, 11) 21 | plt.xticks(()) 22 | plt.yticks(()) 23 | plt.show() 24 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/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/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([.1, .1, .5, .5]) 12 | plt.xticks(()) 13 | plt.yticks(()) 14 | plt.text(0.1, 0.1, 'axes([0.1, 0.1, .8, .8])', ha='left', va='center', 15 | size=16, alpha=.5) 16 | 17 | plt.axes([.2, .2, .5, .5]) 18 | plt.xticks(()) 19 | plt.yticks(()) 20 | plt.text(0.1, 0.1, 'axes([0.2, 0.2, .5, .5])', ha='left', va='center', 21 | size=16, alpha=.5) 22 | 23 | plt.axes([0.3, 0.3, .5, .5]) 24 | plt.xticks(()) 25 | plt.yticks(()) 26 | plt.text(0.1, 0.1, 'axes([0.3, 0.3, .5, .5])', ha='left', va='center', 27 | size=16, alpha=.5) 28 | 29 | plt.axes([.4, .4, .5, .5]) 30 | plt.xticks(()) 31 | plt.yticks(()) 32 | plt.text(0.1, 0.1, 'axes([0.4, 0.4, .5, .5])', ha='left', va='center', 33 | size=16, alpha=.5) 34 | 35 | plt.show() 36 | -------------------------------------------------------------------------------- /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([.1, .1, .8, .8]) 12 | plt.xticks(()) 13 | plt.yticks(()) 14 | plt.text(.6, .6, 'axes([0.1, 0.1, .8, .8])', ha='center', va='center', 15 | size=20, alpha=.5) 16 | 17 | plt.axes([.2, .2, .3, .3]) 18 | plt.xticks(()) 19 | plt.yticks(()) 20 | plt.text(.5, .5, 'axes([0.2, 0.2, .3, .3])', ha='center', va='center', 21 | size=16, alpha=.5) 22 | 23 | plt.show() 24 | -------------------------------------------------------------------------------- /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 | matplotlib.use('Agg') 11 | import matplotlib.pyplot as plt 12 | 13 | fig = plt.figure(figsize=(5, 4), dpi=72) 14 | axes = fig.add_axes([0.01, 0.01, .98, 0.98]) 15 | x = np.linspace(0, 2, 200, endpoint=True) 16 | y = np.sin(2 * np.pi * x) 17 | plt.plot(x, y, lw=.25, c='k') 18 | plt.xticks(np.arange(0.0, 2.0, 0.1)) 19 | plt.yticks(np.arange(-1.0, 1.0, 0.1)) 20 | plt.grid() 21 | plt.show() 22 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_bar.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(-.5, n) 18 | plt.xticks(()) 19 | plt.ylim(-1, 1) 20 | plt.yticks(()) 21 | 22 | plt.text(-0.05, 1.02, " Bar Plot: plt.bar(...)\n", 23 | horizontalalignment='left', 24 | verticalalignment='top', 25 | size='xx-large', 26 | bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), 27 | transform=plt.gca().transAxes) 28 | 29 | plt.text(-0.05, 1.01, "\n\n Make a bar plot with rectangles ", 30 | horizontalalignment='left', 31 | verticalalignment='top', 32 | size='large', 33 | transform=plt.gca().transAxes) 34 | 35 | plt.show() 36 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_bar_ex.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 | 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 | 16 | plt.axes([0.025, 0.025, 0.95, 0.95]) 17 | plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white') 18 | plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white') 19 | 20 | for x, y in zip(X, Y1): 21 | plt.text(x + 0.4, y + 0.05, '%.2f' % y, ha='center', va= 'bottom') 22 | 23 | for x, y in zip(X, Y2): 24 | plt.text(x + 0.4, -y - 0.05, '%.2f' % y, ha='center', va= 'top') 25 | 26 | plt.xlim(-.5, n) 27 | plt.xticks(()) 28 | plt.ylim(-1.25, 1.25) 29 | plt.yticks(()) 30 | 31 | plt.show() 32 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_boxplot.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 11 | matplotlib.use('Agg') 12 | import matplotlib.pyplot as plt 13 | 14 | 15 | fig = plt.figure(figsize=(8, 5), dpi=72) 16 | fig.patch.set_alpha(0.0) 17 | axes = plt.subplot(111) 18 | 19 | n = 5 20 | Z = np.zeros((n, 4)) 21 | X = np.linspace(0, 2, n, endpoint=True) 22 | Y = np.random.random((n, 4)) 23 | plt.boxplot(Y) 24 | 25 | plt.xticks(()), plt.yticks(()) 26 | 27 | plt.text(-0.05, 1.02, " Box Plot: plt.boxplot(...)\n", 28 | horizontalalignment='left', 29 | verticalalignment='top', 30 | size='xx-large', 31 | bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), 32 | transform=axes.transAxes) 33 | 34 | plt.text(-0.05, 1.01, " Make a box and whisker plot ", 35 | horizontalalignment='left', 36 | verticalalignment='top', 37 | size='large', 38 | transform=axes.transAxes) 39 | 40 | plt.show() 41 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/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, .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/plot_colormaps.py: -------------------------------------------------------------------------------- 1 | """ 2 | Colormaps 3 | ========= 4 | 5 | An example plotting the matplotlib colormaps. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | plt.rc('text', usetex=False) 12 | a = np.outer(np.arange(0, 1, 0.01), np.ones(10)) 13 | 14 | plt.figure(figsize=(10, 5)) 15 | plt.subplots_adjust(top=0.8, bottom=0.05, left=0.01, right=0.99) 16 | maps = [m for m in plt.cm.datad if not m.endswith("_r")] 17 | maps.sort() 18 | l = len(maps) + 1 19 | 20 | for i, m in enumerate(maps): 21 | plt.subplot(1, l, i+1) 22 | plt.axis("off") 23 | plt.imshow(a, aspect='auto', cmap=plt.get_cmap(m), origin="lower") 24 | plt.title(m, rotation=90, fontsize=10, va='bottom') 25 | 26 | plt.show() 27 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_contour.py: -------------------------------------------------------------------------------- 1 | """ 2 | Display the contours of a function 3 | =================================== 4 | 5 | An example demoing how to plot the contours of a function, with 6 | additional layout tweeks. 7 | 8 | """ 9 | 10 | import numpy as np 11 | import matplotlib.pyplot as plt 12 | 13 | def f(x,y): 14 | return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) 15 | 16 | n = 256 17 | x = np.linspace(-3, 3, n) 18 | y = np.linspace(-3, 3, n) 19 | X, Y = np.meshgrid(x, y) 20 | 21 | plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.hot) 22 | C = plt.contour(X, Y, f(X,Y), 8, colors='black', linewidth=.5) 23 | plt.clabel(C, inline=1, fontsize=10) 24 | plt.xticks(()) 25 | plt.yticks(()) 26 | 27 | plt.text(-0.05, 1.02, " Contour Plot: plt.contour(..)\n", 28 | horizontalalignment='left', 29 | verticalalignment='top', 30 | size='xx-large', 31 | bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), 32 | transform=plt.gca().transAxes) 33 | 34 | plt.text(-0.05, 1.01, "\n\n Draw contour lines and filled contours ", 35 | horizontalalignment='left', 36 | verticalalignment='top', 37 | size='large', 38 | transform=plt.gca().transAxes) 39 | 40 | plt.show() 41 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_contour_ex.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 | def f(x,y): 13 | return (1 - x / 2 + x**5 + y**3) * np.exp(-x**2 -y**2) 14 | 15 | n = 256 16 | x = np.linspace(-3, 3, n) 17 | y = np.linspace(-3, 3, n) 18 | X,Y = np.meshgrid(x, y) 19 | 20 | plt.axes([0.025, 0.025, 0.95, 0.95]) 21 | 22 | plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.hot) 23 | C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5) 24 | plt.clabel(C, inline=1, fontsize=10) 25 | 26 | plt.xticks(()) 27 | plt.yticks(()) 28 | plt.show() 29 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/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(np.arange(4), np.ones(4), color="blue", dashes=[15, 15], 19 | linewidth=8, dash_capstyle='butt') 20 | 21 | plt.plot(5 + np.arange(4), np.ones(4), color="blue", dashes=[15, 15], 22 | linewidth=8, dash_capstyle='round') 23 | 24 | plt.plot(10 + np.arange(4), np.ones(4), color="blue", dashes=[15, 15], 25 | linewidth=8, dash_capstyle='projecting') 26 | 27 | plt.xlim(0, 14) 28 | plt.xticks(()) 29 | plt.yticks(()) 30 | 31 | plt.show() 32 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/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(np.arange(3), [0, 1, 0], color="blue", dashes=[12, 5], linewidth=8, 19 | dash_joinstyle='miter') 20 | plt.plot(4 + np.arange(3), [0, 1, 0], color="blue", dashes=[12, 5], 21 | linewidth=8, dash_joinstyle='bevel') 22 | plt.plot(8 + np.arange(3), [0, 1, 0], color="blue", dashes=[12, 5], 23 | linewidth=8, dash_joinstyle='round') 24 | 25 | plt.xlim(0, 12) 26 | plt.ylim(-1, 2) 27 | plt.xticks(()) 28 | plt.yticks(()) 29 | 30 | plt.show() 31 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_exercice_1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Excercise 1 3 | =========== 4 | 5 | Solution of the excercise 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, endpoint=True) 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/plot_exercice_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, endpoint=True) 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., 4.) 28 | 29 | # Set x ticks 30 | plt.xticks(np.linspace(-4, 4, 9, endpoint=True)) 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, endpoint=True)) 37 | 38 | # Show result on screen 39 | plt.show() 40 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_exercice_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, endpoint=True) 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, endpoint=True)) 22 | 23 | plt.ylim(-1.0, 1.0) 24 | plt.yticks(np.linspace(-1, 1, 5, endpoint=True)) 25 | 26 | plt.show() 27 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_exercice_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, endpoint=True) 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/plot_exercice_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, endpoint=True) 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/plot_exercice_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, 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 | 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 | [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) 24 | 25 | plt.ylim(C.min() * 1.1, C.max() * 1.1) 26 | plt.yticks([-1, 0, +1], 27 | [r'$-1$', r'$0$', r'$+1$']) 28 | 29 | plt.show() 30 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_exercice_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([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], 31 | [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) 32 | 33 | plt.ylim(C.min() * 1.1, C.max() * 1.1) 34 | plt.yticks([-1, 0, +1], 35 | [r'$-1$', r'$0$', r'$+1$']) 36 | 37 | plt.show() 38 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_exercice_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([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], 31 | [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) 32 | 33 | plt.ylim(C.min() * 1.1, C.max() * 1.1) 34 | plt.yticks([-1, +1], 35 | [r'$-1$', r'$+1$']) 36 | 37 | plt.legend(loc='upper left') 38 | 39 | plt.show() 40 | -------------------------------------------------------------------------------- /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 | matplotlib.use('Agg') 11 | import matplotlib.pyplot as plt 12 | 13 | fig = plt.figure(figsize=(5, 4), dpi=72) 14 | axes = fig.add_axes([0.01, 0.01, .98, 0.98]) 15 | X = np.linspace(0, 2, 200, endpoint=True) 16 | Y = np.sin(2*np.pi*X) 17 | plt.plot(X, Y, lw=2) 18 | plt.ylim(-1.1, 1.1) 19 | plt.grid() 20 | 21 | plt.show() 22 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_grid_ex.py: -------------------------------------------------------------------------------- 1 | """ 2 | Grid 3 | ==== 4 | 5 | Displaying a grid on the axes in matploblib. 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | 10 | ax = plt.axes([0.025, 0.025, 0.95, 0.95]) 11 | 12 | ax.set_xlim(0,4) 13 | ax.set_ylim(0,3) 14 | ax.xaxis.set_major_locator(plt.MultipleLocator(1.0)) 15 | ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1)) 16 | ax.yaxis.set_major_locator(plt.MultipleLocator(1.0)) 17 | ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1)) 18 | ax.grid(which='major', axis='x', linewidth=0.75, linestyle='-', color='0.75') 19 | ax.grid(which='minor', axis='x', linewidth=0.25, linestyle='-', color='0.75') 20 | ax.grid(which='major', axis='y', linewidth=0.75, linestyle='-', color='0.75') 21 | ax.grid(which='minor', axis='y', linewidth=0.25, linestyle='-', color='0.75') 22 | ax.set_xticklabels([]) 23 | ax.set_yticklabels([]) 24 | 25 | plt.show() 26 | -------------------------------------------------------------------------------- /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 | import matplotlib.gridspec as 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=.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=.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=.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=.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=.5) 38 | 39 | plt.tight_layout() 40 | plt.show() 41 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_imshow.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 | def f(x, y): 12 | return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) 13 | 14 | n = 10 15 | x = np.linspace(-3, 3, 8 * n) 16 | y = np.linspace(-3, 3, 6 * n) 17 | X, Y = np.meshgrid(x, y) 18 | Z = f(X, Y) 19 | plt.imshow(Z, interpolation='nearest', cmap='bone', origin='lower') 20 | plt.xticks(()) 21 | plt.yticks(()) 22 | 23 | plt.text(-0.05, 1.02, " Imshow: plt.imshow(...)\n", 24 | horizontalalignment='left', 25 | verticalalignment='top', 26 | size='xx-large', 27 | bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), 28 | transform=plt.gca().transAxes) 29 | 30 | plt.text(-0.05, 1.01, "\n\n Display an image to current axes ", 31 | horizontalalignment='left', 32 | verticalalignment='top', 33 | family='Lint McCree Intl BB', 34 | size='large', 35 | transform=plt.gca().transAxes) 36 | 37 | plt.show() 38 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_imshow_ex.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 | def f(x, y): 12 | return (1 - x / 2 + x ** 5 + y ** 3 ) * np.exp(-x ** 2 - y ** 2) 13 | 14 | n = 10 15 | x = np.linspace(-3, 3, 3.5 * n) 16 | y = np.linspace(-3, 3, 3.0 * n) 17 | X, Y = np.meshgrid(x, y) 18 | Z = f(X, Y) 19 | 20 | plt.axes([0.025, 0.025, 0.95, 0.95]) 21 | plt.imshow(Z, interpolation='nearest', cmap='bone', origin='lower') 22 | plt.colorbar(shrink=.92) 23 | 24 | plt.xticks(()) 25 | plt.yticks(()) 26 | plt.show() 27 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/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 | def linestyle(ls, i): 12 | X = i * .5 * np.ones(11) 13 | Y = np.arange(11) 14 | plt.plot(X, Y, ls, color=(.0, .0, 1, 1), lw=3, ms=8, 15 | mfc=(.75, .75, 1, 1), mec=(0, 0, 1, 1)) 16 | plt.text(.5 * i, 10.25, ls, rotation=90, fontsize=15, va='bottom') 17 | 18 | linestyles = ['-', '--', ':', '-.', '.', ',', 'o', '^', 'v', '<', '>', 's', 19 | '+', 'x', 'd', '1', '2', '3', '4', 'h', 'p', '|', '_', 'D', 'H'] 20 | n_lines = len(linestyles) 21 | 22 | size = 20 * n_lines, 300 23 | dpi = 72.0 24 | figsize= size[0] / float(dpi), size[1] / float(dpi) 25 | fig = plt.figure(figsize=figsize, dpi=dpi) 26 | fig.patch.set_alpha(0) 27 | plt.axes([0, 0.01, 1, .9], frameon=False) 28 | 29 | for i, ls in enumerate(linestyles): 30 | linestyle(ls, i) 31 | 32 | plt.xlim(-.2, .2 + .5*n_lines) 33 | plt.xticks(()) 34 | plt.yticks(()) 35 | 36 | plt.show() 37 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/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, .1, 1, .8], frameon=False) 16 | 17 | for i in range(1, 11): 18 | plt.plot([i, i], [0, 1], color='b', lw=i/2.) 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/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 | def marker(m, i): 12 | X = i * .5 * np.ones(11) 13 | Y = np.arange(11) 14 | 15 | plt.plot(X, Y, lw=1, marker=m, ms=10, mfc=(.75, .75, 1, 1), 16 | mec=(0, 0, 1, 1)) 17 | plt.text(.5 * i, 10.25, repr(m), rotation=90, fontsize=15, va='bottom') 18 | 19 | markers = [0, 1, 2, 3, 4, 5, 6, 7, 'o', 'h', '_', '1', '2', '3', '4', 20 | '8', 'p', '^', 'v', '<', '>', '|', 'd', ',', '+', 's', '*', 21 | '|', 'x', 'D', 'H', '.'] 22 | 23 | n_markers = len(markers) 24 | 25 | size = 20 * n_markers, 300 26 | dpi = 72.0 27 | figsize= size[0] / float(dpi), size[1] / float(dpi) 28 | fig = plt.figure(figsize=figsize, dpi=dpi) 29 | fig.patch.set_alpha(0) 30 | plt.axes([0, 0.01, 1, .9], frameon=False) 31 | 32 | for i, m in enumerate(markers): 33 | marker(m, i) 34 | 35 | plt.xlim(-.2, .2 + .5 * n_markers) 36 | plt.xticks(()) 37 | plt.yticks(()) 38 | 39 | plt.show() 40 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/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 | for i in range(1, 11): 19 | r, g, b = np.random.uniform(0, 1, 3) 20 | plt.plot([i, ], [1, ], 's', markersize=5, markerfacecolor='w', 21 | markeredgewidth=1.5, markeredgecolor=(r, g, b, 1)) 22 | 23 | plt.xlim(0, 11) 24 | plt.xticks(()) 25 | plt.yticks(()) 26 | 27 | plt.show() 28 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/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([i, ], [1, ], 's', markersize=5, 19 | markeredgewidth=1 + i/10., markeredgecolor='k', markerfacecolor='w') 20 | plt.xlim(0, 11) 21 | plt.xticks(()) 22 | plt.yticks(()) 23 | 24 | plt.show() 25 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/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 | for i in range(1, 11): 19 | r, g, b = np.random.uniform(0, 1, 3) 20 | plt.plot([i, ], [1, ], 's', markersize=8, markerfacecolor=(r, g, b, 1), 21 | markeredgewidth=.1, markeredgecolor=(0, 0, 0, .5)) 22 | plt.xlim(0, 11) 23 | plt.xticks(()) 24 | plt.yticks(()) 25 | plt.show() 26 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/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([i, ], [1, ], 's', markersize=i, markerfacecolor='w', 19 | markeredgewidth=.5, markeredgecolor='k') 20 | 21 | plt.xlim(0, 11) 22 | plt.xticks(()) 23 | plt.yticks(()) 24 | 25 | plt.show() 26 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_multiplot.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 | plt.text(-0.05, 1.02, " Multiplot: plt.subplot(...)\n", 15 | horizontalalignment='left', 16 | verticalalignment='top', 17 | size='xx-large', 18 | bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), 19 | transform=ax.transAxes) 20 | plt.text(-0.05, 1.01, "\n\n Plot several plots at once ", 21 | horizontalalignment='left', 22 | verticalalignment='top', 23 | size='large', 24 | transform=ax.transAxes) 25 | 26 | ax = plt.subplot(2, 2, 3) 27 | ax.set_xticklabels([]) 28 | ax.set_yticklabels([]) 29 | 30 | ax = plt.subplot(2, 2, 4) 31 | ax.set_xticklabels([]) 32 | ax.set_yticklabels([]) 33 | 34 | plt.show() 35 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_multiplot_ex.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 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*.05, colors = ['%f' % (i/float(n)) 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 | plt.text(-0.05, 1.02, " Pie Chart: plt.pie(...)\n", 26 | horizontalalignment='left', 27 | verticalalignment='top', 28 | size='xx-large', 29 | bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), 30 | transform=plt.gca().transAxes) 31 | 32 | plt.text(-0.05, 1.01, "\n\n Make a pie chart of an array ", 33 | horizontalalignment='left', 34 | verticalalignment='top', 35 | size='large', 36 | transform=plt.gca().transAxes) 37 | 38 | plt.show() 39 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_pie_ex.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*.05, colors = ['%f' % (i/float(n)) 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 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 | plt.text(-0.05, 1.02, " Regular Plot: plt.plot(...)\n", 22 | horizontalalignment='left', 23 | verticalalignment='top', 24 | size='xx-large', 25 | bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), 26 | transform=plt.gca().transAxes) 27 | 28 | plt.text(-0.05, 1.01, "\n\n Plot lines and/or markers ", 29 | horizontalalignment='left', 30 | verticalalignment='top', 31 | size='large', 32 | transform=plt.gca().transAxes) 33 | 34 | plt.show() 35 | -------------------------------------------------------------------------------- /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 import axes3d 10 | 11 | ax = plt.gca(projection='3d') 12 | X, Y, Z = axes3d.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 | ax.text2D(-0.05, 1.05, " 3D plots \n\n", 21 | horizontalalignment='left', 22 | verticalalignment='top', 23 | family='Lint McCree Intl BB', 24 | size='x-large', 25 | bbox=dict(facecolor='white', alpha=1.0, width=350,height=60), 26 | transform=plt.gca().transAxes) 27 | 28 | ax.text2D(-0.05, .975, " Plot 2D or 3D data", 29 | horizontalalignment='left', 30 | verticalalignment='top', 31 | family='Lint McCree Intl BB', 32 | size='medium', 33 | transform=plt.gca().transAxes) 34 | 35 | plt.show() 36 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_plot3d.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 | fig = plt.figure() 13 | ax = Axes3D(fig) 14 | X = np.arange(-4, 4, 0.25) 15 | Y = np.arange(-4, 4, 0.25) 16 | X, Y = np.meshgrid(X, Y) 17 | R = np.sqrt(X ** 2 + Y ** 2) 18 | Z = np.sin(R) 19 | 20 | ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.hot) 21 | ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.cm.hot) 22 | ax.set_zlim(-2, 2) 23 | plt.xticks(()) 24 | plt.yticks(()) 25 | ax.set_zticks(()) 26 | 27 | ax.text2D(0.05, .93, " 3D plots \n", 28 | horizontalalignment='left', 29 | verticalalignment='top', 30 | size='xx-large', 31 | bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), 32 | transform=plt.gca().transAxes) 33 | 34 | ax.text2D(0.05, .87, " Plot 2D or 3D data", 35 | horizontalalignment='left', 36 | verticalalignment='top', 37 | size='large', 38 | transform=plt.gca().transAxes) 39 | 40 | plt.show() 41 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_plot3d_ex.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 | fig = plt.figure() 13 | ax = Axes3D(fig) 14 | X = np.arange(-4, 4, 0.25) 15 | Y = np.arange(-4, 4, 0.25) 16 | X, Y = np.meshgrid(X, Y) 17 | R = np.sqrt(X ** 2 + Y ** 2) 18 | Z = np.sin(R) 19 | 20 | ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.hot) 21 | ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.cm.hot) 22 | ax.set_zlim(-2, 2) 23 | 24 | plt.show() 25 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_plot_ex.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, endpoint=True) 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=.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=.25) 22 | plt.fill_between(X, -1, Y - 1, (Y - 1) < -1, color='red', alpha=.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_polar.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plotting in polar, decorated 3 | ============================= 4 | 5 | An example showing how to plot in polar coordinnate, and some 6 | decorations. 7 | """ 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | 12 | plt.subplot(1, 1, 1, polar=True) 13 | 14 | N = 20 15 | theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N) 16 | radii = 10 * np.random.rand(N) 17 | width = np.pi / 4 * np.random.rand(N) 18 | bars = plt.bar(theta, radii, width=width, bottom=0.0) 19 | for r, bar in zip(radii, bars): 20 | bar.set_facecolor(plt.cm.jet(r / 10.)) 21 | bar.set_alpha(0.5) 22 | plt.gca().set_xticklabels([]) 23 | plt.gca().set_yticklabels([]) 24 | 25 | plt.text(-0.2, 1.02, " Polar Axis\n", 26 | horizontalalignment='left', 27 | verticalalignment='top', 28 | size='xx-large', 29 | bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), 30 | transform=plt.gca().transAxes) 31 | plt.text(-0.2, 1.01, "\n\n Plot anything using polar axis ", 32 | horizontalalignment='left', 33 | verticalalignment='top', 34 | size='large', 35 | transform=plt.gca().transAxes) 36 | 37 | plt.show() 38 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_polar_ex.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plotting in polar coordinnates 3 | =============================== 4 | 5 | A simple example showing how to plot in polar coordinnates with 6 | matplotlib. 7 | """ 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | 12 | ax = plt.axes([0.025, 0.025, 0.95, 0.95], polar=True) 13 | 14 | N = 20 15 | theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N) 16 | radii = 10 * np.random.rand(N) 17 | width = np.pi / 4 * np.random.rand(N) 18 | bars = plt.bar(theta, radii, width=width, bottom=0.0) 19 | 20 | for r,bar in zip(radii, bars): 21 | bar.set_facecolor(plt.cm.jet(r/10.)) 22 | bar.set_alpha(0.5) 23 | 24 | ax.set_xticklabels([]) 25 | ax.set_yticklabels([]) 26 | plt.show() 27 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_quiver.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plotting quiver decorated 3 | ========================== 4 | 5 | An example showing quiver with decorations. 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | n = 8 12 | X, Y = np.mgrid[0:n, 0:n] 13 | T = np.arctan2(Y - n/ 2., X - n / 2.) 14 | R = 10 + np.sqrt((Y - n / 2.) ** 2 + (X - n / 2.) ** 2) 15 | U, V = R * np.cos(T), R * np.sin(T) 16 | 17 | plt.quiver(X, Y, U, V, R, alpha=.5) 18 | plt.quiver(X, Y, U, V, edgecolor='k', facecolor='None', linewidth=.5) 19 | 20 | plt.xlim(-1, n) 21 | plt.xticks(()) 22 | plt.ylim(-1, n) 23 | plt.yticks(()) 24 | 25 | plt.text(-0.05, 1.02, " Quiver Plot: plt.quiver(...)\n", 26 | horizontalalignment='left', 27 | verticalalignment='top', 28 | size='xx-large', 29 | bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), 30 | transform=plt.gca().transAxes) 31 | 32 | plt.text(-0.05, 1.01, "\n\n Plot a 2-D field of arrows ", 33 | horizontalalignment='left', 34 | verticalalignment='top', 35 | size='large', 36 | transform=plt.gca().transAxes) 37 | 38 | plt.show() 39 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_quiver_ex.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., X - n/2.) 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=.5) 20 | plt.quiver(X, Y, U, V, edgecolor='k', facecolor='None', linewidth=.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 | 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 | X = np.random.normal(0, 1, n) 13 | Y = np.random.normal(0, 1, n) 14 | 15 | T = np.arctan2(Y,X) 16 | 17 | plt.scatter(X, Y, s=75, c=T, alpha=.5) 18 | plt.xlim(-1.5, 1.5) 19 | plt.xticks(()) 20 | plt.ylim(-1.5, 1.5) 21 | plt.yticks(()) 22 | 23 | plt.text(-0.05, 1.02, " Scatter Plot: plt.scatter(...)\n", 24 | horizontalalignment='left', 25 | verticalalignment='top', 26 | size='xx-large', 27 | bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), 28 | transform=plt.gca().transAxes) 29 | 30 | plt.text(-0.05, 1.01, "\n\n Make a scatter plot of x versus y ", 31 | horizontalalignment='left', 32 | verticalalignment='top', 33 | size='large', 34 | transform=plt.gca().transAxes) 35 | 36 | plt.show() 37 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_scatter_ex.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 | X = np.random.normal(0, 1, n) 13 | Y = np.random.normal(0, 1, n) 14 | T = np.arctan2(Y, X) 15 | 16 | plt.axes([0.025, 0.025, 0.95, 0.95]) 17 | plt.scatter(X, Y, s=75, c=T, alpha=.5) 18 | 19 | plt.xlim(-1.5, 1.5) 20 | plt.xticks(()) 21 | plt.ylim(-1.5, 1.5) 22 | plt.yticks(()) 23 | 24 | plt.show() 25 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/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, 19 | solid_capstyle='butt') 20 | 21 | plt.plot(5 + np.arange(4), np.ones(4), color="blue", linewidth=8, 22 | solid_capstyle='round') 23 | 24 | plt.plot(10 + np.arange(4), np.ones(4), color="blue", linewidth=8, 25 | solid_capstyle='projecting') 26 | 27 | plt.xlim(0, 14) 28 | plt.xticks(()) 29 | plt.yticks(()) 30 | 31 | plt.show() 32 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_solid_joinstyle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Solid joint style 3 | ================== 4 | 5 | An example showing the differen 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, 19 | solid_joinstyle='miter') 20 | plt.plot(4 + np.arange(3), [0, 1, 0], color="blue", linewidth=8, 21 | solid_joinstyle='bevel') 22 | plt.plot(8 + np.arange(3), [0, 1, 0], color="blue", linewidth=8, 23 | solid_joinstyle='round') 24 | 25 | plt.xlim(0, 12) 26 | plt.ylim(-1, 2) 27 | plt.xticks(()) 28 | plt.yticks(()) 29 | 30 | plt.show() 31 | -------------------------------------------------------------------------------- /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', 15 | size=20, alpha=.5) 16 | 17 | plt.subplot(2, 2, 2) 18 | plt.xticks(()) 19 | plt.yticks(()) 20 | plt.text(0.5, 0.5, 'subplot(2,2,2)', ha='center', va='center', 21 | size=20, alpha=.5) 22 | 23 | plt.subplot(2, 2, 3) 24 | plt.xticks(()) 25 | plt.yticks(()) 26 | 27 | plt.text(0.5, 0.5, 'subplot(2,2,3)', ha='center', va='center', 28 | size=20, alpha=.5) 29 | 30 | plt.subplot(2, 2, 4) 31 | plt.xticks(()) 32 | plt.yticks(()) 33 | plt.text(0.5, 0.5, 'subplot(2,2,4)', ha='center', va='center', 34 | size=20, alpha=.5) 35 | 36 | plt.tight_layout() 37 | plt.show() 38 | -------------------------------------------------------------------------------- /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', 15 | size=24, alpha=.5) 16 | 17 | plt.subplot(2, 1, 2) 18 | plt.xticks(()) 19 | plt.yticks(()) 20 | plt.text(0.5, 0.5, 'subplot(2,1,2)', ha='center', va='center', 21 | size=24, alpha=.5) 22 | 23 | plt.tight_layout() 24 | plt.show() 25 | -------------------------------------------------------------------------------- /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', 16 | size=24, alpha=.5) 17 | 18 | plt.subplot(1, 2, 2) 19 | plt.xticks(()) 20 | plt.yticks(()) 21 | plt.text(0.5, 0.5, 'subplot(1,2,2)', ha='center', va='center', 22 | size=24, alpha=.5) 23 | 24 | plt.tight_layout() 25 | plt.show() 26 | -------------------------------------------------------------------------------- /intro/matplotlib/examples/plot_text_ex.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((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]$")) 14 | eqs.append((r"$\frac{d\rho}{d t} + \rho \vec{v}\cdot\nabla\vec{v} = -\nabla p + \mu\nabla^2 \vec{v} + \rho \vec{g}$")) 15 | eqs.append((r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$")) 16 | eqs.append((r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$")) 17 | eqs.append((r"$F_G = G\frac{m_1m_2}{r^2}$")) 18 | 19 | plt.axes([0.025, 0.025, 0.95, 0.95]) 20 | 21 | for i in range(24): 22 | index = np.random.randint(0, len(eqs)) 23 | eq = eqs[index] 24 | size = np.random.uniform(12, 32) 25 | x,y = np.random.uniform(0, 1, 2) 26 | alpha = np.random.uniform(0.25, .75) 27 | plt.text(x, y, eq, ha='center', va='center', color="#11557c", alpha=alpha, 28 | transform=plt.gca().transAxes, fontsize=size, clip_on=True) 29 | plt.xticks(()) 30 | plt.yticks(()) 31 | 32 | plt.show() 33 | -------------------------------------------------------------------------------- /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 | matplotlib.use('Agg') 11 | import matplotlib.pyplot as plt 12 | 13 | matplotlib.rc('grid', color='black', linestyle='-', linewidth=1) 14 | 15 | fig = plt.figure(figsize=(5,4),dpi=72) 16 | axes = fig.add_axes([0.01, 0.01, .98, 0.98], axisbg='.75') 17 | X = np.linspace(0, 2, 40, endpoint=True) 18 | Y = np.sin(2 * np.pi * X) 19 | plt.plot(X, Y, lw=.05, c='b', antialiased=False) 20 | 21 | plt.xticks(()) 22 | plt.yticks(np.arange(-1., 1., 0.2)) 23 | plt.grid() 24 | ax = plt.gca() 25 | 26 | plt.show() 27 | -------------------------------------------------------------------------------- /intro/numpy/data: -------------------------------------------------------------------------------- 1 | ../../data/ -------------------------------------------------------------------------------- /intro/numpy/images/cpu-cacheline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/numpy/images/cpu-cacheline.png -------------------------------------------------------------------------------- /intro/numpy/images/faces.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/numpy/images/faces.png -------------------------------------------------------------------------------- /intro/numpy/images/markov-chain.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/numpy/images/markov-chain.png -------------------------------------------------------------------------------- /intro/numpy/images/numpy_broadcasting.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/numpy/images/numpy_broadcasting.png -------------------------------------------------------------------------------- /intro/numpy/images/numpy_fancy_indexing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/numpy/images/numpy_fancy_indexing.png -------------------------------------------------------------------------------- /intro/numpy/images/numpy_indexing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/numpy/images/numpy_indexing.png -------------------------------------------------------------------------------- /intro/numpy/images/prime-sieve.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/numpy/images/prime-sieve.png -------------------------------------------------------------------------------- /intro/numpy/images/random_walk.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/numpy/images/random_walk.png -------------------------------------------------------------------------------- /intro/numpy/images/random_walk_schema.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/numpy/images/random_walk_schema.png -------------------------------------------------------------------------------- /intro/numpy/images/reductions.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/numpy/images/reductions.png -------------------------------------------------------------------------------- /intro/numpy/images/route66.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/numpy/images/route66.png -------------------------------------------------------------------------------- /intro/numpy/images/surf.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/numpy/images/surf.png -------------------------------------------------------------------------------- /intro/numpy/images/threefundamental.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/numpy/images/threefundamental.png -------------------------------------------------------------------------------- /intro/numpy/index.rst: -------------------------------------------------------------------------------- 1 | .. _numpy: 2 | 3 | *********************************************** 4 | NumPy: 操作和处理数据 5 | *********************************************** 6 | 7 | **作者**: *Emmanuelle Gouillart, Didrik Pinte, Gaël Varoquaux, and 8 | Pauli Virtanen* 9 | 10 | .. .. contents:: Chapters contents 11 | :local: 12 | :depth: 4 13 | 14 | 这一章节大致介绍了Numpy,Numpy是Python高效数值计算的核心工具。 15 | 16 | ____ 17 | 18 | .. include:: ../../includes/big_toc_css.rst 19 | 20 | .. toctree:: 21 | array_object.rst 22 | operations.rst 23 | elaborate_arrays.rst 24 | advanced_operations.rst 25 | exercises.rst 26 | -------------------------------------------------------------------------------- /intro/numpy/random_walk.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/numpy/random_walk.png -------------------------------------------------------------------------------- /intro/numpy/random_walk_schema.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/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 xrange(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 xrange(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 | plt.plot(year, hare_grad, year, -lynxes) 32 | plt.savefig('plot.png') 33 | -------------------------------------------------------------------------------- /intro/numpy/solutions/2_3_crude_integration.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from numpy import newaxis 3 | 4 | def f(a, b, c): 5 | return a**b - c 6 | 7 | a = np.linspace(0, 1, 24) 8 | b = np.linspace(0, 1, 12) 9 | c = np.linspace(0, 1, 6) 10 | 11 | samples = f(a[:,newaxis,newaxis], 12 | b[newaxis,:,newaxis], 13 | 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 | import numpy as np 5 | import matplotlib.pyplot as plt 6 | from numpy import newaxis 7 | 8 | def compute_mandelbrot(N_max, some_threshold, nx, ny): 9 | # A grid of c-values 10 | x = np.linspace(-2, 1, nx) 11 | y = np.linspace(-1.5, 1.5, ny) 12 | 13 | c = x[:,newaxis] + 1j*y[newaxis,:] 14 | 15 | # Mandelbrot iteration 16 | 17 | z = c 18 | for j in xrange(N_max): 19 | z = z**2 + c 20 | 21 | mandelbrot_set = (abs(z) < some_threshold) 22 | 23 | return mandelbrot_set 24 | 25 | # Save 26 | 27 | mandelbrot_set = compute_mandelbrot(50, 50., 601, 401) 28 | 29 | plt.imshow(mandelbrot_set.T, extent=[-2, 1, -1.5, 1.5]) 30 | plt.gray() 31 | plt.savefig('mandelbrot.png') 32 | -------------------------------------------------------------------------------- /intro/numpy/solutions/2_5_markov_chain.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | np.random.seed(1234) 4 | 5 | n_states = 5 6 | n_steps = 50 7 | tolerance = 1e-5 8 | 9 | # Random transition matrix and state vector 10 | P = np.random.rand(n_states, n_states) 11 | p = np.random.rand(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 xrange(n_steps): 21 | p = P.T.dot(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 | def some_function(input): 5 | """ 6 | Call a Fortran routine, and preserve input shape 7 | """ 8 | input = np.asarray(input) 9 | # fortran_module.some_function() only accepts 1-D arrays! 10 | output = fortran_module.some_function(input.ravel()) 11 | return output.reshape(input.shape) 12 | 13 | print some_function(np.array([1, 2, 3])) 14 | print some_function(np.array([[1, 2], [3, 4]])) 15 | -------------------------------------------------------------------------------- /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/phd053104s.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/phd053104s.png -------------------------------------------------------------------------------- /intro/random_c.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/random_c.jpg -------------------------------------------------------------------------------- /intro/snapshot_ipython.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/snapshot_ipython.png -------------------------------------------------------------------------------- /intro/solutions/curvefit_temperature_data.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | from scipy import optimize 4 | 5 | 6 | temp_max = np.array([17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18]) 7 | temp_min = np.array([-62, -59, -56, -46, -32, -18, -9, -13, -25, -46, -52, -58]) 8 | 9 | def yearly_temps(times, avg, ampl, time_offset): 10 | return avg + ampl * np.cos((times + time_offset) * 2 * np.pi / times.max()) 11 | 12 | months = np.arange(12) 13 | res_max, cov_max = optimize.curve_fit(yearly_temps, months, 14 | temp_max, [20, 10, 0]) 15 | res_min, cov_min = optimize.curve_fit(yearly_temps, months, 16 | temp_min, [-40, 20, 0]) 17 | 18 | days = np.linspace(0, 12, num=365) 19 | plt.plot(months, temp_max, 'ro') 20 | plt.plot(days, yearly_temps(days, *res_max), 'r-') 21 | plt.plot(months, temp_min, 'bo') 22 | plt.plot(days, yearly_temps(days, *res_min), 'b-') 23 | plt.xlabel('Month') 24 | plt.ylabel('Temperature ($^\circ$C)') 25 | 26 | plt.show() 27 | -------------------------------------------------------------------------------- /intro/solutions/data.txt: -------------------------------------------------------------------------------- 1 | 10.2 2 | 43.1 3 | 32.6 4 | 32.5 5 | 61.3 6 | 58.2 -------------------------------------------------------------------------------- /intro/solutions/data_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 | def load_data(filename): 7 | fp = open(filename) 8 | data_string = fp.read() 9 | fp.close() 10 | 11 | data = [] 12 | for x in data_string.split(): 13 | # Data is read in as a string. We need to convert it to floats 14 | data.append(float(x)) 15 | 16 | # Could instead use the following one line with list comprehensions! 17 | # data = [float(x) for x in data_string.split()] 18 | return data 19 | 20 | if __name__ == '__main__': 21 | data = load_data('data.txt') 22 | # Python provides these basic math functions 23 | print('min: %f' % min(data)) 24 | print('max: %f' % max(data)) 25 | print('sum: %f' % sum(data)) 26 | -------------------------------------------------------------------------------- /intro/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 15 | if filename.endswith('.py')] 16 | 17 | def key(item): 18 | return len(item) 19 | 20 | file_list.sort(key=key) 21 | return file_list 22 | 23 | 24 | if __name__ == '__main__': 25 | file_list = os.listdir(sys.argv[-1]) 26 | sorted_file_list = filter_and_sort(file_list) 27 | print sorted_file_list 28 | 29 | -------------------------------------------------------------------------------- /intro/solutions/image_blur.py: -------------------------------------------------------------------------------- 1 | """ 2 | Simple image blur by convolution with a Gaussian kernel 3 | """ 4 | 5 | import numpy as np 6 | from scipy import fftpack 7 | import matplotlib.pyplot as plt 8 | 9 | # read image 10 | img = plt.imread('../../data/elephant.png') 11 | 12 | # prepare an 1-D Gaussian convolution kernel 13 | t = np.linspace(-10, 10, 30) 14 | bump = np.exp(-0.1*t**2) 15 | bump /= np.trapz(bump) # normalize the integral to 1 16 | 17 | # make a 2-D kernel out of it 18 | kernel = bump[:, np.newaxis] * bump[np.newaxis, :] 19 | 20 | # padded fourier transform, with the same shape as the image 21 | kernel_ft = fftpack.fft2(kernel, shape=img.shape[:2], axes=(0, 1)) 22 | 23 | # convolve 24 | img_ft = fftpack.fft2(img, axes=(0, 1)) 25 | img2_ft = kernel_ft[:, :, np.newaxis] * img_ft 26 | img2 = fftpack.ifft2(img2_ft, axes=(0, 1)).real 27 | 28 | # clip values to range 29 | img2 = np.clip(img2, 0, 1) 30 | 31 | # plot output 32 | plt.imshow(img2) 33 | plt.show() 34 | 35 | # Further exercise (only if you are familiar with this stuff): 36 | # 37 | # A "wrapped border" appears in the upper left and top edges of the 38 | # image. This is because the padding is not done correctly, and does 39 | # not take the kernel size into account (so the convolution "flows out 40 | # of bounds of the image"). Try to remove this artifact. 41 | -------------------------------------------------------------------------------- /intro/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 | def find_module(module): 8 | result = [] 9 | # Loop over the list of paths in sys.path 10 | for subdir in sys.path: 11 | # Join the subdir path with the module we're searching for 12 | pth = os.path.join(subdir, module) 13 | # Use glob to test if the pth is exists 14 | res = glob.glob(pth) 15 | # glob returns a list, if it is not empty, the pth exists 16 | if len(res) > 0: 17 | result.append(res) 18 | return result 19 | 20 | 21 | if __name__ == '__main__': 22 | result = find_module('site.py') 23 | print result 24 | 25 | -------------------------------------------------------------------------------- /intro/solutions/periodicity_finder.py: -------------------------------------------------------------------------------- 1 | """ 2 | Discover the periods in ../../data/populations.txt 3 | """ 4 | import numpy as np 5 | import matplotlib.pyplot as plt 6 | 7 | data = np.loadtxt('../../data/populations.txt') 8 | years = data[:, 0] 9 | populations = data[:, 1:] 10 | 11 | ft_populations = np.fft.fft(populations, axis=0) 12 | frequencies = np.fft.fftfreq(populations.shape[0], years[1] - years[0]) 13 | periods = 1 / frequencies 14 | 15 | plt.figure() 16 | plt.plot(years, populations * 1e-3) 17 | plt.xlabel('Year') 18 | plt.ylabel('Population number ($\cdot10^3$)') 19 | plt.legend(['hare', 'lynx', 'carrot'], loc=1) 20 | 21 | plt.figure() 22 | plt.plot(periods, abs(ft_populations) * 1e-3, 'o') 23 | plt.xlim(0, 22) 24 | plt.xlabel('Period') 25 | plt.ylabel('Power ($\cdot10^3$)') 26 | 27 | plt.show() 28 | 29 | # There's probably a period of around 10 years (obvious from the 30 | # plot), but for this crude a method, there's not enough data to say 31 | # much more. 32 | -------------------------------------------------------------------------------- /intro/solutions/pi_wallis.py: -------------------------------------------------------------------------------- 1 | """ 2 | The correction for the calculation of pi using the Wallis formula. 3 | """ 4 | from __future__ import division 5 | 6 | pi = 3.14159265358979312 7 | 8 | my_pi = 1. 9 | 10 | for i in range(1, 100000): 11 | my_pi *= 4 * i ** 2 / (4 * i ** 2 - 1.) 12 | 13 | my_pi *= 2 14 | 15 | print pi 16 | print my_pi 17 | print abs(pi - my_pi) 18 | 19 | ############################################################################### 20 | num = 1 21 | den = 1 22 | for i in range(1, 100000): 23 | tmp = 4 * i * i 24 | num *= tmp 25 | den *= tmp - 1 26 | 27 | better_pi = 2 * (num / den) 28 | 29 | print pi 30 | print better_pi 31 | print abs(pi - better_pi) 32 | print abs(my_pi - better_pi) 33 | 34 | ############################################################################### 35 | # Solution in a single line using more adcanved constructs (reduce, lambda, 36 | # list comprehensions 37 | print 2 * reduce(lambda x, y: x * y, 38 | [float((4 * (i ** 2))) / ((4 * (i ** 2)) - 1) 39 | for i in range(1, 100000)]) 40 | -------------------------------------------------------------------------------- /intro/solutions/quick_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implement the quick sort algorithm. 3 | """ 4 | 5 | def qsort(lst): 6 | """ Quick sort: returns a sorted copy of the list. 7 | """ 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 | # And now check that qsort does sort: 30 | assert qsort(range(10)) == range(10) 31 | assert qsort(range(10)[::-1]) == range(10) 32 | assert qsort([1, 4, 2, 5, 3]) == sorted([1, 4, 2, 5, 3]) 33 | -------------------------------------------------------------------------------- /intro/solutions/test_dir_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Test the dir_sort logic. 3 | """ 4 | import dir_sort 5 | 6 | def test_filter_and_sort(): 7 | # Test that non '.py' files are not filtered. 8 | file_list = ['a', 'aaa', 'aa', '', 'z', 'zzzzz'] 9 | file_list2 = dir_sort.filter_and_sort(file_list) 10 | assert len(file_list2) == 0 11 | 12 | # Test that the otuput file list is ordered by length. 13 | file_list = [ n + '.py' for n in file_list] 14 | file_list2 = dir_sort.filter_and_sort(file_list) 15 | name1 = file_list2.pop(0) 16 | for name in file_list2: 17 | assert len(name1) <= len(name) 18 | 19 | 20 | if __name__ == '__main__': 21 | test_filter_and_sort() 22 | 23 | -------------------------------------------------------------------------------- /intro/summary-exercises/README.txt: -------------------------------------------------------------------------------- 1 | Examples for the summary excercises 2 | ==================================== 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /intro/summary-exercises/examples/README.rst: -------------------------------------------------------------------------------- 1 | Examples for the summary excercices 2 | ==================================== 3 | 4 | -------------------------------------------------------------------------------- /intro/summary-exercises/examples/max-speeds.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/summary-exercises/examples/max-speeds.npy -------------------------------------------------------------------------------- /intro/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 | from scipy.interpolate import UnivariateSpline 11 | import pylab as pl 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 = UnivariateSpline(cprob, sorted_max_speeds) 19 | nprob = np.linspace(0, 1, 1e2) 20 | fitted_max_speeds = speed_spline(nprob) 21 | 22 | fifty_prob = 1. - 0.02 23 | fifty_wind = speed_spline(fifty_prob) 24 | 25 | pl.figure() 26 | pl.plot(sorted_max_speeds, cprob, 'o') 27 | pl.plot(fitted_max_speeds, nprob, 'g--') 28 | pl.plot([fifty_wind], [fifty_prob], 'o', ms=8., mfc='y', mec='y') 29 | pl.text(30, 0.05, '$V_{50} = %.2f \, m/s$' % fifty_wind) 30 | pl.plot([fifty_wind, fifty_wind], [pl.axis()[2], fifty_prob], 'k--') 31 | pl.xlabel('Annual wind speed maxima [$m/s$]') 32 | pl.ylabel('Cumulative probability') 33 | -------------------------------------------------------------------------------- /intro/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 | import numpy as np 8 | from scipy.interpolate import UnivariateSpline 9 | import pylab as pl 10 | 11 | 12 | def gumbell_dist(arr): 13 | return -np.log(-np.log(arr)) 14 | 15 | years_nb = 21 16 | wspeeds = np.load('sprog-windspeeds.npy') 17 | max_speeds = np.array([arr.max() for arr in np.array_split(wspeeds, years_nb)]) 18 | sorted_max_speeds = np.sort(max_speeds) 19 | 20 | cprob = (np.arange(years_nb, dtype=np.float32) + 1)/(years_nb + 1) 21 | gprob = gumbell_dist(cprob) 22 | speed_spline = UnivariateSpline(gprob, sorted_max_speeds, k=1) 23 | nprob = gumbell_dist(np.linspace(1e-3, 1-1e-3, 1e2)) 24 | fitted_max_speeds = speed_spline(nprob) 25 | 26 | fifty_prob = gumbell_dist(49./50.) 27 | fifty_wind = speed_spline(fifty_prob) 28 | 29 | pl.figure() 30 | pl.plot(sorted_max_speeds, gprob, 'o') 31 | pl.plot(fitted_max_speeds, nprob, 'g--') 32 | pl.plot([fifty_wind], [fifty_prob], 'o', ms=8., mfc='y', mec='y') 33 | pl.plot([fifty_wind, fifty_wind], [pl.axis()[2], fifty_prob], 'k--') 34 | pl.text(35, -1, r'$V_{50} = %.2f \, m/s$' % fifty_wind) 35 | pl.xlabel('Annual wind speed maxima [$m/s$]') 36 | pl.ylabel('Gumbell cumulative probability') 37 | pl.show() 38 | -------------------------------------------------------------------------------- /intro/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 | import numpy as np 8 | from scipy.interpolate import UnivariateSpline 9 | import pylab as pl 10 | 11 | 12 | def gumbell_dist(arr): 13 | return -np.log(-np.log(arr)) 14 | 15 | years_nb = 21 16 | wspeeds = np.load('sprog-windspeeds.npy') 17 | max_speeds = np.array([arr.max() for arr in np.array_split(wspeeds, years_nb)]) 18 | sorted_max_speeds = np.sort(max_speeds) 19 | 20 | cprob = (np.arange(years_nb, dtype=np.float32) + 1)/(years_nb + 1) 21 | gprob = gumbell_dist(cprob) 22 | speed_spline = UnivariateSpline(gprob, sorted_max_speeds, k=1) 23 | nprob = gumbell_dist(np.linspace(1e-3, 1-1e-3, 1e2)) 24 | fitted_max_speeds = speed_spline(nprob) 25 | 26 | fifty_prob = gumbell_dist(49./50.) 27 | fifty_wind = speed_spline(fifty_prob) 28 | 29 | pl.figure() 30 | pl.bar(np.arange(years_nb) + 1, max_speeds) 31 | pl.axis('tight') 32 | pl.xlabel('Year') 33 | pl.ylabel('Annual wind speed maxima [$m/s$]') 34 | -------------------------------------------------------------------------------- /intro/summary-exercises/examples/sprog-windspeeds.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/summary-exercises/examples/sprog-windspeeds.npy -------------------------------------------------------------------------------- /intro/summary-exercises/waveform_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/summary-exercises/waveform_1.png -------------------------------------------------------------------------------- /intro/summary-exercises/waveform_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/intro/summary-exercises/waveform_2.png -------------------------------------------------------------------------------- /packages/3d_plotting/decorations.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/3d_plotting/decorations.png -------------------------------------------------------------------------------- /packages/3d_plotting/examples/README.txt: -------------------------------------------------------------------------------- 1 | Examples for the Mayavi chapter 2 | ================================ 3 | 4 | -------------------------------------------------------------------------------- /packages/3d_plotting/examples/animate_data.py: -------------------------------------------------------------------------------- 1 | """ 2 | A small demo of data animation 3 | =============================== 4 | 5 | """ 6 | import numpy as np 7 | from mayavi import mlab 8 | 9 | # Create some simple data 10 | x , y , z = np.ogrid[-5:5:100j ,-5:5:100j, -5:5:100j] 11 | scalars = np.sin(x * y * z) / (x * y * z) 12 | 13 | iso = mlab.contour3d(scalars, transparent=True, contours=[0.5]) 14 | for i in range(1, 20): 15 | scalars = np.sin(i * x * y * z) /(x * y * z) 16 | iso.mlab_source.scalars = scalars 17 | 18 | # Start the event loop, if needed 19 | mlab.show() 20 | -------------------------------------------------------------------------------- /packages/3d_plotting/examples/contour3d.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/3d_plotting/examples/contour3d.png -------------------------------------------------------------------------------- /packages/3d_plotting/examples/mesh.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/3d_plotting/examples/mesh.png -------------------------------------------------------------------------------- /packages/3d_plotting/examples/mlab_dialog.py: -------------------------------------------------------------------------------- 1 | """ 2 | A dialog with Mayavi 3 | ==================== 4 | 5 | Simple example demoing a dialog with Mayavi 6 | """ 7 | 8 | import numpy as np 9 | from traits.api import HasTraits, Instance 10 | from traitsui.api import View, Item, HGroup 11 | from mayavi.core.ui.api import SceneEditor, MlabSceneModel 12 | 13 | def curve(n_turns): 14 | "The function creating the x, y, z coordinates needed to plot" 15 | phi = np.linspace(0, 2*np.pi, 2000) 16 | return [np.cos(phi) * (1 + 0.5*np.cos(n_turns*phi)), 17 | np.sin(phi) * (1 + 0.5*np.cos(n_turns*phi)), 18 | 0.5*np.sin(n_turns*phi)] 19 | 20 | 21 | class Visualization(HasTraits): 22 | "The class that contains the dialog" 23 | scene = Instance(MlabSceneModel, ()) 24 | 25 | def __init__(self): 26 | HasTraits.__init__(self) 27 | x, y, z = curve(n_turns=2) 28 | # Populating our plot 29 | self.plot = self.scene.mlab.plot3d(x, y, z) 30 | 31 | # Describe the dialog 32 | view = View(Item('scene', height=300, show_label=False, 33 | editor=SceneEditor()), 34 | HGroup('n_turns'), resizable=True) 35 | 36 | # Fire up the dialog 37 | Visualization().configure_traits() 38 | -------------------------------------------------------------------------------- /packages/3d_plotting/examples/mlab_interactive_dialog.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/3d_plotting/examples/mlab_interactive_dialog.png -------------------------------------------------------------------------------- /packages/3d_plotting/examples/mlab_interactive_dialog.py: -------------------------------------------------------------------------------- 1 | """ 2 | Interactive dialog with Mayavi 3 | ============================== 4 | 5 | Example demoing an interactive dialog with Mayavi 6 | """ 7 | 8 | import numpy as np 9 | from traits.api import HasTraits, Instance 10 | from traitsui.api import View, Item, HGroup 11 | from mayavi.core.ui.api import SceneEditor, MlabSceneModel 12 | 13 | def curve(n_turns): 14 | phi = np.linspace(0, 2*np.pi, 2000) 15 | return [np.cos(phi) * (1 + 0.5*np.cos(n_turns*phi)), 16 | np.sin(phi) * (1 + 0.5*np.cos(n_turns*phi)), 17 | 0.5*np.sin(n_turns*phi)] 18 | 19 | 20 | # The class that contains the dialog 21 | from traits.api import Range, on_trait_change 22 | 23 | class Visualization(HasTraits): 24 | n_turns = Range(0, 30, 11) 25 | scene = Instance(MlabSceneModel, ()) 26 | 27 | def __init__(self): 28 | HasTraits.__init__(self) 29 | x, y, z = curve(self.n_turns) 30 | self.plot = self.scene.mlab.plot3d(x, y, z) 31 | 32 | @on_trait_change('n_turns') 33 | def update_plot(self): 34 | x, y, z = curve(self.n_turns) 35 | self.plot.mlab_source.set(x=x, y=y, z=z) 36 | 37 | view = View(Item('scene', height=300, show_label=False, 38 | editor=SceneEditor()), 39 | HGroup('n_turns'), resizable=True) 40 | 41 | # Fire up the dialog 42 | Visualization().configure_traits() 43 | -------------------------------------------------------------------------------- /packages/3d_plotting/examples/plot3d.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/3d_plotting/examples/plot3d.png -------------------------------------------------------------------------------- /packages/3d_plotting/examples/points3d.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/3d_plotting/examples/points3d.png -------------------------------------------------------------------------------- /packages/3d_plotting/examples/simple_example.py: -------------------------------------------------------------------------------- 1 | """ 2 | Surface plot 3 | ============ 4 | 5 | A simple surface plot with Mayavi 6 | """ 7 | 8 | import numpy as np 9 | 10 | x, y = np.mgrid[-10:10:100j, -10:10:100j] 11 | r = np.sqrt(x**2 + y**2) 12 | z = np.sin(r)/r 13 | 14 | from enthought.mayavi import mlab 15 | mlab.surf(z, warp_scale='auto') 16 | 17 | mlab.outline() 18 | mlab.axes() 19 | -------------------------------------------------------------------------------- /packages/3d_plotting/examples/surf.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/3d_plotting/examples/surf.png -------------------------------------------------------------------------------- /packages/3d_plotting/examples/visualize_field.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/3d_plotting/examples/visualize_field.png -------------------------------------------------------------------------------- /packages/3d_plotting/examples/viz_volume_structure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/3d_plotting/examples/viz_volume_structure.png -------------------------------------------------------------------------------- /packages/3d_plotting/examples/viz_volume_structure.py: -------------------------------------------------------------------------------- 1 | """ 2 | Volume visualization 3 | ===================== 4 | 5 | Use Mayavi to visualize the structure of a VolumeImg 6 | """ 7 | 8 | from mayavi import mlab 9 | import numpy as np 10 | 11 | x, y, z = np.mgrid[-5:5:64j, -5:5:64j, -5:5:64j] 12 | 13 | data = x*x*0.5 + y*y + z*z*2.0 14 | 15 | mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1)) 16 | mlab.clf() 17 | 18 | src = mlab.pipeline.scalar_field(x, y, z, data) 19 | 20 | mlab.pipeline.surface(src, opacity=0.4) 21 | 22 | src2 = mlab.pipeline.scalar_field(x[::9, ::9, ::9], 23 | y[::9, ::9, ::9], 24 | z[::9, ::9, ::9], 25 | data[::9, ::9, ::9]) 26 | mlab.pipeline.surface(mlab.pipeline.extract_edges(src2), color=(0, 0, 0)) 27 | mlab.pipeline.glyph(src2, mode='cube', scale_factor=0.4, scale_mode='none') 28 | mlab.savefig('viz_volume_structure.png') 29 | mlab.show() 30 | 31 | 32 | -------------------------------------------------------------------------------- /packages/3d_plotting/examples/viz_volume_unstructure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/3d_plotting/examples/viz_volume_unstructure.png -------------------------------------------------------------------------------- /packages/3d_plotting/examples/viz_volume_unstructure.py: -------------------------------------------------------------------------------- 1 | """ 2 | Visualizing unstructured data 3 | ============================== 4 | 5 | Use Mayavi to visualize unstructured data 6 | """ 7 | 8 | from mayavi import mlab 9 | import numpy as np 10 | 11 | np.random.seed(0) 12 | 13 | x, y, z = 10 * np.random.random(size=(3, 200)) 14 | 15 | data = x*x*0.5 + y*y + z*z*2.0 16 | 17 | mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1)) 18 | mlab.clf() 19 | 20 | src = mlab.pipeline.scalar_scatter(x, y, z, data) 21 | mlab.pipeline.glyph(src, mode='cube', scale_factor=0.4, scale_mode='none') 22 | mlab.savefig('viz_volume_unstructure.png') 23 | mlab.show() 24 | 25 | 26 | -------------------------------------------------------------------------------- /packages/3d_plotting/interaction.rst: -------------------------------------------------------------------------------- 1 | Interactive work 2 | ================= 3 | 4 | .. only:: latex 5 | 6 | The quicket way to create beautiful visualization with Mayavi is 7 | probably to interactivly tweak the various settings. 8 | 9 | The "pipeline dialog" 10 | ---------------------- 11 | 12 | Click on the 'Mayavi' button in the scene, and you can control properties 13 | of objects with dialogs. 14 | 15 | .. image:: pipeline.png 16 | :align: center 17 | :scale: 80 18 | 19 | * Set the background of the figure in the `Mayavi Scene` node 20 | * Set the colormap in the `Colors and legends` node 21 | * Right click on the node to add modules or filters 22 | 23 | The script recording button 24 | ----------------------------- 25 | 26 | To find out what code can be used to program these changes, click on the 27 | red button as you modify those properties, and it will generate the 28 | corresponding lines of code. 29 | 30 | -------------------------------------------------------------------------------- /packages/3d_plotting/mayavi-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/3d_plotting/mayavi-logo.png -------------------------------------------------------------------------------- /packages/3d_plotting/pipeline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/3d_plotting/pipeline.png -------------------------------------------------------------------------------- /packages/3d_plotting/polar_mesh.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/3d_plotting/polar_mesh.png -------------------------------------------------------------------------------- /packages/3d_plotting/simple_example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/3d_plotting/simple_example.png -------------------------------------------------------------------------------- /packages/index.rst: -------------------------------------------------------------------------------- 1 | Packages and applications 2 | =================================================================== 3 | 4 | This part of the *Scipy lecture notes* is dedicated to various scientific 5 | packages useful for extended needs. 6 | 7 | | 8 | 9 | 10 | .. include:: ../includes/big_toc_css.rst 11 | 12 | .. include:: ../tune_toc.rst 13 | 14 | .. rst-class:: tune 15 | 16 | .. toctree:: 17 | :maxdepth: 3 18 | 19 | statistics/index.rst 20 | sympy.rst 21 | scikit-image/index.rst 22 | traits/index.rst 23 | 3d_plotting/index.rst 24 | scikit-learn/index.rst 25 | 26 | -------------------------------------------------------------------------------- /packages/scikit-image/examples/README.txt: -------------------------------------------------------------------------------- 1 | Examples for the scikit-image chapter 2 | ====================================== 3 | 4 | -------------------------------------------------------------------------------- /packages/scikit-image/examples/plot_boundaries.py: -------------------------------------------------------------------------------- 1 | """ 2 | Segementation contours 3 | ====================== 4 | 5 | Visualize segmentation contours on original grayscale image. 6 | """ 7 | 8 | from skimage import data, segmentation 9 | # scikit-image has changed its API 10 | try: 11 | from skimage import filters 12 | except ImportError: 13 | from skimage import filter as filters 14 | import matplotlib.pyplot as plt 15 | import numpy as np 16 | 17 | coins = data.coins() 18 | mask = coins > filters.threshold_otsu(coins) 19 | clean_border = segmentation.clear_border(mask).astype(np.int) 20 | 21 | coins_edges = segmentation.mark_boundaries(coins, clean_border) 22 | 23 | plt.figure(figsize=(8, 3.5)) 24 | plt.subplot(121) 25 | plt.imshow(clean_border, cmap='gray') 26 | plt.axis('off') 27 | plt.subplot(122) 28 | plt.imshow(coins_edges) 29 | plt.axis('off') 30 | 31 | plt.tight_layout() 32 | plt.show() 33 | -------------------------------------------------------------------------------- /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((9, 9)) 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 | from matplotlib import 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, 16 | translation=(210, 50)) 17 | image = warp(data.checkerboard(), tform.inverse, output_shape=(350, 350)) 18 | 19 | coords = corner_peaks(corner_harris(image), min_distance=5) 20 | coords_subpix = corner_subpix(image, coords, window_size=13) 21 | 22 | plt.gray() 23 | plt.imshow(image, interpolation='nearest') 24 | plt.plot(coords_subpix[:, 1], coords_subpix[:, 0], '+r', markersize=15, mew=5) 25 | plt.plot(coords[:, 1], coords[:, 0], '.b', markersize=7) 26 | plt.axis('off') 27 | plt.show() 28 | -------------------------------------------------------------------------------- /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 | try: 13 | from skimage import filters 14 | except ImportError: 15 | from skimage import filter as filters 16 | from skimage import restoration 17 | 18 | coins = data.coins() 19 | gaussian_filter_coins = filters.gaussian_filter(coins, sigma=2) 20 | med_filter_coins = filters.rank.median(coins, np.ones((3, 3))) 21 | tv_filter_coins = restoration.denoise_tv_chambolle(coins, weight=0.1) 22 | 23 | plt.figure(figsize=(16, 4)) 24 | plt.subplot(141) 25 | plt.imshow(coins[10:80, 300:370], cmap='gray', interpolation='nearest') 26 | plt.axis('off') 27 | plt.title('Image') 28 | plt.subplot(142) 29 | plt.imshow(gaussian_filter_coins[10:80, 300:370], cmap='gray', 30 | interpolation='nearest') 31 | plt.axis('off') 32 | plt.title('Gaussian filter') 33 | plt.subplot(143) 34 | plt.imshow(med_filter_coins[10:80, 300:370], cmap='gray', 35 | interpolation='nearest') 36 | plt.axis('off') 37 | plt.title('Median filter') 38 | plt.subplot(144) 39 | plt.imshow(tv_filter_coins[10:80, 300:370], cmap='gray', 40 | interpolation='nearest') 41 | plt.axis('off') 42 | plt.title('TV filter') 43 | plt.show() 44 | -------------------------------------------------------------------------------- /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 | try: 11 | from skimage import filters 12 | except ImportError: 13 | from skimage import filter as filters 14 | import matplotlib.pyplot as plt 15 | import numpy as np 16 | 17 | n = 12 18 | l = 256 19 | np.random.seed(1) 20 | im = np.zeros((l, l)) 21 | points = l * np.random.random((2, n ** 2)) 22 | im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 23 | im = filters.gaussian_filter(im, sigma= l / (4. * n)) 24 | blobs = im > 0.7 * im.mean() 25 | 26 | all_labels = measure.label(blobs) 27 | blobs_labels = measure.label(blobs, background=0) 28 | 29 | plt.figure(figsize=(9, 3.5)) 30 | plt.subplot(131) 31 | plt.imshow(blobs, cmap='gray') 32 | plt.axis('off') 33 | plt.subplot(132) 34 | plt.imshow(all_labels, cmap='spectral') 35 | plt.axis('off') 36 | plt.subplot(133) 37 | plt.imshow(blobs_labels, cmap='spectral') 38 | plt.axis('off') 39 | 40 | plt.tight_layout() 41 | plt.show() 42 | -------------------------------------------------------------------------------- /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 | # scikit-image has changes its API 11 | try: 12 | from skimage import filters 13 | except ImportError: 14 | from skimage import filter as filters 15 | import matplotlib.pyplot as plt 16 | 17 | text = data.text() 18 | hsobel_text = filters.hsobel(text) 19 | 20 | plt.figure(figsize=(12, 3)) 21 | 22 | plt.subplot(121) 23 | plt.imshow(text, cmap='gray', interpolation='nearest') 24 | plt.axis('off') 25 | plt.subplot(122) 26 | plt.imshow(hsobel_text, cmap='spectral', interpolation='nearest') 27 | plt.axis('off') 28 | plt.tight_layout() 29 | plt.show() 30 | -------------------------------------------------------------------------------- /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 | try: 11 | from skimage import filters 12 | except ImportError: 13 | from skimage import filter as filters 14 | from skimage import exposure 15 | 16 | camera = data.camera() 17 | val = filters.threshold_otsu(camera) 18 | 19 | hist, bins_center = exposure.histogram(camera) 20 | 21 | plt.figure(figsize=(9, 4)) 22 | plt.subplot(131) 23 | plt.imshow(camera, cmap='gray', interpolation='nearest') 24 | plt.axis('off') 25 | plt.subplot(132) 26 | plt.imshow(camera < val, cmap='gray', interpolation='nearest') 27 | plt.axis('off') 28 | plt.subplot(133) 29 | plt.plot(bins_center, hist, lw=2) 30 | plt.axvline(val, color='k', ls='--') 31 | 32 | plt.tight_layout() 33 | plt.show() 34 | -------------------------------------------------------------------------------- /packages/scikit-image/viewer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-image/viewer.png -------------------------------------------------------------------------------- /packages/scikit-learn/cluster_iris_truth.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/cluster_iris_truth.png -------------------------------------------------------------------------------- /packages/scikit-learn/digits_first_image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/digits_first_image.png -------------------------------------------------------------------------------- /packages/scikit-learn/digits_svm.py: -------------------------------------------------------------------------------- 1 | from sklearn import datasets, svm 2 | 3 | digits = datasets.load_digits() 4 | clf = svm.SVC(kernel='linear') 5 | n_train = int(.9 * digits.target.shape[0]) 6 | clf.fit(digits.data[:n_train], digits.target[:n_train]) 7 | print clf.score(digits.data[n_train:], digits.target[n_train:]) 8 | -------------------------------------------------------------------------------- /packages/scikit-learn/face.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/face.png -------------------------------------------------------------------------------- /packages/scikit-learn/face_compressed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/face_compressed.png -------------------------------------------------------------------------------- /packages/scikit-learn/faces.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/faces.png -------------------------------------------------------------------------------- /packages/scikit-learn/faces.py: -------------------------------------------------------------------------------- 1 | """ 2 | Stripped-down version of the face recognition example by Olivier Grisel 3 | 4 | http://scikit-learn.org/dev/auto_examples/applications/face_recognition.html 5 | 6 | ## original shape of images: 50, 37 7 | """ 8 | 9 | import numpy as np 10 | from sklearn import cross_val, datasets, decomposition, svm 11 | 12 | # .. 13 | # .. load data .. 14 | lfw_people = datasets.fetch_lfw_people(min_faces_per_person=70, resize=0.4) 15 | faces = np.reshape(lfw_people.data, (lfw_people.target.shape[0], -1)) 16 | train, test = iter(cross_val.StratifiedKFold(lfw_people.target, k=4)).next() 17 | X_train, X_test = faces[train], faces[test] 18 | y_train, y_test = lfw_people.target[train], lfw_people.target[test] 19 | 20 | # .. 21 | # .. dimension reduction .. 22 | pca = decomposition.RandomizedPCA(n_components=150, whiten=True) 23 | pca.fit(X_train) 24 | X_train_pca = pca.transform(X_train) 25 | X_test_pca = pca.transform(X_test) 26 | 27 | # .. 28 | # .. classification .. 29 | clf = svm.SVC(C=5., gamma=0.001) 30 | clf.fit(X_train_pca, y_train) 31 | 32 | print 'Score on unseen data: ' 33 | print clf.score(X_test_pca, y_test) 34 | 35 | 36 | -------------------------------------------------------------------------------- /packages/scikit-learn/images/Virginia_Iris.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/images/Virginia_Iris.png -------------------------------------------------------------------------------- /packages/scikit-learn/iris_knn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/iris_knn.png -------------------------------------------------------------------------------- /packages/scikit-learn/iris_svm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/iris_svm.png -------------------------------------------------------------------------------- /packages/scikit-learn/k_means_iris_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/k_means_iris_3.png -------------------------------------------------------------------------------- /packages/scikit-learn/k_means_iris_8.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/k_means_iris_8.png -------------------------------------------------------------------------------- /packages/scikit-learn/pca_3d_aligned.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/pca_3d_aligned.jpg -------------------------------------------------------------------------------- /packages/scikit-learn/pca_3d_axis.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/pca_3d_axis.jpg -------------------------------------------------------------------------------- /packages/scikit-learn/pca_digits_spectrum.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/pca_digits_spectrum.png -------------------------------------------------------------------------------- /packages/scikit-learn/pca_iris.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/pca_iris.png -------------------------------------------------------------------------------- /packages/scikit-learn/plot_compare_methods_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/plot_compare_methods_1.png -------------------------------------------------------------------------------- /packages/scikit-learn/plot_faces_decomposition_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/plot_faces_decomposition_2.png -------------------------------------------------------------------------------- /packages/scikit-learn/scikit-learn-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/scikit-learn-logo.png -------------------------------------------------------------------------------- /packages/scikit-learn/show_digit.py: -------------------------------------------------------------------------------- 1 | from sklearn import datasets 2 | import pylab as pl 3 | 4 | digits = datasets.load_digits() 5 | 6 | for i in range(8): 7 | pl.subplot(2, 4, 1 + i) 8 | pl.imshow(digits.images[3 * i], cmap=pl.cm.gray_r, interpolation='nearest') 9 | # pl.axis('off') 10 | pl.show() 11 | 12 | pl.imshow(digits.images[8], cmap=pl.cm.gray_r, interpolation='nearest') 13 | pl.show() 14 | 15 | pl.imshow(digits.images[8].reshape(1, -1), cmap=pl.cm.gray_r, interpolation='nearest') 16 | pl.axis('off') 17 | pl.show() 18 | -------------------------------------------------------------------------------- /packages/scikit-learn/show_ica.py: -------------------------------------------------------------------------------- 1 | from sklearn import datasets, decomposition 2 | import pylab as pl 3 | import numpy as np 4 | 5 | digits = datasets.load_digits() 6 | 7 | digits.data += .2 * np.random.normal(size=digits.data.shape) 8 | ica = decomposition.FastICA(n_components=10) 9 | tt = ica.fit(digits.data.T).transform(digits.data.T).T 10 | 11 | for i in range(8): 12 | pl.subplot(2, 4, 1 + i) 13 | pl.imshow(tt[i].reshape(8, 8), cmap=pl.cm.gray_r, interpolation='nearest') 14 | # pl.axis('off') 15 | pl.show() 16 | -------------------------------------------------------------------------------- /packages/scikit-learn/show_pca.py: -------------------------------------------------------------------------------- 1 | from sklearn import datasets, decomposition 2 | import pylab as pl 3 | 4 | iris = datasets.load_iris() 5 | 6 | pca = decomposition.PCA(n_components=2) 7 | iris_2D = pca.fit(iris.data).transform(iris.data) 8 | 9 | pl.scatter(iris_2D[:, 0], iris_2D[:, 1], c=iris.target) 10 | pl.show() 11 | -------------------------------------------------------------------------------- /packages/scikit-learn/svm_kernel_linear.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/svm_kernel_linear.png -------------------------------------------------------------------------------- /packages/scikit-learn/svm_kernel_poly.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/svm_kernel_poly.png -------------------------------------------------------------------------------- /packages/scikit-learn/svm_kernel_rbf.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/svm_kernel_rbf.png -------------------------------------------------------------------------------- /packages/scikit-learn/svm_margin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/svm_margin.png -------------------------------------------------------------------------------- /packages/scikit-learn/svm_margin_no_penalty.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/scikit-learn/svm_margin_no_penalty.png -------------------------------------------------------------------------------- /packages/statistics/examples/README.txt: -------------------------------------------------------------------------------- 1 | Code examples 2 | ---------------------------- 3 | 4 | Code examples for the statistics in Python tutorial. 5 | 6 | -------------------------------------------------------------------------------- /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.tools 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 | plt.show() 29 | -------------------------------------------------------------------------------- /packages/statistics/examples/solutions/README.txt: -------------------------------------------------------------------------------- 1 | Solutions to the exercises of the course 2 | ---------------------------------------- 3 | 4 | -------------------------------------------------------------------------------- /packages/statistics/two_sided.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/statistics/two_sided.png -------------------------------------------------------------------------------- /packages/traits/ETS.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/traits/ETS.jpg -------------------------------------------------------------------------------- /packages/traits/reservoir.py: -------------------------------------------------------------------------------- 1 | from traits.api import HasTraits, Str, Float, Range 2 | 3 | class Reservoir(HasTraits): 4 | name = Str 5 | max_storage = Float(1e6, desc='Maximal storage [hm3]') 6 | max_release = Float(10, desc='Maximal release [m3/s]') 7 | head = Float(10, desc='Hydraulic head [m]') 8 | efficiency = Range(0, 1.) 9 | 10 | def energy_production(self, release): 11 | ''' Returns the energy production [Wh] for the given release [m3/s] 12 | ''' 13 | power = 1000 * 9.81 * self.head * release * self.efficiency 14 | return power * 3600 15 | 16 | 17 | if __name__ == '__main__': 18 | reservoir = Reservoir( 19 | name = 'Project A', 20 | max_storage = 30, 21 | max_release = 100.0, 22 | head = 60, 23 | efficiency = 0.8 24 | ) 25 | 26 | release = 80 27 | print 'Releasing {} m3/s produces {} kWh'.format( 28 | release, reservoir.energy_production(release) 29 | ) 30 | -------------------------------------------------------------------------------- /packages/traits/reservoir_default_view.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/traits/reservoir_default_view.png -------------------------------------------------------------------------------- /packages/traits/reservoir_evolution.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/traits/reservoir_evolution.png -------------------------------------------------------------------------------- /packages/traits/reservoir_simple_view.py: -------------------------------------------------------------------------------- 1 | from traits.api import HasTraits, Str, Float, Range 2 | from traitsui.api import View 3 | 4 | class Reservoir(HasTraits): 5 | name = Str 6 | max_storage = Float(1e6, desc='Maximal storage [hm3]') 7 | max_release = Float(10, desc='Maximal release [m3/s]') 8 | head = Float(10, desc='Hydraulic head [m]') 9 | efficiency = Range(0, 1.) 10 | 11 | traits_view = View( 12 | 'name', 'max_storage', 'max_release', 'head', 'efficiency', 13 | title = 'Reservoir', 14 | resizable = True, 15 | ) 16 | 17 | def energy_production(self, release): 18 | ''' Returns the energy production [Wh] for the given release [m3/s] 19 | ''' 20 | power = 1000 * 9.81 * self.head * release * self.efficiency 21 | return power * 3600 22 | 23 | 24 | if __name__ == '__main__': 25 | reservoir = Reservoir( 26 | name = 'Project A', 27 | max_storage = 30, 28 | max_release = 100.0, 29 | head = 60, 30 | efficiency = 0.8 31 | ) 32 | 33 | reservoir.configure_traits() 34 | -------------------------------------------------------------------------------- /packages/traits/reservoir_state_dynamic_listener.py: -------------------------------------------------------------------------------- 1 | from reservoir import Reservoir 2 | from reservoir_state_property import ReservoirState 3 | 4 | def wake_up_watchman_if_spillage(new_value): 5 | if new_value > 0: 6 | print 'Wake up watchman! Spilling {} hm3'.format(new_value) 7 | 8 | if __name__ == '__main__': 9 | projectA = Reservoir( 10 | name = 'Project A', 11 | max_storage = 30, 12 | max_release = 100.0, 13 | hydraulic_head = 60, 14 | efficiency = 0.8 15 | ) 16 | 17 | state = ReservoirState(reservoir=projectA, storage=10) 18 | 19 | #register the dynamic listener 20 | state.on_trait_change(wake_up_watchman_if_spillage, name='spillage') 21 | 22 | state.release = 90 23 | state.inflows = 0 24 | state.print_state() 25 | 26 | print 'Forcing spillage' 27 | state.inflows = 100 28 | state.release = 0 29 | 30 | print 'Why do we have two executions of the callback ?' 31 | -------------------------------------------------------------------------------- /packages/traits/reservoir_state_view.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/traits/reservoir_state_view.png -------------------------------------------------------------------------------- /packages/traits/reservoir_view.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/traits/reservoir_view.png -------------------------------------------------------------------------------- /pyplots/demo_detrend.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pylab as pl 3 | from scipy import signal 4 | t = np.linspace(0, 5, 100) 5 | x = t + np.random.normal(size=100) 6 | 7 | pl.plot(t, x, linewidth=3) 8 | pl.plot(t, signal.detrend(x), linewidth=3) 9 | 10 | -------------------------------------------------------------------------------- /pyplots/demo_resample.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pylab as pl 3 | from scipy import signal 4 | t = np.linspace(0, 5, 100) 5 | x = np.sin(t) 6 | 7 | pl.plot(t, x, linewidth=3) 8 | pl.plot(t[::2], signal.resample(x, 50), 'ko') 9 | 10 | -------------------------------------------------------------------------------- /pyplots/fftpack_frequency.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy import fftpack 3 | import pylab as pl 4 | 5 | 6 | np.random.seed(1234) 7 | 8 | time_step = 0.02 9 | period = 5. 10 | 11 | time_vec = np.arange(0, 20, time_step) 12 | sig = np.sin(2 * np.pi / period * time_vec) + \ 13 | 0.5 * np.random.randn(time_vec.size) 14 | 15 | sample_freq = fftpack.fftfreq(sig.size, d=time_step) 16 | sig_fft = fftpack.fft(sig) 17 | pidxs = np.where(sample_freq > 0) 18 | freqs, power = sample_freq[pidxs], np.abs(sig_fft)[pidxs] 19 | freq = freqs[power.argmax()] 20 | 21 | pl.figure() 22 | pl.plot(freqs, power) 23 | pl.xlabel('Frequency [Hz]') 24 | pl.ylabel('plower') 25 | axes = pl.axes([0.3, 0.3, 0.5, 0.5]) 26 | pl.title('Peak frequency') 27 | pl.plot(freqs[:8], power[:8]) 28 | pl.setp(axes, yticks=[]) 29 | 30 | 31 | -------------------------------------------------------------------------------- /pyplots/fftpack_signals.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy import fftpack 3 | import pylab as pl 4 | 5 | np.random.seed(1234) 6 | 7 | time_step = 0.02 8 | period = 5. 9 | 10 | time_vec = np.arange(0, 20, time_step) 11 | sig = np.sin(2 * np.pi / period * time_vec) + \ 12 | 0.5 * np.random.randn(time_vec.size) 13 | 14 | sample_freq = fftpack.fftfreq(sig.size, d=time_step) 15 | sig_fft = fftpack.fft(sig) 16 | pidxs = np.where(sample_freq > 0) 17 | freqs, power = sample_freq[pidxs], np.abs(sig_fft)[pidxs] 18 | freq = freqs[power.argmax()] 19 | 20 | sig_fft[np.abs(sample_freq) > freq] = 0 21 | main_sig = fftpack.ifft(sig_fft) 22 | 23 | pl.figure() 24 | pl.plot(time_vec, sig) 25 | pl.plot(time_vec, main_sig, linewidth=3) 26 | pl.xlabel('Time [s]') 27 | pl.ylabel('Amplitude') 28 | 29 | -------------------------------------------------------------------------------- /pyplots/normal_distribution.py: -------------------------------------------------------------------------------- 1 | from scipy import stats 2 | import numpy as np 3 | import pylab as pl 4 | a = np.random.normal(size=10000) 5 | bins = np.linspace(-5, 5, 30) 6 | histogram, bins = np.histogram(a, bins=bins, normed=True) 7 | bins = 0.5*(bins[1:] + bins[:-1]) 8 | from scipy import stats 9 | b = stats.norm.pdf(bins) 10 | pl.plot(bins, histogram) 11 | pl.plot(bins, b) 12 | 13 | -------------------------------------------------------------------------------- /pyplots/numpy_intro_1.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | x = np.linspace(0, 3, 20) 5 | y = np.linspace(0, 9, 20) 6 | plt.plot(x, y) # line plot 7 | plt.plot(x, y, 'o') # dot plot 8 | plt.show() # <-- shows the plot (not needed with Ipython) 9 | -------------------------------------------------------------------------------- /pyplots/numpy_intro_10.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | x = np.linspace(-1, 1, 2000) 4 | y = np.cos(x) + 0.3*np.random.rand(2000) 5 | p = np.polynomial.Chebyshev.fit(x, y, 90) 6 | 7 | t = np.linspace(-1, 1, 200) 8 | plt.plot(x, y, 'r.') 9 | plt.plot(t, p(t), 'k-', lw=3) 10 | plt.show() 11 | -------------------------------------------------------------------------------- /pyplots/numpy_intro_2.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | image = np.random.rand(30, 30) 5 | plt.imshow(image, cmap=plt.cm.hot) 6 | plt.colorbar() 7 | plt.show() 8 | -------------------------------------------------------------------------------- /pyplots/numpy_intro_3.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | img = plt.imread('../data/elephant.png') 5 | print img.shape, img.dtype 6 | # (200, 300, 3) dtype('float32') 7 | 8 | plt.imshow(img) 9 | plt.savefig('plot.png') 10 | plt.show() 11 | 12 | plt.imsave('red_elephant', img[:,:,0], cmap=plt.cm.gray) 13 | 14 | # This saved only one channel (of RGB) 15 | 16 | plt.imshow(plt.imread('red_elephant.png')) 17 | plt.show() 18 | 19 | # Other libraries: 20 | 21 | from scipy.misc import imsave 22 | imsave('tiny_elephant.png', img[::6,::6]) 23 | plt.imshow(plt.imread('tiny_elephant.png'), interpolation='nearest') 24 | plt.show() 25 | -------------------------------------------------------------------------------- /pyplots/numpy_intro_4.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | # We can first plot the data: 5 | 6 | data = np.loadtxt('../data/populations.txt') 7 | year, hares, lynxes, carrots = data.T # trick: columns to variables 8 | 9 | plt.axes([0.2, 0.1, 0.5, 0.8]) 10 | plt.plot(year, hares, year, lynxes, year, carrots) 11 | plt.legend(('Hare', 'Lynx', 'Carrot'), loc=(1.05, 0.5)) 12 | plt.show() 13 | 14 | # The mean populations over time: 15 | populations = data[:,1:] 16 | print populations.mean(axis=0) 17 | # [ 34080.95238095, 20166.66666667, 42400. ] 18 | 19 | # The sample standard deviations: 20 | print populations.std(axis=0, ddof=1) 21 | # [ 21413.98185877, 16655.99991995, 3404.55577132] 22 | 23 | # Which species has the highest population each year? 24 | print np.argmax(populations, axis=1) 25 | # [2, 2, 0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 0, 0, 0, 1, 2, 2, 2, 2, 2] 26 | -------------------------------------------------------------------------------- /pyplots/numpy_intro_5.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | n_stories = 1000 # number of walkers 5 | t_max = 200 # time during which we follow the walker 6 | 7 | # We randomly choose all the steps 1 or -1 of the walk 8 | 9 | t = np.arange(t_max) 10 | steps = 2 * np.random.random_integers(0, 1, (n_stories, t_max)) - 1 11 | print np.unique(steps) # Verification: all steps are 1 or -1 12 | # [-1, 1] 13 | 14 | # We build the walks by summing steps along the time 15 | 16 | positions = np.cumsum(steps, axis=1) # axis = 1: dimension of time 17 | sq_distance = positions**2 18 | 19 | # We get the mean in the axis of the stories 20 | 21 | mean_sq_distance = np.mean(sq_distance, axis=0) 22 | 23 | # Plot the results: 24 | 25 | plt.figure(figsize=(4, 3)) 26 | plt.plot(t, np.sqrt(mean_sq_distance), 'g.', t, np.sqrt(t), 'y-') 27 | plt.xlabel(r"$t$") 28 | plt.ylabel(r"$\sqrt{\langle (\delta x)^2 \rangle}$") 29 | plt.show() 30 | -------------------------------------------------------------------------------- /pyplots/numpy_intro_6.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | x, y = np.arange(5), np.arange(5) 5 | distance = np.sqrt(x**2 + y[:, np.newaxis]**2) 6 | print distance 7 | # [[ 0. , 1. , 2. , 3. , 4. ], 8 | # [ 1. , 1.41421356, 2.23606798, 3.16227766, 4.12310563], 9 | # [ 2. , 2.23606798, 2.82842712, 3.60555128, 4.47213595], 10 | # [ 3. , 3.16227766, 3.60555128, 4.24264069, 5. ], 11 | # [ 4. , 4.12310563, 4.47213595, 5. , 5.65685425]] 12 | 13 | 14 | # Or in color: 15 | 16 | plt.pcolor(distance) 17 | plt.colorbar() 18 | plt.axis('equal') 19 | plt.show() # <-- again, not needed in interactive Python 20 | -------------------------------------------------------------------------------- /pyplots/numpy_intro_7.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | data = np.loadtxt('../data/populations.txt') 5 | year, hares, lynxes, carrots = data.T # trick: columns to variables 6 | 7 | plt.axes([0.2, 0.1, 0.5, 0.8]) 8 | plt.plot(year, hares, year, lynxes, year, carrots) 9 | plt.legend(('Hare', 'Lynx', 'Carrot'), loc=(1.05, 0.5)) 10 | plt.show() 11 | -------------------------------------------------------------------------------- /pyplots/numpy_intro_8.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | data = np.loadtxt('../data/populations.txt') 5 | populations = np.ma.masked_array(data[:,1:]) 6 | year = data[:,0] 7 | 8 | bad_years = (((year >= 1903) & (year <= 1910)) 9 | | ((year >= 1917) & (year <= 1918))) 10 | populations[bad_years,0] = np.ma.masked 11 | populations[bad_years,1] = np.ma.masked 12 | 13 | print populations.mean(axis=0) 14 | # [40472.7272727 18627.2727273 42400.0] 15 | 16 | print populations.std(axis=0) 17 | # [21087.656489 15625.7998142 3322.50622558] 18 | 19 | # Note that Matplotlib knows about masked arrays: 20 | 21 | plt.plot(year, populations, 'o-') 22 | plt.show() 23 | -------------------------------------------------------------------------------- /pyplots/numpy_intro_9.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | x = np.linspace(0, 1, 20) 5 | y = np.cos(x) + 0.3*np.random.rand(20) 6 | p = np.poly1d(np.polyfit(x, y, 3)) 7 | 8 | t = np.linspace(0, 1, 200) 9 | plt.plot(x, y, 'o', t, p(t), '-') 10 | plt.show() 11 | -------------------------------------------------------------------------------- /pyplots/odeint_damped_spring_mass.py: -------------------------------------------------------------------------------- 1 | """Damped spring-mass oscillator 2 | """ 3 | 4 | import numpy as np 5 | from scipy.integrate import odeint 6 | import pylab as pl 7 | 8 | mass = 0.5 9 | kspring = 4 10 | cviscous = 0.4 11 | 12 | nu_coef = cviscous / mass 13 | om_coef = kspring / mass 14 | 15 | def calc_deri(yvec, time, nuc, omc): 16 | return (yvec[1], -nuc * yvec[1] - omc * yvec[0]) 17 | 18 | time_vec = np.linspace(0, 10, 100) 19 | yarr = odeint(calc_deri, (1, 0), time_vec, args=(nu_coef, om_coef)) 20 | 21 | pl.plot(time_vec, yarr[:, 0], label='y') 22 | pl.plot(time_vec, yarr[:, 1], label="y'") 23 | pl.legend() 24 | 25 | -------------------------------------------------------------------------------- /pyplots/odeint_introduction.py: -------------------------------------------------------------------------------- 1 | """Solve the ODE dy/dt = -2y between t = 0..4, with the 2 | initial condition y(t=0) = 1. 3 | """ 4 | 5 | import numpy as np 6 | from scipy.integrate import odeint 7 | import pylab as pl 8 | 9 | def calc_derivative(ypos, time): 10 | return -2*ypos 11 | 12 | time_vec = np.linspace(0, 4, 40) 13 | yvec = odeint(calc_derivative, 1, time_vec) 14 | 15 | pl.plot(time_vec, yvec) 16 | pl.xlabel('Time [s]') 17 | pl.ylabel('y position [m]') 18 | 19 | -------------------------------------------------------------------------------- /pyplots/scipy_interpolation.py: -------------------------------------------------------------------------------- 1 | """Generate the interpolation.png image for the interpolate 2 | section of the Scipy tutorial 3 | """ 4 | 5 | import numpy as np 6 | from scipy.interpolate import interp1d 7 | import pylab as pl 8 | 9 | measured_time = np.linspace(0, 1, 10) 10 | noise = (np.random.random(10)*2 - 1) * 1e-1 11 | measures = np.sin(2 * np.pi * measured_time) + noise 12 | 13 | linear_interp = interp1d(measured_time, measures) 14 | computed_time = np.linspace(0, 1, 50) 15 | linear_results = linear_interp(computed_time) 16 | cubic_interp = interp1d(measured_time, measures, kind='cubic') 17 | cubic_results = cubic_interp(computed_time) 18 | 19 | pl.plot(measured_time, measures, 'o', ms=6, label='measures') 20 | pl.plot(computed_time, linear_results, label='linear interp') 21 | pl.plot(computed_time, cubic_results, label='cubic interp') 22 | pl.legend() 23 | -------------------------------------------------------------------------------- /pyplots/scipy_optimize_example1.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | def f(x): 5 | return x**2 + 10*np.sin(x) 6 | 7 | 8 | x = np.arange(-10, 10, 0.1) 9 | plt.plot(x, f(x)) 10 | -------------------------------------------------------------------------------- /pyplots/scipy_optimize_example2.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy import optimize 3 | import matplotlib.pyplot as plt 4 | 5 | x = np.arange(-10, 10, 0.1) 6 | def f(x): 7 | return x**2 + 10*np.sin(x) 8 | 9 | 10 | grid = (-10, 10, 0.1) 11 | xmin_global = optimize.brute(f, (grid,)) 12 | xmin_local = optimize.fminbound(f, 0, 10) 13 | root = optimize.fsolve(f, 1) # our initial guess is 1 14 | root2 = optimize.fsolve(f, -2.5) 15 | 16 | xdata = np.linspace(-10, 10, num=20) 17 | np.random.seed(1234) 18 | ydata = f(xdata) + np.random.randn(xdata.size) 19 | 20 | def f2(x, a, b): 21 | return a*x**2 + b*np.sin(x) 22 | 23 | guess = [2, 2] 24 | params, params_covariance = optimize.curve_fit(f2, xdata, ydata, guess) 25 | 26 | 27 | fig = plt.figure() 28 | ax = fig.add_subplot(111) 29 | ax.plot(x, f(x), 'b-', label="f(x)") 30 | ax.plot(x, f2(x, *params), 'r--', label="Curve fit result") 31 | xmins = np.array([xmin_global[0], xmin_local]) 32 | ax.plot(xmins, f(xmins), 'go', label="Minima") 33 | roots = np.array([root, root2]) 34 | ax.plot(roots, f(roots), 'kv', label="Roots") 35 | ax.legend() 36 | ax.set_xlabel('x') 37 | ax.set_ylabel('f(x)') 38 | -------------------------------------------------------------------------------- /pyplots/scipy_optimize_sixhump.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy import optimize 3 | import matplotlib.pyplot as plt 4 | from mpl_toolkits.mplot3d import Axes3D 5 | 6 | 7 | def sixhump(x): 8 | return (4 - 2.1*x[0]**2 + x[0]**4 / 3.) * x[0]**2 + x[0] * x[1] + (-4 + \ 9 | 4*x[1]**2) * x[1] **2 10 | 11 | x = np.linspace(-2, 2) 12 | y = np.linspace(-1, 1) 13 | xg, yg = np.meshgrid(x, y) 14 | 15 | #plt.figure() # simple visualization for use in tutorial 16 | #plt.imshow(sixhump([xg, yg])) 17 | #plt.colorbar() 18 | 19 | fig = plt.figure() 20 | ax = fig.add_subplot(111, projection='3d') 21 | surf = ax.plot_surface(xg, yg, sixhump([xg, yg]), rstride=1, cstride=1, 22 | cmap=plt.cm.jet, linewidth=0, antialiased=False) 23 | 24 | ax.set_xlabel('x') 25 | ax.set_ylabel('y') 26 | ax.set_zlabel('f(x, y)') 27 | ax.set_title('Six-hump Camelback function') 28 | -------------------------------------------------------------------------------- /sphinxext/README.txt: -------------------------------------------------------------------------------- 1 | 2 | FIXME: This directory is copied from the matplolib. 3 | 4 | -------------------------------------------------------------------------------- /sphinxext/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayleicn/scipy-lecture-notes-zh-CN/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/sphinxext/__init__.py -------------------------------------------------------------------------------- /sphinxext/suites.py: -------------------------------------------------------------------------------- 1 | def fib(n): 2 | "return nth term of Fibonacci sequence" 3 | a, b = 0, 1 4 | i = 0 5 | while i