How to execute fitting of temporal data series

From KratosWiki
Jump to: navigation, search

A least square procedure could be useful for the interpolation with arbitrary functions of temporal series of any parameter. The interpolant function is defined through a certain number of parameters (X1, X2, ..., Xn) tat have to be evaluated. The main difficulty is that some interpolant functions (such as sin, cos, ...), doing the fitting can bring to a non linear procedure. Using scipy libraries in python, the calculation of (X1, X2, ..., Xn) could be done with "scipy.optimize" package. The basic command to consider are the following ones:

       import math
       from scipy.optimize import leastsq
       
       def residuals(p, y, x):
           omega,B,C,D = p
           err = []
           for i in range(0,len(x)-1):
               err.append(y[i] - math.exp(-0.0001 * omega * x[i]) * (B * math.sin(omega * x[i]) + C * math.cos(omega * x[i])) - D)
           return err;
       
       #---------------------------------------------------------
       # there should be defined of t and A, the temporal series to interpolate
       #---------------------------------------------------------
       
       p0 = [0.2, 2.0, 3.0, 4.0]
       AFit = leastsq(residuals,p0,args=(A,t))


After having imported all the needed libraries (module math and leastsq form scipy.optimize libraries), a residual function is defined. This contains the interpolant function still written in a parametric way. In this example, the interpolant function is a dumped sinusoid with an average value that could be different from zero and it brings to a non linear system to solve with omega, B, C and D as variables. The command to execute the data fitting is represented by the two last lines: in the first the initial value of the solution (needed to start the iterative procedure) is defined, whereas in the second one the analysis is started. "Afit" is a variable in which the fitting results are stored (the value of all the parameters setted in "residuals" function).

IMPORTANT: "p0", the initial value for the iteration, MUST be choose with a particular care: due to the non linear procedure, the resolution of the system could bring to a solution that correspond to a local minimum of the sum of the square residuals and not to the absolute one. It would be useful to test the sensibility of the procedure changing the initial solution "p0".

For any other information on the python procedure have a look at http://www.sipy.org.

Personal tools
Categories