JakobJakobson13
JakobJakobson13

Reputation: 145

Fit differential equation with scipy

how can I fit the differential function of the followint scipy tutorial

Scipy Differential Equation Tutorial?

In the end I want to fit some datapoints that follow a set of two differential equations with six parameters in total but I'd like to start with an easy example. So far I tried the functions scipy.optimize.curve_fit and scipy.optimize.leastsq but I did not get anywhere.

So this is how far I came:

import numpy as np
import scipy.optimize as scopt
import scipy.integrate as scint
import scipy.optimize as scopt

def pend(y, t, b, c):
    theta, omega = y
    dydt = [omega, -b*omega - c*np.sin(theta)]
    return dydt


def test_pend(y, t, b, c):
    theta, omega = y
    dydt = [omega, -b*omega - c*np.sin(theta)]
    return dydt

b = 0.25
c = 5.0

y0 = [np.pi - 0.1, 0.0]
guess = [0.5, 4]
t = np.linspace(0, 1, 11)

sol = scint.odeint(pend, y0, t, args=(b, c))

popt, pcov = scopt.curve_fit(test_pend, guess, t, sol)

with the following error message:

ValueError: too many values to unpack (expected 2)

And I'm sorry as this is assumingly a pretty simple question but I don't get it to work. So thanks in advance.

Upvotes: 2

Views: 5124

Answers (1)

Lutz Lehmann
Lutz Lehmann

Reputation: 25992

You need to provide a function f(t,b,c) that given an argument or a list of arguments in t returns the value of the function at the argument(s). This requires some work, either by determining the type of t or by using a construct that works either way:

def f(t,b,c): 
    tspan = np.hstack([[0],np.hstack([t])])
    return scint.odeint(pend, y0, tspan, args=(b,c))[1:,0]

popt, pcov = scopt.curve_fit(f, t, sol[:,0], p0=guess)

which returns popt = array([ 0.25, 5. ]).

This can be extended to fit even more parameters,

def f(t, a0,a1, b,c): 
    tspan = np.hstack([[0],np.hstack([t])])
    return scint.odeint(pend, [a0,a1], tspan, args=(b,c))[1:,0]

popt, pcov = scopt.curve_fit(f, t, sol[:,0], p0=guess)

which results in popt = [ 3.04159267e+00, -2.38543640e-07, 2.49993362e-01, 4.99998795e+00].


Another possibility is to explicitly compute the square norm of the differences to the target solution and apply minimization to the so-defined scalar function.

 def f(param): 
     b,c = param
     t_sol = scint.odeint(pend, y0, t, args=(b,c))
     return np.linalg.norm(t_sol[:,0]-sol[:,0]);

res = scopt.minimize(f, np.array(guess))

which returns in res

      fun: 1.572327981969186e-08
 hess_inv: array([[ 0.00031325,  0.00033478],
                  [ 0.00033478,  0.00035841]])
      jac: array([ 0.06129361, -0.04859557])
  message: 'Desired error not necessarily achieved due to precision loss.'
     nfev: 518
      nit: 27
     njev: 127
   status: 2
  success: False
        x: array([ 0.24999905,  4.99999884])

Upvotes: 2

Related Questions