Stammeo
Stammeo

Reputation: 17

fsolve mismatch shape error when nonlinear equations solver called from ODE solver

I have a system of two nonlinear equations inside my function "par_impl(y)", which I can solve using scipy.optimize.root standalone. Here "y" is a parameter. But I would like this system to be called from the ODE solver odeint in order to solve it for different value of "y", coupled to a simple ODE. This gives me fsolve mismatch shape error.

import numpy as np

from scipy.optimize import root import

matplotlib.pyplot as plt

from scipy.integrate import odeint

def par_impl(y):

def functionh(x):
    return [y + (x[0]**2) - x[1] -23, -4 - y*x[0] + (x[1]**2)]
sol = root(functionh, [1, 1])

return sol.x

def dy_dt(y, t):

dydt = (y**0.5) + par_impl(y)[0]

return dydt    

ls = np.linspace(0, 2, 50) y_0 = 2

Ps = odeint(dy_dt, y_0, ls)

y = Ps[:,0]

plt.plot(ls, y, "+", label="X") plt.legend(); plt.figure()

The error that I obtain is:

File "C:\Users\matteo\AppData\Local\Continuum\anaconda3\lib\site-packages\scipy\optimize\minpack.py", line 41, in _check_func raise TypeError(msg)

TypeError: fsolve: there is a mismatch between the input and output shape of the 'func' argument 'functionh'.Shape should be (2,) but it is (2, 1).

Upvotes: 0

Views: 694

Answers (1)

Sheldore
Sheldore

Reputation: 39052

The problem was that y was a list of len = 1 in your code. To access its element, you needed y[0] in your function. Below is a working version of your code (not showing the whole code) with the output plot.

from scipy.optimize import root
from scipy.integrate import odeint
# Other plotting and numpy imports

def par_impl(y):
    def functionh(x):
        return [y[0] + (x[0]**2) - x[1] -23, -4 - y[0]*x[0] + (x[1]**2)] # y --> y[0]
    sol = root(functionh, ([1, 1]))
    return sol.x

# dy_dt function here  

# Rest of your code unchanged

plt.plot(ls, y, "+", label="X") 
plt.legend()

Output

enter image description here

Upvotes: 0

Related Questions