scipy 1.16.2__cp312-cp312-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1530) hide show
  1. scipy/__config__.py +161 -0
  2. scipy/__init__.py +150 -0
  3. scipy/_cyutility.cp312-win_arm64.lib +0 -0
  4. scipy/_cyutility.cp312-win_arm64.pyd +0 -0
  5. scipy/_distributor_init.py +18 -0
  6. scipy/_lib/__init__.py +14 -0
  7. scipy/_lib/_array_api.py +931 -0
  8. scipy/_lib/_array_api_compat_vendor.py +9 -0
  9. scipy/_lib/_array_api_no_0d.py +103 -0
  10. scipy/_lib/_bunch.py +229 -0
  11. scipy/_lib/_ccallback.py +251 -0
  12. scipy/_lib/_ccallback_c.cp312-win_arm64.lib +0 -0
  13. scipy/_lib/_ccallback_c.cp312-win_arm64.pyd +0 -0
  14. scipy/_lib/_disjoint_set.py +254 -0
  15. scipy/_lib/_docscrape.py +761 -0
  16. scipy/_lib/_elementwise_iterative_method.py +346 -0
  17. scipy/_lib/_fpumode.cp312-win_arm64.lib +0 -0
  18. scipy/_lib/_fpumode.cp312-win_arm64.pyd +0 -0
  19. scipy/_lib/_gcutils.py +105 -0
  20. scipy/_lib/_pep440.py +487 -0
  21. scipy/_lib/_sparse.py +41 -0
  22. scipy/_lib/_test_ccallback.cp312-win_arm64.lib +0 -0
  23. scipy/_lib/_test_ccallback.cp312-win_arm64.pyd +0 -0
  24. scipy/_lib/_test_deprecation_call.cp312-win_arm64.lib +0 -0
  25. scipy/_lib/_test_deprecation_call.cp312-win_arm64.pyd +0 -0
  26. scipy/_lib/_test_deprecation_def.cp312-win_arm64.lib +0 -0
  27. scipy/_lib/_test_deprecation_def.cp312-win_arm64.pyd +0 -0
  28. scipy/_lib/_testutils.py +373 -0
  29. scipy/_lib/_threadsafety.py +58 -0
  30. scipy/_lib/_tmpdirs.py +86 -0
  31. scipy/_lib/_uarray/LICENSE +29 -0
  32. scipy/_lib/_uarray/__init__.py +116 -0
  33. scipy/_lib/_uarray/_backend.py +707 -0
  34. scipy/_lib/_uarray/_uarray.cp312-win_arm64.lib +0 -0
  35. scipy/_lib/_uarray/_uarray.cp312-win_arm64.pyd +0 -0
  36. scipy/_lib/_util.py +1283 -0
  37. scipy/_lib/array_api_compat/__init__.py +22 -0
  38. scipy/_lib/array_api_compat/_internal.py +59 -0
  39. scipy/_lib/array_api_compat/common/__init__.py +1 -0
  40. scipy/_lib/array_api_compat/common/_aliases.py +727 -0
  41. scipy/_lib/array_api_compat/common/_fft.py +213 -0
  42. scipy/_lib/array_api_compat/common/_helpers.py +1058 -0
  43. scipy/_lib/array_api_compat/common/_linalg.py +232 -0
  44. scipy/_lib/array_api_compat/common/_typing.py +192 -0
  45. scipy/_lib/array_api_compat/cupy/__init__.py +13 -0
  46. scipy/_lib/array_api_compat/cupy/_aliases.py +156 -0
  47. scipy/_lib/array_api_compat/cupy/_info.py +336 -0
  48. scipy/_lib/array_api_compat/cupy/_typing.py +31 -0
  49. scipy/_lib/array_api_compat/cupy/fft.py +36 -0
  50. scipy/_lib/array_api_compat/cupy/linalg.py +49 -0
  51. scipy/_lib/array_api_compat/dask/__init__.py +0 -0
  52. scipy/_lib/array_api_compat/dask/array/__init__.py +12 -0
  53. scipy/_lib/array_api_compat/dask/array/_aliases.py +376 -0
  54. scipy/_lib/array_api_compat/dask/array/_info.py +416 -0
  55. scipy/_lib/array_api_compat/dask/array/fft.py +21 -0
  56. scipy/_lib/array_api_compat/dask/array/linalg.py +72 -0
  57. scipy/_lib/array_api_compat/numpy/__init__.py +28 -0
  58. scipy/_lib/array_api_compat/numpy/_aliases.py +190 -0
  59. scipy/_lib/array_api_compat/numpy/_info.py +366 -0
  60. scipy/_lib/array_api_compat/numpy/_typing.py +30 -0
  61. scipy/_lib/array_api_compat/numpy/fft.py +35 -0
  62. scipy/_lib/array_api_compat/numpy/linalg.py +143 -0
  63. scipy/_lib/array_api_compat/torch/__init__.py +22 -0
  64. scipy/_lib/array_api_compat/torch/_aliases.py +855 -0
  65. scipy/_lib/array_api_compat/torch/_info.py +369 -0
  66. scipy/_lib/array_api_compat/torch/_typing.py +3 -0
  67. scipy/_lib/array_api_compat/torch/fft.py +85 -0
  68. scipy/_lib/array_api_compat/torch/linalg.py +121 -0
  69. scipy/_lib/array_api_extra/__init__.py +38 -0
  70. scipy/_lib/array_api_extra/_delegation.py +171 -0
  71. scipy/_lib/array_api_extra/_lib/__init__.py +1 -0
  72. scipy/_lib/array_api_extra/_lib/_at.py +463 -0
  73. scipy/_lib/array_api_extra/_lib/_backends.py +46 -0
  74. scipy/_lib/array_api_extra/_lib/_funcs.py +937 -0
  75. scipy/_lib/array_api_extra/_lib/_lazy.py +357 -0
  76. scipy/_lib/array_api_extra/_lib/_testing.py +278 -0
  77. scipy/_lib/array_api_extra/_lib/_utils/__init__.py +1 -0
  78. scipy/_lib/array_api_extra/_lib/_utils/_compat.py +74 -0
  79. scipy/_lib/array_api_extra/_lib/_utils/_compat.pyi +45 -0
  80. scipy/_lib/array_api_extra/_lib/_utils/_helpers.py +559 -0
  81. scipy/_lib/array_api_extra/_lib/_utils/_typing.py +10 -0
  82. scipy/_lib/array_api_extra/_lib/_utils/_typing.pyi +105 -0
  83. scipy/_lib/array_api_extra/testing.py +359 -0
  84. scipy/_lib/cobyqa/__init__.py +20 -0
  85. scipy/_lib/cobyqa/framework.py +1240 -0
  86. scipy/_lib/cobyqa/main.py +1506 -0
  87. scipy/_lib/cobyqa/models.py +1529 -0
  88. scipy/_lib/cobyqa/problem.py +1296 -0
  89. scipy/_lib/cobyqa/settings.py +132 -0
  90. scipy/_lib/cobyqa/subsolvers/__init__.py +14 -0
  91. scipy/_lib/cobyqa/subsolvers/geometry.py +387 -0
  92. scipy/_lib/cobyqa/subsolvers/optim.py +1203 -0
  93. scipy/_lib/cobyqa/utils/__init__.py +18 -0
  94. scipy/_lib/cobyqa/utils/exceptions.py +22 -0
  95. scipy/_lib/cobyqa/utils/math.py +77 -0
  96. scipy/_lib/cobyqa/utils/versions.py +67 -0
  97. scipy/_lib/decorator.py +399 -0
  98. scipy/_lib/deprecation.py +274 -0
  99. scipy/_lib/doccer.py +366 -0
  100. scipy/_lib/messagestream.cp312-win_arm64.lib +0 -0
  101. scipy/_lib/messagestream.cp312-win_arm64.pyd +0 -0
  102. scipy/_lib/pyprima/__init__.py +212 -0
  103. scipy/_lib/pyprima/cobyla/__init__.py +0 -0
  104. scipy/_lib/pyprima/cobyla/cobyla.py +559 -0
  105. scipy/_lib/pyprima/cobyla/cobylb.py +714 -0
  106. scipy/_lib/pyprima/cobyla/geometry.py +226 -0
  107. scipy/_lib/pyprima/cobyla/initialize.py +215 -0
  108. scipy/_lib/pyprima/cobyla/trustregion.py +492 -0
  109. scipy/_lib/pyprima/cobyla/update.py +289 -0
  110. scipy/_lib/pyprima/common/__init__.py +0 -0
  111. scipy/_lib/pyprima/common/_bounds.py +34 -0
  112. scipy/_lib/pyprima/common/_linear_constraints.py +46 -0
  113. scipy/_lib/pyprima/common/_nonlinear_constraints.py +54 -0
  114. scipy/_lib/pyprima/common/_project.py +173 -0
  115. scipy/_lib/pyprima/common/checkbreak.py +93 -0
  116. scipy/_lib/pyprima/common/consts.py +47 -0
  117. scipy/_lib/pyprima/common/evaluate.py +99 -0
  118. scipy/_lib/pyprima/common/history.py +38 -0
  119. scipy/_lib/pyprima/common/infos.py +30 -0
  120. scipy/_lib/pyprima/common/linalg.py +435 -0
  121. scipy/_lib/pyprima/common/message.py +290 -0
  122. scipy/_lib/pyprima/common/powalg.py +131 -0
  123. scipy/_lib/pyprima/common/preproc.py +277 -0
  124. scipy/_lib/pyprima/common/present.py +5 -0
  125. scipy/_lib/pyprima/common/ratio.py +54 -0
  126. scipy/_lib/pyprima/common/redrho.py +47 -0
  127. scipy/_lib/pyprima/common/selectx.py +296 -0
  128. scipy/_lib/tests/__init__.py +0 -0
  129. scipy/_lib/tests/test__gcutils.py +110 -0
  130. scipy/_lib/tests/test__pep440.py +67 -0
  131. scipy/_lib/tests/test__testutils.py +32 -0
  132. scipy/_lib/tests/test__threadsafety.py +51 -0
  133. scipy/_lib/tests/test__util.py +641 -0
  134. scipy/_lib/tests/test_array_api.py +322 -0
  135. scipy/_lib/tests/test_bunch.py +169 -0
  136. scipy/_lib/tests/test_ccallback.py +196 -0
  137. scipy/_lib/tests/test_config.py +45 -0
  138. scipy/_lib/tests/test_deprecation.py +10 -0
  139. scipy/_lib/tests/test_doccer.py +143 -0
  140. scipy/_lib/tests/test_import_cycles.py +18 -0
  141. scipy/_lib/tests/test_public_api.py +482 -0
  142. scipy/_lib/tests/test_scipy_version.py +28 -0
  143. scipy/_lib/tests/test_tmpdirs.py +48 -0
  144. scipy/_lib/tests/test_warnings.py +137 -0
  145. scipy/_lib/uarray.py +31 -0
  146. scipy/cluster/__init__.py +31 -0
  147. scipy/cluster/_hierarchy.cp312-win_arm64.lib +0 -0
  148. scipy/cluster/_hierarchy.cp312-win_arm64.pyd +0 -0
  149. scipy/cluster/_optimal_leaf_ordering.cp312-win_arm64.lib +0 -0
  150. scipy/cluster/_optimal_leaf_ordering.cp312-win_arm64.pyd +0 -0
  151. scipy/cluster/_vq.cp312-win_arm64.lib +0 -0
  152. scipy/cluster/_vq.cp312-win_arm64.pyd +0 -0
  153. scipy/cluster/hierarchy.py +4348 -0
  154. scipy/cluster/tests/__init__.py +0 -0
  155. scipy/cluster/tests/hierarchy_test_data.py +145 -0
  156. scipy/cluster/tests/test_disjoint_set.py +202 -0
  157. scipy/cluster/tests/test_hierarchy.py +1238 -0
  158. scipy/cluster/tests/test_vq.py +434 -0
  159. scipy/cluster/vq.py +832 -0
  160. scipy/conftest.py +683 -0
  161. scipy/constants/__init__.py +358 -0
  162. scipy/constants/_codata.py +2266 -0
  163. scipy/constants/_constants.py +369 -0
  164. scipy/constants/codata.py +21 -0
  165. scipy/constants/constants.py +53 -0
  166. scipy/constants/tests/__init__.py +0 -0
  167. scipy/constants/tests/test_codata.py +78 -0
  168. scipy/constants/tests/test_constants.py +83 -0
  169. scipy/datasets/__init__.py +90 -0
  170. scipy/datasets/_download_all.py +71 -0
  171. scipy/datasets/_fetchers.py +225 -0
  172. scipy/datasets/_registry.py +26 -0
  173. scipy/datasets/_utils.py +81 -0
  174. scipy/datasets/tests/__init__.py +0 -0
  175. scipy/datasets/tests/test_data.py +128 -0
  176. scipy/differentiate/__init__.py +27 -0
  177. scipy/differentiate/_differentiate.py +1129 -0
  178. scipy/differentiate/tests/__init__.py +0 -0
  179. scipy/differentiate/tests/test_differentiate.py +694 -0
  180. scipy/fft/__init__.py +114 -0
  181. scipy/fft/_backend.py +196 -0
  182. scipy/fft/_basic.py +1650 -0
  183. scipy/fft/_basic_backend.py +197 -0
  184. scipy/fft/_debug_backends.py +22 -0
  185. scipy/fft/_fftlog.py +223 -0
  186. scipy/fft/_fftlog_backend.py +200 -0
  187. scipy/fft/_helper.py +348 -0
  188. scipy/fft/_pocketfft/LICENSE.md +25 -0
  189. scipy/fft/_pocketfft/__init__.py +9 -0
  190. scipy/fft/_pocketfft/basic.py +251 -0
  191. scipy/fft/_pocketfft/helper.py +249 -0
  192. scipy/fft/_pocketfft/pypocketfft.cp312-win_arm64.lib +0 -0
  193. scipy/fft/_pocketfft/pypocketfft.cp312-win_arm64.pyd +0 -0
  194. scipy/fft/_pocketfft/realtransforms.py +109 -0
  195. scipy/fft/_pocketfft/tests/__init__.py +0 -0
  196. scipy/fft/_pocketfft/tests/test_basic.py +1011 -0
  197. scipy/fft/_pocketfft/tests/test_real_transforms.py +505 -0
  198. scipy/fft/_realtransforms.py +706 -0
  199. scipy/fft/_realtransforms_backend.py +63 -0
  200. scipy/fft/tests/__init__.py +0 -0
  201. scipy/fft/tests/mock_backend.py +96 -0
  202. scipy/fft/tests/test_backend.py +98 -0
  203. scipy/fft/tests/test_basic.py +504 -0
  204. scipy/fft/tests/test_fftlog.py +215 -0
  205. scipy/fft/tests/test_helper.py +558 -0
  206. scipy/fft/tests/test_multithreading.py +84 -0
  207. scipy/fft/tests/test_real_transforms.py +247 -0
  208. scipy/fftpack/__init__.py +103 -0
  209. scipy/fftpack/_basic.py +428 -0
  210. scipy/fftpack/_helper.py +115 -0
  211. scipy/fftpack/_pseudo_diffs.py +554 -0
  212. scipy/fftpack/_realtransforms.py +598 -0
  213. scipy/fftpack/basic.py +20 -0
  214. scipy/fftpack/convolve.cp312-win_arm64.lib +0 -0
  215. scipy/fftpack/convolve.cp312-win_arm64.pyd +0 -0
  216. scipy/fftpack/helper.py +19 -0
  217. scipy/fftpack/pseudo_diffs.py +22 -0
  218. scipy/fftpack/realtransforms.py +19 -0
  219. scipy/fftpack/tests/__init__.py +0 -0
  220. scipy/fftpack/tests/fftw_double_ref.npz +0 -0
  221. scipy/fftpack/tests/fftw_longdouble_ref.npz +0 -0
  222. scipy/fftpack/tests/fftw_single_ref.npz +0 -0
  223. scipy/fftpack/tests/test.npz +0 -0
  224. scipy/fftpack/tests/test_basic.py +877 -0
  225. scipy/fftpack/tests/test_helper.py +54 -0
  226. scipy/fftpack/tests/test_import.py +33 -0
  227. scipy/fftpack/tests/test_pseudo_diffs.py +388 -0
  228. scipy/fftpack/tests/test_real_transforms.py +836 -0
  229. scipy/integrate/__init__.py +122 -0
  230. scipy/integrate/_bvp.py +1160 -0
  231. scipy/integrate/_cubature.py +729 -0
  232. scipy/integrate/_dop.cp312-win_arm64.lib +0 -0
  233. scipy/integrate/_dop.cp312-win_arm64.pyd +0 -0
  234. scipy/integrate/_ivp/__init__.py +8 -0
  235. scipy/integrate/_ivp/base.py +290 -0
  236. scipy/integrate/_ivp/bdf.py +478 -0
  237. scipy/integrate/_ivp/common.py +451 -0
  238. scipy/integrate/_ivp/dop853_coefficients.py +193 -0
  239. scipy/integrate/_ivp/ivp.py +755 -0
  240. scipy/integrate/_ivp/lsoda.py +224 -0
  241. scipy/integrate/_ivp/radau.py +572 -0
  242. scipy/integrate/_ivp/rk.py +601 -0
  243. scipy/integrate/_ivp/tests/__init__.py +0 -0
  244. scipy/integrate/_ivp/tests/test_ivp.py +1287 -0
  245. scipy/integrate/_ivp/tests/test_rk.py +37 -0
  246. scipy/integrate/_lebedev.py +5450 -0
  247. scipy/integrate/_lsoda.cp312-win_arm64.lib +0 -0
  248. scipy/integrate/_lsoda.cp312-win_arm64.pyd +0 -0
  249. scipy/integrate/_ode.py +1395 -0
  250. scipy/integrate/_odepack.cp312-win_arm64.lib +0 -0
  251. scipy/integrate/_odepack.cp312-win_arm64.pyd +0 -0
  252. scipy/integrate/_odepack_py.py +273 -0
  253. scipy/integrate/_quad_vec.py +674 -0
  254. scipy/integrate/_quadpack.cp312-win_arm64.lib +0 -0
  255. scipy/integrate/_quadpack.cp312-win_arm64.pyd +0 -0
  256. scipy/integrate/_quadpack_py.py +1283 -0
  257. scipy/integrate/_quadrature.py +1336 -0
  258. scipy/integrate/_rules/__init__.py +12 -0
  259. scipy/integrate/_rules/_base.py +518 -0
  260. scipy/integrate/_rules/_gauss_kronrod.py +202 -0
  261. scipy/integrate/_rules/_gauss_legendre.py +62 -0
  262. scipy/integrate/_rules/_genz_malik.py +210 -0
  263. scipy/integrate/_tanhsinh.py +1385 -0
  264. scipy/integrate/_test_multivariate.cp312-win_arm64.lib +0 -0
  265. scipy/integrate/_test_multivariate.cp312-win_arm64.pyd +0 -0
  266. scipy/integrate/_test_odeint_banded.cp312-win_arm64.lib +0 -0
  267. scipy/integrate/_test_odeint_banded.cp312-win_arm64.pyd +0 -0
  268. scipy/integrate/_vode.cp312-win_arm64.lib +0 -0
  269. scipy/integrate/_vode.cp312-win_arm64.pyd +0 -0
  270. scipy/integrate/dop.py +15 -0
  271. scipy/integrate/lsoda.py +15 -0
  272. scipy/integrate/odepack.py +17 -0
  273. scipy/integrate/quadpack.py +23 -0
  274. scipy/integrate/tests/__init__.py +0 -0
  275. scipy/integrate/tests/test__quad_vec.py +211 -0
  276. scipy/integrate/tests/test_banded_ode_solvers.py +305 -0
  277. scipy/integrate/tests/test_bvp.py +714 -0
  278. scipy/integrate/tests/test_cubature.py +1375 -0
  279. scipy/integrate/tests/test_integrate.py +840 -0
  280. scipy/integrate/tests/test_odeint_jac.py +74 -0
  281. scipy/integrate/tests/test_quadpack.py +680 -0
  282. scipy/integrate/tests/test_quadrature.py +730 -0
  283. scipy/integrate/tests/test_tanhsinh.py +1171 -0
  284. scipy/integrate/vode.py +15 -0
  285. scipy/interpolate/__init__.py +228 -0
  286. scipy/interpolate/_bary_rational.py +715 -0
  287. scipy/interpolate/_bsplines.py +2469 -0
  288. scipy/interpolate/_cubic.py +973 -0
  289. scipy/interpolate/_dfitpack.cp312-win_arm64.lib +0 -0
  290. scipy/interpolate/_dfitpack.cp312-win_arm64.pyd +0 -0
  291. scipy/interpolate/_dierckx.cp312-win_arm64.lib +0 -0
  292. scipy/interpolate/_dierckx.cp312-win_arm64.pyd +0 -0
  293. scipy/interpolate/_fitpack.cp312-win_arm64.lib +0 -0
  294. scipy/interpolate/_fitpack.cp312-win_arm64.pyd +0 -0
  295. scipy/interpolate/_fitpack2.py +2397 -0
  296. scipy/interpolate/_fitpack_impl.py +811 -0
  297. scipy/interpolate/_fitpack_py.py +898 -0
  298. scipy/interpolate/_fitpack_repro.py +996 -0
  299. scipy/interpolate/_interpnd.cp312-win_arm64.lib +0 -0
  300. scipy/interpolate/_interpnd.cp312-win_arm64.pyd +0 -0
  301. scipy/interpolate/_interpolate.py +2266 -0
  302. scipy/interpolate/_ndbspline.py +415 -0
  303. scipy/interpolate/_ndgriddata.py +329 -0
  304. scipy/interpolate/_pade.py +67 -0
  305. scipy/interpolate/_polyint.py +1025 -0
  306. scipy/interpolate/_ppoly.cp312-win_arm64.lib +0 -0
  307. scipy/interpolate/_ppoly.cp312-win_arm64.pyd +0 -0
  308. scipy/interpolate/_rbf.py +290 -0
  309. scipy/interpolate/_rbfinterp.py +550 -0
  310. scipy/interpolate/_rbfinterp_pythran.cp312-win_arm64.lib +0 -0
  311. scipy/interpolate/_rbfinterp_pythran.cp312-win_arm64.pyd +0 -0
  312. scipy/interpolate/_rgi.py +764 -0
  313. scipy/interpolate/_rgi_cython.cp312-win_arm64.lib +0 -0
  314. scipy/interpolate/_rgi_cython.cp312-win_arm64.pyd +0 -0
  315. scipy/interpolate/dfitpack.py +24 -0
  316. scipy/interpolate/fitpack.py +31 -0
  317. scipy/interpolate/fitpack2.py +29 -0
  318. scipy/interpolate/interpnd.py +24 -0
  319. scipy/interpolate/interpolate.py +30 -0
  320. scipy/interpolate/ndgriddata.py +23 -0
  321. scipy/interpolate/polyint.py +24 -0
  322. scipy/interpolate/rbf.py +18 -0
  323. scipy/interpolate/tests/__init__.py +0 -0
  324. scipy/interpolate/tests/data/bug-1310.npz +0 -0
  325. scipy/interpolate/tests/data/estimate_gradients_hang.npy +0 -0
  326. scipy/interpolate/tests/data/gcvspl.npz +0 -0
  327. scipy/interpolate/tests/test_bary_rational.py +368 -0
  328. scipy/interpolate/tests/test_bsplines.py +3754 -0
  329. scipy/interpolate/tests/test_fitpack.py +519 -0
  330. scipy/interpolate/tests/test_fitpack2.py +1431 -0
  331. scipy/interpolate/tests/test_gil.py +64 -0
  332. scipy/interpolate/tests/test_interpnd.py +452 -0
  333. scipy/interpolate/tests/test_interpolate.py +2630 -0
  334. scipy/interpolate/tests/test_ndgriddata.py +308 -0
  335. scipy/interpolate/tests/test_pade.py +107 -0
  336. scipy/interpolate/tests/test_polyint.py +972 -0
  337. scipy/interpolate/tests/test_rbf.py +246 -0
  338. scipy/interpolate/tests/test_rbfinterp.py +534 -0
  339. scipy/interpolate/tests/test_rgi.py +1151 -0
  340. scipy/io/__init__.py +116 -0
  341. scipy/io/_fast_matrix_market/__init__.py +600 -0
  342. scipy/io/_fast_matrix_market/_fmm_core.cp312-win_arm64.lib +0 -0
  343. scipy/io/_fast_matrix_market/_fmm_core.cp312-win_arm64.pyd +0 -0
  344. scipy/io/_fortran.py +354 -0
  345. scipy/io/_harwell_boeing/__init__.py +7 -0
  346. scipy/io/_harwell_boeing/_fortran_format_parser.py +316 -0
  347. scipy/io/_harwell_boeing/hb.py +571 -0
  348. scipy/io/_harwell_boeing/tests/__init__.py +0 -0
  349. scipy/io/_harwell_boeing/tests/test_fortran_format.py +74 -0
  350. scipy/io/_harwell_boeing/tests/test_hb.py +70 -0
  351. scipy/io/_idl.py +917 -0
  352. scipy/io/_mmio.py +968 -0
  353. scipy/io/_netcdf.py +1104 -0
  354. scipy/io/_test_fortran.cp312-win_arm64.lib +0 -0
  355. scipy/io/_test_fortran.cp312-win_arm64.pyd +0 -0
  356. scipy/io/arff/__init__.py +28 -0
  357. scipy/io/arff/_arffread.py +873 -0
  358. scipy/io/arff/arffread.py +19 -0
  359. scipy/io/arff/tests/__init__.py +0 -0
  360. scipy/io/arff/tests/data/iris.arff +225 -0
  361. scipy/io/arff/tests/data/missing.arff +8 -0
  362. scipy/io/arff/tests/data/nodata.arff +11 -0
  363. scipy/io/arff/tests/data/quoted_nominal.arff +13 -0
  364. scipy/io/arff/tests/data/quoted_nominal_spaces.arff +13 -0
  365. scipy/io/arff/tests/data/test1.arff +10 -0
  366. scipy/io/arff/tests/data/test10.arff +8 -0
  367. scipy/io/arff/tests/data/test11.arff +11 -0
  368. scipy/io/arff/tests/data/test2.arff +15 -0
  369. scipy/io/arff/tests/data/test3.arff +6 -0
  370. scipy/io/arff/tests/data/test4.arff +11 -0
  371. scipy/io/arff/tests/data/test5.arff +26 -0
  372. scipy/io/arff/tests/data/test6.arff +12 -0
  373. scipy/io/arff/tests/data/test7.arff +15 -0
  374. scipy/io/arff/tests/data/test8.arff +12 -0
  375. scipy/io/arff/tests/data/test9.arff +14 -0
  376. scipy/io/arff/tests/test_arffread.py +421 -0
  377. scipy/io/harwell_boeing.py +17 -0
  378. scipy/io/idl.py +17 -0
  379. scipy/io/matlab/__init__.py +66 -0
  380. scipy/io/matlab/_byteordercodes.py +75 -0
  381. scipy/io/matlab/_mio.py +375 -0
  382. scipy/io/matlab/_mio4.py +632 -0
  383. scipy/io/matlab/_mio5.py +901 -0
  384. scipy/io/matlab/_mio5_params.py +281 -0
  385. scipy/io/matlab/_mio5_utils.cp312-win_arm64.lib +0 -0
  386. scipy/io/matlab/_mio5_utils.cp312-win_arm64.pyd +0 -0
  387. scipy/io/matlab/_mio_utils.cp312-win_arm64.lib +0 -0
  388. scipy/io/matlab/_mio_utils.cp312-win_arm64.pyd +0 -0
  389. scipy/io/matlab/_miobase.py +435 -0
  390. scipy/io/matlab/_streams.cp312-win_arm64.lib +0 -0
  391. scipy/io/matlab/_streams.cp312-win_arm64.pyd +0 -0
  392. scipy/io/matlab/byteordercodes.py +17 -0
  393. scipy/io/matlab/mio.py +16 -0
  394. scipy/io/matlab/mio4.py +17 -0
  395. scipy/io/matlab/mio5.py +19 -0
  396. scipy/io/matlab/mio5_params.py +18 -0
  397. scipy/io/matlab/mio5_utils.py +17 -0
  398. scipy/io/matlab/mio_utils.py +17 -0
  399. scipy/io/matlab/miobase.py +16 -0
  400. scipy/io/matlab/streams.py +16 -0
  401. scipy/io/matlab/tests/__init__.py +0 -0
  402. scipy/io/matlab/tests/data/bad_miuint32.mat +0 -0
  403. scipy/io/matlab/tests/data/bad_miutf8_array_name.mat +0 -0
  404. scipy/io/matlab/tests/data/big_endian.mat +0 -0
  405. scipy/io/matlab/tests/data/broken_utf8.mat +0 -0
  406. scipy/io/matlab/tests/data/corrupted_zlib_checksum.mat +0 -0
  407. scipy/io/matlab/tests/data/corrupted_zlib_data.mat +0 -0
  408. scipy/io/matlab/tests/data/debigged_m4.mat +0 -0
  409. scipy/io/matlab/tests/data/japanese_utf8.txt +5 -0
  410. scipy/io/matlab/tests/data/little_endian.mat +0 -0
  411. scipy/io/matlab/tests/data/logical_sparse.mat +0 -0
  412. scipy/io/matlab/tests/data/malformed1.mat +0 -0
  413. scipy/io/matlab/tests/data/miuint32_for_miint32.mat +0 -0
  414. scipy/io/matlab/tests/data/miutf8_array_name.mat +0 -0
  415. scipy/io/matlab/tests/data/nasty_duplicate_fieldnames.mat +0 -0
  416. scipy/io/matlab/tests/data/one_by_zero_char.mat +0 -0
  417. scipy/io/matlab/tests/data/parabola.mat +0 -0
  418. scipy/io/matlab/tests/data/single_empty_string.mat +0 -0
  419. scipy/io/matlab/tests/data/some_functions.mat +0 -0
  420. scipy/io/matlab/tests/data/sqr.mat +0 -0
  421. scipy/io/matlab/tests/data/test3dmatrix_6.1_SOL2.mat +0 -0
  422. scipy/io/matlab/tests/data/test3dmatrix_6.5.1_GLNX86.mat +0 -0
  423. scipy/io/matlab/tests/data/test3dmatrix_7.1_GLNX86.mat +0 -0
  424. scipy/io/matlab/tests/data/test3dmatrix_7.4_GLNX86.mat +0 -0
  425. scipy/io/matlab/tests/data/test_empty_struct.mat +0 -0
  426. scipy/io/matlab/tests/data/test_mat4_le_floats.mat +0 -0
  427. scipy/io/matlab/tests/data/test_skip_variable.mat +0 -0
  428. scipy/io/matlab/tests/data/testbool_8_WIN64.mat +0 -0
  429. scipy/io/matlab/tests/data/testcell_6.1_SOL2.mat +0 -0
  430. scipy/io/matlab/tests/data/testcell_6.5.1_GLNX86.mat +0 -0
  431. scipy/io/matlab/tests/data/testcell_7.1_GLNX86.mat +0 -0
  432. scipy/io/matlab/tests/data/testcell_7.4_GLNX86.mat +0 -0
  433. scipy/io/matlab/tests/data/testcellnest_6.1_SOL2.mat +0 -0
  434. scipy/io/matlab/tests/data/testcellnest_6.5.1_GLNX86.mat +0 -0
  435. scipy/io/matlab/tests/data/testcellnest_7.1_GLNX86.mat +0 -0
  436. scipy/io/matlab/tests/data/testcellnest_7.4_GLNX86.mat +0 -0
  437. scipy/io/matlab/tests/data/testcomplex_4.2c_SOL2.mat +0 -0
  438. scipy/io/matlab/tests/data/testcomplex_6.1_SOL2.mat +0 -0
  439. scipy/io/matlab/tests/data/testcomplex_6.5.1_GLNX86.mat +0 -0
  440. scipy/io/matlab/tests/data/testcomplex_7.1_GLNX86.mat +0 -0
  441. scipy/io/matlab/tests/data/testcomplex_7.4_GLNX86.mat +0 -0
  442. scipy/io/matlab/tests/data/testdouble_4.2c_SOL2.mat +0 -0
  443. scipy/io/matlab/tests/data/testdouble_6.1_SOL2.mat +0 -0
  444. scipy/io/matlab/tests/data/testdouble_6.5.1_GLNX86.mat +0 -0
  445. scipy/io/matlab/tests/data/testdouble_7.1_GLNX86.mat +0 -0
  446. scipy/io/matlab/tests/data/testdouble_7.4_GLNX86.mat +0 -0
  447. scipy/io/matlab/tests/data/testemptycell_5.3_SOL2.mat +0 -0
  448. scipy/io/matlab/tests/data/testemptycell_6.5.1_GLNX86.mat +0 -0
  449. scipy/io/matlab/tests/data/testemptycell_7.1_GLNX86.mat +0 -0
  450. scipy/io/matlab/tests/data/testemptycell_7.4_GLNX86.mat +0 -0
  451. scipy/io/matlab/tests/data/testfunc_7.4_GLNX86.mat +0 -0
  452. scipy/io/matlab/tests/data/testhdf5_7.4_GLNX86.mat +0 -0
  453. scipy/io/matlab/tests/data/testmatrix_4.2c_SOL2.mat +0 -0
  454. scipy/io/matlab/tests/data/testmatrix_6.1_SOL2.mat +0 -0
  455. scipy/io/matlab/tests/data/testmatrix_6.5.1_GLNX86.mat +0 -0
  456. scipy/io/matlab/tests/data/testmatrix_7.1_GLNX86.mat +0 -0
  457. scipy/io/matlab/tests/data/testmatrix_7.4_GLNX86.mat +0 -0
  458. scipy/io/matlab/tests/data/testminus_4.2c_SOL2.mat +0 -0
  459. scipy/io/matlab/tests/data/testminus_6.1_SOL2.mat +0 -0
  460. scipy/io/matlab/tests/data/testminus_6.5.1_GLNX86.mat +0 -0
  461. scipy/io/matlab/tests/data/testminus_7.1_GLNX86.mat +0 -0
  462. scipy/io/matlab/tests/data/testminus_7.4_GLNX86.mat +0 -0
  463. scipy/io/matlab/tests/data/testmulti_4.2c_SOL2.mat +0 -0
  464. scipy/io/matlab/tests/data/testmulti_7.1_GLNX86.mat +0 -0
  465. scipy/io/matlab/tests/data/testmulti_7.4_GLNX86.mat +0 -0
  466. scipy/io/matlab/tests/data/testobject_6.1_SOL2.mat +0 -0
  467. scipy/io/matlab/tests/data/testobject_6.5.1_GLNX86.mat +0 -0
  468. scipy/io/matlab/tests/data/testobject_7.1_GLNX86.mat +0 -0
  469. scipy/io/matlab/tests/data/testobject_7.4_GLNX86.mat +0 -0
  470. scipy/io/matlab/tests/data/testonechar_4.2c_SOL2.mat +0 -0
  471. scipy/io/matlab/tests/data/testonechar_6.1_SOL2.mat +0 -0
  472. scipy/io/matlab/tests/data/testonechar_6.5.1_GLNX86.mat +0 -0
  473. scipy/io/matlab/tests/data/testonechar_7.1_GLNX86.mat +0 -0
  474. scipy/io/matlab/tests/data/testonechar_7.4_GLNX86.mat +0 -0
  475. scipy/io/matlab/tests/data/testscalarcell_7.4_GLNX86.mat +0 -0
  476. scipy/io/matlab/tests/data/testsimplecell.mat +0 -0
  477. scipy/io/matlab/tests/data/testsparse_4.2c_SOL2.mat +0 -0
  478. scipy/io/matlab/tests/data/testsparse_6.1_SOL2.mat +0 -0
  479. scipy/io/matlab/tests/data/testsparse_6.5.1_GLNX86.mat +0 -0
  480. scipy/io/matlab/tests/data/testsparse_7.1_GLNX86.mat +0 -0
  481. scipy/io/matlab/tests/data/testsparse_7.4_GLNX86.mat +0 -0
  482. scipy/io/matlab/tests/data/testsparsecomplex_4.2c_SOL2.mat +0 -0
  483. scipy/io/matlab/tests/data/testsparsecomplex_6.1_SOL2.mat +0 -0
  484. scipy/io/matlab/tests/data/testsparsecomplex_6.5.1_GLNX86.mat +0 -0
  485. scipy/io/matlab/tests/data/testsparsecomplex_7.1_GLNX86.mat +0 -0
  486. scipy/io/matlab/tests/data/testsparsecomplex_7.4_GLNX86.mat +0 -0
  487. scipy/io/matlab/tests/data/testsparsefloat_7.4_GLNX86.mat +0 -0
  488. scipy/io/matlab/tests/data/teststring_4.2c_SOL2.mat +0 -0
  489. scipy/io/matlab/tests/data/teststring_6.1_SOL2.mat +0 -0
  490. scipy/io/matlab/tests/data/teststring_6.5.1_GLNX86.mat +0 -0
  491. scipy/io/matlab/tests/data/teststring_7.1_GLNX86.mat +0 -0
  492. scipy/io/matlab/tests/data/teststring_7.4_GLNX86.mat +0 -0
  493. scipy/io/matlab/tests/data/teststringarray_4.2c_SOL2.mat +0 -0
  494. scipy/io/matlab/tests/data/teststringarray_6.1_SOL2.mat +0 -0
  495. scipy/io/matlab/tests/data/teststringarray_6.5.1_GLNX86.mat +0 -0
  496. scipy/io/matlab/tests/data/teststringarray_7.1_GLNX86.mat +0 -0
  497. scipy/io/matlab/tests/data/teststringarray_7.4_GLNX86.mat +0 -0
  498. scipy/io/matlab/tests/data/teststruct_6.1_SOL2.mat +0 -0
  499. scipy/io/matlab/tests/data/teststruct_6.5.1_GLNX86.mat +0 -0
  500. scipy/io/matlab/tests/data/teststruct_7.1_GLNX86.mat +0 -0
  501. scipy/io/matlab/tests/data/teststruct_7.4_GLNX86.mat +0 -0
  502. scipy/io/matlab/tests/data/teststructarr_6.1_SOL2.mat +0 -0
  503. scipy/io/matlab/tests/data/teststructarr_6.5.1_GLNX86.mat +0 -0
  504. scipy/io/matlab/tests/data/teststructarr_7.1_GLNX86.mat +0 -0
  505. scipy/io/matlab/tests/data/teststructarr_7.4_GLNX86.mat +0 -0
  506. scipy/io/matlab/tests/data/teststructnest_6.1_SOL2.mat +0 -0
  507. scipy/io/matlab/tests/data/teststructnest_6.5.1_GLNX86.mat +0 -0
  508. scipy/io/matlab/tests/data/teststructnest_7.1_GLNX86.mat +0 -0
  509. scipy/io/matlab/tests/data/teststructnest_7.4_GLNX86.mat +0 -0
  510. scipy/io/matlab/tests/data/testunicode_7.1_GLNX86.mat +0 -0
  511. scipy/io/matlab/tests/data/testunicode_7.4_GLNX86.mat +0 -0
  512. scipy/io/matlab/tests/data/testvec_4_GLNX86.mat +0 -0
  513. scipy/io/matlab/tests/test_byteordercodes.py +29 -0
  514. scipy/io/matlab/tests/test_mio.py +1399 -0
  515. scipy/io/matlab/tests/test_mio5_utils.py +179 -0
  516. scipy/io/matlab/tests/test_mio_funcs.py +51 -0
  517. scipy/io/matlab/tests/test_mio_utils.py +45 -0
  518. scipy/io/matlab/tests/test_miobase.py +32 -0
  519. scipy/io/matlab/tests/test_pathological.py +33 -0
  520. scipy/io/matlab/tests/test_streams.py +241 -0
  521. scipy/io/mmio.py +17 -0
  522. scipy/io/netcdf.py +17 -0
  523. scipy/io/tests/__init__.py +0 -0
  524. scipy/io/tests/data/Transparent Busy.ani +0 -0
  525. scipy/io/tests/data/array_float32_1d.sav +0 -0
  526. scipy/io/tests/data/array_float32_2d.sav +0 -0
  527. scipy/io/tests/data/array_float32_3d.sav +0 -0
  528. scipy/io/tests/data/array_float32_4d.sav +0 -0
  529. scipy/io/tests/data/array_float32_5d.sav +0 -0
  530. scipy/io/tests/data/array_float32_6d.sav +0 -0
  531. scipy/io/tests/data/array_float32_7d.sav +0 -0
  532. scipy/io/tests/data/array_float32_8d.sav +0 -0
  533. scipy/io/tests/data/array_float32_pointer_1d.sav +0 -0
  534. scipy/io/tests/data/array_float32_pointer_2d.sav +0 -0
  535. scipy/io/tests/data/array_float32_pointer_3d.sav +0 -0
  536. scipy/io/tests/data/array_float32_pointer_4d.sav +0 -0
  537. scipy/io/tests/data/array_float32_pointer_5d.sav +0 -0
  538. scipy/io/tests/data/array_float32_pointer_6d.sav +0 -0
  539. scipy/io/tests/data/array_float32_pointer_7d.sav +0 -0
  540. scipy/io/tests/data/array_float32_pointer_8d.sav +0 -0
  541. scipy/io/tests/data/example_1.nc +0 -0
  542. scipy/io/tests/data/example_2.nc +0 -0
  543. scipy/io/tests/data/example_3_maskedvals.nc +0 -0
  544. scipy/io/tests/data/fortran-3x3d-2i.dat +0 -0
  545. scipy/io/tests/data/fortran-mixed.dat +0 -0
  546. scipy/io/tests/data/fortran-sf8-11x1x10.dat +0 -0
  547. scipy/io/tests/data/fortran-sf8-15x10x22.dat +0 -0
  548. scipy/io/tests/data/fortran-sf8-1x1x1.dat +0 -0
  549. scipy/io/tests/data/fortran-sf8-1x1x5.dat +0 -0
  550. scipy/io/tests/data/fortran-sf8-1x1x7.dat +0 -0
  551. scipy/io/tests/data/fortran-sf8-1x3x5.dat +0 -0
  552. scipy/io/tests/data/fortran-si4-11x1x10.dat +0 -0
  553. scipy/io/tests/data/fortran-si4-15x10x22.dat +0 -0
  554. scipy/io/tests/data/fortran-si4-1x1x1.dat +0 -0
  555. scipy/io/tests/data/fortran-si4-1x1x5.dat +0 -0
  556. scipy/io/tests/data/fortran-si4-1x1x7.dat +0 -0
  557. scipy/io/tests/data/fortran-si4-1x3x5.dat +0 -0
  558. scipy/io/tests/data/invalid_pointer.sav +0 -0
  559. scipy/io/tests/data/null_pointer.sav +0 -0
  560. scipy/io/tests/data/scalar_byte.sav +0 -0
  561. scipy/io/tests/data/scalar_byte_descr.sav +0 -0
  562. scipy/io/tests/data/scalar_complex32.sav +0 -0
  563. scipy/io/tests/data/scalar_complex64.sav +0 -0
  564. scipy/io/tests/data/scalar_float32.sav +0 -0
  565. scipy/io/tests/data/scalar_float64.sav +0 -0
  566. scipy/io/tests/data/scalar_heap_pointer.sav +0 -0
  567. scipy/io/tests/data/scalar_int16.sav +0 -0
  568. scipy/io/tests/data/scalar_int32.sav +0 -0
  569. scipy/io/tests/data/scalar_int64.sav +0 -0
  570. scipy/io/tests/data/scalar_string.sav +0 -0
  571. scipy/io/tests/data/scalar_uint16.sav +0 -0
  572. scipy/io/tests/data/scalar_uint32.sav +0 -0
  573. scipy/io/tests/data/scalar_uint64.sav +0 -0
  574. scipy/io/tests/data/struct_arrays.sav +0 -0
  575. scipy/io/tests/data/struct_arrays_byte_idl80.sav +0 -0
  576. scipy/io/tests/data/struct_arrays_replicated.sav +0 -0
  577. scipy/io/tests/data/struct_arrays_replicated_3d.sav +0 -0
  578. scipy/io/tests/data/struct_inherit.sav +0 -0
  579. scipy/io/tests/data/struct_pointer_arrays.sav +0 -0
  580. scipy/io/tests/data/struct_pointer_arrays_replicated.sav +0 -0
  581. scipy/io/tests/data/struct_pointer_arrays_replicated_3d.sav +0 -0
  582. scipy/io/tests/data/struct_pointers.sav +0 -0
  583. scipy/io/tests/data/struct_pointers_replicated.sav +0 -0
  584. scipy/io/tests/data/struct_pointers_replicated_3d.sav +0 -0
  585. scipy/io/tests/data/struct_scalars.sav +0 -0
  586. scipy/io/tests/data/struct_scalars_replicated.sav +0 -0
  587. scipy/io/tests/data/struct_scalars_replicated_3d.sav +0 -0
  588. scipy/io/tests/data/test-1234Hz-le-1ch-10S-20bit-extra.wav +0 -0
  589. scipy/io/tests/data/test-44100Hz-2ch-32bit-float-be.wav +0 -0
  590. scipy/io/tests/data/test-44100Hz-2ch-32bit-float-le.wav +0 -0
  591. scipy/io/tests/data/test-44100Hz-be-1ch-4bytes.wav +0 -0
  592. scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-early-eof-no-data.wav +0 -0
  593. scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-early-eof.wav +0 -0
  594. scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-incomplete-chunk.wav +0 -0
  595. scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-rf64.wav +0 -0
  596. scipy/io/tests/data/test-44100Hz-le-1ch-4bytes.wav +0 -0
  597. scipy/io/tests/data/test-48000Hz-2ch-64bit-float-le-wavex.wav +0 -0
  598. scipy/io/tests/data/test-8000Hz-be-3ch-5S-24bit.wav +0 -0
  599. scipy/io/tests/data/test-8000Hz-le-1ch-1byte-ulaw.wav +0 -0
  600. scipy/io/tests/data/test-8000Hz-le-2ch-1byteu.wav +0 -0
  601. scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit-inconsistent.wav +0 -0
  602. scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit-rf64.wav +0 -0
  603. scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit.wav +0 -0
  604. scipy/io/tests/data/test-8000Hz-le-3ch-5S-36bit.wav +0 -0
  605. scipy/io/tests/data/test-8000Hz-le-3ch-5S-45bit.wav +0 -0
  606. scipy/io/tests/data/test-8000Hz-le-3ch-5S-53bit.wav +0 -0
  607. scipy/io/tests/data/test-8000Hz-le-3ch-5S-64bit.wav +0 -0
  608. scipy/io/tests/data/test-8000Hz-le-4ch-9S-12bit.wav +0 -0
  609. scipy/io/tests/data/test-8000Hz-le-5ch-9S-5bit.wav +0 -0
  610. scipy/io/tests/data/various_compressed.sav +0 -0
  611. scipy/io/tests/test_fortran.py +264 -0
  612. scipy/io/tests/test_idl.py +483 -0
  613. scipy/io/tests/test_mmio.py +831 -0
  614. scipy/io/tests/test_netcdf.py +550 -0
  615. scipy/io/tests/test_paths.py +93 -0
  616. scipy/io/tests/test_wavfile.py +501 -0
  617. scipy/io/wavfile.py +938 -0
  618. scipy/linalg/__init__.pxd +1 -0
  619. scipy/linalg/__init__.py +236 -0
  620. scipy/linalg/_basic.py +2146 -0
  621. scipy/linalg/_blas_subroutines.h +164 -0
  622. scipy/linalg/_cythonized_array_utils.cp312-win_arm64.lib +0 -0
  623. scipy/linalg/_cythonized_array_utils.cp312-win_arm64.pyd +0 -0
  624. scipy/linalg/_cythonized_array_utils.pxd +40 -0
  625. scipy/linalg/_cythonized_array_utils.pyi +16 -0
  626. scipy/linalg/_decomp.py +1645 -0
  627. scipy/linalg/_decomp_cholesky.py +413 -0
  628. scipy/linalg/_decomp_cossin.py +236 -0
  629. scipy/linalg/_decomp_interpolative.cp312-win_arm64.lib +0 -0
  630. scipy/linalg/_decomp_interpolative.cp312-win_arm64.pyd +0 -0
  631. scipy/linalg/_decomp_ldl.py +356 -0
  632. scipy/linalg/_decomp_lu.py +401 -0
  633. scipy/linalg/_decomp_lu_cython.cp312-win_arm64.lib +0 -0
  634. scipy/linalg/_decomp_lu_cython.cp312-win_arm64.pyd +0 -0
  635. scipy/linalg/_decomp_lu_cython.pyi +6 -0
  636. scipy/linalg/_decomp_polar.py +113 -0
  637. scipy/linalg/_decomp_qr.py +494 -0
  638. scipy/linalg/_decomp_qz.py +452 -0
  639. scipy/linalg/_decomp_schur.py +336 -0
  640. scipy/linalg/_decomp_svd.py +545 -0
  641. scipy/linalg/_decomp_update.cp312-win_arm64.lib +0 -0
  642. scipy/linalg/_decomp_update.cp312-win_arm64.pyd +0 -0
  643. scipy/linalg/_expm_frechet.py +417 -0
  644. scipy/linalg/_fblas.cp312-win_arm64.lib +0 -0
  645. scipy/linalg/_fblas.cp312-win_arm64.pyd +0 -0
  646. scipy/linalg/_flapack.cp312-win_arm64.lib +0 -0
  647. scipy/linalg/_flapack.cp312-win_arm64.pyd +0 -0
  648. scipy/linalg/_lapack_subroutines.h +1521 -0
  649. scipy/linalg/_linalg_pythran.cp312-win_arm64.lib +0 -0
  650. scipy/linalg/_linalg_pythran.cp312-win_arm64.pyd +0 -0
  651. scipy/linalg/_matfuncs.py +1050 -0
  652. scipy/linalg/_matfuncs_expm.cp312-win_arm64.lib +0 -0
  653. scipy/linalg/_matfuncs_expm.cp312-win_arm64.pyd +0 -0
  654. scipy/linalg/_matfuncs_expm.pyi +6 -0
  655. scipy/linalg/_matfuncs_inv_ssq.py +886 -0
  656. scipy/linalg/_matfuncs_schur_sqrtm.cp312-win_arm64.lib +0 -0
  657. scipy/linalg/_matfuncs_schur_sqrtm.cp312-win_arm64.pyd +0 -0
  658. scipy/linalg/_matfuncs_sqrtm.py +107 -0
  659. scipy/linalg/_matfuncs_sqrtm_triu.cp312-win_arm64.lib +0 -0
  660. scipy/linalg/_matfuncs_sqrtm_triu.cp312-win_arm64.pyd +0 -0
  661. scipy/linalg/_misc.py +191 -0
  662. scipy/linalg/_procrustes.py +113 -0
  663. scipy/linalg/_sketches.py +189 -0
  664. scipy/linalg/_solve_toeplitz.cp312-win_arm64.lib +0 -0
  665. scipy/linalg/_solve_toeplitz.cp312-win_arm64.pyd +0 -0
  666. scipy/linalg/_solvers.py +862 -0
  667. scipy/linalg/_special_matrices.py +1322 -0
  668. scipy/linalg/_testutils.py +65 -0
  669. scipy/linalg/basic.py +23 -0
  670. scipy/linalg/blas.py +495 -0
  671. scipy/linalg/cython_blas.cp312-win_arm64.lib +0 -0
  672. scipy/linalg/cython_blas.cp312-win_arm64.pyd +0 -0
  673. scipy/linalg/cython_blas.pxd +169 -0
  674. scipy/linalg/cython_blas.pyx +1432 -0
  675. scipy/linalg/cython_lapack.cp312-win_arm64.lib +0 -0
  676. scipy/linalg/cython_lapack.cp312-win_arm64.pyd +0 -0
  677. scipy/linalg/cython_lapack.pxd +1528 -0
  678. scipy/linalg/cython_lapack.pyx +12045 -0
  679. scipy/linalg/decomp.py +23 -0
  680. scipy/linalg/decomp_cholesky.py +21 -0
  681. scipy/linalg/decomp_lu.py +21 -0
  682. scipy/linalg/decomp_qr.py +20 -0
  683. scipy/linalg/decomp_schur.py +21 -0
  684. scipy/linalg/decomp_svd.py +21 -0
  685. scipy/linalg/interpolative.py +989 -0
  686. scipy/linalg/lapack.py +1081 -0
  687. scipy/linalg/matfuncs.py +23 -0
  688. scipy/linalg/misc.py +21 -0
  689. scipy/linalg/special_matrices.py +22 -0
  690. scipy/linalg/tests/__init__.py +0 -0
  691. scipy/linalg/tests/_cython_examples/extending.pyx +23 -0
  692. scipy/linalg/tests/_cython_examples/meson.build +34 -0
  693. scipy/linalg/tests/data/carex_15_data.npz +0 -0
  694. scipy/linalg/tests/data/carex_18_data.npz +0 -0
  695. scipy/linalg/tests/data/carex_19_data.npz +0 -0
  696. scipy/linalg/tests/data/carex_20_data.npz +0 -0
  697. scipy/linalg/tests/data/carex_6_data.npz +0 -0
  698. scipy/linalg/tests/data/gendare_20170120_data.npz +0 -0
  699. scipy/linalg/tests/test_basic.py +2074 -0
  700. scipy/linalg/tests/test_batch.py +588 -0
  701. scipy/linalg/tests/test_blas.py +1127 -0
  702. scipy/linalg/tests/test_cython_blas.py +118 -0
  703. scipy/linalg/tests/test_cython_lapack.py +22 -0
  704. scipy/linalg/tests/test_cythonized_array_utils.py +130 -0
  705. scipy/linalg/tests/test_decomp.py +3189 -0
  706. scipy/linalg/tests/test_decomp_cholesky.py +268 -0
  707. scipy/linalg/tests/test_decomp_cossin.py +314 -0
  708. scipy/linalg/tests/test_decomp_ldl.py +137 -0
  709. scipy/linalg/tests/test_decomp_lu.py +308 -0
  710. scipy/linalg/tests/test_decomp_polar.py +110 -0
  711. scipy/linalg/tests/test_decomp_update.py +1701 -0
  712. scipy/linalg/tests/test_extending.py +46 -0
  713. scipy/linalg/tests/test_fblas.py +607 -0
  714. scipy/linalg/tests/test_interpolative.py +232 -0
  715. scipy/linalg/tests/test_lapack.py +3620 -0
  716. scipy/linalg/tests/test_matfuncs.py +1125 -0
  717. scipy/linalg/tests/test_matmul_toeplitz.py +136 -0
  718. scipy/linalg/tests/test_procrustes.py +214 -0
  719. scipy/linalg/tests/test_sketches.py +118 -0
  720. scipy/linalg/tests/test_solve_toeplitz.py +150 -0
  721. scipy/linalg/tests/test_solvers.py +844 -0
  722. scipy/linalg/tests/test_special_matrices.py +636 -0
  723. scipy/misc/__init__.py +6 -0
  724. scipy/misc/common.py +6 -0
  725. scipy/misc/doccer.py +6 -0
  726. scipy/ndimage/__init__.py +174 -0
  727. scipy/ndimage/_ctest.cp312-win_arm64.lib +0 -0
  728. scipy/ndimage/_ctest.cp312-win_arm64.pyd +0 -0
  729. scipy/ndimage/_cytest.cp312-win_arm64.lib +0 -0
  730. scipy/ndimage/_cytest.cp312-win_arm64.pyd +0 -0
  731. scipy/ndimage/_delegators.py +303 -0
  732. scipy/ndimage/_filters.py +2422 -0
  733. scipy/ndimage/_fourier.py +306 -0
  734. scipy/ndimage/_interpolation.py +1033 -0
  735. scipy/ndimage/_measurements.py +1689 -0
  736. scipy/ndimage/_morphology.py +2634 -0
  737. scipy/ndimage/_nd_image.cp312-win_arm64.lib +0 -0
  738. scipy/ndimage/_nd_image.cp312-win_arm64.pyd +0 -0
  739. scipy/ndimage/_ndimage_api.py +16 -0
  740. scipy/ndimage/_ni_docstrings.py +214 -0
  741. scipy/ndimage/_ni_label.cp312-win_arm64.lib +0 -0
  742. scipy/ndimage/_ni_label.cp312-win_arm64.pyd +0 -0
  743. scipy/ndimage/_ni_support.py +139 -0
  744. scipy/ndimage/_rank_filter_1d.cp312-win_arm64.lib +0 -0
  745. scipy/ndimage/_rank_filter_1d.cp312-win_arm64.pyd +0 -0
  746. scipy/ndimage/_support_alternative_backends.py +84 -0
  747. scipy/ndimage/filters.py +27 -0
  748. scipy/ndimage/fourier.py +21 -0
  749. scipy/ndimage/interpolation.py +22 -0
  750. scipy/ndimage/measurements.py +24 -0
  751. scipy/ndimage/morphology.py +27 -0
  752. scipy/ndimage/tests/__init__.py +12 -0
  753. scipy/ndimage/tests/data/label_inputs.txt +21 -0
  754. scipy/ndimage/tests/data/label_results.txt +294 -0
  755. scipy/ndimage/tests/data/label_strels.txt +42 -0
  756. scipy/ndimage/tests/dots.png +0 -0
  757. scipy/ndimage/tests/test_c_api.py +102 -0
  758. scipy/ndimage/tests/test_datatypes.py +67 -0
  759. scipy/ndimage/tests/test_filters.py +3083 -0
  760. scipy/ndimage/tests/test_fourier.py +187 -0
  761. scipy/ndimage/tests/test_interpolation.py +1491 -0
  762. scipy/ndimage/tests/test_measurements.py +1592 -0
  763. scipy/ndimage/tests/test_morphology.py +2950 -0
  764. scipy/ndimage/tests/test_ni_support.py +78 -0
  765. scipy/ndimage/tests/test_splines.py +70 -0
  766. scipy/odr/__init__.py +131 -0
  767. scipy/odr/__odrpack.cp312-win_arm64.lib +0 -0
  768. scipy/odr/__odrpack.cp312-win_arm64.pyd +0 -0
  769. scipy/odr/_add_newdocs.py +34 -0
  770. scipy/odr/_models.py +315 -0
  771. scipy/odr/_odrpack.py +1154 -0
  772. scipy/odr/models.py +20 -0
  773. scipy/odr/odrpack.py +21 -0
  774. scipy/odr/tests/__init__.py +0 -0
  775. scipy/odr/tests/test_odr.py +607 -0
  776. scipy/optimize/__init__.pxd +1 -0
  777. scipy/optimize/__init__.py +460 -0
  778. scipy/optimize/_basinhopping.py +741 -0
  779. scipy/optimize/_bglu_dense.cp312-win_arm64.lib +0 -0
  780. scipy/optimize/_bglu_dense.cp312-win_arm64.pyd +0 -0
  781. scipy/optimize/_bracket.py +706 -0
  782. scipy/optimize/_chandrupatla.py +551 -0
  783. scipy/optimize/_cobyla_py.py +297 -0
  784. scipy/optimize/_cobyqa_py.py +72 -0
  785. scipy/optimize/_constraints.py +598 -0
  786. scipy/optimize/_dcsrch.py +728 -0
  787. scipy/optimize/_differentiable_functions.py +835 -0
  788. scipy/optimize/_differentialevolution.py +1970 -0
  789. scipy/optimize/_direct.cp312-win_arm64.lib +0 -0
  790. scipy/optimize/_direct.cp312-win_arm64.pyd +0 -0
  791. scipy/optimize/_direct_py.py +280 -0
  792. scipy/optimize/_dual_annealing.py +732 -0
  793. scipy/optimize/_elementwise.py +798 -0
  794. scipy/optimize/_group_columns.cp312-win_arm64.lib +0 -0
  795. scipy/optimize/_group_columns.cp312-win_arm64.pyd +0 -0
  796. scipy/optimize/_hessian_update_strategy.py +479 -0
  797. scipy/optimize/_highspy/__init__.py +0 -0
  798. scipy/optimize/_highspy/_core.cp312-win_arm64.lib +0 -0
  799. scipy/optimize/_highspy/_core.cp312-win_arm64.pyd +0 -0
  800. scipy/optimize/_highspy/_highs_options.cp312-win_arm64.lib +0 -0
  801. scipy/optimize/_highspy/_highs_options.cp312-win_arm64.pyd +0 -0
  802. scipy/optimize/_highspy/_highs_wrapper.py +338 -0
  803. scipy/optimize/_isotonic.py +157 -0
  804. scipy/optimize/_lbfgsb.cp312-win_arm64.lib +0 -0
  805. scipy/optimize/_lbfgsb.cp312-win_arm64.pyd +0 -0
  806. scipy/optimize/_lbfgsb_py.py +634 -0
  807. scipy/optimize/_linesearch.py +896 -0
  808. scipy/optimize/_linprog.py +733 -0
  809. scipy/optimize/_linprog_doc.py +1434 -0
  810. scipy/optimize/_linprog_highs.py +422 -0
  811. scipy/optimize/_linprog_ip.py +1141 -0
  812. scipy/optimize/_linprog_rs.py +572 -0
  813. scipy/optimize/_linprog_simplex.py +663 -0
  814. scipy/optimize/_linprog_util.py +1521 -0
  815. scipy/optimize/_lsap.cp312-win_arm64.lib +0 -0
  816. scipy/optimize/_lsap.cp312-win_arm64.pyd +0 -0
  817. scipy/optimize/_lsq/__init__.py +5 -0
  818. scipy/optimize/_lsq/bvls.py +183 -0
  819. scipy/optimize/_lsq/common.py +731 -0
  820. scipy/optimize/_lsq/dogbox.py +345 -0
  821. scipy/optimize/_lsq/givens_elimination.cp312-win_arm64.lib +0 -0
  822. scipy/optimize/_lsq/givens_elimination.cp312-win_arm64.pyd +0 -0
  823. scipy/optimize/_lsq/least_squares.py +1044 -0
  824. scipy/optimize/_lsq/lsq_linear.py +361 -0
  825. scipy/optimize/_lsq/trf.py +587 -0
  826. scipy/optimize/_lsq/trf_linear.py +249 -0
  827. scipy/optimize/_milp.py +394 -0
  828. scipy/optimize/_minimize.py +1199 -0
  829. scipy/optimize/_minpack.cp312-win_arm64.lib +0 -0
  830. scipy/optimize/_minpack.cp312-win_arm64.pyd +0 -0
  831. scipy/optimize/_minpack_py.py +1178 -0
  832. scipy/optimize/_moduleTNC.cp312-win_arm64.lib +0 -0
  833. scipy/optimize/_moduleTNC.cp312-win_arm64.pyd +0 -0
  834. scipy/optimize/_nnls.py +96 -0
  835. scipy/optimize/_nonlin.py +1634 -0
  836. scipy/optimize/_numdiff.py +963 -0
  837. scipy/optimize/_optimize.py +4169 -0
  838. scipy/optimize/_pava_pybind.cp312-win_arm64.lib +0 -0
  839. scipy/optimize/_pava_pybind.cp312-win_arm64.pyd +0 -0
  840. scipy/optimize/_qap.py +760 -0
  841. scipy/optimize/_remove_redundancy.py +522 -0
  842. scipy/optimize/_root.py +732 -0
  843. scipy/optimize/_root_scalar.py +538 -0
  844. scipy/optimize/_shgo.py +1606 -0
  845. scipy/optimize/_shgo_lib/__init__.py +0 -0
  846. scipy/optimize/_shgo_lib/_complex.py +1225 -0
  847. scipy/optimize/_shgo_lib/_vertex.py +460 -0
  848. scipy/optimize/_slsqp_py.py +603 -0
  849. scipy/optimize/_slsqplib.cp312-win_arm64.lib +0 -0
  850. scipy/optimize/_slsqplib.cp312-win_arm64.pyd +0 -0
  851. scipy/optimize/_spectral.py +260 -0
  852. scipy/optimize/_tnc.py +438 -0
  853. scipy/optimize/_trlib/__init__.py +12 -0
  854. scipy/optimize/_trlib/_trlib.cp312-win_arm64.lib +0 -0
  855. scipy/optimize/_trlib/_trlib.cp312-win_arm64.pyd +0 -0
  856. scipy/optimize/_trustregion.py +318 -0
  857. scipy/optimize/_trustregion_constr/__init__.py +6 -0
  858. scipy/optimize/_trustregion_constr/canonical_constraint.py +390 -0
  859. scipy/optimize/_trustregion_constr/equality_constrained_sqp.py +231 -0
  860. scipy/optimize/_trustregion_constr/minimize_trustregion_constr.py +584 -0
  861. scipy/optimize/_trustregion_constr/projections.py +411 -0
  862. scipy/optimize/_trustregion_constr/qp_subproblem.py +637 -0
  863. scipy/optimize/_trustregion_constr/report.py +49 -0
  864. scipy/optimize/_trustregion_constr/tests/__init__.py +0 -0
  865. scipy/optimize/_trustregion_constr/tests/test_canonical_constraint.py +296 -0
  866. scipy/optimize/_trustregion_constr/tests/test_nested_minimize.py +39 -0
  867. scipy/optimize/_trustregion_constr/tests/test_projections.py +214 -0
  868. scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py +645 -0
  869. scipy/optimize/_trustregion_constr/tests/test_report.py +34 -0
  870. scipy/optimize/_trustregion_constr/tr_interior_point.py +361 -0
  871. scipy/optimize/_trustregion_dogleg.py +122 -0
  872. scipy/optimize/_trustregion_exact.py +437 -0
  873. scipy/optimize/_trustregion_krylov.py +65 -0
  874. scipy/optimize/_trustregion_ncg.py +126 -0
  875. scipy/optimize/_tstutils.py +972 -0
  876. scipy/optimize/_zeros.cp312-win_arm64.lib +0 -0
  877. scipy/optimize/_zeros.cp312-win_arm64.pyd +0 -0
  878. scipy/optimize/_zeros_py.py +1475 -0
  879. scipy/optimize/cobyla.py +19 -0
  880. scipy/optimize/cython_optimize/__init__.py +133 -0
  881. scipy/optimize/cython_optimize/_zeros.cp312-win_arm64.lib +0 -0
  882. scipy/optimize/cython_optimize/_zeros.cp312-win_arm64.pyd +0 -0
  883. scipy/optimize/cython_optimize/_zeros.pxd +33 -0
  884. scipy/optimize/cython_optimize/c_zeros.pxd +26 -0
  885. scipy/optimize/cython_optimize.pxd +11 -0
  886. scipy/optimize/elementwise.py +38 -0
  887. scipy/optimize/lbfgsb.py +23 -0
  888. scipy/optimize/linesearch.py +18 -0
  889. scipy/optimize/minpack.py +27 -0
  890. scipy/optimize/minpack2.py +17 -0
  891. scipy/optimize/moduleTNC.py +19 -0
  892. scipy/optimize/nonlin.py +29 -0
  893. scipy/optimize/optimize.py +40 -0
  894. scipy/optimize/slsqp.py +22 -0
  895. scipy/optimize/tests/__init__.py +0 -0
  896. scipy/optimize/tests/_cython_examples/extending.pyx +43 -0
  897. scipy/optimize/tests/_cython_examples/meson.build +32 -0
  898. scipy/optimize/tests/test__basinhopping.py +535 -0
  899. scipy/optimize/tests/test__differential_evolution.py +1703 -0
  900. scipy/optimize/tests/test__dual_annealing.py +416 -0
  901. scipy/optimize/tests/test__linprog_clean_inputs.py +312 -0
  902. scipy/optimize/tests/test__numdiff.py +885 -0
  903. scipy/optimize/tests/test__remove_redundancy.py +228 -0
  904. scipy/optimize/tests/test__root.py +124 -0
  905. scipy/optimize/tests/test__shgo.py +1164 -0
  906. scipy/optimize/tests/test__spectral.py +226 -0
  907. scipy/optimize/tests/test_bracket.py +896 -0
  908. scipy/optimize/tests/test_chandrupatla.py +982 -0
  909. scipy/optimize/tests/test_cobyla.py +195 -0
  910. scipy/optimize/tests/test_cobyqa.py +252 -0
  911. scipy/optimize/tests/test_constraint_conversion.py +286 -0
  912. scipy/optimize/tests/test_constraints.py +255 -0
  913. scipy/optimize/tests/test_cython_optimize.py +92 -0
  914. scipy/optimize/tests/test_differentiable_functions.py +1025 -0
  915. scipy/optimize/tests/test_direct.py +321 -0
  916. scipy/optimize/tests/test_extending.py +28 -0
  917. scipy/optimize/tests/test_hessian_update_strategy.py +300 -0
  918. scipy/optimize/tests/test_isotonic_regression.py +167 -0
  919. scipy/optimize/tests/test_lbfgsb_hessinv.py +65 -0
  920. scipy/optimize/tests/test_lbfgsb_setulb.py +122 -0
  921. scipy/optimize/tests/test_least_squares.py +986 -0
  922. scipy/optimize/tests/test_linear_assignment.py +116 -0
  923. scipy/optimize/tests/test_linesearch.py +328 -0
  924. scipy/optimize/tests/test_linprog.py +2577 -0
  925. scipy/optimize/tests/test_lsq_common.py +297 -0
  926. scipy/optimize/tests/test_lsq_linear.py +287 -0
  927. scipy/optimize/tests/test_milp.py +459 -0
  928. scipy/optimize/tests/test_minimize_constrained.py +845 -0
  929. scipy/optimize/tests/test_minpack.py +1194 -0
  930. scipy/optimize/tests/test_nnls.py +469 -0
  931. scipy/optimize/tests/test_nonlin.py +572 -0
  932. scipy/optimize/tests/test_optimize.py +3344 -0
  933. scipy/optimize/tests/test_quadratic_assignment.py +455 -0
  934. scipy/optimize/tests/test_regression.py +40 -0
  935. scipy/optimize/tests/test_slsqp.py +645 -0
  936. scipy/optimize/tests/test_tnc.py +345 -0
  937. scipy/optimize/tests/test_trustregion.py +110 -0
  938. scipy/optimize/tests/test_trustregion_exact.py +351 -0
  939. scipy/optimize/tests/test_trustregion_krylov.py +170 -0
  940. scipy/optimize/tests/test_zeros.py +998 -0
  941. scipy/optimize/tnc.py +22 -0
  942. scipy/optimize/zeros.py +26 -0
  943. scipy/signal/__init__.py +316 -0
  944. scipy/signal/_arraytools.py +264 -0
  945. scipy/signal/_czt.py +575 -0
  946. scipy/signal/_delegators.py +568 -0
  947. scipy/signal/_filter_design.py +5893 -0
  948. scipy/signal/_fir_filter_design.py +1458 -0
  949. scipy/signal/_lti_conversion.py +534 -0
  950. scipy/signal/_ltisys.py +3546 -0
  951. scipy/signal/_max_len_seq.py +139 -0
  952. scipy/signal/_max_len_seq_inner.cp312-win_arm64.lib +0 -0
  953. scipy/signal/_max_len_seq_inner.cp312-win_arm64.pyd +0 -0
  954. scipy/signal/_peak_finding.py +1310 -0
  955. scipy/signal/_peak_finding_utils.cp312-win_arm64.lib +0 -0
  956. scipy/signal/_peak_finding_utils.cp312-win_arm64.pyd +0 -0
  957. scipy/signal/_polyutils.py +172 -0
  958. scipy/signal/_savitzky_golay.py +357 -0
  959. scipy/signal/_short_time_fft.py +2228 -0
  960. scipy/signal/_signal_api.py +30 -0
  961. scipy/signal/_signaltools.py +5309 -0
  962. scipy/signal/_sigtools.cp312-win_arm64.lib +0 -0
  963. scipy/signal/_sigtools.cp312-win_arm64.pyd +0 -0
  964. scipy/signal/_sosfilt.cp312-win_arm64.lib +0 -0
  965. scipy/signal/_sosfilt.cp312-win_arm64.pyd +0 -0
  966. scipy/signal/_spectral_py.py +2471 -0
  967. scipy/signal/_spline.cp312-win_arm64.lib +0 -0
  968. scipy/signal/_spline.cp312-win_arm64.pyd +0 -0
  969. scipy/signal/_spline.pyi +34 -0
  970. scipy/signal/_spline_filters.py +848 -0
  971. scipy/signal/_support_alternative_backends.py +73 -0
  972. scipy/signal/_upfirdn.py +219 -0
  973. scipy/signal/_upfirdn_apply.cp312-win_arm64.lib +0 -0
  974. scipy/signal/_upfirdn_apply.cp312-win_arm64.pyd +0 -0
  975. scipy/signal/_waveforms.py +687 -0
  976. scipy/signal/_wavelets.py +29 -0
  977. scipy/signal/bsplines.py +21 -0
  978. scipy/signal/filter_design.py +28 -0
  979. scipy/signal/fir_filter_design.py +21 -0
  980. scipy/signal/lti_conversion.py +20 -0
  981. scipy/signal/ltisys.py +25 -0
  982. scipy/signal/signaltools.py +27 -0
  983. scipy/signal/spectral.py +21 -0
  984. scipy/signal/spline.py +18 -0
  985. scipy/signal/tests/__init__.py +0 -0
  986. scipy/signal/tests/_scipy_spectral_test_shim.py +311 -0
  987. scipy/signal/tests/mpsig.py +122 -0
  988. scipy/signal/tests/test_array_tools.py +111 -0
  989. scipy/signal/tests/test_bsplines.py +365 -0
  990. scipy/signal/tests/test_cont2discrete.py +424 -0
  991. scipy/signal/tests/test_czt.py +221 -0
  992. scipy/signal/tests/test_dltisys.py +599 -0
  993. scipy/signal/tests/test_filter_design.py +4744 -0
  994. scipy/signal/tests/test_fir_filter_design.py +851 -0
  995. scipy/signal/tests/test_ltisys.py +1225 -0
  996. scipy/signal/tests/test_max_len_seq.py +71 -0
  997. scipy/signal/tests/test_peak_finding.py +915 -0
  998. scipy/signal/tests/test_result_type.py +51 -0
  999. scipy/signal/tests/test_savitzky_golay.py +363 -0
  1000. scipy/signal/tests/test_short_time_fft.py +1107 -0
  1001. scipy/signal/tests/test_signaltools.py +4735 -0
  1002. scipy/signal/tests/test_spectral.py +2141 -0
  1003. scipy/signal/tests/test_splines.py +427 -0
  1004. scipy/signal/tests/test_upfirdn.py +322 -0
  1005. scipy/signal/tests/test_waveforms.py +400 -0
  1006. scipy/signal/tests/test_wavelets.py +59 -0
  1007. scipy/signal/tests/test_windows.py +987 -0
  1008. scipy/signal/waveforms.py +20 -0
  1009. scipy/signal/wavelets.py +17 -0
  1010. scipy/signal/windows/__init__.py +52 -0
  1011. scipy/signal/windows/_windows.py +2513 -0
  1012. scipy/signal/windows/windows.py +23 -0
  1013. scipy/sparse/__init__.py +350 -0
  1014. scipy/sparse/_base.py +1613 -0
  1015. scipy/sparse/_bsr.py +880 -0
  1016. scipy/sparse/_compressed.py +1328 -0
  1017. scipy/sparse/_construct.py +1454 -0
  1018. scipy/sparse/_coo.py +1581 -0
  1019. scipy/sparse/_csc.py +367 -0
  1020. scipy/sparse/_csparsetools.cp312-win_arm64.lib +0 -0
  1021. scipy/sparse/_csparsetools.cp312-win_arm64.pyd +0 -0
  1022. scipy/sparse/_csr.py +558 -0
  1023. scipy/sparse/_data.py +569 -0
  1024. scipy/sparse/_dia.py +677 -0
  1025. scipy/sparse/_dok.py +669 -0
  1026. scipy/sparse/_extract.py +178 -0
  1027. scipy/sparse/_index.py +444 -0
  1028. scipy/sparse/_lil.py +632 -0
  1029. scipy/sparse/_matrix.py +169 -0
  1030. scipy/sparse/_matrix_io.py +167 -0
  1031. scipy/sparse/_sparsetools.cp312-win_arm64.lib +0 -0
  1032. scipy/sparse/_sparsetools.cp312-win_arm64.pyd +0 -0
  1033. scipy/sparse/_spfuncs.py +76 -0
  1034. scipy/sparse/_sputils.py +632 -0
  1035. scipy/sparse/base.py +24 -0
  1036. scipy/sparse/bsr.py +22 -0
  1037. scipy/sparse/compressed.py +20 -0
  1038. scipy/sparse/construct.py +38 -0
  1039. scipy/sparse/coo.py +23 -0
  1040. scipy/sparse/csc.py +22 -0
  1041. scipy/sparse/csgraph/__init__.py +210 -0
  1042. scipy/sparse/csgraph/_flow.cp312-win_arm64.lib +0 -0
  1043. scipy/sparse/csgraph/_flow.cp312-win_arm64.pyd +0 -0
  1044. scipy/sparse/csgraph/_laplacian.py +563 -0
  1045. scipy/sparse/csgraph/_matching.cp312-win_arm64.lib +0 -0
  1046. scipy/sparse/csgraph/_matching.cp312-win_arm64.pyd +0 -0
  1047. scipy/sparse/csgraph/_min_spanning_tree.cp312-win_arm64.lib +0 -0
  1048. scipy/sparse/csgraph/_min_spanning_tree.cp312-win_arm64.pyd +0 -0
  1049. scipy/sparse/csgraph/_reordering.cp312-win_arm64.lib +0 -0
  1050. scipy/sparse/csgraph/_reordering.cp312-win_arm64.pyd +0 -0
  1051. scipy/sparse/csgraph/_shortest_path.cp312-win_arm64.lib +0 -0
  1052. scipy/sparse/csgraph/_shortest_path.cp312-win_arm64.pyd +0 -0
  1053. scipy/sparse/csgraph/_tools.cp312-win_arm64.lib +0 -0
  1054. scipy/sparse/csgraph/_tools.cp312-win_arm64.pyd +0 -0
  1055. scipy/sparse/csgraph/_traversal.cp312-win_arm64.lib +0 -0
  1056. scipy/sparse/csgraph/_traversal.cp312-win_arm64.pyd +0 -0
  1057. scipy/sparse/csgraph/_validation.py +66 -0
  1058. scipy/sparse/csgraph/tests/__init__.py +0 -0
  1059. scipy/sparse/csgraph/tests/test_connected_components.py +119 -0
  1060. scipy/sparse/csgraph/tests/test_conversions.py +61 -0
  1061. scipy/sparse/csgraph/tests/test_flow.py +209 -0
  1062. scipy/sparse/csgraph/tests/test_graph_laplacian.py +368 -0
  1063. scipy/sparse/csgraph/tests/test_matching.py +307 -0
  1064. scipy/sparse/csgraph/tests/test_pydata_sparse.py +197 -0
  1065. scipy/sparse/csgraph/tests/test_reordering.py +70 -0
  1066. scipy/sparse/csgraph/tests/test_shortest_path.py +540 -0
  1067. scipy/sparse/csgraph/tests/test_spanning_tree.py +66 -0
  1068. scipy/sparse/csgraph/tests/test_traversal.py +148 -0
  1069. scipy/sparse/csr.py +22 -0
  1070. scipy/sparse/data.py +18 -0
  1071. scipy/sparse/dia.py +22 -0
  1072. scipy/sparse/dok.py +22 -0
  1073. scipy/sparse/extract.py +23 -0
  1074. scipy/sparse/lil.py +22 -0
  1075. scipy/sparse/linalg/__init__.py +148 -0
  1076. scipy/sparse/linalg/_dsolve/__init__.py +71 -0
  1077. scipy/sparse/linalg/_dsolve/_add_newdocs.py +147 -0
  1078. scipy/sparse/linalg/_dsolve/_superlu.cp312-win_arm64.lib +0 -0
  1079. scipy/sparse/linalg/_dsolve/_superlu.cp312-win_arm64.pyd +0 -0
  1080. scipy/sparse/linalg/_dsolve/linsolve.py +882 -0
  1081. scipy/sparse/linalg/_dsolve/tests/__init__.py +0 -0
  1082. scipy/sparse/linalg/_dsolve/tests/test_linsolve.py +928 -0
  1083. scipy/sparse/linalg/_eigen/__init__.py +22 -0
  1084. scipy/sparse/linalg/_eigen/_svds.py +540 -0
  1085. scipy/sparse/linalg/_eigen/_svds_doc.py +382 -0
  1086. scipy/sparse/linalg/_eigen/arpack/COPYING +45 -0
  1087. scipy/sparse/linalg/_eigen/arpack/__init__.py +20 -0
  1088. scipy/sparse/linalg/_eigen/arpack/_arpack.cp312-win_arm64.lib +0 -0
  1089. scipy/sparse/linalg/_eigen/arpack/_arpack.cp312-win_arm64.pyd +0 -0
  1090. scipy/sparse/linalg/_eigen/arpack/arpack.py +1706 -0
  1091. scipy/sparse/linalg/_eigen/arpack/tests/__init__.py +0 -0
  1092. scipy/sparse/linalg/_eigen/arpack/tests/test_arpack.py +717 -0
  1093. scipy/sparse/linalg/_eigen/lobpcg/__init__.py +16 -0
  1094. scipy/sparse/linalg/_eigen/lobpcg/lobpcg.py +1110 -0
  1095. scipy/sparse/linalg/_eigen/lobpcg/tests/__init__.py +0 -0
  1096. scipy/sparse/linalg/_eigen/lobpcg/tests/test_lobpcg.py +725 -0
  1097. scipy/sparse/linalg/_eigen/tests/__init__.py +0 -0
  1098. scipy/sparse/linalg/_eigen/tests/test_svds.py +886 -0
  1099. scipy/sparse/linalg/_expm_multiply.py +816 -0
  1100. scipy/sparse/linalg/_interface.py +920 -0
  1101. scipy/sparse/linalg/_isolve/__init__.py +20 -0
  1102. scipy/sparse/linalg/_isolve/_gcrotmk.py +503 -0
  1103. scipy/sparse/linalg/_isolve/iterative.py +1051 -0
  1104. scipy/sparse/linalg/_isolve/lgmres.py +230 -0
  1105. scipy/sparse/linalg/_isolve/lsmr.py +486 -0
  1106. scipy/sparse/linalg/_isolve/lsqr.py +589 -0
  1107. scipy/sparse/linalg/_isolve/minres.py +372 -0
  1108. scipy/sparse/linalg/_isolve/tests/__init__.py +0 -0
  1109. scipy/sparse/linalg/_isolve/tests/test_gcrotmk.py +183 -0
  1110. scipy/sparse/linalg/_isolve/tests/test_iterative.py +809 -0
  1111. scipy/sparse/linalg/_isolve/tests/test_lgmres.py +225 -0
  1112. scipy/sparse/linalg/_isolve/tests/test_lsmr.py +185 -0
  1113. scipy/sparse/linalg/_isolve/tests/test_lsqr.py +120 -0
  1114. scipy/sparse/linalg/_isolve/tests/test_minres.py +97 -0
  1115. scipy/sparse/linalg/_isolve/tests/test_utils.py +9 -0
  1116. scipy/sparse/linalg/_isolve/tfqmr.py +179 -0
  1117. scipy/sparse/linalg/_isolve/utils.py +121 -0
  1118. scipy/sparse/linalg/_matfuncs.py +940 -0
  1119. scipy/sparse/linalg/_norm.py +195 -0
  1120. scipy/sparse/linalg/_onenormest.py +467 -0
  1121. scipy/sparse/linalg/_propack/_cpropack.cp312-win_arm64.lib +0 -0
  1122. scipy/sparse/linalg/_propack/_cpropack.cp312-win_arm64.pyd +0 -0
  1123. scipy/sparse/linalg/_propack/_dpropack.cp312-win_arm64.lib +0 -0
  1124. scipy/sparse/linalg/_propack/_dpropack.cp312-win_arm64.pyd +0 -0
  1125. scipy/sparse/linalg/_propack/_spropack.cp312-win_arm64.lib +0 -0
  1126. scipy/sparse/linalg/_propack/_spropack.cp312-win_arm64.pyd +0 -0
  1127. scipy/sparse/linalg/_propack/_zpropack.cp312-win_arm64.lib +0 -0
  1128. scipy/sparse/linalg/_propack/_zpropack.cp312-win_arm64.pyd +0 -0
  1129. scipy/sparse/linalg/_special_sparse_arrays.py +949 -0
  1130. scipy/sparse/linalg/_svdp.py +309 -0
  1131. scipy/sparse/linalg/dsolve.py +22 -0
  1132. scipy/sparse/linalg/eigen.py +21 -0
  1133. scipy/sparse/linalg/interface.py +20 -0
  1134. scipy/sparse/linalg/isolve.py +22 -0
  1135. scipy/sparse/linalg/matfuncs.py +18 -0
  1136. scipy/sparse/linalg/tests/__init__.py +0 -0
  1137. scipy/sparse/linalg/tests/propack_test_data.npz +0 -0
  1138. scipy/sparse/linalg/tests/test_expm_multiply.py +367 -0
  1139. scipy/sparse/linalg/tests/test_interface.py +561 -0
  1140. scipy/sparse/linalg/tests/test_matfuncs.py +592 -0
  1141. scipy/sparse/linalg/tests/test_norm.py +154 -0
  1142. scipy/sparse/linalg/tests/test_onenormest.py +252 -0
  1143. scipy/sparse/linalg/tests/test_propack.py +165 -0
  1144. scipy/sparse/linalg/tests/test_pydata_sparse.py +272 -0
  1145. scipy/sparse/linalg/tests/test_special_sparse_arrays.py +337 -0
  1146. scipy/sparse/sparsetools.py +17 -0
  1147. scipy/sparse/spfuncs.py +17 -0
  1148. scipy/sparse/sputils.py +17 -0
  1149. scipy/sparse/tests/__init__.py +0 -0
  1150. scipy/sparse/tests/data/csc_py2.npz +0 -0
  1151. scipy/sparse/tests/data/csc_py3.npz +0 -0
  1152. scipy/sparse/tests/test_arithmetic1d.py +341 -0
  1153. scipy/sparse/tests/test_array_api.py +561 -0
  1154. scipy/sparse/tests/test_base.py +5870 -0
  1155. scipy/sparse/tests/test_common1d.py +447 -0
  1156. scipy/sparse/tests/test_construct.py +872 -0
  1157. scipy/sparse/tests/test_coo.py +1119 -0
  1158. scipy/sparse/tests/test_csc.py +98 -0
  1159. scipy/sparse/tests/test_csr.py +214 -0
  1160. scipy/sparse/tests/test_dok.py +209 -0
  1161. scipy/sparse/tests/test_extract.py +51 -0
  1162. scipy/sparse/tests/test_indexing1d.py +603 -0
  1163. scipy/sparse/tests/test_matrix_io.py +109 -0
  1164. scipy/sparse/tests/test_minmax1d.py +128 -0
  1165. scipy/sparse/tests/test_sparsetools.py +344 -0
  1166. scipy/sparse/tests/test_spfuncs.py +97 -0
  1167. scipy/sparse/tests/test_sputils.py +424 -0
  1168. scipy/spatial/__init__.py +129 -0
  1169. scipy/spatial/_ckdtree.cp312-win_arm64.lib +0 -0
  1170. scipy/spatial/_ckdtree.cp312-win_arm64.pyd +0 -0
  1171. scipy/spatial/_distance_pybind.cp312-win_arm64.lib +0 -0
  1172. scipy/spatial/_distance_pybind.cp312-win_arm64.pyd +0 -0
  1173. scipy/spatial/_distance_wrap.cp312-win_arm64.lib +0 -0
  1174. scipy/spatial/_distance_wrap.cp312-win_arm64.pyd +0 -0
  1175. scipy/spatial/_geometric_slerp.py +238 -0
  1176. scipy/spatial/_hausdorff.cp312-win_arm64.lib +0 -0
  1177. scipy/spatial/_hausdorff.cp312-win_arm64.pyd +0 -0
  1178. scipy/spatial/_kdtree.py +920 -0
  1179. scipy/spatial/_plotutils.py +274 -0
  1180. scipy/spatial/_procrustes.py +132 -0
  1181. scipy/spatial/_qhull.cp312-win_arm64.lib +0 -0
  1182. scipy/spatial/_qhull.cp312-win_arm64.pyd +0 -0
  1183. scipy/spatial/_qhull.pyi +213 -0
  1184. scipy/spatial/_spherical_voronoi.py +341 -0
  1185. scipy/spatial/_voronoi.cp312-win_arm64.lib +0 -0
  1186. scipy/spatial/_voronoi.cp312-win_arm64.pyd +0 -0
  1187. scipy/spatial/_voronoi.pyi +4 -0
  1188. scipy/spatial/ckdtree.py +18 -0
  1189. scipy/spatial/distance.py +3147 -0
  1190. scipy/spatial/distance.pyi +210 -0
  1191. scipy/spatial/kdtree.py +25 -0
  1192. scipy/spatial/qhull.py +25 -0
  1193. scipy/spatial/qhull_src/COPYING_QHULL.txt +39 -0
  1194. scipy/spatial/tests/__init__.py +0 -0
  1195. scipy/spatial/tests/data/cdist-X1.txt +10 -0
  1196. scipy/spatial/tests/data/cdist-X2.txt +20 -0
  1197. scipy/spatial/tests/data/degenerate_pointset.npz +0 -0
  1198. scipy/spatial/tests/data/iris.txt +150 -0
  1199. scipy/spatial/tests/data/pdist-boolean-inp.txt +20 -0
  1200. scipy/spatial/tests/data/pdist-chebyshev-ml-iris.txt +1 -0
  1201. scipy/spatial/tests/data/pdist-chebyshev-ml.txt +1 -0
  1202. scipy/spatial/tests/data/pdist-cityblock-ml-iris.txt +1 -0
  1203. scipy/spatial/tests/data/pdist-cityblock-ml.txt +1 -0
  1204. scipy/spatial/tests/data/pdist-correlation-ml-iris.txt +1 -0
  1205. scipy/spatial/tests/data/pdist-correlation-ml.txt +1 -0
  1206. scipy/spatial/tests/data/pdist-cosine-ml-iris.txt +1 -0
  1207. scipy/spatial/tests/data/pdist-cosine-ml.txt +1 -0
  1208. scipy/spatial/tests/data/pdist-double-inp.txt +20 -0
  1209. scipy/spatial/tests/data/pdist-euclidean-ml-iris.txt +1 -0
  1210. scipy/spatial/tests/data/pdist-euclidean-ml.txt +1 -0
  1211. scipy/spatial/tests/data/pdist-hamming-ml.txt +1 -0
  1212. scipy/spatial/tests/data/pdist-jaccard-ml.txt +1 -0
  1213. scipy/spatial/tests/data/pdist-jensenshannon-ml-iris.txt +1 -0
  1214. scipy/spatial/tests/data/pdist-jensenshannon-ml.txt +1 -0
  1215. scipy/spatial/tests/data/pdist-minkowski-3.2-ml-iris.txt +1 -0
  1216. scipy/spatial/tests/data/pdist-minkowski-3.2-ml.txt +1 -0
  1217. scipy/spatial/tests/data/pdist-minkowski-5.8-ml-iris.txt +1 -0
  1218. scipy/spatial/tests/data/pdist-seuclidean-ml-iris.txt +1 -0
  1219. scipy/spatial/tests/data/pdist-seuclidean-ml.txt +1 -0
  1220. scipy/spatial/tests/data/pdist-spearman-ml.txt +1 -0
  1221. scipy/spatial/tests/data/random-bool-data.txt +100 -0
  1222. scipy/spatial/tests/data/random-double-data.txt +100 -0
  1223. scipy/spatial/tests/data/random-int-data.txt +100 -0
  1224. scipy/spatial/tests/data/random-uint-data.txt +100 -0
  1225. scipy/spatial/tests/data/selfdual-4d-polytope.txt +27 -0
  1226. scipy/spatial/tests/test__plotutils.py +91 -0
  1227. scipy/spatial/tests/test__procrustes.py +116 -0
  1228. scipy/spatial/tests/test_distance.py +2389 -0
  1229. scipy/spatial/tests/test_hausdorff.py +199 -0
  1230. scipy/spatial/tests/test_kdtree.py +1536 -0
  1231. scipy/spatial/tests/test_qhull.py +1313 -0
  1232. scipy/spatial/tests/test_slerp.py +417 -0
  1233. scipy/spatial/tests/test_spherical_voronoi.py +358 -0
  1234. scipy/spatial/transform/__init__.py +31 -0
  1235. scipy/spatial/transform/_rigid_transform.cp312-win_arm64.lib +0 -0
  1236. scipy/spatial/transform/_rigid_transform.cp312-win_arm64.pyd +0 -0
  1237. scipy/spatial/transform/_rotation.cp312-win_arm64.lib +0 -0
  1238. scipy/spatial/transform/_rotation.cp312-win_arm64.pyd +0 -0
  1239. scipy/spatial/transform/_rotation_groups.py +140 -0
  1240. scipy/spatial/transform/_rotation_spline.py +460 -0
  1241. scipy/spatial/transform/rotation.py +21 -0
  1242. scipy/spatial/transform/tests/__init__.py +0 -0
  1243. scipy/spatial/transform/tests/test_rigid_transform.py +1221 -0
  1244. scipy/spatial/transform/tests/test_rotation.py +2569 -0
  1245. scipy/spatial/transform/tests/test_rotation_groups.py +169 -0
  1246. scipy/spatial/transform/tests/test_rotation_spline.py +183 -0
  1247. scipy/special/__init__.pxd +1 -0
  1248. scipy/special/__init__.py +841 -0
  1249. scipy/special/_add_newdocs.py +9961 -0
  1250. scipy/special/_basic.py +3576 -0
  1251. scipy/special/_comb.cp312-win_arm64.lib +0 -0
  1252. scipy/special/_comb.cp312-win_arm64.pyd +0 -0
  1253. scipy/special/_ellip_harm.py +214 -0
  1254. scipy/special/_ellip_harm_2.cp312-win_arm64.lib +0 -0
  1255. scipy/special/_ellip_harm_2.cp312-win_arm64.pyd +0 -0
  1256. scipy/special/_gufuncs.cp312-win_arm64.lib +0 -0
  1257. scipy/special/_gufuncs.cp312-win_arm64.pyd +0 -0
  1258. scipy/special/_input_validation.py +17 -0
  1259. scipy/special/_lambertw.py +149 -0
  1260. scipy/special/_logsumexp.py +426 -0
  1261. scipy/special/_mptestutils.py +453 -0
  1262. scipy/special/_multiufuncs.py +610 -0
  1263. scipy/special/_orthogonal.py +2592 -0
  1264. scipy/special/_orthogonal.pyi +330 -0
  1265. scipy/special/_precompute/__init__.py +0 -0
  1266. scipy/special/_precompute/cosine_cdf.py +17 -0
  1267. scipy/special/_precompute/expn_asy.py +54 -0
  1268. scipy/special/_precompute/gammainc_asy.py +116 -0
  1269. scipy/special/_precompute/gammainc_data.py +124 -0
  1270. scipy/special/_precompute/hyp2f1_data.py +484 -0
  1271. scipy/special/_precompute/lambertw.py +68 -0
  1272. scipy/special/_precompute/loggamma.py +43 -0
  1273. scipy/special/_precompute/struve_convergence.py +131 -0
  1274. scipy/special/_precompute/utils.py +38 -0
  1275. scipy/special/_precompute/wright_bessel.py +342 -0
  1276. scipy/special/_precompute/wright_bessel_data.py +152 -0
  1277. scipy/special/_precompute/wrightomega.py +41 -0
  1278. scipy/special/_precompute/zetac.py +27 -0
  1279. scipy/special/_sf_error.py +15 -0
  1280. scipy/special/_specfun.cp312-win_arm64.lib +0 -0
  1281. scipy/special/_specfun.cp312-win_arm64.pyd +0 -0
  1282. scipy/special/_special_ufuncs.cp312-win_arm64.lib +0 -0
  1283. scipy/special/_special_ufuncs.cp312-win_arm64.pyd +0 -0
  1284. scipy/special/_spfun_stats.py +106 -0
  1285. scipy/special/_spherical_bessel.py +397 -0
  1286. scipy/special/_support_alternative_backends.py +295 -0
  1287. scipy/special/_test_internal.cp312-win_arm64.lib +0 -0
  1288. scipy/special/_test_internal.cp312-win_arm64.pyd +0 -0
  1289. scipy/special/_test_internal.pyi +9 -0
  1290. scipy/special/_testutils.py +321 -0
  1291. scipy/special/_ufuncs.cp312-win_arm64.lib +0 -0
  1292. scipy/special/_ufuncs.cp312-win_arm64.pyd +0 -0
  1293. scipy/special/_ufuncs.pyi +522 -0
  1294. scipy/special/_ufuncs.pyx +13173 -0
  1295. scipy/special/_ufuncs_cxx.cp312-win_arm64.lib +0 -0
  1296. scipy/special/_ufuncs_cxx.cp312-win_arm64.pyd +0 -0
  1297. scipy/special/_ufuncs_cxx.pxd +142 -0
  1298. scipy/special/_ufuncs_cxx.pyx +427 -0
  1299. scipy/special/_ufuncs_cxx_defs.h +147 -0
  1300. scipy/special/_ufuncs_defs.h +57 -0
  1301. scipy/special/add_newdocs.py +15 -0
  1302. scipy/special/basic.py +87 -0
  1303. scipy/special/cython_special.cp312-win_arm64.lib +0 -0
  1304. scipy/special/cython_special.cp312-win_arm64.pyd +0 -0
  1305. scipy/special/cython_special.pxd +259 -0
  1306. scipy/special/cython_special.pyi +3 -0
  1307. scipy/special/orthogonal.py +45 -0
  1308. scipy/special/sf_error.py +20 -0
  1309. scipy/special/specfun.py +24 -0
  1310. scipy/special/spfun_stats.py +17 -0
  1311. scipy/special/tests/__init__.py +0 -0
  1312. scipy/special/tests/_cython_examples/extending.pyx +12 -0
  1313. scipy/special/tests/_cython_examples/meson.build +34 -0
  1314. scipy/special/tests/data/__init__.py +0 -0
  1315. scipy/special/tests/data/boost.npz +0 -0
  1316. scipy/special/tests/data/gsl.npz +0 -0
  1317. scipy/special/tests/data/local.npz +0 -0
  1318. scipy/special/tests/test_basic.py +4815 -0
  1319. scipy/special/tests/test_bdtr.py +112 -0
  1320. scipy/special/tests/test_boost_ufuncs.py +64 -0
  1321. scipy/special/tests/test_boxcox.py +125 -0
  1322. scipy/special/tests/test_cdflib.py +712 -0
  1323. scipy/special/tests/test_cdft_asymptotic.py +49 -0
  1324. scipy/special/tests/test_cephes_intp_cast.py +29 -0
  1325. scipy/special/tests/test_cosine_distr.py +83 -0
  1326. scipy/special/tests/test_cython_special.py +363 -0
  1327. scipy/special/tests/test_data.py +719 -0
  1328. scipy/special/tests/test_dd.py +42 -0
  1329. scipy/special/tests/test_digamma.py +45 -0
  1330. scipy/special/tests/test_ellip_harm.py +278 -0
  1331. scipy/special/tests/test_erfinv.py +89 -0
  1332. scipy/special/tests/test_exponential_integrals.py +118 -0
  1333. scipy/special/tests/test_extending.py +28 -0
  1334. scipy/special/tests/test_faddeeva.py +85 -0
  1335. scipy/special/tests/test_gamma.py +12 -0
  1336. scipy/special/tests/test_gammainc.py +152 -0
  1337. scipy/special/tests/test_hyp2f1.py +2566 -0
  1338. scipy/special/tests/test_hypergeometric.py +234 -0
  1339. scipy/special/tests/test_iv_ratio.py +249 -0
  1340. scipy/special/tests/test_kolmogorov.py +491 -0
  1341. scipy/special/tests/test_lambertw.py +109 -0
  1342. scipy/special/tests/test_legendre.py +1518 -0
  1343. scipy/special/tests/test_log1mexp.py +85 -0
  1344. scipy/special/tests/test_loggamma.py +70 -0
  1345. scipy/special/tests/test_logit.py +162 -0
  1346. scipy/special/tests/test_logsumexp.py +469 -0
  1347. scipy/special/tests/test_mpmath.py +2293 -0
  1348. scipy/special/tests/test_nan_inputs.py +65 -0
  1349. scipy/special/tests/test_ndtr.py +77 -0
  1350. scipy/special/tests/test_ndtri_exp.py +94 -0
  1351. scipy/special/tests/test_orthogonal.py +821 -0
  1352. scipy/special/tests/test_orthogonal_eval.py +275 -0
  1353. scipy/special/tests/test_owens_t.py +53 -0
  1354. scipy/special/tests/test_pcf.py +24 -0
  1355. scipy/special/tests/test_pdtr.py +48 -0
  1356. scipy/special/tests/test_powm1.py +65 -0
  1357. scipy/special/tests/test_precompute_expn_asy.py +24 -0
  1358. scipy/special/tests/test_precompute_gammainc.py +108 -0
  1359. scipy/special/tests/test_precompute_utils.py +36 -0
  1360. scipy/special/tests/test_round.py +18 -0
  1361. scipy/special/tests/test_sf_error.py +146 -0
  1362. scipy/special/tests/test_sici.py +36 -0
  1363. scipy/special/tests/test_specfun.py +48 -0
  1364. scipy/special/tests/test_spence.py +32 -0
  1365. scipy/special/tests/test_spfun_stats.py +61 -0
  1366. scipy/special/tests/test_sph_harm.py +85 -0
  1367. scipy/special/tests/test_spherical_bessel.py +400 -0
  1368. scipy/special/tests/test_support_alternative_backends.py +248 -0
  1369. scipy/special/tests/test_trig.py +72 -0
  1370. scipy/special/tests/test_ufunc_signatures.py +46 -0
  1371. scipy/special/tests/test_wright_bessel.py +205 -0
  1372. scipy/special/tests/test_wrightomega.py +117 -0
  1373. scipy/special/tests/test_zeta.py +301 -0
  1374. scipy/stats/__init__.py +670 -0
  1375. scipy/stats/_ansari_swilk_statistics.cp312-win_arm64.lib +0 -0
  1376. scipy/stats/_ansari_swilk_statistics.cp312-win_arm64.pyd +0 -0
  1377. scipy/stats/_axis_nan_policy.py +692 -0
  1378. scipy/stats/_biasedurn.cp312-win_arm64.lib +0 -0
  1379. scipy/stats/_biasedurn.cp312-win_arm64.pyd +0 -0
  1380. scipy/stats/_biasedurn.pxd +27 -0
  1381. scipy/stats/_binned_statistic.py +795 -0
  1382. scipy/stats/_binomtest.py +375 -0
  1383. scipy/stats/_bws_test.py +177 -0
  1384. scipy/stats/_censored_data.py +459 -0
  1385. scipy/stats/_common.py +5 -0
  1386. scipy/stats/_constants.py +42 -0
  1387. scipy/stats/_continued_fraction.py +387 -0
  1388. scipy/stats/_continuous_distns.py +12486 -0
  1389. scipy/stats/_correlation.py +210 -0
  1390. scipy/stats/_covariance.py +636 -0
  1391. scipy/stats/_crosstab.py +204 -0
  1392. scipy/stats/_discrete_distns.py +2098 -0
  1393. scipy/stats/_distn_infrastructure.py +4201 -0
  1394. scipy/stats/_distr_params.py +299 -0
  1395. scipy/stats/_distribution_infrastructure.py +5750 -0
  1396. scipy/stats/_entropy.py +428 -0
  1397. scipy/stats/_finite_differences.py +145 -0
  1398. scipy/stats/_fit.py +1351 -0
  1399. scipy/stats/_hypotests.py +2060 -0
  1400. scipy/stats/_kde.py +732 -0
  1401. scipy/stats/_ksstats.py +600 -0
  1402. scipy/stats/_levy_stable/__init__.py +1231 -0
  1403. scipy/stats/_levy_stable/levyst.cp312-win_arm64.lib +0 -0
  1404. scipy/stats/_levy_stable/levyst.cp312-win_arm64.pyd +0 -0
  1405. scipy/stats/_mannwhitneyu.py +492 -0
  1406. scipy/stats/_mgc.py +550 -0
  1407. scipy/stats/_morestats.py +4626 -0
  1408. scipy/stats/_mstats_basic.py +3658 -0
  1409. scipy/stats/_mstats_extras.py +521 -0
  1410. scipy/stats/_multicomp.py +449 -0
  1411. scipy/stats/_multivariate.py +7281 -0
  1412. scipy/stats/_new_distributions.py +452 -0
  1413. scipy/stats/_odds_ratio.py +466 -0
  1414. scipy/stats/_page_trend_test.py +486 -0
  1415. scipy/stats/_probability_distribution.py +1964 -0
  1416. scipy/stats/_qmc.py +2956 -0
  1417. scipy/stats/_qmc_cy.cp312-win_arm64.lib +0 -0
  1418. scipy/stats/_qmc_cy.cp312-win_arm64.pyd +0 -0
  1419. scipy/stats/_qmc_cy.pyi +54 -0
  1420. scipy/stats/_qmvnt.py +454 -0
  1421. scipy/stats/_qmvnt_cy.cp312-win_arm64.lib +0 -0
  1422. scipy/stats/_qmvnt_cy.cp312-win_arm64.pyd +0 -0
  1423. scipy/stats/_quantile.py +335 -0
  1424. scipy/stats/_rcont/__init__.py +4 -0
  1425. scipy/stats/_rcont/rcont.cp312-win_arm64.lib +0 -0
  1426. scipy/stats/_rcont/rcont.cp312-win_arm64.pyd +0 -0
  1427. scipy/stats/_relative_risk.py +263 -0
  1428. scipy/stats/_resampling.py +2352 -0
  1429. scipy/stats/_result_classes.py +40 -0
  1430. scipy/stats/_sampling.py +1314 -0
  1431. scipy/stats/_sensitivity_analysis.py +713 -0
  1432. scipy/stats/_sobol.cp312-win_arm64.lib +0 -0
  1433. scipy/stats/_sobol.cp312-win_arm64.pyd +0 -0
  1434. scipy/stats/_sobol.pyi +54 -0
  1435. scipy/stats/_sobol_direction_numbers.npz +0 -0
  1436. scipy/stats/_stats.cp312-win_arm64.lib +0 -0
  1437. scipy/stats/_stats.cp312-win_arm64.pyd +0 -0
  1438. scipy/stats/_stats.pxd +10 -0
  1439. scipy/stats/_stats_mstats_common.py +322 -0
  1440. scipy/stats/_stats_py.py +11089 -0
  1441. scipy/stats/_stats_pythran.cp312-win_arm64.lib +0 -0
  1442. scipy/stats/_stats_pythran.cp312-win_arm64.pyd +0 -0
  1443. scipy/stats/_survival.py +683 -0
  1444. scipy/stats/_tukeylambda_stats.py +199 -0
  1445. scipy/stats/_unuran/__init__.py +0 -0
  1446. scipy/stats/_unuran/unuran_wrapper.cp312-win_arm64.lib +0 -0
  1447. scipy/stats/_unuran/unuran_wrapper.cp312-win_arm64.pyd +0 -0
  1448. scipy/stats/_unuran/unuran_wrapper.pyi +179 -0
  1449. scipy/stats/_variation.py +126 -0
  1450. scipy/stats/_warnings_errors.py +38 -0
  1451. scipy/stats/_wilcoxon.py +265 -0
  1452. scipy/stats/biasedurn.py +16 -0
  1453. scipy/stats/contingency.py +521 -0
  1454. scipy/stats/distributions.py +24 -0
  1455. scipy/stats/kde.py +18 -0
  1456. scipy/stats/morestats.py +27 -0
  1457. scipy/stats/mstats.py +140 -0
  1458. scipy/stats/mstats_basic.py +42 -0
  1459. scipy/stats/mstats_extras.py +25 -0
  1460. scipy/stats/mvn.py +17 -0
  1461. scipy/stats/qmc.py +236 -0
  1462. scipy/stats/sampling.py +73 -0
  1463. scipy/stats/stats.py +41 -0
  1464. scipy/stats/tests/__init__.py +0 -0
  1465. scipy/stats/tests/common_tests.py +356 -0
  1466. scipy/stats/tests/data/_mvt.py +171 -0
  1467. scipy/stats/tests/data/fisher_exact_results_from_r.py +607 -0
  1468. scipy/stats/tests/data/jf_skew_t_gamlss_pdf_data.npy +0 -0
  1469. scipy/stats/tests/data/levy_stable/stable-Z1-cdf-sample-data.npy +0 -0
  1470. scipy/stats/tests/data/levy_stable/stable-Z1-pdf-sample-data.npy +0 -0
  1471. scipy/stats/tests/data/levy_stable/stable-loc-scale-sample-data.npy +0 -0
  1472. scipy/stats/tests/data/nist_anova/AtmWtAg.dat +108 -0
  1473. scipy/stats/tests/data/nist_anova/SiRstv.dat +85 -0
  1474. scipy/stats/tests/data/nist_anova/SmLs01.dat +249 -0
  1475. scipy/stats/tests/data/nist_anova/SmLs02.dat +1869 -0
  1476. scipy/stats/tests/data/nist_anova/SmLs03.dat +18069 -0
  1477. scipy/stats/tests/data/nist_anova/SmLs04.dat +249 -0
  1478. scipy/stats/tests/data/nist_anova/SmLs05.dat +1869 -0
  1479. scipy/stats/tests/data/nist_anova/SmLs06.dat +18069 -0
  1480. scipy/stats/tests/data/nist_anova/SmLs07.dat +249 -0
  1481. scipy/stats/tests/data/nist_anova/SmLs08.dat +1869 -0
  1482. scipy/stats/tests/data/nist_anova/SmLs09.dat +18069 -0
  1483. scipy/stats/tests/data/nist_linregress/Norris.dat +97 -0
  1484. scipy/stats/tests/data/rel_breitwigner_pdf_sample_data_ROOT.npy +0 -0
  1485. scipy/stats/tests/data/studentized_range_mpmath_ref.json +1499 -0
  1486. scipy/stats/tests/test_axis_nan_policy.py +1388 -0
  1487. scipy/stats/tests/test_binned_statistic.py +568 -0
  1488. scipy/stats/tests/test_censored_data.py +152 -0
  1489. scipy/stats/tests/test_contingency.py +294 -0
  1490. scipy/stats/tests/test_continued_fraction.py +173 -0
  1491. scipy/stats/tests/test_continuous.py +2198 -0
  1492. scipy/stats/tests/test_continuous_basic.py +1053 -0
  1493. scipy/stats/tests/test_continuous_fit_censored.py +683 -0
  1494. scipy/stats/tests/test_correlation.py +80 -0
  1495. scipy/stats/tests/test_crosstab.py +115 -0
  1496. scipy/stats/tests/test_discrete_basic.py +580 -0
  1497. scipy/stats/tests/test_discrete_distns.py +700 -0
  1498. scipy/stats/tests/test_distributions.py +10413 -0
  1499. scipy/stats/tests/test_entropy.py +322 -0
  1500. scipy/stats/tests/test_fast_gen_inversion.py +435 -0
  1501. scipy/stats/tests/test_fit.py +1090 -0
  1502. scipy/stats/tests/test_hypotests.py +1991 -0
  1503. scipy/stats/tests/test_kdeoth.py +676 -0
  1504. scipy/stats/tests/test_marray.py +289 -0
  1505. scipy/stats/tests/test_mgc.py +217 -0
  1506. scipy/stats/tests/test_morestats.py +3259 -0
  1507. scipy/stats/tests/test_mstats_basic.py +2071 -0
  1508. scipy/stats/tests/test_mstats_extras.py +172 -0
  1509. scipy/stats/tests/test_multicomp.py +405 -0
  1510. scipy/stats/tests/test_multivariate.py +4381 -0
  1511. scipy/stats/tests/test_odds_ratio.py +148 -0
  1512. scipy/stats/tests/test_qmc.py +1492 -0
  1513. scipy/stats/tests/test_quantile.py +199 -0
  1514. scipy/stats/tests/test_rank.py +345 -0
  1515. scipy/stats/tests/test_relative_risk.py +95 -0
  1516. scipy/stats/tests/test_resampling.py +2000 -0
  1517. scipy/stats/tests/test_sampling.py +1450 -0
  1518. scipy/stats/tests/test_sensitivity_analysis.py +310 -0
  1519. scipy/stats/tests/test_stats.py +9707 -0
  1520. scipy/stats/tests/test_survival.py +466 -0
  1521. scipy/stats/tests/test_tukeylambda_stats.py +85 -0
  1522. scipy/stats/tests/test_variation.py +216 -0
  1523. scipy/version.py +12 -0
  1524. scipy-1.16.2.dist-info/DELVEWHEEL +2 -0
  1525. scipy-1.16.2.dist-info/LICENSE.txt +912 -0
  1526. scipy-1.16.2.dist-info/METADATA +1061 -0
  1527. scipy-1.16.2.dist-info/RECORD +1530 -0
  1528. scipy-1.16.2.dist-info/WHEEL +4 -0
  1529. scipy.libs/msvcp140-5f1c5dd31916990d94181e07bc3afb32.dll +0 -0
  1530. scipy.libs/scipy_openblas-f3ac85b1f412f7e86514c923dc4058d1.dll +0 -0
@@ -0,0 +1,4169 @@
1
+ #__docformat__ = "restructuredtext en"
2
+ # ******NOTICE***************
3
+ # optimize.py module by Travis E. Oliphant
4
+ #
5
+ # You may copy and use this module as you see fit with no
6
+ # guarantee implied provided you keep this notice in all copies.
7
+ # *****END NOTICE************
8
+
9
+ # A collection of optimization algorithms. Version 0.5
10
+ # CHANGES
11
+ # Added fminbound (July 2001)
12
+ # Added brute (Aug. 2002)
13
+ # Finished line search satisfying strong Wolfe conditions (Mar. 2004)
14
+ # Updated strong Wolfe conditions line search to use
15
+ # cubic-interpolation (Mar. 2004)
16
+
17
+
18
+ # Minimization routines
19
+
20
+ __all__ = ['fmin', 'fmin_powell', 'fmin_bfgs', 'fmin_ncg', 'fmin_cg',
21
+ 'fminbound', 'brent', 'golden', 'bracket', 'rosen', 'rosen_der',
22
+ 'rosen_hess', 'rosen_hess_prod', 'brute', 'approx_fprime',
23
+ 'line_search', 'check_grad', 'OptimizeResult', 'show_options',
24
+ 'OptimizeWarning']
25
+
26
+ __docformat__ = "restructuredtext en"
27
+
28
+ import math
29
+ import warnings
30
+ import sys
31
+ import inspect
32
+ from numpy import eye, argmin, zeros, shape, asarray, sqrt
33
+ import numpy as np
34
+ from scipy.linalg import cholesky, issymmetric, LinAlgError
35
+ from scipy.sparse.linalg import LinearOperator
36
+ from ._linesearch import (line_search_wolfe1, line_search_wolfe2,
37
+ line_search_wolfe2 as line_search,
38
+ LineSearchWarning)
39
+ from ._numdiff import approx_derivative
40
+ from scipy._lib._util import getfullargspec_no_self as _getfullargspec
41
+ from scipy._lib._util import (MapWrapper, check_random_state, _RichResult,
42
+ _call_callback_maybe_halt, _transition_to_rng)
43
+ from scipy.optimize._differentiable_functions import ScalarFunction, FD_METHODS
44
+ from scipy._lib._array_api import array_namespace, xp_capabilities, xp_promote
45
+ from scipy._lib import array_api_extra as xpx
46
+
47
+
48
+ # standard status messages of optimizers
49
+ _status_message = {'success': 'Optimization terminated successfully.',
50
+ 'maxfev': 'Maximum number of function evaluations has '
51
+ 'been exceeded.',
52
+ 'maxiter': 'Maximum number of iterations has been '
53
+ 'exceeded.',
54
+ 'pr_loss': 'Desired error not necessarily achieved due '
55
+ 'to precision loss.',
56
+ 'nan': 'NaN result encountered.',
57
+ 'out_of_bounds': 'The result is outside of the provided '
58
+ 'bounds.'}
59
+
60
+
61
+ class MemoizeJac:
62
+ """Decorator that caches the return values of a function returning ``(fun, grad)``
63
+ each time it is called."""
64
+
65
+ def __init__(self, fun):
66
+ self.fun = fun
67
+ self.jac = None
68
+ self._value = None
69
+ self.x = None
70
+
71
+ def _compute_if_needed(self, x, *args):
72
+ if not np.all(x == self.x) or self._value is None or self.jac is None:
73
+ self.x = np.asarray(x).copy()
74
+ fg = self.fun(x, *args)
75
+ self.jac = fg[1]
76
+ self._value = fg[0]
77
+
78
+ def __call__(self, x, *args):
79
+ """ returns the function value """
80
+ self._compute_if_needed(x, *args)
81
+ return self._value
82
+
83
+ def derivative(self, x, *args):
84
+ self._compute_if_needed(x, *args)
85
+ return self.jac
86
+
87
+
88
+ def _wrap_callback(callback, method=None):
89
+ """Wrap a user-provided callback so that attributes can be attached."""
90
+ if callback is None or method in {'tnc', 'slsqp', 'cobyla', 'cobyqa'}:
91
+ return callback # don't wrap
92
+
93
+ sig = inspect.signature(callback)
94
+
95
+ if set(sig.parameters) == {'intermediate_result'}:
96
+ def wrapped_callback(res):
97
+ return callback(intermediate_result=res)
98
+ elif method == 'trust-constr':
99
+ def wrapped_callback(res):
100
+ return callback(np.copy(res.x), res)
101
+ elif method == 'differential_evolution':
102
+ def wrapped_callback(res):
103
+ return callback(np.copy(res.x), res.convergence)
104
+ else:
105
+ def wrapped_callback(res):
106
+ return callback(np.copy(res.x))
107
+
108
+ wrapped_callback.stop_iteration = False
109
+ return wrapped_callback
110
+
111
+
112
+ class OptimizeResult(_RichResult):
113
+ """
114
+ Represents the optimization result.
115
+
116
+ Attributes
117
+ ----------
118
+ x : ndarray
119
+ The solution of the optimization.
120
+ success : bool
121
+ Whether or not the optimizer exited successfully.
122
+ status : int
123
+ Termination status of the optimizer. Its value depends on the
124
+ underlying solver. Refer to `message` for details.
125
+ message : str
126
+ Description of the cause of the termination.
127
+ fun : float
128
+ Value of objective function at `x`.
129
+ jac, hess : ndarray
130
+ Values of objective function's Jacobian and its Hessian at `x` (if
131
+ available). The Hessian may be an approximation, see the documentation
132
+ of the function in question.
133
+ hess_inv : object
134
+ Inverse of the objective function's Hessian; may be an approximation.
135
+ Not available for all solvers. The type of this attribute may be
136
+ either np.ndarray or scipy.sparse.linalg.LinearOperator.
137
+ nfev, njev, nhev : int
138
+ Number of evaluations of the objective functions and of its
139
+ Jacobian and Hessian.
140
+ nit : int
141
+ Number of iterations performed by the optimizer.
142
+ maxcv : float
143
+ The maximum constraint violation.
144
+
145
+ Notes
146
+ -----
147
+ Depending on the specific solver being used, `OptimizeResult` may
148
+ not have all attributes listed here, and they may have additional
149
+ attributes not listed here. Since this class is essentially a
150
+ subclass of dict with attribute accessors, one can see which
151
+ attributes are available using the `OptimizeResult.keys` method.
152
+
153
+ """
154
+ pass
155
+
156
+
157
+ class OptimizeWarning(UserWarning):
158
+ """General warning for :mod:`scipy.optimize`."""
159
+ pass
160
+
161
+ def _check_positive_definite(Hk):
162
+ def is_pos_def(A):
163
+ if issymmetric(A):
164
+ try:
165
+ cholesky(A)
166
+ return True
167
+ except LinAlgError:
168
+ return False
169
+ else:
170
+ return False
171
+ if Hk is not None:
172
+ if not is_pos_def(Hk):
173
+ raise ValueError("'hess_inv0' matrix isn't positive definite.")
174
+
175
+
176
+ def _check_unknown_options(unknown_options):
177
+ if unknown_options:
178
+ msg = ", ".join(map(str, unknown_options.keys()))
179
+ # Stack level 4: this is called from _minimize_*, which is
180
+ # called from another function in SciPy. Level 4 is the first
181
+ # level in user code.
182
+ warnings.warn(f"Unknown solver options: {msg}", OptimizeWarning, stacklevel=4)
183
+
184
+
185
+ def is_finite_scalar(x):
186
+ """Test whether `x` is either a finite scalar or a finite array scalar.
187
+
188
+ """
189
+ return np.size(x) == 1 and np.isfinite(x)
190
+
191
+
192
+ _epsilon = sqrt(np.finfo(float).eps)
193
+
194
+
195
+ def vecnorm(x, ord=2):
196
+ if ord == np.inf:
197
+ return np.amax(np.abs(x))
198
+ elif ord == -np.inf:
199
+ return np.amin(np.abs(x))
200
+ else:
201
+ return np.sum(np.abs(x)**ord, axis=0)**(1.0 / ord)
202
+
203
+
204
+ def _prepare_scalar_function(fun, x0, jac=None, args=(), bounds=None,
205
+ epsilon=None, finite_diff_rel_step=None,
206
+ hess=None, workers=None):
207
+ """
208
+ Creates a ScalarFunction object for use with scalar minimizers
209
+ (BFGS/LBFGSB/SLSQP/TNC/CG/etc).
210
+
211
+ Parameters
212
+ ----------
213
+ fun : callable
214
+ The objective function to be minimized.
215
+
216
+ ``fun(x, *args) -> float``
217
+
218
+ where ``x`` is an 1-D array with shape (n,) and ``args``
219
+ is a tuple of the fixed parameters needed to completely
220
+ specify the function.
221
+ x0 : ndarray, shape (n,)
222
+ Initial guess. Array of real elements of size (n,),
223
+ where 'n' is the number of independent variables.
224
+ jac : {callable, '2-point', '3-point', 'cs', None}, optional
225
+ Method for computing the gradient vector. If it is a callable, it
226
+ should be a function that returns the gradient vector:
227
+
228
+ ``jac(x, *args) -> array_like, shape (n,)``
229
+
230
+ If one of `{'2-point', '3-point', 'cs'}` is selected then the gradient
231
+ is calculated with a relative step for finite differences. If `None`,
232
+ then two-point finite differences with an absolute step is used.
233
+ args : tuple, optional
234
+ Extra arguments passed to the objective function and its
235
+ derivatives (`fun`, `jac` functions).
236
+ bounds : sequence, optional
237
+ Bounds on variables. 'new-style' bounds are required.
238
+ eps : float or ndarray
239
+ If ``jac is None`` the absolute step size used for numerical
240
+ approximation of the jacobian via forward differences.
241
+ finite_diff_rel_step : None or array_like, optional
242
+ If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to
243
+ use for numerical approximation of the jacobian. The absolute step
244
+ size is computed as ``h = rel_step * sign(x0) * max(1, abs(x0))``,
245
+ possibly adjusted to fit into the bounds. For ``jac='3-point'``
246
+ the sign of `h` is ignored. If None (default) then step is selected
247
+ automatically.
248
+ hess : {callable, '2-point', '3-point', 'cs', None}
249
+ Computes the Hessian matrix. If it is callable, it should return the
250
+ Hessian matrix:
251
+
252
+ ``hess(x, *args) -> {LinearOperator, spmatrix, array}, (n, n)``
253
+
254
+ Alternatively, the keywords {'2-point', '3-point', 'cs'} select a
255
+ finite difference scheme for numerical estimation.
256
+ Whenever the gradient is estimated via finite-differences, the Hessian
257
+ cannot be estimated with options {'2-point', '3-point', 'cs'} and needs
258
+ to be estimated using one of the quasi-Newton strategies.
259
+ workers : int or map-like callable, optional
260
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
261
+ any numerical differentiation in parallel.
262
+ This evaluation is carried out as ``workers(fun, iterable)``, or
263
+ ``workers(grad, iterable)``, depending on what is being numerically
264
+ differentiated.
265
+ Alternatively, if `workers` is an int the task is subdivided into `workers`
266
+ sections and the function evaluated in parallel
267
+ (uses `multiprocessing.Pool <multiprocessing>`).
268
+ Supply -1 to use all available CPU cores.
269
+ It is recommended that a map-like be used instead of int, as repeated
270
+ calls to `approx_derivative` will incur large overhead from setting up
271
+ new processes.
272
+
273
+ .. versionadded:: 1.16.0
274
+
275
+ Returns
276
+ -------
277
+ sf : ScalarFunction
278
+ """
279
+ if callable(jac):
280
+ grad = jac
281
+ elif jac in FD_METHODS:
282
+ # epsilon is set to None so that ScalarFunction is made to use
283
+ # rel_step
284
+ epsilon = None
285
+ grad = jac
286
+ else:
287
+ # default (jac is None) is to do 2-point finite differences with
288
+ # absolute step size. ScalarFunction has to be provided an
289
+ # epsilon value that is not None to use absolute steps. This is
290
+ # normally the case from most _minimize* methods.
291
+ grad = '2-point'
292
+ epsilon = epsilon
293
+
294
+ if hess is None:
295
+ # ScalarFunction requires something for hess, so we give a dummy
296
+ # implementation here if nothing is provided, return a value of None
297
+ # so that downstream minimisers halt. The results of `fun.hess`
298
+ # should not be used.
299
+ def hess(x, *args):
300
+ return None
301
+
302
+ if bounds is None:
303
+ bounds = (-np.inf, np.inf)
304
+
305
+ # normalize workers
306
+ workers = workers or map
307
+
308
+ # ScalarFunction caches. Reuse of fun(x) during grad
309
+ # calculation reduces overall function evaluations.
310
+ sf = ScalarFunction(fun, x0, args, grad, hess,
311
+ finite_diff_rel_step, bounds, epsilon=epsilon,
312
+ workers=workers)
313
+
314
+ return sf
315
+
316
+
317
+ def _clip_x_for_func(func, bounds):
318
+ # ensures that x values sent to func are clipped to bounds
319
+
320
+ # this is used as a mitigation for gh11403, slsqp/tnc sometimes
321
+ # suggest a move that is outside the limits by 1 or 2 ULP. This
322
+ # unclean fix makes sure x is strictly within bounds.
323
+ def eval(x):
324
+ x = _check_clip_x(x, bounds)
325
+ return func(x)
326
+
327
+ return eval
328
+
329
+
330
+ def _check_clip_x(x, bounds):
331
+ if (x < bounds[0]).any() or (x > bounds[1]).any():
332
+ warnings.warn("Values in x were outside bounds during a "
333
+ "minimize step, clipping to bounds",
334
+ RuntimeWarning, stacklevel=3)
335
+ x = np.clip(x, bounds[0], bounds[1])
336
+ return x
337
+
338
+ return x
339
+
340
+
341
+ @xp_capabilities()
342
+ def rosen(x):
343
+ """
344
+ The Rosenbrock function.
345
+
346
+ The function computed is::
347
+
348
+ sum(100.0*(x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0)
349
+
350
+ Parameters
351
+ ----------
352
+ x : array_like
353
+ 1-D array of points at which the Rosenbrock function is to be computed.
354
+
355
+ Returns
356
+ -------
357
+ f : float
358
+ The value of the Rosenbrock function.
359
+
360
+ See Also
361
+ --------
362
+ rosen_der, rosen_hess, rosen_hess_prod
363
+
364
+ Examples
365
+ --------
366
+ >>> import numpy as np
367
+ >>> from scipy.optimize import rosen
368
+ >>> X = 0.1 * np.arange(10)
369
+ >>> rosen(X)
370
+ 76.56
371
+
372
+ For higher-dimensional input ``rosen`` broadcasts.
373
+ In the following example, we use this to plot a 2D landscape.
374
+ Note that ``rosen_hess`` does not broadcast in this manner.
375
+
376
+ >>> import matplotlib.pyplot as plt
377
+ >>> from mpl_toolkits.mplot3d import Axes3D
378
+ >>> x = np.linspace(-1, 1, 50)
379
+ >>> X, Y = np.meshgrid(x, x)
380
+ >>> ax = plt.subplot(111, projection='3d')
381
+ >>> ax.plot_surface(X, Y, rosen([X, Y]))
382
+ >>> plt.show()
383
+ """
384
+ xp = array_namespace(x)
385
+ x = xp_promote(x, force_floating=True, xp=xp)
386
+ r = xp.sum(100.0 * (x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0,
387
+ axis=0, dtype=x.dtype)
388
+ return r
389
+
390
+
391
+ @xp_capabilities(skip_backends=[('jax.numpy', "JAX doesn't allow item assignment.")])
392
+ def rosen_der(x):
393
+ """
394
+ The derivative (i.e. gradient) of the Rosenbrock function.
395
+
396
+ Parameters
397
+ ----------
398
+ x : array_like
399
+ 1-D array of points at which the derivative is to be computed.
400
+
401
+ Returns
402
+ -------
403
+ rosen_der : (N,) ndarray
404
+ The gradient of the Rosenbrock function at `x`.
405
+
406
+ See Also
407
+ --------
408
+ rosen, rosen_hess, rosen_hess_prod
409
+
410
+ Examples
411
+ --------
412
+ >>> import numpy as np
413
+ >>> from scipy.optimize import rosen_der
414
+ >>> X = 0.1 * np.arange(9)
415
+ >>> rosen_der(X)
416
+ array([ -2. , 10.6, 15.6, 13.4, 6.4, -3. , -12.4, -19.4, 62. ])
417
+
418
+ """
419
+ xp = array_namespace(x)
420
+ x = xp_promote(x, force_floating=True, xp=xp)
421
+ xm = x[1:-1]
422
+ xm_m1 = x[:-2]
423
+ xm_p1 = x[2:]
424
+ der = xp.zeros_like(x)
425
+ der[1:-1] = (200 * (xm - xm_m1**2) -
426
+ 400 * (xm_p1 - xm**2) * xm - 2 * (1 - xm))
427
+ der[0] = -400 * x[0] * (x[1] - x[0]**2) - 2 * (1 - x[0])
428
+ der[-1] = 200 * (x[-1] - x[-2]**2)
429
+ return der
430
+
431
+
432
+ @xp_capabilities(skip_backends=[('jax.numpy', "JAX doesn't allow item assignment.")])
433
+ def rosen_hess(x):
434
+ """
435
+ The Hessian matrix of the Rosenbrock function.
436
+
437
+ Parameters
438
+ ----------
439
+ x : array_like
440
+ 1-D array of points at which the Hessian matrix is to be computed.
441
+
442
+ Returns
443
+ -------
444
+ rosen_hess : ndarray
445
+ The Hessian matrix of the Rosenbrock function at `x`.
446
+
447
+ See Also
448
+ --------
449
+ rosen, rosen_der, rosen_hess_prod
450
+
451
+ Examples
452
+ --------
453
+ >>> import numpy as np
454
+ >>> from scipy.optimize import rosen_hess
455
+ >>> X = 0.1 * np.arange(4)
456
+ >>> rosen_hess(X)
457
+ array([[-38., 0., 0., 0.],
458
+ [ 0., 134., -40., 0.],
459
+ [ 0., -40., 130., -80.],
460
+ [ 0., 0., -80., 200.]])
461
+
462
+ """
463
+ xp = array_namespace(x)
464
+ x = xp_promote(x, force_floating=True, xp=xp)
465
+
466
+ H = (xpx.create_diagonal(-400 * x[:-1], offset=1, xp=xp)
467
+ - xpx.create_diagonal(400 * x[:-1], offset=-1, xp=xp))
468
+ diagonal = xp.zeros(x.shape[0], dtype=x.dtype)
469
+ diagonal = xpx.at(diagonal)[0].set(1200 * x[0]**2 - 400 * x[1] + 2)
470
+ diagonal = xpx.at(diagonal)[-1].set(200)
471
+ diagonal = xpx.at(diagonal)[1:-1].set(202 + 1200 * x[1:-1]**2 - 400 * x[2:])
472
+ return H + xpx.create_diagonal(diagonal, xp=xp)
473
+
474
+
475
+ @xp_capabilities(skip_backends=[('jax.numpy', "JAX doesn't allow item assignment.")])
476
+ def rosen_hess_prod(x, p):
477
+ """
478
+ Product of the Hessian matrix of the Rosenbrock function with a vector.
479
+
480
+ Parameters
481
+ ----------
482
+ x : array_like
483
+ 1-D array of points at which the Hessian matrix is to be computed.
484
+ p : array_like
485
+ 1-D array, the vector to be multiplied by the Hessian matrix.
486
+
487
+ Returns
488
+ -------
489
+ rosen_hess_prod : ndarray
490
+ The Hessian matrix of the Rosenbrock function at `x` multiplied
491
+ by the vector `p`.
492
+
493
+ See Also
494
+ --------
495
+ rosen, rosen_der, rosen_hess
496
+
497
+ Examples
498
+ --------
499
+ >>> import numpy as np
500
+ >>> from scipy.optimize import rosen_hess_prod
501
+ >>> X = 0.1 * np.arange(9)
502
+ >>> p = 0.5 * np.arange(9)
503
+ >>> rosen_hess_prod(X, p)
504
+ array([ -0., 27., -10., -95., -192., -265., -278., -195., -180.])
505
+
506
+ """
507
+ xp = array_namespace(x, p)
508
+ x = xp_promote(x, force_floating=True, xp=xp)
509
+ x = xpx.atleast_nd(x, ndim=1, xp=xp)
510
+ p = xp.asarray(p, dtype=x.dtype)
511
+ Hp = xp.zeros(x.shape[0], dtype=x.dtype)
512
+ Hp[0] = (1200 * x[0]**2 - 400 * x[1] + 2) * p[0] - 400 * x[0] * p[1]
513
+ Hp[1:-1] = (-400 * x[:-2] * p[:-2] +
514
+ (202 + 1200 * x[1:-1]**2 - 400 * x[2:]) * p[1:-1] -
515
+ 400 * x[1:-1] * p[2:])
516
+ Hp[-1] = -400 * x[-2] * p[-2] + 200*p[-1]
517
+ return Hp
518
+
519
+
520
+ def _wrap_scalar_function(function, args):
521
+ # wraps a minimizer function to count number of evaluations
522
+ # and to easily provide an args kwd.
523
+ ncalls = [0]
524
+ if function is None:
525
+ return ncalls, None
526
+
527
+ def function_wrapper(x, *wrapper_args):
528
+ ncalls[0] += 1
529
+ # A copy of x is sent to the user function (gh13740)
530
+ fx = function(np.copy(x), *(wrapper_args + args))
531
+ # Ideally, we'd like to a have a true scalar returned from f(x). For
532
+ # backwards-compatibility, also allow np.array([1.3]), np.array([[1.3]]) etc.
533
+ if not np.isscalar(fx):
534
+ try:
535
+ fx = np.asarray(fx).item()
536
+ except (TypeError, ValueError) as e:
537
+ raise ValueError("The user-provided objective function "
538
+ "must return a scalar value.") from e
539
+ return fx
540
+
541
+ return ncalls, function_wrapper
542
+
543
+
544
+ class _MaxFuncCallError(RuntimeError):
545
+ pass
546
+
547
+
548
+ def _wrap_scalar_function_maxfun_validation(function, args, maxfun):
549
+ # wraps a minimizer function to count number of evaluations
550
+ # and to easily provide an args kwd.
551
+ ncalls = [0]
552
+ if function is None:
553
+ return ncalls, None
554
+
555
+ def function_wrapper(x, *wrapper_args):
556
+ if ncalls[0] >= maxfun:
557
+ raise _MaxFuncCallError("Too many function calls")
558
+ ncalls[0] += 1
559
+ # A copy of x is sent to the user function (gh13740)
560
+ fx = function(np.copy(x), *(wrapper_args + args))
561
+ # Ideally, we'd like to a have a true scalar returned from f(x). For
562
+ # backwards-compatibility, also allow np.array([1.3]),
563
+ # np.array([[1.3]]) etc.
564
+ if not np.isscalar(fx):
565
+ try:
566
+ fx = np.asarray(fx).item()
567
+ except (TypeError, ValueError) as e:
568
+ raise ValueError("The user-provided objective function "
569
+ "must return a scalar value.") from e
570
+ return fx
571
+
572
+ return ncalls, function_wrapper
573
+
574
+
575
+ def fmin(func, x0, args=(), xtol=1e-4, ftol=1e-4, maxiter=None, maxfun=None,
576
+ full_output=0, disp=1, retall=0, callback=None, initial_simplex=None):
577
+ """
578
+ Minimize a function using the downhill simplex algorithm.
579
+
580
+ This algorithm only uses function values, not derivatives or second
581
+ derivatives.
582
+
583
+ Parameters
584
+ ----------
585
+ func : callable func(x,*args)
586
+ The objective function to be minimized.
587
+ x0 : ndarray
588
+ Initial guess.
589
+ args : tuple, optional
590
+ Extra arguments passed to func, i.e., ``f(x,*args)``.
591
+ xtol : float, optional
592
+ Absolute error in xopt between iterations that is acceptable for
593
+ convergence.
594
+ ftol : number, optional
595
+ Absolute error in func(xopt) between iterations that is acceptable for
596
+ convergence.
597
+ maxiter : int, optional
598
+ Maximum number of iterations to perform.
599
+ maxfun : number, optional
600
+ Maximum number of function evaluations to make.
601
+ full_output : bool, optional
602
+ Set to True if fopt and warnflag outputs are desired.
603
+ disp : bool, optional
604
+ Set to True to print convergence messages.
605
+ retall : bool, optional
606
+ Set to True to return list of solutions at each iteration.
607
+ callback : callable, optional
608
+ Called after each iteration, as callback(xk), where xk is the
609
+ current parameter vector.
610
+ initial_simplex : array_like of shape (N + 1, N), optional
611
+ Initial simplex. If given, overrides `x0`.
612
+ ``initial_simplex[j,:]`` should contain the coordinates of
613
+ the jth vertex of the ``N+1`` vertices in the simplex, where
614
+ ``N`` is the dimension.
615
+
616
+ Returns
617
+ -------
618
+ xopt : ndarray
619
+ Parameter that minimizes function.
620
+ fopt : float
621
+ Value of function at minimum: ``fopt = func(xopt)``.
622
+ iter : int
623
+ Number of iterations performed.
624
+ funcalls : int
625
+ Number of function calls made.
626
+ warnflag : int
627
+ 1 : Maximum number of function evaluations made.
628
+ 2 : Maximum number of iterations reached.
629
+ allvecs : list
630
+ Solution at each iteration.
631
+
632
+ See also
633
+ --------
634
+ minimize: Interface to minimization algorithms for multivariate
635
+ functions. See the 'Nelder-Mead' `method` in particular.
636
+
637
+ Notes
638
+ -----
639
+ Uses a Nelder-Mead simplex algorithm to find the minimum of function of
640
+ one or more variables.
641
+
642
+ This algorithm has a long history of successful use in applications.
643
+ But it will usually be slower than an algorithm that uses first or
644
+ second derivative information. In practice, it can have poor
645
+ performance in high-dimensional problems and is not robust to
646
+ minimizing complicated functions. Additionally, there currently is no
647
+ complete theory describing when the algorithm will successfully
648
+ converge to the minimum, or how fast it will if it does. Both the ftol and
649
+ xtol criteria must be met for convergence.
650
+
651
+ Examples
652
+ --------
653
+ >>> def f(x):
654
+ ... return x**2
655
+
656
+ >>> from scipy import optimize
657
+
658
+ >>> minimum = optimize.fmin(f, 1)
659
+ Optimization terminated successfully.
660
+ Current function value: 0.000000
661
+ Iterations: 17
662
+ Function evaluations: 34
663
+ >>> minimum[0]
664
+ -8.8817841970012523e-16
665
+
666
+ References
667
+ ----------
668
+ .. [1] Nelder, J.A. and Mead, R. (1965), "A simplex method for function
669
+ minimization", The Computer Journal, 7, pp. 308-313
670
+
671
+ .. [2] Wright, M.H. (1996), "Direct Search Methods: Once Scorned, Now
672
+ Respectable", in Numerical Analysis 1995, Proceedings of the
673
+ 1995 Dundee Biennial Conference in Numerical Analysis, D.F.
674
+ Griffiths and G.A. Watson (Eds.), Addison Wesley Longman,
675
+ Harlow, UK, pp. 191-208.
676
+
677
+ """
678
+ opts = {'xatol': xtol,
679
+ 'fatol': ftol,
680
+ 'maxiter': maxiter,
681
+ 'maxfev': maxfun,
682
+ 'disp': disp,
683
+ 'return_all': retall,
684
+ 'initial_simplex': initial_simplex}
685
+
686
+ callback = _wrap_callback(callback)
687
+ res = _minimize_neldermead(func, x0, args, callback=callback, **opts)
688
+ if full_output:
689
+ retlist = res['x'], res['fun'], res['nit'], res['nfev'], res['status']
690
+ if retall:
691
+ retlist += (res['allvecs'], )
692
+ return retlist
693
+ else:
694
+ if retall:
695
+ return res['x'], res['allvecs']
696
+ else:
697
+ return res['x']
698
+
699
+
700
+ def _minimize_neldermead(func, x0, args=(), callback=None,
701
+ maxiter=None, maxfev=None, disp=False,
702
+ return_all=False, initial_simplex=None,
703
+ xatol=1e-4, fatol=1e-4, adaptive=False, bounds=None,
704
+ **unknown_options):
705
+ """
706
+ Minimization of scalar function of one or more variables using the
707
+ Nelder-Mead algorithm.
708
+
709
+ Options
710
+ -------
711
+ disp : bool
712
+ Set to True to print convergence messages.
713
+ maxiter, maxfev : int
714
+ Maximum allowed number of iterations and function evaluations.
715
+ Will default to ``N*200``, where ``N`` is the number of
716
+ variables, if neither `maxiter` or `maxfev` is set. If both
717
+ `maxiter` and `maxfev` are set, minimization will stop at the
718
+ first reached.
719
+ return_all : bool, optional
720
+ Set to True to return a list of the best solution at each of the
721
+ iterations.
722
+ initial_simplex : array_like of shape (N + 1, N)
723
+ Initial simplex. If given, overrides `x0`.
724
+ ``initial_simplex[j,:]`` should contain the coordinates of
725
+ the jth vertex of the ``N+1`` vertices in the simplex, where
726
+ ``N`` is the dimension.
727
+ xatol : float, optional
728
+ Absolute error in xopt between iterations that is acceptable for
729
+ convergence.
730
+ fatol : number, optional
731
+ Absolute error in func(xopt) between iterations that is acceptable for
732
+ convergence.
733
+ adaptive : bool, optional
734
+ Adapt algorithm parameters to dimensionality of problem. Useful for
735
+ high-dimensional minimization [1]_.
736
+ bounds : sequence or `Bounds`, optional
737
+ Bounds on variables. There are two ways to specify the bounds:
738
+
739
+ 1. Instance of `Bounds` class.
740
+ 2. Sequence of ``(min, max)`` pairs for each element in `x`. None
741
+ is used to specify no bound.
742
+
743
+ Note that this just clips all vertices in simplex based on
744
+ the bounds.
745
+
746
+ References
747
+ ----------
748
+ .. [1] Gao, F. and Han, L.
749
+ Implementing the Nelder-Mead simplex algorithm with adaptive
750
+ parameters. 2012. Computational Optimization and Applications.
751
+ 51:1, pp. 259-277
752
+
753
+ """
754
+ _check_unknown_options(unknown_options)
755
+ maxfun = maxfev
756
+ retall = return_all
757
+
758
+ x0 = np.atleast_1d(x0).flatten()
759
+ dtype = x0.dtype if np.issubdtype(x0.dtype, np.inexact) else np.float64
760
+ x0 = np.asarray(x0, dtype=dtype)
761
+
762
+ if adaptive:
763
+ dim = float(len(x0))
764
+ rho = 1
765
+ chi = 1 + 2/dim
766
+ psi = 0.75 - 1/(2*dim)
767
+ sigma = 1 - 1/dim
768
+ else:
769
+ rho = 1
770
+ chi = 2
771
+ psi = 0.5
772
+ sigma = 0.5
773
+
774
+ nonzdelt = 0.05
775
+ zdelt = 0.00025
776
+
777
+ if bounds is not None:
778
+ lower_bound, upper_bound = bounds.lb, bounds.ub
779
+ # check bounds
780
+ if (lower_bound > upper_bound).any():
781
+ raise ValueError("Nelder Mead - one of the lower bounds "
782
+ "is greater than an upper bound.")
783
+ if np.any(lower_bound > x0) or np.any(x0 > upper_bound):
784
+ warnings.warn("Initial guess is not within the specified bounds",
785
+ OptimizeWarning, stacklevel=3)
786
+
787
+ if bounds is not None:
788
+ x0 = np.clip(x0, lower_bound, upper_bound)
789
+
790
+ if initial_simplex is None:
791
+ N = len(x0)
792
+
793
+ sim = np.empty((N + 1, N), dtype=x0.dtype)
794
+ sim[0] = x0
795
+ for k in range(N):
796
+ y = np.array(x0, copy=True)
797
+ if y[k] != 0:
798
+ y[k] = (1 + nonzdelt)*y[k]
799
+ else:
800
+ y[k] = zdelt
801
+ sim[k + 1] = y
802
+ else:
803
+ sim = np.atleast_2d(initial_simplex).copy()
804
+ dtype = sim.dtype if np.issubdtype(sim.dtype, np.inexact) else np.float64
805
+ sim = np.asarray(sim, dtype=dtype)
806
+ if sim.ndim != 2 or sim.shape[0] != sim.shape[1] + 1:
807
+ raise ValueError("`initial_simplex` should be an array of shape (N+1,N)")
808
+ if len(x0) != sim.shape[1]:
809
+ raise ValueError("Size of `initial_simplex` is not consistent with `x0`")
810
+ N = sim.shape[1]
811
+
812
+ if retall:
813
+ allvecs = [sim[0]]
814
+
815
+ # If neither are set, then set both to default
816
+ if maxiter is None and maxfun is None:
817
+ maxiter = N * 200
818
+ maxfun = N * 200
819
+ elif maxiter is None:
820
+ # Convert remaining Nones, to np.inf, unless the other is np.inf, in
821
+ # which case use the default to avoid unbounded iteration
822
+ if maxfun == np.inf:
823
+ maxiter = N * 200
824
+ else:
825
+ maxiter = np.inf
826
+ elif maxfun is None:
827
+ if maxiter == np.inf:
828
+ maxfun = N * 200
829
+ else:
830
+ maxfun = np.inf
831
+
832
+ if bounds is not None:
833
+ # The default simplex construction may make all entries (for a given
834
+ # parameter) greater than an upper bound if x0 is very close to the
835
+ # upper bound. If one simply clips the simplex to the bounds this could
836
+ # make the simplex entries degenerate. If that occurs reflect into the
837
+ # interior.
838
+ msk = sim > upper_bound
839
+ # reflect into the interior
840
+ sim = np.where(msk, 2*upper_bound - sim, sim)
841
+ # but make sure the reflection is no less than the lower_bound
842
+ sim = np.clip(sim, lower_bound, upper_bound)
843
+
844
+ one2np1 = list(range(1, N + 1))
845
+ fsim = np.full((N + 1,), np.inf, dtype=float)
846
+
847
+ fcalls, func = _wrap_scalar_function_maxfun_validation(func, args, maxfun)
848
+
849
+ try:
850
+ for k in range(N + 1):
851
+ fsim[k] = func(sim[k])
852
+ except _MaxFuncCallError:
853
+ pass
854
+ finally:
855
+ ind = np.argsort(fsim)
856
+ sim = np.take(sim, ind, 0)
857
+ fsim = np.take(fsim, ind, 0)
858
+
859
+ ind = np.argsort(fsim)
860
+ fsim = np.take(fsim, ind, 0)
861
+ # sort so sim[0,:] has the lowest function value
862
+ sim = np.take(sim, ind, 0)
863
+
864
+ iterations = 1
865
+
866
+ while (fcalls[0] < maxfun and iterations < maxiter):
867
+ try:
868
+ if (np.max(np.ravel(np.abs(sim[1:] - sim[0]))) <= xatol and
869
+ np.max(np.abs(fsim[0] - fsim[1:])) <= fatol):
870
+ break
871
+
872
+ xbar = np.add.reduce(sim[:-1], 0) / N
873
+ xr = (1 + rho) * xbar - rho * sim[-1]
874
+ if bounds is not None:
875
+ xr = np.clip(xr, lower_bound, upper_bound)
876
+ fxr = func(xr)
877
+ doshrink = 0
878
+
879
+ if fxr < fsim[0]:
880
+ xe = (1 + rho * chi) * xbar - rho * chi * sim[-1]
881
+ if bounds is not None:
882
+ xe = np.clip(xe, lower_bound, upper_bound)
883
+ fxe = func(xe)
884
+
885
+ if fxe < fxr:
886
+ sim[-1] = xe
887
+ fsim[-1] = fxe
888
+ else:
889
+ sim[-1] = xr
890
+ fsim[-1] = fxr
891
+ else: # fsim[0] <= fxr
892
+ if fxr < fsim[-2]:
893
+ sim[-1] = xr
894
+ fsim[-1] = fxr
895
+ else: # fxr >= fsim[-2]
896
+ # Perform contraction
897
+ if fxr < fsim[-1]:
898
+ xc = (1 + psi * rho) * xbar - psi * rho * sim[-1]
899
+ if bounds is not None:
900
+ xc = np.clip(xc, lower_bound, upper_bound)
901
+ fxc = func(xc)
902
+
903
+ if fxc <= fxr:
904
+ sim[-1] = xc
905
+ fsim[-1] = fxc
906
+ else:
907
+ doshrink = 1
908
+ else:
909
+ # Perform an inside contraction
910
+ xcc = (1 - psi) * xbar + psi * sim[-1]
911
+ if bounds is not None:
912
+ xcc = np.clip(xcc, lower_bound, upper_bound)
913
+ fxcc = func(xcc)
914
+
915
+ if fxcc < fsim[-1]:
916
+ sim[-1] = xcc
917
+ fsim[-1] = fxcc
918
+ else:
919
+ doshrink = 1
920
+
921
+ if doshrink:
922
+ for j in one2np1:
923
+ sim[j] = sim[0] + sigma * (sim[j] - sim[0])
924
+ if bounds is not None:
925
+ sim[j] = np.clip(
926
+ sim[j], lower_bound, upper_bound)
927
+ fsim[j] = func(sim[j])
928
+ iterations += 1
929
+ except _MaxFuncCallError:
930
+ pass
931
+ ind = np.argsort(fsim)
932
+ sim = np.take(sim, ind, 0)
933
+ fsim = np.take(fsim, ind, 0)
934
+ if retall:
935
+ allvecs.append(sim[0])
936
+ intermediate_result = OptimizeResult(x=sim[0], fun=fsim[0])
937
+ if _call_callback_maybe_halt(callback, intermediate_result):
938
+ break
939
+
940
+ x = sim[0]
941
+ fval = np.min(fsim)
942
+ warnflag = 0
943
+
944
+ if fcalls[0] >= maxfun:
945
+ warnflag = 1
946
+ msg = _status_message['maxfev']
947
+ if disp:
948
+ warnings.warn(msg, RuntimeWarning, stacklevel=3)
949
+ elif iterations >= maxiter:
950
+ warnflag = 2
951
+ msg = _status_message['maxiter']
952
+ if disp:
953
+ warnings.warn(msg, RuntimeWarning, stacklevel=3)
954
+ else:
955
+ msg = _status_message['success']
956
+ if disp:
957
+ print(msg)
958
+ print(f" Current function value: {fval:f}")
959
+ print(f" Iterations: {iterations:d}")
960
+ print(f" Function evaluations: {fcalls[0]:d}")
961
+
962
+ result = OptimizeResult(fun=fval, nit=iterations, nfev=fcalls[0],
963
+ status=warnflag, success=(warnflag == 0),
964
+ message=msg, x=x, final_simplex=(sim, fsim))
965
+ if retall:
966
+ result['allvecs'] = allvecs
967
+ return result
968
+
969
+
970
+ def approx_fprime(xk, f, epsilon=_epsilon, *args):
971
+ """Finite difference approximation of the derivatives of a
972
+ scalar or vector-valued function.
973
+
974
+ If a function maps from :math:`R^n` to :math:`R^m`, its derivatives form
975
+ an m-by-n matrix
976
+ called the Jacobian, where an element :math:`(i, j)` is a partial
977
+ derivative of f[i] with respect to ``xk[j]``.
978
+
979
+ Parameters
980
+ ----------
981
+ xk : array_like
982
+ The coordinate vector at which to determine the gradient of `f`.
983
+ f : callable
984
+ Function of which to estimate the derivatives of. Has the signature
985
+ ``f(xk, *args)`` where `xk` is the argument in the form of a 1-D array
986
+ and `args` is a tuple of any additional fixed parameters needed to
987
+ completely specify the function. The argument `xk` passed to this
988
+ function is an ndarray of shape (n,) (never a scalar even if n=1).
989
+ It must return a 1-D array_like of shape (m,) or a scalar.
990
+
991
+ Suppose the callable has signature ``f0(x, *my_args, **my_kwargs)``, where
992
+ ``my_args`` and ``my_kwargs`` are required positional and keyword arguments.
993
+ Rather than passing ``f0`` as the callable, wrap it to accept
994
+ only ``x``; e.g., pass ``fun=lambda x: f0(x, *my_args, **my_kwargs)`` as the
995
+ callable, where ``my_args`` (tuple) and ``my_kwargs`` (dict) have been
996
+ gathered before invoking this function.
997
+
998
+ .. versionchanged:: 1.9.0
999
+ `f` is now able to return a 1-D array-like, with the :math:`(m, n)`
1000
+ Jacobian being estimated.
1001
+
1002
+ epsilon : {float, array_like}, optional
1003
+ Increment to `xk` to use for determining the function gradient.
1004
+ If a scalar, uses the same finite difference delta for all partial
1005
+ derivatives. If an array, should contain one value per element of
1006
+ `xk`. Defaults to ``sqrt(np.finfo(float).eps)``, which is approximately
1007
+ 1.49e-08.
1008
+ \\*args : args, optional
1009
+ Any other arguments that are to be passed to `f`.
1010
+
1011
+ Returns
1012
+ -------
1013
+ jac : ndarray
1014
+ The partial derivatives of `f` to `xk`.
1015
+
1016
+ See Also
1017
+ --------
1018
+ check_grad : Check correctness of gradient function against approx_fprime.
1019
+
1020
+ Notes
1021
+ -----
1022
+ The function gradient is determined by the forward finite difference
1023
+ formula::
1024
+
1025
+ f(xk[i] + epsilon[i]) - f(xk[i])
1026
+ f'[i] = ---------------------------------
1027
+ epsilon[i]
1028
+
1029
+ Examples
1030
+ --------
1031
+ >>> import numpy as np
1032
+ >>> from scipy import optimize
1033
+ >>> def func(x, c0, c1):
1034
+ ... "Coordinate vector `x` should be an array of size two."
1035
+ ... return c0 * x[0]**2 + c1*x[1]**2
1036
+
1037
+ >>> x = np.ones(2)
1038
+ >>> c0, c1 = (1, 200)
1039
+ >>> eps = np.sqrt(np.finfo(float).eps)
1040
+ >>> optimize.approx_fprime(x, func, [eps, np.sqrt(200) * eps], c0, c1)
1041
+ array([ 2. , 400.00004208])
1042
+
1043
+ """
1044
+ xk = np.asarray(xk, float)
1045
+ f0 = f(xk, *args)
1046
+
1047
+ return approx_derivative(f, xk, method='2-point', abs_step=epsilon,
1048
+ args=args, f0=f0)
1049
+
1050
+
1051
+ @_transition_to_rng("seed", position_num=6)
1052
+ def check_grad(func, grad, x0, *args, epsilon=_epsilon,
1053
+ direction='all', rng=None):
1054
+ r"""Check the correctness of a gradient function by comparing it against a
1055
+ (forward) finite-difference approximation of the gradient.
1056
+
1057
+ Parameters
1058
+ ----------
1059
+ func : callable ``func(x0, *args)``
1060
+ Function whose derivative is to be checked.
1061
+ grad : callable ``grad(x0, *args)``
1062
+ Jacobian of `func`.
1063
+ x0 : ndarray
1064
+ Points to check `grad` against forward difference approximation of grad
1065
+ using `func`.
1066
+ args : \\*args, optional
1067
+ Extra arguments passed to `func` and `grad`.
1068
+ epsilon : float, optional
1069
+ Step size used for the finite difference approximation. It defaults to
1070
+ ``sqrt(np.finfo(float).eps)``, which is approximately 1.49e-08.
1071
+ direction : str, optional
1072
+ If set to ``'random'``, then gradients along a random vector
1073
+ are used to check `grad` against forward difference approximation
1074
+ using `func`. By default it is ``'all'``, in which case, all
1075
+ the one hot direction vectors are considered to check `grad`.
1076
+ If `func` is a vector valued function then only ``'all'`` can be used.
1077
+ rng : `numpy.random.Generator`, optional
1078
+ Pseudorandom number generator state. When `rng` is None, a new
1079
+ `numpy.random.Generator` is created using entropy from the
1080
+ operating system. Types other than `numpy.random.Generator` are
1081
+ passed to `numpy.random.default_rng` to instantiate a ``Generator``.
1082
+
1083
+ The random numbers generated affect the random vector along which gradients
1084
+ are computed to check ``grad``. Note that `rng` is only used when `direction`
1085
+ argument is set to `'random'`.
1086
+
1087
+ Returns
1088
+ -------
1089
+ err : float
1090
+ The square root of the sum of squares (i.e., the 2-norm) of the
1091
+ difference between ``grad(x0, *args)`` and the finite difference
1092
+ approximation of `grad` using func at the points `x0`.
1093
+
1094
+ See Also
1095
+ --------
1096
+ approx_fprime
1097
+
1098
+ Examples
1099
+ --------
1100
+ >>> import numpy as np
1101
+ >>> def func(x):
1102
+ ... return x[0]**2 - 0.5 * x[1]**3
1103
+ >>> def grad(x):
1104
+ ... return [2 * x[0], -1.5 * x[1]**2]
1105
+ >>> from scipy.optimize import check_grad
1106
+ >>> check_grad(func, grad, [1.5, -1.5])
1107
+ 2.9802322387695312e-08 # may vary
1108
+ >>> rng = np.random.default_rng()
1109
+ >>> check_grad(func, grad, [1.5, -1.5],
1110
+ ... direction='random', seed=rng)
1111
+ 2.9802322387695312e-08
1112
+
1113
+ """
1114
+ step = epsilon
1115
+ x0 = np.asarray(x0)
1116
+
1117
+ def g(w, func, x0, v, *args):
1118
+ return func(x0 + w*v, *args)
1119
+
1120
+ if direction == 'random':
1121
+ _grad = np.asanyarray(grad(x0, *args))
1122
+ if _grad.ndim > 1:
1123
+ raise ValueError("'random' can only be used with scalar valued"
1124
+ " func")
1125
+ rng_gen = check_random_state(rng)
1126
+ v = rng_gen.standard_normal(size=(x0.shape))
1127
+ _args = (func, x0, v) + args
1128
+ _func = g
1129
+ vars = np.zeros((1,))
1130
+ analytical_grad = np.dot(_grad, v)
1131
+ elif direction == 'all':
1132
+ _args = args
1133
+ _func = func
1134
+ vars = x0
1135
+ analytical_grad = grad(x0, *args)
1136
+ else:
1137
+ raise ValueError(f"{direction} is not a valid string for "
1138
+ "``direction`` argument")
1139
+
1140
+ return np.sqrt(np.sum(np.abs(
1141
+ (analytical_grad - approx_fprime(vars, _func, step, *_args))**2
1142
+ )))
1143
+
1144
+
1145
+ def approx_fhess_p(x0, p, fprime, epsilon, *args):
1146
+ # calculate fprime(x0) first, as this may be cached by ScalarFunction
1147
+ f1 = fprime(*((x0,) + args))
1148
+ f2 = fprime(*((x0 + epsilon*p,) + args))
1149
+ return (f2 - f1) / epsilon
1150
+
1151
+
1152
+ class _LineSearchError(RuntimeError):
1153
+ pass
1154
+
1155
+
1156
+ def _line_search_wolfe12(f, fprime, xk, pk, gfk, old_fval, old_old_fval,
1157
+ **kwargs):
1158
+ """
1159
+ Same as line_search_wolfe1, but fall back to line_search_wolfe2 if
1160
+ suitable step length is not found, and raise an exception if a
1161
+ suitable step length is not found.
1162
+
1163
+ Raises
1164
+ ------
1165
+ _LineSearchError
1166
+ If no suitable step size is found
1167
+
1168
+ """
1169
+
1170
+ extra_condition = kwargs.pop('extra_condition', None)
1171
+
1172
+ ret = line_search_wolfe1(f, fprime, xk, pk, gfk,
1173
+ old_fval, old_old_fval,
1174
+ **kwargs)
1175
+
1176
+ if ret[0] is not None and extra_condition is not None:
1177
+ xp1 = xk + ret[0] * pk
1178
+ if not extra_condition(ret[0], xp1, ret[3], ret[5]):
1179
+ # Reject step if extra_condition fails
1180
+ ret = (None,)
1181
+
1182
+ if ret[0] is None:
1183
+ # line search failed: try different one.
1184
+ with warnings.catch_warnings():
1185
+ warnings.simplefilter('ignore', LineSearchWarning)
1186
+ kwargs2 = {}
1187
+ for key in ('c1', 'c2', 'amax'):
1188
+ if key in kwargs:
1189
+ kwargs2[key] = kwargs[key]
1190
+ ret = line_search_wolfe2(f, fprime, xk, pk, gfk,
1191
+ old_fval, old_old_fval,
1192
+ extra_condition=extra_condition,
1193
+ **kwargs2)
1194
+
1195
+ if ret[0] is None:
1196
+ raise _LineSearchError()
1197
+
1198
+ return ret
1199
+
1200
+
1201
+ def fmin_bfgs(f, x0, fprime=None, args=(), gtol=1e-5, norm=np.inf,
1202
+ epsilon=_epsilon, maxiter=None, full_output=0, disp=1,
1203
+ retall=0, callback=None, xrtol=0, c1=1e-4, c2=0.9,
1204
+ hess_inv0=None):
1205
+ """
1206
+ Minimize a function using the BFGS algorithm.
1207
+
1208
+ Parameters
1209
+ ----------
1210
+ f : callable ``f(x,*args)``
1211
+ Objective function to be minimized.
1212
+ x0 : ndarray
1213
+ Initial guess, shape (n,)
1214
+ fprime : callable ``f'(x,*args)``, optional
1215
+ Gradient of f.
1216
+ args : tuple, optional
1217
+ Extra arguments passed to f and fprime.
1218
+ gtol : float, optional
1219
+ Terminate successfully if gradient norm is less than `gtol`
1220
+ norm : float, optional
1221
+ Order of norm (Inf is max, -Inf is min)
1222
+ epsilon : int or ndarray, optional
1223
+ If `fprime` is approximated, use this value for the step size.
1224
+ callback : callable, optional
1225
+ An optional user-supplied function to call after each
1226
+ iteration. Called as ``callback(xk)``, where ``xk`` is the
1227
+ current parameter vector.
1228
+ maxiter : int, optional
1229
+ Maximum number of iterations to perform.
1230
+ full_output : bool, optional
1231
+ If True, return ``fopt``, ``func_calls``, ``grad_calls``, and
1232
+ ``warnflag`` in addition to ``xopt``.
1233
+ disp : bool, optional
1234
+ Print convergence message if True.
1235
+ retall : bool, optional
1236
+ Return a list of results at each iteration if True.
1237
+ xrtol : float, default: 0
1238
+ Relative tolerance for `x`. Terminate successfully if step
1239
+ size is less than ``xk * xrtol`` where ``xk`` is the current
1240
+ parameter vector.
1241
+ c1 : float, default: 1e-4
1242
+ Parameter for Armijo condition rule.
1243
+ c2 : float, default: 0.9
1244
+ Parameter for curvature condition rule.
1245
+ hess_inv0 : None or ndarray, optional``
1246
+ Initial inverse hessian estimate, shape (n, n). If None (default) then
1247
+ the identity matrix is used.
1248
+
1249
+ Returns
1250
+ -------
1251
+ xopt : ndarray
1252
+ Parameters which minimize f, i.e., ``f(xopt) == fopt``.
1253
+ fopt : float
1254
+ Minimum value.
1255
+ gopt : ndarray
1256
+ Value of gradient at minimum, f'(xopt), which should be near 0.
1257
+ Bopt : ndarray
1258
+ Value of 1/f''(xopt), i.e., the inverse Hessian matrix.
1259
+ func_calls : int
1260
+ Number of function_calls made.
1261
+ grad_calls : int
1262
+ Number of gradient calls made.
1263
+ warnflag : integer
1264
+ 1 : Maximum number of iterations exceeded.
1265
+ 2 : Gradient and/or function calls not changing.
1266
+ 3 : NaN result encountered.
1267
+ allvecs : list
1268
+ The value of `xopt` at each iteration. Only returned if `retall` is
1269
+ True.
1270
+
1271
+ Notes
1272
+ -----
1273
+ Optimize the function, `f`, whose gradient is given by `fprime`
1274
+ using the quasi-Newton method of Broyden, Fletcher, Goldfarb,
1275
+ and Shanno (BFGS).
1276
+
1277
+ Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.
1278
+
1279
+ See Also
1280
+ --------
1281
+ minimize: Interface to minimization algorithms for multivariate
1282
+ functions. See ``method='BFGS'`` in particular.
1283
+
1284
+ References
1285
+ ----------
1286
+ Wright, and Nocedal 'Numerical Optimization', 1999, p. 198.
1287
+
1288
+ Examples
1289
+ --------
1290
+ >>> import numpy as np
1291
+ >>> from scipy.optimize import fmin_bfgs
1292
+ >>> def quadratic_cost(x, Q):
1293
+ ... return x @ Q @ x
1294
+ ...
1295
+ >>> x0 = np.array([-3, -4])
1296
+ >>> cost_weight = np.diag([1., 10.])
1297
+ >>> # Note that a trailing comma is necessary for a tuple with single element
1298
+ >>> fmin_bfgs(quadratic_cost, x0, args=(cost_weight,))
1299
+ Optimization terminated successfully.
1300
+ Current function value: 0.000000
1301
+ Iterations: 7 # may vary
1302
+ Function evaluations: 24 # may vary
1303
+ Gradient evaluations: 8 # may vary
1304
+ array([ 2.85169950e-06, -4.61820139e-07])
1305
+
1306
+ >>> def quadratic_cost_grad(x, Q):
1307
+ ... return 2 * Q @ x
1308
+ ...
1309
+ >>> fmin_bfgs(quadratic_cost, x0, quadratic_cost_grad, args=(cost_weight,))
1310
+ Optimization terminated successfully.
1311
+ Current function value: 0.000000
1312
+ Iterations: 7
1313
+ Function evaluations: 8
1314
+ Gradient evaluations: 8
1315
+ array([ 2.85916637e-06, -4.54371951e-07])
1316
+
1317
+ """
1318
+ opts = {'gtol': gtol,
1319
+ 'norm': norm,
1320
+ 'eps': epsilon,
1321
+ 'disp': disp,
1322
+ 'maxiter': maxiter,
1323
+ 'return_all': retall,
1324
+ 'xrtol': xrtol,
1325
+ 'c1': c1,
1326
+ 'c2': c2,
1327
+ 'hess_inv0': hess_inv0}
1328
+
1329
+ callback = _wrap_callback(callback)
1330
+ res = _minimize_bfgs(f, x0, args, fprime, callback=callback, **opts)
1331
+
1332
+ if full_output:
1333
+ retlist = (res['x'], res['fun'], res['jac'], res['hess_inv'],
1334
+ res['nfev'], res['njev'], res['status'])
1335
+ if retall:
1336
+ retlist += (res['allvecs'], )
1337
+ return retlist
1338
+ else:
1339
+ if retall:
1340
+ return res['x'], res['allvecs']
1341
+ else:
1342
+ return res['x']
1343
+
1344
+
1345
+ def _minimize_bfgs(fun, x0, args=(), jac=None, callback=None,
1346
+ gtol=1e-5, norm=np.inf, eps=_epsilon, maxiter=None,
1347
+ disp=False, return_all=False, finite_diff_rel_step=None,
1348
+ xrtol=0, c1=1e-4, c2=0.9,
1349
+ hess_inv0=None, workers=None, **unknown_options):
1350
+ """
1351
+ Minimization of scalar function of one or more variables using the
1352
+ BFGS algorithm.
1353
+
1354
+ Options
1355
+ -------
1356
+ disp : bool
1357
+ Set to True to print convergence messages.
1358
+ maxiter : int
1359
+ Maximum number of iterations to perform.
1360
+ gtol : float
1361
+ Terminate successfully if gradient norm is less than `gtol`.
1362
+ norm : float
1363
+ Order of norm (Inf is max, -Inf is min).
1364
+ eps : float or ndarray
1365
+ If `jac is None` the absolute step size used for numerical
1366
+ approximation of the jacobian via forward differences.
1367
+ return_all : bool, optional
1368
+ Set to True to return a list of the best solution at each of the
1369
+ iterations.
1370
+ finite_diff_rel_step : None or array_like, optional
1371
+ If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to
1372
+ use for numerical approximation of the jacobian. The absolute step
1373
+ size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``,
1374
+ possibly adjusted to fit into the bounds. For ``jac='3-point'``
1375
+ the sign of `h` is ignored. If None (default) then step is selected
1376
+ automatically.
1377
+ xrtol : float, default: 0
1378
+ Relative tolerance for `x`. Terminate successfully if step size is
1379
+ less than ``xk * xrtol`` where ``xk`` is the current parameter vector.
1380
+ c1 : float, default: 1e-4
1381
+ Parameter for Armijo condition rule.
1382
+ c2 : float, default: 0.9
1383
+ Parameter for curvature condition rule.
1384
+ hess_inv0 : None or ndarray, optional
1385
+ Initial inverse hessian estimate, shape (n, n). If None (default) then
1386
+ the identity matrix is used.
1387
+ workers : int, map-like callable, optional
1388
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
1389
+ any numerical differentiation in parallel.
1390
+ This evaluation is carried out as ``workers(fun, iterable)``.
1391
+
1392
+ .. versionadded:: 1.16.0
1393
+
1394
+ Notes
1395
+ -----
1396
+ Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.
1397
+
1398
+ If minimization doesn't complete successfully, with an error message of
1399
+ ``Desired error not necessarily achieved due to precision loss``, then
1400
+ consider setting `gtol` to a higher value. This precision loss typically
1401
+ occurs when the (finite difference) numerical differentiation cannot provide
1402
+ sufficient precision to satisfy the `gtol` termination criterion.
1403
+ This can happen when working in single precision and a callable jac is not
1404
+ provided. For single precision problems a `gtol` of 1e-3 seems to work.
1405
+ """
1406
+ _check_unknown_options(unknown_options)
1407
+ _check_positive_definite(hess_inv0)
1408
+ retall = return_all
1409
+
1410
+ x0 = asarray(x0).flatten()
1411
+ if x0.ndim == 0:
1412
+ x0.shape = (1,)
1413
+ if maxiter is None:
1414
+ maxiter = len(x0) * 200
1415
+
1416
+ sf = _prepare_scalar_function(fun, x0, jac, args=args, epsilon=eps,
1417
+ finite_diff_rel_step=finite_diff_rel_step,
1418
+ workers=workers)
1419
+
1420
+ f = sf.fun
1421
+ myfprime = sf.grad
1422
+
1423
+ old_fval = f(x0)
1424
+ gfk = myfprime(x0)
1425
+
1426
+ k = 0
1427
+ N = len(x0)
1428
+ I = np.eye(N, dtype=int)
1429
+ Hk = I if hess_inv0 is None else hess_inv0
1430
+
1431
+ # Sets the initial step guess to dx ~ 1
1432
+ old_old_fval = old_fval + np.linalg.norm(gfk) / 2
1433
+
1434
+ xk = x0
1435
+ if retall:
1436
+ allvecs = [x0]
1437
+ warnflag = 0
1438
+ gnorm = vecnorm(gfk, ord=norm)
1439
+ while (gnorm > gtol) and (k < maxiter):
1440
+ pk = -np.dot(Hk, gfk)
1441
+ try:
1442
+ alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \
1443
+ _line_search_wolfe12(f, myfprime, xk, pk, gfk,
1444
+ old_fval, old_old_fval, amin=1e-100,
1445
+ amax=1e100, c1=c1, c2=c2)
1446
+ except _LineSearchError:
1447
+ # Line search failed to find a better solution.
1448
+ warnflag = 2
1449
+ break
1450
+
1451
+ sk = alpha_k * pk
1452
+ xkp1 = xk + sk
1453
+
1454
+ if retall:
1455
+ allvecs.append(xkp1)
1456
+ xk = xkp1
1457
+ if gfkp1 is None:
1458
+ gfkp1 = myfprime(xkp1)
1459
+
1460
+ yk = gfkp1 - gfk
1461
+ gfk = gfkp1
1462
+ k += 1
1463
+ intermediate_result = OptimizeResult(x=xk, fun=old_fval)
1464
+ if _call_callback_maybe_halt(callback, intermediate_result):
1465
+ break
1466
+ gnorm = vecnorm(gfk, ord=norm)
1467
+ if (gnorm <= gtol):
1468
+ break
1469
+
1470
+ # See Chapter 5 in P.E. Frandsen, K. Jonasson, H.B. Nielsen,
1471
+ # O. Tingleff: "Unconstrained Optimization", IMM, DTU. 1999.
1472
+ # These notes are available here:
1473
+ # http://www2.imm.dtu.dk/documents/ftp/publlec.html
1474
+ if (alpha_k*vecnorm(pk) <= xrtol*(xrtol + vecnorm(xk))):
1475
+ break
1476
+
1477
+ if not np.isfinite(old_fval):
1478
+ # We correctly found +-Inf as optimal value, or something went
1479
+ # wrong.
1480
+ warnflag = 2
1481
+ break
1482
+
1483
+ rhok_inv = np.dot(yk, sk)
1484
+ # this was handled in numeric, let it remains for more safety
1485
+ # Cryptic comment above is preserved for posterity. Future reader:
1486
+ # consider change to condition below proposed in gh-1261/gh-17345.
1487
+ if rhok_inv == 0.:
1488
+ rhok = 1000.0
1489
+ if disp:
1490
+ msg = "Divide-by-zero encountered: rhok assumed large"
1491
+ _print_success_message_or_warn(True, msg)
1492
+ else:
1493
+ rhok = 1. / rhok_inv
1494
+
1495
+ A1 = I - sk[:, np.newaxis] * yk[np.newaxis, :] * rhok
1496
+ A2 = I - yk[:, np.newaxis] * sk[np.newaxis, :] * rhok
1497
+ Hk = np.dot(A1, np.dot(Hk, A2)) + (rhok * sk[:, np.newaxis] *
1498
+ sk[np.newaxis, :])
1499
+
1500
+ fval = old_fval
1501
+
1502
+ if warnflag == 2:
1503
+ msg = _status_message['pr_loss']
1504
+ elif k >= maxiter:
1505
+ warnflag = 1
1506
+ msg = _status_message['maxiter']
1507
+ elif np.isnan(gnorm) or np.isnan(fval) or np.isnan(xk).any():
1508
+ warnflag = 3
1509
+ msg = _status_message['nan']
1510
+ else:
1511
+ msg = _status_message['success']
1512
+
1513
+ if disp:
1514
+ _print_success_message_or_warn(warnflag, msg)
1515
+ print(f" Current function value: {fval:f}")
1516
+ print(f" Iterations: {k:d}")
1517
+ print(f" Function evaluations: {sf.nfev:d}")
1518
+ print(f" Gradient evaluations: {sf.ngev:d}")
1519
+
1520
+ result = OptimizeResult(fun=fval, jac=gfk, hess_inv=Hk, nfev=sf.nfev,
1521
+ njev=sf.ngev, status=warnflag,
1522
+ success=(warnflag == 0), message=msg, x=xk,
1523
+ nit=k)
1524
+ if retall:
1525
+ result['allvecs'] = allvecs
1526
+ return result
1527
+
1528
+
1529
+ def _print_success_message_or_warn(warnflag, message, warntype=None):
1530
+ if not warnflag:
1531
+ print(message)
1532
+ else:
1533
+ warnings.warn(message, warntype or OptimizeWarning, stacklevel=3)
1534
+
1535
+
1536
+ def fmin_cg(f, x0, fprime=None, args=(), gtol=1e-5, norm=np.inf,
1537
+ epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0,
1538
+ callback=None, c1=1e-4, c2=0.4):
1539
+ """
1540
+ Minimize a function using a nonlinear conjugate gradient algorithm.
1541
+
1542
+ Parameters
1543
+ ----------
1544
+ f : callable, ``f(x, *args)``
1545
+ Objective function to be minimized. Here `x` must be a 1-D array of
1546
+ the variables that are to be changed in the search for a minimum, and
1547
+ `args` are the other (fixed) parameters of `f`.
1548
+ x0 : ndarray
1549
+ A user-supplied initial estimate of `xopt`, the optimal value of `x`.
1550
+ It must be a 1-D array of values.
1551
+ fprime : callable, ``fprime(x, *args)``, optional
1552
+ A function that returns the gradient of `f` at `x`. Here `x` and `args`
1553
+ are as described above for `f`. The returned value must be a 1-D array.
1554
+ Defaults to None, in which case the gradient is approximated
1555
+ numerically (see `epsilon`, below).
1556
+ args : tuple, optional
1557
+ Parameter values passed to `f` and `fprime`. Must be supplied whenever
1558
+ additional fixed parameters are needed to completely specify the
1559
+ functions `f` and `fprime`.
1560
+ gtol : float, optional
1561
+ Stop when the norm of the gradient is less than `gtol`.
1562
+ norm : float, optional
1563
+ Order to use for the norm of the gradient
1564
+ (``-np.inf`` is min, ``np.inf`` is max).
1565
+ epsilon : float or ndarray, optional
1566
+ Step size(s) to use when `fprime` is approximated numerically. Can be a
1567
+ scalar or a 1-D array. Defaults to ``sqrt(eps)``, with eps the
1568
+ floating point machine precision. Usually ``sqrt(eps)`` is about
1569
+ 1.5e-8.
1570
+ maxiter : int, optional
1571
+ Maximum number of iterations to perform. Default is ``200 * len(x0)``.
1572
+ full_output : bool, optional
1573
+ If True, return `fopt`, `func_calls`, `grad_calls`, and `warnflag` in
1574
+ addition to `xopt`. See the Returns section below for additional
1575
+ information on optional return values.
1576
+ disp : bool, optional
1577
+ If True, return a convergence message, followed by `xopt`.
1578
+ retall : bool, optional
1579
+ If True, add to the returned values the results of each iteration.
1580
+ callback : callable, optional
1581
+ An optional user-supplied function, called after each iteration.
1582
+ Called as ``callback(xk)``, where ``xk`` is the current value of `x0`.
1583
+ c1 : float, default: 1e-4
1584
+ Parameter for Armijo condition rule.
1585
+ c2 : float, default: 0.4
1586
+ Parameter for curvature condition rule.
1587
+
1588
+ Returns
1589
+ -------
1590
+ xopt : ndarray
1591
+ Parameters which minimize f, i.e., ``f(xopt) == fopt``.
1592
+ fopt : float, optional
1593
+ Minimum value found, f(xopt). Only returned if `full_output` is True.
1594
+ func_calls : int, optional
1595
+ The number of function_calls made. Only returned if `full_output`
1596
+ is True.
1597
+ grad_calls : int, optional
1598
+ The number of gradient calls made. Only returned if `full_output` is
1599
+ True.
1600
+ warnflag : int, optional
1601
+ Integer value with warning status, only returned if `full_output` is
1602
+ True.
1603
+
1604
+ 0 : Success.
1605
+
1606
+ 1 : The maximum number of iterations was exceeded.
1607
+
1608
+ 2 : Gradient and/or function calls were not changing. May indicate
1609
+ that precision was lost, i.e., the routine did not converge.
1610
+
1611
+ 3 : NaN result encountered.
1612
+
1613
+ allvecs : list of ndarray, optional
1614
+ List of arrays, containing the results at each iteration.
1615
+ Only returned if `retall` is True.
1616
+
1617
+ See Also
1618
+ --------
1619
+ minimize : common interface to all `scipy.optimize` algorithms for
1620
+ unconstrained and constrained minimization of multivariate
1621
+ functions. It provides an alternative way to call
1622
+ ``fmin_cg``, by specifying ``method='CG'``.
1623
+
1624
+ Notes
1625
+ -----
1626
+ This conjugate gradient algorithm is based on that of Polak and Ribiere
1627
+ [1]_.
1628
+
1629
+ Conjugate gradient methods tend to work better when:
1630
+
1631
+ 1. `f` has a unique global minimizing point, and no local minima or
1632
+ other stationary points,
1633
+ 2. `f` is, at least locally, reasonably well approximated by a
1634
+ quadratic function of the variables,
1635
+ 3. `f` is continuous and has a continuous gradient,
1636
+ 4. `fprime` is not too large, e.g., has a norm less than 1000,
1637
+ 5. The initial guess, `x0`, is reasonably close to `f` 's global
1638
+ minimizing point, `xopt`.
1639
+
1640
+ Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.
1641
+
1642
+ References
1643
+ ----------
1644
+ .. [1] Wright & Nocedal, "Numerical Optimization", 1999, pp. 120-122.
1645
+
1646
+ Examples
1647
+ --------
1648
+ Example 1: seek the minimum value of the expression
1649
+ ``a*u**2 + b*u*v + c*v**2 + d*u + e*v + f`` for given values
1650
+ of the parameters and an initial guess ``(u, v) = (0, 0)``.
1651
+
1652
+ >>> import numpy as np
1653
+ >>> args = (2, 3, 7, 8, 9, 10) # parameter values
1654
+ >>> def f(x, *args):
1655
+ ... u, v = x
1656
+ ... a, b, c, d, e, f = args
1657
+ ... return a*u**2 + b*u*v + c*v**2 + d*u + e*v + f
1658
+ >>> def gradf(x, *args):
1659
+ ... u, v = x
1660
+ ... a, b, c, d, e, f = args
1661
+ ... gu = 2*a*u + b*v + d # u-component of the gradient
1662
+ ... gv = b*u + 2*c*v + e # v-component of the gradient
1663
+ ... return np.asarray((gu, gv))
1664
+ >>> x0 = np.asarray((0, 0)) # Initial guess.
1665
+ >>> from scipy import optimize
1666
+ >>> res1 = optimize.fmin_cg(f, x0, fprime=gradf, args=args)
1667
+ Optimization terminated successfully.
1668
+ Current function value: 1.617021
1669
+ Iterations: 4
1670
+ Function evaluations: 8
1671
+ Gradient evaluations: 8
1672
+ >>> res1
1673
+ array([-1.80851064, -0.25531915])
1674
+
1675
+ Example 2: solve the same problem using the `minimize` function.
1676
+ (This `myopts` dictionary shows all of the available options,
1677
+ although in practice only non-default values would be needed.
1678
+ The returned value will be a dictionary.)
1679
+
1680
+ >>> opts = {'maxiter' : None, # default value.
1681
+ ... 'disp' : True, # non-default value.
1682
+ ... 'gtol' : 1e-5, # default value.
1683
+ ... 'norm' : np.inf, # default value.
1684
+ ... 'eps' : 1.4901161193847656e-08} # default value.
1685
+ >>> res2 = optimize.minimize(f, x0, jac=gradf, args=args,
1686
+ ... method='CG', options=opts)
1687
+ Optimization terminated successfully.
1688
+ Current function value: 1.617021
1689
+ Iterations: 4
1690
+ Function evaluations: 8
1691
+ Gradient evaluations: 8
1692
+ >>> res2.x # minimum found
1693
+ array([-1.80851064, -0.25531915])
1694
+
1695
+ """
1696
+ opts = {'gtol': gtol,
1697
+ 'norm': norm,
1698
+ 'eps': epsilon,
1699
+ 'disp': disp,
1700
+ 'maxiter': maxiter,
1701
+ 'return_all': retall}
1702
+
1703
+ callback = _wrap_callback(callback)
1704
+ res = _minimize_cg(f, x0, args, fprime, callback=callback, c1=c1, c2=c2,
1705
+ **opts)
1706
+
1707
+ if full_output:
1708
+ retlist = res['x'], res['fun'], res['nfev'], res['njev'], res['status']
1709
+ if retall:
1710
+ retlist += (res['allvecs'], )
1711
+ return retlist
1712
+ else:
1713
+ if retall:
1714
+ return res['x'], res['allvecs']
1715
+ else:
1716
+ return res['x']
1717
+
1718
+
1719
+ def _minimize_cg(fun, x0, args=(), jac=None, callback=None,
1720
+ gtol=1e-5, norm=np.inf, eps=_epsilon, maxiter=None,
1721
+ disp=False, return_all=False, finite_diff_rel_step=None,
1722
+ c1=1e-4, c2=0.4, workers=None,
1723
+ **unknown_options):
1724
+ """
1725
+ Minimization of scalar function of one or more variables using the
1726
+ conjugate gradient algorithm.
1727
+
1728
+ Options
1729
+ -------
1730
+ disp : bool
1731
+ Set to True to print convergence messages.
1732
+ maxiter : int
1733
+ Maximum number of iterations to perform.
1734
+ gtol : float
1735
+ Gradient norm must be less than `gtol` before successful
1736
+ termination.
1737
+ norm : float
1738
+ Order of norm (Inf is max, -Inf is min).
1739
+ eps : float or ndarray
1740
+ If `jac is None` the absolute step size used for numerical
1741
+ approximation of the jacobian via forward differences.
1742
+ return_all : bool, optional
1743
+ Set to True to return a list of the best solution at each of the
1744
+ iterations.
1745
+ finite_diff_rel_step : None or array_like, optional
1746
+ If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to
1747
+ use for numerical approximation of the jacobian. The absolute step
1748
+ size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``,
1749
+ possibly adjusted to fit into the bounds. For ``jac='3-point'``
1750
+ the sign of `h` is ignored. If None (default) then step is selected
1751
+ automatically.
1752
+ c1 : float, default: 1e-4
1753
+ Parameter for Armijo condition rule.
1754
+ c2 : float, default: 0.4
1755
+ Parameter for curvature condition rule.
1756
+ workers : int, map-like callable, optional
1757
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
1758
+ any numerical differentiation in parallel.
1759
+ This evaluation is carried out as ``workers(fun, iterable)``.
1760
+
1761
+ .. versionadded:: 1.16.0
1762
+
1763
+ Notes
1764
+ -----
1765
+ Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.
1766
+ """
1767
+ _check_unknown_options(unknown_options)
1768
+
1769
+ retall = return_all
1770
+
1771
+ x0 = asarray(x0).flatten()
1772
+ if maxiter is None:
1773
+ maxiter = len(x0) * 200
1774
+
1775
+ sf = _prepare_scalar_function(fun, x0, jac=jac, args=args, epsilon=eps,
1776
+ finite_diff_rel_step=finite_diff_rel_step,
1777
+ workers=workers)
1778
+
1779
+ f = sf.fun
1780
+ myfprime = sf.grad
1781
+
1782
+ old_fval = f(x0)
1783
+ gfk = myfprime(x0)
1784
+
1785
+ k = 0
1786
+ xk = x0
1787
+ # Sets the initial step guess to dx ~ 1
1788
+ old_old_fval = old_fval + np.linalg.norm(gfk) / 2
1789
+
1790
+ if retall:
1791
+ allvecs = [xk]
1792
+ warnflag = 0
1793
+ pk = -gfk
1794
+ gnorm = vecnorm(gfk, ord=norm)
1795
+
1796
+ sigma_3 = 0.01
1797
+
1798
+ while (gnorm > gtol) and (k < maxiter):
1799
+ deltak = np.dot(gfk, gfk)
1800
+
1801
+ cached_step = [None]
1802
+
1803
+ def polak_ribiere_powell_step(alpha, gfkp1=None):
1804
+ xkp1 = xk + alpha * pk
1805
+ if gfkp1 is None:
1806
+ gfkp1 = myfprime(xkp1)
1807
+ yk = gfkp1 - gfk
1808
+ beta_k = max(0, np.dot(yk, gfkp1) / deltak)
1809
+ pkp1 = -gfkp1 + beta_k * pk
1810
+ gnorm = vecnorm(gfkp1, ord=norm)
1811
+ return (alpha, xkp1, pkp1, gfkp1, gnorm)
1812
+
1813
+ def descent_condition(alpha, xkp1, fp1, gfkp1):
1814
+ # Polak-Ribiere+ needs an explicit check of a sufficient
1815
+ # descent condition, which is not guaranteed by strong Wolfe.
1816
+ #
1817
+ # See Gilbert & Nocedal, "Global convergence properties of
1818
+ # conjugate gradient methods for optimization",
1819
+ # SIAM J. Optimization 2, 21 (1992).
1820
+ cached_step[:] = polak_ribiere_powell_step(alpha, gfkp1)
1821
+ alpha, xk, pk, gfk, gnorm = cached_step
1822
+
1823
+ # Accept step if it leads to convergence.
1824
+ if gnorm <= gtol:
1825
+ return True
1826
+
1827
+ # Accept step if sufficient descent condition applies.
1828
+ return np.dot(pk, gfk) <= -sigma_3 * np.dot(gfk, gfk)
1829
+
1830
+ try:
1831
+ alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \
1832
+ _line_search_wolfe12(f, myfprime, xk, pk, gfk, old_fval,
1833
+ old_old_fval, c1=c1, c2=c2, amin=1e-100,
1834
+ amax=1e100, extra_condition=descent_condition)
1835
+ except _LineSearchError:
1836
+ # Line search failed to find a better solution.
1837
+ warnflag = 2
1838
+ break
1839
+
1840
+ # Reuse already computed results if possible
1841
+ if alpha_k == cached_step[0]:
1842
+ alpha_k, xk, pk, gfk, gnorm = cached_step
1843
+ else:
1844
+ alpha_k, xk, pk, gfk, gnorm = polak_ribiere_powell_step(alpha_k, gfkp1)
1845
+
1846
+ if retall:
1847
+ allvecs.append(xk)
1848
+ k += 1
1849
+ intermediate_result = OptimizeResult(x=xk, fun=old_fval)
1850
+ if _call_callback_maybe_halt(callback, intermediate_result):
1851
+ break
1852
+
1853
+ fval = old_fval
1854
+ if warnflag == 2:
1855
+ msg = _status_message['pr_loss']
1856
+ elif k >= maxiter:
1857
+ warnflag = 1
1858
+ msg = _status_message['maxiter']
1859
+ elif np.isnan(gnorm) or np.isnan(fval) or np.isnan(xk).any():
1860
+ warnflag = 3
1861
+ msg = _status_message['nan']
1862
+ else:
1863
+ msg = _status_message['success']
1864
+
1865
+ if disp:
1866
+ _print_success_message_or_warn(warnflag, msg)
1867
+ print(f" Current function value: {fval:f}")
1868
+ print(f" Iterations: {k:d}")
1869
+ print(f" Function evaluations: {sf.nfev:d}")
1870
+ print(f" Gradient evaluations: {sf.ngev:d}")
1871
+
1872
+ result = OptimizeResult(fun=fval, jac=gfk, nfev=sf.nfev,
1873
+ njev=sf.ngev, status=warnflag,
1874
+ success=(warnflag == 0), message=msg, x=xk,
1875
+ nit=k)
1876
+ if retall:
1877
+ result['allvecs'] = allvecs
1878
+ return result
1879
+
1880
+
1881
+ def fmin_ncg(f, x0, fprime, fhess_p=None, fhess=None, args=(), avextol=1e-5,
1882
+ epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0,
1883
+ callback=None, c1=1e-4, c2=0.9):
1884
+ """
1885
+ Unconstrained minimization of a function using the Newton-CG method.
1886
+
1887
+ Parameters
1888
+ ----------
1889
+ f : callable ``f(x, *args)``
1890
+ Objective function to be minimized.
1891
+ x0 : ndarray
1892
+ Initial guess.
1893
+ fprime : callable ``f'(x, *args)``
1894
+ Gradient of f.
1895
+ fhess_p : callable ``fhess_p(x, p, *args)``, optional
1896
+ Function which computes the Hessian of f times an
1897
+ arbitrary vector, p.
1898
+ fhess : callable ``fhess(x, *args)``, optional
1899
+ Function to compute the Hessian matrix of f.
1900
+ args : tuple, optional
1901
+ Extra arguments passed to f, fprime, fhess_p, and fhess
1902
+ (the same set of extra arguments is supplied to all of
1903
+ these functions).
1904
+ epsilon : float or ndarray, optional
1905
+ If fhess is approximated, use this value for the step size.
1906
+ callback : callable, optional
1907
+ An optional user-supplied function which is called after
1908
+ each iteration. Called as callback(xk), where xk is the
1909
+ current parameter vector.
1910
+ avextol : float, optional
1911
+ Convergence is assumed when the average relative error in
1912
+ the minimizer falls below this amount.
1913
+ maxiter : int, optional
1914
+ Maximum number of iterations to perform.
1915
+ full_output : bool, optional
1916
+ If True, return the optional outputs.
1917
+ disp : bool, optional
1918
+ If True, print convergence message.
1919
+ retall : bool, optional
1920
+ If True, return a list of results at each iteration.
1921
+ c1 : float, default: 1e-4
1922
+ Parameter for Armijo condition rule.
1923
+ c2 : float, default: 0.9
1924
+ Parameter for curvature condition rule
1925
+
1926
+ Returns
1927
+ -------
1928
+ xopt : ndarray
1929
+ Parameters which minimize f, i.e., ``f(xopt) == fopt``.
1930
+ fopt : float
1931
+ Value of the function at xopt, i.e., ``fopt = f(xopt)``.
1932
+ fcalls : int
1933
+ Number of function calls made.
1934
+ gcalls : int
1935
+ Number of gradient calls made.
1936
+ hcalls : int
1937
+ Number of Hessian calls made.
1938
+ warnflag : int
1939
+ Warnings generated by the algorithm.
1940
+ 1 : Maximum number of iterations exceeded.
1941
+ 2 : Line search failure (precision loss).
1942
+ 3 : NaN result encountered.
1943
+ allvecs : list
1944
+ The result at each iteration, if retall is True (see below).
1945
+
1946
+ See also
1947
+ --------
1948
+ minimize: Interface to minimization algorithms for multivariate
1949
+ functions. See the 'Newton-CG' `method` in particular.
1950
+
1951
+ Notes
1952
+ -----
1953
+ Only one of `fhess_p` or `fhess` need to be given. If `fhess`
1954
+ is provided, then `fhess_p` will be ignored. If neither `fhess`
1955
+ nor `fhess_p` is provided, then the hessian product will be
1956
+ approximated using finite differences on `fprime`. `fhess_p`
1957
+ must compute the hessian times an arbitrary vector. If it is not
1958
+ given, finite-differences on `fprime` are used to compute
1959
+ it.
1960
+
1961
+ Newton-CG methods are also called truncated Newton methods. This
1962
+ function differs from scipy.optimize.fmin_tnc because
1963
+
1964
+ 1. scipy.optimize.fmin_ncg is written purely in Python using NumPy
1965
+ and scipy while scipy.optimize.fmin_tnc calls a C function.
1966
+ 2. scipy.optimize.fmin_ncg is only for unconstrained minimization
1967
+ while scipy.optimize.fmin_tnc is for unconstrained minimization
1968
+ or box constrained minimization. (Box constraints give
1969
+ lower and upper bounds for each variable separately.)
1970
+
1971
+ Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.
1972
+
1973
+ References
1974
+ ----------
1975
+ Wright & Nocedal, 'Numerical Optimization', 1999, p. 140.
1976
+
1977
+ """
1978
+ opts = {'xtol': avextol,
1979
+ 'eps': epsilon,
1980
+ 'maxiter': maxiter,
1981
+ 'disp': disp,
1982
+ 'return_all': retall}
1983
+
1984
+ callback = _wrap_callback(callback)
1985
+ res = _minimize_newtoncg(f, x0, args, fprime, fhess, fhess_p,
1986
+ callback=callback, c1=c1, c2=c2, **opts)
1987
+
1988
+ if full_output:
1989
+ retlist = (res['x'], res['fun'], res['nfev'], res['njev'],
1990
+ res['nhev'], res['status'])
1991
+ if retall:
1992
+ retlist += (res['allvecs'], )
1993
+ return retlist
1994
+ else:
1995
+ if retall:
1996
+ return res['x'], res['allvecs']
1997
+ else:
1998
+ return res['x']
1999
+
2000
+
2001
+ def _minimize_newtoncg(fun, x0, args=(), jac=None, hess=None, hessp=None,
2002
+ callback=None, xtol=1e-5, eps=_epsilon, maxiter=None,
2003
+ disp=False, return_all=False, c1=1e-4, c2=0.9, workers=None,
2004
+ **unknown_options):
2005
+ """
2006
+ Minimization of scalar function of one or more variables using the
2007
+ Newton-CG algorithm.
2008
+
2009
+ Note that the `jac` parameter (Jacobian) is required.
2010
+
2011
+ Options
2012
+ -------
2013
+ disp : bool
2014
+ Set to True to print convergence messages.
2015
+ xtol : float
2016
+ Average relative error in solution `xopt` acceptable for
2017
+ convergence.
2018
+ maxiter : int
2019
+ Maximum number of iterations to perform.
2020
+ eps : float or ndarray
2021
+ If `hessp` is approximated, use this value for the step size.
2022
+ return_all : bool, optional
2023
+ Set to True to return a list of the best solution at each of the
2024
+ iterations.
2025
+ c1 : float, default: 1e-4
2026
+ Parameter for Armijo condition rule.
2027
+ c2 : float, default: 0.9
2028
+ Parameter for curvature condition rule.
2029
+ workers : int, map-like callable, optional
2030
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
2031
+ any numerical differentiation in parallel.
2032
+ This evaluation is carried out as ``workers(fun, iterable)``.
2033
+
2034
+ .. versionadded:: 1.16.0
2035
+
2036
+ Notes
2037
+ -----
2038
+ Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.
2039
+ """
2040
+ _check_unknown_options(unknown_options)
2041
+ if jac is None:
2042
+ raise ValueError('Jacobian is required for Newton-CG method')
2043
+ fhess_p = hessp
2044
+ fhess = hess
2045
+ avextol = xtol
2046
+ epsilon = eps
2047
+ retall = return_all
2048
+
2049
+ x0 = asarray(x0).flatten()
2050
+ # TODO: add hessp (callable or FD) to ScalarFunction?
2051
+ sf = _prepare_scalar_function(
2052
+ fun, x0, jac, args=args, epsilon=eps, hess=hess, workers=workers
2053
+ )
2054
+ f = sf.fun
2055
+ fprime = sf.grad
2056
+ _h = sf.hess(x0)
2057
+
2058
+ # Logic for hess/hessp
2059
+ # - If a callable(hess) is provided, then use that
2060
+ # - If hess is a FD_METHOD, or the output from hess(x) is a LinearOperator
2061
+ # then create a hessp function using those.
2062
+ # - If hess is None but you have callable(hessp) then use the hessp.
2063
+ # - If hess and hessp are None then approximate hessp using the grad/jac.
2064
+
2065
+ if (hess in FD_METHODS or isinstance(_h, LinearOperator)):
2066
+ fhess = None
2067
+
2068
+ def _hessp(x, p, *args):
2069
+ return sf.hess(x).dot(p)
2070
+
2071
+ fhess_p = _hessp
2072
+
2073
+ def terminate(warnflag, msg):
2074
+ if disp:
2075
+ _print_success_message_or_warn(warnflag, msg)
2076
+ print(f" Current function value: {old_fval:f}")
2077
+ print(f" Iterations: {k:d}")
2078
+ print(f" Function evaluations: {sf.nfev:d}")
2079
+ print(f" Gradient evaluations: {sf.ngev:d}")
2080
+ print(f" Hessian evaluations: {hcalls:d}")
2081
+ fval = old_fval
2082
+ result = OptimizeResult(fun=fval, jac=gfk, nfev=sf.nfev,
2083
+ njev=sf.ngev, nhev=hcalls, status=warnflag,
2084
+ success=(warnflag == 0), message=msg, x=xk,
2085
+ nit=k)
2086
+ if retall:
2087
+ result['allvecs'] = allvecs
2088
+ return result
2089
+
2090
+ hcalls = 0
2091
+ if maxiter is None:
2092
+ maxiter = len(x0)*200
2093
+ cg_maxiter = 20*len(x0)
2094
+
2095
+ xtol = len(x0) * avextol
2096
+ # Make sure we enter the while loop.
2097
+ update_l1norm = np.finfo(float).max
2098
+ xk = np.copy(x0)
2099
+ if retall:
2100
+ allvecs = [xk]
2101
+ k = 0
2102
+ gfk = None
2103
+ old_fval = f(x0)
2104
+ old_old_fval = None
2105
+ float64eps = np.finfo(np.float64).eps
2106
+ while update_l1norm > xtol:
2107
+ if k >= maxiter:
2108
+ msg = "Warning: " + _status_message['maxiter']
2109
+ return terminate(1, msg)
2110
+ # Compute a search direction pk by applying the CG method to
2111
+ # del2 f(xk) p = - grad f(xk) starting from 0.
2112
+ b = -fprime(xk)
2113
+ maggrad = np.linalg.norm(b, ord=1)
2114
+ eta = min(0.5, math.sqrt(maggrad))
2115
+ termcond = eta * maggrad
2116
+ xsupi = zeros(len(x0), dtype=x0.dtype)
2117
+ ri = -b
2118
+ psupi = -ri
2119
+ i = 0
2120
+ dri0 = np.dot(ri, ri)
2121
+
2122
+ if fhess is not None: # you want to compute hessian once.
2123
+ A = sf.hess(xk)
2124
+ hcalls += 1
2125
+
2126
+ for k2 in range(cg_maxiter):
2127
+ if np.add.reduce(np.abs(ri)) <= termcond:
2128
+ break
2129
+ if fhess is None:
2130
+ if fhess_p is None:
2131
+ Ap = approx_fhess_p(xk, psupi, fprime, epsilon)
2132
+ else:
2133
+ Ap = fhess_p(xk, psupi, *args)
2134
+ hcalls += 1
2135
+ else:
2136
+ # hess was supplied as a callable or hessian update strategy, so
2137
+ # A is a dense numpy array or sparse array
2138
+ Ap = A.dot(psupi)
2139
+ # check curvature
2140
+ Ap = asarray(Ap).squeeze() # get rid of matrices...
2141
+ curv = np.dot(psupi, Ap)
2142
+ if 0 <= curv <= 3 * float64eps:
2143
+ break
2144
+ elif curv < 0:
2145
+ if (i > 0):
2146
+ break
2147
+ else:
2148
+ # fall back to steepest descent direction
2149
+ xsupi = dri0 / (-curv) * b
2150
+ break
2151
+ alphai = dri0 / curv
2152
+ xsupi += alphai * psupi
2153
+ ri += alphai * Ap
2154
+ dri1 = np.dot(ri, ri)
2155
+ betai = dri1 / dri0
2156
+ psupi = -ri + betai * psupi
2157
+ i += 1
2158
+ dri0 = dri1 # update np.dot(ri,ri) for next time.
2159
+ else:
2160
+ # curvature keeps increasing, bail out
2161
+ msg = ("Warning: CG iterations didn't converge. The Hessian is not "
2162
+ "positive definite.")
2163
+ return terminate(3, msg)
2164
+
2165
+ pk = xsupi # search direction is solution to system.
2166
+ gfk = -b # gradient at xk
2167
+
2168
+ try:
2169
+ alphak, fc, gc, old_fval, old_old_fval, gfkp1 = \
2170
+ _line_search_wolfe12(f, fprime, xk, pk, gfk,
2171
+ old_fval, old_old_fval, c1=c1, c2=c2)
2172
+ except _LineSearchError:
2173
+ # Line search failed to find a better solution.
2174
+ msg = "Warning: " + _status_message['pr_loss']
2175
+ return terminate(2, msg)
2176
+
2177
+ update = alphak * pk
2178
+ xk += update # upcast if necessary
2179
+ if retall:
2180
+ allvecs.append(xk)
2181
+ k += 1
2182
+ intermediate_result = OptimizeResult(x=xk, fun=old_fval)
2183
+ if _call_callback_maybe_halt(callback, intermediate_result):
2184
+ return terminate(5, "")
2185
+ update_l1norm = np.linalg.norm(update, ord=1)
2186
+
2187
+ else:
2188
+ if np.isnan(old_fval) or np.isnan(update_l1norm):
2189
+ return terminate(3, _status_message['nan'])
2190
+
2191
+ msg = _status_message['success']
2192
+ return terminate(0, msg)
2193
+
2194
+
2195
+ def fminbound(func, x1, x2, args=(), xtol=1e-5, maxfun=500,
2196
+ full_output=0, disp=1):
2197
+ """Bounded minimization for scalar functions.
2198
+
2199
+ Parameters
2200
+ ----------
2201
+ func : callable f(x,*args)
2202
+ Objective function to be minimized (must accept and return scalars).
2203
+ x1, x2 : float or array scalar
2204
+ Finite optimization bounds.
2205
+ args : tuple, optional
2206
+ Extra arguments passed to function.
2207
+ xtol : float, optional
2208
+ The convergence tolerance.
2209
+ maxfun : int, optional
2210
+ Maximum number of function evaluations allowed.
2211
+ full_output : bool, optional
2212
+ If True, return optional outputs.
2213
+ disp: int, optional
2214
+ If non-zero, print messages.
2215
+
2216
+ ``0`` : no message printing.
2217
+
2218
+ ``1`` : non-convergence notification messages only.
2219
+
2220
+ ``2`` : print a message on convergence too.
2221
+
2222
+ ``3`` : print iteration results.
2223
+
2224
+ Returns
2225
+ -------
2226
+ xopt : ndarray
2227
+ Parameters (over given interval) which minimize the
2228
+ objective function.
2229
+ fval : number
2230
+ (Optional output) The function value evaluated at the minimizer.
2231
+ ierr : int
2232
+ (Optional output) An error flag (0 if converged, 1 if maximum number of
2233
+ function calls reached).
2234
+ numfunc : int
2235
+ (Optional output) The number of function calls made.
2236
+
2237
+ See also
2238
+ --------
2239
+ minimize_scalar: Interface to minimization algorithms for scalar
2240
+ univariate functions. See the 'Bounded' `method` in particular.
2241
+
2242
+ Notes
2243
+ -----
2244
+ Finds a local minimizer of the scalar function `func` in the
2245
+ interval x1 < xopt < x2 using Brent's method. (See `brent`
2246
+ for auto-bracketing.)
2247
+
2248
+ References
2249
+ ----------
2250
+ .. [1] Forsythe, G.E., M. A. Malcolm, and C. B. Moler. "Computer Methods
2251
+ for Mathematical Computations." Prentice-Hall Series in Automatic
2252
+ Computation 259 (1977).
2253
+ .. [2] Brent, Richard P. Algorithms for Minimization Without Derivatives.
2254
+ Courier Corporation, 2013.
2255
+
2256
+ Examples
2257
+ --------
2258
+ `fminbound` finds the minimizer of the function in the given range.
2259
+ The following examples illustrate this.
2260
+
2261
+ >>> from scipy import optimize
2262
+ >>> def f(x):
2263
+ ... return (x-1)**2
2264
+ >>> minimizer = optimize.fminbound(f, -4, 4)
2265
+ >>> minimizer
2266
+ 1.0
2267
+ >>> minimum = f(minimizer)
2268
+ >>> minimum
2269
+ 0.0
2270
+ >>> res = optimize.fminbound(f, 3, 4, full_output=True)
2271
+ >>> minimizer, fval, ierr, numfunc = res
2272
+ >>> minimizer
2273
+ 3.000005960860986
2274
+ >>> minimum = f(minimizer)
2275
+ >>> minimum, fval
2276
+ (4.000023843479476, 4.000023843479476)
2277
+ """
2278
+ options = {'xatol': xtol,
2279
+ 'maxiter': maxfun,
2280
+ 'disp': disp}
2281
+
2282
+ res = _minimize_scalar_bounded(func, (x1, x2), args, **options)
2283
+ if full_output:
2284
+ return res['x'], res['fun'], res['status'], res['nfev']
2285
+ else:
2286
+ return res['x']
2287
+
2288
+
2289
+ def _minimize_scalar_bounded(func, bounds, args=(),
2290
+ xatol=1e-5, maxiter=500, disp=0,
2291
+ **unknown_options):
2292
+ """
2293
+ Options
2294
+ -------
2295
+ maxiter : int
2296
+ Maximum number of iterations to perform.
2297
+ disp: int, optional
2298
+ If non-zero, print messages.
2299
+
2300
+ ``0`` : no message printing.
2301
+
2302
+ ``1`` : non-convergence notification messages only.
2303
+
2304
+ ``2`` : print a message on convergence too.
2305
+
2306
+ ``3`` : print iteration results.
2307
+
2308
+ xatol : float
2309
+ Absolute error in solution `xopt` acceptable for convergence.
2310
+
2311
+ """
2312
+ _check_unknown_options(unknown_options)
2313
+ maxfun = maxiter
2314
+ # Test bounds are of correct form
2315
+ if len(bounds) != 2:
2316
+ raise ValueError('bounds must have two elements.')
2317
+ x1, x2 = bounds
2318
+
2319
+ if not (is_finite_scalar(x1) and is_finite_scalar(x2)):
2320
+ raise ValueError("Optimization bounds must be finite scalars.")
2321
+
2322
+ if x1 > x2:
2323
+ raise ValueError("The lower bound exceeds the upper bound.")
2324
+
2325
+ flag = 0
2326
+ header = ' Func-count x f(x) Procedure'
2327
+ step = ' initial'
2328
+
2329
+ sqrt_eps = sqrt(2.2e-16)
2330
+ golden_mean = 0.5 * (3.0 - sqrt(5.0))
2331
+ a, b = x1, x2
2332
+ fulc = a + golden_mean * (b - a)
2333
+ nfc, xf = fulc, fulc
2334
+ rat = e = 0.0
2335
+ x = xf
2336
+ fx = func(x, *args)
2337
+ num = 1
2338
+ fmin_data = (1, xf, fx)
2339
+ fu = np.inf
2340
+
2341
+ ffulc = fnfc = fx
2342
+ xm = 0.5 * (a + b)
2343
+ tol1 = sqrt_eps * np.abs(xf) + xatol / 3.0
2344
+ tol2 = 2.0 * tol1
2345
+
2346
+ if disp > 2:
2347
+ print(" ")
2348
+ print(header)
2349
+ print("%5.0f %12.6g %12.6g %s" % (fmin_data + (step,)))
2350
+
2351
+ while (np.abs(xf - xm) > (tol2 - 0.5 * (b - a))):
2352
+ golden = 1
2353
+ # Check for parabolic fit
2354
+ if np.abs(e) > tol1:
2355
+ golden = 0
2356
+ r = (xf - nfc) * (fx - ffulc)
2357
+ q = (xf - fulc) * (fx - fnfc)
2358
+ p = (xf - fulc) * q - (xf - nfc) * r
2359
+ q = 2.0 * (q - r)
2360
+ if q > 0.0:
2361
+ p = -p
2362
+ q = np.abs(q)
2363
+ r = e
2364
+ e = rat
2365
+
2366
+ # Check for acceptability of parabola
2367
+ if ((np.abs(p) < np.abs(0.5*q*r)) and (p > q*(a - xf)) and
2368
+ (p < q * (b - xf))):
2369
+ rat = (p + 0.0) / q
2370
+ x = xf + rat
2371
+ step = ' parabolic'
2372
+
2373
+ if ((x - a) < tol2) or ((b - x) < tol2):
2374
+ si = np.sign(xm - xf) + ((xm - xf) == 0)
2375
+ rat = tol1 * si
2376
+ else: # do a golden-section step
2377
+ golden = 1
2378
+
2379
+ if golden: # do a golden-section step
2380
+ if xf >= xm:
2381
+ e = a - xf
2382
+ else:
2383
+ e = b - xf
2384
+ rat = golden_mean*e
2385
+ step = ' golden'
2386
+
2387
+ si = np.sign(rat) + (rat == 0)
2388
+ x = xf + si * np.maximum(np.abs(rat), tol1)
2389
+ fu = func(x, *args)
2390
+ num += 1
2391
+ fmin_data = (num, x, fu)
2392
+ if disp > 2:
2393
+ print("%5.0f %12.6g %12.6g %s" % (fmin_data + (step,)))
2394
+
2395
+ if fu <= fx:
2396
+ if x >= xf:
2397
+ a = xf
2398
+ else:
2399
+ b = xf
2400
+ fulc, ffulc = nfc, fnfc
2401
+ nfc, fnfc = xf, fx
2402
+ xf, fx = x, fu
2403
+ else:
2404
+ if x < xf:
2405
+ a = x
2406
+ else:
2407
+ b = x
2408
+ if (fu <= fnfc) or (nfc == xf):
2409
+ fulc, ffulc = nfc, fnfc
2410
+ nfc, fnfc = x, fu
2411
+ elif (fu <= ffulc) or (fulc == xf) or (fulc == nfc):
2412
+ fulc, ffulc = x, fu
2413
+
2414
+ xm = 0.5 * (a + b)
2415
+ tol1 = sqrt_eps * np.abs(xf) + xatol / 3.0
2416
+ tol2 = 2.0 * tol1
2417
+
2418
+ if num >= maxfun:
2419
+ flag = 1
2420
+ break
2421
+
2422
+ if np.isnan(xf) or np.isnan(fx) or np.isnan(fu):
2423
+ flag = 2
2424
+
2425
+ fval = fx
2426
+ if disp > 0:
2427
+ _endprint(x, flag, fval, maxfun, xatol, disp)
2428
+
2429
+ result = OptimizeResult(fun=fval, status=flag, success=(flag == 0),
2430
+ message={0: 'Solution found.',
2431
+ 1: 'Maximum number of function calls '
2432
+ 'reached.',
2433
+ 2: _status_message['nan']}.get(flag, ''),
2434
+ x=xf, nfev=num, nit=num)
2435
+
2436
+ return result
2437
+
2438
+
2439
+ class Brent:
2440
+ #need to rethink design of __init__
2441
+ def __init__(self, func, args=(), tol=1.48e-8, maxiter=500,
2442
+ full_output=0, disp=0):
2443
+ self.func = func
2444
+ self.args = args
2445
+ self.tol = tol
2446
+ self.maxiter = maxiter
2447
+ self._mintol = 1.0e-11
2448
+ self._cg = 0.3819660
2449
+ self.xmin = None
2450
+ self.fval = None
2451
+ self.iter = 0
2452
+ self.funcalls = 0
2453
+ self.disp = disp
2454
+
2455
+ # need to rethink design of set_bracket (new options, etc.)
2456
+ def set_bracket(self, brack=None):
2457
+ self.brack = brack
2458
+
2459
+ def get_bracket_info(self):
2460
+ #set up
2461
+ func = self.func
2462
+ args = self.args
2463
+ brack = self.brack
2464
+ ### BEGIN core bracket_info code ###
2465
+ ### carefully DOCUMENT any CHANGES in core ##
2466
+ if brack is None:
2467
+ xa, xb, xc, fa, fb, fc, funcalls = bracket(func, args=args)
2468
+ elif len(brack) == 2:
2469
+ xa, xb, xc, fa, fb, fc, funcalls = bracket(func, xa=brack[0],
2470
+ xb=brack[1], args=args)
2471
+ elif len(brack) == 3:
2472
+ xa, xb, xc = brack
2473
+ if (xa > xc): # swap so xa < xc can be assumed
2474
+ xc, xa = xa, xc
2475
+ if not ((xa < xb) and (xb < xc)):
2476
+ raise ValueError(
2477
+ "Bracketing values (xa, xb, xc) do not"
2478
+ " fulfill this requirement: (xa < xb) and (xb < xc)"
2479
+ )
2480
+ fa = func(*((xa,) + args))
2481
+ fb = func(*((xb,) + args))
2482
+ fc = func(*((xc,) + args))
2483
+ if not ((fb < fa) and (fb < fc)):
2484
+ raise ValueError(
2485
+ "Bracketing values (xa, xb, xc) do not fulfill"
2486
+ " this requirement: (f(xb) < f(xa)) and (f(xb) < f(xc))"
2487
+ )
2488
+
2489
+ funcalls = 3
2490
+ else:
2491
+ raise ValueError("Bracketing interval must be "
2492
+ "length 2 or 3 sequence.")
2493
+ ### END core bracket_info code ###
2494
+
2495
+ return xa, xb, xc, fa, fb, fc, funcalls
2496
+
2497
+ def optimize(self):
2498
+ # set up for optimization
2499
+ func = self.func
2500
+ xa, xb, xc, fa, fb, fc, funcalls = self.get_bracket_info()
2501
+ _mintol = self._mintol
2502
+ _cg = self._cg
2503
+ #################################
2504
+ #BEGIN CORE ALGORITHM
2505
+ #################################
2506
+ x = w = v = xb
2507
+ fw = fv = fx = fb
2508
+ if (xa < xc):
2509
+ a = xa
2510
+ b = xc
2511
+ else:
2512
+ a = xc
2513
+ b = xa
2514
+ deltax = 0.0
2515
+ iter = 0
2516
+
2517
+ if self.disp > 2:
2518
+ print(" ")
2519
+ print(f"{'Func-count':^12} {'x':^12} {'f(x)': ^12}")
2520
+ print(f"{funcalls:^12g} {x:^12.6g} {fx:^12.6g}")
2521
+
2522
+ while (iter < self.maxiter):
2523
+ tol1 = self.tol * np.abs(x) + _mintol
2524
+ tol2 = 2.0 * tol1
2525
+ xmid = 0.5 * (a + b)
2526
+ # check for convergence
2527
+ if np.abs(x - xmid) < (tol2 - 0.5 * (b - a)):
2528
+ break
2529
+ # XXX In the first iteration, rat is only bound in the true case
2530
+ # of this conditional. This used to cause an UnboundLocalError
2531
+ # (gh-4140). It should be set before the if (but to what?).
2532
+ if (np.abs(deltax) <= tol1):
2533
+ if (x >= xmid):
2534
+ deltax = a - x # do a golden section step
2535
+ else:
2536
+ deltax = b - x
2537
+ rat = _cg * deltax
2538
+ else: # do a parabolic step
2539
+ tmp1 = (x - w) * (fx - fv)
2540
+ tmp2 = (x - v) * (fx - fw)
2541
+ p = (x - v) * tmp2 - (x - w) * tmp1
2542
+ tmp2 = 2.0 * (tmp2 - tmp1)
2543
+ if (tmp2 > 0.0):
2544
+ p = -p
2545
+ tmp2 = np.abs(tmp2)
2546
+ dx_temp = deltax
2547
+ deltax = rat
2548
+ # check parabolic fit
2549
+ if ((p > tmp2 * (a - x)) and (p < tmp2 * (b - x)) and
2550
+ (np.abs(p) < np.abs(0.5 * tmp2 * dx_temp))):
2551
+ rat = p * 1.0 / tmp2 # if parabolic step is useful.
2552
+ u = x + rat
2553
+ if ((u - a) < tol2 or (b - u) < tol2):
2554
+ if xmid - x >= 0:
2555
+ rat = tol1
2556
+ else:
2557
+ rat = -tol1
2558
+ else:
2559
+ if (x >= xmid):
2560
+ deltax = a - x # if it's not do a golden section step
2561
+ else:
2562
+ deltax = b - x
2563
+ rat = _cg * deltax
2564
+
2565
+ if (np.abs(rat) < tol1): # update by at least tol1
2566
+ if rat >= 0:
2567
+ u = x + tol1
2568
+ else:
2569
+ u = x - tol1
2570
+ else:
2571
+ u = x + rat
2572
+ fu = func(*((u,) + self.args)) # calculate new output value
2573
+ funcalls += 1
2574
+
2575
+ if (fu > fx): # if it's bigger than current
2576
+ if (u < x):
2577
+ a = u
2578
+ else:
2579
+ b = u
2580
+ if (fu <= fw) or (w == x):
2581
+ v = w
2582
+ w = u
2583
+ fv = fw
2584
+ fw = fu
2585
+ elif (fu <= fv) or (v == x) or (v == w):
2586
+ v = u
2587
+ fv = fu
2588
+ else:
2589
+ if (u >= x):
2590
+ a = x
2591
+ else:
2592
+ b = x
2593
+ v = w
2594
+ w = x
2595
+ x = u
2596
+ fv = fw
2597
+ fw = fx
2598
+ fx = fu
2599
+
2600
+ if self.disp > 2:
2601
+ print(f"{funcalls:^12g} {x:^12.6g} {fx:^12.6g}")
2602
+
2603
+ iter += 1
2604
+ #################################
2605
+ #END CORE ALGORITHM
2606
+ #################################
2607
+
2608
+ self.xmin = x
2609
+ self.fval = fx
2610
+ self.iter = iter
2611
+ self.funcalls = funcalls
2612
+
2613
+ def get_result(self, full_output=False):
2614
+ if full_output:
2615
+ return self.xmin, self.fval, self.iter, self.funcalls
2616
+ else:
2617
+ return self.xmin
2618
+
2619
+
2620
+ def brent(func, args=(), brack=None, tol=1.48e-8, full_output=0, maxiter=500):
2621
+ """
2622
+ Given a function of one variable and a possible bracket, return
2623
+ a local minimizer of the function isolated to a fractional precision
2624
+ of tol.
2625
+
2626
+ Parameters
2627
+ ----------
2628
+ func : callable f(x,*args)
2629
+ Objective function.
2630
+ args : tuple, optional
2631
+ Additional arguments (if present).
2632
+ brack : tuple, optional
2633
+ Either a triple ``(xa, xb, xc)`` satisfying ``xa < xb < xc`` and
2634
+ ``func(xb) < func(xa) and func(xb) < func(xc)``, or a pair
2635
+ ``(xa, xb)`` to be used as initial points for a downhill bracket search
2636
+ (see `scipy.optimize.bracket`).
2637
+ The minimizer ``x`` will not necessarily satisfy ``xa <= x <= xb``.
2638
+ tol : float, optional
2639
+ Relative error in solution `xopt` acceptable for convergence.
2640
+ full_output : bool, optional
2641
+ If True, return all output args (xmin, fval, iter,
2642
+ funcalls).
2643
+ maxiter : int, optional
2644
+ Maximum number of iterations in solution.
2645
+
2646
+ Returns
2647
+ -------
2648
+ xmin : ndarray
2649
+ Optimum point.
2650
+ fval : float
2651
+ (Optional output) Optimum function value.
2652
+ iter : int
2653
+ (Optional output) Number of iterations.
2654
+ funcalls : int
2655
+ (Optional output) Number of objective function evaluations made.
2656
+
2657
+ See also
2658
+ --------
2659
+ minimize_scalar: Interface to minimization algorithms for scalar
2660
+ univariate functions. See the 'Brent' `method` in particular.
2661
+
2662
+ Notes
2663
+ -----
2664
+ Uses inverse parabolic interpolation when possible to speed up
2665
+ convergence of golden section method.
2666
+
2667
+ Does not ensure that the minimum lies in the range specified by
2668
+ `brack`. See `scipy.optimize.fminbound`.
2669
+
2670
+ Examples
2671
+ --------
2672
+ We illustrate the behaviour of the function when `brack` is of
2673
+ size 2 and 3 respectively. In the case where `brack` is of the
2674
+ form ``(xa, xb)``, we can see for the given values, the output does
2675
+ not necessarily lie in the range ``(xa, xb)``.
2676
+
2677
+ >>> def f(x):
2678
+ ... return (x-1)**2
2679
+
2680
+ >>> from scipy import optimize
2681
+
2682
+ >>> minimizer = optimize.brent(f, brack=(1, 2))
2683
+ >>> minimizer
2684
+ 1
2685
+ >>> res = optimize.brent(f, brack=(-1, 0.5, 2), full_output=True)
2686
+ >>> xmin, fval, iter, funcalls = res
2687
+ >>> f(xmin), fval
2688
+ (0.0, 0.0)
2689
+
2690
+ """
2691
+ options = {'xtol': tol,
2692
+ 'maxiter': maxiter}
2693
+ res = _minimize_scalar_brent(func, brack, args, **options)
2694
+ if full_output:
2695
+ return res['x'], res['fun'], res['nit'], res['nfev']
2696
+ else:
2697
+ return res['x']
2698
+
2699
+
2700
+ def _minimize_scalar_brent(func, brack=None, args=(), xtol=1.48e-8,
2701
+ maxiter=500, disp=0,
2702
+ **unknown_options):
2703
+ """
2704
+ Options
2705
+ -------
2706
+ maxiter : int
2707
+ Maximum number of iterations to perform.
2708
+ xtol : float
2709
+ Relative error in solution `xopt` acceptable for convergence.
2710
+ disp : int, optional
2711
+ If non-zero, print messages.
2712
+
2713
+ ``0`` : no message printing.
2714
+
2715
+ ``1`` : non-convergence notification messages only.
2716
+
2717
+ ``2`` : print a message on convergence too.
2718
+
2719
+ ``3`` : print iteration results.
2720
+
2721
+ Notes
2722
+ -----
2723
+ Uses inverse parabolic interpolation when possible to speed up
2724
+ convergence of golden section method.
2725
+
2726
+ """
2727
+ _check_unknown_options(unknown_options)
2728
+ tol = xtol
2729
+ if tol < 0:
2730
+ raise ValueError(f'tolerance should be >= 0, got {tol!r}')
2731
+
2732
+ brent = Brent(func=func, args=args, tol=tol,
2733
+ full_output=True, maxiter=maxiter, disp=disp)
2734
+ brent.set_bracket(brack)
2735
+ brent.optimize()
2736
+ x, fval, nit, nfev = brent.get_result(full_output=True)
2737
+
2738
+ success = nit < maxiter and not (np.isnan(x) or np.isnan(fval))
2739
+
2740
+ if success:
2741
+ message = ("\nOptimization terminated successfully;\n"
2742
+ "The returned value satisfies the termination criteria\n"
2743
+ f"(using xtol = {xtol} )")
2744
+ else:
2745
+ if nit >= maxiter:
2746
+ message = "\nMaximum number of iterations exceeded"
2747
+ if np.isnan(x) or np.isnan(fval):
2748
+ message = f"{_status_message['nan']}"
2749
+
2750
+ if disp:
2751
+ _print_success_message_or_warn(not success, message)
2752
+
2753
+ return OptimizeResult(fun=fval, x=x, nit=nit, nfev=nfev,
2754
+ success=success, message=message)
2755
+
2756
+
2757
+ def golden(func, args=(), brack=None, tol=_epsilon,
2758
+ full_output=0, maxiter=5000):
2759
+ """
2760
+ Return the minimizer of a function of one variable using the golden section
2761
+ method.
2762
+
2763
+ Given a function of one variable and a possible bracketing interval,
2764
+ return a minimizer of the function isolated to a fractional precision of
2765
+ tol.
2766
+
2767
+ Parameters
2768
+ ----------
2769
+ func : callable func(x,*args)
2770
+ Objective function to minimize.
2771
+ args : tuple, optional
2772
+ Additional arguments (if present), passed to func.
2773
+ brack : tuple, optional
2774
+ Either a triple ``(xa, xb, xc)`` where ``xa < xb < xc`` and
2775
+ ``func(xb) < func(xa) and func(xb) < func(xc)``, or a pair (xa, xb)
2776
+ to be used as initial points for a downhill bracket search (see
2777
+ `scipy.optimize.bracket`).
2778
+ The minimizer ``x`` will not necessarily satisfy ``xa <= x <= xb``.
2779
+ tol : float, optional
2780
+ x tolerance stop criterion
2781
+ full_output : bool, optional
2782
+ If True, return optional outputs.
2783
+ maxiter : int
2784
+ Maximum number of iterations to perform.
2785
+
2786
+ Returns
2787
+ -------
2788
+ xmin : ndarray
2789
+ Optimum point.
2790
+ fval : float
2791
+ (Optional output) Optimum function value.
2792
+ funcalls : int
2793
+ (Optional output) Number of objective function evaluations made.
2794
+
2795
+ See also
2796
+ --------
2797
+ minimize_scalar: Interface to minimization algorithms for scalar
2798
+ univariate functions. See the 'Golden' `method` in particular.
2799
+
2800
+ Notes
2801
+ -----
2802
+ Uses analog of bisection method to decrease the bracketed
2803
+ interval.
2804
+
2805
+ Examples
2806
+ --------
2807
+ We illustrate the behaviour of the function when `brack` is of
2808
+ size 2 and 3, respectively. In the case where `brack` is of the
2809
+ form (xa,xb), we can see for the given values, the output need
2810
+ not necessarily lie in the range ``(xa, xb)``.
2811
+
2812
+ >>> def f(x):
2813
+ ... return (x-1)**2
2814
+
2815
+ >>> from scipy import optimize
2816
+
2817
+ >>> minimizer = optimize.golden(f, brack=(1, 2))
2818
+ >>> minimizer
2819
+ 1
2820
+ >>> res = optimize.golden(f, brack=(-1, 0.5, 2), full_output=True)
2821
+ >>> xmin, fval, funcalls = res
2822
+ >>> f(xmin), fval
2823
+ (9.925165290385052e-18, 9.925165290385052e-18)
2824
+
2825
+ """
2826
+ options = {'xtol': tol, 'maxiter': maxiter}
2827
+ res = _minimize_scalar_golden(func, brack, args, **options)
2828
+ if full_output:
2829
+ return res['x'], res['fun'], res['nfev']
2830
+ else:
2831
+ return res['x']
2832
+
2833
+
2834
+ def _minimize_scalar_golden(func, brack=None, args=(),
2835
+ xtol=_epsilon, maxiter=5000, disp=0,
2836
+ **unknown_options):
2837
+ """
2838
+ Options
2839
+ -------
2840
+ xtol : float
2841
+ Relative error in solution `xopt` acceptable for convergence.
2842
+ maxiter : int
2843
+ Maximum number of iterations to perform.
2844
+ disp: int, optional
2845
+ If non-zero, print messages.
2846
+
2847
+ ``0`` : no message printing.
2848
+
2849
+ ``1`` : non-convergence notification messages only.
2850
+
2851
+ ``2`` : print a message on convergence too.
2852
+
2853
+ ``3`` : print iteration results.
2854
+ """
2855
+ _check_unknown_options(unknown_options)
2856
+ tol = xtol
2857
+ if brack is None:
2858
+ xa, xb, xc, fa, fb, fc, funcalls = bracket(func, args=args)
2859
+ elif len(brack) == 2:
2860
+ xa, xb, xc, fa, fb, fc, funcalls = bracket(func, xa=brack[0],
2861
+ xb=brack[1], args=args)
2862
+ elif len(brack) == 3:
2863
+ xa, xb, xc = brack
2864
+ if (xa > xc): # swap so xa < xc can be assumed
2865
+ xc, xa = xa, xc
2866
+ if not ((xa < xb) and (xb < xc)):
2867
+ raise ValueError(
2868
+ "Bracketing values (xa, xb, xc) do not"
2869
+ " fulfill this requirement: (xa < xb) and (xb < xc)"
2870
+ )
2871
+ fa = func(*((xa,) + args))
2872
+ fb = func(*((xb,) + args))
2873
+ fc = func(*((xc,) + args))
2874
+ if not ((fb < fa) and (fb < fc)):
2875
+ raise ValueError(
2876
+ "Bracketing values (xa, xb, xc) do not fulfill"
2877
+ " this requirement: (f(xb) < f(xa)) and (f(xb) < f(xc))"
2878
+ )
2879
+ funcalls = 3
2880
+ else:
2881
+ raise ValueError("Bracketing interval must be length 2 or 3 sequence.")
2882
+
2883
+ _gR = 0.61803399 # golden ratio conjugate: 2.0/(1.0+sqrt(5.0))
2884
+ _gC = 1.0 - _gR
2885
+ x3 = xc
2886
+ x0 = xa
2887
+ if (np.abs(xc - xb) > np.abs(xb - xa)):
2888
+ x1 = xb
2889
+ x2 = xb + _gC * (xc - xb)
2890
+ else:
2891
+ x2 = xb
2892
+ x1 = xb - _gC * (xb - xa)
2893
+ f1 = func(*((x1,) + args))
2894
+ f2 = func(*((x2,) + args))
2895
+ funcalls += 2
2896
+ nit = 0
2897
+
2898
+ if disp > 2:
2899
+ print(" ")
2900
+ print(f"{'Func-count':^12} {'x':^12} {'f(x)': ^12}")
2901
+
2902
+ for i in range(maxiter):
2903
+ if np.abs(x3 - x0) <= tol * (np.abs(x1) + np.abs(x2)):
2904
+ break
2905
+ if (f2 < f1):
2906
+ x0 = x1
2907
+ x1 = x2
2908
+ x2 = _gR * x1 + _gC * x3
2909
+ f1 = f2
2910
+ f2 = func(*((x2,) + args))
2911
+ else:
2912
+ x3 = x2
2913
+ x2 = x1
2914
+ x1 = _gR * x2 + _gC * x0
2915
+ f2 = f1
2916
+ f1 = func(*((x1,) + args))
2917
+ funcalls += 1
2918
+ if disp > 2:
2919
+ if (f1 < f2):
2920
+ xmin, fval = x1, f1
2921
+ else:
2922
+ xmin, fval = x2, f2
2923
+ print(f"{funcalls:^12g} {xmin:^12.6g} {fval:^12.6g}")
2924
+
2925
+ nit += 1
2926
+ # end of iteration loop
2927
+
2928
+ if (f1 < f2):
2929
+ xmin = x1
2930
+ fval = f1
2931
+ else:
2932
+ xmin = x2
2933
+ fval = f2
2934
+
2935
+ success = nit < maxiter and not (np.isnan(fval) or np.isnan(xmin))
2936
+
2937
+ if success:
2938
+ message = ("\nOptimization terminated successfully;\n"
2939
+ "The returned value satisfies the termination criteria\n"
2940
+ f"(using xtol = {xtol} )")
2941
+ else:
2942
+ if nit >= maxiter:
2943
+ message = "\nMaximum number of iterations exceeded"
2944
+ if np.isnan(xmin) or np.isnan(fval):
2945
+ message = f"{_status_message['nan']}"
2946
+
2947
+ if disp:
2948
+ _print_success_message_or_warn(not success, message)
2949
+
2950
+ return OptimizeResult(fun=fval, nfev=funcalls, x=xmin, nit=nit,
2951
+ success=success, message=message)
2952
+
2953
+
2954
+ def bracket(func, xa=0.0, xb=1.0, args=(), grow_limit=110.0, maxiter=1000):
2955
+ """
2956
+ Bracket the minimum of a function.
2957
+
2958
+ Given a function and distinct initial points, search in the
2959
+ downhill direction (as defined by the initial points) and return
2960
+ three points that bracket the minimum of the function.
2961
+
2962
+ Parameters
2963
+ ----------
2964
+ func : callable f(x,*args)
2965
+ Objective function to minimize.
2966
+ xa, xb : float, optional
2967
+ Initial points. Defaults `xa` to 0.0, and `xb` to 1.0.
2968
+ A local minimum need not be contained within this interval.
2969
+ args : tuple, optional
2970
+ Additional arguments (if present), passed to `func`.
2971
+ grow_limit : float, optional
2972
+ Maximum grow limit. Defaults to 110.0
2973
+ maxiter : int, optional
2974
+ Maximum number of iterations to perform. Defaults to 1000.
2975
+
2976
+ Returns
2977
+ -------
2978
+ xa, xb, xc : float
2979
+ Final points of the bracket.
2980
+ fa, fb, fc : float
2981
+ Objective function values at the bracket points.
2982
+ funcalls : int
2983
+ Number of function evaluations made.
2984
+
2985
+ Raises
2986
+ ------
2987
+ BracketError
2988
+ If no valid bracket is found before the algorithm terminates.
2989
+ See notes for conditions of a valid bracket.
2990
+
2991
+ Notes
2992
+ -----
2993
+ The algorithm attempts to find three strictly ordered points (i.e.
2994
+ :math:`x_a < x_b < x_c` or :math:`x_c < x_b < x_a`) satisfying
2995
+ :math:`f(x_b) ≤ f(x_a)` and :math:`f(x_b) ≤ f(x_c)`, where one of the
2996
+ inequalities must be satisfied strictly and all :math:`x_i` must be
2997
+ finite.
2998
+
2999
+ Examples
3000
+ --------
3001
+ This function can find a downward convex region of a function:
3002
+
3003
+ >>> import numpy as np
3004
+ >>> import matplotlib.pyplot as plt
3005
+ >>> from scipy.optimize import bracket
3006
+ >>> def f(x):
3007
+ ... return 10*x**2 + 3*x + 5
3008
+ >>> x = np.linspace(-2, 2)
3009
+ >>> y = f(x)
3010
+ >>> init_xa, init_xb = 0.1, 1
3011
+ >>> xa, xb, xc, fa, fb, fc, funcalls = bracket(f, xa=init_xa, xb=init_xb)
3012
+ >>> plt.axvline(x=init_xa, color="k", linestyle="--")
3013
+ >>> plt.axvline(x=init_xb, color="k", linestyle="--")
3014
+ >>> plt.plot(x, y, "-k")
3015
+ >>> plt.plot(xa, fa, "bx")
3016
+ >>> plt.plot(xb, fb, "rx")
3017
+ >>> plt.plot(xc, fc, "bx")
3018
+ >>> plt.show()
3019
+
3020
+ Note that both initial points were to the right of the minimum, and the
3021
+ third point was found in the "downhill" direction: the direction
3022
+ in which the function appeared to be decreasing (to the left).
3023
+ The final points are strictly ordered, and the function value
3024
+ at the middle point is less than the function values at the endpoints;
3025
+ it follows that a minimum must lie within the bracket.
3026
+
3027
+ """
3028
+ _gold = 1.618034 # golden ratio: (1.0+sqrt(5.0))/2.0
3029
+ _verysmall_num = 1e-21
3030
+ # convert to numpy floats if not already
3031
+ xa, xb = np.asarray([xa, xb])
3032
+ fa = func(*(xa,) + args)
3033
+ fb = func(*(xb,) + args)
3034
+ if (fa < fb): # Switch so fa > fb
3035
+ xa, xb = xb, xa
3036
+ fa, fb = fb, fa
3037
+ xc = xb + _gold * (xb - xa)
3038
+ fc = func(*((xc,) + args))
3039
+ funcalls = 3
3040
+ iter = 0
3041
+ while (fc < fb):
3042
+ tmp1 = (xb - xa) * (fb - fc)
3043
+ tmp2 = (xb - xc) * (fb - fa)
3044
+ val = tmp2 - tmp1
3045
+ if np.abs(val) < _verysmall_num:
3046
+ denom = 2.0 * _verysmall_num
3047
+ else:
3048
+ denom = 2.0 * val
3049
+ w = xb - ((xb - xc) * tmp2 - (xb - xa) * tmp1) / denom
3050
+ wlim = xb + grow_limit * (xc - xb)
3051
+ msg = ("No valid bracket was found before the iteration limit was "
3052
+ "reached. Consider trying different initial points or "
3053
+ "increasing `maxiter`.")
3054
+ if iter > maxiter:
3055
+ raise RuntimeError(msg)
3056
+ iter += 1
3057
+ if (w - xc) * (xb - w) > 0.0:
3058
+ fw = func(*((w,) + args))
3059
+ funcalls += 1
3060
+ if (fw < fc):
3061
+ xa = xb
3062
+ xb = w
3063
+ fa = fb
3064
+ fb = fw
3065
+ break
3066
+ elif (fw > fb):
3067
+ xc = w
3068
+ fc = fw
3069
+ break
3070
+ w = xc + _gold * (xc - xb)
3071
+ fw = func(*((w,) + args))
3072
+ funcalls += 1
3073
+ elif (w - wlim)*(wlim - xc) >= 0.0:
3074
+ w = wlim
3075
+ fw = func(*((w,) + args))
3076
+ funcalls += 1
3077
+ elif (w - wlim)*(xc - w) > 0.0:
3078
+ fw = func(*((w,) + args))
3079
+ funcalls += 1
3080
+ if (fw < fc):
3081
+ xb = xc
3082
+ xc = w
3083
+ w = xc + _gold * (xc - xb)
3084
+ fb = fc
3085
+ fc = fw
3086
+ fw = func(*((w,) + args))
3087
+ funcalls += 1
3088
+ else:
3089
+ w = xc + _gold * (xc - xb)
3090
+ fw = func(*((w,) + args))
3091
+ funcalls += 1
3092
+ xa = xb
3093
+ xb = xc
3094
+ xc = w
3095
+ fa = fb
3096
+ fb = fc
3097
+ fc = fw
3098
+
3099
+ # three conditions for a valid bracket
3100
+ cond1 = (fb < fc and fb <= fa) or (fb < fa and fb <= fc)
3101
+ cond2 = (xa < xb < xc or xc < xb < xa)
3102
+ cond3 = np.isfinite(xa) and np.isfinite(xb) and np.isfinite(xc)
3103
+ msg = ("The algorithm terminated without finding a valid bracket. "
3104
+ "Consider trying different initial points.")
3105
+ if not (cond1 and cond2 and cond3):
3106
+ e = BracketError(msg)
3107
+ e.data = (xa, xb, xc, fa, fb, fc, funcalls)
3108
+ raise e
3109
+
3110
+ return xa, xb, xc, fa, fb, fc, funcalls
3111
+
3112
+
3113
+ class BracketError(RuntimeError):
3114
+ pass
3115
+
3116
+
3117
+ def _recover_from_bracket_error(solver, fun, bracket, args, **options):
3118
+ # `bracket` was originally written without checking whether the resulting
3119
+ # bracket is valid. `brent` and `golden` built on top of it without
3120
+ # checking the returned bracket for validity, and their output can be
3121
+ # incorrect without warning/error if the original bracket is invalid.
3122
+ # gh-14858 noticed the problem, and the following is the desired
3123
+ # behavior:
3124
+ # - `scipy.optimize.bracket`, `scipy.optimize.brent`, and
3125
+ # `scipy.optimize.golden` should raise an error if the bracket is
3126
+ # invalid, as opposed to silently returning garbage
3127
+ # - `scipy.optimize.minimize_scalar` should return with `success=False`
3128
+ # and other information
3129
+ # The changes that would be required to achieve this the traditional
3130
+ # way (`return`ing all the required information from bracket all the way
3131
+ # up to `minimizer_scalar`) are extensive and invasive. (See a6aa40d.)
3132
+ # We can achieve the same thing by raising the error in `bracket`, but
3133
+ # storing the information needed by `minimize_scalar` in the error object,
3134
+ # and intercepting it here.
3135
+ try:
3136
+ res = solver(fun, bracket, args, **options)
3137
+ except BracketError as e:
3138
+ msg = str(e)
3139
+ xa, xb, xc, fa, fb, fc, funcalls = e.data
3140
+ xs, fs = [xa, xb, xc], [fa, fb, fc]
3141
+ if np.any(np.isnan([xs, fs])):
3142
+ x, fun = np.nan, np.nan
3143
+ else:
3144
+ imin = np.argmin(fs)
3145
+ x, fun = xs[imin], fs[imin]
3146
+ return OptimizeResult(fun=fun, nfev=funcalls, x=x,
3147
+ nit=0, success=False, message=msg)
3148
+ return res
3149
+
3150
+
3151
+ def _line_for_search(x0, alpha, lower_bound, upper_bound):
3152
+ """
3153
+ Given a parameter vector ``x0`` with length ``n`` and a direction
3154
+ vector ``alpha`` with length ``n``, and lower and upper bounds on
3155
+ each of the ``n`` parameters, what are the bounds on a scalar
3156
+ ``l`` such that ``lower_bound <= x0 + alpha * l <= upper_bound``.
3157
+
3158
+
3159
+ Parameters
3160
+ ----------
3161
+ x0 : np.array.
3162
+ The vector representing the current location.
3163
+ Note ``np.shape(x0) == (n,)``.
3164
+ alpha : np.array.
3165
+ The vector representing the direction.
3166
+ Note ``np.shape(alpha) == (n,)``.
3167
+ lower_bound : np.array.
3168
+ The lower bounds for each parameter in ``x0``. If the ``i``th
3169
+ parameter in ``x0`` is unbounded below, then ``lower_bound[i]``
3170
+ should be ``-np.inf``.
3171
+ Note ``np.shape(lower_bound) == (n,)``.
3172
+ upper_bound : np.array.
3173
+ The upper bounds for each parameter in ``x0``. If the ``i``th
3174
+ parameter in ``x0`` is unbounded above, then ``upper_bound[i]``
3175
+ should be ``np.inf``.
3176
+ Note ``np.shape(upper_bound) == (n,)``.
3177
+
3178
+ Returns
3179
+ -------
3180
+ res : tuple ``(lmin, lmax)``
3181
+ The bounds for ``l`` such that
3182
+ ``lower_bound[i] <= x0[i] + alpha[i] * l <= upper_bound[i]``
3183
+ for all ``i``.
3184
+
3185
+ """
3186
+ # get nonzero indices of alpha so we don't get any zero division errors.
3187
+ # alpha will not be all zero, since it is called from _linesearch_powell
3188
+ # where we have a check for this.
3189
+ nonzero, = alpha.nonzero()
3190
+ lower_bound, upper_bound = lower_bound[nonzero], upper_bound[nonzero]
3191
+ x0, alpha = x0[nonzero], alpha[nonzero]
3192
+ low = (lower_bound - x0) / alpha
3193
+ high = (upper_bound - x0) / alpha
3194
+
3195
+ # positive and negative indices
3196
+ pos = alpha > 0
3197
+
3198
+ lmin_pos = np.where(pos, low, 0)
3199
+ lmin_neg = np.where(pos, 0, high)
3200
+ lmax_pos = np.where(pos, high, 0)
3201
+ lmax_neg = np.where(pos, 0, low)
3202
+
3203
+ lmin = np.max(lmin_pos + lmin_neg)
3204
+ lmax = np.min(lmax_pos + lmax_neg)
3205
+
3206
+ # if x0 is outside the bounds, then it is possible that there is
3207
+ # no way to get back in the bounds for the parameters being updated
3208
+ # with the current direction alpha.
3209
+ # when this happens, lmax < lmin.
3210
+ # If this is the case, then we can just return (0, 0)
3211
+ return (lmin, lmax) if lmax >= lmin else (0, 0)
3212
+
3213
+
3214
+ def _linesearch_powell(func, p, xi, tol=1e-3,
3215
+ lower_bound=None, upper_bound=None, fval=None):
3216
+ """Line-search algorithm using fminbound.
3217
+
3218
+ Find the minimum of the function ``func(x0 + alpha*direc)``.
3219
+
3220
+ lower_bound : np.array.
3221
+ The lower bounds for each parameter in ``x0``. If the ``i``th
3222
+ parameter in ``x0`` is unbounded below, then ``lower_bound[i]``
3223
+ should be ``-np.inf``.
3224
+ Note ``np.shape(lower_bound) == (n,)``.
3225
+ upper_bound : np.array.
3226
+ The upper bounds for each parameter in ``x0``. If the ``i``th
3227
+ parameter in ``x0`` is unbounded above, then ``upper_bound[i]``
3228
+ should be ``np.inf``.
3229
+ Note ``np.shape(upper_bound) == (n,)``.
3230
+ fval : number.
3231
+ ``fval`` is equal to ``func(p)``, the idea is just to avoid
3232
+ recomputing it so we can limit the ``fevals``.
3233
+
3234
+ """
3235
+ def myfunc(alpha):
3236
+ return func(p + alpha*xi)
3237
+
3238
+ # if xi is zero, then don't optimize
3239
+ if not np.any(xi):
3240
+ return ((fval, p, xi) if fval is not None else (func(p), p, xi))
3241
+ elif lower_bound is None and upper_bound is None:
3242
+ # non-bounded minimization
3243
+ res = _recover_from_bracket_error(_minimize_scalar_brent,
3244
+ myfunc, None, tuple(), xtol=tol)
3245
+ alpha_min, fret = res.x, res.fun
3246
+ xi = alpha_min * xi
3247
+ return fret, p + xi, xi
3248
+ else:
3249
+ bound = _line_for_search(p, xi, lower_bound, upper_bound)
3250
+ if np.isneginf(bound[0]) and np.isposinf(bound[1]):
3251
+ # equivalent to unbounded
3252
+ return _linesearch_powell(func, p, xi, fval=fval, tol=tol)
3253
+ elif not np.isneginf(bound[0]) and not np.isposinf(bound[1]):
3254
+ # we can use a bounded scalar minimization
3255
+ res = _minimize_scalar_bounded(myfunc, bound, xatol=tol / 100)
3256
+ xi = res.x * xi
3257
+ return res.fun, p + xi, xi
3258
+ else:
3259
+ # only bounded on one side. use the tangent function to convert
3260
+ # the infinity bound to a finite bound. The new bounded region
3261
+ # is a subregion of the region bounded by -np.pi/2 and np.pi/2.
3262
+ bound = np.arctan(bound[0]), np.arctan(bound[1])
3263
+ res = _minimize_scalar_bounded(
3264
+ lambda x: myfunc(np.tan(x)),
3265
+ bound,
3266
+ xatol=tol / 100)
3267
+ xi = np.tan(res.x) * xi
3268
+ return res.fun, p + xi, xi
3269
+
3270
+
3271
+ def fmin_powell(func, x0, args=(), xtol=1e-4, ftol=1e-4, maxiter=None,
3272
+ maxfun=None, full_output=0, disp=1, retall=0, callback=None,
3273
+ direc=None):
3274
+ """
3275
+ Minimize a function using modified Powell's method.
3276
+
3277
+ This method only uses function values, not derivatives.
3278
+
3279
+ Parameters
3280
+ ----------
3281
+ func : callable f(x,*args)
3282
+ Objective function to be minimized.
3283
+ x0 : ndarray
3284
+ Initial guess.
3285
+ args : tuple, optional
3286
+ Extra arguments passed to func.
3287
+ xtol : float, optional
3288
+ Line-search error tolerance.
3289
+ ftol : float, optional
3290
+ Relative error in ``func(xopt)`` acceptable for convergence.
3291
+ maxiter : int, optional
3292
+ Maximum number of iterations to perform.
3293
+ maxfun : int, optional
3294
+ Maximum number of function evaluations to make.
3295
+ full_output : bool, optional
3296
+ If True, ``fopt``, ``xi``, ``direc``, ``iter``, ``funcalls``, and
3297
+ ``warnflag`` are returned.
3298
+ disp : bool, optional
3299
+ If True, print convergence messages.
3300
+ retall : bool, optional
3301
+ If True, return a list of the solution at each iteration.
3302
+ callback : callable, optional
3303
+ An optional user-supplied function, called after each
3304
+ iteration. Called as ``callback(xk)``, where ``xk`` is the
3305
+ current parameter vector.
3306
+ direc : ndarray, optional
3307
+ Initial fitting step and parameter order set as an (N, N) array, where N
3308
+ is the number of fitting parameters in `x0`. Defaults to step size 1.0
3309
+ fitting all parameters simultaneously (``np.eye((N, N))``). To
3310
+ prevent initial consideration of values in a step or to change initial
3311
+ step size, set to 0 or desired step size in the Jth position in the Mth
3312
+ block, where J is the position in `x0` and M is the desired evaluation
3313
+ step, with steps being evaluated in index order. Step size and ordering
3314
+ will change freely as minimization proceeds.
3315
+
3316
+ Returns
3317
+ -------
3318
+ xopt : ndarray
3319
+ Parameter which minimizes `func`.
3320
+ fopt : number
3321
+ Value of function at minimum: ``fopt = func(xopt)``.
3322
+ direc : ndarray
3323
+ Current direction set.
3324
+ iter : int
3325
+ Number of iterations.
3326
+ funcalls : int
3327
+ Number of function calls made.
3328
+ warnflag : int
3329
+ Integer warning flag:
3330
+ 1 : Maximum number of function evaluations.
3331
+ 2 : Maximum number of iterations.
3332
+ 3 : NaN result encountered.
3333
+ 4 : The result is out of the provided bounds.
3334
+ allvecs : list
3335
+ List of solutions at each iteration.
3336
+
3337
+ See also
3338
+ --------
3339
+ minimize: Interface to unconstrained minimization algorithms for
3340
+ multivariate functions. See the 'Powell' method in particular.
3341
+
3342
+ Notes
3343
+ -----
3344
+ Uses a modification of Powell's method to find the minimum of
3345
+ a function of N variables. Powell's method is a conjugate
3346
+ direction method.
3347
+
3348
+ The algorithm has two loops. The outer loop merely iterates over the inner
3349
+ loop. The inner loop minimizes over each current direction in the direction
3350
+ set. At the end of the inner loop, if certain conditions are met, the
3351
+ direction that gave the largest decrease is dropped and replaced with the
3352
+ difference between the current estimated x and the estimated x from the
3353
+ beginning of the inner-loop.
3354
+
3355
+ The technical conditions for replacing the direction of greatest
3356
+ increase amount to checking that
3357
+
3358
+ 1. No further gain can be made along the direction of greatest increase
3359
+ from that iteration.
3360
+ 2. The direction of greatest increase accounted for a large sufficient
3361
+ fraction of the decrease in the function value from that iteration of
3362
+ the inner loop.
3363
+
3364
+ References
3365
+ ----------
3366
+ Powell M.J.D. (1964) An efficient method for finding the minimum of a
3367
+ function of several variables without calculating derivatives,
3368
+ Computer Journal, 7 (2):155-162.
3369
+
3370
+ Press W., Teukolsky S.A., Vetterling W.T., and Flannery B.P.:
3371
+ Numerical Recipes (any edition), Cambridge University Press
3372
+
3373
+ Examples
3374
+ --------
3375
+ >>> def f(x):
3376
+ ... return x**2
3377
+
3378
+ >>> from scipy import optimize
3379
+
3380
+ >>> minimum = optimize.fmin_powell(f, -1)
3381
+ Optimization terminated successfully.
3382
+ Current function value: 0.000000
3383
+ Iterations: 2
3384
+ Function evaluations: 16
3385
+ >>> minimum
3386
+ array(0.0)
3387
+
3388
+ """
3389
+ opts = {'xtol': xtol,
3390
+ 'ftol': ftol,
3391
+ 'maxiter': maxiter,
3392
+ 'maxfev': maxfun,
3393
+ 'disp': disp,
3394
+ 'direc': direc,
3395
+ 'return_all': retall}
3396
+
3397
+ callback = _wrap_callback(callback)
3398
+ res = _minimize_powell(func, x0, args, callback=callback, **opts)
3399
+
3400
+ if full_output:
3401
+ retlist = (res['x'], res['fun'], res['direc'], res['nit'],
3402
+ res['nfev'], res['status'])
3403
+ if retall:
3404
+ retlist += (res['allvecs'], )
3405
+ return retlist
3406
+ else:
3407
+ if retall:
3408
+ return res['x'], res['allvecs']
3409
+ else:
3410
+ return res['x']
3411
+
3412
+
3413
+ def _minimize_powell(func, x0, args=(), callback=None, bounds=None,
3414
+ xtol=1e-4, ftol=1e-4, maxiter=None, maxfev=None,
3415
+ disp=False, direc=None, return_all=False,
3416
+ **unknown_options):
3417
+ """
3418
+ Minimization of scalar function of one or more variables using the
3419
+ modified Powell algorithm.
3420
+
3421
+ Parameters
3422
+ ----------
3423
+ fun : callable
3424
+ The objective function to be minimized::
3425
+
3426
+ fun(x, *args) -> float
3427
+
3428
+ where ``x`` is a 1-D array with shape (n,) and ``args``
3429
+ is a tuple of the fixed parameters needed to completely
3430
+ specify the function.
3431
+ x0 : ndarray, shape (n,)
3432
+ Initial guess. Array of real elements of size (n,),
3433
+ where ``n`` is the number of independent variables.
3434
+ args : tuple, optional
3435
+ Extra arguments passed to the objective function and its
3436
+ derivatives (`fun`, `jac` and `hess` functions).
3437
+ method : str or callable, optional
3438
+ The present documentation is specific to ``method='powell'``, but other
3439
+ options are available. See documentation for `scipy.optimize.minimize`.
3440
+ bounds : sequence or `Bounds`, optional
3441
+ Bounds on decision variables. There are two ways to specify the bounds:
3442
+
3443
+ 1. Instance of `Bounds` class.
3444
+ 2. Sequence of ``(min, max)`` pairs for each element in `x`. None
3445
+ is used to specify no bound.
3446
+
3447
+ If bounds are not provided, then an unbounded line search will be used.
3448
+ If bounds are provided and the initial guess is within the bounds, then
3449
+ every function evaluation throughout the minimization procedure will be
3450
+ within the bounds. If bounds are provided, the initial guess is outside
3451
+ the bounds, and `direc` is full rank (or left to default), then some
3452
+ function evaluations during the first iteration may be outside the
3453
+ bounds, but every function evaluation after the first iteration will be
3454
+ within the bounds. If `direc` is not full rank, then some parameters
3455
+ may not be optimized and the solution is not guaranteed to be within
3456
+ the bounds.
3457
+
3458
+ options : dict, optional
3459
+ A dictionary of solver options. All methods accept the following
3460
+ generic options:
3461
+
3462
+ maxiter : int
3463
+ Maximum number of iterations to perform. Depending on the
3464
+ method each iteration may use several function evaluations.
3465
+ disp : bool
3466
+ Set to True to print convergence messages.
3467
+
3468
+ See method-specific options for ``method='powell'`` below.
3469
+ callback : callable, optional
3470
+ Called after each iteration. The signature is::
3471
+
3472
+ callback(xk)
3473
+
3474
+ where ``xk`` is the current parameter vector.
3475
+
3476
+ Returns
3477
+ -------
3478
+ res : OptimizeResult
3479
+ The optimization result represented as a ``OptimizeResult`` object.
3480
+ Important attributes are: ``x`` the solution array, ``success`` a
3481
+ Boolean flag indicating if the optimizer exited successfully and
3482
+ ``message`` which describes the cause of the termination. See
3483
+ `OptimizeResult` for a description of other attributes.
3484
+
3485
+ Options
3486
+ -------
3487
+ disp : bool
3488
+ Set to True to print convergence messages.
3489
+ xtol : float
3490
+ Relative error in solution `xopt` acceptable for convergence.
3491
+ ftol : float
3492
+ Relative error in ``fun(xopt)`` acceptable for convergence.
3493
+ maxiter, maxfev : int
3494
+ Maximum allowed number of iterations and function evaluations.
3495
+ Will default to ``N*1000``, where ``N`` is the number of
3496
+ variables, if neither `maxiter` or `maxfev` is set. If both
3497
+ `maxiter` and `maxfev` are set, minimization will stop at the
3498
+ first reached.
3499
+ direc : ndarray
3500
+ Initial set of direction vectors for the Powell method.
3501
+ return_all : bool, optional
3502
+ Set to True to return a list of the best solution at each of the
3503
+ iterations.
3504
+ """
3505
+ _check_unknown_options(unknown_options)
3506
+ maxfun = maxfev
3507
+ retall = return_all
3508
+
3509
+ x = asarray(x0).flatten()
3510
+ if retall:
3511
+ allvecs = [x]
3512
+ N = len(x)
3513
+ # If neither are set, then set both to default
3514
+ if maxiter is None and maxfun is None:
3515
+ maxiter = N * 1000
3516
+ maxfun = N * 1000
3517
+ elif maxiter is None:
3518
+ # Convert remaining Nones, to np.inf, unless the other is np.inf, in
3519
+ # which case use the default to avoid unbounded iteration
3520
+ if maxfun == np.inf:
3521
+ maxiter = N * 1000
3522
+ else:
3523
+ maxiter = np.inf
3524
+ elif maxfun is None:
3525
+ if maxiter == np.inf:
3526
+ maxfun = N * 1000
3527
+ else:
3528
+ maxfun = np.inf
3529
+
3530
+ # we need to use a mutable object here that we can update in the
3531
+ # wrapper function
3532
+ fcalls, func = _wrap_scalar_function_maxfun_validation(func, args, maxfun)
3533
+
3534
+ if direc is None:
3535
+ direc = eye(N, dtype=float)
3536
+ else:
3537
+ direc = asarray(direc, dtype=float)
3538
+ if np.linalg.matrix_rank(direc) != direc.shape[0]:
3539
+ warnings.warn("direc input is not full rank, some parameters may "
3540
+ "not be optimized",
3541
+ OptimizeWarning, stacklevel=3)
3542
+
3543
+ if bounds is None:
3544
+ # don't make these arrays of all +/- inf. because
3545
+ # _linesearch_powell will do an unnecessary check of all the elements.
3546
+ # just keep them None, _linesearch_powell will not have to check
3547
+ # all the elements.
3548
+ lower_bound, upper_bound = None, None
3549
+ else:
3550
+ # bounds is standardized in _minimize.py.
3551
+ lower_bound, upper_bound = bounds.lb, bounds.ub
3552
+ if np.any(lower_bound > x0) or np.any(x0 > upper_bound):
3553
+ warnings.warn("Initial guess is not within the specified bounds",
3554
+ OptimizeWarning, stacklevel=3)
3555
+
3556
+ fval = func(x)
3557
+ x1 = x.copy()
3558
+ iter = 0
3559
+ while True:
3560
+ try:
3561
+ fx = fval
3562
+ bigind = 0
3563
+ delta = 0.0
3564
+ for i in range(N):
3565
+ direc1 = direc[i]
3566
+ fx2 = fval
3567
+ fval, x, direc1 = _linesearch_powell(func, x, direc1,
3568
+ tol=xtol * 100,
3569
+ lower_bound=lower_bound,
3570
+ upper_bound=upper_bound,
3571
+ fval=fval)
3572
+ if (fx2 - fval) > delta:
3573
+ delta = fx2 - fval
3574
+ bigind = i
3575
+ iter += 1
3576
+ if retall:
3577
+ allvecs.append(x)
3578
+ intermediate_result = OptimizeResult(x=x, fun=fval)
3579
+ if _call_callback_maybe_halt(callback, intermediate_result):
3580
+ break
3581
+ bnd = ftol * (np.abs(fx) + np.abs(fval)) + 1e-20
3582
+ if 2.0 * (fx - fval) <= bnd:
3583
+ break
3584
+ if fcalls[0] >= maxfun:
3585
+ break
3586
+ if iter >= maxiter:
3587
+ break
3588
+ if np.isnan(fx) and np.isnan(fval):
3589
+ # Ended up in a nan-region: bail out
3590
+ break
3591
+
3592
+ # Construct the extrapolated point
3593
+ direc1 = x - x1
3594
+ x1 = x.copy()
3595
+ # make sure that we don't go outside the bounds when extrapolating
3596
+ if lower_bound is None and upper_bound is None:
3597
+ lmax = 1
3598
+ else:
3599
+ _, lmax = _line_for_search(x, direc1, lower_bound, upper_bound)
3600
+ x2 = x + min(lmax, 1) * direc1
3601
+ fx2 = func(x2)
3602
+
3603
+ if (fx > fx2):
3604
+ t = 2.0*(fx + fx2 - 2.0*fval)
3605
+ temp = (fx - fval - delta)
3606
+ t *= temp*temp
3607
+ temp = fx - fx2
3608
+ t -= delta*temp*temp
3609
+ if t < 0.0:
3610
+ fval, x, direc1 = _linesearch_powell(
3611
+ func, x, direc1,
3612
+ tol=xtol * 100,
3613
+ lower_bound=lower_bound,
3614
+ upper_bound=upper_bound,
3615
+ fval=fval
3616
+ )
3617
+ if np.any(direc1):
3618
+ direc[bigind] = direc[-1]
3619
+ direc[-1] = direc1
3620
+ except _MaxFuncCallError:
3621
+ break
3622
+
3623
+ warnflag = 0
3624
+ msg = _status_message['success']
3625
+ # out of bounds is more urgent than exceeding function evals or iters,
3626
+ # but I don't want to cause inconsistencies by changing the
3627
+ # established warning flags for maxfev and maxiter, so the out of bounds
3628
+ # warning flag becomes 3, but is checked for first.
3629
+ if bounds and (np.any(lower_bound > x) or np.any(x > upper_bound)):
3630
+ warnflag = 4
3631
+ msg = _status_message['out_of_bounds']
3632
+ elif fcalls[0] >= maxfun:
3633
+ warnflag = 1
3634
+ msg = _status_message['maxfev']
3635
+ elif iter >= maxiter:
3636
+ warnflag = 2
3637
+ msg = _status_message['maxiter']
3638
+ elif np.isnan(fval) or np.isnan(x).any():
3639
+ warnflag = 3
3640
+ msg = _status_message['nan']
3641
+
3642
+ if disp:
3643
+ _print_success_message_or_warn(warnflag, msg, RuntimeWarning)
3644
+ print(f" Current function value: {fval:f}")
3645
+ print(f" Iterations: {iter:d}")
3646
+ print(f" Function evaluations: {fcalls[0]:d}")
3647
+ result = OptimizeResult(fun=fval, direc=direc, nit=iter, nfev=fcalls[0],
3648
+ status=warnflag, success=(warnflag == 0),
3649
+ message=msg, x=x)
3650
+ if retall:
3651
+ result['allvecs'] = allvecs
3652
+ return result
3653
+
3654
+
3655
+ def _endprint(x, flag, fval, maxfun, xtol, disp):
3656
+ if flag == 0:
3657
+ if disp > 1:
3658
+ print("\nOptimization terminated successfully;\n"
3659
+ "The returned value satisfies the termination criteria\n"
3660
+ "(using xtol = ", xtol, ")")
3661
+ return
3662
+
3663
+ if flag == 1:
3664
+ msg = ("\nMaximum number of function evaluations exceeded --- "
3665
+ "increase maxfun argument.\n")
3666
+ elif flag == 2:
3667
+ msg = f"\n{_status_message['nan']}"
3668
+
3669
+ _print_success_message_or_warn(flag, msg)
3670
+ return
3671
+
3672
+
3673
+ def brute(func, ranges, args=(), Ns=20, full_output=0, finish=fmin,
3674
+ disp=False, workers=1):
3675
+ """Minimize a function over a given range by brute force.
3676
+
3677
+ Uses the "brute force" method, i.e., computes the function's value
3678
+ at each point of a multidimensional grid of points, to find the global
3679
+ minimum of the function.
3680
+
3681
+ The function is evaluated everywhere in the range with the datatype of the
3682
+ first call to the function, as enforced by the ``vectorize`` NumPy
3683
+ function. The value and type of the function evaluation returned when
3684
+ ``full_output=True`` are affected in addition by the ``finish`` argument
3685
+ (see Notes).
3686
+
3687
+ The brute force approach is inefficient because the number of grid points
3688
+ increases exponentially - the number of grid points to evaluate is
3689
+ ``Ns ** len(x)``. Consequently, even with coarse grid spacing, even
3690
+ moderately sized problems can take a long time to run, and/or run into
3691
+ memory limitations.
3692
+
3693
+ Parameters
3694
+ ----------
3695
+ func : callable
3696
+ The objective function to be minimized. Must be in the
3697
+ form ``f(x, *args)``, where ``x`` is the argument in
3698
+ the form of a 1-D array and ``args`` is a tuple of any
3699
+ additional fixed parameters needed to completely specify
3700
+ the function.
3701
+ ranges : tuple
3702
+ Each component of the `ranges` tuple must be either a
3703
+ "slice object" or a range tuple of the form ``(low, high)``.
3704
+ The program uses these to create the grid of points on which
3705
+ the objective function will be computed. See `Note 2` for
3706
+ more detail.
3707
+ args : tuple, optional
3708
+ Any additional fixed parameters needed to completely specify
3709
+ the function.
3710
+ Ns : int, optional
3711
+ Number of grid points along the axes, if not otherwise
3712
+ specified. See `Note2`.
3713
+ full_output : bool, optional
3714
+ If True, return the evaluation grid and the objective function's
3715
+ values on it.
3716
+ finish : callable, optional
3717
+ An optimization function that is called with the result of brute force
3718
+ minimization as initial guess. `finish` should take `func` and
3719
+ the initial guess as positional arguments, and take `args` as
3720
+ keyword arguments. It may additionally take `full_output`
3721
+ and/or `disp` as keyword arguments. Use None if no "polishing"
3722
+ function is to be used. See Notes for more details.
3723
+ disp : bool, optional
3724
+ Set to True to print convergence messages from the `finish` callable.
3725
+ workers : int or map-like callable, optional
3726
+ If `workers` is an int the grid is subdivided into `workers`
3727
+ sections and evaluated in parallel (uses
3728
+ `multiprocessing.Pool <multiprocessing>`).
3729
+ Supply `-1` to use all cores available to the Process.
3730
+ Alternatively supply a map-like callable, such as
3731
+ `multiprocessing.Pool.map` for evaluating the grid in parallel.
3732
+ This evaluation is carried out as ``workers(func, iterable)``.
3733
+ Requires that `func` be pickleable.
3734
+
3735
+ .. versionadded:: 1.3.0
3736
+
3737
+ Returns
3738
+ -------
3739
+ x0 : ndarray
3740
+ A 1-D array containing the coordinates of a point at which the
3741
+ objective function had its minimum value. (See `Note 1` for
3742
+ which point is returned.)
3743
+ fval : float
3744
+ Function value at the point `x0`. (Returned when `full_output` is
3745
+ True.)
3746
+ grid : tuple
3747
+ Representation of the evaluation grid. It has the same
3748
+ length as `x0`. (Returned when `full_output` is True.)
3749
+ Jout : ndarray
3750
+ Function values at each point of the evaluation
3751
+ grid, i.e., ``Jout = func(*grid)``. (Returned
3752
+ when `full_output` is True.)
3753
+
3754
+ See Also
3755
+ --------
3756
+ basinhopping, differential_evolution
3757
+
3758
+ Notes
3759
+ -----
3760
+ *Note 1*: The program finds the gridpoint at which the lowest value
3761
+ of the objective function occurs. If `finish` is None, that is the
3762
+ point returned. When the global minimum occurs within (or not very far
3763
+ outside) the grid's boundaries, and the grid is fine enough, that
3764
+ point will be in the neighborhood of the global minimum.
3765
+
3766
+ However, users often employ some other optimization program to
3767
+ "polish" the gridpoint values, i.e., to seek a more precise
3768
+ (local) minimum near `brute's` best gridpoint.
3769
+ The `brute` function's `finish` option provides a convenient way to do
3770
+ that. Any polishing program used must take `brute's` output as its
3771
+ initial guess as a positional argument, and take `brute's` input values
3772
+ for `args` as keyword arguments, otherwise an error will be raised.
3773
+ It may additionally take `full_output` and/or `disp` as keyword arguments.
3774
+
3775
+ `brute` assumes that the `finish` function returns either an
3776
+ `OptimizeResult` object or a tuple in the form:
3777
+ ``(xmin, Jmin, ... , statuscode)``, where ``xmin`` is the minimizing
3778
+ value of the argument, ``Jmin`` is the minimum value of the objective
3779
+ function, "..." may be some other returned values (which are not used
3780
+ by `brute`), and ``statuscode`` is the status code of the `finish` program.
3781
+
3782
+ Note that when `finish` is not None, the values returned are those
3783
+ of the `finish` program, *not* the gridpoint ones. Consequently,
3784
+ while `brute` confines its search to the input grid points,
3785
+ the `finish` program's results usually will not coincide with any
3786
+ gridpoint, and may fall outside the grid's boundary. Thus, if a
3787
+ minimum only needs to be found over the provided grid points, make
3788
+ sure to pass in ``finish=None``.
3789
+
3790
+ *Note 2*: The grid of points is a `numpy.mgrid` object.
3791
+ For `brute` the `ranges` and `Ns` inputs have the following effect.
3792
+ Each component of the `ranges` tuple can be either a slice object or a
3793
+ two-tuple giving a range of values, such as (0, 5). If the component is a
3794
+ slice object, `brute` uses it directly. If the component is a two-tuple
3795
+ range, `brute` internally converts it to a slice object that interpolates
3796
+ `Ns` points from its low-value to its high-value, inclusive.
3797
+
3798
+ Examples
3799
+ --------
3800
+ We illustrate the use of `brute` to seek the global minimum of a function
3801
+ of two variables that is given as the sum of a positive-definite
3802
+ quadratic and two deep "Gaussian-shaped" craters. Specifically, define
3803
+ the objective function `f` as the sum of three other functions,
3804
+ ``f = f1 + f2 + f3``. We suppose each of these has a signature
3805
+ ``(z, *params)``, where ``z = (x, y)``, and ``params`` and the functions
3806
+ are as defined below.
3807
+
3808
+ >>> import numpy as np
3809
+ >>> params = (2, 3, 7, 8, 9, 10, 44, -1, 2, 26, 1, -2, 0.5)
3810
+ >>> def f1(z, *params):
3811
+ ... x, y = z
3812
+ ... a, b, c, d, e, f, g, h, i, j, k, l, scale = params
3813
+ ... return (a * x**2 + b * x * y + c * y**2 + d*x + e*y + f)
3814
+
3815
+ >>> def f2(z, *params):
3816
+ ... x, y = z
3817
+ ... a, b, c, d, e, f, g, h, i, j, k, l, scale = params
3818
+ ... return (-g*np.exp(-((x-h)**2 + (y-i)**2) / scale))
3819
+
3820
+ >>> def f3(z, *params):
3821
+ ... x, y = z
3822
+ ... a, b, c, d, e, f, g, h, i, j, k, l, scale = params
3823
+ ... return (-j*np.exp(-((x-k)**2 + (y-l)**2) / scale))
3824
+
3825
+ >>> def f(z, *params):
3826
+ ... return f1(z, *params) + f2(z, *params) + f3(z, *params)
3827
+
3828
+ Thus, the objective function may have local minima near the minimum
3829
+ of each of the three functions of which it is composed. To
3830
+ use `fmin` to polish its gridpoint result, we may then continue as
3831
+ follows:
3832
+
3833
+ >>> rranges = (slice(-4, 4, 0.25), slice(-4, 4, 0.25))
3834
+ >>> from scipy import optimize
3835
+ >>> resbrute = optimize.brute(f, rranges, args=params, full_output=True,
3836
+ ... finish=optimize.fmin)
3837
+ >>> resbrute[0] # global minimum
3838
+ array([-1.05665192, 1.80834843])
3839
+ >>> resbrute[1] # function value at global minimum
3840
+ -3.4085818767
3841
+
3842
+ Note that if `finish` had been set to None, we would have gotten the
3843
+ gridpoint [-1.0 1.75] where the rounded function value is -2.892.
3844
+
3845
+ """
3846
+ N = len(ranges)
3847
+ if N > 40:
3848
+ raise ValueError("Brute Force not possible with more "
3849
+ "than 40 variables.")
3850
+ lrange = list(ranges)
3851
+ for k in range(N):
3852
+ if not isinstance(lrange[k], slice):
3853
+ if len(lrange[k]) < 3:
3854
+ lrange[k] = tuple(lrange[k]) + (complex(Ns),)
3855
+ lrange[k] = slice(*lrange[k])
3856
+ if (N == 1):
3857
+ lrange = lrange[0]
3858
+
3859
+ grid = np.mgrid[lrange]
3860
+
3861
+ # obtain an array of parameters that is iterable by a map-like callable
3862
+ inpt_shape = grid.shape
3863
+ if (N > 1):
3864
+ grid = np.reshape(grid, (inpt_shape[0], np.prod(inpt_shape[1:]))).T
3865
+
3866
+ if not np.iterable(args):
3867
+ args = (args,)
3868
+
3869
+ wrapped_func = _Brute_Wrapper(func, args)
3870
+
3871
+ # iterate over input arrays, possibly in parallel
3872
+ with MapWrapper(pool=workers) as mapper:
3873
+ Jout = np.array(list(mapper(wrapped_func, grid)))
3874
+ if (N == 1):
3875
+ grid = (grid,)
3876
+ Jout = np.squeeze(Jout)
3877
+ elif (N > 1):
3878
+ Jout = np.reshape(Jout, inpt_shape[1:])
3879
+ grid = np.reshape(grid.T, inpt_shape)
3880
+
3881
+ Nshape = shape(Jout)
3882
+
3883
+ indx = argmin(Jout.ravel(), axis=-1)
3884
+ Nindx = np.empty(N, int)
3885
+ xmin = np.empty(N, float)
3886
+ for k in range(N - 1, -1, -1):
3887
+ thisN = Nshape[k]
3888
+ Nindx[k] = indx % Nshape[k]
3889
+ indx = indx // thisN
3890
+ for k in range(N):
3891
+ xmin[k] = grid[k][tuple(Nindx)]
3892
+
3893
+ Jmin = Jout[tuple(Nindx)]
3894
+ if (N == 1):
3895
+ grid = grid[0]
3896
+ xmin = xmin[0]
3897
+
3898
+ if callable(finish):
3899
+ # set up kwargs for `finish` function
3900
+ finish_args = _getfullargspec(finish).args
3901
+ finish_kwargs = dict()
3902
+ if 'full_output' in finish_args:
3903
+ finish_kwargs['full_output'] = 1
3904
+ if 'disp' in finish_args:
3905
+ finish_kwargs['disp'] = disp
3906
+ elif 'options' in finish_args:
3907
+ # pass 'disp' as `options`
3908
+ # (e.g., if `finish` is `minimize`)
3909
+ finish_kwargs['options'] = {'disp': disp}
3910
+
3911
+ # run minimizer
3912
+ res = finish(func, xmin, args=args, **finish_kwargs)
3913
+
3914
+ if isinstance(res, OptimizeResult):
3915
+ xmin = res.x
3916
+ Jmin = res.fun
3917
+ success = res.success
3918
+ else:
3919
+ xmin = res[0]
3920
+ Jmin = res[1]
3921
+ success = res[-1] == 0
3922
+ if not success:
3923
+ if disp:
3924
+ warnings.warn("Either final optimization did not succeed or `finish` "
3925
+ "does not return `statuscode` as its last argument.",
3926
+ RuntimeWarning, stacklevel=2)
3927
+
3928
+ if full_output:
3929
+ return xmin, Jmin, grid, Jout
3930
+ else:
3931
+ return xmin
3932
+
3933
+
3934
+ class _Brute_Wrapper:
3935
+ """
3936
+ Object to wrap user cost function for optimize.brute, allowing picklability
3937
+ """
3938
+
3939
+ def __init__(self, f, args):
3940
+ self.f = f
3941
+ self.args = [] if args is None else args
3942
+
3943
+ def __call__(self, x):
3944
+ # flatten needed for one dimensional case.
3945
+ return self.f(np.asarray(x).flatten(), *self.args)
3946
+
3947
+
3948
+ def show_options(solver=None, method=None, disp=True):
3949
+ """
3950
+ Show documentation for additional options of optimization solvers.
3951
+
3952
+ These are method-specific options that can be supplied through the
3953
+ ``options`` dict.
3954
+
3955
+ Parameters
3956
+ ----------
3957
+ solver : str
3958
+ Type of optimization solver. One of 'minimize', 'minimize_scalar',
3959
+ 'root', 'root_scalar', 'linprog', or 'quadratic_assignment'.
3960
+ method : str, optional
3961
+ If not given, shows all methods of the specified solver. Otherwise,
3962
+ show only the options for the specified method. Valid values
3963
+ corresponds to methods' names of respective solver (e.g., 'BFGS' for
3964
+ 'minimize').
3965
+ disp : bool, optional
3966
+ Whether to print the result rather than returning it.
3967
+
3968
+ Returns
3969
+ -------
3970
+ text
3971
+ Either None (for disp=True) or the text string (disp=False)
3972
+
3973
+ Notes
3974
+ -----
3975
+ The solver-specific methods are:
3976
+
3977
+ `scipy.optimize.minimize`
3978
+
3979
+ - :ref:`Nelder-Mead <optimize.minimize-neldermead>`
3980
+ - :ref:`Powell <optimize.minimize-powell>`
3981
+ - :ref:`CG <optimize.minimize-cg>`
3982
+ - :ref:`BFGS <optimize.minimize-bfgs>`
3983
+ - :ref:`Newton-CG <optimize.minimize-newtoncg>`
3984
+ - :ref:`L-BFGS-B <optimize.minimize-lbfgsb>`
3985
+ - :ref:`TNC <optimize.minimize-tnc>`
3986
+ - :ref:`COBYLA <optimize.minimize-cobyla>`
3987
+ - :ref:`COBYQA <optimize.minimize-cobyqa>`
3988
+ - :ref:`SLSQP <optimize.minimize-slsqp>`
3989
+ - :ref:`dogleg <optimize.minimize-dogleg>`
3990
+ - :ref:`trust-ncg <optimize.minimize-trustncg>`
3991
+
3992
+ `scipy.optimize.root`
3993
+
3994
+ - :ref:`hybr <optimize.root-hybr>`
3995
+ - :ref:`lm <optimize.root-lm>`
3996
+ - :ref:`broyden1 <optimize.root-broyden1>`
3997
+ - :ref:`broyden2 <optimize.root-broyden2>`
3998
+ - :ref:`anderson <optimize.root-anderson>`
3999
+ - :ref:`linearmixing <optimize.root-linearmixing>`
4000
+ - :ref:`diagbroyden <optimize.root-diagbroyden>`
4001
+ - :ref:`excitingmixing <optimize.root-excitingmixing>`
4002
+ - :ref:`krylov <optimize.root-krylov>`
4003
+ - :ref:`df-sane <optimize.root-dfsane>`
4004
+
4005
+ `scipy.optimize.minimize_scalar`
4006
+
4007
+ - :ref:`brent <optimize.minimize_scalar-brent>`
4008
+ - :ref:`golden <optimize.minimize_scalar-golden>`
4009
+ - :ref:`bounded <optimize.minimize_scalar-bounded>`
4010
+
4011
+ `scipy.optimize.root_scalar`
4012
+
4013
+ - :ref:`bisect <optimize.root_scalar-bisect>`
4014
+ - :ref:`brentq <optimize.root_scalar-brentq>`
4015
+ - :ref:`brenth <optimize.root_scalar-brenth>`
4016
+ - :ref:`ridder <optimize.root_scalar-ridder>`
4017
+ - :ref:`toms748 <optimize.root_scalar-toms748>`
4018
+ - :ref:`newton <optimize.root_scalar-newton>`
4019
+ - :ref:`secant <optimize.root_scalar-secant>`
4020
+ - :ref:`halley <optimize.root_scalar-halley>`
4021
+
4022
+ `scipy.optimize.linprog`
4023
+
4024
+ - :ref:`simplex <optimize.linprog-simplex>`
4025
+ - :ref:`interior-point <optimize.linprog-interior-point>`
4026
+ - :ref:`revised simplex <optimize.linprog-revised_simplex>`
4027
+ - :ref:`highs <optimize.linprog-highs>`
4028
+ - :ref:`highs-ds <optimize.linprog-highs-ds>`
4029
+ - :ref:`highs-ipm <optimize.linprog-highs-ipm>`
4030
+
4031
+ `scipy.optimize.quadratic_assignment`
4032
+
4033
+ - :ref:`faq <optimize.qap-faq>`
4034
+ - :ref:`2opt <optimize.qap-2opt>`
4035
+
4036
+ Examples
4037
+ --------
4038
+ We can print documentations of a solver in stdout:
4039
+
4040
+ >>> from scipy.optimize import show_options
4041
+ >>> show_options(solver="minimize")
4042
+ ...
4043
+
4044
+ Specifying a method is possible:
4045
+
4046
+ >>> show_options(solver="minimize", method="Nelder-Mead")
4047
+ ...
4048
+
4049
+ We can also get the documentations as a string:
4050
+
4051
+ >>> show_options(solver="minimize", method="Nelder-Mead", disp=False)
4052
+ Minimization of scalar function of one or more variables using the ...
4053
+
4054
+ """
4055
+ import textwrap
4056
+
4057
+ doc_routines = {
4058
+ 'minimize': (
4059
+ ('bfgs', 'scipy.optimize._optimize._minimize_bfgs'),
4060
+ ('cg', 'scipy.optimize._optimize._minimize_cg'),
4061
+ ('cobyla', 'scipy.optimize._cobyla_py._minimize_cobyla'),
4062
+ ('cobyqa', 'scipy.optimize._cobyqa_py._minimize_cobyqa'),
4063
+ ('dogleg', 'scipy.optimize._trustregion_dogleg._minimize_dogleg'),
4064
+ ('l-bfgs-b', 'scipy.optimize._lbfgsb_py._minimize_lbfgsb'),
4065
+ ('nelder-mead', 'scipy.optimize._optimize._minimize_neldermead'),
4066
+ ('newton-cg', 'scipy.optimize._optimize._minimize_newtoncg'),
4067
+ ('powell', 'scipy.optimize._optimize._minimize_powell'),
4068
+ ('slsqp', 'scipy.optimize._slsqp_py._minimize_slsqp'),
4069
+ ('tnc', 'scipy.optimize._tnc._minimize_tnc'),
4070
+ ('trust-ncg',
4071
+ 'scipy.optimize._trustregion_ncg._minimize_trust_ncg'),
4072
+ ('trust-constr',
4073
+ 'scipy.optimize._trustregion_constr.'
4074
+ '_minimize_trustregion_constr'),
4075
+ ('trust-exact',
4076
+ 'scipy.optimize._trustregion_exact._minimize_trustregion_exact'),
4077
+ ('trust-krylov',
4078
+ 'scipy.optimize._trustregion_krylov._minimize_trust_krylov'),
4079
+ ),
4080
+ 'root': (
4081
+ ('hybr', 'scipy.optimize._minpack_py._root_hybr'),
4082
+ ('lm', 'scipy.optimize._root._root_leastsq'),
4083
+ ('broyden1', 'scipy.optimize._root._root_broyden1_doc'),
4084
+ ('broyden2', 'scipy.optimize._root._root_broyden2_doc'),
4085
+ ('anderson', 'scipy.optimize._root._root_anderson_doc'),
4086
+ ('diagbroyden', 'scipy.optimize._root._root_diagbroyden_doc'),
4087
+ ('excitingmixing', 'scipy.optimize._root._root_excitingmixing_doc'),
4088
+ ('linearmixing', 'scipy.optimize._root._root_linearmixing_doc'),
4089
+ ('krylov', 'scipy.optimize._root._root_krylov_doc'),
4090
+ ('df-sane', 'scipy.optimize._spectral._root_df_sane'),
4091
+ ),
4092
+ 'root_scalar': (
4093
+ ('bisect', 'scipy.optimize._root_scalar._root_scalar_bisect_doc'),
4094
+ ('brentq', 'scipy.optimize._root_scalar._root_scalar_brentq_doc'),
4095
+ ('brenth', 'scipy.optimize._root_scalar._root_scalar_brenth_doc'),
4096
+ ('ridder', 'scipy.optimize._root_scalar._root_scalar_ridder_doc'),
4097
+ ('toms748', 'scipy.optimize._root_scalar._root_scalar_toms748_doc'),
4098
+ ('secant', 'scipy.optimize._root_scalar._root_scalar_secant_doc'),
4099
+ ('newton', 'scipy.optimize._root_scalar._root_scalar_newton_doc'),
4100
+ ('halley', 'scipy.optimize._root_scalar._root_scalar_halley_doc'),
4101
+ ),
4102
+ 'linprog': (
4103
+ ('simplex', 'scipy.optimize._linprog._linprog_simplex_doc'),
4104
+ ('interior-point', 'scipy.optimize._linprog._linprog_ip_doc'),
4105
+ ('revised simplex', 'scipy.optimize._linprog._linprog_rs_doc'),
4106
+ ('highs-ipm', 'scipy.optimize._linprog._linprog_highs_ipm_doc'),
4107
+ ('highs-ds', 'scipy.optimize._linprog._linprog_highs_ds_doc'),
4108
+ ('highs', 'scipy.optimize._linprog._linprog_highs_doc'),
4109
+ ),
4110
+ 'quadratic_assignment': (
4111
+ ('faq', 'scipy.optimize._qap._quadratic_assignment_faq'),
4112
+ ('2opt', 'scipy.optimize._qap._quadratic_assignment_2opt'),
4113
+ ),
4114
+ 'minimize_scalar': (
4115
+ ('brent', 'scipy.optimize._optimize._minimize_scalar_brent'),
4116
+ ('bounded', 'scipy.optimize._optimize._minimize_scalar_bounded'),
4117
+ ('golden', 'scipy.optimize._optimize._minimize_scalar_golden'),
4118
+ ),
4119
+ }
4120
+
4121
+ if solver is None:
4122
+ text = ["\n\n\n========\n", "minimize\n", "========\n"]
4123
+ text.append(show_options('minimize', disp=False))
4124
+ text.extend(["\n\n===============\n", "minimize_scalar\n",
4125
+ "===============\n"])
4126
+ text.append(show_options('minimize_scalar', disp=False))
4127
+ text.extend(["\n\n\n====\n", "root\n",
4128
+ "====\n"])
4129
+ text.append(show_options('root', disp=False))
4130
+ text.extend(['\n\n\n=======\n', 'linprog\n',
4131
+ '=======\n'])
4132
+ text.append(show_options('linprog', disp=False))
4133
+ text = "".join(text)
4134
+ else:
4135
+ solver = solver.lower()
4136
+ if solver not in doc_routines:
4137
+ raise ValueError(f'Unknown solver {solver!r}')
4138
+
4139
+ if method is None:
4140
+ text = []
4141
+ for name, _ in doc_routines[solver]:
4142
+ text.extend(["\n\n" + name, "\n" + "="*len(name) + "\n\n"])
4143
+ text.append(show_options(solver, name, disp=False))
4144
+ text = "".join(text)
4145
+ else:
4146
+ method = method.lower()
4147
+ methods = dict(doc_routines[solver])
4148
+ if method not in methods:
4149
+ raise ValueError(f"Unknown method {method!r}")
4150
+ name = methods[method]
4151
+
4152
+ # Import function object
4153
+ parts = name.split('.')
4154
+ mod_name = ".".join(parts[:-1])
4155
+ __import__(mod_name)
4156
+ obj = getattr(sys.modules[mod_name], parts[-1])
4157
+
4158
+ # Get doc
4159
+ doc = obj.__doc__
4160
+ if doc is not None:
4161
+ text = textwrap.dedent(doc).strip()
4162
+ else:
4163
+ text = ""
4164
+
4165
+ if disp:
4166
+ print(text)
4167
+ return
4168
+ else:
4169
+ return text