本文整理汇总了Python中scipy.optimize.root方法的典型用法代码示例。如果您正苦于以下问题:Python optimize.root方法的具体用法?Python optimize.root怎么用?Python optimize.root使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.optimize
的用法示例。
在下文中一共展示了optimize.root方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: find_first_best
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import root [as 别名]
def find_first_best(self):
'''
Find the first best allocation
'''
model = self.model
S, Θ, G = self.S, self.Θ, self.G
Uc, Un = model.Uc, model.Un
def res(z):
c = z[:S]
n = z[S:]
return np.hstack([Θ * Uc(c, n) + Un(c, n), Θ * n - c - G])
res = root(res, 0.5 * np.ones(2 * S))
if not res.success:
raise Exception('Could not find first best')
self.cFB = res.x[:S]
self.nFB = res.x[S:]
# Multiplier on the resource constraint
self.ΞFB = Uc(self.cFB, self.nFB)
self.zFB = np.hstack([self.cFB, self.nFB, self.ΞFB])
示例2: time0_allocation
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import root [as 别名]
def time0_allocation(self, B_, s_0):
'''
Finds the optimal allocation given initial government debt B_ and state s_0
'''
model, π, Θ, G, β = self.model, self.π, self.Θ, self.G, self.β
Uc, Ucc, Un, Unn = model.Uc, model.Ucc, model.Un, model.Unn
# First order conditions of planner's problem
def FOC(z):
μ, c, n, Ξ = z
xprime = self.time1_allocation(μ)[2]
return np.hstack([Uc(c, n) * (c - B_) + Un(c, n) * n + β * π[s_0] @ xprime,
Uc(c, n) - μ * (Ucc(c, n) *
(c - B_) + Uc(c, n)) - Ξ,
Un(c, n) - μ * (Unn(c, n) * n +
Un(c, n)) + Θ[s_0] * Ξ,
(Θ * n - c - G)[s_0]])
# Find root
res = root(FOC, np.array(
[0, self.cFB[s_0], self.nFB[s_0], self.ΞFB[s_0]]))
if not res.success:
raise Exception('Could not find time 0 LS allocation.')
return res.x
示例3: find_first_best
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import root [as 别名]
def find_first_best(self):
'''
Find the first best allocation
'''
Para = self.Para
S,Theta,Uc,Un,G = self.S,self.Theta,Para.Uc,Para.Un,self.G
def res(z):
c = z[:S]
n = z[S:]
return np.hstack(
[Theta*Uc(c,n)+Un(c,n), Theta*n - c - G]
)
res = root(res,0.5*np.ones(2*S))
if not res.success:
raise Exception('Could not find first best')
self.cFB = res.x[:S]
self.nFB = res.x[S:]
self.XiFB = Uc(self.cFB,self.nFB) #multiplier on the resource constraint.
self.zFB = np.hstack([self.cFB,self.nFB,self.XiFB])
示例4: find_first_best
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import root [as 别名]
def find_first_best(self):
'''
Find the first best allocation
'''
model = self.model
S, Θ, Uc, Un, G = self.S, self.Θ, model.Uc, model.Un, self.G
def res(z):
c = z[:S]
n = z[S:]
return np.hstack(
[Θ * Uc(c, n) + Un(c, n), Θ * n - c - G]
)
res = root(res, 0.5 * np.ones(2 * S))
if not res.success:
raise Exception('Could not find first best')
self.cFB = res.x[:S]
self.nFB = res.x[S:]
# multiplier on the resource constraint.
self.ΞFB = Uc(self.cFB, self.nFB)
self.zFB = np.hstack([self.cFB, self.nFB, self.ΞFB])
示例5: find_first_best
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import root [as 别名]
def find_first_best(self):
'''
Find the first best allocation
'''
Para = self.Para
S,Theta,Uc,Un,G = self.S,self.Theta,Para.Uc,Para.Un,self.G
def res(z):
c = z[:S]
n = z[S:]
return np.hstack(
[Theta*Uc(c,n)+Un(c,n), Theta*n - c - G]
)
res = root(res,0.5*np.ones(2*S))
if not res.success:
raise Exception('Could not find first best')
self.cFB = res.x[:S]
self.nFB = res.x[S:]
self.XiFB = Uc(self.cFB,self.nFB) #multiplier on the resource constraint.
self.zFB = np.hstack([self.cFB,self.nFB,self.XiFB])
示例6: time0_allocation
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import root [as 别名]
def time0_allocation(self,B_,s_0):
'''
Finds the optimal allocation given initial government debt B_ and state s_0
'''
Para,Pi,Theta,G,beta = self.Para,self.Pi,self.Theta,self.G,self.beta
Uc,Ucc,Un,Unn = Para.Uc,Para.Ucc,Para.Un,Para.Unn
#first order conditions of planner's problem
def FOC(z):
mu,c,n,Xi = z
xprime = self.time1_allocation(mu)[2]
return np.hstack([
Uc(c,n)*(c-B_) + Un(c,n)*n + beta*Pi[s_0].dot(xprime),
Uc(c,n) - mu*(Ucc(c,n)*(c-B_) + Uc(c,n)) - Xi,
Un(c,n) - mu*(Unn(c,n)*n+Un(c,n)) + Theta[s_0]*Xi,
(Theta*n - c - G)[s_0]
])
#find root
res = root(FOC,np.array([0.,self.cFB[s_0],self.nFB[s_0],self.XiFB[s_0]]))
if not res.success:
raise Exception('Could not find time 0 LS allocation.')
return res.x
示例7: test_f_size
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import root [as 别名]
def test_f_size(self):
# gh8320
# check that decreasing the size of the returned array raises an error
# and doesn't segfault
class fun(object):
def __init__(self):
self.count = 0
def __call__(self, x):
self.count += 1
if not (self.count % 5):
ret = x[0] + 0.5 * (x[0] - x[1]) ** 3 - 1.0
else:
ret = ([x[0] + 0.5 * (x[0] - x[1]) ** 3 - 1.0,
0.5 * (x[1] - x[0]) ** 3 + x[1]])
return ret
F = fun()
with assert_raises(ValueError):
sol = root(F, [0.1, 0.0], method='lm')
示例8: percentile_scale
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import root [as 别名]
def percentile_scale(self, per=0.9):
"""Calculate the percentile scale of the isotrope model.
This is the distance, where the given percentile of the variance
is reached by the variogram
"""
# check the given percentile
if not 0.0 < per < 1.0:
raise ValueError(
"percentile needs to be within (0, 1), got: " + str(per)
)
# define a curve, that has its root at the wanted point
def curve(x):
return 1.0 - self.correlation(x) - per
# take 'per * len_scale' as initial guess
return root(curve, per * self.len_scale)["x"][0]
###########################################################################
### spectrum methods (can be overridden for speedup) ######################
###########################################################################
示例9: _nodes_LGL_old
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import root [as 别名]
def _nodes_LGL_old(self, n):
"""Return Legendre-Gauss-Lobatto nodes.
Gauss-Lobatto nodes are roots of P'_{n-1}(x) and -1, 1.
ref. http://keisan.casio.jp/exec/system/1360718708
"""
x0 = np.zeros(0)
for i in range(2, n):
xi = (1-3.0*(n-2)/8.0/(n-1)**3)*np.cos((4.0*i-3)/(4.0*(n-1)+1)*np.pi)
x0 = np.append(x0, xi)
x0 = np.sort(x0)
roots = np.zeros(0)
for x in x0:
optResult = optimize.root(self._LegendreDerivative, x, args=(n-1,))
roots = np.append(roots, optResult.x)
nodes = np.hstack((-1, roots, 1))
return nodes
示例10: logistic_default_param
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import root [as 别名]
def logistic_default_param(x, y):
slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
A = min(y) if slope > 0 else max(y)
K = max(y) if slope > 0 else min(y)
if len(x) == 3:
if sum(y) == 0:
# if we have all zeros, the logistic should just return all zeros
A, K, M, B = 0, 0, 0, 0
else:
assert y[0] != y[1] != y[2], "x = {}, y = {}".format(x, y)
B0 = (10 / float(max(x) - min(x)))
B = optimize.root(TimeSeries._logistic_end_point_error, x0=B0, args=(A, K, x, y, slope))['x'][0]
M = TimeSeries._approx_M(A, K, B, x[1], y[1])
else:
B = 10 / float(max(x) - min(x))
M = min(x) + (max(x) - min(x)) / 2.
return A, K, M, B
示例11: _untransform_logistic
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import root [as 别名]
def _untransform_logistic(self, unconstrained, constrained):
"""
Function to allow using a numerical root-finder to reverse the
logistic transform.
"""
resid = np.zeros(unconstrained.shape, dtype=unconstrained.dtype)
exp = np.exp(unconstrained)
sum_exp = np.sum(exp)
for i in range(len(unconstrained)):
resid[i] = (unconstrained[i] -
np.log(1 + sum_exp - exp[i]) +
np.log(1 / constrained[i] - 1))
return resid
示例12: test_tol_parameter
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import root [as 别名]
def test_tol_parameter(self):
# Check that the minimize() tol= argument does something
def func(z):
x, y = z
return np.array([x**3 - 1, y**3 - 1])
def dfunc(z):
x, y = z
return np.array([[3*x**2, 0], [0, 3*y**2]])
for method in ['hybr', 'lm', 'broyden1', 'broyden2', 'anderson',
'diagbroyden', 'krylov']:
if method in ('linearmixing', 'excitingmixing'):
# doesn't converge
continue
if method in ('hybr', 'lm'):
jac = dfunc
else:
jac = None
sol1 = root(func, [1.1,1.1], jac=jac, tol=1e-4, method=method)
sol2 = root(func, [1.1,1.1], jac=jac, tol=0.5, method=method)
msg = "%s: %s vs. %s" % (method, func(sol1.x), func(sol2.x))
assert_(sol1.success, msg)
assert_(sol2.success, msg)
assert_(abs(func(sol1.x)).max() < abs(func(sol2.x)).max(),
msg)
示例13: _check_root
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import root [as 别名]
def _check_root(self, f, method, f_tol=1e-2):
res = root(f, f.xin, method=method,
options={'ftol': f_tol, 'maxiter': 200, 'disp': 0})
assert_(np.absolute(res.fun).max() < f_tol)
示例14: test_problem_root
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import root [as 别名]
def test_problem_root(self):
""" Tests for root """
for f in [F, F2, F3, F4_powell, F5, F6]:
for meth in SOLVERS:
if meth in f.KNOWN_BAD:
if meth in MUST_WORK:
yield self._check_func_fail, f, meth
continue
yield self._check_root, f, meth
示例15: test_root_broyden1
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import root [as 别名]
def test_root_broyden1(self):
res = root(F, F.xin, method='broyden1',
options={'nit': 12, 'jac_options': {'alpha': 1}})
assert_(nonlin.norm(res.x) < 1e-9)
assert_(nonlin.norm(res.fun) < 1e-9)