I have this code:
import numpy as np
from scipy.optimize import curve_fit
def lin_func(x, a, b):
return a * x + b
a = 0.005/4
b = 10000/4
N = 10000
position_list = np.array([-100,-50,-20,0,20,50,100])
def get_params(N):
counts_list = np.zeros(len(position_list))
for i in range(len(position_list)):
position_0 = position_list[i]
counts = 0
for j in range(N):
position = np.random.normal(position_0,10)
p = 0.5+a+b*position*10**(-6)
counts = counts + np.sum(np.random.binomial(1000, p, 1))
counts_list[i] = counts
print(np.sqrt(counts_list))
popt, pcov = curve_fit(lin_func, position_list*10**(-6), counts_list, absolute_sigma = np.sqrt(counts_list))
return popt[1]/(N*1000)
K = 100
params_list = np.zeros(K)
for i in range(K):
params_list[i] = get_params(N)-0.5
print(params_list[i])
When I run it, it runs ok for a while, but then it displays this error:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
This only happens if I add absolute_sigma = np.sqrt(counts_list)
to the function call, however if I print counts_list
I don't see anything wrong with the number, just before the error pops up (they seem similar to the values printed when the function call works just fine). I am not sure how to debug this.
This is the full error message:
ValueError Traceback (most recent call last)
Cell In[10], line 4
2 params_list = np.zeros(K)
3 for i in range(K):
----> 4 params_list[i] = get_params(N)-0.5
5 print(params_list[i])
Cell In[9], line 13, in get_params(N)
11 counts_list[i] = counts
12 print(np.sqrt(counts_list))
---> 13 popt, pcov = curve_fit(lin_func, position_list*10**(-6), counts_list, absolute_sigma = np.sqrt(counts_list))
14 return popt[1]/(N*1000)
File ~/miniforge3/lib/python3.10/site-packages/scipy/optimize/_minpack_py.py:897, in curve_fit(f, xdata, ydata, p0, sigma, absolute_sigma, check_finite, bounds, method, jac, full_output, **kwargs)
895 pcov.fill(inf)
896 warn_cov = True
--> 897 elif not absolute_sigma:
898 if ysize > p0.size:
899 s_sq = cost / (ysize - p0.size)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Take another look at the curve_fit
docstring. absolute_sigma
is expected to be a boolean parameter. I suspect you meant to set the parameter sigma
, not absolute_sigma
.