@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.
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Declarative minimization front-end.
3
+ *
4
+ * A single entry point in the tangent/ds options-object style:
5
+ *
6
+ * const result = minimize({
7
+ * f: (x) => (x[0] - 1) ** 2 + (x[1] + 2) ** 2,
8
+ * x0: [0, 0],
9
+ * method: 'neldermead', // default
10
+ * maxIter: 500,
11
+ * });
12
+ * // result: {x, fx, iterations, converged, method, ...}
13
+ *
14
+ * Gradient-based methods use `grad` when provided, the combined
15
+ * (x) => {loss, gradient} form when f returns one, and central finite
16
+ * differences otherwise.
17
+ */
18
+
19
+ import { nelderMead } from './neldermead.js';
20
+ import { lbfgs } from './lbfgs.js';
21
+ import { adam, gradientDescent } from './gradient.js';
22
+ import { makeBoundsTransform, wrapObjective } from './bounds.js';
23
+
24
+ /**
25
+ * The curated roster: textbook-intuitive plus modern best practice.
26
+ * - neldermead: derivative-free, geometric intuition
27
+ * - lbfgs: the modern default for smooth objectives
28
+ * - gd: the teaching baseline for gradient descent
29
+ * - adam: the modern default for stochastic/ML-style objectives
30
+ * momentumDescent and rmsprop remain importable (and in the ds compat
31
+ * layer) but are deliberately not part of the declarative roster.
32
+ */
33
+ const METHODS = {
34
+ neldermead: nelderMead,
35
+ 'nelder-mead': nelderMead,
36
+ lbfgs: lbfgs,
37
+ 'l-bfgs': lbfgs,
38
+ gd: gradientDescent,
39
+ sgd: gradientDescent,
40
+ gradient_descent: gradientDescent,
41
+ adam: adam,
42
+ };
43
+
44
+ /**
45
+ * List the available minimization methods.
46
+ * @returns {Array<string>}
47
+ */
48
+ export function methods() {
49
+ return Object.keys(METHODS);
50
+ }
51
+
52
+ /**
53
+ * Minimize a scalar function of one or more variables.
54
+ *
55
+ * @param {Object} spec
56
+ * @param {Function} spec.f - Objective: (x) => number or (x) => {loss, gradient}
57
+ * @param {Array<number>} spec.x0 - Initial parameters
58
+ * @param {string} [spec.method='neldermead'] - One of methods()
59
+ * @param {Function} [spec.grad] - Gradient: (x) => Array<number> (gradient methods only)
60
+ * @param {...*} [spec.options] - Remaining keys are passed to the method
61
+ * (maxIter, tol, learningRate, fTol, xTol, history, verbose, ...)
62
+ * @returns {Object} {x, fx, iterations, converged, method, ...}
63
+ */
64
+ export function minimize(spec = {}) {
65
+ const { f, x0, method = 'neldermead', bounds, ...options } = spec;
66
+
67
+ if (typeof f !== 'function') {
68
+ throw new Error('minimize: spec.f must be a function');
69
+ }
70
+ if (!Array.isArray(x0) || x0.length === 0 || x0.some((v) => typeof v !== 'number')) {
71
+ throw new Error('minimize: spec.x0 must be a non-empty array of numbers');
72
+ }
73
+
74
+ const key = String(method).toLowerCase();
75
+ const minimizer = METHODS[key];
76
+ if (!minimizer) {
77
+ throw new Error(
78
+ `minimize: unknown method '${method}'. Available: ${Object.keys(METHODS).join(', ')}`,
79
+ );
80
+ }
81
+
82
+ // Box bounds: run the method in MINUIT-transformed internal space.
83
+ // history/gradNorm are then reported in internal coordinates.
84
+ const T = bounds ? makeBoundsTransform(bounds, x0.length) : null;
85
+ if (T) {
86
+ const wrapped = wrapObjective(f, options.grad, T);
87
+ const result = minimizer(wrapped.f, T.toInternal(x0), { ...options, grad: wrapped.grad });
88
+ result.x = T.toExternal(result.x);
89
+ result.method = key;
90
+ result.bounded = true;
91
+ return result;
92
+ }
93
+
94
+ const result = minimizer(f, x0, options);
95
+ result.method = key;
96
+ return result;
97
+ }
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Nelder-Mead downhill simplex minimization (derivative-free).
3
+ *
4
+ * Ported from fmin (https://github.com/benfred/fmin),
5
+ * Copyright 2016, Ben Frederickson, BSD-3-Clause.
6
+ * See THIRD_PARTY_NOTICES.md.
7
+ *
8
+ * Changes from the original: unified options/result shape, iteration and
9
+ * function-evaluation counters, explicit convergence flag, separate fTol/xTol
10
+ * options (the original read both from `minErrorDelta`), and support for
11
+ * objectives in tangent/ds combined form ((x) => {loss, gradient}).
12
+ */
13
+
14
+ import { weightedSum } from './blas1.js';
15
+ import { makeScalarEvaluator } from './evaluate.js';
16
+
17
+ /**
18
+ * Minimize a function using the Nelder-Mead downhill simplex method.
19
+ *
20
+ * @param {Function} f - Objective: (x) => number (or (x) => {loss, ...})
21
+ * @param {Array<number>} x0 - Initial parameters
22
+ * @param {Object} [options]
23
+ * @param {number} [options.maxIter=200*n] - Maximum iterations
24
+ * @param {number} [options.fTol=1e-6] - Convergence tolerance on f spread across the simplex
25
+ * @param {number} [options.xTol=1e-5] - Convergence tolerance on x spread across the simplex
26
+ * @param {number} [options.rho=1] - Reflection coefficient
27
+ * @param {number} [options.chi=2] - Expansion coefficient
28
+ * @param {number} [options.psi=-0.5] - Contraction coefficient
29
+ * @param {number} [options.sigma=0.5] - Reduction (shrink) coefficient
30
+ * @param {number} [options.nonZeroDelta=1.05] - Relative perturbation for nonzero x0 entries
31
+ * @param {number} [options.zeroDelta=1e-3] - Absolute perturbation for zero x0 entries
32
+ * @param {boolean} [options.history=false] - Record {x, fx, simplex} per iteration
33
+ * @returns {Object} {x, fx, iterations, fevals, converged, history?}
34
+ */
35
+ export function nelderMead(f, x0, options = {}) {
36
+ const n = x0.length;
37
+ const maxIter = options.maxIter || n * 200;
38
+ const fTol = options.fTol || options.tol || 1e-6;
39
+ const xTol = options.xTol || 1e-5;
40
+ const nonZeroDelta = options.nonZeroDelta || 1.05;
41
+ const zeroDelta = options.zeroDelta || 1e-3;
42
+ const rho = options.rho !== undefined ? options.rho : 1;
43
+ const chi = options.chi !== undefined ? options.chi : 2;
44
+ const psi = options.psi !== undefined ? options.psi : -0.5;
45
+ const sigma = options.sigma !== undefined ? options.sigma : 0.5;
46
+ const trackHistory = options.history || false;
47
+
48
+ const evaluateScalar = makeScalarEvaluator(f);
49
+ let fevals = 0;
50
+ const fn = (x) => {
51
+ fevals++;
52
+ return evaluateScalar(x);
53
+ };
54
+
55
+ // Initialize the simplex: x0 plus one perturbed point per dimension.
56
+ // Each vertex is an array with `fx` and `id` bookkeeping properties.
57
+ const simplex = new Array(n + 1);
58
+ simplex[0] = x0.slice();
59
+ simplex[0].fx = fn(x0);
60
+ simplex[0].id = 0;
61
+ for (let i = 0; i < n; ++i) {
62
+ const point = x0.slice();
63
+ point[i] = point[i] ? point[i] * nonZeroDelta : zeroDelta;
64
+ simplex[i + 1] = point;
65
+ simplex[i + 1].fx = fn(point);
66
+ simplex[i + 1].id = i + 1;
67
+ }
68
+
69
+ function updateSimplex(value) {
70
+ for (let i = 0; i < value.length; i++) {
71
+ simplex[n][i] = value[i];
72
+ }
73
+ simplex[n].fx = value.fx;
74
+ }
75
+
76
+ const sortOrder = (a, b) => a.fx - b.fx;
77
+
78
+ const centroid = x0.slice();
79
+ const reflected = x0.slice();
80
+ const contracted = x0.slice();
81
+ const expanded = x0.slice();
82
+
83
+ const history = trackHistory ? [] : null;
84
+ let converged = false;
85
+ let iteration = 0;
86
+
87
+ for (; iteration < maxIter; ++iteration) {
88
+ simplex.sort(sortOrder);
89
+
90
+ if (trackHistory) {
91
+ // Copy the simplex (later iterations mutate it) and sort by vertex id
92
+ // for a consistent order between iterations.
93
+ const sortedSimplex = simplex.map((v) => {
94
+ const state = v.slice();
95
+ state.fx = v.fx;
96
+ state.id = v.id;
97
+ return state;
98
+ });
99
+ sortedSimplex.sort((a, b) => a.id - b.id);
100
+ history.push({
101
+ x: simplex[0].slice(),
102
+ fx: simplex[0].fx,
103
+ simplex: sortedSimplex,
104
+ });
105
+ }
106
+
107
+ let maxDiff = 0;
108
+ for (let i = 0; i < n; ++i) {
109
+ maxDiff = Math.max(maxDiff, Math.abs(simplex[0][i] - simplex[1][i]));
110
+ }
111
+
112
+ if (Math.abs(simplex[0].fx - simplex[n].fx) < fTol && maxDiff < xTol) {
113
+ converged = true;
114
+ break;
115
+ }
116
+
117
+ // Centroid of all but the worst point
118
+ for (let i = 0; i < n; ++i) {
119
+ centroid[i] = 0;
120
+ for (let j = 0; j < n; ++j) {
121
+ centroid[i] += simplex[j][i];
122
+ }
123
+ centroid[i] /= n;
124
+ }
125
+
126
+ // Reflect the worst point past the centroid
127
+ const worst = simplex[n];
128
+ weightedSum(reflected, 1 + rho, centroid, -rho, worst);
129
+ reflected.fx = fn(reflected);
130
+
131
+ if (reflected.fx < simplex[0].fx) {
132
+ // Best point seen so far: try expanding
133
+ weightedSum(expanded, 1 + chi, centroid, -chi, worst);
134
+ expanded.fx = fn(expanded);
135
+ if (expanded.fx < reflected.fx) {
136
+ updateSimplex(expanded);
137
+ } else {
138
+ updateSimplex(reflected);
139
+ }
140
+ } else if (reflected.fx >= simplex[n - 1].fx) {
141
+ // Worse than the second worst: contract
142
+ let shouldReduce = false;
143
+
144
+ if (reflected.fx > worst.fx) {
145
+ // Inside contraction
146
+ weightedSum(contracted, 1 + psi, centroid, -psi, worst);
147
+ contracted.fx = fn(contracted);
148
+ if (contracted.fx < worst.fx) {
149
+ updateSimplex(contracted);
150
+ } else {
151
+ shouldReduce = true;
152
+ }
153
+ } else {
154
+ // Outside contraction
155
+ weightedSum(contracted, 1 - psi * rho, centroid, psi * rho, worst);
156
+ contracted.fx = fn(contracted);
157
+ if (contracted.fx < reflected.fx) {
158
+ updateSimplex(contracted);
159
+ } else {
160
+ shouldReduce = true;
161
+ }
162
+ }
163
+
164
+ if (shouldReduce) {
165
+ if (sigma >= 1) break;
166
+ // Shrink the simplex toward the best point
167
+ for (let i = 1; i < simplex.length; ++i) {
168
+ weightedSum(simplex[i], 1 - sigma, simplex[0], sigma, simplex[i]);
169
+ simplex[i].fx = fn(simplex[i]);
170
+ }
171
+ }
172
+ } else {
173
+ updateSimplex(reflected);
174
+ }
175
+ }
176
+
177
+ simplex.sort(sortOrder);
178
+
179
+ const result = {
180
+ x: Array.from(simplex[0]),
181
+ fx: simplex[0].fx,
182
+ iterations: iteration,
183
+ nfev: fevals,
184
+ fevals, // deprecated alias for nfev
185
+ converged,
186
+ success: converged, // suite-wide "did it work" flag (matches ode)
187
+ };
188
+ if (trackHistory) {
189
+ result.history = history;
190
+ }
191
+ return result;
192
+ }
package/src/numdiff.js ADDED
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Numerical differentiation utilities
3
+ */
4
+
5
+ /**
6
+ * Approximate the gradient of a scalar function by central finite differences.
7
+ *
8
+ * @param {Function} f - Scalar function (x: Array<number>) => number
9
+ * @param {Array<number>} x - Point at which to evaluate the gradient
10
+ * @param {Object} [options]
11
+ * @param {number} [options.h=1e-6] - Step size
12
+ * @returns {Array<number>} Gradient approximation
13
+ */
14
+ export function numericalGradient(f, x, options = {}) {
15
+ const h = options.h || 1e-6;
16
+ const n = x.length;
17
+ const grad = new Array(n);
18
+ const xi = x.slice();
19
+
20
+ for (let i = 0; i < n; i++) {
21
+ xi[i] = x[i] + h;
22
+ const fPlus = f(xi);
23
+ xi[i] = x[i] - h;
24
+ const fMinus = f(xi);
25
+ xi[i] = x[i];
26
+ grad[i] = (fPlus - fMinus) / (2 * h);
27
+ }
28
+
29
+ return grad;
30
+ }
31
+
32
+ /**
33
+ * Central finite-difference Jacobian of a vector-valued function.
34
+ * Per-component step h_j = step * max(1, |x_j|).
35
+ *
36
+ * @param {Function} f - (x: Array<number>) => Array<number> of length m
37
+ * @param {Array<number>} x - Point of length n
38
+ * @param {Object} [options]
39
+ * @param {number} [options.step=1e-6] - Relative step size
40
+ * @returns {Array<Array<number>>} m-by-n Jacobian
41
+ */
42
+ export function numericalJacobian(f, x, options = {}) {
43
+ const step = options.step || 1e-6;
44
+ const n = x.length;
45
+ const xi = x.slice();
46
+ const cols = new Array(n);
47
+ let m = -1;
48
+ for (let j = 0; j < n; j++) {
49
+ const h = step * Math.max(1, Math.abs(x[j]));
50
+ xi[j] = x[j] + h;
51
+ const fPlus = f(xi);
52
+ xi[j] = x[j] - h;
53
+ const fMinus = f(xi);
54
+ xi[j] = x[j];
55
+ if (m < 0) m = fPlus.length;
56
+ const col = new Array(m);
57
+ for (let i = 0; i < m; i++) col[i] = (fPlus[i] - fMinus[i]) / (2 * h);
58
+ cols[j] = col;
59
+ }
60
+ // Transpose columns into an m-by-n row-major matrix
61
+ const J = new Array(m);
62
+ for (let i = 0; i < m; i++) {
63
+ J[i] = new Array(n);
64
+ for (let j = 0; j < n; j++) J[i][j] = cols[j][i];
65
+ }
66
+ return J;
67
+ }
68
+
69
+ /**
70
+ * Central finite-difference Hessian of a scalar function.
71
+ *
72
+ * @param {Function} f - (x: Array<number>) => number
73
+ * @param {Array<number>} x - Point of length n
74
+ * @param {Object} [options]
75
+ * @param {number} [options.step=1e-4] - Relative step size
76
+ * @returns {Array<Array<number>>} n-by-n symmetric Hessian
77
+ */
78
+ export function numericalHessian(f, x, options = {}) {
79
+ const h = options.step || 1e-4;
80
+ const n = x.length;
81
+ const step = x.map((v) => h * Math.max(1, Math.abs(v)));
82
+ const f0 = f(x);
83
+ const H = Array.from({ length: n }, () => new Array(n).fill(0));
84
+ const e = x.slice();
85
+ for (let i = 0; i < n; i++) {
86
+ for (let j = i; j < n; j++) {
87
+ if (i === j) {
88
+ e[i] = x[i] + step[i];
89
+ const fp = f(e);
90
+ e[i] = x[i] - step[i];
91
+ const fm = f(e);
92
+ e[i] = x[i];
93
+ H[i][i] = (fp - 2 * f0 + fm) / (step[i] * step[i]);
94
+ } else {
95
+ e[i] = x[i] + step[i];
96
+ e[j] = x[j] + step[j];
97
+ const fpp = f(e);
98
+ e[j] = x[j] - step[j];
99
+ const fpm = f(e);
100
+ e[i] = x[i] - step[i];
101
+ const fmm = f(e);
102
+ e[j] = x[j] + step[j];
103
+ const fmp = f(e);
104
+ e[i] = x[i];
105
+ e[j] = x[j];
106
+ H[i][j] = (fpp - fpm - fmp + fmm) / (4 * step[i] * step[j]);
107
+ H[j][i] = H[i][j];
108
+ }
109
+ }
110
+ }
111
+ return H;
112
+ }