@tangent.to/opt 0.1.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.
- package/LICENSE +21 -0
- package/README.md +138 -0
- package/THIRD_PARTY_NOTICES.md +37 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +7 -0
- package/package.json +60 -0
- package/src/blas1.js +56 -0
- package/src/bounds.js +187 -0
- package/src/compat.js +148 -0
- package/src/evaluate.js +66 -0
- package/src/gradient.js +236 -0
- package/src/index.js +67 -0
- package/src/lbfgs.js +176 -0
- package/src/leastsq.js +418 -0
- package/src/linesearch.js +134 -0
- package/src/linsolve.js +99 -0
- package/src/minimize.js +97 -0
- package/src/neldermead.js +192 -0
- package/src/numdiff.js +112 -0
- package/src/scalar.js +623 -0
package/src/leastsq.js
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Nonlinear least squares: Levenberg-Marquardt and a curve_fit-style wrapper.
|
|
3
|
+
*
|
|
4
|
+
* The cost is 0.5 * sum(r(p)^2). Each iteration solves the Marquardt-damped
|
|
5
|
+
* normal equations
|
|
6
|
+
*
|
|
7
|
+
* (J^T J + lambda * diag(J^T J)) delta = -J^T r
|
|
8
|
+
*
|
|
9
|
+
* accepting steps that reduce the cost (lambda /= lambdaDown) and rejecting
|
|
10
|
+
* the rest (lambda *= lambdaUp, retry). Non-finite trial residuals are
|
|
11
|
+
* treated as rejected steps, never as errors.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { solve } from './linsolve.js';
|
|
15
|
+
import { makeBoundsTransform, wrapResiduals } from './bounds.js';
|
|
16
|
+
|
|
17
|
+
const FD_STEP = 1e-6;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Robust loss functions, scipy.optimize.least_squares-compatible:
|
|
21
|
+
* cost = 0.5 * fScale^2 * sum(rho(z_i)) with z_i = (r_i / fScale)^2.
|
|
22
|
+
* drho is rho'(z), used as the IRLS weight in the normal equations.
|
|
23
|
+
*/
|
|
24
|
+
const LOSSES = {
|
|
25
|
+
linear: null,
|
|
26
|
+
huber: {
|
|
27
|
+
rho: (z) => (z <= 1 ? z : 2 * Math.sqrt(z) - 1),
|
|
28
|
+
drho: (z) => (z <= 1 ? 1 : 1 / Math.sqrt(z)),
|
|
29
|
+
},
|
|
30
|
+
soft_l1: {
|
|
31
|
+
rho: (z) => 2 * (Math.sqrt(1 + z) - 1),
|
|
32
|
+
drho: (z) => 1 / Math.sqrt(1 + z),
|
|
33
|
+
},
|
|
34
|
+
cauchy: {
|
|
35
|
+
rho: (z) => Math.log1p(z),
|
|
36
|
+
drho: (z) => 1 / (1 + z),
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Central finite-difference Jacobian of a residual function.
|
|
42
|
+
* Step per component: h = FD_STEP * max(1, |p_i|).
|
|
43
|
+
*
|
|
44
|
+
* @param {Function} residuals - (p) => Array<number> of length m
|
|
45
|
+
* @param {Array<number>} p - Point of length n
|
|
46
|
+
* @param {number} m - Number of residuals
|
|
47
|
+
* @returns {Array<Array<number>>} m-by-n Jacobian
|
|
48
|
+
*/
|
|
49
|
+
function fdJacobian(residuals, p, m) {
|
|
50
|
+
const n = p.length;
|
|
51
|
+
const J = new Array(m);
|
|
52
|
+
for (let j = 0; j < m; j++) {
|
|
53
|
+
J[j] = new Array(n);
|
|
54
|
+
}
|
|
55
|
+
const pi = p.slice();
|
|
56
|
+
for (let i = 0; i < n; i++) {
|
|
57
|
+
const h = FD_STEP * Math.max(1, Math.abs(p[i]));
|
|
58
|
+
pi[i] = p[i] + h;
|
|
59
|
+
const rPlus = residuals(pi);
|
|
60
|
+
pi[i] = p[i] - h;
|
|
61
|
+
const rMinus = residuals(pi);
|
|
62
|
+
pi[i] = p[i];
|
|
63
|
+
for (let j = 0; j < m; j++) {
|
|
64
|
+
J[j][i] = (rPlus[j] - rMinus[j]) / (2 * h);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return J;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Cost 0.5 * sum(r^2); NaN if any residual is non-finite. */
|
|
71
|
+
function halfSumSquares(r) {
|
|
72
|
+
let sum = 0;
|
|
73
|
+
for (let j = 0; j < r.length; j++) {
|
|
74
|
+
sum += r[j] * r[j];
|
|
75
|
+
}
|
|
76
|
+
return 0.5 * sum;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Robust cost 0.5 * fScale^2 * sum(rho((r/fScale)^2)); reduces to
|
|
81
|
+
* halfSumSquares for the linear loss. NaN if any residual is non-finite.
|
|
82
|
+
*/
|
|
83
|
+
function robustCost(r, lossFn, fScale) {
|
|
84
|
+
if (!lossFn) return halfSumSquares(r);
|
|
85
|
+
let sum = 0;
|
|
86
|
+
const s2 = fScale * fScale;
|
|
87
|
+
for (let j = 0; j < r.length; j++) {
|
|
88
|
+
sum += lossFn.rho((r[j] * r[j]) / s2);
|
|
89
|
+
}
|
|
90
|
+
return 0.5 * s2 * sum;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Per-residual IRLS weights rho'((r/fScale)^2), or null for the linear loss. */
|
|
94
|
+
function robustWeights(r, lossFn, fScale) {
|
|
95
|
+
if (!lossFn) return null;
|
|
96
|
+
const w = new Array(r.length);
|
|
97
|
+
const s2 = fScale * fScale;
|
|
98
|
+
for (let j = 0; j < r.length; j++) {
|
|
99
|
+
w[j] = lossFn.drho((r[j] * r[j]) / s2);
|
|
100
|
+
}
|
|
101
|
+
return w;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Form the (optionally IRLS-weighted) normal-equation pieces
|
|
106
|
+
* J^T W J (n-by-n) and g = J^T W r (length n), W = diag(w).
|
|
107
|
+
* With w = null this is plain J^T J and J^T r; with robust weights, g is
|
|
108
|
+
* exactly the gradient of the robust cost, so the gTol test stays valid.
|
|
109
|
+
*
|
|
110
|
+
* @param {Array<Array<number>>} J - m-by-n Jacobian
|
|
111
|
+
* @param {Array<number>} r - Residuals of length m
|
|
112
|
+
* @param {Array<number>|null} [w] - Per-residual weights
|
|
113
|
+
* @returns {{JTJ: Array<Array<number>>, g: Array<number>}}
|
|
114
|
+
*/
|
|
115
|
+
function normalEquations(J, r, w = null) {
|
|
116
|
+
const m = J.length;
|
|
117
|
+
const n = J[0].length;
|
|
118
|
+
const JTJ = new Array(n);
|
|
119
|
+
const g = new Array(n).fill(0);
|
|
120
|
+
for (let i = 0; i < n; i++) {
|
|
121
|
+
JTJ[i] = new Array(n).fill(0);
|
|
122
|
+
}
|
|
123
|
+
for (let k = 0; k < m; k++) {
|
|
124
|
+
const row = J[k];
|
|
125
|
+
const wk = w === null ? 1 : w[k];
|
|
126
|
+
for (let i = 0; i < n; i++) {
|
|
127
|
+
g[i] += wk * row[i] * r[k];
|
|
128
|
+
for (let j = i; j < n; j++) {
|
|
129
|
+
JTJ[i][j] += wk * row[i] * row[j];
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
for (let i = 0; i < n; i++) {
|
|
134
|
+
for (let j = 0; j < i; j++) {
|
|
135
|
+
JTJ[i][j] = JTJ[j][i];
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return { JTJ, g };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Minimize 0.5 * sum(r(p)^2) with Levenberg-Marquardt.
|
|
143
|
+
*
|
|
144
|
+
* @param {Object} spec
|
|
145
|
+
* @param {Function} spec.residuals - (p) => Array<number> of length m
|
|
146
|
+
* @param {Array<number>} spec.x0 - Initial parameters of length n
|
|
147
|
+
* @param {Function} [spec.jacobian] - (p) => m-by-n Array<Array<number>>;
|
|
148
|
+
* central finite differences on the residuals otherwise
|
|
149
|
+
* @param {number} [spec.maxIter=200] - Maximum accepted iterations
|
|
150
|
+
* @param {number} [spec.fTol=1e-10] - Relative cost reduction on an accepted step
|
|
151
|
+
* @param {number} [spec.xTol=1e-10] - Max relative step component on an accepted step
|
|
152
|
+
* @param {number} [spec.gTol=1e-10] - Inf-norm of the gradient J^T r
|
|
153
|
+
* @param {number} [spec.lambda0=1e-3] - Initial damping
|
|
154
|
+
* @param {number} [spec.lambdaUp=10] - Damping increase factor on rejection
|
|
155
|
+
* @param {number} [spec.lambdaDown=10] - Damping decrease factor on acceptance
|
|
156
|
+
* @param {string} [spec.loss='linear'] - 'linear' | 'huber' | 'soft_l1' | 'cauchy';
|
|
157
|
+
* robust losses down-weight outliers (IRLS, scipy least_squares semantics)
|
|
158
|
+
* @param {number} [spec.fScale=1] - Residual scale at which the robust losses
|
|
159
|
+
* start to flatten (scipy's f_scale)
|
|
160
|
+
* @param {Array<Array<number|null>>} [spec.bounds] - Per-parameter [lo, hi] box
|
|
161
|
+
* bounds (MINUIT transform; null/±Infinity for unbounded sides)
|
|
162
|
+
* @param {boolean} [spec.history=false] - Record {cost, lambda} per accepted iteration
|
|
163
|
+
* @returns {Object} {x, fx, residuals, iterations, fevals, converged, history?}
|
|
164
|
+
*/
|
|
165
|
+
export function leastSquares(spec = {}) {
|
|
166
|
+
const {
|
|
167
|
+
residuals,
|
|
168
|
+
jacobian,
|
|
169
|
+
x0,
|
|
170
|
+
maxIter = 200,
|
|
171
|
+
fTol = 1e-10,
|
|
172
|
+
xTol = 1e-10,
|
|
173
|
+
gTol = 1e-10,
|
|
174
|
+
lambda0 = 1e-3,
|
|
175
|
+
lambdaUp = 10,
|
|
176
|
+
lambdaDown = 10,
|
|
177
|
+
loss = 'linear',
|
|
178
|
+
fScale = 1,
|
|
179
|
+
bounds,
|
|
180
|
+
history: trackHistory = false,
|
|
181
|
+
} = spec;
|
|
182
|
+
|
|
183
|
+
if (typeof residuals !== 'function') {
|
|
184
|
+
throw new Error('leastSquares: spec.residuals must be a function');
|
|
185
|
+
}
|
|
186
|
+
if (!Array.isArray(x0) || x0.length === 0 || x0.some((v) => typeof v !== 'number')) {
|
|
187
|
+
throw new Error('leastSquares: spec.x0 must be a non-empty array of numbers');
|
|
188
|
+
}
|
|
189
|
+
if (!(loss in LOSSES)) {
|
|
190
|
+
throw new Error(
|
|
191
|
+
`leastSquares: unknown loss '${loss}'. Available: ${Object.keys(LOSSES).join(', ')}`,
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
const lossFn = LOSSES[loss];
|
|
195
|
+
|
|
196
|
+
// Box bounds: solve in MINUIT-transformed internal space, report externally.
|
|
197
|
+
const T = bounds ? makeBoundsTransform(bounds, x0.length) : null;
|
|
198
|
+
if (T) {
|
|
199
|
+
const wrapped = wrapResiduals(residuals, jacobian, T);
|
|
200
|
+
const inner = leastSquares({
|
|
201
|
+
...spec,
|
|
202
|
+
bounds: undefined,
|
|
203
|
+
residuals: wrapped.residuals,
|
|
204
|
+
jacobian: wrapped.jacobian,
|
|
205
|
+
x0: T.toInternal(x0),
|
|
206
|
+
});
|
|
207
|
+
return { ...inner, x: T.toExternal(inner.x), bounded: true };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const n = x0.length;
|
|
211
|
+
let fevals = 0;
|
|
212
|
+
const evalResiduals = (p) => {
|
|
213
|
+
fevals++;
|
|
214
|
+
return residuals(p);
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
let x = x0.slice();
|
|
218
|
+
let r = evalResiduals(x);
|
|
219
|
+
if (!Array.isArray(r) || r.length === 0) {
|
|
220
|
+
throw new Error('leastSquares: residuals must return a non-empty array of numbers');
|
|
221
|
+
}
|
|
222
|
+
const m = r.length;
|
|
223
|
+
let cost = robustCost(r, lossFn, fScale);
|
|
224
|
+
if (!Number.isFinite(cost)) {
|
|
225
|
+
throw new Error('leastSquares: residuals are not finite at x0');
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const evalJacobian = jacobian
|
|
229
|
+
? (p) => jacobian(p)
|
|
230
|
+
: (p) => fdJacobian(evalResiduals, p, m);
|
|
231
|
+
|
|
232
|
+
let lambda = lambda0;
|
|
233
|
+
let converged = false;
|
|
234
|
+
const history = trackHistory ? [] : null;
|
|
235
|
+
let iteration = 0;
|
|
236
|
+
|
|
237
|
+
outer:
|
|
238
|
+
while (iteration < maxIter) {
|
|
239
|
+
const J = evalJacobian(x);
|
|
240
|
+
const { JTJ, g } = normalEquations(J, r, robustWeights(r, lossFn, fScale));
|
|
241
|
+
|
|
242
|
+
let gMax = 0;
|
|
243
|
+
for (let i = 0; i < n; i++) {
|
|
244
|
+
gMax = Math.max(gMax, Math.abs(g[i]));
|
|
245
|
+
}
|
|
246
|
+
if (gMax < gTol) {
|
|
247
|
+
converged = true;
|
|
248
|
+
break;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// Inner loop: retry with increased damping until a step is accepted
|
|
252
|
+
// or the damping safeguard trips.
|
|
253
|
+
for (;;) {
|
|
254
|
+
// A = J^T J + lambda * diag(J^T J); a zero diagonal entry gets
|
|
255
|
+
// lambda itself so the damped system is never singular.
|
|
256
|
+
const A = new Array(n);
|
|
257
|
+
for (let i = 0; i < n; i++) {
|
|
258
|
+
A[i] = JTJ[i].slice();
|
|
259
|
+
A[i][i] = JTJ[i][i] !== 0 ? JTJ[i][i] * (1 + lambda) : lambda;
|
|
260
|
+
}
|
|
261
|
+
const rhs = new Array(n);
|
|
262
|
+
for (let i = 0; i < n; i++) {
|
|
263
|
+
rhs[i] = -g[i];
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
let delta = null;
|
|
267
|
+
try {
|
|
268
|
+
delta = solve(A, rhs);
|
|
269
|
+
} catch {
|
|
270
|
+
// Degenerate damped system: treat as a rejected step.
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
let trialCost = NaN;
|
|
274
|
+
let xTrial = null;
|
|
275
|
+
let rTrial = null;
|
|
276
|
+
if (delta !== null) {
|
|
277
|
+
xTrial = new Array(n);
|
|
278
|
+
for (let i = 0; i < n; i++) {
|
|
279
|
+
xTrial[i] = x[i] + delta[i];
|
|
280
|
+
}
|
|
281
|
+
rTrial = evalResiduals(xTrial);
|
|
282
|
+
trialCost = robustCost(rTrial, lossFn, fScale);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
if (Number.isFinite(trialCost) && trialCost < cost) {
|
|
286
|
+
// Accepted step.
|
|
287
|
+
const costReduction = (cost - trialCost) / cost;
|
|
288
|
+
let maxRelStep = 0;
|
|
289
|
+
for (let i = 0; i < n; i++) {
|
|
290
|
+
maxRelStep = Math.max(maxRelStep, Math.abs(delta[i]) / Math.max(1, Math.abs(x[i])));
|
|
291
|
+
}
|
|
292
|
+
x = xTrial;
|
|
293
|
+
r = rTrial;
|
|
294
|
+
cost = trialCost;
|
|
295
|
+
iteration++;
|
|
296
|
+
if (trackHistory) {
|
|
297
|
+
history.push({ cost, lambda });
|
|
298
|
+
}
|
|
299
|
+
lambda = Math.max(lambda / lambdaDown, 1e-12);
|
|
300
|
+
if (costReduction < fTol || maxRelStep < xTol) {
|
|
301
|
+
converged = true;
|
|
302
|
+
break outer;
|
|
303
|
+
}
|
|
304
|
+
break;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// Rejected step (cost increase, or NaN/Infinity residuals).
|
|
308
|
+
lambda *= lambdaUp;
|
|
309
|
+
if (lambda > 1e12) {
|
|
310
|
+
break outer;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const result = {
|
|
316
|
+
x,
|
|
317
|
+
fx: cost,
|
|
318
|
+
residuals: r.slice(),
|
|
319
|
+
iterations: iteration,
|
|
320
|
+
fevals,
|
|
321
|
+
converged,
|
|
322
|
+
};
|
|
323
|
+
if (trackHistory) {
|
|
324
|
+
result.history = history;
|
|
325
|
+
}
|
|
326
|
+
return result;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Fit a scalar model to (x, y) data, scipy.optimize.curve_fit style.
|
|
331
|
+
*
|
|
332
|
+
* @param {Object} spec
|
|
333
|
+
* @param {Function} spec.model - (x, params) => number for a scalar datum x
|
|
334
|
+
* @param {Array<number>} spec.x - Independent data
|
|
335
|
+
* @param {Array<number>} spec.y - Dependent data, same length as x
|
|
336
|
+
* @param {Array<number>} spec.p0 - Initial parameters
|
|
337
|
+
* @param {...*} [spec.options] - Remaining keys are passed to leastSquares
|
|
338
|
+
* (jacobian, maxIter, fTol, xTol, gTol, lambda0, lambdaUp, lambdaDown, history)
|
|
339
|
+
* @returns {Object} {params, cov, stdErr, fx, iterations, converged}
|
|
340
|
+
*/
|
|
341
|
+
export function curveFit(spec = {}) {
|
|
342
|
+
const { model, x, y, p0, ...options } = spec;
|
|
343
|
+
|
|
344
|
+
if (typeof model !== 'function') {
|
|
345
|
+
throw new Error('curveFit: spec.model must be a function');
|
|
346
|
+
}
|
|
347
|
+
if (!Array.isArray(x) || !Array.isArray(y)) {
|
|
348
|
+
throw new Error('curveFit: spec.x and spec.y must be arrays of numbers');
|
|
349
|
+
}
|
|
350
|
+
if (x.length !== y.length) {
|
|
351
|
+
throw new Error(
|
|
352
|
+
`curveFit: x and y must have the same length (got ${x.length} and ${y.length})`,
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
if (!Array.isArray(p0) || p0.length === 0 || p0.some((v) => typeof v !== 'number')) {
|
|
356
|
+
throw new Error('curveFit: spec.p0 must be a non-empty array of numbers');
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
const m = x.length;
|
|
360
|
+
const residuals = (p) => {
|
|
361
|
+
const r = new Array(m);
|
|
362
|
+
for (let i = 0; i < m; i++) {
|
|
363
|
+
r[i] = y[i] - model(x[i], p);
|
|
364
|
+
}
|
|
365
|
+
return r;
|
|
366
|
+
};
|
|
367
|
+
|
|
368
|
+
const result = leastSquares({ residuals, x0: p0, ...options });
|
|
369
|
+
|
|
370
|
+
// Covariance estimate: cov = inv(J^T J) * s^2 with s^2 = 2*fx / (m - n),
|
|
371
|
+
// solved column-by-column against the identity. Singular or
|
|
372
|
+
// under-determined systems yield NaN entries instead of throwing.
|
|
373
|
+
// The Gaussian formula is only valid for the linear loss; robust fits
|
|
374
|
+
// report NaN (a sandwich estimator may be added later).
|
|
375
|
+
const n = p0.length;
|
|
376
|
+
const cov = new Array(n);
|
|
377
|
+
const stdErr = new Array(n);
|
|
378
|
+
let filled = false;
|
|
379
|
+
const gaussian = !options.loss || options.loss === 'linear';
|
|
380
|
+
if (m > n && gaussian) {
|
|
381
|
+
const J = options.jacobian ? options.jacobian(result.x) : fdJacobian(residuals, result.x, m);
|
|
382
|
+
const { JTJ } = normalEquations(J, result.residuals);
|
|
383
|
+
const s2 = (2 * result.fx) / (m - n);
|
|
384
|
+
try {
|
|
385
|
+
const columns = new Array(n);
|
|
386
|
+
for (let j = 0; j < n; j++) {
|
|
387
|
+
const e = new Array(n).fill(0);
|
|
388
|
+
e[j] = 1;
|
|
389
|
+
columns[j] = solve(JTJ, e);
|
|
390
|
+
}
|
|
391
|
+
for (let i = 0; i < n; i++) {
|
|
392
|
+
cov[i] = new Array(n);
|
|
393
|
+
for (let j = 0; j < n; j++) {
|
|
394
|
+
cov[i][j] = columns[j][i] * s2;
|
|
395
|
+
}
|
|
396
|
+
stdErr[i] = Math.sqrt(cov[i][i]);
|
|
397
|
+
}
|
|
398
|
+
filled = true;
|
|
399
|
+
} catch {
|
|
400
|
+
// Singular J^T J: fall through to the NaN fill.
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
if (!filled) {
|
|
404
|
+
for (let i = 0; i < n; i++) {
|
|
405
|
+
cov[i] = new Array(n).fill(NaN);
|
|
406
|
+
stdErr[i] = NaN;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
return {
|
|
411
|
+
params: result.x,
|
|
412
|
+
cov,
|
|
413
|
+
stdErr,
|
|
414
|
+
fx: result.fx,
|
|
415
|
+
iterations: result.iterations,
|
|
416
|
+
converged: result.converged,
|
|
417
|
+
};
|
|
418
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Strong Wolfe line search (bracket + zoom with cubic interpolation),
|
|
3
|
+
* after Nocedal & Wright, "Numerical Optimization", algorithms 3.5/3.6.
|
|
4
|
+
*
|
|
5
|
+
* Guarantees, on success, a step t with:
|
|
6
|
+
* f(x + t*p) <= f(x) + c1 * t * g0'p (sufficient decrease)
|
|
7
|
+
* |g(x + t*p)'p| <= c2 * |g0'p| (curvature)
|
|
8
|
+
*
|
|
9
|
+
* Non-finite trial values are treated as "step too long" and bracketed
|
|
10
|
+
* away rather than propagated.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
function dot(a, b) {
|
|
14
|
+
let s = 0;
|
|
15
|
+
for (let i = 0; i < a.length; i++) s += a[i] * b[i];
|
|
16
|
+
return s;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Cubic minimizer of a Hermite interpolant on [a, b] given f and f' at a
|
|
21
|
+
* and f at b (and optionally f' at b). Falls back to the midpoint when the
|
|
22
|
+
* interpolation is degenerate or lands outside a safeguarded interior.
|
|
23
|
+
*/
|
|
24
|
+
function interpolate(a, fa, da, b, fb, db) {
|
|
25
|
+
// Try cubic interpolation using both derivatives when available
|
|
26
|
+
if (db !== undefined && Number.isFinite(db)) {
|
|
27
|
+
const d1 = da + db - 3 * (fa - fb) / (a - b);
|
|
28
|
+
const disc = d1 * d1 - da * db;
|
|
29
|
+
if (disc >= 0) {
|
|
30
|
+
const d2 = Math.sign(b - a) * Math.sqrt(disc);
|
|
31
|
+
const t = b - (b - a) * ((db + d2 - d1) / (db - da + 2 * d2));
|
|
32
|
+
if (Number.isFinite(t)) return t;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
// Quadratic through fa, da, fb
|
|
36
|
+
const t = a - (da * (b - a) * (b - a)) / (2 * (fb - fa - da * (b - a)));
|
|
37
|
+
return Number.isFinite(t) ? t : (a + b) / 2;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Strong Wolfe line search along direction p from x.
|
|
42
|
+
*
|
|
43
|
+
* @param {Function} evaluate - (x) => {loss, gradient}
|
|
44
|
+
* @param {Array<number>} x - Starting point
|
|
45
|
+
* @param {Array<number>|Float64Array} p - Descent direction (g0'p must be < 0)
|
|
46
|
+
* @param {number} f0 - f(x)
|
|
47
|
+
* @param {Array<number>} g0 - gradient at x
|
|
48
|
+
* @param {Object} [options]
|
|
49
|
+
* @param {number} [options.t0=1] - Initial step
|
|
50
|
+
* @param {number} [options.c1=1e-4] - Sufficient-decrease constant
|
|
51
|
+
* @param {number} [options.c2=0.9] - Curvature constant
|
|
52
|
+
* @param {number} [options.maxIter=25] - Bracketing iterations
|
|
53
|
+
* @param {number} [options.tMax=1e10] - Maximum step
|
|
54
|
+
* @returns {Object} {success, t, fx, gradient, xNew, fevals}
|
|
55
|
+
*/
|
|
56
|
+
export function strongWolfeLineSearch(evaluate, x, p, f0, g0, options = {}) {
|
|
57
|
+
const c1 = options.c1 !== undefined ? options.c1 : 1e-4;
|
|
58
|
+
const c2 = options.c2 !== undefined ? options.c2 : 0.9;
|
|
59
|
+
const maxIter = options.maxIter || 25;
|
|
60
|
+
const tMax = options.tMax || 1e10;
|
|
61
|
+
const n = x.length;
|
|
62
|
+
|
|
63
|
+
const d0 = dot(g0, p);
|
|
64
|
+
if (!(d0 < 0)) {
|
|
65
|
+
return { success: false, t: 0, fx: f0, gradient: g0, xNew: x, fevals: 0 };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
let fevals = 0;
|
|
69
|
+
const xTrial = new Array(n);
|
|
70
|
+
const phi = (t) => {
|
|
71
|
+
for (let i = 0; i < n; i++) xTrial[i] = x[i] + t * p[i];
|
|
72
|
+
const { loss, gradient } = evaluate(xTrial);
|
|
73
|
+
fevals++;
|
|
74
|
+
return { f: loss, g: gradient, dphi: dot(gradient, p) };
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const fail = () => ({ success: false, t: 0, fx: f0, gradient: g0, xNew: x, fevals });
|
|
78
|
+
const ok = (t, e) => ({
|
|
79
|
+
success: true,
|
|
80
|
+
t,
|
|
81
|
+
fx: e.f,
|
|
82
|
+
gradient: e.g,
|
|
83
|
+
xNew: x.map((xi, i) => xi + t * p[i]),
|
|
84
|
+
fevals,
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
/** Zoom phase: the Wolfe step is bracketed in [lo, hi] (in function-value order). */
|
|
88
|
+
function zoom(tLo, eLo, tHi, eHi) {
|
|
89
|
+
for (let j = 0; j < maxIter; j++) {
|
|
90
|
+
let t = interpolate(tLo, eLo.f, eLo.dphi, tHi, eHi.f, eHi.dphi);
|
|
91
|
+
const lo = Math.min(tLo, tHi);
|
|
92
|
+
const hi = Math.max(tLo, tHi);
|
|
93
|
+
// Safeguard: keep the trial strictly interior, else bisect
|
|
94
|
+
if (!Number.isFinite(t) || t <= lo + 0.1 * (hi - lo) || t >= hi - 0.1 * (hi - lo)) {
|
|
95
|
+
t = (tLo + tHi) / 2;
|
|
96
|
+
}
|
|
97
|
+
const e = phi(t);
|
|
98
|
+
if (!Number.isFinite(e.f) || e.f > f0 + c1 * t * d0 || e.f >= eLo.f) {
|
|
99
|
+
tHi = t;
|
|
100
|
+
eHi = e;
|
|
101
|
+
} else {
|
|
102
|
+
if (Math.abs(e.dphi) <= -c2 * d0) return ok(t, e);
|
|
103
|
+
if (e.dphi * (tHi - tLo) >= 0) {
|
|
104
|
+
tHi = tLo;
|
|
105
|
+
eHi = eLo;
|
|
106
|
+
}
|
|
107
|
+
tLo = t;
|
|
108
|
+
eLo = e;
|
|
109
|
+
}
|
|
110
|
+
if (Math.abs(tHi - tLo) < 1e-16 * Math.max(1, Math.abs(tLo))) break;
|
|
111
|
+
}
|
|
112
|
+
// Interval collapsed: accept lo if it at least sufficiently decreases f
|
|
113
|
+
return eLo.f < f0 + c1 * tLo * d0 && tLo > 0 ? ok(tLo, eLo) : fail();
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
let tPrev = 0;
|
|
117
|
+
let ePrev = { f: f0, g: g0, dphi: d0 };
|
|
118
|
+
let t = options.t0 !== undefined ? options.t0 : 1;
|
|
119
|
+
|
|
120
|
+
for (let i = 0; i < maxIter; i++) {
|
|
121
|
+
const e = phi(t);
|
|
122
|
+
if (!Number.isFinite(e.f) || e.f > f0 + c1 * t * d0 || (i > 0 && e.f >= ePrev.f)) {
|
|
123
|
+
return zoom(tPrev, ePrev, t, e);
|
|
124
|
+
}
|
|
125
|
+
if (Math.abs(e.dphi) <= -c2 * d0) return ok(t, e);
|
|
126
|
+
if (e.dphi >= 0) return zoom(t, e, tPrev, ePrev);
|
|
127
|
+
tPrev = t;
|
|
128
|
+
ePrev = e;
|
|
129
|
+
t = Math.min(2 * t, tMax);
|
|
130
|
+
if (t >= tMax) return fail();
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
return fail();
|
|
134
|
+
}
|
package/src/linsolve.js
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dense linear-system solver.
|
|
3
|
+
*
|
|
4
|
+
* Gaussian elimination with scaled partial pivoting for the small n-by-n
|
|
5
|
+
* systems that arise in Levenberg-Marquardt normal equations. Inputs are
|
|
6
|
+
* copied, never mutated.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Solve the linear system A x = b.
|
|
11
|
+
*
|
|
12
|
+
* @param {Array<Array<number>>} A - n-by-n coefficient matrix (not mutated)
|
|
13
|
+
* @param {Array<number>} b - Right-hand side of length n (not mutated)
|
|
14
|
+
* @returns {Array<number>} Solution vector x
|
|
15
|
+
* @throws {Error} If A is not square, b has the wrong length, or A is singular
|
|
16
|
+
*/
|
|
17
|
+
export function solve(A, b) {
|
|
18
|
+
if (!Array.isArray(A) || A.length === 0) {
|
|
19
|
+
throw new Error('solve: A must be a non-empty square matrix');
|
|
20
|
+
}
|
|
21
|
+
const n = A.length;
|
|
22
|
+
for (let i = 0; i < n; i++) {
|
|
23
|
+
if (!Array.isArray(A[i]) || A[i].length !== n) {
|
|
24
|
+
throw new Error('solve: A must be a non-empty square matrix');
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
if (!Array.isArray(b) || b.length !== n) {
|
|
28
|
+
throw new Error('solve: b must be an array with the same length as A');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Working copies: elimination happens in place on these.
|
|
32
|
+
const M = new Array(n);
|
|
33
|
+
for (let i = 0; i < n; i++) {
|
|
34
|
+
M[i] = A[i].slice();
|
|
35
|
+
}
|
|
36
|
+
const x = b.slice();
|
|
37
|
+
|
|
38
|
+
// Row scale factors for scaled partial pivoting.
|
|
39
|
+
const scale = new Array(n);
|
|
40
|
+
for (let i = 0; i < n; i++) {
|
|
41
|
+
let s = 0;
|
|
42
|
+
for (let j = 0; j < n; j++) {
|
|
43
|
+
s = Math.max(s, Math.abs(M[i][j]));
|
|
44
|
+
}
|
|
45
|
+
if (s === 0) {
|
|
46
|
+
throw new Error('solve: matrix is singular (zero row)');
|
|
47
|
+
}
|
|
48
|
+
scale[i] = s;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
for (let k = 0; k < n; k++) {
|
|
52
|
+
// Pick the pivot row maximizing |M[i][k]| / scale[i].
|
|
53
|
+
let pivotRow = k;
|
|
54
|
+
let pivotSize = Math.abs(M[k][k]) / scale[k];
|
|
55
|
+
for (let i = k + 1; i < n; i++) {
|
|
56
|
+
const size = Math.abs(M[i][k]) / scale[i];
|
|
57
|
+
if (size > pivotSize) {
|
|
58
|
+
pivotSize = size;
|
|
59
|
+
pivotRow = i;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (!(pivotSize >= 1e-300)) {
|
|
63
|
+
throw new Error('solve: matrix is singular to working precision');
|
|
64
|
+
}
|
|
65
|
+
if (pivotRow !== k) {
|
|
66
|
+
const rowTmp = M[k];
|
|
67
|
+
M[k] = M[pivotRow];
|
|
68
|
+
M[pivotRow] = rowTmp;
|
|
69
|
+
const bTmp = x[k];
|
|
70
|
+
x[k] = x[pivotRow];
|
|
71
|
+
x[pivotRow] = bTmp;
|
|
72
|
+
const sTmp = scale[k];
|
|
73
|
+
scale[k] = scale[pivotRow];
|
|
74
|
+
scale[pivotRow] = sTmp;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const pivot = M[k][k];
|
|
78
|
+
for (let i = k + 1; i < n; i++) {
|
|
79
|
+
const factor = M[i][k] / pivot;
|
|
80
|
+
if (factor === 0) continue;
|
|
81
|
+
M[i][k] = 0;
|
|
82
|
+
for (let j = k + 1; j < n; j++) {
|
|
83
|
+
M[i][j] -= factor * M[k][j];
|
|
84
|
+
}
|
|
85
|
+
x[i] -= factor * x[k];
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Back substitution.
|
|
90
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
91
|
+
let sum = x[i];
|
|
92
|
+
for (let j = i + 1; j < n; j++) {
|
|
93
|
+
sum -= M[i][j] * x[j];
|
|
94
|
+
}
|
|
95
|
+
x[i] = sum / M[i][i];
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return x;
|
|
99
|
+
}
|