@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/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@tangent.to/opt",
3
+ "version": "0.1.0",
4
+ "description": "Declarative numerical optimization for JavaScript (ESM): Nelder-Mead, gradient descent, momentum, RMSProp, Adam",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.js",
8
+ "browser": "./dist/index.js",
9
+ "exports": {
10
+ ".": {
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "src",
17
+ "dist",
18
+ "README.md",
19
+ "LICENSE",
20
+ "THIRD_PARTY_NOTICES.md"
21
+ ],
22
+ "scripts": {
23
+ "prepare": "npm run build:browser",
24
+ "test": "vitest",
25
+ "test:run": "vitest run",
26
+ "test:coverage": "vitest --coverage",
27
+ "test:scipy": "uv run --with scipy python3 tests_compare-to-scipy/compare_with_scipy.py",
28
+ "build:browser": "esbuild src/index.js --bundle --platform=browser --format=esm --target=es2020 --outfile=dist/index.js --sourcemap --minify --keep-names",
29
+ "watch": "esbuild src/index.js --bundle --platform=browser --format=esm --target=es2020 --outfile=dist/index.js --sourcemap --keep-names --watch",
30
+ "jsr:publish": "deno publish --allow-dirty",
31
+ "jsr:publish:dry-run": "deno publish --dry-run --allow-dirty",
32
+ "deno:lint": "deno lint src/",
33
+ "deno:fmt": "deno fmt src/",
34
+ "deno:check": "deno check src/index.js"
35
+ },
36
+ "keywords": [
37
+ "optimization",
38
+ "minimize",
39
+ "nelder-mead",
40
+ "gradient-descent",
41
+ "adam",
42
+ "numerical",
43
+ "esm",
44
+ "browser"
45
+ ],
46
+ "author": "Essi Parent",
47
+ "license": "MIT",
48
+ "homepage": "https://github.com/tangent-to/opt",
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "https://github.com/tangent-to/opt"
52
+ },
53
+ "engines": {
54
+ "node": ">=16.0.0"
55
+ },
56
+ "devDependencies": {
57
+ "esbuild": "^0.25.11",
58
+ "vitest": "^1.6.0"
59
+ }
60
+ }
package/src/blas1.js ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Dense vector helpers (BLAS level-1 style).
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
+
9
+ /**
10
+ * Dot product of two vectors
11
+ * @param {Array<number>} a
12
+ * @param {Array<number>} b
13
+ * @returns {number}
14
+ */
15
+ export function dot(a, b) {
16
+ let ret = 0;
17
+ for (let i = 0; i < a.length; ++i) {
18
+ ret += a[i] * b[i];
19
+ }
20
+ return ret;
21
+ }
22
+
23
+ /**
24
+ * Euclidean norm of a vector
25
+ * @param {Array<number>} a
26
+ * @returns {number}
27
+ */
28
+ export function norm2(a) {
29
+ return Math.sqrt(dot(a, a));
30
+ }
31
+
32
+ /**
33
+ * In-place weighted sum: out = w1 * v1 + w2 * v2
34
+ * @param {Array<number>} out - Output vector (mutated)
35
+ * @param {number} w1
36
+ * @param {Array<number>} v1
37
+ * @param {number} w2
38
+ * @param {Array<number>} v2
39
+ */
40
+ export function weightedSum(out, w1, v1, w2, v2) {
41
+ for (let i = 0; i < out.length; ++i) {
42
+ out[i] = w1 * v1[i] + w2 * v2[i];
43
+ }
44
+ }
45
+
46
+ /**
47
+ * In-place scale: out = c * value
48
+ * @param {Array<number>} out - Output vector (mutated)
49
+ * @param {Array<number>} value
50
+ * @param {number} c
51
+ */
52
+ export function scale(out, value, c) {
53
+ for (let i = 0; i < out.length; ++i) {
54
+ out[i] = value[i] * c;
55
+ }
56
+ }
package/src/bounds.js ADDED
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Box bounds via MINUIT-style parameter transforms.
3
+ *
4
+ * A bounded external parameter is mapped onto an unbounded internal one:
5
+ *
6
+ * both bounds: ext = lo + (hi - lo) * (sin(int) + 1) / 2
7
+ * lower only: ext = lo - 1 + sqrt(int^2 + 1)
8
+ * upper only: ext = hi + 1 - sqrt(int^2 + 1)
9
+ *
10
+ * Optimizers run in internal space; gradients are chain-ruled by the
11
+ * transform derivative d ext / d int. This bounds every method at once
12
+ * (L-BFGS, Nelder-Mead, Levenberg-Marquardt, ...) with no per-method
13
+ * machinery — the approach MINUIT and lmfit have used for decades.
14
+ *
15
+ * Note: as an optimum approaches a bound the transform derivative goes to
16
+ * zero, so active bounds are reached asymptotically (typically to 1e-4
17
+ * or better of the bound, not exactly on it).
18
+ */
19
+
20
+ const FREE = 0;
21
+ const LOWER = 1;
22
+ const UPPER = 2;
23
+ const BOTH = 3;
24
+
25
+ /**
26
+ * Build a bounds transform, or return null when every parameter is free.
27
+ *
28
+ * @param {Array<Array<number|null>>} bounds - Per-parameter [lo, hi];
29
+ * null/undefined/±Infinity mean unbounded on that side
30
+ * @param {number} n - Number of parameters
31
+ * @returns {Object|null} {toInternal, toExternal, dExtDInt, clamp}
32
+ */
33
+ export function makeBoundsTransform(bounds, n) {
34
+ if (!Array.isArray(bounds) || bounds.length !== n) {
35
+ throw new Error(`bounds must be an array of ${n} [lo, hi] pairs`);
36
+ }
37
+
38
+ const kind = new Array(n);
39
+ const lo = new Array(n);
40
+ const hi = new Array(n);
41
+ let anyBounded = false;
42
+
43
+ for (let i = 0; i < n; i++) {
44
+ const pair = bounds[i] || [null, null];
45
+ const l = pair[0] === null || pair[0] === undefined || pair[0] === -Infinity ? null : pair[0];
46
+ const h = pair[1] === null || pair[1] === undefined || pair[1] === Infinity ? null : pair[1];
47
+ if (l !== null && h !== null && !(l < h)) {
48
+ throw new Error(`bounds[${i}]: lower bound must be strictly below upper (got [${l}, ${h}])`);
49
+ }
50
+ lo[i] = l;
51
+ hi[i] = h;
52
+ kind[i] = l === null ? (h === null ? FREE : UPPER) : h === null ? LOWER : BOTH;
53
+ if (kind[i] !== FREE) anyBounded = true;
54
+ }
55
+
56
+ if (!anyBounded) return null;
57
+
58
+ /** Nudge a point strictly inside the bounds (transforms stall exactly on a bound). */
59
+ function clamp(xExt) {
60
+ const out = xExt.slice();
61
+ for (let i = 0; i < n; i++) {
62
+ if (kind[i] === BOTH) {
63
+ const eps = (hi[i] - lo[i]) * 1e-8;
64
+ out[i] = Math.min(Math.max(out[i], lo[i] + eps), hi[i] - eps);
65
+ } else if (kind[i] === LOWER) {
66
+ const eps = 1e-8 * Math.max(1, Math.abs(lo[i]));
67
+ out[i] = Math.max(out[i], lo[i] + eps);
68
+ } else if (kind[i] === UPPER) {
69
+ const eps = 1e-8 * Math.max(1, Math.abs(hi[i]));
70
+ out[i] = Math.min(out[i], hi[i] - eps);
71
+ }
72
+ }
73
+ return out;
74
+ }
75
+
76
+ function toInternal(xExt) {
77
+ const xc = clamp(xExt);
78
+ const out = new Array(n);
79
+ for (let i = 0; i < n; i++) {
80
+ switch (kind[i]) {
81
+ case BOTH:
82
+ out[i] = Math.asin(2 * (xc[i] - lo[i]) / (hi[i] - lo[i]) - 1);
83
+ break;
84
+ case LOWER:
85
+ out[i] = Math.sqrt((xc[i] - lo[i] + 1) ** 2 - 1);
86
+ break;
87
+ case UPPER:
88
+ out[i] = Math.sqrt((hi[i] - xc[i] + 1) ** 2 - 1);
89
+ break;
90
+ default:
91
+ out[i] = xc[i];
92
+ }
93
+ }
94
+ return out;
95
+ }
96
+
97
+ function toExternal(xInt) {
98
+ const out = new Array(n);
99
+ for (let i = 0; i < n; i++) {
100
+ switch (kind[i]) {
101
+ case BOTH:
102
+ out[i] = lo[i] + (hi[i] - lo[i]) * (Math.sin(xInt[i]) + 1) / 2;
103
+ break;
104
+ case LOWER:
105
+ out[i] = lo[i] - 1 + Math.sqrt(xInt[i] * xInt[i] + 1);
106
+ break;
107
+ case UPPER:
108
+ out[i] = hi[i] + 1 - Math.sqrt(xInt[i] * xInt[i] + 1);
109
+ break;
110
+ default:
111
+ out[i] = xInt[i];
112
+ }
113
+ }
114
+ return out;
115
+ }
116
+
117
+ /** Derivative d ext_i / d int_i at an internal point. */
118
+ function dExtDInt(xInt) {
119
+ const out = new Array(n);
120
+ for (let i = 0; i < n; i++) {
121
+ switch (kind[i]) {
122
+ case BOTH:
123
+ out[i] = (hi[i] - lo[i]) / 2 * Math.cos(xInt[i]);
124
+ break;
125
+ case LOWER:
126
+ out[i] = xInt[i] / Math.sqrt(xInt[i] * xInt[i] + 1);
127
+ break;
128
+ case UPPER:
129
+ out[i] = -xInt[i] / Math.sqrt(xInt[i] * xInt[i] + 1);
130
+ break;
131
+ default:
132
+ out[i] = 1;
133
+ }
134
+ }
135
+ return out;
136
+ }
137
+
138
+ return { toInternal, toExternal, dExtDInt, clamp };
139
+ }
140
+
141
+ /**
142
+ * Wrap an objective (and optional gradient) so optimizers can run in
143
+ * internal space. Supports both the scalar form (x) => number and the
144
+ * combined form (x) => {loss, gradient}.
145
+ *
146
+ * @param {Function} f - External objective
147
+ * @param {Function|undefined} grad - External gradient
148
+ * @param {Object} T - Transform from makeBoundsTransform
149
+ * @returns {{f: Function, grad: Function|undefined}}
150
+ */
151
+ export function wrapObjective(f, grad, T) {
152
+ const fInt = (xInt) => {
153
+ const out = f(T.toExternal(xInt));
154
+ if (out !== null && typeof out === 'object' && 'loss' in out) {
155
+ const d = T.dExtDInt(xInt);
156
+ return { loss: out.loss, gradient: out.gradient.map((gi, i) => gi * d[i]) };
157
+ }
158
+ return out;
159
+ };
160
+ const gradInt = grad
161
+ ? (xInt) => {
162
+ const d = T.dExtDInt(xInt);
163
+ return grad(T.toExternal(xInt)).map((gi, i) => gi * d[i]);
164
+ }
165
+ : undefined;
166
+ return { f: fInt, grad: gradInt };
167
+ }
168
+
169
+ /**
170
+ * Wrap residuals (and optional Jacobian) for bounded least squares.
171
+ *
172
+ * @param {Function} residuals - External residuals (p) => Array<number>
173
+ * @param {Function|undefined} jacobian - External Jacobian (p) => m-by-n
174
+ * @param {Object} T - Transform from makeBoundsTransform
175
+ * @returns {{residuals: Function, jacobian: Function|undefined}}
176
+ */
177
+ export function wrapResiduals(residuals, jacobian, T) {
178
+ const resInt = (pInt) => residuals(T.toExternal(pInt));
179
+ const jacInt = jacobian
180
+ ? (pInt) => {
181
+ const d = T.dExtDInt(pInt);
182
+ const J = jacobian(T.toExternal(pInt));
183
+ return J.map((row) => row.map((v, i) => v * d[i]));
184
+ }
185
+ : undefined;
186
+ return { residuals: resInt, jacobian: jacInt };
187
+ }
package/src/compat.js ADDED
@@ -0,0 +1,148 @@
1
+ /**
2
+ * tangent/ds compatibility layer.
3
+ *
4
+ * Drop-in equivalents of the classes formerly in ds.core.optimize, so that
5
+ * tangent/ds can re-export this module unchanged:
6
+ *
7
+ * optimizer.minimize(lossFn, x0, options) => {x, history}
8
+ *
9
+ * where lossFn is the combined form (x) => {loss, gradient}. New code should
10
+ * prefer the declarative minimize() or the functional methods directly.
11
+ */
12
+
13
+ import { adam, gradientDescent, momentumDescent, rmsprop } from './gradient.js';
14
+
15
+ class Optimizer {
16
+ constructor(options = {}) {
17
+ this.learningRate = options.learningRate || 0.01;
18
+ this.maxIter = options.maxIter || 1000;
19
+ this.tol = options.tol || 1e-6;
20
+ this.verbose = options.verbose || false;
21
+ }
22
+
23
+ /**
24
+ * Minimize a loss function
25
+ * @param {Function} lossFn - Function that returns {loss, gradient}
26
+ * @param {Array<number>} x0 - Initial parameters
27
+ * @param {Object} options - Additional options
28
+ * @returns {Object} {x, history}
29
+ */
30
+ minimize(_lossFn, _x0, _options = {}) {
31
+ throw new Error('minimize() must be implemented by subclass');
32
+ }
33
+
34
+ _options(options) {
35
+ return {
36
+ learningRate: this.learningRate,
37
+ maxIter: options.maxIter || this.maxIter,
38
+ tol: options.tol || this.tol,
39
+ verbose: this.verbose,
40
+ };
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Gradient Descent (batch; optional backtracking line search)
46
+ */
47
+ export class GradientDescent extends Optimizer {
48
+ constructor(options = {}) {
49
+ super(options);
50
+ this.stochastic = options.stochastic || false;
51
+ this.batchSize = options.batchSize || 32;
52
+ this.lineSearch = options.lineSearch || false;
53
+ }
54
+
55
+ minimize(lossFn, x0, options = {}) {
56
+ const { x, history } = gradientDescent(lossFn, x0, {
57
+ ...this._options(options),
58
+ lineSearch: this.lineSearch,
59
+ });
60
+ return { x, history };
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Momentum Optimizer
66
+ */
67
+ export class MomentumOptimizer extends Optimizer {
68
+ constructor(options = {}) {
69
+ super(options);
70
+ this.momentum = options.momentum || 0.9;
71
+ }
72
+
73
+ minimize(lossFn, x0, options = {}) {
74
+ const { x, history } = momentumDescent(lossFn, x0, {
75
+ ...this._options(options),
76
+ momentum: this.momentum,
77
+ });
78
+ return { x, history: { loss: history.loss, gradNorm: history.gradNorm } };
79
+ }
80
+ }
81
+
82
+ /**
83
+ * RMSProp Optimizer
84
+ */
85
+ export class RMSProp extends Optimizer {
86
+ constructor(options = {}) {
87
+ super(options);
88
+ this.decay = options.decay || 0.9;
89
+ this.epsilon = options.epsilon || 1e-8;
90
+ }
91
+
92
+ minimize(lossFn, x0, options = {}) {
93
+ const { x, history } = rmsprop(lossFn, x0, {
94
+ ...this._options(options),
95
+ decay: this.decay,
96
+ epsilon: this.epsilon,
97
+ });
98
+ return { x, history: { loss: history.loss, gradNorm: history.gradNorm } };
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Adam Optimizer (Adaptive Moment Estimation)
104
+ */
105
+ export class AdamOptimizer extends Optimizer {
106
+ constructor(options = {}) {
107
+ super(options);
108
+ this.beta1 = options.beta1 || 0.9;
109
+ this.beta2 = options.beta2 || 0.999;
110
+ this.epsilon = options.epsilon || 1e-8;
111
+ }
112
+
113
+ minimize(lossFn, x0, options = {}) {
114
+ const { x, history } = adam(lossFn, x0, {
115
+ ...this._options(options),
116
+ beta1: this.beta1,
117
+ beta2: this.beta2,
118
+ epsilon: this.epsilon,
119
+ });
120
+ return { x, history: { loss: history.loss, gradNorm: history.gradNorm } };
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Convenience function to create optimizer by name
126
+ * @param {string} name - Optimizer name
127
+ * @param {Object} options - Optimizer options
128
+ * @returns {Optimizer} Optimizer instance
129
+ */
130
+ export function createOptimizer(name, options = {}) {
131
+ const optimizers = {
132
+ gd: GradientDescent,
133
+ gradient_descent: GradientDescent,
134
+ sgd: GradientDescent,
135
+ momentum: MomentumOptimizer,
136
+ rmsprop: RMSProp,
137
+ adam: AdamOptimizer,
138
+ };
139
+
140
+ const OptimizerClass = optimizers[name.toLowerCase()];
141
+ if (!OptimizerClass) {
142
+ throw new Error(
143
+ `Unknown optimizer: ${name}. Available: ${Object.keys(optimizers).join(', ')}`,
144
+ );
145
+ }
146
+
147
+ return new OptimizerClass(options);
148
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Objective-function normalization.
3
+ *
4
+ * All optimizers work against a single evaluator contract:
5
+ * evaluate(x) => { loss: number, gradient: Array<number> }
6
+ *
7
+ * Users may supply either:
8
+ * - f: (x) => number, plus an optional grad: (x) => Array<number>
9
+ * - f: (x) => { loss, gradient } (tangent/ds loss-function style)
10
+ *
11
+ * When no gradient is available, central finite differences are used.
12
+ */
13
+
14
+ import { numericalGradient } from './numdiff.js';
15
+
16
+ /**
17
+ * Build a normalized evaluator from a user-supplied objective.
18
+ *
19
+ * @param {Function} f - Objective: (x) => number or (x) => {loss, gradient}
20
+ * @param {Function} [grad] - Optional gradient: (x) => Array<number>
21
+ * @param {Object} [options]
22
+ * @param {number} [options.h] - Finite-difference step size
23
+ * @returns {Function} evaluate(x) => {loss, gradient}
24
+ */
25
+ export function makeEvaluator(f, grad, options = {}) {
26
+ return function evaluate(x) {
27
+ const out = f(x);
28
+
29
+ // tangent/ds combined form: f returns {loss, gradient}
30
+ if (out !== null && typeof out === 'object' && 'loss' in out) {
31
+ return out;
32
+ }
33
+
34
+ if (typeof out !== 'number') {
35
+ throw new Error(
36
+ 'Objective must return a number or an object of the form {loss, gradient}',
37
+ );
38
+ }
39
+
40
+ return {
41
+ loss: out,
42
+ gradient: grad ? grad(x) : numericalGradient(f, x, options),
43
+ };
44
+ };
45
+ }
46
+
47
+ /**
48
+ * Build a scalar-only evaluator (for derivative-free methods).
49
+ *
50
+ * @param {Function} f - Objective: (x) => number or (x) => {loss, gradient}
51
+ * @returns {Function} (x) => number
52
+ */
53
+ export function makeScalarEvaluator(f) {
54
+ return function evaluateScalar(x) {
55
+ const out = f(x);
56
+ if (out !== null && typeof out === 'object' && 'loss' in out) {
57
+ return out.loss;
58
+ }
59
+ if (typeof out !== 'number') {
60
+ throw new Error(
61
+ 'Objective must return a number or an object of the form {loss, gradient}',
62
+ );
63
+ }
64
+ return out;
65
+ };
66
+ }