SlideShare ist ein Scribd-Unternehmen logo
1 von 20
Downloaden Sie, um offline zu lesen
Interpolation with Python



                                    November 20, 2009



Wednesday, December 2, 2009
Enthought Python Distribution (EPD)
                          http://www.enthought.com/products/epd.php




Wednesday, December 2, 2009
Enthought Training Courses
               Dec. 7 - 9
               Dec. 10 - 11




                              Python Basics, NumPy, SciPy,
                              Matplotlib, Traits, TraitsUI,
                              Chaco…



Wednesday, December 2, 2009
Enthought Consulting




Wednesday, December 2, 2009
Interpolation




Wednesday, December 2, 2009
Contrast with

                          Curve-fitting   Extrapolation




Wednesday, December 2, 2009
2-D Interpolation




Wednesday, December 2, 2009
Curve interpolation and scattered samples




Wednesday, December 2, 2009
Interpolation basic mathematics

           Given data points            (xi , fi )



                                    f (x)    =             fj φ(x − xj )
                                                      j
                              φ(xi − xj )    =       δij
                                   f (xi )   =       fi




Wednesday, December 2, 2009
Interpolation
     scipy.interpolate — General purpose Interpolation




        •1D Interpolating Class
             • Constructs callable function from data points and
             desired spline interpolation order.
             • Function takes vector of inputs and returns interpolated
             value using the spline.
        •1D and 2D spline interpolation (FITPACK)
             • Smoothing splines up to order 5
             • Parametric splines

                                                         10


Wednesday, December 2, 2009
1D Spline Interpolation
      >>> from scipy.interpolate import interp1d



            interp1d(x, y, kind='linear', axis=-1, copy=True,
            bounds_error=True, fill_value=numpy.nan)

            Returns a function that uses interpolation to find the
            value of new points.

                 • x – 1d array of increasing real values which cannot
                   contain duplicates
                 • y – Nd array of real values whose length along the
                   interpolation axis must be len(x)
                 • kind – kind of interpolation (e.g. 'linear',
                   'nearest', 'quadratic', 'cubic'). Can also be an
                   integer n>1 which returns interpolating spline (with
                   minimum sum-of-squares discontinuity in nth
                   derivative).
                 • axis – axis of y along which to interpolate
                 • copy – make internal copies of x and y
                 • bounds_error – raise error for out-of-bounds
                 • fill_value – if bounds_error is False, then use this
                   value to fill in out-of-bounds.
                                                   11


Wednesday, December 2, 2009
1D Spline Interpolation
  # demo/interpolate/spline.py
  from scipy.interpolate import interp1d
  from pylab import plot, axis, legend
  from numpy import linspace

  # sample values
  x = linspace(0,2*pi,6)
  y = sin(x)

  # Create a spline class for interpolation.
  # kind=5 sets to 5th degree spline.
  # kind='nearest' -> zeroth older hold.
  # kind='linear' -> linear interpolation
  # kind=n -> use an nth order spline
  spline_fit = interp1d(x,y,kind=5)
  xx = linspace(0,2*pi, 50)
  yy = spline_fit(xx)

  # display the results.
  plot(xx, sin(xx), 'r-', x, y, 'ro', xx, yy, 'b--', linewidth=2)
  axis('tight')
  legend(['actual sin', 'original samples', 'interpolated curve'])




                                               12


Wednesday, December 2, 2009
2D Spline Interpolation
      >>> from scipy.interpolate import interp2d



      interp2d(x, y, z, kind='linear')

      Returns a function, f, that uses interpolation to find the value of new points: z_new = f(x_new,
      y_new)

      x – 1d or 2d array
      y – 1d or 2d array
      z – 1d or 2d array representing function evaluated at x
          and y
      kind – kind of interpolation: 'linear', 'quadratic', or
             'cubic'

      The shape of x, y, and z must be the same.




                                   Resulting function is evaluated
                              at   cross product of new inputs.




                                                       13


Wednesday, December 2, 2009
2D Spline Interpolation
     EXAMPLE

    >>> from scipy.interpolate import 
    ...      interp2d
    >>> from numpy import hypot, mgrid, 
    ...                    linspace
    >>> from scipy.special import j0
    >>> x,y = mgrid[-5:6,-5:6]
    >>> z = j0(hypot(x,y))
    >>> newfunc = interp2d(x, y, z,
    ...                     kind='cubic')
    >>> xx = linspace(-5,5,100)
    >>> yy = xx
    # xx and yy are 1-d
    # result is evaluated on the
    # cross product
    >>> zz = newfunc(xx,yy)
    >>> from enthought.mayavi import mlab
    >>> mlab.surf(x,y,z)
    >>> x2, y2 = mgrid[-5:5:100j,
    ...                 -5:5:100j]
    >>> mlab.surf(x2,y2,zz)

                                       14


Wednesday, December 2, 2009
What else is in SciPy?
      • Interpolate: Fitpack interface
                 • splrep : represent 1-d data as spline
                 • splprep : represent N-d parametric curve as spline
                 • splev : evaluate spline at new data points
                 • splint : evaluate integral of spline
                 • splalde : evaluate all derivatives of spline
                 • bisplrep : reprsent 2-d surface as spline
                 • bisplev : evaluate 2-d spline at new data points
                 • Additional class-based interface:
                    –UnivariateSpline
                    –InterpolatedUnivariateSpline
                    –LSQUnivariateSpline
                    –BivariateSpline
                    –SmoothBivariateSpline


Wednesday, December 2, 2009
What else is in SciPy?
      • Interpolate: General spline interface (no fitpack)
                 • splmake : create a general spline representation from data
                 • spleval : evaluate spline at new data
                 • spline : front end to splmake and spleval (all in one)
                 • spltopp : take spline reprentation and return piece-wise
                   polynomial representation of a spline
                 • ppform : piecewise polynomial representation of spline
                 • PiecewisePolynomial : class to generate arbitrary piecewise
                   polynomial interpolator given data + derivatives
                 • lagrange : Lagrange polynomial interpolator
                 • BarycentricInterpolator : polynomial interpolation class
                 • KroghInterpolator : polynomial interpolation class that allows
                   setting derivatives as well




Wednesday, December 2, 2009
What else is in SciPy?
      • Signal: Fast B-spline implementations (equally-spaced)
                 • bspline : B-spline basis functions of order n
                 • gauss_spline : Gaussian approximation to the B-spline
                 • qspline1d : quadratic B-spline coefficients from 1-d data
                 • cspline1d : cubic B-spline coefficients from 1-d data
                 • qspline1d_eval : evaluate quadratic spline
                 • cspline1d_eval : evaluat cubic spline
                 • qspline2d : quadratic B-spline coefficients from 2-d data
                 • cspline2d : cubic B-spline coefficients from 2-d data
                 • spline_filter : spline filter using from coefficients

                 • resample : sinc-interpolation using a Fourier method




Wednesday, December 2, 2009
What else is in SciPy?
      • ndimage: N-d spline interpolation
                 • map_coordinates : N-d interpolation
                 • spline_filter : repeated interpolation from spline coefficients


      • interpolate : Radial Basis Functions
                 • Rbf : N-d interpolation using radial basis functions




Wednesday, December 2, 2009
Things I’d like to see

        • Monotonic Splines
        • PCHIP
        • Finishing out the splmake, spleval interface
        • Improving a simplified interface to all the
          tools
        • An interpnd




Wednesday, December 2, 2009
Scientific Python Classes
                              http://www.enthought.com/training

                   Dec 7-11
                   Feb 22-26               Python for Scientists and Engineers (3 days)
                                           Advanced Modules (2 days)
                   May 17-21               Take both together to receive a discount


                   Aug 23-27




Wednesday, December 2, 2009

Weitere ähnliche Inhalte

Mehr von Enthought, Inc.

Mehr von Enthought, Inc. (8)

February EPD Webinar: How do I...use PiCloud for cloud computing?
February EPD Webinar: How do I...use PiCloud for cloud computing?February EPD Webinar: How do I...use PiCloud for cloud computing?
February EPD Webinar: How do I...use PiCloud for cloud computing?
 
SciPy India 2009
SciPy India 2009SciPy India 2009
SciPy India 2009
 
Parallel Processing with IPython
Parallel Processing with IPythonParallel Processing with IPython
Parallel Processing with IPython
 
Scientific Computing with Python Webinar: Traits
Scientific Computing with Python Webinar: TraitsScientific Computing with Python Webinar: Traits
Scientific Computing with Python Webinar: Traits
 
Scientific Computing with Python Webinar 9/18/2009:Curve Fitting
Scientific Computing with Python Webinar 9/18/2009:Curve FittingScientific Computing with Python Webinar 9/18/2009:Curve Fitting
Scientific Computing with Python Webinar 9/18/2009:Curve Fitting
 
Scientific Computing with Python Webinar --- August 28, 2009
Scientific Computing with Python Webinar --- August 28, 2009Scientific Computing with Python Webinar --- August 28, 2009
Scientific Computing with Python Webinar --- August 28, 2009
 
Scientific Computing with Python Webinar --- June 19, 2009
Scientific Computing with Python Webinar --- June 19, 2009Scientific Computing with Python Webinar --- June 19, 2009
Scientific Computing with Python Webinar --- June 19, 2009
 
Scientific Computing with Python Webinar --- May 22, 2009
Scientific Computing with Python Webinar --- May 22, 2009Scientific Computing with Python Webinar --- May 22, 2009
Scientific Computing with Python Webinar --- May 22, 2009
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 

Interpolation with SciPy and NumPy

  • 1. Interpolation with Python November 20, 2009 Wednesday, December 2, 2009
  • 2. Enthought Python Distribution (EPD) http://www.enthought.com/products/epd.php Wednesday, December 2, 2009
  • 3. Enthought Training Courses Dec. 7 - 9 Dec. 10 - 11 Python Basics, NumPy, SciPy, Matplotlib, Traits, TraitsUI, Chaco… Wednesday, December 2, 2009
  • 6. Contrast with Curve-fitting Extrapolation Wednesday, December 2, 2009
  • 8. Curve interpolation and scattered samples Wednesday, December 2, 2009
  • 9. Interpolation basic mathematics Given data points (xi , fi ) f (x) = fj φ(x − xj ) j φ(xi − xj ) = δij f (xi ) = fi Wednesday, December 2, 2009
  • 10. Interpolation scipy.interpolate — General purpose Interpolation •1D Interpolating Class • Constructs callable function from data points and desired spline interpolation order. • Function takes vector of inputs and returns interpolated value using the spline. •1D and 2D spline interpolation (FITPACK) • Smoothing splines up to order 5 • Parametric splines 10 Wednesday, December 2, 2009
  • 11. 1D Spline Interpolation >>> from scipy.interpolate import interp1d interp1d(x, y, kind='linear', axis=-1, copy=True, bounds_error=True, fill_value=numpy.nan) Returns a function that uses interpolation to find the value of new points. • x – 1d array of increasing real values which cannot contain duplicates • y – Nd array of real values whose length along the interpolation axis must be len(x) • kind – kind of interpolation (e.g. 'linear', 'nearest', 'quadratic', 'cubic'). Can also be an integer n>1 which returns interpolating spline (with minimum sum-of-squares discontinuity in nth derivative). • axis – axis of y along which to interpolate • copy – make internal copies of x and y • bounds_error – raise error for out-of-bounds • fill_value – if bounds_error is False, then use this value to fill in out-of-bounds. 11 Wednesday, December 2, 2009
  • 12. 1D Spline Interpolation # demo/interpolate/spline.py from scipy.interpolate import interp1d from pylab import plot, axis, legend from numpy import linspace # sample values x = linspace(0,2*pi,6) y = sin(x) # Create a spline class for interpolation. # kind=5 sets to 5th degree spline. # kind='nearest' -> zeroth older hold. # kind='linear' -> linear interpolation # kind=n -> use an nth order spline spline_fit = interp1d(x,y,kind=5) xx = linspace(0,2*pi, 50) yy = spline_fit(xx) # display the results. plot(xx, sin(xx), 'r-', x, y, 'ro', xx, yy, 'b--', linewidth=2) axis('tight') legend(['actual sin', 'original samples', 'interpolated curve']) 12 Wednesday, December 2, 2009
  • 13. 2D Spline Interpolation >>> from scipy.interpolate import interp2d interp2d(x, y, z, kind='linear') Returns a function, f, that uses interpolation to find the value of new points: z_new = f(x_new, y_new) x – 1d or 2d array y – 1d or 2d array z – 1d or 2d array representing function evaluated at x and y kind – kind of interpolation: 'linear', 'quadratic', or 'cubic' The shape of x, y, and z must be the same. Resulting function is evaluated at cross product of new inputs. 13 Wednesday, December 2, 2009
  • 14. 2D Spline Interpolation EXAMPLE >>> from scipy.interpolate import ... interp2d >>> from numpy import hypot, mgrid, ... linspace >>> from scipy.special import j0 >>> x,y = mgrid[-5:6,-5:6] >>> z = j0(hypot(x,y)) >>> newfunc = interp2d(x, y, z, ... kind='cubic') >>> xx = linspace(-5,5,100) >>> yy = xx # xx and yy are 1-d # result is evaluated on the # cross product >>> zz = newfunc(xx,yy) >>> from enthought.mayavi import mlab >>> mlab.surf(x,y,z) >>> x2, y2 = mgrid[-5:5:100j, ... -5:5:100j] >>> mlab.surf(x2,y2,zz) 14 Wednesday, December 2, 2009
  • 15. What else is in SciPy? • Interpolate: Fitpack interface • splrep : represent 1-d data as spline • splprep : represent N-d parametric curve as spline • splev : evaluate spline at new data points • splint : evaluate integral of spline • splalde : evaluate all derivatives of spline • bisplrep : reprsent 2-d surface as spline • bisplev : evaluate 2-d spline at new data points • Additional class-based interface: –UnivariateSpline –InterpolatedUnivariateSpline –LSQUnivariateSpline –BivariateSpline –SmoothBivariateSpline Wednesday, December 2, 2009
  • 16. What else is in SciPy? • Interpolate: General spline interface (no fitpack) • splmake : create a general spline representation from data • spleval : evaluate spline at new data • spline : front end to splmake and spleval (all in one) • spltopp : take spline reprentation and return piece-wise polynomial representation of a spline • ppform : piecewise polynomial representation of spline • PiecewisePolynomial : class to generate arbitrary piecewise polynomial interpolator given data + derivatives • lagrange : Lagrange polynomial interpolator • BarycentricInterpolator : polynomial interpolation class • KroghInterpolator : polynomial interpolation class that allows setting derivatives as well Wednesday, December 2, 2009
  • 17. What else is in SciPy? • Signal: Fast B-spline implementations (equally-spaced) • bspline : B-spline basis functions of order n • gauss_spline : Gaussian approximation to the B-spline • qspline1d : quadratic B-spline coefficients from 1-d data • cspline1d : cubic B-spline coefficients from 1-d data • qspline1d_eval : evaluate quadratic spline • cspline1d_eval : evaluat cubic spline • qspline2d : quadratic B-spline coefficients from 2-d data • cspline2d : cubic B-spline coefficients from 2-d data • spline_filter : spline filter using from coefficients • resample : sinc-interpolation using a Fourier method Wednesday, December 2, 2009
  • 18. What else is in SciPy? • ndimage: N-d spline interpolation • map_coordinates : N-d interpolation • spline_filter : repeated interpolation from spline coefficients • interpolate : Radial Basis Functions • Rbf : N-d interpolation using radial basis functions Wednesday, December 2, 2009
  • 19. Things I’d like to see • Monotonic Splines • PCHIP • Finishing out the splmake, spleval interface • Improving a simplified interface to all the tools • An interpnd Wednesday, December 2, 2009
  • 20. Scientific Python Classes http://www.enthought.com/training Dec 7-11 Feb 22-26 Python for Scientists and Engineers (3 days) Advanced Modules (2 days) May 17-21 Take both together to receive a discount Aug 23-27 Wednesday, December 2, 2009