_dcsrch.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. import numpy as np
  2. """
  3. # 2023 - ported from minpack2.dcsrch, dcstep (Fortran) to Python
  4. c MINPACK-1 Project. June 1983.
  5. c Argonne National Laboratory.
  6. c Jorge J. More' and David J. Thuente.
  7. c
  8. c MINPACK-2 Project. November 1993.
  9. c Argonne National Laboratory and University of Minnesota.
  10. c Brett M. Averick, Richard G. Carter, and Jorge J. More'.
  11. """
  12. # NOTE this file was linted by black on first commit, and can be kept that way.
  13. class DCSRCH:
  14. """
  15. Parameters
  16. ----------
  17. phi : callable phi(alpha)
  18. Function at point `alpha`
  19. derphi : callable phi'(alpha)
  20. Objective function derivative. Returns a scalar.
  21. ftol : float
  22. A nonnegative tolerance for the sufficient decrease condition.
  23. gtol : float
  24. A nonnegative tolerance for the curvature condition.
  25. xtol : float
  26. A nonnegative relative tolerance for an acceptable step. The
  27. subroutine exits with a warning if the relative difference between
  28. sty and stx is less than xtol.
  29. stpmin : float
  30. A nonnegative lower bound for the step.
  31. stpmax :
  32. A nonnegative upper bound for the step.
  33. Notes
  34. -----
  35. This subroutine finds a step that satisfies a sufficient
  36. decrease condition and a curvature condition.
  37. Each call of the subroutine updates an interval with
  38. endpoints stx and sty. The interval is initially chosen
  39. so that it contains a minimizer of the modified function
  40. psi(stp) = f(stp) - f(0) - ftol*stp*f'(0).
  41. If psi(stp) <= 0 and f'(stp) >= 0 for some step, then the
  42. interval is chosen so that it contains a minimizer of f.
  43. The algorithm is designed to find a step that satisfies
  44. the sufficient decrease condition
  45. f(stp) <= f(0) + ftol*stp*f'(0),
  46. and the curvature condition
  47. abs(f'(stp)) <= gtol*abs(f'(0)).
  48. If ftol is less than gtol and if, for example, the function
  49. is bounded below, then there is always a step which satisfies
  50. both conditions.
  51. If no step can be found that satisfies both conditions, then
  52. the algorithm stops with a warning. In this case stp only
  53. satisfies the sufficient decrease condition.
  54. A typical invocation of dcsrch has the following outline:
  55. Evaluate the function at stp = 0.0d0; store in f.
  56. Evaluate the gradient at stp = 0.0d0; store in g.
  57. Choose a starting step stp.
  58. task = 'START'
  59. 10 continue
  60. call dcsrch(stp,f,g,ftol,gtol,xtol,task,stpmin,stpmax,
  61. isave,dsave)
  62. if (task .eq. 'FG') then
  63. Evaluate the function and the gradient at stp
  64. go to 10
  65. end if
  66. NOTE: The user must not alter work arrays between calls.
  67. The subroutine statement is
  68. subroutine dcsrch(f,g,stp,ftol,gtol,xtol,stpmin,stpmax,
  69. task,isave,dsave)
  70. where
  71. stp is a double precision variable.
  72. On entry stp is the current estimate of a satisfactory
  73. step. On initial entry, a positive initial estimate
  74. must be provided.
  75. On exit stp is the current estimate of a satisfactory step
  76. if task = 'FG'. If task = 'CONV' then stp satisfies
  77. the sufficient decrease and curvature condition.
  78. f is a double precision variable.
  79. On initial entry f is the value of the function at 0.
  80. On subsequent entries f is the value of the
  81. function at stp.
  82. On exit f is the value of the function at stp.
  83. g is a double precision variable.
  84. On initial entry g is the derivative of the function at 0.
  85. On subsequent entries g is the derivative of the
  86. function at stp.
  87. On exit g is the derivative of the function at stp.
  88. ftol is a double precision variable.
  89. On entry ftol specifies a nonnegative tolerance for the
  90. sufficient decrease condition.
  91. On exit ftol is unchanged.
  92. gtol is a double precision variable.
  93. On entry gtol specifies a nonnegative tolerance for the
  94. curvature condition.
  95. On exit gtol is unchanged.
  96. xtol is a double precision variable.
  97. On entry xtol specifies a nonnegative relative tolerance
  98. for an acceptable step. The subroutine exits with a
  99. warning if the relative difference between sty and stx
  100. is less than xtol.
  101. On exit xtol is unchanged.
  102. task is a character variable of length at least 60.
  103. On initial entry task must be set to 'START'.
  104. On exit task indicates the required action:
  105. If task(1:2) = 'FG' then evaluate the function and
  106. derivative at stp and call dcsrch again.
  107. If task(1:4) = 'CONV' then the search is successful.
  108. If task(1:4) = 'WARN' then the subroutine is not able
  109. to satisfy the convergence conditions. The exit value of
  110. stp contains the best point found during the search.
  111. If task(1:5) = 'ERROR' then there is an error in the
  112. input arguments.
  113. On exit with convergence, a warning or an error, the
  114. variable task contains additional information.
  115. stpmin is a double precision variable.
  116. On entry stpmin is a nonnegative lower bound for the step.
  117. On exit stpmin is unchanged.
  118. stpmax is a double precision variable.
  119. On entry stpmax is a nonnegative upper bound for the step.
  120. On exit stpmax is unchanged.
  121. isave is an integer work array of dimension 2.
  122. dsave is a double precision work array of dimension 13.
  123. Subprograms called
  124. MINPACK-2 ... dcstep
  125. MINPACK-1 Project. June 1983.
  126. Argonne National Laboratory.
  127. Jorge J. More' and David J. Thuente.
  128. MINPACK-2 Project. November 1993.
  129. Argonne National Laboratory and University of Minnesota.
  130. Brett M. Averick, Richard G. Carter, and Jorge J. More'.
  131. """
  132. def __init__(self, phi, derphi, ftol, gtol, xtol, stpmin, stpmax):
  133. self.stage = None
  134. self.ginit = None
  135. self.gtest = None
  136. self.gx = None
  137. self.gy = None
  138. self.finit = None
  139. self.fx = None
  140. self.fy = None
  141. self.stx = None
  142. self.sty = None
  143. self.stmin = None
  144. self.stmax = None
  145. self.width = None
  146. self.width1 = None
  147. # leave all assessment of tolerances/limits to the first call of
  148. # this object
  149. self.ftol = ftol
  150. self.gtol = gtol
  151. self.xtol = xtol
  152. self.stpmin = stpmin
  153. self.stpmax = stpmax
  154. self.phi = phi
  155. self.derphi = derphi
  156. def __call__(self, alpha1, phi0=None, derphi0=None, maxiter=100):
  157. """
  158. Parameters
  159. ----------
  160. alpha1 : float
  161. alpha1 is the current estimate of a satisfactory
  162. step. A positive initial estimate must be provided.
  163. phi0 : float
  164. the value of `phi` at 0 (if known).
  165. derphi0 : float
  166. the derivative of `derphi` at 0 (if known).
  167. maxiter : int
  168. Returns
  169. -------
  170. alpha : float
  171. Step size, or None if no suitable step was found.
  172. phi : float
  173. Value of `phi` at the new point `alpha`.
  174. phi0 : float
  175. Value of `phi` at `alpha=0`.
  176. task : bytes
  177. On exit task indicates status information.
  178. If task[:4] == b'CONV' then the search is successful.
  179. If task[:4] == b'WARN' then the subroutine is not able
  180. to satisfy the convergence conditions. The exit value of
  181. stp contains the best point found during the search.
  182. If task[:5] == b'ERROR' then there is an error in the
  183. input arguments.
  184. """
  185. if phi0 is None:
  186. phi0 = self.phi(0.0)
  187. if derphi0 is None:
  188. derphi0 = self.derphi(0.0)
  189. phi1 = phi0
  190. derphi1 = derphi0
  191. task = b"START"
  192. for i in range(maxiter):
  193. stp, phi1, derphi1, task = self._iterate(
  194. alpha1, phi1, derphi1, task
  195. )
  196. if not np.isfinite(stp):
  197. task = b"WARN"
  198. stp = None
  199. break
  200. if task[:2] == b"FG":
  201. alpha1 = stp
  202. phi1 = self.phi(stp)
  203. derphi1 = self.derphi(stp)
  204. else:
  205. break
  206. else:
  207. # maxiter reached, the line search did not converge
  208. stp = None
  209. task = b"WARNING: dcsrch did not converge within max iterations"
  210. if task[:5] == b"ERROR" or task[:4] == b"WARN":
  211. stp = None # failed
  212. return stp, phi1, phi0, task
  213. def _iterate(self, stp, f, g, task):
  214. """
  215. Parameters
  216. ----------
  217. stp : float
  218. The current estimate of a satisfactory step. On initial entry, a
  219. positive initial estimate must be provided.
  220. f : float
  221. On first call f is the value of the function at 0. On subsequent
  222. entries f should be the value of the function at stp.
  223. g : float
  224. On initial entry g is the derivative of the function at 0. On
  225. subsequent entries g is the derivative of the function at stp.
  226. task : bytes
  227. On initial entry task must be set to 'START'.
  228. On exit with convergence, a warning or an error, the
  229. variable task contains additional information.
  230. Returns
  231. -------
  232. stp, f, g, task: tuple
  233. stp : float
  234. the current estimate of a satisfactory step if task = 'FG'. If
  235. task = 'CONV' then stp satisfies the sufficient decrease and
  236. curvature condition.
  237. f : float
  238. the value of the function at stp.
  239. g : float
  240. the derivative of the function at stp.
  241. task : bytes
  242. On exit task indicates the required action:
  243. If task(1:2) == b'FG' then evaluate the function and
  244. derivative at stp and call dcsrch again.
  245. If task(1:4) == b'CONV' then the search is successful.
  246. If task(1:4) == b'WARN' then the subroutine is not able
  247. to satisfy the convergence conditions. The exit value of
  248. stp contains the best point found during the search.
  249. If task(1:5) == b'ERROR' then there is an error in the
  250. input arguments.
  251. """
  252. p5 = 0.5
  253. p66 = 0.66
  254. xtrapl = 1.1
  255. xtrapu = 4.0
  256. if task[:5] == b"START":
  257. if stp < self.stpmin:
  258. task = b"ERROR: STP .LT. STPMIN"
  259. if stp > self.stpmax:
  260. task = b"ERROR: STP .GT. STPMAX"
  261. if g >= 0:
  262. task = b"ERROR: INITIAL G .GE. ZERO"
  263. if self.ftol < 0:
  264. task = b"ERROR: FTOL .LT. ZERO"
  265. if self.gtol < 0:
  266. task = b"ERROR: GTOL .LT. ZERO"
  267. if self.xtol < 0:
  268. task = b"ERROR: XTOL .LT. ZERO"
  269. if self.stpmin < 0:
  270. task = b"ERROR: STPMIN .LT. ZERO"
  271. if self.stpmax < self.stpmin:
  272. task = b"ERROR: STPMAX .LT. STPMIN"
  273. if task[:5] == b"ERROR":
  274. return stp, f, g, task
  275. # Initialize local variables.
  276. self.brackt = False
  277. self.stage = 1
  278. self.finit = f
  279. self.ginit = g
  280. self.gtest = self.ftol * self.ginit
  281. self.width = self.stpmax - self.stpmin
  282. self.width1 = self.width / p5
  283. # The variables stx, fx, gx contain the values of the step,
  284. # function, and derivative at the best step.
  285. # The variables sty, fy, gy contain the value of the step,
  286. # function, and derivative at sty.
  287. # The variables stp, f, g contain the values of the step,
  288. # function, and derivative at stp.
  289. self.stx = 0.0
  290. self.fx = self.finit
  291. self.gx = self.ginit
  292. self.sty = 0.0
  293. self.fy = self.finit
  294. self.gy = self.ginit
  295. self.stmin = 0
  296. self.stmax = stp + xtrapu * stp
  297. task = b"FG"
  298. return stp, f, g, task
  299. # in the original Fortran this was a location to restore variables
  300. # we don't need to do that because they're attributes.
  301. # If psi(stp) <= 0 and f'(stp) >= 0 for some step, then the
  302. # algorithm enters the second stage.
  303. ftest = self.finit + stp * self.gtest
  304. if self.stage == 1 and f <= ftest and g >= 0:
  305. self.stage = 2
  306. # test for warnings
  307. if self.brackt and (stp <= self.stmin or stp >= self.stmax):
  308. task = b"WARNING: ROUNDING ERRORS PREVENT PROGRESS"
  309. if self.brackt and self.stmax - self.stmin <= self.xtol * self.stmax:
  310. task = b"WARNING: XTOL TEST SATISFIED"
  311. if stp == self.stpmax and f <= ftest and g <= self.gtest:
  312. task = b"WARNING: STP = STPMAX"
  313. if stp == self.stpmin and (f > ftest or g >= self.gtest):
  314. task = b"WARNING: STP = STPMIN"
  315. # test for convergence
  316. if f <= ftest and abs(g) <= self.gtol * -self.ginit:
  317. task = b"CONVERGENCE"
  318. # test for termination
  319. if task[:4] == b"WARN" or task[:4] == b"CONV":
  320. return stp, f, g, task
  321. # A modified function is used to predict the step during the
  322. # first stage if a lower function value has been obtained but
  323. # the decrease is not sufficient.
  324. if self.stage == 1 and f <= self.fx and f > ftest:
  325. # Define the modified function and derivative values.
  326. fm = f - stp * self.gtest
  327. fxm = self.fx - self.stx * self.gtest
  328. fym = self.fy - self.sty * self.gtest
  329. gm = g - self.gtest
  330. gxm = self.gx - self.gtest
  331. gym = self.gy - self.gtest
  332. # Call dcstep to update stx, sty, and to compute the new step.
  333. # dcstep can have several operations which can produce NaN
  334. # e.g. inf/inf. Filter these out.
  335. with np.errstate(invalid="ignore", over="ignore"):
  336. tup = dcstep(
  337. self.stx,
  338. fxm,
  339. gxm,
  340. self.sty,
  341. fym,
  342. gym,
  343. stp,
  344. fm,
  345. gm,
  346. self.brackt,
  347. self.stmin,
  348. self.stmax,
  349. )
  350. self.stx, fxm, gxm, self.sty, fym, gym, stp, self.brackt = tup
  351. # Reset the function and derivative values for f
  352. self.fx = fxm + self.stx * self.gtest
  353. self.fy = fym + self.sty * self.gtest
  354. self.gx = gxm + self.gtest
  355. self.gy = gym + self.gtest
  356. else:
  357. # Call dcstep to update stx, sty, and to compute the new step.
  358. # dcstep can have several operations which can produce NaN
  359. # e.g. inf/inf. Filter these out.
  360. with np.errstate(invalid="ignore", over="ignore"):
  361. tup = dcstep(
  362. self.stx,
  363. self.fx,
  364. self.gx,
  365. self.sty,
  366. self.fy,
  367. self.gy,
  368. stp,
  369. f,
  370. g,
  371. self.brackt,
  372. self.stmin,
  373. self.stmax,
  374. )
  375. (
  376. self.stx,
  377. self.fx,
  378. self.gx,
  379. self.sty,
  380. self.fy,
  381. self.gy,
  382. stp,
  383. self.brackt,
  384. ) = tup
  385. # Decide if a bisection step is needed
  386. if self.brackt:
  387. if abs(self.sty - self.stx) >= p66 * self.width1:
  388. stp = self.stx + p5 * (self.sty - self.stx)
  389. self.width1 = self.width
  390. self.width = abs(self.sty - self.stx)
  391. # Set the minimum and maximum steps allowed for stp.
  392. if self.brackt:
  393. self.stmin = min(self.stx, self.sty)
  394. self.stmax = max(self.stx, self.sty)
  395. else:
  396. self.stmin = stp + xtrapl * (stp - self.stx)
  397. self.stmax = stp + xtrapu * (stp - self.stx)
  398. # Force the step to be within the bounds stpmax and stpmin.
  399. stp = np.clip(stp, self.stpmin, self.stpmax)
  400. # If further progress is not possible, let stp be the best
  401. # point obtained during the search.
  402. if (
  403. self.brackt
  404. and (stp <= self.stmin or stp >= self.stmax)
  405. or (
  406. self.brackt
  407. and self.stmax - self.stmin <= self.xtol * self.stmax
  408. )
  409. ):
  410. stp = self.stx
  411. # Obtain another function and derivative
  412. task = b"FG"
  413. return stp, f, g, task
  414. def dcstep(stx, fx, dx, sty, fy, dy, stp, fp, dp, brackt, stpmin, stpmax):
  415. """
  416. Subroutine dcstep
  417. This subroutine computes a safeguarded step for a search
  418. procedure and updates an interval that contains a step that
  419. satisfies a sufficient decrease and a curvature condition.
  420. The parameter stx contains the step with the least function
  421. value. If brackt is set to .true. then a minimizer has
  422. been bracketed in an interval with endpoints stx and sty.
  423. The parameter stp contains the current step.
  424. The subroutine assumes that if brackt is set to .true. then
  425. min(stx,sty) < stp < max(stx,sty),
  426. and that the derivative at stx is negative in the direction
  427. of the step.
  428. The subroutine statement is
  429. subroutine dcstep(stx,fx,dx,sty,fy,dy,stp,fp,dp,brackt,
  430. stpmin,stpmax)
  431. where
  432. stx is a double precision variable.
  433. On entry stx is the best step obtained so far and is an
  434. endpoint of the interval that contains the minimizer.
  435. On exit stx is the updated best step.
  436. fx is a double precision variable.
  437. On entry fx is the function at stx.
  438. On exit fx is the function at stx.
  439. dx is a double precision variable.
  440. On entry dx is the derivative of the function at
  441. stx. The derivative must be negative in the direction of
  442. the step, that is, dx and stp - stx must have opposite
  443. signs.
  444. On exit dx is the derivative of the function at stx.
  445. sty is a double precision variable.
  446. On entry sty is the second endpoint of the interval that
  447. contains the minimizer.
  448. On exit sty is the updated endpoint of the interval that
  449. contains the minimizer.
  450. fy is a double precision variable.
  451. On entry fy is the function at sty.
  452. On exit fy is the function at sty.
  453. dy is a double precision variable.
  454. On entry dy is the derivative of the function at sty.
  455. On exit dy is the derivative of the function at the exit sty.
  456. stp is a double precision variable.
  457. On entry stp is the current step. If brackt is set to .true.
  458. then on input stp must be between stx and sty.
  459. On exit stp is a new trial step.
  460. fp is a double precision variable.
  461. On entry fp is the function at stp
  462. On exit fp is unchanged.
  463. dp is a double precision variable.
  464. On entry dp is the derivative of the function at stp.
  465. On exit dp is unchanged.
  466. brackt is a logical variable.
  467. On entry brackt specifies if a minimizer has been bracketed.
  468. Initially brackt must be set to .false.
  469. On exit brackt specifies if a minimizer has been bracketed.
  470. When a minimizer is bracketed brackt is set to .true.
  471. stpmin is a double precision variable.
  472. On entry stpmin is a lower bound for the step.
  473. On exit stpmin is unchanged.
  474. stpmax is a double precision variable.
  475. On entry stpmax is an upper bound for the step.
  476. On exit stpmax is unchanged.
  477. MINPACK-1 Project. June 1983
  478. Argonne National Laboratory.
  479. Jorge J. More' and David J. Thuente.
  480. MINPACK-2 Project. November 1993.
  481. Argonne National Laboratory and University of Minnesota.
  482. Brett M. Averick and Jorge J. More'.
  483. """
  484. sgn_dp = np.sign(dp)
  485. sgn_dx = np.sign(dx)
  486. # sgnd = dp * (dx / abs(dx))
  487. sgnd = sgn_dp * sgn_dx
  488. # First case: A higher function value. The minimum is bracketed.
  489. # If the cubic step is closer to stx than the quadratic step, the
  490. # cubic step is taken, otherwise the average of the cubic and
  491. # quadratic steps is taken.
  492. if fp > fx:
  493. theta = 3.0 * (fx - fp) / (stp - stx) + dx + dp
  494. s = max(abs(theta), abs(dx), abs(dp))
  495. gamma = s * np.sqrt((theta / s) ** 2 - (dx / s) * (dp / s))
  496. if stp < stx:
  497. gamma *= -1
  498. p = (gamma - dx) + theta
  499. q = ((gamma - dx) + gamma) + dp
  500. r = p / q
  501. stpc = stx + r * (stp - stx)
  502. stpq = stx + ((dx / ((fx - fp) / (stp - stx) + dx)) / 2.0) * (stp - stx)
  503. if abs(stpc - stx) <= abs(stpq - stx):
  504. stpf = stpc
  505. else:
  506. stpf = stpc + (stpq - stpc) / 2.0
  507. brackt = True
  508. elif sgnd < 0.0:
  509. # Second case: A lower function value and derivatives of opposite
  510. # sign. The minimum is bracketed. If the cubic step is farther from
  511. # stp than the secant step, the cubic step is taken, otherwise the
  512. # secant step is taken.
  513. theta = 3 * (fx - fp) / (stp - stx) + dx + dp
  514. s = max(abs(theta), abs(dx), abs(dp))
  515. gamma = s * np.sqrt((theta / s) ** 2 - (dx / s) * (dp / s))
  516. if stp > stx:
  517. gamma *= -1
  518. p = (gamma - dp) + theta
  519. q = ((gamma - dp) + gamma) + dx
  520. r = p / q
  521. stpc = stp + r * (stx - stp)
  522. stpq = stp + (dp / (dp - dx)) * (stx - stp)
  523. if abs(stpc - stp) > abs(stpq - stp):
  524. stpf = stpc
  525. else:
  526. stpf = stpq
  527. brackt = True
  528. elif abs(dp) < abs(dx):
  529. # Third case: A lower function value, derivatives of the same sign,
  530. # and the magnitude of the derivative decreases.
  531. # The cubic step is computed only if the cubic tends to infinity
  532. # in the direction of the step or if the minimum of the cubic
  533. # is beyond stp. Otherwise the cubic step is defined to be the
  534. # secant step.
  535. theta = 3 * (fx - fp) / (stp - stx) + dx + dp
  536. s = max(abs(theta), abs(dx), abs(dp))
  537. # The case gamma = 0 only arises if the cubic does not tend
  538. # to infinity in the direction of the step.
  539. gamma = s * np.sqrt(max(0, (theta / s) ** 2 - (dx / s) * (dp / s)))
  540. if stp > stx:
  541. gamma = -gamma
  542. p = (gamma - dp) + theta
  543. q = (gamma + (dx - dp)) + gamma
  544. r = p / q
  545. if r < 0 and gamma != 0:
  546. stpc = stp + r * (stx - stp)
  547. elif stp > stx:
  548. stpc = stpmax
  549. else:
  550. stpc = stpmin
  551. stpq = stp + (dp / (dp - dx)) * (stx - stp)
  552. if brackt:
  553. # A minimizer has been bracketed. If the cubic step is
  554. # closer to stp than the secant step, the cubic step is
  555. # taken, otherwise the secant step is taken.
  556. if abs(stpc - stp) < abs(stpq - stp):
  557. stpf = stpc
  558. else:
  559. stpf = stpq
  560. if stp > stx:
  561. stpf = min(stp + 0.66 * (sty - stp), stpf)
  562. else:
  563. stpf = max(stp + 0.66 * (sty - stp), stpf)
  564. else:
  565. # A minimizer has not been bracketed. If the cubic step is
  566. # farther from stp than the secant step, the cubic step is
  567. # taken, otherwise the secant step is taken.
  568. if abs(stpc - stp) > abs(stpq - stp):
  569. stpf = stpc
  570. else:
  571. stpf = stpq
  572. stpf = np.clip(stpf, stpmin, stpmax)
  573. else:
  574. # Fourth case: A lower function value, derivatives of the same sign,
  575. # and the magnitude of the derivative does not decrease. If the
  576. # minimum is not bracketed, the step is either stpmin or stpmax,
  577. # otherwise the cubic step is taken.
  578. if brackt:
  579. theta = 3.0 * (fp - fy) / (sty - stp) + dy + dp
  580. s = max(abs(theta), abs(dy), abs(dp))
  581. gamma = s * np.sqrt((theta / s) ** 2 - (dy / s) * (dp / s))
  582. if stp > sty:
  583. gamma = -gamma
  584. p = (gamma - dp) + theta
  585. q = ((gamma - dp) + gamma) + dy
  586. r = p / q
  587. stpc = stp + r * (sty - stp)
  588. stpf = stpc
  589. elif stp > stx:
  590. stpf = stpmax
  591. else:
  592. stpf = stpmin
  593. # Update the interval which contains a minimizer.
  594. if fp > fx:
  595. sty = stp
  596. fy = fp
  597. dy = dp
  598. else:
  599. if sgnd < 0:
  600. sty = stx
  601. fy = fx
  602. dy = dx
  603. stx = stp
  604. fx = fp
  605. dx = dp
  606. # Compute the new step.
  607. stp = stpf
  608. return stx, fx, dx, sty, fy, dy, stp, brackt