@numero-uno-jpn/rstats 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.ja.md +11 -9
  3. package/README.md +12 -9
  4. package/dist/chunks/chunk-56AMJQ27.js +2 -0
  5. package/dist/chunks/{chunk-O5CMNUJL.js → chunk-76FLTZVF.js} +2 -2
  6. package/dist/chunks/chunk-AIEPW6DX.js +2 -0
  7. package/dist/chunks/chunk-B6KJ4RWG.js +2 -0
  8. package/dist/chunks/{chunk-2TVHT4PF.js → chunk-B7XZMIQO.js} +2 -2
  9. package/dist/chunks/chunk-BJMPSDJ7.js +2 -0
  10. package/dist/chunks/chunk-CB7STL5Z.js +2 -0
  11. package/dist/chunks/{chunk-ZL7EAPO5.js → chunk-CUT3IHMY.js} +1 -1
  12. package/dist/chunks/{chunk-FLITCXLY.js → chunk-CZUOG2U5.js} +2 -2
  13. package/dist/chunks/chunk-FQRNZEH2.js +2 -0
  14. package/dist/chunks/{chunk-BMEO5X5F.js → chunk-HORF36FD.js} +2 -2
  15. package/dist/chunks/{chunk-OZLDZOOA.js → chunk-HSJ4OT3H.js} +1 -1
  16. package/dist/chunks/chunk-J7ZVV4DN.js +2 -0
  17. package/dist/chunks/{chunk-RSTU6CX7.js → chunk-JXEXOD7K.js} +2 -2
  18. package/dist/chunks/chunk-KSH43GX4.js +2 -0
  19. package/dist/chunks/chunk-LMRCFKVK.js +2 -0
  20. package/dist/chunks/{chunk-2I7Z7L5J.js → chunk-MOJ2KIQE.js} +2 -2
  21. package/dist/chunks/{chunk-F7G74UNI.js → chunk-PCTRVBEJ.js} +2 -2
  22. package/dist/chunks/chunk-PLQQ4VFN.js +2 -0
  23. package/dist/chunks/{chunk-ABSUQPOG.js → chunk-QWDK3ZC2.js} +2 -2
  24. package/dist/chunks/chunk-R5BMFVIH.js +2 -0
  25. package/dist/chunks/chunk-R7F7ELS7.js +3 -0
  26. package/dist/chunks/{chunk-3PCHPKBD.js → chunk-RIP2RKAW.js} +2 -2
  27. package/dist/chunks/chunk-RX6MZO2Y.js +2 -0
  28. package/dist/chunks/{chunk-Z2XN4NN7.js → chunk-SDT3YHAG.js} +2 -2
  29. package/dist/chunks/{chunk-WAMHZ47G.js → chunk-THSV22QF.js} +2 -2
  30. package/dist/chunks/{chunk-7ZNFRZO4.js → chunk-TY3IFCLI.js} +2 -2
  31. package/dist/chunks/{chunk-SFZF44G6.js → chunk-V2Y2W7LE.js} +2 -2
  32. package/dist/chunks/{chunk-AHFMBHZW.js → chunk-VALULDEX.js} +1 -1
  33. package/dist/chunks/chunk-VQOU7U7R.js +2 -0
  34. package/dist/chunks/{chunk-KAAUNR3G.js → chunk-YKNRDPIB.js} +1 -1
  35. package/dist/chunks/chunk-YVJ4LDDE.js +2 -0
  36. package/dist/descriptive.js +2 -2
  37. package/dist/distributions.js +2 -2
  38. package/dist/entries/regression.d.ts +3 -0
  39. package/dist/entries/regression.js +6 -0
  40. package/dist/linalg.js +2 -2
  41. package/dist/mixed.js +2 -2
  42. package/dist/models/nls.d.ts +286 -0
  43. package/dist/models/nls.js +1007 -0
  44. package/dist/models/nlsFormula.d.ts +37 -0
  45. package/dist/models/nlsFormula.js +295 -0
  46. package/dist/models/polr.d.ts +341 -0
  47. package/dist/models/polr.js +1028 -0
  48. package/dist/models/rlm.d.ts +282 -0
  49. package/dist/models/rlm.js +766 -0
  50. package/dist/numerics.js +2 -2
  51. package/dist/regression.js +3 -0
  52. package/dist/rstats.js +1 -1
  53. package/dist/special.js +2 -2
  54. package/dist/tests.js +14 -14
  55. package/llms.txt +5 -1
  56. package/package.json +6 -1
  57. package/dist/chunks/chunk-55XSRONZ.js +0 -3
  58. package/dist/chunks/chunk-5AITXV3T.js +0 -2
  59. package/dist/chunks/chunk-BJTGQ52J.js +0 -2
  60. package/dist/chunks/chunk-KND2BFD5.js +0 -2
  61. package/dist/chunks/chunk-N2PNW4HR.js +0 -2
  62. package/dist/chunks/chunk-NVIJXWS6.js +0 -2
  63. package/dist/chunks/chunk-TPBVVP32.js +0 -2
  64. package/dist/chunks/chunk-XNWSQVXS.js +0 -2
@@ -0,0 +1,1007 @@
1
+ // Nonlinear least-squares fitting and its public summaries.
2
+ // Independently derived from Bates & Watts (1988), Bates & Chambers (1992),
3
+ // Golub & Pereyra (1973), and oracle/nls-behaviour.md. No R or PORT source was used.
4
+ import { pt1, qt1 } from "../distributions/t.js";
5
+ import { pf1, qf1 } from "../distributions/f.js";
6
+ import { reported } from "../internal/warnings.js";
7
+ import { evaluateNlsExpression, evaluateNlsWithGradient, parseNlsFormula, } from "./nlsFormula.js";
8
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
9
+ import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
10
+ const NLS_KEYS = ["start", "algorithm", "weights", "lower", "upper", "control"];
11
+ const NLS_CONTROL_KEYS = ["maxiter", "tol", "minFactor", "warnOnly", "scaleOffset"];
12
+ const NLS_PREDICT_KEYS = ["newdata"];
13
+ const NLS_CONFINT_KEYS = ["method", "level", "parm"];
14
+ function column(data, name) {
15
+ const value = data[name];
16
+ if (value === undefined)
17
+ throw new Error("data column '" + name + "' was not found");
18
+ const out = Array.from(value, Number);
19
+ if (!out.every(x => typeof x === "number"))
20
+ throw new TypeError("column '" + name + "' must be numeric");
21
+ return out;
22
+ }
23
+ function expressionVariables(expr, out = new Set()) {
24
+ if (expr.type === "variable")
25
+ out.add(expr.name);
26
+ else if (expr.type === "unary")
27
+ expressionVariables(expr.value, out);
28
+ else if (expr.type === "binary") {
29
+ expressionVariables(expr.left, out);
30
+ expressionVariables(expr.right, out);
31
+ }
32
+ else if (expr.type === "call")
33
+ expr.args.forEach(x => expressionVariables(x, out));
34
+ return out;
35
+ }
36
+ function initialValue(name, x, y) {
37
+ const ymin = minOf(y), ymax = maxOf(y), xMin = minOf(x), xMax = maxOf(x);
38
+ const range = Math.max(xMax - xMin, 1);
39
+ const lower = name.toLowerCase();
40
+ if (name === "Asym" || name === "Vm" || name === "B")
41
+ return ymax;
42
+ if (name === "R0" || name === "A")
43
+ return ymin;
44
+ if (name === "Drop")
45
+ return Math.max(ymax - ymin, 1e-3);
46
+ if (name === "K") {
47
+ const target = (ymin + ymax) / 2;
48
+ let best = 0;
49
+ for (let i = 1; i < y.length; i++)
50
+ if (Math.abs(y[i] - target) < Math.abs(y[best] - target))
51
+ best = i;
52
+ return Math.max(Math.abs(x[best]), 1e-6);
53
+ }
54
+ if (name === "xmid" || name === "c0")
55
+ return (xMin + xMax) / 2;
56
+ if (name === "scal")
57
+ return range / 4;
58
+ if (name === "b2")
59
+ return 2;
60
+ if (name === "b3")
61
+ return 0.6;
62
+ if (name === "lrc")
63
+ return -1;
64
+ if (name === "lrc1")
65
+ return 0;
66
+ if (name === "lrc2")
67
+ return -1.5;
68
+ if (name === "lKe")
69
+ return -2.5;
70
+ if (name === "lKa")
71
+ return 0.5;
72
+ if (name === "lCl")
73
+ return -3;
74
+ if (name === "lrc" || lower.startsWith("lr"))
75
+ return -1;
76
+ if (name === "pwr")
77
+ return 1.5;
78
+ if (name === "A1")
79
+ return ymax * 0.7;
80
+ if (name === "A2")
81
+ return ymax * 0.3;
82
+ return 1;
83
+ }
84
+ function linearTrend(x, y) {
85
+ const mx = x.reduce((s, v) => s + v, 0) / x.length, my = y.reduce((s, v) => s + v, 0) / y.length;
86
+ const denominator = x.reduce((s, v) => s + (v - mx) ** 2, 0);
87
+ if (!(denominator > 0))
88
+ return undefined;
89
+ const slope = x.reduce((s, v, i) => s + (v - mx) * (y[i] - my), 0) / denominator;
90
+ const intercept = my - slope * mx;
91
+ return { intercept, slope, error: x.reduce((s, v, i) => s + (y[i] - intercept - slope * v) ** 2, 0) };
92
+ }
93
+ function asymptoticRiseStart(x, y, shifted) {
94
+ const ymax = maxOf(y), ymin = minOf(y), range = Math.max(ymax - ymin, Number.EPSILON);
95
+ let best;
96
+ for (let k = 0; k <= 180; k++) {
97
+ const Asym = shifted
98
+ ? ymax - 0.2 * range + k * (0.5 * range / 180)
99
+ : ymax + range * 10 ** (-3 + k * 0.03);
100
+ const selected = x.map((value, i) => ({ x: value, y: y[i] })).filter(point => point.y < Asym);
101
+ if (selected.length < (shifted ? 4 : 2))
102
+ continue;
103
+ const sx = selected.map(point => point.x), z = selected.map(point => Math.log(1 - point.y / Asym));
104
+ if (!z.every(Number.isFinite))
105
+ continue;
106
+ let intercept = 0, slope = 0, error = 0;
107
+ if (shifted) {
108
+ const line = linearTrend(sx, z);
109
+ if (!line || !(line.slope < 0))
110
+ continue;
111
+ ({ intercept, slope, error } = line);
112
+ }
113
+ else {
114
+ const denominator = sx.reduce((sum, value) => sum + value * value, 0);
115
+ if (!(denominator > 0))
116
+ continue;
117
+ slope = sx.reduce((sum, value, i) => sum + value * z[i], 0) / denominator;
118
+ if (!(slope < 0))
119
+ continue;
120
+ error = sx.reduce((sum, value, i) => sum + (z[i] - slope * value) ** 2, 0);
121
+ }
122
+ const c0 = intercept / -slope;
123
+ if (shifted && (!Number.isFinite(c0) || c0 < 0 || c0 >= minOf(sx)))
124
+ continue;
125
+ const rate = -slope;
126
+ error = selected.reduce((sum, point) => sum + (point.y - Asym * (1 - Math.exp(-rate * (point.x - c0)))) ** 2, 0);
127
+ const candidate = { Asym, lrc: Math.log(rate), ...(shifted ? { c0 } : {}), error };
128
+ if (!best || candidate.error < best.error)
129
+ best = candidate;
130
+ }
131
+ if (!best)
132
+ return undefined;
133
+ const { error: _error, ...result } = best;
134
+ return result;
135
+ }
136
+ function fourParameterLogisticStart(x, y) {
137
+ const ymin = minOf(y), ymax = maxOf(y), range = Math.max(ymax - ymin, Number.EPSILON);
138
+ let best;
139
+ for (let ia = 0; ia <= 120; ia++) {
140
+ const A = ymin - range * 10 ** (-3 + ia * 0.025);
141
+ for (let ib = 0; ib <= 120; ib++) {
142
+ const B = ymax + range * 10 ** (-3 + ib * 0.025);
143
+ const z = y.map(value => Math.log((B - A) / (value - A) - 1));
144
+ if (!z.every(Number.isFinite))
145
+ continue;
146
+ const line = linearTrend(x, z);
147
+ if (!line || !(line.slope < 0))
148
+ continue;
149
+ const scal = -1 / line.slope, xmid = line.intercept * scal;
150
+ if (!(scal > 0) || !Number.isFinite(xmid))
151
+ continue;
152
+ const error = x.reduce((sum, value, i) => sum + (y[i] - (A + (B - A) / (1 + Math.exp(line.intercept + line.slope * value)))) ** 2, 0);
153
+ if (!best || error < best.error)
154
+ best = { A, B, xmid, scal, error };
155
+ }
156
+ }
157
+ if (!best)
158
+ return undefined;
159
+ const { error: _error, ...result } = best;
160
+ return result;
161
+ }
162
+ function weibullRiseStart(x, y) {
163
+ const ymin = minOf(y), ymax = maxOf(y), range = Math.max(ymax - ymin, Number.EPSILON);
164
+ let best;
165
+ for (let ia = 0; ia <= 180; ia++) {
166
+ const Asym = ymax - 0.04 * range + ia * (0.10 * range / 180);
167
+ const selected = x.map((value, i) => ({ x: value, y: y[i] })).filter(point => point.x > 0 && point.y < Asym);
168
+ if (selected.length < 5)
169
+ continue;
170
+ for (let id = 0; id <= 50; id++) {
171
+ const Drop = (Asym - ymin) * (1.001 + id * 0.002);
172
+ const lx = [], ly = [];
173
+ let valid = true;
174
+ for (const point of selected) {
175
+ const ratio = (Asym - point.y) / Drop;
176
+ if (!(ratio > 0 && ratio < 1)) {
177
+ valid = false;
178
+ break;
179
+ }
180
+ lx.push(Math.log(point.x));
181
+ ly.push(Math.log(-Math.log(ratio)));
182
+ }
183
+ if (!valid)
184
+ continue;
185
+ const line = linearTrend(lx, ly);
186
+ if (!line || !(line.slope > 0))
187
+ continue;
188
+ const rate = Math.exp(line.intercept);
189
+ const error = selected.reduce((sum, point) => sum + (point.y - (Asym - Drop * Math.exp(-rate * point.x ** line.slope))) ** 2, 0);
190
+ if (!best || error < best.error)
191
+ best = { Asym, Drop, lrc: line.intercept, pwr: line.slope, error };
192
+ }
193
+ }
194
+ if (!best)
195
+ return undefined;
196
+ const { error: _error, ...result } = best;
197
+ return result;
198
+ }
199
+ function solve(A0, b0) {
200
+ const n = b0.length;
201
+ if (A0.length !== n || A0.some(row => row.length !== n))
202
+ throw new Error("least-squares system has incompatible dimensions");
203
+ const A = A0.map(row => [...row]), b = [...b0];
204
+ for (let k = 0; k < n; k++) {
205
+ let pivot = k;
206
+ for (let i = k + 1; i < n; i++)
207
+ if (Math.abs(A[i][k]) > Math.abs(A[pivot][k]))
208
+ pivot = i;
209
+ const scale = Math.max(...A.map(row => Math.max(...row.map(Math.abs))), 1);
210
+ if (!(Math.abs(A[pivot][k]) > Number.EPSILON * scale * n * 32))
211
+ throw new Error("singular gradient matrix; parameters are not locally identifiable");
212
+ [A[k], A[pivot]] = [A[pivot], A[k]];
213
+ [b[k], b[pivot]] = [b[pivot], b[k]];
214
+ const d = A[k][k];
215
+ for (let j = k; j < n; j++)
216
+ A[k][j] = A[k][j] / d;
217
+ b[k] = b[k] / d;
218
+ for (let i = 0; i < n; i++) {
219
+ if (i === k)
220
+ continue;
221
+ const f = A[i][k];
222
+ for (let j = k; j < n; j++)
223
+ A[i][j] = A[i][j] - f * A[k][j];
224
+ b[i] = b[i] - f * b[k];
225
+ }
226
+ }
227
+ return b;
228
+ }
229
+ function inverse(A) {
230
+ const n = A.length;
231
+ const columns = Array.from({ length: n }, (_, j) => solve(A, Array.from({ length: n }, (_, i) => i === j ? 1 : 0)));
232
+ return Array.from({ length: n }, (_, i) => columns.map(col => col[i]));
233
+ }
234
+ function normalEquations(J, residuals, weights) {
235
+ const p = J[0]?.length ?? 0;
236
+ const matrix = Array.from({ length: p }, () => Array(p).fill(0));
237
+ const rhs = Array(p).fill(0);
238
+ for (let i = 0; i < J.length; i++) {
239
+ const w = weights[i];
240
+ for (let a = 0; a < p; a++) {
241
+ rhs[a] = rhs[a] + w * J[i][a] * residuals[i];
242
+ for (let b = 0; b < p; b++)
243
+ matrix[a][b] = matrix[a][b] + w * J[i][a] * J[i][b];
244
+ }
245
+ }
246
+ return { matrix, rhs };
247
+ }
248
+ function evaluate(expr, dataRows, y, weights, names, values, algorithm) {
249
+ const parameters = {};
250
+ names.forEach((name, i) => { parameters[name] = values[i]; });
251
+ const fitted = [], residuals = [], jacobian = [];
252
+ let objective = 0;
253
+ for (let i = 0; i < y.length; i++) {
254
+ const row = dataRows[i];
255
+ const evaluated = evaluateNlsWithGradient(expr, row, parameters, names);
256
+ const f = algorithm === "plinear" ? values[values.length - 1] * evaluated.value : evaluated.value;
257
+ const g = algorithm === "plinear"
258
+ ? [...evaluated.gradient.map(v => values[values.length - 1] * v), evaluated.value]
259
+ : evaluated.gradient;
260
+ const r = y[i] - f;
261
+ if (!Number.isFinite(f) || !Number.isFinite(r) || g.some(v => !Number.isFinite(v))) {
262
+ throw new Error("non-finite model value or gradient; check the formula domain and starting values");
263
+ }
264
+ fitted.push(f);
265
+ residuals.push(r);
266
+ jacobian.push(g);
267
+ objective += weights[i] * r * r;
268
+ }
269
+ return { fitted, residuals, jacobian, objective, coefficients: parameters };
270
+ }
271
+ function evaluateProfiled(expr, rows, y, weights, names, values) {
272
+ const parameters = {};
273
+ names.forEach((name, i) => { parameters[name] = values[i]; });
274
+ const basis = [], rawGradient = [];
275
+ for (const row of rows) {
276
+ const result = evaluateNlsWithGradient(expr, row, parameters, names);
277
+ basis.push(result.value);
278
+ rawGradient.push(result.gradient);
279
+ }
280
+ let numerator = 0, denominator = 0;
281
+ for (let i = 0; i < y.length; i++) {
282
+ numerator += weights[i] * basis[i] * y[i];
283
+ denominator += weights[i] * basis[i] * basis[i];
284
+ }
285
+ if (!(denominator > 0))
286
+ throw new Error("plinear basis is identically zero");
287
+ const linear = numerator / denominator;
288
+ const fitted = basis.map(v => linear * v);
289
+ const residuals = y.map((v, i) => v - fitted[i]);
290
+ const projection = names.map((_, j) => {
291
+ let sum = 0;
292
+ for (let i = 0; i < y.length; i++)
293
+ sum += weights[i] * basis[i] * rawGradient[i][j];
294
+ return sum / denominator;
295
+ });
296
+ const jacobian = rawGradient.map((gradient, i) => gradient.map((v, j) => linear * (v - basis[i] * projection[j])));
297
+ const objective = residuals.reduce((s, r, i) => s + weights[i] * r * r, 0);
298
+ return { fitted, residuals, jacobian, objective, linear };
299
+ }
300
+ function makeBounds(bound, names, fallback) {
301
+ if (bound === undefined)
302
+ return names.map(() => fallback);
303
+ if (typeof bound === "number")
304
+ return names.map(() => bound);
305
+ if (Array.isArray(bound)) {
306
+ if (bound.length !== names.length)
307
+ throw new RangeError("bound vector length must equal the number of parameters");
308
+ return [...bound];
309
+ }
310
+ const record = bound;
311
+ return names.map(name => record[name] ?? fallback);
312
+ }
313
+ // Spreading a data column into Math.min/Math.max overflows the call stack for long columns (about 1e5 values).
314
+ const minOf = (values) => values.reduce((m, v) => Math.min(m, v), Infinity);
315
+ const maxOf = (values) => values.reduce((m, v) => Math.max(m, v), -Infinity);
316
+ /**
317
+ * Rounding noise in the weighted residual sum of squares: each residual y - f carries an error of about
318
+ * eps |y|, so the sum carries about 2 eps sum w |r| |y| plus eps^2 sum w y^2 when the residuals are near zero.
319
+ * Relative to the data, so the convergence test does not depend on the units of y.
320
+ */
321
+ function objectiveNoise(residuals, y, weights) {
322
+ let cross = 0, squares = 0;
323
+ for (let i = 0; i < residuals.length; i++) {
324
+ cross += weights[i] * Math.abs(residuals[i] * y[i]);
325
+ squares += weights[i] * y[i] * y[i];
326
+ }
327
+ return 4 * Number.EPSILON * cross + 4 * Number.EPSILON * Number.EPSILON * squares;
328
+ }
329
+ function fitCore(expr, rows, y, weights, names, start, algorithm, lower, upper, control) {
330
+ let values = [...start];
331
+ const warnings = [];
332
+ let current = algorithm === "plinear"
333
+ ? evaluateProfiled(expr, rows, y, weights, names, values)
334
+ : evaluate(expr, rows, y, weights, names, values, algorithm);
335
+ let converged = false, iterations = 0;
336
+ let failureReason = "number of iterations exceeded; nonlinear fit did not converge";
337
+ for (; iterations < control.maxiter; iterations++) {
338
+ const { matrix, rhs } = normalEquations(current.jacobian, current.residuals, weights);
339
+ const boundTolerance = values.map(value => Math.max(16 * Number.EPSILON, Math.sqrt(control.tol) * 0.1) * Math.max(1, Math.abs(value)));
340
+ const freeIndices = names.map((_, i) => i).filter(i => algorithm !== "port" || !((values[i] <= lower[i] + boundTolerance[i] && rhs[i] <= 0)
341
+ || (values[i] >= upper[i] - boundTolerance[i] && rhs[i] >= 0)));
342
+ if (freeIndices.length === 0) {
343
+ converged = true;
344
+ break;
345
+ }
346
+ const reducedMatrix = freeIndices.map(i => freeIndices.map(j => matrix[i][j]));
347
+ const reducedRhs = freeIndices.map(i => rhs[i]);
348
+ const scales = reducedMatrix.map((row, i) => Math.sqrt(Math.max(row[i], Number.MIN_VALUE)));
349
+ const scaledMatrix = reducedMatrix.map((row, i) => row.map((value, j) => value / (scales[i] * scales[j])));
350
+ const scaledRhs = reducedRhs.map((value, i) => value / scales[i]);
351
+ let reducedDelta;
352
+ try {
353
+ reducedDelta = solve(scaledMatrix, scaledRhs).map((value, i) => value / scales[i]);
354
+ }
355
+ catch (error) {
356
+ throw new Error("singular gradient: " + (error instanceof Error ? error.message : String(error)));
357
+ }
358
+ const delta = Array.from({ length: names.length }, () => 0);
359
+ for (let i = 0; i < freeIndices.length; i++)
360
+ delta[freeIndices[i]] = reducedDelta[i];
361
+ const projectedDelta = delta.map((value, i) => {
362
+ if (algorithm !== "port")
363
+ return value;
364
+ // If an active-bound parameter has an inward gradient, never take an infeasible Newton direction.
365
+ if (values[i] <= lower[i] + boundTolerance[i]) {
366
+ return rhs[i] > 0 && value < 0 ? rhs[i] / Math.max(matrix[i][i], Number.MIN_VALUE) : value;
367
+ }
368
+ if (values[i] >= upper[i] - boundTolerance[i]) {
369
+ return rhs[i] < 0 && value > 0 ? rhs[i] / Math.max(matrix[i][i], Number.MIN_VALUE) : value;
370
+ }
371
+ return value;
372
+ });
373
+ const scaledGradientNorm = Math.max(0, ...rhs.map((value, i) => projectedDelta[i] === 0 ? 0 : Math.abs(value) / (Math.sqrt(Math.max(matrix[i][i], Number.MIN_VALUE))
374
+ * (Math.sqrt(current.objective) + control.scaleOffset + Number.EPSILON))));
375
+ const stepNorm = Math.max(0, ...projectedDelta.map((v, i) => Math.abs(v) / (1 + Math.abs(values[i]))));
376
+ const fullCandidate = values.map((v, i) => Math.min(upper[i], Math.max(lower[i], v + projectedDelta[i])));
377
+ const fullStepIsRounded = fullCandidate.every((candidate, i) => Math.abs(candidate - values[i]) <= 4 * Number.EPSILON
378
+ * Math.max(Math.abs(candidate), Math.abs(values[i]), Number.MIN_VALUE));
379
+ if (fullStepIsRounded) {
380
+ converged = true;
381
+ break;
382
+ }
383
+ const stepTolerance = Math.max(1e-12, Math.sqrt(control.tol) * 0.001);
384
+ const gradientTolerance = Math.max(control.tol * 100, 1e-13);
385
+ // The Gauss-Newton model predicts that the full step lowers the objective by delta' J'Wr. When the residuals are
386
+ // near zero, sqrt(RSS) is tiny and the gradient test cannot be met; a small step whose predicted decrease is
387
+ // within the rounding noise of the objective is then the solution. The objective alone is not a stopping rule:
388
+ // its rounding noise allows coefficient errors of about sqrt(eps), so a small step is always required.
389
+ const noise = objectiveNoise(current.residuals, y, weights);
390
+ const predictedDecrease = projectedDelta.reduce((sum, value, i) => sum + value * rhs[i], 0);
391
+ const smallStep = algorithm === "port" || stepNorm <= stepTolerance;
392
+ if (smallStep && (scaledGradientNorm <= gradientTolerance || predictedDecrease <= noise)) {
393
+ // Take the final full step when it does not raise the objective: it costs one evaluation and removes the
394
+ // remaining error of order stepTolerance (quadratically small near a zero-residual solution).
395
+ try {
396
+ const polished = algorithm === "plinear"
397
+ ? evaluateProfiled(expr, rows, y, weights, names, fullCandidate)
398
+ : evaluate(expr, rows, y, weights, names, fullCandidate, algorithm);
399
+ if (polished.objective <= current.objective) {
400
+ values = fullCandidate;
401
+ current = polished;
402
+ }
403
+ }
404
+ catch { /* Keep the current point when the full step leaves the expression domain. */ }
405
+ converged = true;
406
+ break;
407
+ }
408
+ let alpha = 1, accepted = false;
409
+ while (alpha >= control.minFactor) {
410
+ const candidate = values.map((v, i) => Math.min(upper[i], Math.max(lower[i], v + alpha * projectedDelta[i])));
411
+ if (candidate.every((v, i) => v === values[i])) {
412
+ alpha /= 2;
413
+ continue;
414
+ }
415
+ try {
416
+ const trial = algorithm === "plinear"
417
+ ? evaluateProfiled(expr, rows, y, weights, names, candidate)
418
+ : evaluate(expr, rows, y, weights, names, candidate, algorithm);
419
+ const candidateStepNorm = alpha * stepNorm;
420
+ if (trial.objective < current.objective
421
+ || (candidateStepNorm <= stepTolerance * 10 && trial.objective <= current.objective + noise)) {
422
+ values = candidate;
423
+ current = trial;
424
+ accepted = true;
425
+ break;
426
+ }
427
+ }
428
+ catch { /* A trial outside the function domain is rejected and the step is reduced. */ }
429
+ alpha /= 2;
430
+ }
431
+ if (!accepted) {
432
+ if (stepNorm <= stepTolerance * 10) {
433
+ converged = true;
434
+ break;
435
+ }
436
+ failureReason = "step factor reduced below minFactor";
437
+ break;
438
+ }
439
+ }
440
+ if (!converged && iterations >= control.maxiter)
441
+ iterations = control.maxiter;
442
+ if (!converged && !control.warnOnly)
443
+ throw new Error(failureReason);
444
+ const final = algorithm === "plinear"
445
+ ? evaluateProfiled(expr, rows, y, weights, names, values)
446
+ : evaluate(expr, rows, y, weights, names, values, algorithm);
447
+ return { values, ...final, iterations, converged, ...(converged ? {} : { failureReason }) };
448
+ }
449
+ function covarianceFromJacobian(J, weights, sigma2) {
450
+ const p = J[0]?.length ?? 0;
451
+ const columnNorms = Array.from({ length: p }, (_, a) => Math.sqrt(J.reduce((sum, row, i) => sum + weights[i] * row[a] * row[a], 0)));
452
+ if (columnNorms.some(scale => !(scale > 0) || !Number.isFinite(scale))) {
453
+ throw new Error("singular gradient matrix; parameters are not locally identifiable");
454
+ }
455
+ const correlation = Array.from({ length: p }, () => Array(p).fill(0));
456
+ for (let i = 0; i < J.length; i++) {
457
+ for (let a = 0; a < p; a++)
458
+ for (let b = 0; b < p; b++) {
459
+ correlation[a][b] = correlation[a][b] + weights[i] *
460
+ (J[i][a] / columnNorms[a]) * (J[i][b] / columnNorms[b]);
461
+ }
462
+ }
463
+ const inverseCorrelation = inverse(correlation);
464
+ return inverseCorrelation.map((row, a) => row.map((value, b) => value * sigma2 / columnNorms[a] / columnNorms[b]));
465
+ }
466
+ function corrFromCovariance(cov) {
467
+ return cov.map((row, i) => row.map((v, j) => {
468
+ const d = Math.sqrt(Math.max(0, cov[i][i] * cov[j][j]));
469
+ return d === 0 ? Number.NaN : v / d;
470
+ }));
471
+ }
472
+ /**
473
+ * Nonlinear least-squares regression. Equivalent to R's `nls()`.
474
+ *
475
+ * Fits a user-specified nonlinear mean function by Gauss-Newton, variable projection, or bound-constrained
476
+ * least squares. Formula expressions are parsed safely and differentiated symbolically.
477
+ *
478
+ * @param formula Response and nonlinear mean expression.
479
+ * @param data Numeric data columns.
480
+ * @param options Starting values, algorithm, weights, and convergence controls.
481
+ * @returns The fitted coefficients, residuals, covariance, and convergence diagnostics.
482
+ *
483
+ * @example
484
+ * ```ts
485
+ * const data = { conc: [0.02, 0.06, 0.11, 0.22, 0.56, 1.1], rate: [76, 97, 123, 159, 191, 207] };
486
+ * const fit = nls("rate ~ Vm * conc / (K + conc)", data, { start: { Vm: 200, K: 0.05 } });
487
+ * fit.coefficients;
488
+ * ```
489
+ *
490
+ * @category Regression
491
+ */
492
+ export function nls(formula, data, options = {}) {
493
+ checkOptions(options, NLS_KEYS, "nls"); // generated: option-keys.mjs
494
+ checkOptions(nestedOptions(options, "control"), NLS_CONTROL_KEYS, "nls", "control"); // generated: option-keys.mjs
495
+ const parsed = parseNlsFormula(formula);
496
+ const dataNames = new Set(Object.keys(data));
497
+ const inputColumns = Object.fromEntries([...dataNames].map(name => [name, column(data, name)]));
498
+ const firstColumn = Object.values(inputColumns)[0];
499
+ if (firstColumn === undefined)
500
+ throw new RangeError("data must contain at least one column");
501
+ const n = firstColumn.length;
502
+ if (Object.values(inputColumns).some(col => col.length !== n))
503
+ throw new RangeError("all data columns must have the same length");
504
+ const responseVariables = [...expressionVariables(parsed.responseExpression)];
505
+ const nonDataResponseVariables = responseVariables.filter(name => name !== "pi" && !dataNames.has(name));
506
+ if (nonDataResponseVariables.length > 0) {
507
+ throw new SyntaxError("response expression must not contain parameters: " + nonDataResponseVariables.join(", "));
508
+ }
509
+ const rawY = Array.from({ length: n }, (_, i) => {
510
+ const row = Object.fromEntries(Object.entries(inputColumns).map(([name, values]) => [name, values[i]]));
511
+ return evaluateNlsExpression(parsed.responseExpression, row, {});
512
+ });
513
+ const variables = [...expressionVariables(parsed.expression)];
514
+ const startNames = options.start ? Object.keys(options.start) : [];
515
+ const inferredNames = variables.filter(name => name !== "pi" && !dataNames.has(name));
516
+ const parameterNames = options.start
517
+ ? startNames.filter(name => !(name === "pi" && dataNames.has("pi")))
518
+ : inferredNames;
519
+ const responseParameters = responseVariables.filter(name => parameterNames.includes(name));
520
+ if (responseParameters.length > 0) {
521
+ throw new SyntaxError("response expression must not contain parameters: " + responseParameters.join(", "));
522
+ }
523
+ if (parameterNames.length === 0)
524
+ throw new Error("no free parameters were found in the formula");
525
+ if (!options.start && !/\bSS(?:asymp|asympOff|asympOrig|biexp|fol|fpl|gompertz|logis|micmen|weibull)\s*\(/.test(formula)) {
526
+ throw new Error("start must be supplied for a formula without a self-starting model");
527
+ }
528
+ if (options.start && Object.keys(options.start).length !== new Set(Object.keys(options.start)).size) {
529
+ throw new Error("starting parameter names must be unique");
530
+ }
531
+ if (options.start && Object.values(options.start).some(v => !Number.isFinite(v)))
532
+ throw new RangeError("starting values must be finite");
533
+ let start = options.start ? parameterNames.map(name => options.start[name]) : parameterNames.map(name => initialValue(name, rawY, column(data, variables.find(v => dataNames.has(v)) ?? parsed.response)));
534
+ if (!options.start && /\bSSmicmen\s*\(/.test(formula)) {
535
+ const predictorName = variables.find(name => dataNames.has(name));
536
+ if (predictorName) {
537
+ const x = column(data, predictorName);
538
+ const pairs = rawY.map((value, i) => [x[i], value])
539
+ .filter(([a, b]) => Number.isFinite(a) && Number.isFinite(b) && a > 0 && b > 0);
540
+ const u = pairs.map(([a]) => 1 / a), v = pairs.map(([, b]) => 1 / b);
541
+ const meanU = u.reduce((sum, value) => sum + value, 0) / u.length;
542
+ const meanV = v.reduce((sum, value) => sum + value, 0) / v.length;
543
+ const slope = u.reduce((sum, value, i) => sum + (value - meanU) * (v[i] - meanV), 0)
544
+ / u.reduce((sum, value) => sum + (value - meanU) ** 2, 0);
545
+ const intercept = meanV - slope * meanU;
546
+ if (intercept > 0 && slope > 0) {
547
+ for (let i = 0; i < parameterNames.length; i++) {
548
+ if (parameterNames[i] === "Vm")
549
+ start[i] = 1 / intercept;
550
+ if (parameterNames[i] === "K")
551
+ start[i] = slope / intercept;
552
+ }
553
+ }
554
+ }
555
+ }
556
+ if (!options.start) {
557
+ const predictorName = variables.find(name => dataNames.has(name));
558
+ if (predictorName) {
559
+ const x = column(data, predictorName);
560
+ let improved;
561
+ if (/\bSSasympOrig\s*\(/.test(formula))
562
+ improved = asymptoticRiseStart(x, rawY, false);
563
+ else if (/\bSSasympOff\s*\(/.test(formula))
564
+ improved = asymptoticRiseStart(x, rawY, true);
565
+ else if (/\bSSfpl\s*\(/.test(formula))
566
+ improved = fourParameterLogisticStart(x, rawY);
567
+ else if (/\bSSweibull\s*\(/.test(formula))
568
+ improved = weibullRiseStart(x, rawY);
569
+ if (improved)
570
+ for (let i = 0; i < parameterNames.length; i++) {
571
+ const value = improved[parameterNames[i]];
572
+ if (value !== undefined && Number.isFinite(value))
573
+ start[i] = value;
574
+ }
575
+ }
576
+ }
577
+ if (start.some(v => !Number.isFinite(v)))
578
+ throw new RangeError("could not obtain finite starting values");
579
+ const weightRaw = typeof options.weights === "string"
580
+ ? column(data, options.weights)
581
+ : options.weights === undefined ? Array(n).fill(1) : Array.from(options.weights);
582
+ if (weightRaw.length !== n)
583
+ throw new RangeError("weights must have one value per observation");
584
+ if (weightRaw.some(w => !Number.isFinite(w) || w < 0))
585
+ throw new RangeError("weights must be finite and non-negative");
586
+ const predictorNames = variables.filter(name => dataNames.has(name));
587
+ const dataColumns = {};
588
+ for (const name of predictorNames)
589
+ dataColumns[name] = column(data, name);
590
+ const rows = [];
591
+ // Missing values (NaN) drop the row; an infinite value is an error, as in R (found 2026-11-20: rows with
592
+ // Infinity were dropped silently).
593
+ const infinite = (value) => value === Infinity || value === -Infinity;
594
+ for (let i = 0; i < n; i++) {
595
+ if (infinite(rawY[i]) || predictorNames.some(name => infinite(dataColumns[name][i]))) {
596
+ throw new RangeError("NA/NaN/Inf in the response or the predictors: row " + (i + 1) + " has an infinite value");
597
+ }
598
+ if (Number.isNaN(rawY[i]) || weightRaw[i] === 0)
599
+ continue;
600
+ if (predictorNames.some(name => Number.isNaN(dataColumns[name][i])))
601
+ continue;
602
+ rows.push(i);
603
+ }
604
+ const p = parameterNames.length + (options.algorithm === "plinear" ? 1 : 0);
605
+ if (rows.length <= p)
606
+ throw new Error("number of observations must exceed the number of parameters");
607
+ const y = rows.map(i => rawY[i]);
608
+ const weights = rows.map(i => weightRaw[i]);
609
+ const dataRows = rows.map(i => Object.fromEntries(predictorNames.map(name => [name, dataColumns[name][i]])));
610
+ const algorithm = options.algorithm ?? "default";
611
+ if (algorithm !== "default" && algorithm !== "plinear" && algorithm !== "port")
612
+ throw new Error("unsupported algorithm: " + String(algorithm));
613
+ const names = parameterNames;
614
+ const lower = makeBounds(options.lower, names, -Infinity);
615
+ const upper = makeBounds(options.upper, names, Infinity);
616
+ if (algorithm !== "port" && (options.lower !== undefined || options.upper !== undefined)) {
617
+ throw new Error("lower and upper bounds are supported only by algorithm 'port'");
618
+ }
619
+ if (lower.some((v, i) => Number.isNaN(v) || v > upper[i]) || start.some((v, i) => v < lower[i] || v > upper[i])) {
620
+ throw new RangeError("starting values must be within ordered lower and upper bounds");
621
+ }
622
+ const ctl = options.control ?? {};
623
+ const control = {
624
+ maxiter: ctl.maxiter ?? 100,
625
+ tol: ctl.tol ?? 1e-12,
626
+ minFactor: ctl.minFactor ?? 1 / 1024,
627
+ warnOnly: ctl.warnOnly ?? false,
628
+ scaleOffset: ctl.scaleOffset ?? 0,
629
+ };
630
+ if (!(control.maxiter >= 1 && Number.isInteger(control.maxiter)))
631
+ throw new RangeError("maxiter must be a positive integer");
632
+ if (!(control.tol > 0 && Number.isFinite(control.tol)))
633
+ throw new RangeError("tol must be positive and finite");
634
+ if (!(control.minFactor > 0 && control.minFactor <= 1))
635
+ throw new RangeError("minFactor must be in (0, 1]");
636
+ if (!(control.scaleOffset >= 0 && Number.isFinite(control.scaleOffset)))
637
+ throw new RangeError("scaleOffset must be non-negative and finite");
638
+ const fitted = fitCore(parsed.expression, dataRows, y, weights, parameterNames, start, algorithm, lower, upper, control);
639
+ const coefficientNames = algorithm === "plinear" ? [...parameterNames, ".lin"] : parameterNames;
640
+ const coefficients = {};
641
+ parameterNames.forEach((name, i) => { coefficients[name] = fitted.values[i]; });
642
+ if (algorithm === "plinear")
643
+ coefficients[".lin"] = fitted.linear;
644
+ const dfResidual = rows.length - coefficientNames.length;
645
+ const sigma = Math.sqrt(fitted.objective / dfResidual);
646
+ const responseNorm = Math.sqrt(weights.reduce((sum, weight, i) => sum + weight * y[i] * y[i], 0));
647
+ const exactFit = Math.sqrt(fitted.objective) <= 64 * Number.EPSILON * Math.max(responseNorm, Number.MIN_VALUE);
648
+ let fullJacobian = fitted.jacobian;
649
+ if (algorithm === "plinear") {
650
+ const parameters = Object.fromEntries(parameterNames.map((name, i) => [name, fitted.values[i]]));
651
+ fullJacobian = dataRows.map(row => {
652
+ const result = evaluateNlsWithGradient(parsed.expression, row, parameters, parameterNames);
653
+ return [...result.gradient.map(v => coefficients[".lin"] * v), result.value];
654
+ });
655
+ }
656
+ const covariance = exactFit ? coefficientNames.map(() => coefficientNames.map(() => Number.NaN))
657
+ : covarianceFromJacobian(fullJacobian, weights, sigma * sigma);
658
+ const warnings = fitted.converged ? [] : [fitted.failureReason ?? "number of iterations exceeded; nonlinear fit did not converge"];
659
+ return reported("nls", {
660
+ formula, response: parsed.response, parameterNames: coefficientNames, coefficients,
661
+ fitted: fitted.fitted, residuals: fitted.residuals, y, weights, rows, data: dataColumns,
662
+ expression: parsed.expression, deviance: fitted.objective, sigma, dfResidual, nobs: rows.length,
663
+ covariance, correlation: corrFromCovariance(covariance), converged: fitted.converged,
664
+ iterations: fitted.iterations, algorithm, warnings, exactFit,
665
+ });
666
+ }
667
+ /**
668
+ * Summary of a nonlinear least-squares fit. Equivalent to R's `summary.nls()`.
669
+ *
670
+ * @param fit A fitted nonlinear model.
671
+ * @returns The coefficient table, residual scale, and residual degrees of freedom.
672
+ *
673
+ * @example
674
+ * ```ts
675
+ * const data = { conc: [0.02, 0.06, 0.11, 0.22, 0.56, 1.1], rate: [76, 97, 123, 159, 191, 207] };
676
+ * const fit = nls("rate ~ Vm * conc / (K + conc)", data, { start: { Vm: 200, K: 0.05 } });
677
+ * nlsSummary(fit);
678
+ * ```
679
+ *
680
+ * @category Regression
681
+ */
682
+ export function nlsSummary(fit) {
683
+ const rows = fit.parameterNames;
684
+ const values = rows.map((name, i) => {
685
+ const estimate = fit.coefficients[name];
686
+ const se = Math.sqrt(fit.covariance[i][i]);
687
+ const t = estimate / se;
688
+ const p = 2 * pt1(Math.abs(t), fit.dfResidual, false, false);
689
+ return [estimate, se, t, p];
690
+ });
691
+ return reported("nlsSummary", {
692
+ coefficients: { rows, cols: ["Estimate", "Std. Error", "t value", "Pr(>|t|)"], values },
693
+ sigma: fit.sigma, df: [fit.parameterNames.length, fit.dfResidual], deviance: fit.deviance,
694
+ nobs: fit.nobs, warnings: [...fit.warnings],
695
+ }, fit);
696
+ }
697
+ /**
698
+ * Covariance matrix of a nonlinear least-squares fit. Equivalent to R's `vcov.nls()`.
699
+ *
700
+ * @param fit A fitted nonlinear model.
701
+ * @returns The covariance matrix in coefficient order.
702
+ *
703
+ * @example
704
+ * ```ts
705
+ * const data = { conc: [0.02, 0.06, 0.11, 0.22, 0.56, 1.1], rate: [76, 97, 123, 159, 191, 207] };
706
+ * const fit = nls("rate ~ Vm * conc / (K + conc)", data, { start: { Vm: 200, K: 0.05 } });
707
+ * nlsVcov(fit);
708
+ * ```
709
+ *
710
+ * @category Regression
711
+ */
712
+ export function nlsVcov(fit) {
713
+ return fit.covariance.map(row => [...row]);
714
+ }
715
+ /**
716
+ * Predictions from a nonlinear least-squares fit. Equivalent to R's `predict.nls()`.
717
+ *
718
+ * @param fit A fitted nonlinear model.
719
+ * @param options New predictor data.
720
+ * @returns One fitted mean per row of new data.
721
+ *
722
+ * @example
723
+ * ```ts
724
+ * const data = { conc: [0.02, 0.06, 0.11, 0.22, 0.56, 1.1], rate: [76, 97, 123, 159, 191, 207] };
725
+ * const fit = nls("rate ~ Vm * conc / (K + conc)", data, { start: { Vm: 200, K: 0.05 } });
726
+ * nlsPredict(fit, { newdata: { conc: [0.1, 0.5] } });
727
+ * ```
728
+ *
729
+ * @category Regression
730
+ */
731
+ export function nlsPredict(fit, options) {
732
+ checkOptions(options, NLS_PREDICT_KEYS, "nlsPredict"); // generated: option-keys.mjs
733
+ const data = options.newdata;
734
+ const lengths = Object.values(data).map(col => col.length);
735
+ const n = lengths[0] ?? 0;
736
+ if (lengths.some(length => length !== n))
737
+ throw new RangeError("newdata columns must have equal lengths");
738
+ const out = [];
739
+ for (let i = 0; i < n; i++) {
740
+ const row = {};
741
+ for (const [name, col] of Object.entries(data))
742
+ row[name] = Number(col[i]);
743
+ try {
744
+ const value = evaluateNlsExpression(fit.expression, row, fit.coefficients);
745
+ out.push(fit.algorithm === "plinear" ? fit.coefficients[".lin"] * value : value);
746
+ }
747
+ catch {
748
+ out.push(Number.NaN);
749
+ }
750
+ }
751
+ return out;
752
+ }
753
+ /** Refit nuisance parameters with one coefficient fixed, starting from the nearest profile point. */
754
+ function profilePoint(fit, fixedIndex, fixedValue, initial) {
755
+ const nonlinearNames = fit.parameterNames.filter(name => name !== ".lin");
756
+ const nuisanceIndices = nonlinearNames.map((_, i) => i).filter(i => i !== fixedIndex);
757
+ const nuisanceNames = nuisanceIndices.map(i => nonlinearNames[i]);
758
+ let nuisance = [...initial];
759
+ const parameters = () => {
760
+ const full = nonlinearNames.map(name => fit.coefficients[name]);
761
+ full[fixedIndex] = fixedValue;
762
+ nuisanceIndices.forEach((index, j) => { full[index] = nuisance[j]; });
763
+ return full;
764
+ };
765
+ const calculate = () => {
766
+ const vals = parameters();
767
+ const evaluated = fit.algorithm === "plinear"
768
+ ? evaluateProfiled(fit.expression, fit.rows.map(i => Object.fromEntries(Object.entries(fit.data).map(([name, col]) => [name, col[i]]))), fit.y, fit.weights, nonlinearNames, vals)
769
+ : evaluate(fit.expression, fit.rows.map(i => Object.fromEntries(Object.entries(fit.data).map(([name, col]) => [name, col[i]]))), fit.y, fit.weights, nonlinearNames, vals, "default");
770
+ const jacobian = evaluated.jacobian.map(row => nuisanceIndices.map(index => row[index]));
771
+ return { ...evaluated, jacobian };
772
+ };
773
+ let current = calculate();
774
+ for (let iteration = 0; iteration < 200 && nuisance.length > 0; iteration++) {
775
+ const { matrix, rhs } = normalEquations(current.jacobian, current.residuals, fit.weights);
776
+ const scales = matrix.map((row, i) => Math.sqrt(Math.max(row[i], Number.MIN_VALUE)));
777
+ const scaled = matrix.map((row, i) => row.map((value, j) => value / (scales[i] * scales[j])));
778
+ const scaledRhs = rhs.map((value, i) => value / scales[i]);
779
+ const gradientNorm = Math.max(0, ...rhs.map((value, i) => Math.abs(value) / Math.sqrt(Math.max(matrix[i][i], Number.MIN_VALUE))));
780
+ if (gradientNorm <= 1e-11 * (Math.sqrt(current.objective) + 1))
781
+ break;
782
+ let accepted = false;
783
+ for (const damping of [0, 1e-12, 1e-10, 1e-8, 1e-6, 1e-4, 1e-2]) {
784
+ let delta;
785
+ try {
786
+ const system = scaled.map((row, i) => row.map((value, j) => value + (i === j ? damping : 0)));
787
+ delta = solve(system, scaledRhs).map((value, i) => value / scales[i]);
788
+ }
789
+ catch {
790
+ continue;
791
+ }
792
+ const stepNorm = Math.max(0, ...delta.map((value, i) => Math.abs(value) / (1 + Math.abs(nuisance[i]))));
793
+ if (stepNorm <= 1e-12)
794
+ continue;
795
+ let alpha = 1;
796
+ while (alpha >= 1 / 4096) {
797
+ const candidate = nuisance.map((value, i) => value + alpha * delta[i]);
798
+ const previous = nuisance;
799
+ nuisance = candidate;
800
+ try {
801
+ const trial = calculate();
802
+ const roundingAllowance = 8 * Number.EPSILON * Math.max(1, current.objective);
803
+ if (trial.objective < current.objective
804
+ || (alpha * stepNorm <= 1e-10 && trial.objective <= current.objective + roundingAllowance)) {
805
+ current = trial;
806
+ accepted = true;
807
+ break;
808
+ }
809
+ }
810
+ catch { /* reject a point outside the expression domain */ }
811
+ nuisance = previous;
812
+ alpha /= 2;
813
+ }
814
+ if (accepted)
815
+ break;
816
+ }
817
+ if (!accepted)
818
+ break;
819
+ }
820
+ const fullValues = parameters();
821
+ const full = fit.algorithm === "plinear"
822
+ ? evaluateProfiled(fit.expression, fit.rows.map(i => Object.fromEntries(Object.entries(fit.data).map(([name, col]) => [name, col[i]]))), fit.y, fit.weights, nonlinearNames, fullValues)
823
+ : evaluate(fit.expression, fit.rows.map(i => Object.fromEntries(Object.entries(fit.data).map(([name, col]) => [name, col[i]]))), fit.y, fit.weights, nonlinearNames, fullValues, "default");
824
+ return { value: fixedValue, objective: full.objective, nuisance, residuals: full.residuals, jacobian: full.jacobian.map(row => [row[fixedIndex]]), };
825
+ }
826
+ /** Find one profile endpoint by outward bracketing and safeguarded Newton refinement. */
827
+ function profileEndpoint(fit, index, direction, target) {
828
+ const names = fit.parameterNames.filter(name => name !== ".lin");
829
+ const estimate = fit.coefficients[names[index]];
830
+ const seIndex = fit.parameterNames.indexOf(names[index]);
831
+ const se = Math.sqrt(fit.covariance[seIndex][seIndex]);
832
+ if (!(se > 0) || !Number.isFinite(se))
833
+ return Number.NaN;
834
+ const nuisanceNames = names.filter((_, i) => i !== index);
835
+ let warm = nuisanceNames.map(name => fit.coefficients[name]);
836
+ const center = { value: estimate, objective: fit.deviance, nuisance: warm, residuals: fit.residuals, jacobian: [] };
837
+ let inside = center, outside;
838
+ let distance = Math.max(se, Math.abs(estimate) * 1e-4, 1e-8);
839
+ const evaluateAt = (value, start) => profilePoint(fit, index, value, start);
840
+ for (let k = 0; k < 60; k++) {
841
+ const candidateValue = estimate + direction * distance;
842
+ try {
843
+ const candidate = evaluateAt(candidateValue, inside.nuisance);
844
+ if (candidate.objective >= target) {
845
+ outside = candidate;
846
+ break;
847
+ }
848
+ inside = candidate;
849
+ distance *= 1.8;
850
+ }
851
+ catch {
852
+ distance *= 0.5;
853
+ }
854
+ }
855
+ if (!outside)
856
+ return Number.NaN;
857
+ let innerT = 0, outerT = direction * (outside.value - estimate);
858
+ let current = outside;
859
+ let rootValue = Number.NaN;
860
+ for (let iteration = 0; iteration < 100; iteration++) {
861
+ const f = current.objective - target;
862
+ const t = direction * (current.value - estimate);
863
+ if (Math.abs(f) <= 2e-11 * Math.max(1, target)) {
864
+ rootValue = current.value;
865
+ break;
866
+ }
867
+ if (Math.abs(outerT - innerT) <= 2e-10 * Math.max(1, Math.abs(estimate))) {
868
+ rootValue = estimate + direction * ((innerT + outerT) / 2);
869
+ break;
870
+ }
871
+ const derivative = current.residuals.reduce((sum, residual, i) => sum - 2 * fit.weights[i] * residual * current.jacobian[i][0], 0) * direction;
872
+ let nextT = t - f / derivative;
873
+ if (!Number.isFinite(nextT) || !(nextT > innerT && nextT < outerT))
874
+ nextT = (innerT + outerT) / 2;
875
+ const nextValue = estimate + direction * nextT;
876
+ try {
877
+ const trial = evaluateAt(nextValue, current.nuisance);
878
+ if (trial.objective >= target)
879
+ outerT = nextT;
880
+ else
881
+ innerT = nextT;
882
+ current = trial;
883
+ }
884
+ catch {
885
+ outerT = nextT;
886
+ current = evaluateAt(estimate + direction * ((innerT + outerT) / 2), current.nuisance);
887
+ }
888
+ }
889
+ const endpoint = Number.isFinite(rootValue) ? rootValue : estimate + direction * ((innerT + outerT) / 2);
890
+ // Independently verify the endpoint from the original fitted nuisance values.
891
+ const checked = evaluateAt(endpoint, nuisanceNames.map(name => fit.coefficients[name]));
892
+ if (Math.abs(checked.objective - target) > 2e-8 * Math.max(1, target))
893
+ return Number.NaN;
894
+ return endpoint;
895
+ }
896
+ /**
897
+ * Wald or profile confidence intervals for nonlinear parameters. Equivalent to R's `confint.nls()`.
898
+ *
899
+ * @param fit A fitted nonlinear model.
900
+ * @param options Interval method, confidence level, and parameter names.
901
+ * @returns A two-column confidence interval matrix.
902
+ *
903
+ * @example
904
+ * ```ts
905
+ * const data = { conc: [0.02, 0.06, 0.11, 0.22, 0.56, 1.1], rate: [76, 97, 123, 159, 191, 207] };
906
+ * const fit = nls("rate ~ Vm * conc / (K + conc)", data, { start: { Vm: 200, K: 0.05 } });
907
+ * nlsConfint(fit, { method: "wald", level: 0.95 });
908
+ * ```
909
+ *
910
+ * @category Regression
911
+ */
912
+ export function nlsConfint(fit, options = {}) {
913
+ checkOptions(options, NLS_CONFINT_KEYS, "nlsConfint"); // generated: option-keys.mjs
914
+ const method = options.method ?? "profile", level = options.level ?? 0.95;
915
+ if (!(level > 0 && level < 1) || !Number.isFinite(level))
916
+ throw new RangeError("level must be between 0 and 1");
917
+ if (method !== "profile" && method !== "wald")
918
+ throw new Error("method must be 'profile' or 'wald'");
919
+ const names = options.parm ? [...options.parm] : fit.parameterNames.filter(name => method === "wald" || name !== ".lin");
920
+ const warnings = [];
921
+ const values = [];
922
+ const tcrit = qt1((1 + level) / 2, fit.dfResidual, true, false);
923
+ const fcrit = qf1(level, 1, fit.dfResidual, true, false);
924
+ const target = fit.deviance + fit.sigma * fit.sigma * fcrit;
925
+ for (const name of names) {
926
+ const index = fit.parameterNames.indexOf(name);
927
+ if (index < 0)
928
+ throw new Error("unknown parameter: " + name);
929
+ const estimate = fit.coefficients[name];
930
+ const se = Math.sqrt(fit.covariance[index][index]);
931
+ if (method === "wald" || fit.exactFit) {
932
+ values.push([estimate - tcrit * se, estimate + tcrit * se]);
933
+ if (fit.exactFit)
934
+ warnings.push("confidence intervals are unavailable for an exact fit");
935
+ }
936
+ else {
937
+ const profileIndex = fit.parameterNames.filter(parameter => parameter !== ".lin").indexOf(name);
938
+ if (profileIndex < 0) {
939
+ values.push([Number.NaN, Number.NaN]);
940
+ warnings.push("profile confidence limits are unavailable for parameter '" + name + "'");
941
+ }
942
+ else {
943
+ const lower = profileEndpoint(fit, profileIndex, -1, target);
944
+ const upper = profileEndpoint(fit, profileIndex, 1, target);
945
+ values.push([lower, upper]);
946
+ if (!Number.isFinite(lower) || !Number.isFinite(upper)) {
947
+ warnings.push("profile confidence limit could not be found for '" + name + "'");
948
+ }
949
+ }
950
+ }
951
+ }
952
+ const percent = (100 * (1 - level) / 2);
953
+ const cols = method === "wald"
954
+ ? [String(Number(percent.toPrecision(12))) + " %", String(Number((100 - percent).toPrecision(12))) + " %"]
955
+ : [String(Number(percent.toPrecision(12))) + "%", String(Number((100 - percent).toPrecision(12))) + "%"];
956
+ return reported("nlsConfint", { rows: names, cols, values, warnings: [...new Set(warnings)] }, fit);
957
+ }
958
+ /**
959
+ * Analysis of variance for nested nonlinear least-squares fits. Equivalent to R's `anova.nls()`.
960
+ *
961
+ * @param fits Two or more nested fits to the same observations.
962
+ * @returns The sequential F-test table.
963
+ *
964
+ * @example
965
+ * ```ts
966
+ * const data = { x: [1, 2, 3, 4, 5], y: [2, 3, 5, 7, 8] };
967
+ * const small = nls("y ~ a * x", data, { start: { a: 1 } });
968
+ * const large = nls("y ~ a * x + b", data, { start: { a: 1, b: 0 } });
969
+ * nlsAnova(small, large);
970
+ * ```
971
+ *
972
+ * @category Regression
973
+ */
974
+ export function nlsAnova(...fits) {
975
+ if (fits.length < 2)
976
+ throw new Error("nlsAnova requires at least two fitted models");
977
+ const warnings = [...new Set(fits.flatMap(fit => fit.warnings))];
978
+ for (let i = 1; i < fits.length; i++) {
979
+ const a = fits[i - 1], b = fits[i];
980
+ if (a.response !== b.response || a.rows.length !== b.rows.length
981
+ || a.rows.some((row, j) => row !== b.rows[j])
982
+ || a.weights.length !== b.weights.length || a.weights.some((w, j) => w !== b.weights[j])) {
983
+ throw new Error("models were not all fitted to the same observations and weights");
984
+ }
985
+ if (!a.parameterNames.every(name => b.parameterNames.includes(name)))
986
+ throw new Error("models are not nested");
987
+ }
988
+ const table = {
989
+ Model: fits.map(f => f.formula),
990
+ "Res.Df": fits.map(f => f.dfResidual),
991
+ "Res.Sum Sq": fits.map(f => f.deviance),
992
+ Df: ["NA"], "Sum Sq": ["NA"], "F value": ["NA"], "Pr(>F)": ["NA"],
993
+ };
994
+ for (let i = 1; i < fits.length; i++) {
995
+ const a = fits[i - 1], b = fits[i];
996
+ const df = a.dfResidual - b.dfResidual;
997
+ if (df <= 0)
998
+ throw new Error("models are not nested in increasing parameter dimension");
999
+ const sumSq = a.deviance - b.deviance;
1000
+ const f = (sumSq / df) / (b.deviance / b.dfResidual);
1001
+ table.Df.push(df);
1002
+ table["Sum Sq"].push(sumSq);
1003
+ table["F value"].push(f);
1004
+ table["Pr(>F)"].push(pf1(f, df, b.dfResidual, false, false));
1005
+ }
1006
+ return reported("nlsAnova", { table, warnings }, ...fits);
1007
+ }