@ac-kit/math-analysis 0.1.11 → 0.3.0

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 (111) hide show
  1. package/CHANGELOG.md +155 -0
  2. package/README.md +167 -10
  3. package/dist/differentiation/finite-difference.d.ts +41 -0
  4. package/dist/differentiation/finite-difference.d.ts.map +1 -0
  5. package/dist/differentiation/finite-difference.js +53 -0
  6. package/dist/differentiation/finite-difference.js.map +1 -0
  7. package/dist/differentiation/gradient.d.ts +73 -0
  8. package/dist/differentiation/gradient.d.ts.map +1 -0
  9. package/dist/differentiation/gradient.js +167 -0
  10. package/dist/differentiation/gradient.js.map +1 -0
  11. package/dist/index.d.ts +20 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +20 -0
  14. package/dist/index.js.map +1 -1
  15. package/dist/interpolation/barycentric-interpolator.d.ts +29 -0
  16. package/dist/interpolation/barycentric-interpolator.d.ts.map +1 -0
  17. package/dist/interpolation/barycentric-interpolator.js +94 -0
  18. package/dist/interpolation/barycentric-interpolator.js.map +1 -0
  19. package/dist/legendre/_legendre-kernel.d.ts +22 -0
  20. package/dist/legendre/_legendre-kernel.d.ts.map +1 -0
  21. package/dist/legendre/_legendre-kernel.js +232 -0
  22. package/dist/legendre/_legendre-kernel.js.map +1 -0
  23. package/dist/legendre/legendre-fully-normalized.d.ts +52 -0
  24. package/dist/legendre/legendre-fully-normalized.d.ts.map +1 -0
  25. package/dist/legendre/legendre-fully-normalized.js +62 -0
  26. package/dist/legendre/legendre-fully-normalized.js.map +1 -0
  27. package/dist/legendre/legendre-index.d.ts +27 -0
  28. package/dist/legendre/legendre-index.d.ts.map +1 -0
  29. package/dist/legendre/legendre-index.js +31 -0
  30. package/dist/legendre/legendre-index.js.map +1 -0
  31. package/dist/legendre/legendre-schmidt.d.ts +37 -0
  32. package/dist/legendre/legendre-schmidt.d.ts.map +1 -0
  33. package/dist/legendre/legendre-schmidt.js +47 -0
  34. package/dist/legendre/legendre-schmidt.js.map +1 -0
  35. package/dist/ode/runge-kutta4.d.ts +46 -0
  36. package/dist/ode/runge-kutta4.d.ts.map +1 -0
  37. package/dist/ode/runge-kutta4.js +85 -0
  38. package/dist/ode/runge-kutta4.js.map +1 -0
  39. package/dist/optimize/_more-thuente.d.ts +95 -0
  40. package/dist/optimize/_more-thuente.d.ts.map +1 -0
  41. package/dist/optimize/_more-thuente.js +333 -0
  42. package/dist/optimize/_more-thuente.js.map +1 -0
  43. package/dist/optimize/_wolfe-line-search.d.ts +85 -0
  44. package/dist/optimize/_wolfe-line-search.d.ts.map +1 -0
  45. package/dist/optimize/_wolfe-line-search.js +193 -0
  46. package/dist/optimize/_wolfe-line-search.js.map +1 -0
  47. package/dist/optimize/bfgs.d.ts +262 -0
  48. package/dist/optimize/bfgs.d.ts.map +1 -0
  49. package/dist/optimize/bfgs.js +418 -0
  50. package/dist/optimize/bfgs.js.map +1 -0
  51. package/dist/optimize/lbfgs.d.ts +199 -0
  52. package/dist/optimize/lbfgs.d.ts.map +1 -0
  53. package/dist/optimize/lbfgs.js +383 -0
  54. package/dist/optimize/lbfgs.js.map +1 -0
  55. package/dist/optimize/levenberg-marquardt.d.ts +78 -0
  56. package/dist/optimize/levenberg-marquardt.d.ts.map +1 -0
  57. package/dist/optimize/levenberg-marquardt.js +204 -0
  58. package/dist/optimize/levenberg-marquardt.js.map +1 -0
  59. package/dist/optimize/nelder-mead.d.ts +68 -0
  60. package/dist/optimize/nelder-mead.d.ts.map +1 -0
  61. package/dist/optimize/nelder-mead.js +198 -0
  62. package/dist/optimize/nelder-mead.js.map +1 -0
  63. package/dist/quadrature/adaptive-quadrature.d.ts +53 -0
  64. package/dist/quadrature/adaptive-quadrature.d.ts.map +1 -0
  65. package/dist/quadrature/adaptive-quadrature.js +175 -0
  66. package/dist/quadrature/adaptive-quadrature.js.map +1 -0
  67. package/dist/quadrature/gauss-legendre.d.ts +27 -0
  68. package/dist/quadrature/gauss-legendre.d.ts.map +1 -0
  69. package/dist/quadrature/gauss-legendre.js +111 -0
  70. package/dist/quadrature/gauss-legendre.js.map +1 -0
  71. package/dist/quadrature/simpsons-rule.d.ts +27 -0
  72. package/dist/quadrature/simpsons-rule.d.ts.map +1 -0
  73. package/dist/quadrature/simpsons-rule.js +44 -0
  74. package/dist/quadrature/simpsons-rule.js.map +1 -0
  75. package/dist/roots/_brent-kernel.d.ts +38 -0
  76. package/dist/roots/_brent-kernel.d.ts.map +1 -0
  77. package/dist/roots/_brent-kernel.js +112 -0
  78. package/dist/roots/_brent-kernel.js.map +1 -0
  79. package/dist/roots/_grown.d.ts +7 -0
  80. package/dist/roots/_grown.d.ts.map +1 -0
  81. package/dist/roots/_grown.js +19 -0
  82. package/dist/roots/_grown.js.map +1 -0
  83. package/dist/roots/_level-search.d.ts +154 -0
  84. package/dist/roots/_level-search.d.ts.map +1 -0
  85. package/dist/roots/_level-search.js +556 -0
  86. package/dist/roots/_level-search.js.map +1 -0
  87. package/dist/roots/brent.d.ts +59 -0
  88. package/dist/roots/brent.d.ts.map +1 -0
  89. package/dist/roots/brent.js +115 -0
  90. package/dist/roots/brent.js.map +1 -0
  91. package/dist/roots/find-level-bands.d.ts +148 -0
  92. package/dist/roots/find-level-bands.d.ts.map +1 -0
  93. package/dist/roots/find-level-bands.js +351 -0
  94. package/dist/roots/find-level-bands.js.map +1 -0
  95. package/dist/roots/find-level-crossings.d.ts +143 -0
  96. package/dist/roots/find-level-crossings.d.ts.map +1 -0
  97. package/dist/roots/find-level-crossings.js +162 -0
  98. package/dist/roots/find-level-crossings.js.map +1 -0
  99. package/dist/roots/level-search-options.d.ts +56 -0
  100. package/dist/roots/level-search-options.d.ts.map +1 -0
  101. package/dist/roots/level-search-options.js +2 -0
  102. package/dist/roots/level-search-options.js.map +1 -0
  103. package/dist/roots/newton-raphson.d.ts +31 -0
  104. package/dist/roots/newton-raphson.d.ts.map +1 -0
  105. package/dist/roots/newton-raphson.js +69 -0
  106. package/dist/roots/newton-raphson.js.map +1 -0
  107. package/dist/series/sum-series.d.ts +43 -0
  108. package/dist/series/sum-series.d.ts.map +1 -0
  109. package/dist/series/sum-series.js +70 -0
  110. package/dist/series/sum-series.js.map +1 -0
  111. package/package.json +8 -5
@@ -0,0 +1,262 @@
1
+ import { type Callable, type WorkBudget } from "@ac-kit/core";
2
+ import { type Matrix } from "@ac-kit/math-linear";
3
+ /**
4
+ * The function {@link BfgsMinimizer} minimises: its value at `point`, and its
5
+ * gradient written into `gradient` (every entry, each call). Analytic
6
+ * gradients, or any the caller computes (automatic or finite differences).
7
+ *
8
+ * `point` is the minimiser's own array: read it, never write or keep it.
9
+ */
10
+ export type BfgsObjective = Callable<[
11
+ point: Float64Array,
12
+ gradient: Float64Array
13
+ ], number>;
14
+ /**
15
+ * Why a minimisation stopped. The first three are convergence; the others leave
16
+ * the best point found, whose quality the caller must judge.
17
+ *
18
+ * - `"gradient"`: `‖∇f‖∞ ≤ gradientTolerance`.
19
+ * - `"value"`: the decrease of the last step fell to `valueTolerance` relative.
20
+ * - `"step"`: the last step fell to `stepTolerance` relative.
21
+ * - `"max-iterations"`: `maxIterations` steps were taken first.
22
+ * - `"line-search"`: no step along the quasi-Newton direction, then along the
23
+ * steepest descent, lowered `f` — usually the precision floor of `f` near a
24
+ * minimum, sometimes a gradient inconsistent with `f`.
25
+ */
26
+ export type BfgsStatus = "gradient" | "value" | "step" | "max-iterations" | "line-search";
27
+ /**
28
+ * The stopping rules and line-search constants of a {@link BfgsMinimizer}, fixed
29
+ * when it is made.
30
+ */
31
+ export type BfgsOptions = {
32
+ /**
33
+ * Converged once `max |∂f/∂xᵢ| ≤ gradientTolerance` (an absolute test, in the
34
+ * units of `f` over those of `x`). Finite, non-negative; `1e-8` by default.
35
+ */
36
+ readonly gradientTolerance?: number;
37
+ /**
38
+ * Converged once a step lowers `f` by at most `valueTolerance · max(|f|, |f
39
+ * after|, 1)` (SciPy's `ftol` rule). Finite, non-negative; `0`, the default,
40
+ * disables the test.
41
+ */
42
+ readonly valueTolerance?: number;
43
+ /**
44
+ * Converged once a step moves no coordinate by more than `stepTolerance ·
45
+ * max(‖x‖∞, 1)`. Finite, non-negative; `0`, the default, disables the test.
46
+ */
47
+ readonly stepTolerance?: number;
48
+ /**
49
+ * Steps (accepted line searches) at most; a positive integer, 1000 by
50
+ * default.
51
+ */
52
+ readonly maxIterations?: number;
53
+ /**
54
+ * The sufficient-decrease constant `c₁` of the Wolfe conditions, `0 < c₁ <
55
+ * c₂`; `1e-4` by default.
56
+ */
57
+ readonly sufficientDecrease?: number;
58
+ /**
59
+ * The curvature constant `c₂` of the strong Wolfe conditions, `c₁ < c₂ < 1`;
60
+ * `0.9` by default (Nocedal and Wright's choice for quasi-Newton methods).
61
+ * Smaller values search each line more exactly.
62
+ */
63
+ readonly curvature?: number;
64
+ /**
65
+ * Evaluations one line search may use; a positive integer, 20 by default. A
66
+ * search that runs out keeps its best point if it lowered `f`.
67
+ */
68
+ readonly maxLineSearchEvaluations?: number;
69
+ };
70
+ /** What one {@link BfgsMinimizer.minimize} call may also be given. */
71
+ export type BfgsRunOptions = {
72
+ /**
73
+ * The starting inverse Hessian approximation, `dimension × dimension`,
74
+ * symmetric positive definite (only finiteness is checked; a matrix that is
75
+ * not positive definite is replaced, as described on the class), copied.
76
+ * Absent: the identity, rescaled after the first step by `yᵀs / yᵀy` (Nocedal
77
+ * and Wright, eq. 6.20). A previous run's {@link BfgsMinimizer.inverseHessian}
78
+ * warm-starts a related problem.
79
+ */
80
+ readonly initialInverseHessian?: Matrix | null;
81
+ /**
82
+ * Charged one unit per evaluation of the objective; what it throws
83
+ * propagates.
84
+ */
85
+ readonly budget?: WorkBudget;
86
+ /** Checked before every evaluation; aborting throws its reason. */
87
+ readonly signal?: AbortSignal | null;
88
+ };
89
+ /**
90
+ * Minimises a smooth function of `dimension` variables by the BFGS quasi-Newton
91
+ * method (Broyden, Fletcher, Goldfarb and Shanno, 1970) with a line search
92
+ * satisfying the strong Wolfe conditions (Moré and Thuente 1994, MINPACK-2's
93
+ * `dcsrch`): the method of SciPy's `minimize(method="BFGS")` and Optim.jl's
94
+ * `BFGS`, for problems of up to a few hundred variables.
95
+ *
96
+ * Make one per dimension and options, then call {@link minimize} as often as
97
+ * needed: after the constructor nothing is allocated (when the objective
98
+ * allocates nothing itself). The result is left in fields, read-only for
99
+ * callers: {@link value}, {@link gradient}, {@link inverseHessian},
100
+ * {@link iterations}, {@link evaluations}, {@link status}.
101
+ *
102
+ * **Method.** Each step moves along `d = −H·∇f` by a step length satisfying
103
+ * `f(x + αd) ≤ f(x) + c₁·α·∇fᵀd` and `|∇f(x + αd)ᵀd| ≤ c₂·|∇fᵀd|`, then updates
104
+ * the inverse Hessian approximation `H ← (I − ρsyᵀ)H(I − ρysᵀ) + ρssᵀ`, `ρ =
105
+ * 1/yᵀs`, which the curvature condition keeps positive definite. The update is
106
+ * skipped when `yᵀs ≤ ε·‖s‖·‖y‖` (rounding has lost the curvature). When `d` is
107
+ * not a descent direction (`H` lost definiteness to rounding, or was given
108
+ * indefinite), or a line search fails, `H` is reset to a scaled identity and
109
+ * the step retried along the steepest descent; a second failure stops with
110
+ * `"line-search"`. The first line search starts at `α = min(1, 1/‖d‖)`, the
111
+ * others at `α = 1`, where superlinear convergence takes full steps. Near a
112
+ * minimum, where `f` changes by less than its own rounding, a step is also
113
+ * accepted on Hager and Zhang's approximate Wolfe conditions (its value within
114
+ * 16 ulps of the start, `c₂·φ′(0) ≤ φ′(α) ≤ (2c₁ − 1)·φ′(0)`), so the gradient
115
+ * keeps converging past the precision of `f`; the reported value may then sit a
116
+ * few ulps above the lowest seen.
117
+ *
118
+ * **Values.** The start must give a finite value and gradient (else a
119
+ * `RangeError`). A non-finite value or gradient at a trial point — outside the
120
+ * function's domain, an overflow — makes the line search halve its step and
121
+ * stay below it, so a domain boundary is approached, never crossed. On every
122
+ * exit the reported point is the last accepted one (the start if none was),
123
+ * whose value and gradient are reported with it.
124
+ *
125
+ * **Complexity.** O(dimension²) time per step plus the evaluations (usually one
126
+ * or two a step near the minimum), O(dimension²) memory.
127
+ *
128
+ * @example
129
+ * ```ts
130
+ * // Rosenbrock's function, minimum 0 at (1, 1).
131
+ * const minimizer = new BfgsMinimizer(2);
132
+ * const point = minimizer.minimize(
133
+ * new Float64Array(2),
134
+ * (x, gradient) => {
135
+ * const a = 1 - x[0]!;
136
+ * const b = x[1]! - x[0]! * x[0]!;
137
+ * gradient[0] = -2 * a - 400 * x[0]! * b;
138
+ * gradient[1] = 200 * b;
139
+ * return a * a + 100 * b * b;
140
+ * },
141
+ * Float64Array.of(-1.2, 1),
142
+ * );
143
+ * // point ≈ [1, 1], minimizer.status === "gradient"
144
+ * ```;
145
+ */
146
+ export declare class BfgsMinimizer {
147
+ /** Number of variables. */
148
+ readonly dimension: number;
149
+ /**
150
+ * The gradient at the returned point, written by {@link minimize}. The
151
+ * minimiser's own array: read it, never write it.
152
+ */
153
+ readonly gradient: Float64Array;
154
+ /**
155
+ * The final inverse Hessian approximation, `dimension × dimension`, over the
156
+ * minimiser's own storage. Near a minimum it approximates `(∇²f)⁻¹`; a
157
+ * covariance from it is only as good as that approximation (exact Hessians
158
+ * give the covariance; this one is a by-product of the path taken).
159
+ */
160
+ readonly inverseHessian: Matrix;
161
+ /** `f` at the returned point. Read-only for callers. */
162
+ value: number;
163
+ /** Accepted steps of the last run. Read-only for callers. */
164
+ iterations: number;
165
+ /** Evaluations of the objective in the last run. Read-only for callers. */
166
+ evaluations: number;
167
+ /** Why the last run stopped. Read-only for callers. */
168
+ status: BfgsStatus;
169
+ private readonly gradientTolerance_;
170
+ private readonly valueTolerance_;
171
+ private readonly stepTolerance_;
172
+ private readonly maxIterations_;
173
+ private readonly line_;
174
+ private readonly hessian_;
175
+ private readonly point_;
176
+ private readonly direction_;
177
+ private readonly step_;
178
+ private readonly change_;
179
+ private readonly product_;
180
+ /** Numbers passed between methods through fields, never boxed arguments. */
181
+ private slope_;
182
+ private scale_;
183
+ private curvature_;
184
+ /**
185
+ * @throws {RangeError} When `dimension` is not a non-negative safe integer
186
+ * (or its square is not), or an option is out of its range: tolerances
187
+ * negative or not finite, `maxIterations` or `maxLineSearchEvaluations` not
188
+ * a positive integer, not `0 < sufficientDecrease < curvature < 1`.
189
+ */
190
+ constructor(dimension: number, options?: BfgsOptions);
191
+ /** Whether the last run stopped on one of the convergence tests. */
192
+ get converged(): boolean;
193
+ /**
194
+ * Minimises `objective` from `start`, writes the point reached into `out` and
195
+ * returns it; the other results are left in the minimiser's fields.
196
+ *
197
+ * @param out - The point reached, `dimension` numbers. May be `start`.
198
+ * @param objective - The function and its gradient; see
199
+ * {@link BfgsObjective}.
200
+ * @param start - The starting point, `dimension` numbers, only read.
201
+ * @param options - A starting inverse Hessian, a budget, a signal.
202
+ * @returns `out`.
203
+ * @throws {RangeError} When `out` or `start` does not hold `dimension`
204
+ * numbers, `initialInverseHessian` is not `dimension × dimension` and
205
+ * finite, or the objective's value or gradient at `start` is not finite.
206
+ * @throws The signal's reason once aborted, what the budget or the objective
207
+ * throws; the fields then hold the run so far.
208
+ */
209
+ minimize(out: Float64Array, objective: BfgsObjective, start: Float64Array, options?: BfgsRunOptions): Float64Array;
210
+ /** The iterations, from a finite start in `point_`, `gradient`, `value`. */
211
+ private run_;
212
+ /** `direction_ ← −H·gradient`, and `slope_ ← gradientᵀ·direction_`. */
213
+ private computeDirection_;
214
+ /** `H ← scale_·I`. */
215
+ private resetHessian_;
216
+ /**
217
+ * The inverse BFGS update from `step_` (s) and `change_` (y), `curvature_ =
218
+ * yᵀs > 0`: with `Hy` and `yᵀHy`, `H += ((1 + ρ·yᵀHy)·ssᵀ − Hy·sᵀ −
219
+ * s·(Hy)ᵀ)·ρ`.
220
+ */
221
+ private update_;
222
+ }
223
+ /** What {@link bfgs} returns: the fields of a {@link BfgsMinimizer} after a run. */
224
+ export type BfgsResult = {
225
+ /** The point reached. */
226
+ readonly point: Float64Array;
227
+ /** `f` there. */
228
+ readonly value: number;
229
+ /** `∇f` there. */
230
+ readonly gradient: Float64Array;
231
+ /** The final inverse Hessian approximation. */
232
+ readonly inverseHessian: Matrix;
233
+ /** Accepted steps. */
234
+ readonly iterations: number;
235
+ /** Evaluations of the objective. */
236
+ readonly evaluations: number;
237
+ /** Why it stopped. */
238
+ readonly status: BfgsStatus;
239
+ /** Whether `status` is one of the convergence tests. */
240
+ readonly converged: boolean;
241
+ };
242
+ /**
243
+ * Minimises `objective` from `start` with a new {@link BfgsMinimizer}: the
244
+ * one-shot form, which allocates the minimiser and its result. Reuse a
245
+ * minimiser for repeated fits.
246
+ *
247
+ * @example
248
+ * ```ts
249
+ * const result = bfgs(
250
+ * (x, gradient) => {
251
+ * gradient[0] = 2 * (x[0]! - 3);
252
+ * return (x[0]! - 3) ** 2;
253
+ * },
254
+ * Float64Array.of(0),
255
+ * );
256
+ * // result.point ≈ [3], result.converged === true
257
+ * ```;
258
+ *
259
+ * @throws {RangeError} As the constructor and {@link BfgsMinimizer.minimize}.
260
+ */
261
+ export declare function bfgs(objective: BfgsObjective, start: Float64Array, options?: BfgsOptions & BfgsRunOptions): BfgsResult;
262
+ //# sourceMappingURL=bfgs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bfgs.d.ts","sourceRoot":"","sources":["../../src/optimize/bfgs.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,KAAK,QAAQ,EAEb,KAAK,UAAU,EACf,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,KAAK,MAAM,EAAc,MAAM,qBAAqB,CAAC;AAS9D;;;;;;GAMG;AACH,MAAM,MAAM,aAAa,GAAG,QAAQ,CACnC;IAAC,KAAK,EAAE,YAAY;IAAE,QAAQ,EAAE,YAAY;CAAC,EAC7C,MAAM,CACN,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,UAAU,GACnB,UAAU,GACV,OAAO,GACP,MAAM,GACN,gBAAgB,GAChB,aAAa,CAAC;AAEjB;;;GAGG;AACH,MAAM,MAAM,WAAW,GAAG;IACz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Ac,EAAE,MAAM,CAAC;IAChC,sBAAsB;IACtB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,oCAAoC;IACpC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,sBAAsB;IACtB,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;IAC5B,wDAAwD;IACxD,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;CAC5B,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,IAAI,CACnB,SAAS,EAAE,aAAa,EACxB,KAAK,EAAE,YAAY,EACnB,OAAO,CAAC,EAAE,WAAW,GAAG,cAAc,GACpC,UAAU,CAmBZ"}
@@ -0,0 +1,418 @@
1
+ import { assertInteger, describeValue, } from "@ac-kit/core";
2
+ import { matrixView } from "@ac-kit/math-linear";
3
+ import { DEFAULT_GRADIENT_TOLERANCE_, DEFAULT_MAX_ITERATIONS_, nonNegativeOption_, WolfeLineSearch_, } from "./_wolfe-line-search.js";
4
+ /**
5
+ * Minimises a smooth function of `dimension` variables by the BFGS quasi-Newton
6
+ * method (Broyden, Fletcher, Goldfarb and Shanno, 1970) with a line search
7
+ * satisfying the strong Wolfe conditions (Moré and Thuente 1994, MINPACK-2's
8
+ * `dcsrch`): the method of SciPy's `minimize(method="BFGS")` and Optim.jl's
9
+ * `BFGS`, for problems of up to a few hundred variables.
10
+ *
11
+ * Make one per dimension and options, then call {@link minimize} as often as
12
+ * needed: after the constructor nothing is allocated (when the objective
13
+ * allocates nothing itself). The result is left in fields, read-only for
14
+ * callers: {@link value}, {@link gradient}, {@link inverseHessian},
15
+ * {@link iterations}, {@link evaluations}, {@link status}.
16
+ *
17
+ * **Method.** Each step moves along `d = −H·∇f` by a step length satisfying
18
+ * `f(x + αd) ≤ f(x) + c₁·α·∇fᵀd` and `|∇f(x + αd)ᵀd| ≤ c₂·|∇fᵀd|`, then updates
19
+ * the inverse Hessian approximation `H ← (I − ρsyᵀ)H(I − ρysᵀ) + ρssᵀ`, `ρ =
20
+ * 1/yᵀs`, which the curvature condition keeps positive definite. The update is
21
+ * skipped when `yᵀs ≤ ε·‖s‖·‖y‖` (rounding has lost the curvature). When `d` is
22
+ * not a descent direction (`H` lost definiteness to rounding, or was given
23
+ * indefinite), or a line search fails, `H` is reset to a scaled identity and
24
+ * the step retried along the steepest descent; a second failure stops with
25
+ * `"line-search"`. The first line search starts at `α = min(1, 1/‖d‖)`, the
26
+ * others at `α = 1`, where superlinear convergence takes full steps. Near a
27
+ * minimum, where `f` changes by less than its own rounding, a step is also
28
+ * accepted on Hager and Zhang's approximate Wolfe conditions (its value within
29
+ * 16 ulps of the start, `c₂·φ′(0) ≤ φ′(α) ≤ (2c₁ − 1)·φ′(0)`), so the gradient
30
+ * keeps converging past the precision of `f`; the reported value may then sit a
31
+ * few ulps above the lowest seen.
32
+ *
33
+ * **Values.** The start must give a finite value and gradient (else a
34
+ * `RangeError`). A non-finite value or gradient at a trial point — outside the
35
+ * function's domain, an overflow — makes the line search halve its step and
36
+ * stay below it, so a domain boundary is approached, never crossed. On every
37
+ * exit the reported point is the last accepted one (the start if none was),
38
+ * whose value and gradient are reported with it.
39
+ *
40
+ * **Complexity.** O(dimension²) time per step plus the evaluations (usually one
41
+ * or two a step near the minimum), O(dimension²) memory.
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * // Rosenbrock's function, minimum 0 at (1, 1).
46
+ * const minimizer = new BfgsMinimizer(2);
47
+ * const point = minimizer.minimize(
48
+ * new Float64Array(2),
49
+ * (x, gradient) => {
50
+ * const a = 1 - x[0]!;
51
+ * const b = x[1]! - x[0]! * x[0]!;
52
+ * gradient[0] = -2 * a - 400 * x[0]! * b;
53
+ * gradient[1] = 200 * b;
54
+ * return a * a + 100 * b * b;
55
+ * },
56
+ * Float64Array.of(-1.2, 1),
57
+ * );
58
+ * // point ≈ [1, 1], minimizer.status === "gradient"
59
+ * ```;
60
+ */
61
+ export class BfgsMinimizer {
62
+ /** Number of variables. */
63
+ dimension;
64
+ /**
65
+ * The gradient at the returned point, written by {@link minimize}. The
66
+ * minimiser's own array: read it, never write it.
67
+ */
68
+ gradient;
69
+ /**
70
+ * The final inverse Hessian approximation, `dimension × dimension`, over the
71
+ * minimiser's own storage. Near a minimum it approximates `(∇²f)⁻¹`; a
72
+ * covariance from it is only as good as that approximation (exact Hessians
73
+ * give the covariance; this one is a by-product of the path taken).
74
+ */
75
+ inverseHessian;
76
+ /** `f` at the returned point. Read-only for callers. */
77
+ value = 0.5;
78
+ /** Accepted steps of the last run. Read-only for callers. */
79
+ iterations = 0;
80
+ /** Evaluations of the objective in the last run. Read-only for callers. */
81
+ evaluations = 0;
82
+ /** Why the last run stopped. Read-only for callers. */
83
+ status = "max-iterations";
84
+ gradientTolerance_;
85
+ valueTolerance_;
86
+ stepTolerance_;
87
+ maxIterations_;
88
+ line_;
89
+ hessian_;
90
+ point_;
91
+ direction_;
92
+ step_;
93
+ change_;
94
+ product_;
95
+ /** Numbers passed between methods through fields, never boxed arguments. */
96
+ slope_ = 0.5;
97
+ scale_ = 0.5;
98
+ curvature_ = 0.5;
99
+ /**
100
+ * @throws {RangeError} When `dimension` is not a non-negative safe integer
101
+ * (or its square is not), or an option is out of its range: tolerances
102
+ * negative or not finite, `maxIterations` or `maxLineSearchEvaluations` not
103
+ * a positive integer, not `0 < sufficientDecrease < curvature < 1`.
104
+ */
105
+ constructor(dimension, options) {
106
+ assertInteger(dimension, "dimension", 0);
107
+ if (!Number.isSafeInteger(dimension * dimension)) {
108
+ throw new RangeError(`BfgsMinimizer: dimension ${dimension} is too large to allocate`);
109
+ }
110
+ this.gradientTolerance_ = nonNegativeOption_(options?.gradientTolerance, DEFAULT_GRADIENT_TOLERANCE_, "BfgsMinimizer", "gradientTolerance");
111
+ this.valueTolerance_ = nonNegativeOption_(options?.valueTolerance, 0, "BfgsMinimizer", "valueTolerance");
112
+ this.stepTolerance_ = nonNegativeOption_(options?.stepTolerance, 0, "BfgsMinimizer", "stepTolerance");
113
+ this.maxIterations_ = options?.maxIterations ?? DEFAULT_MAX_ITERATIONS_;
114
+ assertInteger(this.maxIterations_, "maxIterations", 1);
115
+ this.line_ = new WolfeLineSearch_(dimension, options, "BfgsMinimizer");
116
+ this.dimension = dimension;
117
+ this.hessian_ = new Float64Array(dimension * dimension);
118
+ this.inverseHessian = matrixView(this.hessian_, dimension, dimension);
119
+ this.gradient = new Float64Array(dimension);
120
+ this.point_ = new Float64Array(dimension);
121
+ this.direction_ = new Float64Array(dimension);
122
+ this.step_ = new Float64Array(dimension);
123
+ this.change_ = new Float64Array(dimension);
124
+ this.product_ = new Float64Array(dimension);
125
+ this.value = Number.NaN;
126
+ }
127
+ /** Whether the last run stopped on one of the convergence tests. */
128
+ get converged() {
129
+ const status = this.status;
130
+ return status === "gradient" || status === "value" || status === "step";
131
+ }
132
+ /**
133
+ * Minimises `objective` from `start`, writes the point reached into `out` and
134
+ * returns it; the other results are left in the minimiser's fields.
135
+ *
136
+ * @param out - The point reached, `dimension` numbers. May be `start`.
137
+ * @param objective - The function and its gradient; see
138
+ * {@link BfgsObjective}.
139
+ * @param start - The starting point, `dimension` numbers, only read.
140
+ * @param options - A starting inverse Hessian, a budget, a signal.
141
+ * @returns `out`.
142
+ * @throws {RangeError} When `out` or `start` does not hold `dimension`
143
+ * numbers, `initialInverseHessian` is not `dimension × dimension` and
144
+ * finite, or the objective's value or gradient at `start` is not finite.
145
+ * @throws The signal's reason once aborted, what the budget or the objective
146
+ * throws; the fields then hold the run so far.
147
+ */
148
+ minimize(out, objective, start, options) {
149
+ const dimension = this.dimension;
150
+ if (out.length !== dimension || start.length !== dimension) {
151
+ throw new RangeError(`BfgsMinimizer.minimize: out and start need ${dimension} numbers, got ${out.length} and ${start.length}`);
152
+ }
153
+ const initial = options?.initialInverseHessian ?? null;
154
+ const hessian = this.hessian_;
155
+ if (initial !== null) {
156
+ if (initial.rows !== dimension ||
157
+ initial.columns !== dimension ||
158
+ initial.data.length !== dimension * dimension) {
159
+ throw new RangeError(`BfgsMinimizer.minimize: initialInverseHessian must be ${dimension} × ${dimension}, got ${initial.rows} × ${initial.columns}`);
160
+ }
161
+ for (let index = 0; index < initial.data.length; index++) {
162
+ if (!Number.isFinite(initial.data[index])) {
163
+ throw new RangeError("BfgsMinimizer.minimize: initialInverseHessian must be finite");
164
+ }
165
+ }
166
+ }
167
+ const point = this.point_;
168
+ const gradient = this.gradient;
169
+ const line = this.line_;
170
+ point.set(start);
171
+ line.begin(objective, options?.budget, options?.signal);
172
+ this.iterations = 0;
173
+ this.evaluations = 0;
174
+ this.status = "max-iterations";
175
+ try {
176
+ line.evaluate(point, gradient);
177
+ this.value = line.value;
178
+ if (!line.finiteAt(gradient)) {
179
+ throw new RangeError(`BfgsMinimizer.minimize: the objective or its gradient is not finite at the start, value ${describeValue(this.value)}`);
180
+ }
181
+ if (initial === null) {
182
+ this.scale_ = 1;
183
+ this.resetHessian_();
184
+ }
185
+ else {
186
+ hessian.set(initial.data);
187
+ }
188
+ this.run_(initial === null);
189
+ }
190
+ finally {
191
+ this.evaluations = line.evaluations;
192
+ line.end();
193
+ out.set(point);
194
+ }
195
+ return out;
196
+ }
197
+ /** The iterations, from a finite start in `point_`, `gradient`, `value`. */
198
+ run_(scaleOnFirstStep) {
199
+ const dimension = this.dimension;
200
+ const point = this.point_;
201
+ const gradient = this.gradient;
202
+ const direction = this.direction_;
203
+ const line = this.line_;
204
+ const trial = line.trial;
205
+ const trialGradient = line.trialGradient;
206
+ const step = this.step_;
207
+ const change = this.change_;
208
+ let scalePending = scaleOnFirstStep;
209
+ let identity = scaleOnFirstStep;
210
+ this.scale_ = 1;
211
+ for (;;) {
212
+ let largestGradient = 0;
213
+ for (let index = 0; index < dimension; index++) {
214
+ const magnitude = Math.abs(gradient[index]);
215
+ if (magnitude > largestGradient) {
216
+ largestGradient = magnitude;
217
+ }
218
+ }
219
+ if (largestGradient <= this.gradientTolerance_) {
220
+ this.status = "gradient";
221
+ return;
222
+ }
223
+ if (this.iterations >= this.maxIterations_) {
224
+ this.status = "max-iterations";
225
+ return;
226
+ }
227
+ this.computeDirection_();
228
+ if (!(this.slope_ < 0)) {
229
+ this.resetHessian_();
230
+ identity = true;
231
+ this.computeDirection_();
232
+ }
233
+ // The first step of an unscaled identity is the steepest descent at
234
+ // its raw length: start the search at a unit step length instead.
235
+ let directionNorm = 0;
236
+ for (let index = 0; index < dimension; index++) {
237
+ const value = direction[index];
238
+ directionNorm += value * value;
239
+ }
240
+ directionNorm = Math.sqrt(directionNorm);
241
+ line.engine.stp =
242
+ scalePending && directionNorm > 1 ? 1 / directionNorm : 1;
243
+ line.startValue = this.value;
244
+ line.slope = this.slope_;
245
+ if (!line.search(point, direction)) {
246
+ if (identity) {
247
+ this.status = "line-search";
248
+ return;
249
+ }
250
+ this.resetHessian_();
251
+ identity = true;
252
+ continue;
253
+ }
254
+ // The accepted point is in the line search's trial buffers and value.
255
+ let largestStep = 0;
256
+ let largestPoint = 0;
257
+ let curvature = 0;
258
+ let stepNorm = 0;
259
+ let changeNorm = 0;
260
+ for (let index = 0; index < dimension; index++) {
261
+ const s = trial[index] - point[index];
262
+ const y = trialGradient[index] - gradient[index];
263
+ const magnitude = Math.abs(trial[index]);
264
+ step[index] = s;
265
+ change[index] = y;
266
+ curvature += s * y;
267
+ stepNorm += s * s;
268
+ changeNorm += y * y;
269
+ if (Math.abs(s) > largestStep) {
270
+ largestStep = Math.abs(s);
271
+ }
272
+ if (magnitude > largestPoint) {
273
+ largestPoint = magnitude;
274
+ }
275
+ }
276
+ const previous = this.value;
277
+ const next = line.value;
278
+ point.set(trial);
279
+ gradient.set(trialGradient);
280
+ this.value = next;
281
+ this.iterations++;
282
+ if (curvature >
283
+ Number.EPSILON * Math.sqrt(stepNorm) * Math.sqrt(changeNorm)) {
284
+ if (scalePending) {
285
+ this.scale_ = curvature / changeNorm;
286
+ this.resetHessian_();
287
+ scalePending = false;
288
+ }
289
+ else if (identity) {
290
+ this.scale_ = curvature / changeNorm;
291
+ }
292
+ this.curvature_ = curvature;
293
+ this.update_();
294
+ identity = false;
295
+ }
296
+ if (this.valueTolerance_ > 0) {
297
+ let reference = Math.abs(previous);
298
+ if (Math.abs(next) > reference) {
299
+ reference = Math.abs(next);
300
+ }
301
+ if (reference < 1) {
302
+ reference = 1;
303
+ }
304
+ if (previous - next <= this.valueTolerance_ * reference) {
305
+ this.status = "value";
306
+ return;
307
+ }
308
+ }
309
+ if (this.stepTolerance_ > 0 &&
310
+ largestStep <=
311
+ this.stepTolerance_ * (largestPoint > 1 ? largestPoint : 1)) {
312
+ this.status = "step";
313
+ return;
314
+ }
315
+ }
316
+ }
317
+ /** `direction_ ← −H·gradient`, and `slope_ ← gradientᵀ·direction_`. */
318
+ computeDirection_() {
319
+ const dimension = this.dimension;
320
+ const hessian = this.hessian_;
321
+ const gradient = this.gradient;
322
+ const direction = this.direction_;
323
+ let slope = 0;
324
+ direction.fill(0);
325
+ for (let column = 0; column < dimension; column++) {
326
+ const factor = gradient[column];
327
+ const offset = dimension * column;
328
+ for (let row = 0; row < dimension; row++) {
329
+ direction[row] = direction[row] - hessian[offset + row] * factor;
330
+ }
331
+ }
332
+ for (let index = 0; index < dimension; index++) {
333
+ slope += direction[index] * gradient[index];
334
+ }
335
+ this.slope_ = slope;
336
+ }
337
+ /** `H ← scale_·I`. */
338
+ resetHessian_() {
339
+ const dimension = this.dimension;
340
+ const hessian = this.hessian_;
341
+ const scale = this.scale_;
342
+ hessian.fill(0);
343
+ for (let index = 0; index < dimension; index++) {
344
+ hessian[(dimension + 1) * index] = scale;
345
+ }
346
+ }
347
+ /**
348
+ * The inverse BFGS update from `step_` (s) and `change_` (y), `curvature_ =
349
+ * yᵀs > 0`: with `Hy` and `yᵀHy`, `H += ((1 + ρ·yᵀHy)·ssᵀ − Hy·sᵀ −
350
+ * s·(Hy)ᵀ)·ρ`.
351
+ */
352
+ update_() {
353
+ const dimension = this.dimension;
354
+ const hessian = this.hessian_;
355
+ const s = this.step_;
356
+ const y = this.change_;
357
+ const hy = this.product_;
358
+ const rho = 1 / this.curvature_;
359
+ let yhy = 0;
360
+ hy.fill(0);
361
+ for (let column = 0; column < dimension; column++) {
362
+ const factor = y[column];
363
+ const offset = dimension * column;
364
+ for (let row = 0; row < dimension; row++) {
365
+ hy[row] = hy[row] + hessian[offset + row] * factor;
366
+ }
367
+ }
368
+ for (let index = 0; index < dimension; index++) {
369
+ yhy += y[index] * hy[index];
370
+ }
371
+ const outer = (1 + rho * yhy) * rho;
372
+ for (let column = 0; column < dimension; column++) {
373
+ const offset = dimension * column;
374
+ const sColumn = s[column];
375
+ const hyColumn = hy[column];
376
+ for (let row = 0; row < dimension; row++) {
377
+ hessian[offset + row] =
378
+ hessian[offset + row] +
379
+ outer * s[row] * sColumn -
380
+ rho * (hy[row] * sColumn + s[row] * hyColumn);
381
+ }
382
+ }
383
+ }
384
+ }
385
+ /**
386
+ * Minimises `objective` from `start` with a new {@link BfgsMinimizer}: the
387
+ * one-shot form, which allocates the minimiser and its result. Reuse a
388
+ * minimiser for repeated fits.
389
+ *
390
+ * @example
391
+ * ```ts
392
+ * const result = bfgs(
393
+ * (x, gradient) => {
394
+ * gradient[0] = 2 * (x[0]! - 3);
395
+ * return (x[0]! - 3) ** 2;
396
+ * },
397
+ * Float64Array.of(0),
398
+ * );
399
+ * // result.point ≈ [3], result.converged === true
400
+ * ```;
401
+ *
402
+ * @throws {RangeError} As the constructor and {@link BfgsMinimizer.minimize}.
403
+ */
404
+ export function bfgs(objective, start, options) {
405
+ const minimizer = new BfgsMinimizer(start.length, options);
406
+ const point = minimizer.minimize(new Float64Array(start.length), objective, start, options);
407
+ return {
408
+ point,
409
+ value: minimizer.value,
410
+ gradient: minimizer.gradient,
411
+ inverseHessian: minimizer.inverseHessian,
412
+ iterations: minimizer.iterations,
413
+ evaluations: minimizer.evaluations,
414
+ status: minimizer.status,
415
+ converged: minimizer.converged,
416
+ };
417
+ }
418
+ //# sourceMappingURL=bfgs.js.map