how to pack my numpy variables and arrays when calling curve_fit? - python

This is my standalone code to reproduce the problem:
import numpy as np
from scipy.optimize import curve_fit
def find_vector_of_minor_axis_from_chunk(data):
n = 20 # number of points
time = np.linspace(0, 2 * np.pi, n)
guess_center_point = data.mean(1)
guess_center_point = guess_center_point[np.newaxis, :].transpose()
guess_a_phase = 0
guess_b_phase = 0
guess_a = 1
guess_b = 1
guess_a_axis_vector = np.array([[1], [0], [0]])
guess_b_axis_vector = np.array([[0], [1], [0]])
p0 = np.array([guess_center_point,
guess_a, guess_a_axis_vector, guess_a_phase,
guess_b, guess_b_axis_vector, guess_b_phase])
def ellipse_func(t, center_point, a, a_axis_vector, a_phase, b, b_axis_vector, b_phase):
return center_point + a * a_axis_vector * np.sin(t * a_phase) + b * b_axis_vector * np.sin(t + b_phase)
popt, pcov = curve_fit(ellipse_func, time, data, p0=p0)
center_point, a, a_axis_vector, a_phase, b, b_axis_vector, b_phase = popt
print(str(a_axis_vector, b_axis_vector))
shorter_vector = a_axis_vector
if np.abs(a_axis_vector) > np.aps(b_axis_vector):
shorter_vector = b_axis_vector
return shorter_vector
def main():
data = np.array([[-4.62767933, -4.6275775, -4.62735346, -4.62719652, -4.62711625, -4.62717975,
-4.62723845, -4.62722407, -4.62713901, -4.62708749, -4.62703238, -4.62689101,
-4.62687185, -4.62694013, -4.62701082, -4.62700483, -4.62697488, -4.62686825,
-4.62675683, -4.62675204],
[-1.58625998, -1.58625039, -1.58619648, -1.58617611, -1.58620606, -1.5861833,
-1.5861821, -1.58619169, -1.58615814, -1.58616893, -1.58613179, -1.58615934,
-1.58611262, -1.58610782, -1.58613179, -1.58614017, -1.58613059, -1.58612699,
-1.58607428, -1.58610183],
[-0.96714786, -0.96713827, -0.96715984, -0.96715145, -0.96716703, -0.96712869,
-0.96716104, -0.96713228, -0.96719698, -0.9671838, -0.96717062, -0.96717062,
-0.96715744, -0.96707717, -0.96709275, -0.96706519, -0.96715026, -0.96711791,
-0.96713588, -0.96714786]])
print(str(find_vector_of_minor_axis_from_chunk(data)))
if __name__ == '__main__':
main()
That gives me this traceback:
Traceback (most recent call last):
File "C:/Users/X/PycharmProjects/lissajous-achse/ellipse_fit.py", line 52, in <module>
main()
File "C:/Users/X/PycharmProjects/lissajous-achse/ellipse_fit.py", line 49, in main
print(str(find_vector_of_minor_axis_from_chunk(data)))
File "C:/Users/X/PycharmProjects/lissajous-achse/ellipse_fit.py", line 25, in find_vector_of_minor_axis_from_chunk
popt, pcov = curve_fit(ellipse_func, time, data, p0=p0)
File "C:\Users\X\PycharmProjects\lissajous-achse\venv\lib\site-packages\scipy\optimize\minpack.py", line 763, in curve_fit
res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
File "C:\Users\X\PycharmProjects\lissajous-achse\venv\lib\site-packages\scipy\optimize\minpack.py", line 392, in leastsq
raise TypeError('Improper input: N=%s must not exceed M=%s' % (n, m))
TypeError: Improper input: N=7 must not exceed M=3
Process finished with exit code 1
My code is an adaption of the second answer here. The problem causing the error message is solved by simple packing of variables here.
Why does the problem not surface in the mentioned second answer? And how can I pack my variables, which consist of several 3d vectors and individual scalars, to solve this problem? How do i pass in my t, which is a constant and should not be optimized?

Apparently python is quite smart regarding the length of the fields of the arguments, depending on the the initial guesses. So i could just pass in ONE variable, and split it up inside the function like so:
import numpy as np
from scipy.optimize import minimize
def find_vector_of_minor_axis_from_chunk(data):
n = 20 # number of points
guess_center_point = data.mean(1)
guess_center_point = guess_center_point[np.newaxis, :].transpose()
guess_a_phase = 0.0
guess_b_phase = 0.0
guess_a = 1.0
guess_b = 1.0
guess_a_axis_vector = np.array([[1.0], [0.0], [0.0]])
guess_b_axis_vector = np.array([[0.0], [1.0], [0.0]])
p0 = np.array([guess_center_point,
guess_a, guess_a_axis_vector, guess_a_phase,
guess_b, guess_b_axis_vector, guess_b_phase])
def ellipse_func(x, data):
center_point = x[0]
a = x[1]
a_axis_vector = x[2]
a_phase = x[3]
b = x[4]
b_axis_vector = x[5]
b_phase = x[6]
t = np.linspace(0, 2 * np.pi, n)
error = center_point + a * a_axis_vector * np.sin(t * a_phase) + b * b_axis_vector * np.sin(t + b_phase) - data
error_sum = np.sum(error**2)
print(str(error_sum))
return error_sum
popt, pcov = minimize(ellipse_func, p0, args=(data))
center_point, a, a_axis_vector, a_phase, b, b_axis_vector, b_phase = popt
print(str(a_axis_vector, b_axis_vector))
shorter_vector = a_axis_vector
if np.abs(a_axis_vector) > np.aps(b_axis_vector):
shorter_vector = b_axis_vector
return shorter_vector
def main():
data = np.array([[-4.62767933, -4.6275775, -4.62735346, -4.62719652, -4.62711625, -4.62717975,
-4.62723845, -4.62722407, -4.62713901, -4.62708749, -4.62703238, -4.62689101,
-4.62687185, -4.62694013, -4.62701082, -4.62700483, -4.62697488, -4.62686825,
-4.62675683, -4.62675204],
[-1.58625998, -1.58625039, -1.58619648, -1.58617611, -1.58620606, -1.5861833,
-1.5861821, -1.58619169, -1.58615814, -1.58616893, -1.58613179, -1.58615934,
-1.58611262, -1.58610782, -1.58613179, -1.58614017, -1.58613059, -1.58612699,
-1.58607428, -1.58610183],
[-0.96714786, -0.96713827, -0.96715984, -0.96715145, -0.96716703, -0.96712869,
-0.96716104, -0.96713228, -0.96719698, -0.9671838, -0.96717062, -0.96717062,
-0.96715744, -0.96707717, -0.96709275, -0.96706519, -0.96715026, -0.96711791,
-0.96713588, -0.96714786]])
print(str(find_vector_of_minor_axis_from_chunk(data)))
if __name__ == '__main__':
main()
Also i fixed some floating point vs integer errors in the vector for the initial values.
However now I get a different error:
Traceback (most recent call last):
File "C:/Users/X/PycharmProjects/lissajous-achse/ellipse_fit.py", line 61, in <module>
main()
File "C:/Users/X/PycharmProjects/lissajous-achse/ellipse_fit.py", line 58, in main
print(str(find_vector_of_minor_axis_from_chunk(data)))
File "C:/Users/X/PycharmProjects/lissajous-achse/ellipse_fit.py", line 34, in find_vector_of_minor_axis_from_chunk
popt, pcov = minimize(ellipse_func, p0, args=(data))
File "C:\Users\X\PycharmProjects\lissajous-achse\venv\lib\site-packages\scipy\optimize\_minimize.py", line 604, in minimize
return _minimize_bfgs(fun, x0, args, jac, callback, **options)
File "C:\Users\X\PycharmProjects\lissajous-achse\venv\lib\site-packages\scipy\optimize\optimize.py", line 1063, in _minimize_bfgs
if isinf(rhok): # this is patch for numpy
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I guess that
The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()
is some internal error, stemming from the internal decision matrix how to proceed. I don't know how I caused it and how to fix it. When i figure out how it is done properly, I will come back and edit this answer.

Related

TypeError: Can not understand

I am fitting a very simple curve having three points. with leastsq method, following all the rules. But still I am getting error. I cannot understand. Can anyone help. Thank you so much
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import leastsq
x = np.array([2.0,30.2,15.0])
y = np.array([45.0,56.2,30.0])
print(x)
print(y)
# model
def t(x,a,b,c):
return a*x**2 + b*x + c
#residual fucntion
def residual_t(x,y,a,b,c):
return y-t(x,a,b,c)
#initial parameters
g0 = np.array([0.0,0.0,0.0])
#leastsq method
coeffs, cov = leastsq(residual_t, g0, args=(x,y))
plt.plot(x,t(x,*coeffs),'r')
plt.plot(x,y,'b')
plt.show()
#finding out Rsquared and Radj squared value
absError = residual_t(y,x,*coeffs)
se = np.square(absError) # squared errors
Rsquared = 1.0 - (np.var(absError) / np.var(y))
n = len(x)
k = len(coeffs)
Radj_sq = (1-((1-Rsquared)/(n-1)))/(n-k-1)
print (f'Rsquared value: {Rsquared} adjusted R saquared value: {Radj_sq}')
TypeError: residual_t() missing 2 required positional arguments: 'b' and 'c'
Why??
coeffs is already a array containing best it values of a, b,c. coeffs is also showing undefined and residual_t is also showing problem. Could you please help me to understand.
With a copy-n-paste of your code (including the *coeffs change), I get
1135:~/mypy$ python3 stack58206395.py
[ 2. 30.2 15. ]
[45. 56.2 30. ]
Traceback (most recent call last):
File "stack58206395.py", line 24, in <module>
coeffs, cov = leastsq(residual_t, g0, args=(x,y))
File "/usr/local/lib/python3.6/dist-packages/scipy/optimize/minpack.py", line 383, in leastsq
shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)
File "/usr/local/lib/python3.6/dist-packages/scipy/optimize/minpack.py", line 26, in _check_func
res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
TypeError: residual_t() missing 2 required positional arguments: 'b' and 'c'
That is the error is in the use of residual_t within the leastsq call.
If I add
residual_t(g0, x, y)
right after the g0 definition I get the same error:
1136:~/mypy$ python3 stack58206395.py
[ 2. 30.2 15. ]
[45. 56.2 30. ]
Traceback (most recent call last):
File "stack58206395.py", line 23, in <module>
residual_t(g0, x, y)
TypeError: residual_t() missing 2 required positional arguments: 'b' and 'c'
So you need to define residual_t to work with a call like this. I'm not going to take a guess as to what you really want, so I'll leave the fix up to you.
Just remember that residual_t will be called with the x0, spliced with the args tuple. This is typical usage for scipy.optimize functions. Review the docs if necessary.
edit
Defining the function as:
def residual_t(abc, x, y):
a,b,c = abc
return y-t(x,a,b,c)
runs without error.

Troubles with solving differental equations in Python

I am trying to complete this, where I have to solve five ordinary
differential equations using odeint and reproduce figures given in that task.
Here is my code:
import scipy as sp
import scipy.interpolate as ip
import numpy as np
import matplotlib.pyplot as pl
d = 8.64
Mu1 = 4.95*10**2
Mu2 = 4.95*10**(-2)
vs = 0.12
vd = 1.23
w = 10**(-3)
k1 = 2.19*10**(-4)
k2 = 6.12*10**(-5)
k3 = 0.997148
k4 = 6.79*10**(-2)
p0 = 1.00
sigmas0 = 2.01
sigmad0 = 2.23
alphas0 = 2.20
alphad0 = 2.26
hs = (sigmas0-(sigmas0**(2)-k3*alphas0*(2*sigmas0-alphas0))**(1/2))/k3
cs = (alphas0-hs)/2
ps = k4*(hs**2)/cs
t_points = [ 1000, 1850, 1950, 1980, 2000, 2050, 2080, 2100, 2120, 2150, 2225, 2300, 2500, 5000 ]
y_points = [ 0.0, 0.0, 1.0, 4.0, 5.0, 8.0, 10.0, 10.5, 10.0, 8.0, 3.5, 2.0, 0.0, 0.0 ]
t1 = np.array(t_points)
y1 = np.array(y_points)
new_length = 1000
new_t = np.linspace(t1.min(), t1.max(), new_length)
new_y2 = ip.pchip_interpolate(t1, y1, new_t)
pl.plot(t_points,y_points,'o', new_t,new_y2)
pl.show()
ft = sp.interpolate.interp1d(new_t, new_y2)
def equations(x, t1):
p = x[0]
alphad = x[1]
alphas = x[2]
sigmad = x[3]
sigmas = x[4]
dpdt = (ps-p)/d + ft/Mu1
dalphaddt = (1/vd)*(k2-w*(alphad-alphas))
dalphasdt = (1/vs)*(w*(alphad-alphas)-k2)
dsigmaddt = (1/vd)*(k1-w*(sigmad-sigmas))
dsigmasdt = (1/vs)*(w*(sigmad-sigmas)-k1-(ps-p)/d*Mu2)
return [dpdt, dalphaddt, dalphasdt, dsigmaddt, dsigmasdt]
solve = sp.integrate.odeint(equations, [p0, alphad0, alphas0, sigmad0, sigmas0], t1)
It seems like this part:
dpdt = (ps-p)/d + ft/Mi1
is wrong and I have no idea how to solve it.
The error says:
TypeError: unsupported operand type(s) for /: 'interp1d' and 'float'.
Any ideas and advices are much appreciated.
EDIT: When I apply changes suggested by meowgoesthedog, I get error:
Traceback (most recent call last):
File "<ipython-input-5-324757833872>", line 1, in <module>
runfile('E:/Data/Project 2/project2.py', wdir='E:/Data/Project 2')
File "D:\Programs\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 668, in runfile
execfile(filename, namespace)
File "D:\Programs\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "E:/Data/Project 2/project2.py", line 59, in <module>
solve = odeint(equations, [p0, alphad0, alphas0, sigmad0, sigmas0], t1)
File "D:\Programs\Anaconda3\lib\site-packages\scipy\integrate\odepack.py", line 233, in odeint
int(bool(tfirst)))
File "E:/Data/Project 2/project2.py", line 51, in equations
dpdt = (ps-p)/d + ft(t1)/Mu1
File "D:\Programs\Anaconda3\lib\site-packages\scipy\interpolate\polyint.py", line 79, in __call__
y = self._evaluate(x)
File "D:\Programs\Anaconda3\lib\site-packages\scipy\interpolate\interpolate.py", line 664, in _evaluate
below_bounds, above_bounds = self._check_bounds(x_new)
File "D:\Programs\Anaconda3\lib\site-packages\scipy\interpolate\interpolate.py", line 696, in _check_bounds
raise ValueError("A value in x_new is above the interpolation "
ValueError: A value in x_new is above the interpolation range.
`
According to interp1d's documentation:
ynew = f(xnew) # use interpolation function returned by interp1d
It returns a function / callable object which takes a value x and returns the interpolated value of f(x). In your case "x" = t:
dpdt = (ps-p)/d + ft(t1)/Mu1 # pass t1 to ft to obtain interpolated value
UPDATE
This new error is due to odeint sampling the function f(t) at values of t beyond the last value of t_points. This is necessary for error correction and there is no option to prevent odeint from doing so. However, we can instead extrapolate f(t) beyond the supplied samples, using InterpolatedUnivariateSpline:
from scipy.interpolate import InterpolatedUnivariateSpline
...
ft = InterpolatedUnivariateSpline(t1, y1, k=1)
As with interp1d, this returns a function with the same signature. However, after applying this fix the result becomes:
Which is of course incorrect.
You have declared hs, cs, ps outside of the function as constants. In-fact they are functions of the alpha* and sigma* variables, so have to be evaluated during each call to equation:
def equations(x, t):
p = x[0]
alphad = x[1]
alphas = x[2]
sigmad = x[3]
sigmas = x[4]
hs = (sigmas-(sigmas**(2)-k3*alphas*(2*sigmas-alphas))**(1/2))/k3
cs = (alphas-hs)/2
ps = k4*(hs**2)/cs
dpdt = (ps-p)/d + ft(t)/Mu1
dalphaddt = (1/vd)*(k2-w*(alphad-alphas))
dalphasdt = (1/vs)*(w*(alphad-alphas)-k2)
dsigmaddt = (1/vd)*(k1-w*(sigmad-sigmas))
dsigmasdt = (1/vs)*(w*(sigmad-sigmas)-k1-(ps-p)/d*Mu2)
return [dpdt, dalphaddt, dalphasdt, dsigmaddt, dsigmasdt]
The result now matches the graph in the exercise... almost.
You passed t1 as the horizontal axis variable to odeint. It only has 14 elements which is too few for a smooth output. Pass new_t instead:
solve = ig.odeint(equations, [p0, alphad0, alphas0, sigmad0, sigmas0], new_t)
The result now exactly matches the expected one!

scipy.optimize.fmin error: setting an array element with a sequence

I tried to fit a sin-function by finding the parameter, which has lowest error-value.
Below is my code:
import numpy as np
import scipy.optimize as opt
from scipy.optimize import leastsq
import matplotlib.pyplot as plt
def func_model(x, para):
''' Model: y = a*sin(2*k*pi*x+theta)'''
a, k, theta = para
return a*np.sin(2*k*np.pi*x+theta)
def func_noise(x, para):
a, k, theta = para
return a*np.sin(2*k*np.pi*x+theta) + np.random.randn(100)
def func_error(para_guess):
'''error_func'''
error_sum = 0
x_seq = np.linspace(-2*np.pi, 0, 100)
para_fact = [10, 0.34, np.pi/6]
for x in x_seq:
error_value = (func_noise(x, para_fact)-func_model(x, para_guess))**2
error_sum = error_sum + error_value
return error_sum
para_guess_init = np.array([7, 0.2, 0])
solution = opt.fmin(func_error, para_guess_init)
print(solution)
But it doesn't work, and said the error: setting an array with a sequence
Traceback:
File "", line 26, in <module>
solution = opt.fmin(func_error, para_guess_init)
File "C:\Users\sun\AppData\Local\Continuum\anaconda3\lib\site-packages\scipy\optimize\optimize.py", line 408, in fmin
res = _minimize_neldermead(func, x0, args, callback=callback, **opts)
File "C:\Users\sun\AppData\Local\Continuum\anaconda3\lib\site-packages\scipy\optimize\optimize.py", line 532, in _minimize_neldermead
fsim[k] = func(sim[k])
ValueError: setting an array element with a sequence.
Can someone help me, thanks in advance
This minimizer expects a scalar function-evaluation to minimize.
Your function func_error returns a vector of size (100,).
Compare your line:
error_value = (func_noise(x, para_fact)-func_model(x, para_guess))**2
with for example:
error_value = np.sum(np.square(
func_noise(x, para_fact)-func_model(x, para_guess)))
although i would prefer (objective changes!):
error_value = np.linalg.norm(
func_noise(x, para_fact)-func_model(x, para_guess))

Scipy fmin_powell function

I'm trying to optimize the function eul with the initial guess X0 (X0 = [0.6421, -0.5046]) using fmin_powell. The function eul gets the initial conditions and calculates the velocity and temperature profile across a vertical flat plate using predictor-corrector method. I've displayed my code below:
def eul(X):
f2, q1 = X
N_tot = 5000;
n=np.linspace(0.0,10.0,N_tot)
f = np.zeros(N_tot,dtype=float).reshape(N_tot,)
dfdn = np.zeros(N_tot,dtype=float).reshape(N_tot,)
d2fdn2 = np.zeros(N_tot,dtype=float).reshape(N_tot,)
q = np.zeros(N_tot,dtype=float).reshape(N_tot,)
dqdn = np.zeros(N_tot,dtype=float).reshape(N_tot,)
Pr = 0.72; #Prandtl Number
##x0 = [d2fdn2_g1, dtdn_g1]
# Boundary Conditions
f[0] = 0.0;
dfdn[0] = 0.0;
d2fdn2[0] = f2;
q[0] = 1.0;
dqdn[0] = q1;
for i in np.arange(0,N_tot-1):
Dn = n[i+1] - n[i];
f_tmp=f[i]+dfdn[i]*Dn;
dfdn_tmp=dfdn[i]+d2fdn2[i]*Dn;
d2fdn2_tmp=d2fdn2[i]+(-3*f[i]*d2fdn2[i]+2*(dfdn[i])**2-q[i])*Dn;
q_tmp=q[i]+dqdn[i]*Dn;
dqdn_tmp=dqdn[i]-3*Pr*f[i]*dqdn[i]*Dn;
f[i+1]=f[i]+0.5*Dn*(dfdn[i]+dfdn_tmp);
dfdn[i+1]=dfdn[i]+0.5*Dn*(d2fdn2[i]+d2fdn2_tmp);
d2fdn2[i+1]=d2fdn2[i]+0.5*Dn*((-3*f[i]*d2fdn2[i]+2*(dfdn[i])**2-q[i])+(-3*f_tmp*d2fdn2_tmp+2*(dfdn_tmp)**2-q_tmp));
q[i+1]=q[i]+0.5*Dn*(dqdn[i]+dqdn_tmp);
dqdn[i+1]=dqdn[i]-0.5*Dn*((3*Pr*f[i]*dqdn[i])+(3*Pr*f_tmp*dqdn_tmp));
if((q[i+1]>1)|(q[i+1]<0)|(f[i+1]>2)|(f[i+1]<0)):
q[N_tot-1]=1+1/i;
dfdn[N_tot-1]=1+1/i;
break
return dfdn, q, n
MAIN PROGRAM
import numpy as np
import scipy as sp
import scipy.optimize
# Initial Guess
d2fdn2_g1 = 0.6421;
dtdn_g1 = -0.5046;
X0 = np.array([d2fdn2_g1, dtdn_g1])
X = scipy.optimize.fmin_powell(eul, X0)
I'm getting an error message:
Traceback (most recent call last):
File "C:\Users\labuser\Desktop\Sankar\New_Euler.py", line 52, in <module>
X = scipy.optimize.fmin_powell(eul, X0)
File "C:\Python27\lib\site-packages\scipy\optimize\optimize.py", line 1519, in fmin_powell
fval, x, direc1 = _linesearch_powell(func, x, direc1, tol=xtol*100)
File "C:\Python27\lib\site-packages\scipy\optimize\optimize.py", line 1418, in _linesearch_powell
alpha_min, fret, iter, num = brent(myfunc, full_output=1, tol=tol)
File "C:\Python27\lib\site-packages\scipy\optimize\optimize.py", line 1241, in brent
brent.optimize()
File "C:\Python27\lib\site-packages\scipy\optimize\optimize.py", line 1113, in optimize
xa,xb,xc,fa,fb,fc,funcalls = self.get_bracket_info()
File "C:\Python27\lib\site-packages\scipy\optimize\optimize.py", line 1089, in get_bracket_info
xa,xb,xc,fa,fb,fc,funcalls = bracket(func, args=args)
File "C:\Python27\lib\site-packages\scipy\optimize\optimize.py", line 1357, in bracket
if (fa < fb): # Switch so fa > fb
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
My guess is your function eul is returning an array. fmin_powell minimizes a scalar function. Check that eul returns a single value, not an array.
(Without seeing more code, the best we can do is guess. It would help if you added the definition of eul to the question.)
Instead of sending an array to fmin_powell just define another function that computes sum of the returned array, and use it.
# Initial Guess
d2fdn2_g1 = 0.6421;
dtdn_g1 = -0.5046;
def eeul(X):
return np.sum(eul(X))
X0 = np.array([d2fdn2_g1, dtdn_g1])
X = scipy.optimize.fmin_powell(eeul, X0)
This seems to work properly.

input/output error in scipy.optimize.fsolve

I seem to be getting an error when I use the root-finder in scipy. I was wondering if anyone could point out what I'm doing wrong.
The function I'm finding the root of is just an easy example, and not particularly important.
If I run this code with scipy 0.9.0:
import numpy as np
from scipy.optimize import fsolve
tmpFunc = lambda xIn: (xIn[0]-4)**2 + (xIn[1]-5)**2 + (xIn[2]-7)**3
x0 = [3,4,5]
xFinal = fsolve(tmpFunc, x0 )
print xFinal
I get the following error message:
Traceback (most recent call last):
File "tmpStack.py", line 7, in <module>
xFinal = fsolve(tmpFunc, x0 )
File "/usr/lib/python2.7/dist-packages/scipy/optimize/minpack.py", line 115, in fsolve
_check_func('fsolve', 'func', func, x0, args, n, (n,))
File "/usr/lib/python2.7/dist-packages/scipy/optimize/minpack.py", line 26, in _check_func
raise TypeError(msg)
TypeError: fsolve: there is a mismatch between the input and output shape of the 'func' argument '<lambda>'.
Well it looks like I was trying to use this routine incorrectly. This routine requires the same number of equations and variables vs. the one equation with three variables I gave it. So if the input to the function to be minimized is a 3-D array the output should be a 3-D array. This code works:
import numpy as np
from scipy.optimize import fsolve
tmpFunc = lambda xIn: np.array( [(xIn[0]-4)**2 + xIn[1], (xIn[1]-5)**2 - xIn[2]) \
, (xIn[2]-7)**3 + xIn[0] ] )
x0 = [3,4,5]
xFinal = fsolve(tmpFunc, x0 )
print xFinal
Which represents solving three equations simultaneously.

Categories