test_minpack.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  1. """
  2. Unit tests for optimization routines from minpack.py.
  3. """
  4. import warnings
  5. import pytest
  6. import threading
  7. from numpy.testing import (assert_, assert_almost_equal, assert_array_equal,
  8. assert_array_almost_equal, assert_allclose)
  9. from pytest import raises as assert_raises
  10. import numpy as np
  11. from numpy import array, float64
  12. from multiprocessing.pool import ThreadPool
  13. from scipy import optimize, linalg
  14. from scipy.special import lambertw
  15. from scipy.optimize._minpack_py import leastsq, curve_fit, fixed_point
  16. from scipy.optimize import OptimizeWarning
  17. from scipy.optimize._minimize import Bounds
  18. class ReturnShape:
  19. """This class exists to create a callable that does not have a '__name__' attribute.
  20. __init__ takes the argument 'shape', which should be a tuple of ints.
  21. When an instance is called with a single argument 'x', it returns numpy.ones(shape).
  22. """
  23. def __init__(self, shape):
  24. self.shape = shape
  25. def __call__(self, x):
  26. return np.ones(self.shape)
  27. def dummy_func(x, shape):
  28. """A function that returns an array of ones of the given shape.
  29. `x` is ignored.
  30. """
  31. return np.ones(shape)
  32. def sequence_parallel(fs):
  33. with ThreadPool(len(fs)) as pool:
  34. return pool.map(lambda f: f(), fs)
  35. # Function and Jacobian for tests of solvers for systems of nonlinear
  36. # equations
  37. def pressure_network(flow_rates, Qtot, k):
  38. """Evaluate non-linear equation system representing
  39. the pressures and flows in a system of n parallel pipes::
  40. f_i = P_i - P_0, for i = 1..n
  41. f_0 = sum(Q_i) - Qtot
  42. where Q_i is the flow rate in pipe i and P_i the pressure in that pipe.
  43. Pressure is modeled as a P=kQ**2 where k is a valve coefficient and
  44. Q is the flow rate.
  45. Parameters
  46. ----------
  47. flow_rates : float
  48. A 1-D array of n flow rates [kg/s].
  49. k : float
  50. A 1-D array of n valve coefficients [1/kg m].
  51. Qtot : float
  52. A scalar, the total input flow rate [kg/s].
  53. Returns
  54. -------
  55. F : float
  56. A 1-D array, F[i] == f_i.
  57. """
  58. P = k * flow_rates**2
  59. F = np.hstack((P[1:] - P[0], flow_rates.sum() - Qtot))
  60. return F
  61. def pressure_network_jacobian(flow_rates, Qtot, k):
  62. """Return the jacobian of the equation system F(flow_rates)
  63. computed by `pressure_network` with respect to
  64. *flow_rates*. See `pressure_network` for the detailed
  65. description of parameters.
  66. Returns
  67. -------
  68. jac : float
  69. *n* by *n* matrix ``df_i/dQ_i`` where ``n = len(flow_rates)``
  70. and *f_i* and *Q_i* are described in the doc for `pressure_network`
  71. """
  72. n = len(flow_rates)
  73. pdiff = np.diag(flow_rates[1:] * 2 * k[1:] - 2 * flow_rates[0] * k[0])
  74. jac = np.empty((n, n))
  75. jac[:n-1, :n-1] = pdiff * 0
  76. jac[:n-1, n-1] = 0
  77. jac[n-1, :] = np.ones(n)
  78. return jac
  79. def pressure_network_fun_and_grad(flow_rates, Qtot, k):
  80. return (pressure_network(flow_rates, Qtot, k),
  81. pressure_network_jacobian(flow_rates, Qtot, k))
  82. class TestFSolve:
  83. def test_pressure_network_no_gradient(self):
  84. # fsolve without gradient, equal pipes -> equal flows.
  85. k = np.full(4, 0.5)
  86. Qtot = 4
  87. initial_guess = array([2., 0., 2., 0.])
  88. final_flows, info, ier, mesg = optimize.fsolve(
  89. pressure_network, initial_guess, args=(Qtot, k),
  90. full_output=True)
  91. assert_array_almost_equal(final_flows, np.ones(4))
  92. assert_(ier == 1, mesg)
  93. def test_pressure_network_with_gradient(self):
  94. # fsolve with gradient, equal pipes -> equal flows
  95. k = np.full(4, 0.5)
  96. Qtot = 4
  97. initial_guess = array([2., 0., 2., 0.])
  98. final_flows = optimize.fsolve(
  99. pressure_network, initial_guess, args=(Qtot, k),
  100. fprime=pressure_network_jacobian)
  101. assert_array_almost_equal(final_flows, np.ones(4))
  102. def test_wrong_shape_func_callable(self):
  103. func = ReturnShape(1)
  104. # x0 is a list of two elements, but func will return an array with
  105. # length 1, so this should result in a TypeError.
  106. x0 = [1.5, 2.0]
  107. assert_raises(TypeError, optimize.fsolve, func, x0)
  108. def test_wrong_shape_func_function(self):
  109. # x0 is a list of two elements, but func will return an array with
  110. # length 1, so this should result in a TypeError.
  111. x0 = [1.5, 2.0]
  112. assert_raises(TypeError, optimize.fsolve, dummy_func, x0, args=((1,),))
  113. def test_wrong_shape_fprime_callable(self):
  114. func = ReturnShape(1)
  115. deriv_func = ReturnShape((2,2))
  116. assert_raises(TypeError, optimize.fsolve, func, x0=[0,1], fprime=deriv_func)
  117. def test_wrong_shape_fprime_function(self):
  118. def func(x):
  119. return dummy_func(x, (2,))
  120. def deriv_func(x):
  121. return dummy_func(x, (3, 3))
  122. assert_raises(TypeError, optimize.fsolve, func, x0=[0,1], fprime=deriv_func)
  123. def test_func_can_raise(self):
  124. def func(*args):
  125. raise ValueError('I raised')
  126. with assert_raises(ValueError, match='I raised'):
  127. optimize.fsolve(func, x0=[0])
  128. def test_Dfun_can_raise(self):
  129. def func(x):
  130. return x - np.array([10])
  131. def deriv_func(*args):
  132. raise ValueError('I raised')
  133. with assert_raises(ValueError, match='I raised'):
  134. optimize.fsolve(func, x0=[0], fprime=deriv_func)
  135. def test_float32(self):
  136. def func(x):
  137. return np.array([x[0] - 100, x[1] - 1000], dtype=np.float32) ** 2
  138. p = optimize.fsolve(func, np.array([1, 1], np.float32))
  139. assert_allclose(func(p), [0, 0], atol=1e-3)
  140. def test_reentrant_func(self):
  141. def func(*args):
  142. self.test_pressure_network_no_gradient()
  143. return pressure_network(*args)
  144. # fsolve without gradient, equal pipes -> equal flows.
  145. k = np.full(4, 0.5)
  146. Qtot = 4
  147. initial_guess = array([2., 0., 2., 0.])
  148. final_flows, info, ier, mesg = optimize.fsolve(
  149. func, initial_guess, args=(Qtot, k),
  150. full_output=True)
  151. assert_array_almost_equal(final_flows, np.ones(4))
  152. assert_(ier == 1, mesg)
  153. def test_reentrant_Dfunc(self):
  154. def deriv_func(*args):
  155. self.test_pressure_network_with_gradient()
  156. return pressure_network_jacobian(*args)
  157. # fsolve with gradient, equal pipes -> equal flows
  158. k = np.full(4, 0.5)
  159. Qtot = 4
  160. initial_guess = array([2., 0., 2., 0.])
  161. final_flows = optimize.fsolve(
  162. pressure_network, initial_guess, args=(Qtot, k),
  163. fprime=deriv_func)
  164. assert_array_almost_equal(final_flows, np.ones(4))
  165. def test_concurrent_no_gradient(self):
  166. v = sequence_parallel([self.test_pressure_network_no_gradient] * 10)
  167. assert all([result is None for result in v])
  168. def test_concurrent_with_gradient(self):
  169. v = sequence_parallel([self.test_pressure_network_with_gradient] * 10)
  170. assert all([result is None for result in v])
  171. class TestRootHybr:
  172. def test_pressure_network_no_gradient(self):
  173. # root/hybr without gradient, equal pipes -> equal flows
  174. k = np.full(4, 0.5)
  175. Qtot = 4
  176. initial_guess = array([2., 0., 2., 0.])
  177. final_flows = optimize.root(pressure_network, initial_guess,
  178. method='hybr', args=(Qtot, k)).x
  179. assert_array_almost_equal(final_flows, np.ones(4))
  180. def test_pressure_network_with_gradient(self):
  181. # root/hybr with gradient, equal pipes -> equal flows
  182. k = np.full(4, 0.5)
  183. Qtot = 4
  184. initial_guess = array([[2., 0., 2., 0.]])
  185. final_flows = optimize.root(pressure_network, initial_guess,
  186. args=(Qtot, k), method='hybr',
  187. jac=pressure_network_jacobian).x
  188. assert_array_almost_equal(final_flows, np.ones(4))
  189. def test_pressure_network_with_gradient_combined(self):
  190. # root/hybr with gradient and function combined, equal pipes -> equal
  191. # flows
  192. k = np.full(4, 0.5)
  193. Qtot = 4
  194. initial_guess = array([2., 0., 2., 0.])
  195. final_flows = optimize.root(pressure_network_fun_and_grad,
  196. initial_guess, args=(Qtot, k),
  197. method='hybr', jac=True).x
  198. assert_array_almost_equal(final_flows, np.ones(4))
  199. class TestRootLM:
  200. def test_pressure_network_no_gradient(self):
  201. # root/lm without gradient, equal pipes -> equal flows
  202. k = np.full(4, 0.5)
  203. Qtot = 4
  204. initial_guess = array([2., 0., 2., 0.])
  205. final_flows = optimize.root(pressure_network, initial_guess,
  206. method='lm', args=(Qtot, k)).x
  207. assert_array_almost_equal(final_flows, np.ones(4))
  208. class TestNfev:
  209. def setup_method(self):
  210. self.nfev = threading.local()
  211. def zero_f(self, y):
  212. if not hasattr(self.nfev, 'c'):
  213. self.nfev.c = 0
  214. self.nfev.c += 1
  215. return y**2-3
  216. @pytest.mark.parametrize('method', ['hybr', 'lm', 'broyden1',
  217. 'broyden2', 'anderson',
  218. 'linearmixing', 'diagbroyden',
  219. 'excitingmixing', 'krylov',
  220. 'df-sane'])
  221. def test_root_nfev(self, method):
  222. self.nfev.c = 0
  223. solution = optimize.root(self.zero_f, 100, method=method)
  224. assert solution.nfev == self.nfev.c
  225. def test_fsolve_nfev(self):
  226. self.nfev.c = 0
  227. x, info, ier, mesg = optimize.fsolve(self.zero_f, 100, full_output=True)
  228. assert info['nfev'] == self.nfev.c
  229. class TestLeastSq:
  230. def setup_method(self):
  231. x = np.linspace(0, 10, 40)
  232. a,b,c = 3.1, 42, -304.2
  233. self.x = x
  234. self.abc = a,b,c
  235. y_true = a*x**2 + b*x + c
  236. rng = np.random.default_rng(123)
  237. self.y_meas = y_true + 0.01*rng.standard_normal(y_true.shape)
  238. def residuals(self, p, y, x):
  239. a,b,c = p
  240. err = y-(a*x**2 + b*x + c)
  241. return err
  242. def residuals_jacobian(self, _p, _y, x):
  243. return -np.vstack([x**2, x, np.ones_like(x)]).T
  244. def test_basic(self):
  245. p0 = array([0,0,0])
  246. params_fit, ier = leastsq(self.residuals, p0,
  247. args=(self.y_meas, self.x))
  248. assert_(ier in (1, 2, 3, 4), f'solution not found (ier={ier})')
  249. # low precision due to random
  250. assert_array_almost_equal(params_fit, self.abc, decimal=2)
  251. def test_basic_with_gradient(self):
  252. p0 = array([0,0,0])
  253. params_fit, ier = leastsq(self.residuals, p0,
  254. args=(self.y_meas, self.x),
  255. Dfun=self.residuals_jacobian)
  256. assert_(ier in (1, 2, 3, 4), f'solution not found (ier={ier})')
  257. # low precision due to random
  258. assert_array_almost_equal(params_fit, self.abc, decimal=2)
  259. def test_full_output(self):
  260. p0 = array([[0,0,0]])
  261. full_output = leastsq(self.residuals, p0,
  262. args=(self.y_meas, self.x),
  263. full_output=True)
  264. params_fit, cov_x, infodict, mesg, ier = full_output
  265. assert_(ier in (1,2,3,4), f'solution not found: {mesg}')
  266. def test_input_untouched(self):
  267. p0 = array([0,0,0],dtype=float64)
  268. p0_copy = array(p0, copy=True)
  269. full_output = leastsq(self.residuals, p0,
  270. args=(self.y_meas, self.x),
  271. full_output=True)
  272. params_fit, cov_x, infodict, mesg, ier = full_output
  273. assert_(ier in (1,2,3,4), f'solution not found: {mesg}')
  274. assert_array_equal(p0, p0_copy)
  275. def test_wrong_shape_func_callable(self):
  276. func = ReturnShape(1)
  277. # x0 is a list of two elements, but func will return an array with
  278. # length 1, so this should result in a TypeError.
  279. x0 = [1.5, 2.0]
  280. assert_raises(TypeError, optimize.leastsq, func, x0)
  281. def test_wrong_shape_func_function(self):
  282. # x0 is a list of two elements, but func will return an array with
  283. # length 1, so this should result in a TypeError.
  284. x0 = [1.5, 2.0]
  285. assert_raises(TypeError, optimize.leastsq, dummy_func, x0, args=((1,),))
  286. def test_wrong_shape_Dfun_callable(self):
  287. func = ReturnShape(1)
  288. deriv_func = ReturnShape((2,2))
  289. assert_raises(TypeError, optimize.leastsq, func, x0=[0,1], Dfun=deriv_func)
  290. def test_wrong_shape_Dfun_function(self):
  291. def func(x):
  292. return dummy_func(x, (2,))
  293. def deriv_func(x):
  294. return dummy_func(x, (3, 3))
  295. assert_raises(TypeError, optimize.leastsq, func, x0=[0,1], Dfun=deriv_func)
  296. def test_float32(self):
  297. # Regression test for gh-1447
  298. def func(p,x,y):
  299. q = p[0]*np.exp(-(x-p[1])**2/(2.0*p[2]**2))+p[3]
  300. return q - y
  301. x = np.array([1.475,1.429,1.409,1.419,1.455,1.519,1.472, 1.368,1.286,
  302. 1.231], dtype=np.float32)
  303. y = np.array([0.0168,0.0193,0.0211,0.0202,0.0171,0.0151,0.0185,0.0258,
  304. 0.034,0.0396], dtype=np.float32)
  305. p0 = np.array([1.0,1.0,1.0,1.0])
  306. p1, success = optimize.leastsq(func, p0, args=(x,y))
  307. assert_(success in [1,2,3,4])
  308. assert_((func(p1,x,y)**2).sum() < 1e-4 * (func(p0,x,y)**2).sum())
  309. def test_func_can_raise(self):
  310. def func(*args):
  311. raise ValueError('I raised')
  312. with assert_raises(ValueError, match='I raised'):
  313. optimize.leastsq(func, x0=[0])
  314. def test_Dfun_can_raise(self):
  315. def func(x):
  316. return x - np.array([10])
  317. def deriv_func(*args):
  318. raise ValueError('I raised')
  319. with assert_raises(ValueError, match='I raised'):
  320. optimize.leastsq(func, x0=[0], Dfun=deriv_func)
  321. def test_reentrant_func(self):
  322. def func(*args):
  323. self.test_basic()
  324. return self.residuals(*args)
  325. p0 = array([0,0,0])
  326. params_fit, ier = leastsq(func, p0,
  327. args=(self.y_meas, self.x))
  328. assert_(ier in (1, 2, 3, 4), f'solution not found (ier={ier})')
  329. # low precision due to random
  330. assert_array_almost_equal(params_fit, self.abc, decimal=2)
  331. def test_reentrant_Dfun(self):
  332. def deriv_func(*args):
  333. self.test_basic()
  334. return self.residuals_jacobian(*args)
  335. p0 = array([0,0,0])
  336. params_fit, ier = leastsq(self.residuals, p0,
  337. args=(self.y_meas, self.x),
  338. Dfun=deriv_func)
  339. assert_(ier in (1, 2, 3, 4), f'solution not found (ier={ier})')
  340. # low precision due to random
  341. assert_array_almost_equal(params_fit, self.abc, decimal=2)
  342. def test_concurrent_no_gradient(self):
  343. v = sequence_parallel([self.test_basic] * 10)
  344. assert all([result is None for result in v])
  345. def test_concurrent_with_gradient(self):
  346. v = sequence_parallel([self.test_basic_with_gradient] * 10)
  347. assert all([result is None for result in v])
  348. def test_func_input_output_length_check(self):
  349. def func(x):
  350. return 2 * (x[0] - 3) ** 2 + 1
  351. with assert_raises(TypeError,
  352. match='Improper input: func input vector length N='):
  353. optimize.leastsq(func, x0=[0, 1])
  354. class TestCurveFit:
  355. def setup_method(self):
  356. self.y = array([1.0, 3.2, 9.5, 13.7])
  357. self.x = array([1.0, 2.0, 3.0, 4.0])
  358. def test_one_argument(self):
  359. def func(x,a):
  360. return x**a
  361. popt, pcov = curve_fit(func, self.x, self.y)
  362. assert_(len(popt) == 1)
  363. assert_(pcov.shape == (1,1))
  364. assert_almost_equal(popt[0], 1.9149, decimal=4)
  365. assert_almost_equal(pcov[0,0], 0.0016, decimal=4)
  366. # Test if we get the same with full_output. Regression test for #1415.
  367. # Also test if check_finite can be turned off.
  368. res = curve_fit(func, self.x, self.y,
  369. full_output=1, check_finite=False)
  370. (popt2, pcov2, infodict, errmsg, ier) = res
  371. assert_array_almost_equal(popt, popt2)
  372. def test_two_argument(self):
  373. def func(x, a, b):
  374. return b*x**a
  375. popt, pcov = curve_fit(func, self.x, self.y)
  376. assert_(len(popt) == 2)
  377. assert_(pcov.shape == (2,2))
  378. assert_array_almost_equal(popt, [1.7989, 1.1642], decimal=4)
  379. assert_array_almost_equal(pcov, [[0.0852, -0.1260], [-0.1260, 0.1912]],
  380. decimal=4)
  381. def test_func_is_classmethod(self):
  382. class test_self:
  383. """This class tests if curve_fit passes the correct number of
  384. arguments when the model function is a class instance method.
  385. """
  386. def func(self, x, a, b):
  387. return b * x**a
  388. test_self_inst = test_self()
  389. popt, pcov = curve_fit(test_self_inst.func, self.x, self.y)
  390. assert_(pcov.shape == (2,2))
  391. assert_array_almost_equal(popt, [1.7989, 1.1642], decimal=4)
  392. assert_array_almost_equal(pcov, [[0.0852, -0.1260], [-0.1260, 0.1912]],
  393. decimal=4)
  394. def test_regression_2639(self):
  395. # This test fails if epsfcn in leastsq is too large.
  396. x = [574.14200000000005, 574.154, 574.16499999999996,
  397. 574.17700000000002, 574.18799999999999, 574.19899999999996,
  398. 574.21100000000001, 574.22199999999998, 574.23400000000004,
  399. 574.245]
  400. y = [859.0, 997.0, 1699.0, 2604.0, 2013.0, 1964.0, 2435.0,
  401. 1550.0, 949.0, 841.0]
  402. guess = [574.1861428571428, 574.2155714285715, 1302.0, 1302.0,
  403. 0.0035019999999983615, 859.0]
  404. good = [5.74177150e+02, 5.74209188e+02, 1.74187044e+03, 1.58646166e+03,
  405. 1.0068462e-02, 8.57450661e+02]
  406. def f_double_gauss(x, x0, x1, A0, A1, sigma, c):
  407. return (A0*np.exp(-(x-x0)**2/(2.*sigma**2))
  408. + A1*np.exp(-(x-x1)**2/(2.*sigma**2)) + c)
  409. popt, pcov = curve_fit(f_double_gauss, x, y, guess, maxfev=10000)
  410. assert_allclose(popt, good, rtol=1e-5)
  411. def test_pcov(self):
  412. xdata = np.array([0, 1, 2, 3, 4, 5])
  413. ydata = np.array([1, 1, 5, 7, 8, 12])
  414. sigma = np.array([1, 2, 1, 2, 1, 2])
  415. def f(x, a, b):
  416. return a*x + b
  417. for method in ['lm', 'trf', 'dogbox']:
  418. popt, pcov = curve_fit(f, xdata, ydata, p0=[2, 0], sigma=sigma,
  419. method=method)
  420. perr_scaled = np.sqrt(np.diag(pcov))
  421. assert_allclose(perr_scaled, [0.20659803, 0.57204404], rtol=1e-3)
  422. popt, pcov = curve_fit(f, xdata, ydata, p0=[2, 0], sigma=3*sigma,
  423. method=method)
  424. perr_scaled = np.sqrt(np.diag(pcov))
  425. assert_allclose(perr_scaled, [0.20659803, 0.57204404], rtol=1e-3)
  426. popt, pcov = curve_fit(f, xdata, ydata, p0=[2, 0], sigma=sigma,
  427. absolute_sigma=True, method=method)
  428. perr = np.sqrt(np.diag(pcov))
  429. assert_allclose(perr, [0.30714756, 0.85045308], rtol=1e-3)
  430. popt, pcov = curve_fit(f, xdata, ydata, p0=[2, 0], sigma=3*sigma,
  431. absolute_sigma=True, method=method)
  432. perr = np.sqrt(np.diag(pcov))
  433. assert_allclose(perr, [3*0.30714756, 3*0.85045308], rtol=1e-3)
  434. # infinite variances
  435. def f_flat(x, a, b):
  436. return a*x
  437. pcov_expected = np.array([np.inf]*4).reshape(2, 2)
  438. with warnings.catch_warnings():
  439. warnings.filterwarnings(
  440. "ignore",
  441. "Covariance of the parameters could not be estimated",
  442. OptimizeWarning)
  443. popt, pcov = curve_fit(f_flat, xdata, ydata, p0=[2, 0], sigma=sigma)
  444. popt1, pcov1 = curve_fit(f, xdata[:2], ydata[:2], p0=[2, 0])
  445. assert_(pcov.shape == (2, 2))
  446. assert_array_equal(pcov, pcov_expected)
  447. assert_(pcov1.shape == (2, 2))
  448. assert_array_equal(pcov1, pcov_expected)
  449. def test_array_like(self):
  450. # Test sequence input. Regression test for gh-3037.
  451. def f_linear(x, a, b):
  452. return a*x + b
  453. x = [1, 2, 3, 4]
  454. y = [3, 5, 7, 9]
  455. assert_allclose(curve_fit(f_linear, x, y)[0], [2, 1], atol=1e-10)
  456. def test_indeterminate_covariance(self):
  457. # Test that a warning is returned when pcov is indeterminate
  458. xdata = np.array([1, 2, 3, 4, 5, 6])
  459. ydata = np.array([1, 2, 3, 4, 5.5, 6])
  460. with pytest.warns(OptimizeWarning):
  461. curve_fit(lambda x, a, b: a*x, xdata, ydata)
  462. def test_NaN_handling(self):
  463. # Test for correct handling of NaNs in input data: gh-3422
  464. # create input with NaNs
  465. xdata = np.array([1, np.nan, 3])
  466. ydata = np.array([1, 2, 3])
  467. assert_raises(ValueError, curve_fit,
  468. lambda x, a, b: a*x + b, xdata, ydata)
  469. assert_raises(ValueError, curve_fit,
  470. lambda x, a, b: a*x + b, ydata, xdata)
  471. assert_raises(ValueError, curve_fit, lambda x, a, b: a*x + b,
  472. xdata, ydata, **{"check_finite": True})
  473. @staticmethod
  474. def _check_nan_policy(f, xdata_with_nan, xdata_without_nan,
  475. ydata_with_nan, ydata_without_nan, method):
  476. kwargs = {'f': f, 'xdata': xdata_with_nan, 'ydata': ydata_with_nan,
  477. 'method': method, 'check_finite': False}
  478. # propagate test
  479. error_msg = ("`nan_policy='propagate'` is not supported "
  480. "by this function.")
  481. with assert_raises(ValueError, match=error_msg):
  482. curve_fit(**kwargs, nan_policy="propagate", maxfev=2000)
  483. # raise test
  484. with assert_raises(ValueError, match="The input contains nan"):
  485. curve_fit(**kwargs, nan_policy="raise")
  486. # omit test
  487. result_with_nan, _ = curve_fit(**kwargs, nan_policy="omit")
  488. kwargs['xdata'] = xdata_without_nan
  489. kwargs['ydata'] = ydata_without_nan
  490. result_without_nan, _ = curve_fit(**kwargs)
  491. assert_allclose(result_with_nan, result_without_nan)
  492. # not valid policy test
  493. # check for argument names in any order
  494. error_msg = (r"nan_policy must be one of \{(?:'raise'|'omit'|None)"
  495. r"(?:, ?(?:'raise'|'omit'|None))*\}")
  496. with assert_raises(ValueError, match=error_msg):
  497. curve_fit(**kwargs, nan_policy="hi")
  498. @pytest.mark.parametrize('method', ["lm", "trf", "dogbox"])
  499. def test_nan_policy_1d(self, method):
  500. def f(x, a, b):
  501. return a*x + b
  502. xdata_with_nan = np.array([2, 3, np.nan, 4, 4, np.nan])
  503. ydata_with_nan = np.array([1, 2, 5, 3, np.nan, 7])
  504. xdata_without_nan = np.array([2, 3, 4])
  505. ydata_without_nan = np.array([1, 2, 3])
  506. self._check_nan_policy(f, xdata_with_nan, xdata_without_nan,
  507. ydata_with_nan, ydata_without_nan, method)
  508. @pytest.mark.parametrize('method', ["lm", "trf", "dogbox"])
  509. def test_nan_policy_2d(self, method):
  510. def f(x, a, b):
  511. x1 = x[0, :]
  512. x2 = x[1, :]
  513. return a*x1 + b + x2
  514. xdata_with_nan = np.array([[2, 3, np.nan, 4, 4, np.nan, 5],
  515. [2, 3, np.nan, np.nan, 4, np.nan, 7]])
  516. ydata_with_nan = np.array([1, 2, 5, 3, np.nan, 7, 10])
  517. xdata_without_nan = np.array([[2, 3, 5], [2, 3, 7]])
  518. ydata_without_nan = np.array([1, 2, 10])
  519. self._check_nan_policy(f, xdata_with_nan, xdata_without_nan,
  520. ydata_with_nan, ydata_without_nan, method)
  521. @pytest.mark.parametrize('n', [2, 3])
  522. @pytest.mark.parametrize('method', ["lm", "trf", "dogbox"])
  523. def test_nan_policy_2_3d(self, n, method):
  524. def f(x, a, b):
  525. x1 = x[..., 0, :].squeeze()
  526. x2 = x[..., 1, :].squeeze()
  527. return a*x1 + b + x2
  528. xdata_with_nan = np.array([[[2, 3, np.nan, 4, 4, np.nan, 5],
  529. [2, 3, np.nan, np.nan, 4, np.nan, 7]]])
  530. xdata_with_nan = xdata_with_nan.squeeze() if n == 2 else xdata_with_nan
  531. ydata_with_nan = np.array([1, 2, 5, 3, np.nan, 7, 10])
  532. xdata_without_nan = np.array([[[2, 3, 5], [2, 3, 7]]])
  533. ydata_without_nan = np.array([1, 2, 10])
  534. self._check_nan_policy(f, xdata_with_nan, xdata_without_nan,
  535. ydata_with_nan, ydata_without_nan, method)
  536. def test_empty_inputs(self):
  537. # Test both with and without bounds (regression test for gh-9864)
  538. assert_raises(ValueError, curve_fit, lambda x, a: a*x, [], [])
  539. assert_raises(ValueError, curve_fit, lambda x, a: a*x, [], [],
  540. bounds=(1, 2))
  541. assert_raises(ValueError, curve_fit, lambda x, a: a*x, [1], [])
  542. assert_raises(ValueError, curve_fit, lambda x, a: a*x, [2], [],
  543. bounds=(1, 2))
  544. def test_function_zero_params(self):
  545. # Fit args is zero, so "Unable to determine number of fit parameters."
  546. assert_raises(ValueError, curve_fit, lambda x: x, [1, 2], [3, 4])
  547. def test_None_x(self): # Added in GH10196
  548. popt, pcov = curve_fit(lambda _, a: a * np.arange(10),
  549. None, 2 * np.arange(10))
  550. assert_allclose(popt, [2.])
  551. def test_method_argument(self):
  552. def f(x, a, b):
  553. return a * np.exp(-b*x)
  554. xdata = np.linspace(0, 1, 11)
  555. ydata = f(xdata, 2., 2.)
  556. for method in ['trf', 'dogbox', 'lm', None]:
  557. popt, pcov = curve_fit(f, xdata, ydata, method=method)
  558. assert_allclose(popt, [2., 2.])
  559. assert_raises(ValueError, curve_fit, f, xdata, ydata, method='unknown')
  560. def test_full_output(self):
  561. def f(x, a, b):
  562. return a * np.exp(-b * x)
  563. xdata = np.linspace(0, 1, 11)
  564. ydata = f(xdata, 2., 2.)
  565. for method in ['trf', 'dogbox', 'lm', None]:
  566. popt, pcov, infodict, errmsg, ier = curve_fit(
  567. f, xdata, ydata, method=method, full_output=True)
  568. assert_allclose(popt, [2., 2.])
  569. assert "nfev" in infodict
  570. assert "fvec" in infodict
  571. if method == 'lm' or method is None:
  572. assert "fjac" in infodict
  573. assert "ipvt" in infodict
  574. assert "qtf" in infodict
  575. assert isinstance(errmsg, str)
  576. assert ier in (1, 2, 3, 4)
  577. def test_bounds(self):
  578. def f(x, a, b):
  579. return a * np.exp(-b*x)
  580. xdata = np.linspace(0, 1, 11)
  581. ydata = f(xdata, 2., 2.)
  582. # The minimum w/out bounds is at [2., 2.],
  583. # and with bounds it's at [1.5, smth].
  584. lb = [1., 0]
  585. ub = [1.5, 3.]
  586. # Test that both variants of the bounds yield the same result
  587. bounds = (lb, ub)
  588. bounds_class = Bounds(lb, ub)
  589. for method in [None, 'trf', 'dogbox']:
  590. popt, pcov = curve_fit(f, xdata, ydata, bounds=bounds,
  591. method=method)
  592. assert_allclose(popt[0], 1.5)
  593. popt_class, pcov_class = curve_fit(f, xdata, ydata,
  594. bounds=bounds_class,
  595. method=method)
  596. assert_allclose(popt_class, popt)
  597. # With bounds, the starting estimate is feasible.
  598. popt, pcov = curve_fit(f, xdata, ydata, method='trf',
  599. bounds=([0., 0], [0.6, np.inf]))
  600. assert_allclose(popt[0], 0.6)
  601. # method='lm' doesn't support bounds.
  602. assert_raises(ValueError, curve_fit, f, xdata, ydata, bounds=bounds,
  603. method='lm')
  604. def test_bounds_p0(self):
  605. # This test is for issue #5719. The problem was that an initial guess
  606. # was ignored when 'trf' or 'dogbox' methods were invoked.
  607. def f(x, a):
  608. return np.sin(x + a)
  609. xdata = np.linspace(-2*np.pi, 2*np.pi, 40)
  610. ydata = np.sin(xdata)
  611. bounds = (-3 * np.pi, 3 * np.pi)
  612. for method in ['trf', 'dogbox']:
  613. popt_1, _ = curve_fit(f, xdata, ydata, p0=2.1*np.pi)
  614. popt_2, _ = curve_fit(f, xdata, ydata, p0=2.1*np.pi,
  615. bounds=bounds, method=method)
  616. # If the initial guess is ignored, then popt_2 would be close 0.
  617. assert_allclose(popt_1, popt_2)
  618. def test_jac(self):
  619. # Test that Jacobian callable is handled correctly and
  620. # weighted if sigma is provided.
  621. def f(x, a, b):
  622. return a * np.exp(-b*x)
  623. def jac(x, a, b):
  624. e = np.exp(-b*x)
  625. return np.vstack((e, -a * x * e)).T
  626. xdata = np.linspace(0, 1, 11)
  627. ydata = f(xdata, 2., 2.)
  628. # Test numerical options for least_squares backend.
  629. for method in ['trf', 'dogbox']:
  630. for scheme in ['2-point', '3-point', 'cs']:
  631. popt, pcov = curve_fit(f, xdata, ydata, jac=scheme,
  632. method=method)
  633. assert_allclose(popt, [2, 2])
  634. # Test the analytic option.
  635. for method in ['lm', 'trf', 'dogbox']:
  636. popt, pcov = curve_fit(f, xdata, ydata, method=method, jac=jac)
  637. assert_allclose(popt, [2, 2])
  638. # Now add an outlier and provide sigma.
  639. ydata[5] = 100
  640. sigma = np.ones(xdata.shape[0])
  641. sigma[5] = 200
  642. for method in ['lm', 'trf', 'dogbox']:
  643. popt, pcov = curve_fit(f, xdata, ydata, sigma=sigma, method=method,
  644. jac=jac)
  645. # Still the optimization process is influenced somehow,
  646. # have to set rtol=1e-3.
  647. assert_allclose(popt, [2, 2], rtol=1e-3)
  648. def test_maxfev_and_bounds(self):
  649. # gh-6340: with no bounds, curve_fit accepts parameter maxfev (via leastsq)
  650. # but with bounds, the parameter is `max_nfev` (via least_squares)
  651. x = np.arange(0, 10)
  652. y = 2*x
  653. popt1, _ = curve_fit(lambda x,p: p*x, x, y, bounds=(0, 3), maxfev=100)
  654. popt2, _ = curve_fit(lambda x,p: p*x, x, y, bounds=(0, 3), max_nfev=100)
  655. assert_allclose(popt1, 2, atol=1e-14)
  656. assert_allclose(popt2, 2, atol=1e-14)
  657. @pytest.mark.parametrize("sigma_dim", [0, 1, 2])
  658. def test_curvefit_omitnan(self, sigma_dim):
  659. def exponential(x, a, b):
  660. return b * np.exp(a * x)
  661. rng = np.random.default_rng(578285731148908)
  662. N = 100
  663. x = np.linspace(1, 10, N)
  664. y = exponential(x, 0.2, 0.5)
  665. if (sigma_dim == 0):
  666. sigma = 0.05
  667. y += rng.normal(0, sigma, N)
  668. elif (sigma_dim == 1):
  669. sigma = x * 0.05
  670. y += rng.normal(0, sigma, N)
  671. elif (sigma_dim == 2):
  672. # The covariance matrix must be symmetric positive-semidefinite
  673. a = rng.normal(0, 2, (N, N))
  674. sigma = a @ a.T
  675. y += rng.multivariate_normal(np.zeros_like(x), sigma)
  676. else:
  677. assert False, "The sigma must be a scalar, 1D array or 2D array."
  678. p0 = [0.1, 1.0]
  679. # Choose indices to place NaNs.
  680. i_x = rng.integers(N, size=5)
  681. i_y = rng.integers(N, size=5)
  682. # Add NaNs and compute result using `curve_fit`
  683. x[i_x] = np.nan
  684. y[i_y] = np.nan
  685. res_opt, res_cov = curve_fit(exponential, x, y, p0=p0, sigma=sigma,
  686. nan_policy="omit")
  687. # Manually remove elements that should be eliminated, and
  688. # calculate reference using `curve_fit`
  689. i_delete = np.unique(np.concatenate((i_x, i_y)))
  690. x = np.delete(x, i_delete, axis=0)
  691. y = np.delete(y, i_delete, axis=0)
  692. sigma = np.asarray(sigma)
  693. if sigma.ndim == 1:
  694. sigma = np.delete(sigma, i_delete)
  695. elif sigma.ndim == 2:
  696. sigma = np.delete(sigma, i_delete, axis=0)
  697. sigma = np.delete(sigma, i_delete, axis=1)
  698. ref_opt, ref_cov = curve_fit(exponential, x, y, p0=p0, sigma=sigma)
  699. assert_allclose(res_opt, ref_opt, atol=1e-14)
  700. assert_allclose(res_cov, ref_cov, atol=1e-14)
  701. def test_curvefit_simplecovariance(self):
  702. def func(x, a, b):
  703. return a * np.exp(-b*x)
  704. def jac(x, a, b):
  705. e = np.exp(-b*x)
  706. return np.vstack((e, -a * x * e)).T
  707. rng = np.random.default_rng(123)
  708. xdata = np.linspace(0, 4, 50)
  709. y = func(xdata, 2.5, 1.3)
  710. ydata = y + 0.2 * rng.standard_normal(size=len(xdata))
  711. sigma = np.zeros(len(xdata)) + 0.2
  712. covar = np.diag(sigma**2)
  713. for jac1, jac2 in [(jac, jac), (None, None)]:
  714. for absolute_sigma in [False, True]:
  715. popt1, pcov1 = curve_fit(func, xdata, ydata, sigma=sigma,
  716. jac=jac1, absolute_sigma=absolute_sigma)
  717. popt2, pcov2 = curve_fit(func, xdata, ydata, sigma=covar,
  718. jac=jac2, absolute_sigma=absolute_sigma)
  719. assert_allclose(popt1, popt2, atol=1e-14)
  720. assert_allclose(pcov1, pcov2, atol=1e-14)
  721. def test_curvefit_covariance(self):
  722. def funcp(x, a, b):
  723. rotn = np.array([[1./np.sqrt(2), -1./np.sqrt(2), 0],
  724. [1./np.sqrt(2), 1./np.sqrt(2), 0],
  725. [0, 0, 1.0]])
  726. return rotn.dot(a * np.exp(-b*x))
  727. def jacp(x, a, b):
  728. rotn = np.array([[1./np.sqrt(2), -1./np.sqrt(2), 0],
  729. [1./np.sqrt(2), 1./np.sqrt(2), 0],
  730. [0, 0, 1.0]])
  731. e = np.exp(-b*x)
  732. return rotn.dot(np.vstack((e, -a * x * e)).T)
  733. def func(x, a, b):
  734. return a * np.exp(-b*x)
  735. def jac(x, a, b):
  736. e = np.exp(-b*x)
  737. return np.vstack((e, -a * x * e)).T
  738. rng = np.random.default_rng(1234)
  739. xdata = np.arange(1, 4)
  740. y = func(xdata, 2.5, 1.0)
  741. ydata = y + 0.2 * rng.standard_normal(size=len(xdata))
  742. sigma = np.zeros(len(xdata)) + 0.2
  743. covar = np.diag(sigma**2)
  744. # Get a rotation matrix, and obtain ydatap = R ydata
  745. # Chisq = ydata^T C^{-1} ydata
  746. # = ydata^T R^T R C^{-1} R^T R ydata
  747. # = ydatap^T Cp^{-1} ydatap
  748. # Cp^{-1} = R C^{-1} R^T
  749. # Cp = R C R^T, since R^-1 = R^T
  750. rotn = np.array([[1./np.sqrt(2), -1./np.sqrt(2), 0],
  751. [1./np.sqrt(2), 1./np.sqrt(2), 0],
  752. [0, 0, 1.0]])
  753. ydatap = rotn.dot(ydata)
  754. covarp = rotn.dot(covar).dot(rotn.T)
  755. for jac1, jac2 in [(jac, jacp), (None, None)]:
  756. for absolute_sigma in [False, True]:
  757. popt1, pcov1 = curve_fit(func, xdata, ydata, sigma=sigma,
  758. jac=jac1, absolute_sigma=absolute_sigma)
  759. popt2, pcov2 = curve_fit(funcp, xdata, ydatap, sigma=covarp,
  760. jac=jac2, absolute_sigma=absolute_sigma)
  761. assert_allclose(popt1, popt2, rtol=1.4e-7, atol=1e-14)
  762. assert_allclose(pcov1, pcov2, rtol=1.4e-7, atol=1e-14)
  763. @pytest.mark.parametrize("absolute_sigma", [False, True])
  764. def test_curvefit_scalar_sigma(self, absolute_sigma):
  765. def func(x, a, b):
  766. return a * x + b
  767. x, y = self.x, self.y
  768. _, pcov1 = curve_fit(func, x, y, sigma=2, absolute_sigma=absolute_sigma)
  769. # Explicitly building the sigma 1D array
  770. _, pcov2 = curve_fit(
  771. func, x, y, sigma=np.full_like(y, 2), absolute_sigma=absolute_sigma
  772. )
  773. assert np.all(pcov1 == pcov2)
  774. def test_dtypes(self):
  775. # regression test for gh-9581: curve_fit fails if x and y dtypes differ
  776. x = np.arange(-3, 5)
  777. y = 1.5*x + 3.0 + 0.5*np.sin(x)
  778. def func(x, a, b):
  779. return a*x + b
  780. for method in ['lm', 'trf', 'dogbox']:
  781. for dtx in [np.float32, np.float64]:
  782. for dty in [np.float32, np.float64]:
  783. x = x.astype(dtx)
  784. y = y.astype(dty)
  785. with warnings.catch_warnings():
  786. warnings.simplefilter("error", OptimizeWarning)
  787. p, cov = curve_fit(func, x, y, method=method)
  788. assert np.isfinite(cov).all()
  789. assert not np.allclose(p, 1) # curve_fit's initial value
  790. def test_dtypes2(self):
  791. # regression test for gh-7117: curve_fit fails if
  792. # both inputs are float32
  793. def hyperbola(x, s_1, s_2, o_x, o_y, c):
  794. b_2 = (s_1 + s_2) / 2
  795. b_1 = (s_2 - s_1) / 2
  796. return o_y + b_1*(x-o_x) + b_2*np.sqrt((x-o_x)**2 + c**2/4)
  797. min_fit = np.array([-3.0, 0.0, -2.0, -10.0, 0.0])
  798. max_fit = np.array([0.0, 3.0, 3.0, 0.0, 10.0])
  799. guess = np.array([-2.5/3.0, 4/3.0, 1.0, -4.0, 0.5])
  800. params = [-2, .4, -1, -5, 9.5]
  801. xdata = np.array([-32, -16, -8, 4, 4, 8, 16, 32])
  802. ydata = hyperbola(xdata, *params)
  803. # run optimization twice, with xdata being float32 and float64
  804. popt_64, _ = curve_fit(f=hyperbola, xdata=xdata, ydata=ydata, p0=guess,
  805. bounds=(min_fit, max_fit))
  806. xdata = xdata.astype(np.float32)
  807. ydata = hyperbola(xdata, *params)
  808. popt_32, _ = curve_fit(f=hyperbola, xdata=xdata, ydata=ydata, p0=guess,
  809. bounds=(min_fit, max_fit))
  810. assert_allclose(popt_32, popt_64, atol=2e-5)
  811. def test_broadcast_y(self):
  812. xdata = np.arange(10)
  813. rng = np.random.default_rng(123)
  814. target = 4.7 * xdata ** 2 + 3.5 * xdata + rng.random(size=len(xdata))
  815. def fit_func(x, a, b):
  816. return a * x ** 2 + b * x - target
  817. for method in ['lm', 'trf', 'dogbox']:
  818. popt0, pcov0 = curve_fit(fit_func,
  819. xdata=xdata,
  820. ydata=np.zeros_like(xdata),
  821. method=method)
  822. popt1, pcov1 = curve_fit(fit_func,
  823. xdata=xdata,
  824. ydata=0,
  825. method=method)
  826. assert_allclose(pcov0, pcov1)
  827. def test_args_in_kwargs(self):
  828. # Ensure that `args` cannot be passed as keyword argument to `curve_fit`
  829. def func(x, a, b):
  830. return a * x + b
  831. with assert_raises(ValueError):
  832. curve_fit(func,
  833. xdata=[1, 2, 3, 4],
  834. ydata=[5, 9, 13, 17],
  835. p0=[1],
  836. args=(1,))
  837. def test_data_point_number_validation(self):
  838. def func(x, a, b, c, d, e):
  839. return a * np.exp(-b * x) + c + d + e
  840. with assert_raises(TypeError, match="The number of func parameters="):
  841. curve_fit(func,
  842. xdata=[1, 2, 3, 4],
  843. ydata=[5, 9, 13, 17])
  844. @pytest.mark.filterwarnings('ignore::RuntimeWarning')
  845. def test_gh4555(self):
  846. # gh-4555 reported that covariance matrices returned by `leastsq`
  847. # can have negative diagonal elements and eigenvalues. (In fact,
  848. # they can also be asymmetric.) This shows up in the output of
  849. # `scipy.optimize.curve_fit`. Check that it has been resolved.giit
  850. def f(x, a, b, c, d, e):
  851. return a*np.log(x + 1 + b) + c*np.log(x + 1 + d) + e
  852. rng = np.random.default_rng(408113519974467917)
  853. n = 100
  854. x = np.arange(n)
  855. y = np.linspace(2, 7, n) + rng.random(n)
  856. p, cov = optimize.curve_fit(f, x, y, maxfev=100000)
  857. assert np.all(np.diag(cov) > 0)
  858. eigs = linalg.eigh(cov)[0] # separate line for debugging
  859. # some platforms see a small negative eigevenvalue
  860. assert np.all(eigs > -1e-2)
  861. assert_allclose(cov, cov.T)
  862. def test_gh4555b(self):
  863. # check that PR gh-17247 did not significantly change covariance matrix
  864. # for simple cases
  865. rng = np.random.default_rng(408113519974467917)
  866. def func(x, a, b, c):
  867. return a * np.exp(-b * x) + c
  868. xdata = np.linspace(0, 4, 50)
  869. y = func(xdata, 2.5, 1.3, 0.5)
  870. y_noise = 0.2 * rng.normal(size=xdata.size)
  871. ydata = y + y_noise
  872. _, res = curve_fit(func, xdata, ydata)
  873. # reference from commit 1d80a2f254380d2b45733258ca42eb6b55c8755b
  874. ref = [[+0.0158972536486215, 0.0069207183284242, -0.0007474400714749],
  875. [+0.0069207183284242, 0.0205057958128679, +0.0053997711275403],
  876. [-0.0007474400714749, 0.0053997711275403, +0.0027833930320877]]
  877. # Linux_Python_38_32bit_full fails with default tolerance
  878. assert_allclose(res, ref, 2e-7)
  879. def test_gh13670(self):
  880. # gh-13670 reported that `curve_fit` executes callables
  881. # with the same values of the parameters at the beginning of
  882. # optimization. Check that this has been resolved.
  883. rng = np.random.default_rng(8250058582555444926)
  884. x = np.linspace(0, 3, 101)
  885. y = 2 * x + 1 + rng.normal(size=101) * 0.5
  886. def line(x, *p):
  887. assert not np.all(line.last_p == p)
  888. line.last_p = p
  889. return x * p[0] + p[1]
  890. def jac(x, *p):
  891. assert not np.all(jac.last_p == p)
  892. jac.last_p = p
  893. return np.array([x, np.ones_like(x)]).T
  894. line.last_p = None
  895. jac.last_p = None
  896. p0 = np.array([1.0, 5.0])
  897. curve_fit(line, x, y, p0, method='lm', jac=jac)
  898. @pytest.mark.parametrize('method', ['trf', 'dogbox'])
  899. def test_gh20155_error_mentions_x0(self, method):
  900. # `curve_fit` produced an error message that referred to an undocumented
  901. # variable `x0`, which was really `p0`. Check that this is resolved.
  902. def func(x,a):
  903. return x**a
  904. message = "Initial guess is outside of provided bounds"
  905. with pytest.raises(ValueError, match=message):
  906. curve_fit(func, self.x, self.y, p0=[1], bounds=(1000, 1001),
  907. method=method)
  908. class TestFixedPoint:
  909. def test_scalar_trivial(self):
  910. # f(x) = 2x; fixed point should be x=0
  911. def func(x):
  912. return 2.0*x
  913. x0 = 1.0
  914. x = fixed_point(func, x0)
  915. assert_almost_equal(x, 0.0)
  916. def test_scalar_basic1(self):
  917. # f(x) = x**2; x0=1.05; fixed point should be x=1
  918. def func(x):
  919. return x**2
  920. x0 = 1.05
  921. x = fixed_point(func, x0)
  922. assert_almost_equal(x, 1.0)
  923. def test_scalar_basic2(self):
  924. # f(x) = x**0.5; x0=1.05; fixed point should be x=1
  925. def func(x):
  926. return x**0.5
  927. x0 = 1.05
  928. x = fixed_point(func, x0)
  929. assert_almost_equal(x, 1.0)
  930. def test_array_trivial(self):
  931. def func(x):
  932. return 2.0*x
  933. x0 = [0.3, 0.15]
  934. with np.errstate(all='ignore'):
  935. x = fixed_point(func, x0)
  936. assert_almost_equal(x, [0.0, 0.0])
  937. def test_array_basic1(self):
  938. # f(x) = c * x**2; fixed point should be x=1/c
  939. def func(x, c):
  940. return c * x**2
  941. c = array([0.75, 1.0, 1.25])
  942. x0 = [1.1, 1.15, 0.9]
  943. with np.errstate(all='ignore'):
  944. x = fixed_point(func, x0, args=(c,))
  945. assert_almost_equal(x, 1.0/c)
  946. def test_array_basic2(self):
  947. # f(x) = c * x**0.5; fixed point should be x=c**2
  948. def func(x, c):
  949. return c * x**0.5
  950. c = array([0.75, 1.0, 1.25])
  951. x0 = [0.8, 1.1, 1.1]
  952. x = fixed_point(func, x0, args=(c,))
  953. assert_almost_equal(x, c**2)
  954. def test_lambertw(self):
  955. # python-list/2010-December/594592.html
  956. xxroot = fixed_point(lambda xx: np.exp(-2.0*xx)/2.0, 1.0,
  957. args=(), xtol=1e-12, maxiter=500)
  958. assert_allclose(xxroot, np.exp(-2.0*xxroot)/2.0)
  959. assert_allclose(xxroot, lambertw(1)/2)
  960. def test_no_acceleration(self):
  961. # GitHub issue 5460
  962. ks = 2
  963. kl = 6
  964. m = 1.3
  965. n0 = 1.001
  966. i0 = ((m-1)/m)*(kl/ks/m)**(1/(m-1))
  967. def func(n):
  968. return np.log(kl/ks/n) / np.log(i0*n/(n - 1)) + 1
  969. n = fixed_point(func, n0, method='iteration')
  970. assert_allclose(n, m)