@numero-uno-jpn/rstats 0.9.0 → 0.11.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/CHANGELOG.md +87 -0
- package/README.ja.md +64 -12
- package/README.md +63 -11
- package/THIRD_PARTY_NOTICES.md +7 -2
- package/dist/chunks/chunk-5WDJPHYY.js +2 -0
- package/dist/chunks/chunk-7GQMKH3Z.js +2 -0
- package/dist/chunks/chunk-AHHS6AC4.js +3 -0
- package/dist/chunks/chunk-ALM3VHFP.js +2 -0
- package/dist/chunks/{chunk-TOVTN5Y2.js → chunk-C5XTWMGB.js} +1 -1
- package/dist/chunks/chunk-CGBNKHNZ.js +2 -0
- package/dist/chunks/{chunk-LWUSYIQ4.js → chunk-EZAFN5CD.js} +1 -1
- package/dist/chunks/{chunk-H2AP6TCR.js → chunk-EZWBRCJL.js} +1 -1
- package/dist/chunks/chunk-F5EDJFEO.js +2 -0
- package/dist/chunks/{chunk-FC2TLHZC.js → chunk-JWBO5WVN.js} +2 -2
- package/dist/chunks/{chunk-LE7TBHNI.js → chunk-TOGXTCZO.js} +2 -2
- package/dist/chunks/chunk-VJ4BDBMU.js +3 -0
- package/dist/chunks/chunk-Y5CNQ266.js +2 -0
- package/dist/chunks/{chunk-BGVMSDVJ.js → chunk-Y5PYRAYP.js} +2 -2
- package/dist/chunks/{chunk-5K4PS7IV.js → chunk-YSWGDOWK.js} +2 -2
- package/dist/data/grouping.d.ts +79 -0
- package/dist/data/grouping.js +262 -0
- package/dist/descriptive/dataFrames.d.ts +110 -0
- package/dist/descriptive/dataFrames.js +392 -0
- package/dist/descriptive/factanal.d.ts +56 -0
- package/dist/descriptive/factanal.js +186 -0
- package/dist/descriptive/missing.d.ts +35 -0
- package/dist/descriptive/missing.js +50 -0
- package/dist/descriptive/omega.d.ts +56 -0
- package/dist/descriptive/omega.js +323 -0
- package/dist/descriptive/pivot.d.ts +89 -0
- package/dist/descriptive/pivot.js +343 -0
- package/dist/descriptive.js +2 -2
- package/dist/distributions/bvnorm.d.ts +15 -0
- package/dist/distributions/bvnorm.js +131 -0
- package/dist/distributions/nbeta.js +34 -1
- package/dist/distributions/nchisq.d.ts +10 -0
- package/dist/distributions/nchisq.js +46 -0
- package/dist/distributions.js +2 -2
- package/dist/entries/descriptive.d.ts +4 -0
- package/dist/entries/descriptive.js +4 -0
- package/dist/entries/distributions.d.ts +1 -0
- package/dist/entries/distributions.js +1 -0
- package/dist/entries/linalg.d.ts +2 -0
- package/dist/entries/linalg.js +2 -0
- package/dist/entries/numerics.d.ts +2 -0
- package/dist/entries/numerics.js +1 -0
- package/dist/entries/tests.d.ts +22 -1
- package/dist/entries/tests.js +19 -1
- package/dist/htest/agreement.d.ts +141 -0
- package/dist/htest/agreement.js +274 -0
- package/dist/htest/ansariTest.d.ts +12 -0
- package/dist/htest/ansariTest.js +5 -17
- package/dist/htest/aov.d.ts +19 -0
- package/dist/htest/aov.js +22 -15
- package/dist/htest/cor.d.ts +12 -0
- package/dist/htest/cor.js +9 -27
- package/dist/htest/core/simulate.d.ts +2 -0
- package/dist/htest/core/simulate.js +1 -1
- package/dist/htest/dunnett.d.ts +5 -0
- package/dist/htest/dunnett.js +89 -0
- package/dist/htest/effectSize.d.ts +112 -0
- package/dist/htest/effectSize.js +385 -0
- package/dist/htest/ksTest.d.ts +13 -0
- package/dist/htest/ksTest.js +5 -8
- package/dist/htest/leveneTest.d.ts +30 -0
- package/dist/htest/leveneTest.js +41 -0
- package/dist/htest/multipleComparisons.d.ts +147 -0
- package/dist/htest/multipleComparisons.js +369 -0
- package/dist/htest/normalityTests.d.ts +44 -0
- package/dist/htest/normalityTests.js +164 -0
- package/dist/htest/onewayTest.d.ts +14 -0
- package/dist/htest/onewayTest.js +5 -7
- package/dist/htest/polycor.d.ts +117 -0
- package/dist/htest/polycor.js +468 -0
- package/dist/htest/power.d.ts +132 -0
- package/dist/htest/power.js +227 -0
- package/dist/htest/pwr.d.ts +263 -0
- package/dist/htest/pwr.js +440 -0
- package/dist/htest/rankTests.d.ts +64 -0
- package/dist/htest/rankTests.js +27 -29
- package/dist/htest/tTest.d.ts +20 -0
- package/dist/htest/tTest.js +19 -24
- package/dist/htest/testFormula.d.ts +57 -0
- package/dist/htest/testFormula.js +171 -0
- package/dist/htest/trendTests.d.ts +57 -0
- package/dist/htest/trendTests.js +167 -0
- package/dist/htest/varTest.d.ts +23 -0
- package/dist/htest/varTest.js +11 -21
- package/dist/htest/wilcoxTest.d.ts +14 -0
- package/dist/htest/wilcoxTest.js +9 -24
- package/dist/linalg/eigen.d.ts +8 -0
- package/dist/linalg/eigen.js +5 -4
- package/dist/linalg/expm.d.ts +48 -0
- package/dist/linalg/expm.js +472 -0
- package/dist/linalg/ops.d.ts +13 -2
- package/dist/linalg/ops.js +20 -5
- package/dist/linalg/schur.d.ts +48 -0
- package/dist/linalg/schur.js +225 -0
- package/dist/linalg.js +2 -2
- package/dist/models/anovaSequential.d.ts +58 -0
- package/dist/models/anovaSequential.js +138 -0
- package/dist/models/aovEz.d.ts +64 -0
- package/dist/models/aovEz.js +332 -0
- package/dist/models/aovStrata.d.ts +32 -0
- package/dist/models/aovStrata.js +104 -0
- package/dist/models/carAnova.d.ts +30 -0
- package/dist/models/carAnova.js +121 -0
- package/dist/models/coxph.d.ts +101 -0
- package/dist/models/coxph.js +502 -0
- package/dist/models/ddLeastSquares.d.ts +30 -0
- package/dist/models/ddLeastSquares.js +90 -0
- package/dist/models/ddMatrix.d.ts +10 -0
- package/dist/models/ddMatrix.js +91 -0
- package/dist/models/formula.d.ts +83 -0
- package/dist/models/formula.js +333 -0
- package/dist/models/lm.d.ts +84 -3
- package/dist/models/lm.js +141 -44
- package/dist/models/mauchly.d.ts +48 -0
- package/dist/models/mauchly.js +123 -0
- package/dist/models/modelFrame.d.ts +40 -0
- package/dist/models/modelFrame.js +131 -0
- package/dist/models/modelMatrix.d.ts +88 -0
- package/dist/models/modelMatrix.js +170 -0
- package/dist/models/survival.d.ts +87 -0
- package/dist/models/survival.js +238 -0
- package/dist/numerics.js +2 -2
- package/dist/optim/lbfgsb.d.ts +20 -0
- package/dist/optim/lbfgsb.js +1240 -0
- package/dist/optim/optim.d.ts +85 -0
- package/dist/optim/optim.js +610 -0
- package/dist/rstats.js +19 -4
- package/dist/special.js +2 -2
- package/dist/tests.js +17 -4
- package/llms.txt +114 -0
- package/package.json +3 -2
- package/dist/chunks/chunk-24U4DKRY.js +0 -2
- package/dist/chunks/chunk-IVOBWYLV.js +0 -2
- package/dist/chunks/chunk-JLSTEMSN.js +0 -2
- package/dist/chunks/chunk-MF4VBCHQ.js +0 -2
- package/dist/chunks/chunk-MSAUU6PY.js +0 -2
- package/dist/chunks/chunk-YC4JWUKG.js +0 -2
- package/dist/chunks/chunk-ZRO446BP.js +0 -2
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/** Methods of {@link optim} */
|
|
2
|
+
export type OptimMethod = "Nelder-Mead" | "BFGS" | "CG" | "L-BFGS-B" | "SANN" | "Brent";
|
|
3
|
+
/** Control parameters of {@link optim} (R's `control`, in camelCase) */
|
|
4
|
+
export interface OptimControl {
|
|
5
|
+
/** Maximum number of iterations. Default 500 for Nelder-Mead, 10000 for SANN, 100 otherwise. */
|
|
6
|
+
maxit?: number;
|
|
7
|
+
/** Relative convergence tolerance. Default `sqrt(eps)`. */
|
|
8
|
+
reltol?: number;
|
|
9
|
+
/** Absolute convergence tolerance (stop when the value falls to it). Default `-Infinity`. */
|
|
10
|
+
abstol?: number;
|
|
11
|
+
/** Scaling of the parameters: the optimisation is on `par / parscale`. Default 1. */
|
|
12
|
+
parscale?: number | readonly number[];
|
|
13
|
+
/** Scaling of the objective: `fn / fnscale` is minimised (negative to maximise). Default 1. */
|
|
14
|
+
fnscale?: number;
|
|
15
|
+
/** Steps of the finite-difference gradient, in the scaled parameters. Default 1e-3. */
|
|
16
|
+
ndeps?: number | readonly number[];
|
|
17
|
+
/** Nelder-Mead reflection factor. Default 1. */
|
|
18
|
+
alpha?: number;
|
|
19
|
+
/** Nelder-Mead contraction factor. Default 0.5. */
|
|
20
|
+
beta?: number;
|
|
21
|
+
/** Nelder-Mead expansion factor. Default 2. */
|
|
22
|
+
gamma?: number;
|
|
23
|
+
/** CG update: 1 Fletcher-Reeves (default), 2 Polak-Ribière, 3 Beale-Sorenson. */
|
|
24
|
+
type?: number;
|
|
25
|
+
/** L-BFGS-B: number of corrections kept. Default 5. */
|
|
26
|
+
lmm?: number;
|
|
27
|
+
/** L-BFGS-B: relative reduction tolerance in units of the machine epsilon. Default 1e7. */
|
|
28
|
+
factr?: number;
|
|
29
|
+
/** L-BFGS-B: tolerance on the projected gradient. Default 0. */
|
|
30
|
+
pgtol?: number;
|
|
31
|
+
/** SANN: starting temperature. Default 10. */
|
|
32
|
+
temp?: number;
|
|
33
|
+
/** SANN: evaluations per temperature. Default 10. */
|
|
34
|
+
tmax?: number;
|
|
35
|
+
}
|
|
36
|
+
/** Options of {@link optim} */
|
|
37
|
+
export interface OptimOptions {
|
|
38
|
+
/** Gradient of fn (numerical by central differences when omitted) */
|
|
39
|
+
gr?: (par: number[]) => number[];
|
|
40
|
+
/** Default `"Nelder-Mead"` */
|
|
41
|
+
method?: OptimMethod;
|
|
42
|
+
/** Lower bounds (L-BFGS-B and Brent), recycled. Default `-Infinity`. */
|
|
43
|
+
lower?: number | readonly number[];
|
|
44
|
+
/** Upper bounds (L-BFGS-B and Brent), recycled. Default `Infinity`. */
|
|
45
|
+
upper?: number | readonly number[];
|
|
46
|
+
/** Also return the numerically differentiated Hessian at the solution. Default `false`. */
|
|
47
|
+
hessian?: boolean;
|
|
48
|
+
control?: OptimControl;
|
|
49
|
+
}
|
|
50
|
+
/** Result of {@link optim} */
|
|
51
|
+
export interface OptimResult {
|
|
52
|
+
par: number[];
|
|
53
|
+
value: number;
|
|
54
|
+
/** Evaluations of fn and gr (NaN where R has NA) */
|
|
55
|
+
counts: [number, number];
|
|
56
|
+
/** 0 success, 1 iteration limit reached, 10 Nelder-Mead simplex degenerate, 51 / 52 L-BFGS-B warning / error */
|
|
57
|
+
convergence: number;
|
|
58
|
+
/** L-BFGS-B's final message; null for the other methods */
|
|
59
|
+
message: string | null;
|
|
60
|
+
hessian?: number[][];
|
|
61
|
+
/** R's warnings */
|
|
62
|
+
warnings: string[];
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Numerically differentiated Hessian of fn at par, from central differences of the gradient (gr, or the numerical
|
|
66
|
+
* gradient of fn). Equivalent to R's `optimHess()`; `control` uses `fnscale`, `parscale` and `ndeps`.
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* ```ts
|
|
70
|
+
* optimHess([1, 2], (x) => x[0] ** 2 + 3 * x[0] * x[1] + x[1] ** 2); // ≈ [[2, 3], [3, 2]]
|
|
71
|
+
* ```
|
|
72
|
+
*/
|
|
73
|
+
export declare function optimHess(par: readonly number[], fn: (par: number[]) => number, gr?: (par: number[]) => number[], control?: OptimControl): number[][];
|
|
74
|
+
/**
|
|
75
|
+
* General-purpose minimisation of `fn` from the starting point `par`. Equivalent to R's `optim()`: the same methods
|
|
76
|
+
* with the same iterations, so the same results and counts.
|
|
77
|
+
*
|
|
78
|
+
* @example
|
|
79
|
+
* ```ts
|
|
80
|
+
* const rosen = (x: number[]) => 100 * (x[1] - x[0] ** 2) ** 2 + (1 - x[0]) ** 2;
|
|
81
|
+
* optim([-1.2, 1], rosen).par; // [1.0002601387256695, 1.000505999303765]
|
|
82
|
+
* optim([-1.2, 1], rosen, { method: "BFGS" }).counts; // [120, 38]
|
|
83
|
+
* ```
|
|
84
|
+
*/
|
|
85
|
+
export declare function optim(par: readonly number[], fn: (par: number[]) => number, options?: OptimOptions): OptimResult;
|
|
@@ -0,0 +1,610 @@
|
|
|
1
|
+
// General-purpose optimisation, R's optim() and optimHess(): Nelder-Mead, BFGS (variable metric) and CG (conjugate
|
|
2
|
+
// gradients) are J. C. Nash's Algorithms 19, 21 and 22 ("Compact Numerical Methods for Computers", 2nd ed., Adam
|
|
3
|
+
// Hilger, 1990) with R's details as described in oracle/optim-behaviour.md; L-BFGS-B is the Netlib code of Zhu, Byrd,
|
|
4
|
+
// Lu and Nocedal (src/optim/lbfgsb.ts); SANN is Bélisle's simulated annealing (C. J. P. Bélisle, "Convergence
|
|
5
|
+
// theorems for a class of simulated annealing algorithms on R^d", J. Appl. Probab. 29 (1992) 885-895) with R's random
|
|
6
|
+
// numbers; Brent is optimize(). Written for rStats.js from the specification (no R code was read or used).
|
|
7
|
+
import { optimize } from "../numerics/integrate.js";
|
|
8
|
+
import { normRand, unifRand } from "../random/rng.js";
|
|
9
|
+
import { lbfgsb } from "./lbfgsb.js";
|
|
10
|
+
// R's constants (oracle/optim-behaviour.md, rule 5)
|
|
11
|
+
/** Scale at which a step is taken to change nothing */
|
|
12
|
+
const SHIFT = 10;
|
|
13
|
+
/** Sufficient-decrease factor of the line searches */
|
|
14
|
+
const DECREASE = 1e-4;
|
|
15
|
+
/** Step reduction of the line searches */
|
|
16
|
+
const REDUCTION = 0.2;
|
|
17
|
+
/** Growth of the first step of CG's next line search */
|
|
18
|
+
const GROWTH = 1.7;
|
|
19
|
+
/** Value used for a function value that is not finite (Nelder-Mead, SANN) */
|
|
20
|
+
const HUGE_VALUE = 1e35;
|
|
21
|
+
/** e - 1 to 8 digits, SANN's temperature schedule */
|
|
22
|
+
const E_MINUS_1 = 1.7182818;
|
|
23
|
+
function recycle(v, n, dflt) {
|
|
24
|
+
if (v === undefined)
|
|
25
|
+
return new Array(n).fill(dflt);
|
|
26
|
+
const a = typeof v === "number" ? [v] : v;
|
|
27
|
+
if (a.length === 0)
|
|
28
|
+
throw new RangeError("argument of length 0");
|
|
29
|
+
return Array.from({ length: n }, (_, i) => a[i % a.length]);
|
|
30
|
+
}
|
|
31
|
+
/** The scaled problem: p = par / parscale, f(p) = fn(p * parscale) / fnscale */
|
|
32
|
+
class Scaled {
|
|
33
|
+
fn;
|
|
34
|
+
gr;
|
|
35
|
+
parscale;
|
|
36
|
+
fnscale;
|
|
37
|
+
ndeps;
|
|
38
|
+
n;
|
|
39
|
+
constructor(fn, gr, parscale, fnscale, ndeps) {
|
|
40
|
+
this.fn = fn;
|
|
41
|
+
this.gr = gr;
|
|
42
|
+
this.parscale = parscale;
|
|
43
|
+
this.fnscale = fnscale;
|
|
44
|
+
this.ndeps = ndeps;
|
|
45
|
+
this.n = parscale.length;
|
|
46
|
+
}
|
|
47
|
+
unscale(p) {
|
|
48
|
+
return p.map((v, i) => v * this.parscale[i]);
|
|
49
|
+
}
|
|
50
|
+
f(p) {
|
|
51
|
+
return this.fn(this.unscale(p)) / this.fnscale;
|
|
52
|
+
}
|
|
53
|
+
/** Gradient in the scaled parameters; numerical steps are cut at the bounds when given (L-BFGS-B) */
|
|
54
|
+
g(p, lower, upper) {
|
|
55
|
+
const { n, parscale, fnscale } = this;
|
|
56
|
+
if (this.gr !== undefined) {
|
|
57
|
+
const gx = this.gr(this.unscale(p));
|
|
58
|
+
if (gx.length !== n)
|
|
59
|
+
throw new RangeError(`gradient in optim evaluated to length ${gx.length} not ${n}`);
|
|
60
|
+
return gx.map((v, i) => (v * parscale[i]) / fnscale);
|
|
61
|
+
}
|
|
62
|
+
const x = this.unscale(p);
|
|
63
|
+
const slopes = new Array(n);
|
|
64
|
+
for (let i = 0; i < n; i++) {
|
|
65
|
+
const eps = this.ndeps[i];
|
|
66
|
+
let up = p[i] + eps;
|
|
67
|
+
let down = p[i] - eps;
|
|
68
|
+
let width;
|
|
69
|
+
if (lower === undefined || upper === undefined)
|
|
70
|
+
width = 2 * eps;
|
|
71
|
+
else {
|
|
72
|
+
let epsUp = eps;
|
|
73
|
+
let epsDown = eps;
|
|
74
|
+
if (up > upper[i]) {
|
|
75
|
+
up = upper[i];
|
|
76
|
+
epsUp = up - p[i];
|
|
77
|
+
}
|
|
78
|
+
if (down < lower[i]) {
|
|
79
|
+
down = lower[i];
|
|
80
|
+
epsDown = p[i] - down;
|
|
81
|
+
}
|
|
82
|
+
width = epsUp + epsDown;
|
|
83
|
+
}
|
|
84
|
+
x[i] = up * parscale[i];
|
|
85
|
+
const v1 = this.fn(x.slice()) / fnscale;
|
|
86
|
+
x[i] = down * parscale[i];
|
|
87
|
+
const v2 = this.fn(x.slice()) / fnscale;
|
|
88
|
+
slopes[i] = (v1 - v2) / width;
|
|
89
|
+
if (!Number.isFinite(slopes[i]))
|
|
90
|
+
throw new Error(`non-finite finite-difference value [${i + 1}]`);
|
|
91
|
+
x[i] = p[i] * parscale[i];
|
|
92
|
+
}
|
|
93
|
+
return slopes;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/** Replaces a value that is not finite by a large one (for the derivative-free methods) */
|
|
97
|
+
const orHuge = (v) => (Number.isFinite(v) ? v : HUGE_VALUE);
|
|
98
|
+
/** Whether `from + amount` is indistinguishable from `from` at the scale of SHIFT (the rule "10 + x == 10 + y") */
|
|
99
|
+
const unchanged = (from, to) => SHIFT + from === SHIFT + to;
|
|
100
|
+
/**
|
|
101
|
+
* Backtracking line search shared by BFGS and CG: from `from` along `dir`, trial points `from + step dir` with the
|
|
102
|
+
* step cut by REDUCTION until the value satisfies the sufficient-decrease test against `best` or the trial point no
|
|
103
|
+
* longer moves any coordinate. `point` receives the last trial point.
|
|
104
|
+
*/
|
|
105
|
+
function backtrack(s, from, dir, slope, best, firstStep, point, lastValue) {
|
|
106
|
+
const n = from.length;
|
|
107
|
+
let step = firstStep;
|
|
108
|
+
let value = lastValue;
|
|
109
|
+
let evals = 0;
|
|
110
|
+
for (;;) {
|
|
111
|
+
let same = 0;
|
|
112
|
+
for (let i = 0; i < n; i++) {
|
|
113
|
+
point[i] = from[i] + step * dir[i];
|
|
114
|
+
if (unchanged(from[i], point[i]))
|
|
115
|
+
same++;
|
|
116
|
+
}
|
|
117
|
+
if (same === n)
|
|
118
|
+
return { step, accepted: false, value, evals };
|
|
119
|
+
value = s.f(point);
|
|
120
|
+
evals++;
|
|
121
|
+
if (Number.isFinite(value) && value <= best + slope * step * DECREASE)
|
|
122
|
+
return { step, accepted: true, value, evals };
|
|
123
|
+
step *= REDUCTION;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/** Nelder-Mead simplex (Nash's Algorithm 19, with R's details from the specification) */
|
|
127
|
+
function simplexSearch(s, start, reflect, contract, expand, abstol, reltol, maxit) {
|
|
128
|
+
const n = start.length;
|
|
129
|
+
if (maxit <= 0)
|
|
130
|
+
return { par: start.slice(), value: s.f(start), fnEvals: 0, gradEvals: NaN, code: 0 };
|
|
131
|
+
const startValue = s.f(start);
|
|
132
|
+
if (!Number.isFinite(startValue))
|
|
133
|
+
throw new Error("function cannot be evaluated at initial parameters");
|
|
134
|
+
let evals = 1;
|
|
135
|
+
const tolerance = reltol * (Math.abs(startValue) + reltol);
|
|
136
|
+
// the vertices and their values (NaN: to be computed)
|
|
137
|
+
const vertex = [start.slice()];
|
|
138
|
+
const value = [startValue];
|
|
139
|
+
let initialStep = 0;
|
|
140
|
+
for (const v of start)
|
|
141
|
+
if (0.1 * Math.abs(v) > initialStep)
|
|
142
|
+
initialStep = 0.1 * Math.abs(v);
|
|
143
|
+
if (initialStep === 0)
|
|
144
|
+
initialStep = 0.1;
|
|
145
|
+
let extent = 0;
|
|
146
|
+
for (let j = 0; j < n; j++) {
|
|
147
|
+
const v = start.slice();
|
|
148
|
+
let used = initialStep;
|
|
149
|
+
v[j] = start[j] + used;
|
|
150
|
+
while (v[j] === start[j]) {
|
|
151
|
+
used *= 10;
|
|
152
|
+
v[j] = start[j] + used;
|
|
153
|
+
}
|
|
154
|
+
extent += used;
|
|
155
|
+
vertex.push(v);
|
|
156
|
+
value.push(NaN);
|
|
157
|
+
}
|
|
158
|
+
let lastExtent = extent;
|
|
159
|
+
let low = 0;
|
|
160
|
+
let code = 0;
|
|
161
|
+
const centroid = new Array(n);
|
|
162
|
+
do {
|
|
163
|
+
for (let j = 0; j <= n; j++) {
|
|
164
|
+
if (j !== low && Number.isNaN(value[j])) {
|
|
165
|
+
value[j] = orHuge(s.f(vertex[j]));
|
|
166
|
+
evals++;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
let lowValue = value[low];
|
|
170
|
+
let highValue = lowValue;
|
|
171
|
+
let high = low;
|
|
172
|
+
for (let j = 0; j <= n; j++) {
|
|
173
|
+
if (j === low)
|
|
174
|
+
continue;
|
|
175
|
+
const v = value[j];
|
|
176
|
+
if (v < lowValue) {
|
|
177
|
+
low = j;
|
|
178
|
+
lowValue = v;
|
|
179
|
+
}
|
|
180
|
+
if (v > highValue) {
|
|
181
|
+
high = j;
|
|
182
|
+
highValue = v;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
if (highValue <= lowValue + tolerance || lowValue <= abstol)
|
|
186
|
+
break;
|
|
187
|
+
const worst = vertex[high];
|
|
188
|
+
for (let i = 0; i < n; i++) {
|
|
189
|
+
// all vertices summed, less the worst one
|
|
190
|
+
let total = -worst[i];
|
|
191
|
+
for (const v of vertex)
|
|
192
|
+
total += v[i];
|
|
193
|
+
centroid[i] = total / n;
|
|
194
|
+
}
|
|
195
|
+
const reflected = centroid.map((m, i) => (1 + reflect) * m - reflect * worst[i]);
|
|
196
|
+
const reflectedValue = orHuge(s.f(reflected));
|
|
197
|
+
evals++;
|
|
198
|
+
if (reflectedValue < lowValue) {
|
|
199
|
+
const expanded = reflected.map((r, i) => expand * r + (1 - expand) * centroid[i]);
|
|
200
|
+
const expandedValue = orHuge(s.f(expanded));
|
|
201
|
+
evals++;
|
|
202
|
+
const better = expandedValue < reflectedValue;
|
|
203
|
+
vertex[high] = better ? expanded : reflected;
|
|
204
|
+
value[high] = better ? expandedValue : reflectedValue;
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
if (reflectedValue < highValue) {
|
|
208
|
+
vertex[high] = reflected;
|
|
209
|
+
value[high] = reflectedValue;
|
|
210
|
+
}
|
|
211
|
+
const contracted = vertex[high].map((h, i) => (1 - contract) * h + contract * centroid[i]);
|
|
212
|
+
const contractedValue = orHuge(s.f(contracted));
|
|
213
|
+
evals++;
|
|
214
|
+
if (contractedValue < value[high]) {
|
|
215
|
+
vertex[high] = contracted;
|
|
216
|
+
value[high] = contractedValue;
|
|
217
|
+
}
|
|
218
|
+
else if (reflectedValue >= highValue) {
|
|
219
|
+
// shrink towards the lowest vertex; its values are recomputed on the next pass
|
|
220
|
+
const best = vertex[low];
|
|
221
|
+
extent = 0;
|
|
222
|
+
vertex.forEach((v, j) => {
|
|
223
|
+
if (j === low)
|
|
224
|
+
return;
|
|
225
|
+
for (let i = 0; i < n; i++) {
|
|
226
|
+
v[i] = contract * (v[i] - best[i]) + best[i];
|
|
227
|
+
extent += Math.abs(v[i] - best[i]);
|
|
228
|
+
}
|
|
229
|
+
value[j] = NaN;
|
|
230
|
+
});
|
|
231
|
+
if (!(extent < lastExtent)) {
|
|
232
|
+
code = 10;
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
lastExtent = extent;
|
|
236
|
+
}
|
|
237
|
+
} while (evals <= maxit);
|
|
238
|
+
if (code !== 10 && evals > maxit)
|
|
239
|
+
code = 1;
|
|
240
|
+
return { par: vertex[low].slice(), value: value[low], fnEvals: evals, gradEvals: NaN, code };
|
|
241
|
+
}
|
|
242
|
+
/** Variable metric (BFGS; Nash's Algorithm 21, with R's details and order of arithmetic from the specification) */
|
|
243
|
+
function variableMetric(s, start, abstol, reltol, maxit) {
|
|
244
|
+
const n = start.length;
|
|
245
|
+
const point = start.slice();
|
|
246
|
+
if (maxit <= 0)
|
|
247
|
+
return { par: point, value: s.f(point), fnEvals: 0, gradEvals: 0, code: 0 };
|
|
248
|
+
let value = s.f(point);
|
|
249
|
+
if (!Number.isFinite(value))
|
|
250
|
+
throw new Error("initial value in 'vmmin' is not finite");
|
|
251
|
+
let best = value;
|
|
252
|
+
let fnEvals = 1;
|
|
253
|
+
let gradEvals = 1;
|
|
254
|
+
let grad = s.g(point);
|
|
255
|
+
let lastReset = gradEvals;
|
|
256
|
+
// the inverse Hessian approximation H, kept as its lower triangle
|
|
257
|
+
const H = Array.from({ length: n }, (_, i) => new Array(i + 1).fill(0));
|
|
258
|
+
const h = (i, j) => (j <= i ? H[i][j] : H[j][i]);
|
|
259
|
+
const dir = new Array(n).fill(0);
|
|
260
|
+
const from = new Array(n).fill(0);
|
|
261
|
+
const Hy = new Array(n).fill(0);
|
|
262
|
+
let stalled = false;
|
|
263
|
+
let limitReached = false;
|
|
264
|
+
do {
|
|
265
|
+
if (lastReset === gradEvals) {
|
|
266
|
+
for (let i = 0; i < n; i++) {
|
|
267
|
+
H[i].fill(0);
|
|
268
|
+
H[i][i] = 1;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
for (let i = 0; i < n; i++)
|
|
272
|
+
from[i] = point[i];
|
|
273
|
+
const prevGrad = grad.slice();
|
|
274
|
+
let slope = 0;
|
|
275
|
+
for (let i = 0; i < n; i++) {
|
|
276
|
+
let d = 0;
|
|
277
|
+
for (let j = 0; j < n; j++)
|
|
278
|
+
d -= h(i, j) * grad[j];
|
|
279
|
+
dir[i] = d;
|
|
280
|
+
slope += d * grad[i];
|
|
281
|
+
}
|
|
282
|
+
if (slope < 0) {
|
|
283
|
+
const search = backtrack(s, from, dir, slope, best, 1, point, value);
|
|
284
|
+
fnEvals += search.evals;
|
|
285
|
+
value = search.value;
|
|
286
|
+
let progressed = search.accepted;
|
|
287
|
+
// too small a change counts as none, with the value taken as the best
|
|
288
|
+
if (!(value > abstol && Math.abs(value - best) > reltol * (Math.abs(best) + reltol))) {
|
|
289
|
+
progressed = false;
|
|
290
|
+
best = value;
|
|
291
|
+
}
|
|
292
|
+
if (progressed) {
|
|
293
|
+
best = value;
|
|
294
|
+
grad = s.g(point);
|
|
295
|
+
gradEvals++;
|
|
296
|
+
// step and change of gradient
|
|
297
|
+
const y = prevGrad;
|
|
298
|
+
let sy = 0;
|
|
299
|
+
for (let i = 0; i < n; i++) {
|
|
300
|
+
dir[i] = search.step * dir[i];
|
|
301
|
+
y[i] = grad[i] - y[i];
|
|
302
|
+
sy += dir[i] * y[i];
|
|
303
|
+
}
|
|
304
|
+
if (sy > 0) {
|
|
305
|
+
let yHy = 0;
|
|
306
|
+
for (let i = 0; i < n; i++) {
|
|
307
|
+
let v = 0;
|
|
308
|
+
for (let j = 0; j < n; j++)
|
|
309
|
+
v += h(i, j) * y[j];
|
|
310
|
+
Hy[i] = v;
|
|
311
|
+
yHy += v * y[i];
|
|
312
|
+
}
|
|
313
|
+
const factor = 1 + yHy / sy;
|
|
314
|
+
for (let i = 0; i < n; i++) {
|
|
315
|
+
for (let j = 0; j <= i; j++)
|
|
316
|
+
H[i][j] = H[i][j] + (factor * dir[i] * dir[j] - Hy[i] * dir[j] - dir[i] * Hy[j]) / sy;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
else
|
|
320
|
+
lastReset = gradEvals;
|
|
321
|
+
stalled = false;
|
|
322
|
+
}
|
|
323
|
+
else {
|
|
324
|
+
// no progress: start again from the identity, unless that was just done
|
|
325
|
+
stalled = lastReset === gradEvals;
|
|
326
|
+
lastReset = gradEvals;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
else {
|
|
330
|
+
// not a descent direction: the same
|
|
331
|
+
stalled = lastReset === gradEvals;
|
|
332
|
+
lastReset = gradEvals;
|
|
333
|
+
}
|
|
334
|
+
if (gradEvals >= maxit) {
|
|
335
|
+
limitReached = true;
|
|
336
|
+
break;
|
|
337
|
+
}
|
|
338
|
+
if (gradEvals - lastReset > 2 * n)
|
|
339
|
+
lastReset = gradEvals;
|
|
340
|
+
} while (!stalled || lastReset !== gradEvals);
|
|
341
|
+
return { par: point, value: best, fnEvals, gradEvals, code: limitReached ? 1 : 0 };
|
|
342
|
+
}
|
|
343
|
+
/** Conjugate gradients (Nash's Algorithm 22, with R's details from the specification) */
|
|
344
|
+
function conjugateGradients(s, start, type, abstol, reltol, maxit) {
|
|
345
|
+
const n = start.length;
|
|
346
|
+
const point = start.slice();
|
|
347
|
+
if (maxit <= 0)
|
|
348
|
+
return { par: point, value: s.f(point), fnEvals: 0, gradEvals: 0, code: 0 };
|
|
349
|
+
if (type !== 1 && type !== 2 && type !== 3)
|
|
350
|
+
throw new RangeError("unknown 'type' in \"CG\" method of 'optim'");
|
|
351
|
+
const threshold = reltol * n * Math.sqrt(reltol);
|
|
352
|
+
let value = s.f(point);
|
|
353
|
+
if (!Number.isFinite(value))
|
|
354
|
+
throw new Error("function cannot be evaluated at initial parameters");
|
|
355
|
+
let best = value;
|
|
356
|
+
let fnEvals = 1;
|
|
357
|
+
let gradEvals = 0;
|
|
358
|
+
const dir = new Array(n);
|
|
359
|
+
const prevGrad = new Array(n);
|
|
360
|
+
const from = new Array(n).fill(0);
|
|
361
|
+
let moved = true;
|
|
362
|
+
let inner = 0;
|
|
363
|
+
let numer = 0;
|
|
364
|
+
for (;;) {
|
|
365
|
+
// restart: steepest descent, first step 1
|
|
366
|
+
dir.fill(0);
|
|
367
|
+
prevGrad.fill(0);
|
|
368
|
+
inner = 0;
|
|
369
|
+
let firstStep = 1;
|
|
370
|
+
moved = true;
|
|
371
|
+
do {
|
|
372
|
+
inner++;
|
|
373
|
+
gradEvals++;
|
|
374
|
+
// the result is the point of the last gradient, with the best value
|
|
375
|
+
if (gradEvals > maxit)
|
|
376
|
+
return { par: from.slice(), value: best, fnEvals, gradEvals, code: 1 };
|
|
377
|
+
const grad = s.g(point);
|
|
378
|
+
numer = 0;
|
|
379
|
+
let denom = 0;
|
|
380
|
+
for (let i = 0; i < n; i++) {
|
|
381
|
+
from[i] = point[i];
|
|
382
|
+
const gi = grad[i];
|
|
383
|
+
const ci = prevGrad[i];
|
|
384
|
+
if (type === 1) {
|
|
385
|
+
numer += gi * gi;
|
|
386
|
+
denom += ci * ci;
|
|
387
|
+
}
|
|
388
|
+
else if (type === 2) {
|
|
389
|
+
numer += gi * (gi - ci);
|
|
390
|
+
denom += ci * ci;
|
|
391
|
+
}
|
|
392
|
+
else {
|
|
393
|
+
numer += gi * (gi - ci);
|
|
394
|
+
denom += dir[i] * (gi - ci);
|
|
395
|
+
}
|
|
396
|
+
prevGrad[i] = gi;
|
|
397
|
+
}
|
|
398
|
+
if (!(numer > threshold))
|
|
399
|
+
break;
|
|
400
|
+
const beta = denom > 0 ? numer / denom : 1;
|
|
401
|
+
let slope = 0;
|
|
402
|
+
for (let i = 0; i < n; i++) {
|
|
403
|
+
dir[i] = dir[i] * beta - grad[i];
|
|
404
|
+
slope += dir[i] * grad[i];
|
|
405
|
+
}
|
|
406
|
+
const search = backtrack(s, from, dir, slope, best, firstStep, point, value);
|
|
407
|
+
fnEvals += search.evals;
|
|
408
|
+
value = search.value;
|
|
409
|
+
moved = search.accepted;
|
|
410
|
+
const step = search.step;
|
|
411
|
+
if (moved) {
|
|
412
|
+
best = value;
|
|
413
|
+
// minimum of the parabola through the start (value and slope) and the accepted point
|
|
414
|
+
let curvature = 2 * (value - best - slope * step);
|
|
415
|
+
if (curvature > 0) {
|
|
416
|
+
curvature = -((slope * step * step) / curvature);
|
|
417
|
+
for (let i = 0; i < n; i++)
|
|
418
|
+
point[i] = from[i] + curvature * dir[i];
|
|
419
|
+
best = value;
|
|
420
|
+
value = s.f(point);
|
|
421
|
+
fnEvals++;
|
|
422
|
+
if (value < best)
|
|
423
|
+
best = value;
|
|
424
|
+
else
|
|
425
|
+
for (let i = 0; i < n; i++)
|
|
426
|
+
point[i] = from[i] + step * dir[i];
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
firstStep = Math.min(1, GROWTH * step);
|
|
430
|
+
} while (moved && inner !== n);
|
|
431
|
+
if (inner === 1 && (!moved || !(numer > threshold) || best <= abstol))
|
|
432
|
+
break;
|
|
433
|
+
}
|
|
434
|
+
return { par: from.slice(), value: best, fnEvals, gradEvals, code: 0 };
|
|
435
|
+
}
|
|
436
|
+
/** Simulated annealing with Gaussian candidates (Bélisle 1992; R's default candidate generator) */
|
|
437
|
+
function annealing(s, start, maxit, perTemperature, startTemperature) {
|
|
438
|
+
let current = start.slice();
|
|
439
|
+
if (maxit <= 0)
|
|
440
|
+
return { par: current, value: s.f(current), fnEvals: 0, gradEvals: NaN, code: 0 };
|
|
441
|
+
const spread = 1 / startTemperature;
|
|
442
|
+
let currentValue = orHuge(s.f(current));
|
|
443
|
+
let bestValue = currentValue;
|
|
444
|
+
let bestPoint = current.slice();
|
|
445
|
+
let evals = 1;
|
|
446
|
+
while (evals < maxit) {
|
|
447
|
+
const temperature = startTemperature / Math.log(evals + E_MINUS_1);
|
|
448
|
+
for (let k = 0; k < perTemperature && evals < maxit; k++) {
|
|
449
|
+
const candidate = current.map((v) => v + spread * temperature * normRand());
|
|
450
|
+
const candidateValue = orHuge(s.f(candidate));
|
|
451
|
+
const rise = candidateValue - currentValue;
|
|
452
|
+
if (rise <= 0 || unifRand() < Math.exp(-rise / temperature)) {
|
|
453
|
+
current = candidate;
|
|
454
|
+
currentValue = candidateValue;
|
|
455
|
+
if (currentValue <= bestValue) {
|
|
456
|
+
bestPoint = current.slice();
|
|
457
|
+
bestValue = currentValue;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
evals++;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
return { par: bestPoint, value: bestValue, fnEvals: maxit, gradEvals: NaN, code: 0 };
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* Numerically differentiated Hessian of fn at par, from central differences of the gradient (gr, or the numerical
|
|
467
|
+
* gradient of fn). Equivalent to R's `optimHess()`; `control` uses `fnscale`, `parscale` and `ndeps`.
|
|
468
|
+
*
|
|
469
|
+
* @example
|
|
470
|
+
* ```ts
|
|
471
|
+
* optimHess([1, 2], (x) => x[0] ** 2 + 3 * x[0] * x[1] + x[1] ** 2); // ≈ [[2, 3], [3, 2]]
|
|
472
|
+
* ```
|
|
473
|
+
*/
|
|
474
|
+
export function optimHess(par, fn, gr, control = {}) {
|
|
475
|
+
const n = par.length;
|
|
476
|
+
const s = new Scaled(fn, gr, recycle(control.parscale, n, 1), control.fnscale ?? 1, recycle(control.ndeps, n, 1e-3));
|
|
477
|
+
return hessianOf(s, par);
|
|
478
|
+
}
|
|
479
|
+
function hessianOf(s, par) {
|
|
480
|
+
const { n, parscale, fnscale, ndeps } = s;
|
|
481
|
+
const p = par.map((v, i) => v / parscale[i]);
|
|
482
|
+
const hess = Array.from({ length: n }, () => new Array(n).fill(0));
|
|
483
|
+
for (let i = 0; i < n; i++) {
|
|
484
|
+
const step = ndeps[i] / parscale[i];
|
|
485
|
+
const centre = p[i];
|
|
486
|
+
p[i] = centre + step;
|
|
487
|
+
const gradUp = s.g(p);
|
|
488
|
+
p[i] = centre - step;
|
|
489
|
+
const gradDown = s.g(p);
|
|
490
|
+
p[i] = centre;
|
|
491
|
+
for (let j = 0; j < n; j++)
|
|
492
|
+
hess[i][j] = (fnscale * (gradUp[j] - gradDown[j])) / (2 * step * parscale[i] * parscale[j]);
|
|
493
|
+
}
|
|
494
|
+
// symmetrise
|
|
495
|
+
for (let i = 0; i < n; i++) {
|
|
496
|
+
for (let j = 0; j < i; j++) {
|
|
497
|
+
const v = 0.5 * (hess[i][j] + hess[j][i]);
|
|
498
|
+
hess[i][j] = v;
|
|
499
|
+
hess[j][i] = v;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
return hess;
|
|
503
|
+
}
|
|
504
|
+
const METHODS = ["Nelder-Mead", "BFGS", "CG", "L-BFGS-B", "SANN", "Brent"];
|
|
505
|
+
/**
|
|
506
|
+
* General-purpose minimisation of `fn` from the starting point `par`. Equivalent to R's `optim()`: the same methods
|
|
507
|
+
* with the same iterations, so the same results and counts.
|
|
508
|
+
*
|
|
509
|
+
* @example
|
|
510
|
+
* ```ts
|
|
511
|
+
* const rosen = (x: number[]) => 100 * (x[1] - x[0] ** 2) ** 2 + (1 - x[0]) ** 2;
|
|
512
|
+
* optim([-1.2, 1], rosen).par; // [1.0002601387256695, 1.000505999303765]
|
|
513
|
+
* optim([-1.2, 1], rosen, { method: "BFGS" }).counts; // [120, 38]
|
|
514
|
+
* ```
|
|
515
|
+
*/
|
|
516
|
+
export function optim(par, fn, options = {}) {
|
|
517
|
+
const n = par.length;
|
|
518
|
+
let method = options.method ?? "Nelder-Mead";
|
|
519
|
+
if (!METHODS.includes(method))
|
|
520
|
+
throw new RangeError(`unknown method '${String(method)}'`);
|
|
521
|
+
const control = options.control ?? {};
|
|
522
|
+
const warnings = [];
|
|
523
|
+
const lower = recycle(options.lower, n, -Infinity);
|
|
524
|
+
const upper = recycle(options.upper, n, Infinity);
|
|
525
|
+
if ((lower.some((v) => v > -Infinity) || upper.some((v) => v < Infinity)) && method !== "L-BFGS-B" && method !== "Brent") {
|
|
526
|
+
warnings.push("bounds can only be used with method L-BFGS-B (or Brent)");
|
|
527
|
+
method = "L-BFGS-B";
|
|
528
|
+
}
|
|
529
|
+
const parscale = recycle(control.parscale, n, 1);
|
|
530
|
+
const fnscale = control.fnscale ?? 1;
|
|
531
|
+
const ndeps = recycle(control.ndeps, n, 1e-3);
|
|
532
|
+
const maxit = control.maxit ?? (method === "Nelder-Mead" ? 500 : method === "SANN" ? 10000 : 100);
|
|
533
|
+
const reltol = control.reltol ?? Math.sqrt(2 ** -52);
|
|
534
|
+
const abstol = control.abstol ?? -Infinity;
|
|
535
|
+
if (method === "Nelder-Mead" && n === 1)
|
|
536
|
+
warnings.push('one-dimensional optimization by Nelder-Mead is unreliable:\nuse "Brent" or optimize() directly');
|
|
537
|
+
if (method === "L-BFGS-B" && (control.reltol !== undefined || control.abstol !== undefined))
|
|
538
|
+
warnings.push("method L-BFGS-B uses 'factr' (and 'pgtol') instead of 'reltol' and 'abstol'");
|
|
539
|
+
const s = new Scaled(fn, options.gr, parscale, fnscale, ndeps);
|
|
540
|
+
const start = par.map((v, i) => v / parscale[i]);
|
|
541
|
+
let run;
|
|
542
|
+
let message = null;
|
|
543
|
+
switch (method) {
|
|
544
|
+
case "Nelder-Mead":
|
|
545
|
+
run = simplexSearch(s, start, control.alpha ?? 1, control.beta ?? 0.5, control.gamma ?? 2, abstol, reltol, maxit);
|
|
546
|
+
break;
|
|
547
|
+
case "BFGS":
|
|
548
|
+
run = variableMetric(s, start, abstol, reltol, maxit);
|
|
549
|
+
break;
|
|
550
|
+
case "CG":
|
|
551
|
+
run = conjugateGradients(s, start, control.type ?? 1, abstol, reltol, maxit);
|
|
552
|
+
break;
|
|
553
|
+
case "SANN": {
|
|
554
|
+
const perTemperature = control.tmax ?? 10;
|
|
555
|
+
if (!(perTemperature >= 1))
|
|
556
|
+
throw new RangeError("'tmax' is not a positive integer");
|
|
557
|
+
run = annealing(s, start, maxit, Math.trunc(perTemperature), control.temp ?? 10);
|
|
558
|
+
break;
|
|
559
|
+
}
|
|
560
|
+
case "Brent": {
|
|
561
|
+
if (n !== 1)
|
|
562
|
+
throw new RangeError('method = "Brent" is only available for one-dimensional optimization');
|
|
563
|
+
if (!Number.isFinite(lower[0]) || !Number.isFinite(upper[0]))
|
|
564
|
+
throw new RangeError("'lower' and 'upper' must be finite values");
|
|
565
|
+
const r = optimize((x) => fn([x]) / fnscale, lower[0], upper[0], { tol: reltol });
|
|
566
|
+
run = { par: [r.optimum], value: r.objective, fnEvals: NaN, gradEvals: NaN, code: 0 };
|
|
567
|
+
// par is not scaled for Brent
|
|
568
|
+
const result = { par: run.par, value: run.value * fnscale, counts: [NaN, NaN], convergence: 0, message: null, warnings };
|
|
569
|
+
if (options.hessian)
|
|
570
|
+
result.hessian = hessianOf(s, result.par);
|
|
571
|
+
return result;
|
|
572
|
+
}
|
|
573
|
+
default: {
|
|
574
|
+
// L-BFGS-B
|
|
575
|
+
const lo = lower.map((v, i) => v / parscale[i]);
|
|
576
|
+
const up = upper.map((v, i) => v / parscale[i]);
|
|
577
|
+
if (n === 0) {
|
|
578
|
+
run = { par: [], value: s.f([]), fnEvals: 0, gradEvals: 0, code: 0 };
|
|
579
|
+
message = "NOTHING TO DO";
|
|
580
|
+
break;
|
|
581
|
+
}
|
|
582
|
+
const nbd = lo.map((l, i) => {
|
|
583
|
+
const fl = Number.isFinite(l);
|
|
584
|
+
const fu = Number.isFinite(up[i]);
|
|
585
|
+
return fl && fu ? 2 : fl ? 1 : fu ? 3 : 0;
|
|
586
|
+
});
|
|
587
|
+
let iterations = 0;
|
|
588
|
+
const r = lbfgsb(n, control.lmm ?? 5, start, lo, up, nbd, control.factr ?? 1e7, control.pgtol ?? 0, (x) => {
|
|
589
|
+
const f = s.f(x);
|
|
590
|
+
if (!Number.isFinite(f))
|
|
591
|
+
throw new Error("L-BFGS-B needs finite values of 'fn'");
|
|
592
|
+
return { f, g: s.g(x, lo, up) };
|
|
593
|
+
}, () => ++iterations > maxit);
|
|
594
|
+
message = r.task;
|
|
595
|
+
const code = r.task.startsWith("NEW_X") ? 1 : r.task.startsWith("CONV") ? 0 : r.task.startsWith("WARN") ? 51 : 52;
|
|
596
|
+
run = { par: r.x, value: r.f, fnEvals: r.nfgv, gradEvals: r.nfgv, code };
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
const result = {
|
|
600
|
+
par: s.unscale(run.par),
|
|
601
|
+
value: run.value * fnscale,
|
|
602
|
+
counts: [run.fnEvals, run.gradEvals],
|
|
603
|
+
convergence: run.code,
|
|
604
|
+
message,
|
|
605
|
+
warnings,
|
|
606
|
+
};
|
|
607
|
+
if (options.hessian)
|
|
608
|
+
result.hessian = hessianOf(s, result.par);
|
|
609
|
+
return result;
|
|
610
|
+
}
|