I have defined a SymPy piecewise function to compute the Federal Income tax for 2017. I know the function is working as I have tried various inputs and compared it to verified tax calculators and it gives the same result.
However, when trying to plot the SymPy function, I get the error:
TypeError: '>=' not supported between instances of 'complex' and 'int'
I never defined any complex numbers.
def getFedTax(alpha,p,GI):
# alpha is an array indicating the starting dollar amount of each tax bracket, not including 0
#p is an array of the Tax Percentage amount corresponding to the interval BEFORE each alpha, i.e. [0,alpha0) corresponds to p0, [alpha0, alpha1) corresponds to p1, etc.
#x is the Gross Income for computation
# create an array of the cumulative sums for each starting point in alpha
cumsums = [0,p[0]*(alpha[0]-0)]
cumnum = cumsums[1]
for i,num in enumerate(alpha[1:-1],start=1):
cumsums.append(p[i]*(alpha[i]-alpha[i-1]) + cumnum)
cumnum = cumnum + p[i]*(alpha[i]-alpha[i-1])
cumsums.append(p[-2]*(alpha[-1]-alpha[-2]) + cumnum)
#Create the argument list of tuples for the SymPy.Piecewise function
argtuples = []
for n,bracstart in enumerate(alpha):
if n == 0:
argtuples.append((cumsums[0] + p[0]*x, And(0<=x, x<alpha[0])))
elif 0 < n and n < len(alpha)-1:
argtuples.append((cumsums[n] + p[n]*(x - alpha[n-1]), And(alpha[n-1] <= x, x < alpha[n])))
else:
argtuples.append((cumsums[-1]+p[-1]*(x-alpha[-1]), x>alpha[-1]))
t = Piecewise(*argtuples)
return round(t.subs(x,GI),2), t
from sympy import Piecewise, And
from sympy.plotting.plot import plot
from sympy.abc import x
ti = getFedTax([9325.00,37950.00,91900.00,191650.00,416700.00,418400.00],
[0.10,0.15,0.25,0.28,.33,.35,.396],1000000)
plot(ti[1],(x,1.,450000.00))
Full traceback:
runfile('C:/Users/galileo/Downloads/trial.py',
wdir='C:/Users/galileo/Downloads')
File "c:\users\galileo\appdata\local\programs\python\python36\lib\site-
packages\spyder\utils\site\sitecustomize.py", line 710, in runfile
execfile(filename, namespace)
File "c:\users\galileo\appdata\local\programs\python\python36\lib\site-
packages\spyder\utils\site\sitecustomize.py", line 101, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/galileo/Downloads/trial.py", line 39, in <module>
plot(ti[1],(x,1.,450000.00))
File "c:\users\galileo\appdata\local\programs\python\python36\lib\site-
packages\sympy\plotting\plot.py", line 1295, in plot
plots.show()
File "c:\users\galileo\appdata\local\programs\python\python36\lib\site-
packages\sympy\plotting\plot.py", line 196, in show
self._backend.show()
File "c:\users\galileo\appdata\local\programs\python\python36\lib\site-
packages\sympy\plotting\plot.py", line 1029, in show
self.process_series()
File "c:\users\galileo\appdata\local\programs\python\python36\lib\site-
packages\sympy\plotting\plot.py", line 908, in process_series
collection = self.LineCollection(s.get_segments())
File "c:\users\galileo\appdata\local\programs\python\python36\lib\site-
packages\sympy\plotting\plot.py", line 514, in get_segments
f_start = f(self.start)
File "c:\users\galileo\appdata\local\programs\python\python36\lib\site-
packages\sympy\plotting\experimental_lambdify.py", line 231, in __call__
result = self.lambda_func(args)
File "c:\users\galileo\appdata\local\programs\python\python36\lib\site-
packages\sympy\plotting\experimental_lambdify.py", line 316, in __call__
return self.lambda_func(*args, **kwargs)
File "<string>", line 1, in <lambda>
TypeError: '>=' not supported between instances of 'complex' and 'int'
Plotting of piecewise linear was bugged, and seems to have been fixed in january 2018
Upgrading to SymPy 1.2 (from 1.1.1 which was shipped by default with Anaconda) did the trick for me.
from sympy import symbols
from sympy.plotting import plot
x = symbols('x')
from sympy import Piecewise, log
f = 2*x+3
g = x+1
p = Piecewise((-1, x < -1), (g, x <= 1), (f, True))
plot(p)
Related
I'm trying to find the max height of a rocket launched using the equation for the height. I have the derivative already set, so now I need to solve for zero using the derivative. The equation I'm trying to solve for 0 is
-0.0052t^3 + 4.26t + 0.000161534t^3.751
The related code is as follows
def velocity(equation):
time = Symbol('t')
derivative = equation.diff(time)
return derivative
def max_height():
time = Symbol('t')
equ = 2.13 * (time ** 2) - 0.0013 * (time ** 4) + 0.000034 * (time ** 4.751)
return solve(Eq(velocity(equ), 0))
if __name__ == '__main__':
t = Symbol('t')
print(max_height())
I tried inserting the direct equation into the Eq, like so...
return solve(Eq(-0.0052t^3 + 4.26t + 0.000161534t^3.751, 0))
thinking the problem might be with the return type of velocity, but that didn't work. I also tried playing around with making them class functions, but that didn't seem to help either.
The result I'm getting is that it runs indefinitely until I stop it. When I do stop it, I get the following errors
Traceback (most recent call last):
File "C:\Users\...\main.py", line 40, in <module>
print(max_height())
File "C:\Users\...\main.py", line 29, in max_height
return solve(Eq(velocity(equ), 0))
File "C:\Users\...\venv\lib\site-packages\sympy\solvers\solvers.py", line 1095, in solve
solution = _solve(f[0], *symbols, **flags)
File "C:\Users\...\venv\lib\site-packages\sympy\solvers\solvers.py", line 1675, in _solve
u = unrad(f_num, symbol)
File "C:\Users\...\venv\lib\site-packages\sympy\solvers\solvers.py", line 3517, in unrad
neq = unrad(eq, *syms, **flags)
File "C:\Users\...\venv\lib\site-packages\sympy\solvers\solvers.py", line 3300, in unrad
eq = _mexpand(eq, recursive=True)
File "C:\Users\...\venv\lib\site-packages\sympy\core\function.py", line 2837, in _mexpand
was, expr = expr, expand_mul(expand_multinomial(expr))
File "C:\Users\...\venv\lib\site-packages\sympy\core\function.py", line 2860, in expand_mul
return sympify(expr).expand(deep=deep, mul=True, power_exp=False,
File "C:\Users\...\venv\lib\site-packages\sympy\core\cache.py", line 72, in wrapper
retval = cfunc(*args, **kwargs)
File "C:\Users\...\venv\lib\site-packages\sympy\core\expr.py", line 3630, in expand
expr, _ = Expr._expand_hint(
File "C:\Users\...\venv\lib\site-packages\sympy\core\expr.py", line 3555, in _expand_hint
arg, arghit = Expr._expand_hint(arg, hint, **hints)
File "C:\Users\...\venv\lib\site-packages\sympy\core\expr.py", line 3563, in _expand_hint
newexpr = getattr(expr, hint)(**hints)
File "C:\...\venv\lib\site-packages\sympy\core\mul.py", line 936, in _eval_expand_mul
n, d = fraction(expr)
File "C:\...\venv\lib\site-packages\sympy\simplify\radsimp.py", line 1113, in fraction
return Mul(*numer, evaluate=not exact), Mul(*denom, evaluate=not exact)
File "C:\...\venv\lib\site-packages\sympy\core\cache.py", line 72, in wrapper
retval = cfunc(*args, **kwargs)
File "C:\...\venv\lib\site-packages\sympy\core\operations.py", line 85, in __new__
c_part, nc_part, order_symbols = cls.flatten(args)
File "C:\...\venv\lib\site-packages\sympy\core\mul.py", line 523, in flatten
c_part.append(p)
Any help would be greatly appreciated.
There are several problems:
You can't use ^ for exponentiation. In Python you need **. See sympy - gotchas.
Another problem is that you have 3 different variables t. This should be just one variable. If there is only one variable in an equation, equation.diff() automatically uses that one. If there are multiple, you also need to pass the correct variable to your velocity function.
As your equations uses floats, sympy gets very confused as it tries to find exact symbolic solutions, which doesn't work well in floats which are by definition only approximations. Especially the float in the exponent is hard for sympy. To cope, sympy uses a numerical solver nsolve, but which needs a seed value to start number crunching. Depending on the seed, either 0, 40.50 or 87.55 is obtained.
Here is how the updated code could look like:
from sympy import Symbol, Eq, nsolve
def velocity(equation):
derivative = equation.diff()
return derivative
def max_height():
time = Symbol('t')
equ = 2.13 * (time ** 2) - 0.0013 * (time ** 4) + 0.000034 * (time ** 4.751)
return nsolve(Eq(velocity(equ), 0), 30)
print(max_height())
It could help to draw a plot (using lambdify() to make the functions accessible in matplotlib):
from sympy import Symbol, Eq, nsolve, lambdify
def velocity(equation, time):
derivative = equation.diff(time)
return derivative
def get_equation(time):
return 2.13 * (time ** 2) - 0.0013 * (time ** 4) + 0.000034 * (time ** 4.751)
def max_height(equ, time):
return [nsolve(Eq(velocity(equ, time), 0), initial_guess) for initial_guess in [0, 30, 500]]
time = Symbol('t')
equ = get_equation(time)
max_heigths = max_height(equ, time)
equ_np = lambdify(time, equ)
vel_np = lambdify(time, velocity(equ, time))
import matplotlib.pyplot as plt
import numpy as np
xs = np.linspace(0, 105, 2000)
ys = equ_np(xs)
max_heigths = np.array(max_heigths)
plt.plot(xs, equ_np(xs), label='equation')
plt.plot(xs, vel_np(xs), label='velocity')
plt.axhline(0, ls='--', color='black')
plt.scatter(max_heigths, equ_np(max_heigths), s=100, color='red', alpha=0.5, label='extremes')
plt.legend()
plt.show()
Metpy.plots.skewT.plot_barbs throws this error:
TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
when given 3 Numpy arrays: pressure, u, and v.
Other users who reported this error message either did not use the correct dtype or used np as a variable name. I have verified that neither of these is the cause in my case. I have also tried removing the units from the u and v arrays.
import numpy as np
import metpy.plots as mpplots
# units comes from another file
pres = np.array([nan, 96950.26215278, 96877.55755208, 96763.37230603, 96652.54882812]) * units.pascal
u = np.array([nan, 0.36735288, 0.44829027, 1.29182593, -0.94374102]) * units.meter / units.second
v = np.array([nan, 4.61110612, 5.74110696, 6.01459714, 5.5652721]) * units.meter / units.second
rotation = 30
fig = mpplots.SkewT(rotation=rotation, aspect=80.5)
fig.ax.yaxis.set_major_locator(ticker.MultipleLocator(5))
fig.plot(pres, temp, 'r', label="Temperature")
fig.plot(pres, t_d, 'g', label="Dewpoint")
fig.ax.set_ylim(np.nanmax(pres.to(units.hPa).magnitude) + 10,
np.nanmin(pres.to(units.hPa).magnitude) - 20)
fig.ax.set_xlim(np.nanmin(t_d.to(units.degC).magnitude) - 5,
np.nanmax(temp.to(units.degC).magnitude) + 10)
fig.plot_dry_adiabats(linewidth=0.5, label="Dry Adiabats")
fig.plot_moist_adiabats(linewidth=0.5, label="Moist Adiabats")
fig.plot_mixing_lines(linewidth=0.5, label="Mixing Ratio")
fig.plot_barbs(np.array(pres.magnitude, dtype='float64') * pres.units,
np.array(u.magnitude, dtype='float64') * u.units,
np.array(v.magnitude, dtype='float64') * v.units)
Traceback (most recent call last):
File "/snap/pycharm-professional/167/helpers/pydev/pydevd.py", line 1415, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "/snap/pycharm-professional/167/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/home/.../sample_analysis.py", line 43, in <module>
fig = plotting.plot_skewT(temp=temp, pres=pres, t_d=t_d, u=u, v=v, units=units)
File "/home/.../plotting.py", line 248, in plot_skewT
np.array(v.magnitude, dtype='float64') * v.units)
File "/home/.../miniconda3/envs/Profiles/lib/python3.7/site-packages/metpy/plots/skewt.py", line 440, in plot_barbs
clip_on=True, zorder=2, **kwargs)
File "/home/.../miniconda3/envs/Profiles/lib/python3.7/site-packages/matplotlib/__init__.py", line 1785, in inner
return func(ax, *args, **kwargs)
File "/home/.../miniconda3/envs/Profiles/lib/python3.7/site-packages/matplotlib/axes/_axes.py", line 4874, in barbs
b = mquiver.Barbs(self, *args, **kw)
File "/home/.../miniconda3/envs/Profiles/lib/python3.7/site-packages/matplotlib/quiver.py", line 965, in __init__
self.set_UVC(u, v, c)
File "/home/.../miniconda3/envs/Profiles/lib/python3.7/site-packages/matplotlib/quiver.py", line 1145, in set_UVC
self.u = ma.masked_invalid(U, copy=False).ravel()
File "/home/.../miniconda3/envs/Profiles/lib/python3.7/site-packages/numpy/ma/core.py", line 2366, in masked_invalid
condition = ~(np.isfinite(a))
TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
Process finished with exit code 1
I was able to make it work with this:
import numpy as np
import metpy.plots as mpplots
from metpy.units import units
pres = np.array([np.nan, 96950.26215278, 96877.55755208, 96763.37230603, 96652.54882812]) * units.pascal
u = np.array([np.nan, 0.36735288, 0.44829027, 1.29182593, -0.94374102]) * units.meter / units.second
v = np.array([np.nan, 4.61110612, 5.74110696, 6.01459714, 5.5652721]) * units.meter / units.second
fig = mpplots.SkewT(rotation=30, aspect=80.5)
fig.plot_dry_adiabats(linewidth=0.5, label="Dry Adiabats")
fig.plot_moist_adiabats(linewidth=0.5, label="Moist Adiabats")
fig.plot_mixing_lines(linewidth=0.5, label="Mixing Ratio")
fig.plot_barbs(pres.astype('float64'), u.astype('float64'), v.astype('float64'))
I suspect there may be something that needs to be done in the process of reading the data to generate the nans properly.
I am just trying to fit a function which retrieves the correlation Pearson coefficient between two arrays. These two arrays are passed to the function as input parameters but they do not change. For the function, they should be interpreted as constants. I found an option for the parameters where it is possible to fix one parameter, i.e., it can not vary, but it works only for scalar values.
When I call Model.make_params(), the Model Class tries to check of these arrays are lower or grater than the minimum/maximum. This evaluation is not needed as they are constants.
My function:
def __lin_iteration2__(xref, yref_scaled, xobs, yobs, slope, offset, verbose=False, niter=None):
Acal = 1 + (offset + slope*xref)/xref
xr_new = xref * Acal
obs_interp1d = interp1d(xobs, yobs, kind='cubic')
yobs_new = scale_vector(obs_interp1d(xr_new))
rho = Pearson(yref_scaled, yobs_new)
return rho
Where xref, yref_scaled, xobs and yobs are arrays that do not change, i.e., constants. 'interp1d' is the interpolator operator coming from scipy.interpolate, 'scale_vector' scale a vector between -1 and 1, and 'Pearson' calculates the Pearson correlation coefficient.
Who I setup the Model class:
m = Model(corr.__lin_iteration3__)
par = m.make_params(yref_scaled = corr.yref_scaled, \
obs_interp1d=corr.obs_interp1d, offset=0, scale=0)
par['yref_scaled'].vary = False
par['obs_interp1d'].vary = False
r = m.fit
The error I got (just in the second line when I call the 'make_params' function of Model Class):
Traceback (most recent call last):
File "<ipython-input-3-c8f6550e831e>", line 1, in <module>
runfile('/home/andrey/Noveltis/tests/new_correl_sp/new_correl.py', wdir='/home/andrey/Noveltis/tests/new_correl_sp')
File "/usr/lib/python3/dist-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "/usr/lib/python3/dist-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/home/andrey/Noveltis/tests/new_correl_sp/new_correl.py", line 264, in <module>
obs_interp1d=corr.obs_interp1d, offset=0, scale=0)
File "/usr/lib/python3/dist-packages/lmfit/model.py", line 401, in make_params
params.add(par)
File "/usr/lib/python3/dist-packages/lmfit/parameter.py", line 338, in add
self.__setitem__(name.name, name)
File "/usr/lib/python3/dist-packages/lmfit/parameter.py", line 145, in __setitem__
self._asteval.symtable[key] = par.value
File "/usr/lib/python3/dist-packages/lmfit/parameter.py", line 801, in value
return self._getval()
File "/usr/lib/python3/dist-packages/lmfit/parameter.py", line 786, in _getval
if self._val > self.max:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In lmfit, arguments to the model function are expected to be scalar, floating point parameter values, except for "independent variables" which can be any python objects. By default, the first function argument is assumed to be an independent variable, as is any keyword argument with a non-numeric default value. But, you can specify which arguments are the independent variables (and there can be more than one) when creating your model.
I think what you want is:
m = Model(corr.__lin_iteration3__, independent_vars=['xref', 'yref_scaled', 'xobs', 'yobs'])
But also: You could also pass is any Python object, so you could pack your ref and obs data into other structures and do something like
def lin_iteration(Data, slope, offset, verbose=False, niter=None):
Acal = 1 + (offset + slope*Data['xref'])/Data['xref']
xr_new = Data['xref'] * Acal
# or maybe that would be clearer as just
# xr_new = offset + (1+slope)* Data['xref']
obs_interp1d = interp1d(Data['xobs'], Data['yobs'], kind='cubic')
yobs_new = scale_vector(obs_interp1d(xr_new))
rho = Pearson(Data['yref_scaled'], yobs_new)
return rho
and
m = Model(lin_iteration)
par = m.make_params(offset=0, scale=0)
Data = {'xref': xref, 'yref_scaled': yref_scaled, 'xobs': xobs, 'yobs': yobs}
result = m.fit(Data, params)
Of course, that's all untested but it might make your life easier...
import matplotlib.pyplot as plt
import numpy as np
import math
from scipy import *
from scipy.integrate import quad, dblquad, tplquad
q=range(1,6)
L=range(1,6)
sigmak=range(1,6)
x_lower = -3000
x_upper = 3000
y_lower = -3000
y_upper = 3000 #Integrate range
def final(a,b): #final(a,b)=0 to be plotted on a-b plane
m=a
n=b
def f3(x,y):
mass=0
for i in range(len(q)):
mass+=(L[i]*exp(-(x*x+y*y/(q[i]*q[i]))/(2*sigmak[i]*sigmak[i])))/(2*3.1415926*q[i]*sigmak[i]*sigmak[i])
return mass*(m-x)/((x-m)**2+(y-n)**2)
val=dblquad(f3,x_lower, x_upper, lambda x : y_lower, lambda x: y_upper)
return val[0]
y,x=np.ogrid[-1000:1000:200j,-1000:1000:200j]# plot range
f=final(x,y)
plt.figure(figsize=(9,4))
plt.subplot(121)
extent=[np.min(x),np.max(x),np.min(y),np.max(y)]
cs=plt.contour(f,extent=extent,levels=[0,0.1],colors=["b","r"],linestyles=["solid","dashed"],linewidths=[2,2])
plt.show()
Above is my codes. And I want to plot final(x,y)=0 in a plane. final(x,y) is a function which is a little complicated.When I run my code, it raises
Traceback (most recent call last):
File "test.py", line 25, in <module>
f=final(x,y)
File "test.py", line 22, in final
val=dblquad(f3,x_lower, x_upper, lambda x : y_lower, lambda x: y_upper)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/integrate/quadpack.py", line 433, in dblquad
return quad(_infunc,a,b,(func,gfun,hfun,args),epsabs=epsabs,epsrel=epsrel)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/integrate/quadpack.py", line 252, in quad
retval = _quad(func,a,b,args,full_output,epsabs,epsrel,limit,points)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/integrate/quadpack.py", line 317, in _quad
return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/integrate/quadpack.py", line 381, in _infunc
return quad(func,a,b,args=myargs)[0]
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/integrate/quadpack.py", line 252, in quad
retval = _quad(func,a,b,args,full_output,epsabs,epsrel,limit,points)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/integrate/quadpack.py", line 317, in _quad
return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
quadpack.error: Supplied function does not return a valid float.
So what's my problem? Thank you if anyone could help me!
Not sure what you are trying to do here
dblquad returns 2 floats, the resultant integral and an estimate of the error.
By making a for loop like below we can export an array but i don't think that's what you need
def final(a,b): #final(a,b)=0 to be plotted on a-b plane
outcome = []
for i in range(len(a)):
#print(i)
print(a[i])
m=a[i]
n=b[i]
def f3(x,y):
mass=0
for i in range(len(q)):
mass+=(L[i]*exp(-(x*x+y*y/(q[i]*q[i]))/(2*sigmak[i]*sigmak[i])))/(2*3.1415926*q[i]*sigmak[i]*sigmak[i])
return mass*(m-x)/((x-m)**2+(y-n)**2)
val=dblquad(f3,a[0], a[-1], lambda x : m, lambda x: a[-1])
outcome.append(val)
return np.array(outcome)
y=np.ogrid[-10:10:10j]
x=np.ogrid[-10:10:10j]
f=final(x,y)
Be more precise in what you are trying to achieve.
I want to use the function Hessiandiag from the package (Numdifftools) to get the diagonal elements of an Hessian matrix using the optimal parameters that minimizes a function.
Here's a simple example of the usage of Hessiandiag taken from developers website of Numdifftools:
import numpy as np
import numdifftools as nd
fun = lambda x : x[0] + x[1]**2 + x[2]**3
ddfun = lambda x : np.asarray((0, 2, 6*x[2]))
Hfun = nd.Hessdiag(fun)
hd = Hfun([1,2,3]) # HD = [ 0,2,18]
Say that my function that I want to get the Hessian matrix is too complex to be written using lambda. My function is stored in another file under the name Latent (using the def Latent(x1, x2, x3) command). I can't do the following:
from Latent import Latent # That's my function
import numpy as np
import numdifftools as nd
fun = lambda x1, x2, x3 : Latent(x1, x2, x3)
Hfun = nd.Hessdiag(fun)
hd = Hfun([np.array([1.2, 1.5, 2]), np.array(3.4, 5), 6]) # three parameters
...this doesn't work...
This is the error:
raise ValueError('%s must be scalar, one of [1 2 3 4].' % name)
ValueError: n must be scalar, one of [1 2 3 4].
How can I use nd.Hessdiag with my complex function without using lambda?
UPDATE
I have also tried this:
fun = lambda x: Latent(x[0], x[1], x[2])
Hfun = nd.Hessdiag(fun)
hd = Hfun([x1, x2, x3])
I get this error:
File "C:\Users\chamar.stu\AppData\Local\Continuum\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 601, in runfile
execfile(filename, namespace)
File "C:\Users\chamar.stu\AppData\Local\Continuum\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 66, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "F:/dropbox/Dropbox/Research/Fisher Martineau Sheng/SEC/codes/Python Latent Factor/V1/Main_v1.py", line 101, in <module>
hd = Hfun(np.array([est_param, allret_.T, n, capt, num_treat]))
File "C:\Users\chamar.stu\AppData\Local\Continuum\Anaconda\lib\site-packages\numdifftools\core.py", line 1161, in __call__
return self.hessdiag(x)
File "C:\Users\chamar.stu\AppData\Local\Continuum\Anaconda\lib\site-packages\numdifftools\core.py", line 1171, in hessdiag
dder, self.error_estimate, self.final_delta = self._partial_der(x)
File "C:\Users\chamar.stu\AppData\Local\Continuum\Anaconda\lib\site-packages\numdifftools\core.py", line 830, in _partial_der
self._x = np.asarray(x0, dtype=float)
File "C:\Users\chamar.stu\AppData\Local\Continuum\Anaconda\lib\site-packages\numpy\core\numeric.py", line 460, in asarray
return array(a, dtype, copy=False, order=order)
ValueError: setting an array element with a sequence.