PK çTUZ!Ùt t plot_image_filters.ipynb{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Plot filtering on images\n\n\nDemo filtering for denoising of images.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Load some data\nfrom scipy import misc\nface = misc.face(gray=True)\nface = face[:512, -512:] # crop out square on right\n\n# Apply a variety of filters\nfrom scipy import ndimage\nfrom scipy import signal\nfrom matplotlib import pyplot as plt\n\nimport numpy as np\nnoisy_face = np.copy(face).astype(np.float)\nnoisy_face += face.std() * 0.5 * np.random.standard_normal(face.shape)\nblurred_face = ndimage.gaussian_filter(noisy_face, sigma=3)\nmedian_face = ndimage.median_filter(noisy_face, size=5)\nwiener_face = signal.wiener(noisy_face, (5, 5))\n\nplt.figure(figsize=(12, 3.5))\nplt.subplot(141)\nplt.imshow(noisy_face, cmap=plt.cm.gray)\nplt.axis('off')\nplt.title('noisy')\n\nplt.subplot(142)\nplt.imshow(blurred_face, cmap=plt.cm.gray)\nplt.axis('off')\nplt.title('Gaussian filter')\n\nplt.subplot(143)\nplt.imshow(median_face, cmap=plt.cm.gray)\nplt.axis('off')\nplt.title('median filter')\n\nplt.subplot(144)\nplt.imshow(wiener_face, cmap=plt.cm.gray)\nplt.title('Wiener filter')\nplt.axis('off')\n\nplt.subplots_adjust(wspace=.05, left=.01, bottom=.01, right=.99, top=.99)\n\nplt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.13" } }, "nbformat": 4, "nbformat_minor": 0 }PK æTUü.ÄÍ plot_curve_fit.ipynb{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Curve fitting\n\n\nDemos a simple curve fitting\n\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "First generate some data\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n\n# Seed the random number generator for reproducibility\nnp.random.seed(0)\n\nx_data = np.linspace(-5, 5, num=50)\ny_data = 2.9 * np.sin(1.5 * x_data) + np.random.normal(size=50)\n\n# And plot it\nimport matplotlib.pyplot as plt\nplt.figure(figsize=(6, 4))\nplt.scatter(x_data, y_data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now fit a simple sine function to the data\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from scipy import optimize\n\ndef test_func(x, a, b):\n return a * np.sin(b * x)\n\nparams, params_covariance = optimize.curve_fit(test_func, x_data, y_data,\n p0=[2, 2])\n\nprint(params)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And plot the resulting curve on the data\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.figure(figsize=(6, 4))\nplt.scatter(x_data, y_data, label='Data')\nplt.plot(x_data, test_func(x_data, params[0], params[1]),\n label='Fitted function')\n\nplt.legend(loc='best')\n\nplt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.13" } }, "nbformat": 4, "nbformat_minor": 0 }PK èTUšEÆ plot_2d_minimization.ipynb{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Optimization of a two-parameter function\n\n\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n\n\n# Define the function that we are interested in\ndef sixhump(x):\n return ((4 - 2.1*x[0]**2 + x[0]**4 / 3.) * x[0]**2 + x[0] * x[1]\n + (-4 + 4*x[1]**2) * x[1] **2)\n\n# Make a grid to evaluate the function (for plotting)\nx = np.linspace(-2, 2)\ny = np.linspace(-1, 1)\nxg, yg = np.meshgrid(x, y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A 2D image plot of the function\n###########################################################\n Simple visualization in 2D\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nplt.figure()\nplt.imshow(sixhump([xg, yg]), extent=[-2, 2, -1, 1], origin=\"lower\")\nplt.colorbar()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A 3D surface plot of the function\n###########################################################\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from mpl_toolkits.mplot3d import Axes3D\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nsurf = ax.plot_surface(xg, yg, sixhump([xg, yg]), rstride=1, cstride=1,\n cmap=plt.cm.jet, linewidth=0, antialiased=False)\n\nax.set_xlabel('x')\nax.set_ylabel('y')\nax.set_zlabel('f(x, y)')\nax.set_title('Six-hump Camelback function')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Find the minima\n###########################################################\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from scipy import optimize\n\nx_min = optimize.minimize(sixhump, x0=[0, 0])\n\nplt.figure()\n# Show the function in 2D\nplt.imshow(sixhump([xg, yg]), extent=[-2, 2, -1, 1], origin=\"lower\")\nplt.colorbar()\n# And the minimum that we've found:\nplt.scatter(x_min.x[0], x_min.x[1])\n\nplt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.13" } }, "nbformat": 4, "nbformat_minor": 0 }PK èTUchˆ ˆ plot_fftpack.ipynb{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Plotting and manipulating FFTs for filtering\n\n\nPlot the power of the FFT of a signal and inverse FFT back to reconstruct\na signal.\n\nThis example demonstrate :func:`scipy.fftpack.fft`,\n:func:`scipy.fftpack.fftfreq` and :func:`scipy.fftpack.ifft`. It\nimplements a basic filter that is very suboptimal, and should not be\nused.\n\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\nfrom scipy import fftpack\nfrom matplotlib import pyplot as plt" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Generate the signal\n###########################################################\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Seed the random number generator\nnp.random.seed(1234)\n\ntime_step = 0.02\nperiod = 5.\n\ntime_vec = np.arange(0, 20, time_step)\nsig = (np.sin(2 * np.pi / period * time_vec)\n + 0.5 * np.random.randn(time_vec.size))\n\nplt.figure(figsize=(6, 5))\nplt.plot(time_vec, sig, label='Original signal')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Compute and plot the power\n###########################################################\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# The FFT of the signal\nsig_fft = fftpack.fft(sig)\n\n# And the power (sig_fft is of complex dtype)\npower = np.abs(sig_fft)**2\n\n# The corresponding frequencies\nsample_freq = fftpack.fftfreq(sig.size, d=time_step)\n\n# Plot the FFT power\nplt.figure(figsize=(6, 5))\nplt.plot(sample_freq, power)\nplt.xlabel('Frequency [Hz]')\nplt.ylabel('plower')\n\n# Find the peak frequency: we can focus on only the positive frequencies\npos_mask = np.where(sample_freq > 0)\nfreqs = sample_freq[pos_mask]\npeak_freq = freqs[power[pos_mask].argmax()]\n\n# Check that it does indeed correspond to the frequency that we generate\n# the signal with\nnp.allclose(peak_freq, 1./period)\n\n# An inner plot to show the peak frequency\naxes = plt.axes([0.55, 0.3, 0.3, 0.5])\nplt.title('Peak frequency')\nplt.plot(freqs[:8], power[pos_mask][:8])\nplt.setp(axes, yticks=[])\n\n# scipy.signal.find_peaks_cwt can also be used for more advanced\n# peak detection" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Remove all the high frequencies\n###########################################################\n\n We now remove all the high frequencies and transform back from\n frequencies to signal.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "high_freq_fft = sig_fft.copy()\nhigh_freq_fft[np.abs(sample_freq) > peak_freq] = 0\nfiltered_sig = fftpack.ifft(high_freq_fft)\n\nplt.figure(figsize=(6, 5))\nplt.plot(time_vec, sig, label='Original signal')\nplt.plot(time_vec, filtered_sig, linewidth=3, label='Filtered signal')\nplt.xlabel('Time [s]')\nplt.ylabel('Amplitude')\n\nplt.legend(loc='best')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Note** This is actually a bad way of creating a filter: such brutal\ncut-off in frequency space does not control distorsion on the signal.\n\nFilters should be created using the scipy filter design code\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.13" } }, "nbformat": 4, "nbformat_minor": 0 }PK æTU€½³ç· · plot_odeint_simple.ipynb{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Integrating a simple ODE\n\n\nSolve the ODE dy/dt = -2y between t = 0..4, with the initial condition\ny(t=0) = 1.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\nfrom scipy.integrate import odeint\nfrom matplotlib import pyplot as plt\n\ndef calc_derivative(ypos, time):\n return -2*ypos\n\ntime_vec = np.linspace(0, 4, 40)\nyvec = odeint(calc_derivative, 1, time_vec)\n\nplt.figure(figsize=(4, 3))\nplt.plot(time_vec, yvec)\nplt.xlabel('t: Time')\nplt.ylabel('y: Position')\nplt.tight_layout()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.13" } }, "nbformat": 4, "nbformat_minor": 0 }PK æTUҨ˲6 6 plot_optimize_example1.ipynb{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Finding the minimum of a smooth function\n\n\nDemos various methods to find the minimum of a function.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef f(x):\n return x**2 + 10*np.sin(x)\n\n\nx = np.arange(-10, 10, 0.1)\nplt.plot(x, f(x))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now find the minimum with a few methods\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from scipy import optimize\n\n# The default (Nelder Mead)\nprint(optimize.minimize(f, x0=0))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(optimize.minimize(f, x0=0, method=\"L-BFGS-B\"))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.13" } }, "nbformat": 4, "nbformat_minor": 0 }PK æTUÅÖY Y plot_t_test.ipynb{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Comparing 2 sets of samples from Gaussians\n\n\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\nfrom matplotlib import pyplot as plt\n\n# Generates 2 sets of observations\nsamples1 = np.random.normal(0, size=1000)\nsamples2 = np.random.normal(1, size=1000)\n\n# Compute a histogram of the sample\nbins = np.linspace(-4, 4, 30)\nhistogram1, bins = np.histogram(samples1, bins=bins, density=True)\nhistogram2, bins = np.histogram(samples2, bins=bins, density=True)\n\nplt.figure(figsize=(6, 4))\nplt.hist(samples1, bins=bins, density=True, label=\"Samples 1\")\nplt.hist(samples2, bins=bins, density=True, label=\"Samples 2\")\nplt.legend(loc='best')\nplt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.13" } }, "nbformat": 4, "nbformat_minor": 0 }PK çTUìê¦ö­ ­ plot_mathematical_morpho.ipynb{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Demo mathematical morphology\n\n\nA basic demo of binary opening and closing.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Generate some binary data\nimport numpy as np\nnp.random.seed(0)\na = np.zeros((50, 50))\na[10:-10, 10:-10] = 1\na += 0.25 * np.random.standard_normal(a.shape)\nmask = a>=0.5\n\n# Apply mathematical morphology\nfrom scipy import ndimage\nopened_mask = ndimage.binary_opening(mask)\nclosed_mask = ndimage.binary_closing(opened_mask)\n\n# Plot\nfrom matplotlib import pyplot as plt\n\nplt.figure(figsize=(12, 3.5))\nplt.subplot(141)\nplt.imshow(a, cmap=plt.cm.gray)\nplt.axis('off')\nplt.title('a')\n\nplt.subplot(142)\nplt.imshow(mask, cmap=plt.cm.gray)\nplt.axis('off')\nplt.title('mask')\n\nplt.subplot(143)\nplt.imshow(opened_mask, cmap=plt.cm.gray)\nplt.axis('off')\nplt.title('opened_mask')\n\nplt.subplot(144)\nplt.imshow(closed_mask, cmap=plt.cm.gray)\nplt.title('closed_mask')\nplt.axis('off')\n\nplt.subplots_adjust(wspace=.05, left=.01, bottom=.01, right=.99, top=.99)\n\nplt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.13" } }, "nbformat": 4, "nbformat_minor": 0 }PK æTU¬ÏK q q plot_spectrogram.ipynb{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n======================================\nSpectrogram, power spectral density\n======================================\n\nDemo spectrogram and power spectral density on a frequency chirp.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\nfrom matplotlib import pyplot as plt" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Generate a chirp signal\n###########################################################\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Seed the random number generator\nnp.random.seed(0)\n\ntime_step = .01\ntime_vec = np.arange(0, 70, time_step)\n\n# A signal with a small frequency chirp\nsig = np.sin(0.5 * np.pi * time_vec * (1 + .1 * time_vec))\n\nplt.figure(figsize=(8, 5))\nplt.plot(time_vec, sig)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Compute and plot the spectrogram\n###########################################################\n\n The spectrum of the signal on consecutive time windows\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from scipy import signal\nfreqs, times, spectrogram = signal.spectrogram(sig)\n\nplt.figure(figsize=(5, 4))\nplt.imshow(spectrogram, aspect='auto', cmap='hot_r', origin='lower')\nplt.title('Spectrogram')\nplt.ylabel('Frequency band')\nplt.xlabel('Time window')\nplt.tight_layout()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Compute and plot the power spectral density (PSD)\n###########################################################\n\n The power of the signal per frequency band\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "freqs, psd = signal.welch(sig)\n\nplt.figure(figsize=(5, 4))\nplt.semilogx(freqs, psd)\nplt.title('PSD: power spectral density')\nplt.xlabel('Frequency')\nplt.ylabel('Power')\nplt.tight_layout()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.13" } }, "nbformat": 4, "nbformat_minor": 0 }PK æTU„¡ .Š Š $ plot_odeint_damped_spring_mass.ipynb{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Integrate the Damped spring-mass oscillator\n\n\n\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\nfrom scipy.integrate import odeint\nfrom matplotlib import pyplot as plt\n\nmass = 0.5 # kg\nkspring = 4 # N/m\ncviscous = 0.4 # N s/m\n\n\neps = cviscous / (2 * mass * np.sqrt(kspring/mass))\nomega = np.sqrt(kspring / mass)\n\n\ndef calc_deri(yvec, time, eps, omega):\n return (yvec[1], -eps * omega * yvec[1] - omega **2 * yvec[0])\n\ntime_vec = np.linspace(0, 10, 100)\nyinit = (1, 0)\nyarr = odeint(calc_deri, yinit, time_vec, args=(eps, omega))\n\nplt.figure(figsize=(4, 3))\nplt.plot(time_vec, yarr[:, 0], label='y')\nplt.plot(time_vec, yarr[:, 1], label=\"y'\")\nplt.legend(loc='best')\nplt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.13" } }, "nbformat": 4, "nbformat_minor": 0 }PK æTUúòCb b plot_interpolation.ipynb{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# A demo of 1D interpolation\n\n\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Generate data\nimport numpy as np\nnp.random.seed(0)\nmeasured_time = np.linspace(0, 1, 10)\nnoise = 1e-1 * (np.random.random(10)*2 - 1)\nmeasures = np.sin(2 * np.pi * measured_time) + noise\n\n# Interpolate it to new time points\nfrom scipy.interpolate import interp1d\nlinear_interp = interp1d(measured_time, measures)\ninterpolation_time = np.linspace(0, 1, 50)\nlinear_results = linear_interp(interpolation_time)\ncubic_interp = interp1d(measured_time, measures, kind='cubic')\ncubic_results = cubic_interp(interpolation_time)\n\n# Plot the data and the interpolation\nfrom matplotlib import pyplot as plt\nplt.figure(figsize=(6, 4))\nplt.plot(measured_time, measures, 'o', ms=6, label='measures')\nplt.plot(interpolation_time, linear_results, label='linear interp')\nplt.plot(interpolation_time, cubic_results, label='cubic interp')\nplt.legend()\nplt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.13" } }, "nbformat": 4, "nbformat_minor": 0 }PK çTUŸ¤¨„Ä Ä plot_connect_measurements.ipynb{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Demo connected components\n\n\nExtracting and labeling connected components in a 2D array\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\nfrom matplotlib import pyplot as plt" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Generate some binary data\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "np.random.seed(0)\nx, y = np.indices((100, 100))\nsig = np.sin(2*np.pi*x/50.) * np.sin(2*np.pi*y/50.) * (1+x*y/50.**2)**2\nmask = sig > 1\n\nplt.figure(figsize=(7, 3.5))\nplt.subplot(1, 2, 1)\nplt.imshow(sig)\nplt.axis('off')\nplt.title('sig')\n\nplt.subplot(1, 2, 2)\nplt.imshow(mask, cmap=plt.cm.gray)\nplt.axis('off')\nplt.title('mask')\nplt.subplots_adjust(wspace=.05, left=.01, bottom=.01, right=.99, top=.9)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Label connected components\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from scipy import ndimage\nlabels, nb = ndimage.label(mask)\n\nplt.figure(figsize=(3.5, 3.5))\nplt.imshow(labels)\nplt.title('label')\nplt.axis('off')\n\nplt.subplots_adjust(wspace=.05, left=.01, bottom=.01, right=.99, top=.9)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Extract the 4th connected component, and crop the array around it\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "sl = ndimage.find_objects(labels==4)\nplt.figure(figsize=(3.5, 3.5))\nplt.imshow(sig[sl[0]])\nplt.title('Cropped connected component')\nplt.axis('off')\n\nplt.subplots_adjust(wspace=.05, left=.01, bottom=.01, right=.99, top=.9)\n\nplt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.13" } }, "nbformat": 4, "nbformat_minor": 0 }PK çTU”D3j j plot_optimize_example2.ipynb{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Minima and roots of a function\n\n\nDemos finding minima and roots of a function.\n\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Define the function\n###########################################################\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n\nx = np.arange(-10, 10, 0.1)\ndef f(x):\n return x**2 + 10*np.sin(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Find minima\n###########################################################\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from scipy import optimize\n\n# Global optimization\ngrid = (-10, 10, 0.1)\nxmin_global = optimize.brute(f, (grid, ))\nprint(\"Global minima found %s\" % xmin_global)\n\n# Constrain optimization\nxmin_local = optimize.fminbound(f, 0, 10)\nprint(\"Local minimum found %s\" % xmin_local)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Root finding\n###########################################################\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "root = optimize.root(f, 1) # our initial guess is 1\nprint(\"First root found %s\" % root.x)\nroot2 = optimize.root(f, -2.5)\nprint(\"Second root found %s\" % root2.x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Plot function, minima, and roots\n###########################################################\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nfig = plt.figure(figsize=(6, 4))\nax = fig.add_subplot(111)\n\n# Plot the function\nax.plot(x, f(x), 'b-', label=\"f(x)\")\n\n# Plot the minima\nxmins = np.array([xmin_global[0], xmin_local])\nax.plot(xmins, f(xmins), 'go', label=\"Minima\")\n\n# Plot the roots\nroots = np.array([root.x, root2.x])\nax.plot(roots, f(roots), 'kv', label=\"Roots\")\n\n# Decorate the figure\nax.legend(loc='best')\nax.set_xlabel('x')\nax.set_ylabel('f(x)')\nax.axhline(0, color='gray')\nplt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.13" } }, "nbformat": 4, "nbformat_minor": 0 }PK æTUûfù`P P plot_detrend.ipynb{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Detrending a signal\n\n\n:func:`scipy.signal.detrend` removes a linear trend.\n\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Generate a random signal with a trend\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\nt = np.linspace(0, 5, 100)\nx = t + np.random.normal(size=100)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Detrend\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from scipy import signal\nx_detrended = signal.detrend(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Plot\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from matplotlib import pyplot as plt\nplt.figure(figsize=(5, 4))\nplt.plot(t, x, label=\"x\")\nplt.plot(t, x_detrended, label=\"x_detrended\")\nplt.legend(loc='best')\nplt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.13" } }, "nbformat": 4, "nbformat_minor": 0 }PK æTUÍV¾Ê  plot_resample.ipynb{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\nResample a signal with scipy.signal.resample\n=============================================\n\n:func:`scipy.signal.resample` uses FFT to resample a 1D signal.\n\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Generate a signal with 100 data point\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\nt = np.linspace(0, 5, 100)\nx = np.sin(t)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Downsample it by a factor of 4\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from scipy import signal\nx_resampled = signal.resample(x, 25)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Plot\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from matplotlib import pyplot as plt\nplt.figure(figsize=(5, 4))\nplt.plot(t, x, label='Original signal')\nplt.plot(t[::4], x_resampled, 'ko', label='Resampled signal')\n\nplt.legend(loc='best')\nplt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.13" } }, "nbformat": 4, "nbformat_minor": 0 }PK çTU§c*kì ì plot_image_transform.ipynb{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Plot geometrical transformations on images\n\n\nDemo geometrical transformations of images.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Load some data\nfrom scipy import misc\nface = misc.face(gray=True)\n\n# Apply a variety of transformations\nfrom scipy import ndimage\nfrom matplotlib import pyplot as plt\nshifted_face = ndimage.shift(face, (50, 50))\nshifted_face2 = ndimage.shift(face, (50, 50), mode='nearest')\nrotated_face = ndimage.rotate(face, 30)\ncropped_face = face[50:-50, 50:-50]\nzoomed_face = ndimage.zoom(face, 2)\nzoomed_face.shape\n\nplt.figure(figsize=(15, 3))\nplt.subplot(151)\nplt.imshow(shifted_face, cmap=plt.cm.gray)\nplt.axis('off')\n\nplt.subplot(152)\nplt.imshow(shifted_face2, cmap=plt.cm.gray)\nplt.axis('off')\n\nplt.subplot(153)\nplt.imshow(rotated_face, cmap=plt.cm.gray)\nplt.axis('off')\n\nplt.subplot(154)\nplt.imshow(cropped_face, cmap=plt.cm.gray)\nplt.axis('off')\n\nplt.subplot(155)\nplt.imshow(zoomed_face, cmap=plt.cm.gray)\nplt.axis('off')\n\nplt.subplots_adjust(wspace=.05, left=.01, bottom=.01, right=.99, top=.99)\n\nplt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.13" } }, "nbformat": 4, "nbformat_minor": 0 }PK æTUÝÕ}OR R plot_normal_distribution.ipynb{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n=======================================\nNormal distribution: histogram and PDF\n=======================================\n\nExplore the normal distribution: a histogram built from samples and the\nPDF (probability density function).\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n\n# Sample from a normal distribution using numpy's random number generator\nsamples = np.random.normal(size=10000)\n\n# Compute a histogram of the sample\nbins = np.linspace(-5, 5, 30)\nhistogram, bins = np.histogram(samples, bins=bins, density=True)\n\nbin_centers = 0.5*(bins[1:] + bins[:-1])\n\n# Compute the PDF on the bin centers from scipy distribution object\nfrom scipy import stats\npdf = stats.norm.pdf(bin_centers)\n\nfrom matplotlib import pyplot as plt\nplt.figure(figsize=(6, 4))\nplt.plot(bin_centers, histogram, label=\"Histogram of samples\")\nplt.plot(bin_centers, pdf, label=\"PDF\")\nplt.legend()\nplt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.13" } }, "nbformat": 4, "nbformat_minor": 0 }PK éTUABíÛ Û &

-