Fitting ODE model, Python Curve_Fit

1.3k Views Asked by At

I want to fit and SIR model to data. I already found an excellent answer on this site (https://stackoverflow.com/questions/34422410/fitting-sir-model-based-on-least-squares); however I am running into issues when trying to import the data from a CSV file. Below is the code and the output:

import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate, optimize

#Data / read in the data 
import pandas as pd
data = pd.read_csv (r'C:\Users\hreed\Desktop\Data_Florida.csv')  #read in the data
data = data.to_numpy(dtype = float)  #convert to np.array with floats

time = np.linspace(0, len(data), len(data), dtype = float) #create time array based on data length

#The model
def model(y, x, beta, gamma):
    S = -beta * y[0] * y[1] 
    R = gamma * y[1]
    I = -(S + R)
    return S, I, R

#gives I(t)
def fit_odeint(x, beta, gamma):
    return integrate.odeint(model, (S0, I0, R0), x, args=(beta, gamma))[:,1]

#initial conditions 
I0 = data[0]
S0 = 1-data[0]
R0 = 0.0

#fitting the data
variables, pcov = optimize.curve_fit(fit_odeint, time, data)

#return solution to best fit parameters
fitted = fit_odeint(time, *variables)

#plotting 
plt.plot(time, data, 'o')
plt.plot(time, fitted)
plt.show()

I get the following output/error:

ValueError: object too deep for desired array

Traceback (most recent call last):

  File "C:\Users\hreed\Desktop\SIR DATA FITTING.py", line 39, in <module>
    variables, pcov = optimize.curve_fit(fit_odeint, time, data)

  File "C:\Users\hreed\anaconda3\lib\site-packages\scipy\optimize\minpack.py", line 784, in curve_fit
    res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)

  File "C:\Users\hreed\anaconda3\lib\site-packages\scipy\optimize\minpack.py", line 422, in leastsq
    retval = _minpack._lmdif(func, x0, args, full_output, ftol, xtol,

error: Result from function call is not a proper array of floats.

I have checked that my data and time are np.arrays, have floats in them, and are of the same length. I have no idea how to fix this issue - it seems that Python is telling me I am not using np.arrays with floats. I am pretty new to python (started learning withing the past year) and coding and am still trying to get used to it. Please help me!