nicnaz
nicnaz

Reputation: 23

Scipy optimize error

I have a fairly simply parameter estimation problem with ODEs I want to solve in Python. I have been using the odeint function for solving the ODEs and the scipy.optimize library for finding the parameter. When I use the odeint function by itself I get no problems but via the scipy.optimize it gives me an error RuntimeError: The array return by func must be one-dimensional, but got ndim=2.

I do not think it is a duplicate with How to fix the error: The array return by func must be one-dimensional, but got ndim=2 as I can run the odeint solver independently....

Code below:

import numpy as np
from scipy.integrate import odeint
from scipy.optimize import minimize

init = [0,0]
t_end = 5
dt = 0.01
tspan = np.arange(0,t_end+dt,dt)

def my_fun(y,t,K):
    if t<=0.07:
        s = 2000
    else:
        s = 0
    return np.array([s+3.6*(y[1]-y[0]) +K*y[0], 0.38*y[0]-0.48*y[1] +K*y[1]])

def solver(t,p2):    
    y_ode = odeint(my_fun,init,t,args = (p2,))
    return y_ode

test = solver(tspan,0.01)
print(test)

y_real = solver(tspan, 0.1)

def err_fun(p):
    return np.sum((y_real-solver(tspan,p))**2)


print(err_fun(0.01))      
c0 = [0.2]

optim = minimize(err_fun,c0,method='Nelder-Mead')

Upvotes: 2

Views: 1027

Answers (1)

Warren Weckesser
Warren Weckesser

Reputation: 114831

The problem is that minimize calls err_fun with an argument that is a one-dimensional array of length 1; err_fun passes this to solver, and solver passes it to odeint, which passes it to my_fun as the K argument. Take a look at the difference in the shape of the output of my_fun when K is either a scalar or an array with length 1:

In [43]: my_fun([1, 2], 0, 0.05)  # K is a scalar.
Out[43]: array([ 2.00365e+03, -4.80000e-01])

In [44]: my_fun([1, 2], 0, np.array([0.05]))  # K is an array.
Out[44]: 
array([[ 2.00365e+03],
       [-4.80000e-01]])

When K is a one-dimensional array with length 1, my_fun returns an array with shape (2, 1). That's not what odeint expects.

To fix this, you'll have to convert that array to a scalar somewhere in the chain of calls. For example, you could do it immediately in err_fun, with something like:

def err_fun(p):
    if not np.isscalar(p):
        p = p[0]
    return np.sum((y_real-solver(tspan,p))**2)

When I do that and run your script, the code works. Here's what I get for optim:

In [46]: optim
Out[46]: 
 final_simplex: (array([[0.1       ],
       [0.09999512]]), array([2.95795174e-22, 4.03900365e-05]))
           fun: 2.9579517415523713e-22
       message: 'Optimization terminated successfully.'
          nfev: 34
           nit: 17
        status: 0
       success: True
             x: array([0.1])

Upvotes: 1

Related Questions