@numero-uno-jpn/rstats 1.6.0 → 1.8.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 (67) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.ja.md +11 -9
  3. package/README.md +12 -9
  4. package/dist/chunks/{chunk-O5CMNUJL.js → chunk-2X6PE6JF.js} +2 -2
  5. package/dist/chunks/{chunk-KAAUNR3G.js → chunk-2ZQ2TSZS.js} +1 -1
  6. package/dist/chunks/{chunk-F7G74UNI.js → chunk-3DO726WZ.js} +2 -2
  7. package/dist/chunks/{chunk-WAMHZ47G.js → chunk-45HUI3M4.js} +2 -2
  8. package/dist/chunks/{chunk-ABSUQPOG.js → chunk-52RWDNO6.js} +2 -2
  9. package/dist/chunks/chunk-53OM63EU.js +2 -0
  10. package/dist/chunks/{chunk-2I7Z7L5J.js → chunk-73IRLCTF.js} +2 -2
  11. package/dist/chunks/chunk-7ODUCEGX.js +2 -0
  12. package/dist/chunks/{chunk-55XSRONZ.js → chunk-ANZUXEMH.js} +2 -2
  13. package/dist/chunks/chunk-BHQGMZTI.js +2 -0
  14. package/dist/chunks/{chunk-3PCHPKBD.js → chunk-D3LKPD4H.js} +2 -2
  15. package/dist/chunks/chunk-DG2RTNIR.js +2 -0
  16. package/dist/chunks/{chunk-Z2XN4NN7.js → chunk-GRTQ7FYQ.js} +2 -2
  17. package/dist/chunks/chunk-HXYH5ZMB.js +2 -0
  18. package/dist/chunks/{chunk-NVIJXWS6.js → chunk-HYJ4MIZE.js} +2 -2
  19. package/dist/chunks/{chunk-ZL7EAPO5.js → chunk-IJST2ZGT.js} +1 -1
  20. package/dist/chunks/{chunk-2TVHT4PF.js → chunk-JIAFWEED.js} +2 -2
  21. package/dist/chunks/{chunk-7ZNFRZO4.js → chunk-JXJDCQYE.js} +2 -2
  22. package/dist/chunks/{chunk-FLITCXLY.js → chunk-LZB43TUL.js} +2 -2
  23. package/dist/chunks/chunk-MLNWWGGE.js +2 -0
  24. package/dist/chunks/{chunk-OZLDZOOA.js → chunk-QQHF5T2A.js} +1 -1
  25. package/dist/chunks/chunk-RWZ6ICYN.js +2 -0
  26. package/dist/chunks/{chunk-RSTU6CX7.js → chunk-TQM6KGKT.js} +2 -2
  27. package/dist/chunks/chunk-TUL6UFLQ.js +2 -0
  28. package/dist/chunks/{chunk-BMEO5X5F.js → chunk-TYMC2D5I.js} +2 -2
  29. package/dist/chunks/chunk-V7ECXPWY.js +2 -0
  30. package/dist/chunks/chunk-VB6PVRSN.js +2 -0
  31. package/dist/chunks/chunk-Y4KNH43T.js +2 -0
  32. package/dist/chunks/{chunk-AHFMBHZW.js → chunk-YD4U3QZ3.js} +1 -1
  33. package/dist/chunks/{chunk-SFZF44G6.js → chunk-YT62DNDS.js} +2 -2
  34. package/dist/descriptive.js +2 -2
  35. package/dist/distributions.js +2 -2
  36. package/dist/entries/regression.d.ts +7 -0
  37. package/dist/entries/regression.js +12 -0
  38. package/dist/linalg.js +2 -2
  39. package/dist/mixed.js +2 -2
  40. package/dist/models/gee.d.ts +280 -0
  41. package/dist/models/gee.js +704 -0
  42. package/dist/models/glmnet.d.ts +259 -0
  43. package/dist/models/glmnet.js +1112 -0
  44. package/dist/models/modelMatrix.d.ts +2 -0
  45. package/dist/models/nls.d.ts +286 -0
  46. package/dist/models/nls.js +1007 -0
  47. package/dist/models/nlsFormula.d.ts +37 -0
  48. package/dist/models/nlsFormula.js +295 -0
  49. package/dist/models/polr.d.ts +341 -0
  50. package/dist/models/polr.js +1028 -0
  51. package/dist/models/rlm.d.ts +282 -0
  52. package/dist/models/rlm.js +766 -0
  53. package/dist/models/rq.d.ts +203 -0
  54. package/dist/models/rq.js +1089 -0
  55. package/dist/numerics.js +2 -2
  56. package/dist/regression.js +3 -0
  57. package/dist/rstats.js +1 -1
  58. package/dist/special.js +2 -2
  59. package/dist/tests.js +15 -15
  60. package/llms.txt +8 -1
  61. package/package.json +6 -1
  62. package/dist/chunks/chunk-5AITXV3T.js +0 -2
  63. package/dist/chunks/chunk-BJTGQ52J.js +0 -2
  64. package/dist/chunks/chunk-KND2BFD5.js +0 -2
  65. package/dist/chunks/chunk-N2PNW4HR.js +0 -2
  66. package/dist/chunks/chunk-TPBVVP32.js +0 -2
  67. package/dist/chunks/chunk-XNWSQVXS.js +0 -2
@@ -0,0 +1,37 @@
1
+ export type NlsExpr = {
2
+ type: "number";
3
+ value: number;
4
+ } | {
5
+ type: "variable";
6
+ name: string;
7
+ } | {
8
+ type: "unary";
9
+ op: "+" | "-";
10
+ value: NlsExpr;
11
+ } | {
12
+ type: "binary";
13
+ op: "+" | "-" | "*" | "/" | "^";
14
+ left: NlsExpr;
15
+ right: NlsExpr;
16
+ } | {
17
+ type: "call";
18
+ name: string;
19
+ args: NlsExpr[];
20
+ };
21
+ export interface ParsedNlsFormula {
22
+ response: string;
23
+ responseExpression: NlsExpr;
24
+ expression: NlsExpr;
25
+ }
26
+ /** Parse a response ~ expression formula without invoking JavaScript or the linear formula parser. */
27
+ export declare function parseNlsFormula(formula: string): ParsedNlsFormula;
28
+ export declare function differentiateNls(expr: NlsExpr, parameter: string): NlsExpr;
29
+ /** Evaluate an expression for one row and one parameter vector. */
30
+ export declare function evaluateNlsExpression(expr: NlsExpr, data: Readonly<Record<string, number>>, parameters: Readonly<Record<string, number>>): number;
31
+ /** Evaluate the mean and its symbolic parameter gradient for one observation. */
32
+ export declare function evaluateNlsWithGradient(expr: NlsExpr, data: Readonly<Record<string, number>>, parameters: Readonly<Record<string, number>>, parameterNames: readonly string[]): {
33
+ value: number;
34
+ gradient: number[];
35
+ };
36
+ /** The supported built-in self-starting model names. */
37
+ export declare const nlsSelfStartNames: readonly string[];
@@ -0,0 +1,295 @@
1
+ // Nonlinear model formula parser, expression evaluator, and symbolic derivatives.
2
+ // Independently derived from elementary calculus and the model equations in oracle/nls-behaviour.md.
3
+ const FUNCTIONS = {
4
+ exp: 1, log: 1, log10: 1, sqrt: 1, abs: 1, sin: 1, cos: 1, tan: 1,
5
+ sinh: 1, cosh: 1, tanh: 1, log1p: 1, atan: 1, asin: 1, acos: 1,
6
+ };
7
+ const SELF_START = {
8
+ SSmicmen: { args: 3, expression: "p1*p0/(p2+p0)" },
9
+ SSlogis: { args: 4, expression: "p1/(1+exp((p2-p0)/p3))" },
10
+ SSasymp: { args: 4, expression: "p1+(p2-p1)*exp(-exp(p3)*p0)" },
11
+ SSasympOff: { args: 4, expression: "p1*(1-exp(-exp(p2)*(p0-p3)))" },
12
+ SSasympOrig: { args: 3, expression: "p1*(1-exp(-exp(p2)*p0))" },
13
+ SSbiexp: { args: 5, expression: "p1*exp(-exp(p2)*p0)+p3*exp(-exp(p4)*p0)" },
14
+ SSfol: { args: 5, expression: "p0*exp(p2)*exp(p3)/(exp(p4)*(exp(p3)-exp(p2)))*(exp(-exp(p2)*p1)-exp(-exp(p3)*p1))" },
15
+ SSfpl: { args: 5, expression: "p1+(p2-p1)/(1+exp((p3-p0)/p4))" },
16
+ SSgompertz: { args: 4, expression: "p1*exp(-p2*p3^p0)" },
17
+ SSweibull: { args: 5, expression: "p1-p2*exp(-exp(p3)*p0^p4)" },
18
+ };
19
+ function tokenize(source) {
20
+ const out = [];
21
+ let i = 0;
22
+ while (i < source.length) {
23
+ const c = source[i];
24
+ if (/\s/.test(c)) {
25
+ i++;
26
+ continue;
27
+ }
28
+ const number = /^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/.exec(source.slice(i));
29
+ if (number) {
30
+ out.push({ kind: "number", text: number[0] });
31
+ i += number[0].length;
32
+ continue;
33
+ }
34
+ const name = /^[A-Za-z.][A-Za-z0-9._]*/.exec(source.slice(i));
35
+ if (name) {
36
+ out.push({ kind: "name", text: name[0] });
37
+ i += name[0].length;
38
+ continue;
39
+ }
40
+ if ("+-*/^(),".includes(c)) {
41
+ out.push({ kind: "operator", text: c });
42
+ i++;
43
+ continue;
44
+ }
45
+ throw new SyntaxError("invalid nonlinear expression: unexpected character " + c);
46
+ }
47
+ out.push({ kind: "end", text: "" });
48
+ return out;
49
+ }
50
+ class ExpressionParser {
51
+ tokens;
52
+ position = 0;
53
+ constructor(source) { this.tokens = tokenize(source); }
54
+ peek() { return this.tokens[this.position]; }
55
+ take() { return this.tokens[this.position++]; }
56
+ accept(text) {
57
+ if (this.peek().text !== text)
58
+ return false;
59
+ this.take();
60
+ return true;
61
+ }
62
+ parse() {
63
+ const value = this.expression(0);
64
+ if (this.peek().kind !== "end")
65
+ throw new SyntaxError("invalid nonlinear expression: trailing input");
66
+ return value;
67
+ }
68
+ primary() {
69
+ const token = this.take();
70
+ if (token.kind === "number") {
71
+ const value = Number(token.text);
72
+ if (!Number.isFinite(value))
73
+ throw new SyntaxError("non-finite numeric literal");
74
+ return { type: "number", value };
75
+ }
76
+ if (token.kind === "name") {
77
+ if (!this.accept("("))
78
+ return { type: "variable", name: token.text };
79
+ const args = [];
80
+ if (!this.accept(")")) {
81
+ do {
82
+ args.push(this.expression(0));
83
+ } while (this.accept(","));
84
+ if (!this.accept(")"))
85
+ throw new SyntaxError("invalid nonlinear expression: missing ')'");
86
+ }
87
+ const expected = FUNCTIONS[token.text] ?? SELF_START[token.text]?.args;
88
+ if (expected === undefined)
89
+ throw new SyntaxError("unsupported nonlinear function: " + token.text);
90
+ if (args.length !== expected)
91
+ throw new SyntaxError(token.text + " expects " + expected + " arguments");
92
+ return { type: "call", name: token.text, args };
93
+ }
94
+ if (token.text === "(") {
95
+ const value = this.expression(0);
96
+ if (!this.accept(")"))
97
+ throw new SyntaxError("invalid nonlinear expression: missing ')'");
98
+ return value;
99
+ }
100
+ if (token.text === "+" || token.text === "-") {
101
+ return { type: "unary", op: token.text, value: this.expression(4) };
102
+ }
103
+ throw new SyntaxError("invalid nonlinear expression: expected a value");
104
+ }
105
+ expression(minBinding) {
106
+ let left = this.primary();
107
+ for (;;) {
108
+ const op = this.peek().text;
109
+ const binding = op === "+" || op === "-" ? 1 : op === "*" || op === "/" ? 2 : op === "^" ? 5 : -1;
110
+ if (binding <= minBinding)
111
+ break;
112
+ this.take();
113
+ const right = this.expression(op === "^" ? binding - 1 : binding);
114
+ left = { type: "binary", op: op, left, right };
115
+ }
116
+ return left;
117
+ }
118
+ }
119
+ /** Parse a response ~ expression formula without invoking JavaScript or the linear formula parser. */
120
+ export function parseNlsFormula(formula) {
121
+ if (typeof formula !== "string")
122
+ throw new TypeError("formula must be a string");
123
+ let depth = 0, split = -1;
124
+ for (let i = 0; i < formula.length; i++) {
125
+ const c = formula[i];
126
+ if (c === "(")
127
+ depth++;
128
+ else if (c === ")")
129
+ depth--;
130
+ else if (c === "~" && depth === 0) {
131
+ if (split !== -1)
132
+ throw new SyntaxError("formula must contain exactly one '~'");
133
+ split = i;
134
+ }
135
+ if (depth < 0)
136
+ throw new SyntaxError("unbalanced parentheses in formula");
137
+ }
138
+ if (depth !== 0)
139
+ throw new SyntaxError("unbalanced parentheses in formula");
140
+ if (split < 0)
141
+ throw new SyntaxError("formula must be response ~ expression");
142
+ const response = formula.slice(0, split).trim();
143
+ if (!response)
144
+ throw new SyntaxError("formula has an empty response expression");
145
+ const responseExpression = new ExpressionParser(response).parse();
146
+ const rhs = formula.slice(split + 1).trim();
147
+ if (!rhs)
148
+ throw new SyntaxError("formula has an empty right-hand side");
149
+ return { response, responseExpression, expression: expandSelfStart(new ExpressionParser(rhs).parse()) };
150
+ }
151
+ function expandSelfStart(expr) {
152
+ if (expr.type === "call" && SELF_START[expr.name]) {
153
+ const spec = SELF_START[expr.name];
154
+ const replacements = new Map();
155
+ expr.args.forEach((arg, i) => replacements.set("p" + i, expandSelfStart(arg)));
156
+ return substitute(new ExpressionParser(spec.expression).parse(), replacements);
157
+ }
158
+ if (expr.type === "call")
159
+ return { ...expr, args: expr.args.map(expandSelfStart) };
160
+ if (expr.type === "unary")
161
+ return { ...expr, value: expandSelfStart(expr.value) };
162
+ if (expr.type === "binary")
163
+ return { ...expr, left: expandSelfStart(expr.left), right: expandSelfStart(expr.right) };
164
+ return expr;
165
+ }
166
+ function substitute(expr, replacements) {
167
+ if (expr.type === "variable")
168
+ return replacements.get(expr.name) ?? expr;
169
+ if (expr.type === "call")
170
+ return { ...expr, args: expr.args.map(x => substitute(x, replacements)) };
171
+ if (expr.type === "unary")
172
+ return { ...expr, value: substitute(expr.value, replacements) };
173
+ if (expr.type === "binary")
174
+ return { ...expr, left: substitute(expr.left, replacements), right: substitute(expr.right, replacements) };
175
+ return expr;
176
+ }
177
+ const num = (value) => ({ type: "number", value });
178
+ const variable = (name) => ({ type: "variable", name });
179
+ const binary = (op, left, right) => ({ type: "binary", op, left, right });
180
+ const call = (name, ...args) => ({ type: "call", name, args });
181
+ /** Construct the symbolic derivative of an expression with respect to one parameter. */
182
+ function isZeroDerivative(expr) {
183
+ if (expr.type === "number")
184
+ return expr.value === 0;
185
+ if (expr.type === "unary")
186
+ return isZeroDerivative(expr.value);
187
+ if (expr.type === "binary" && (expr.op === "+" || expr.op === "-"))
188
+ return isZeroDerivative(expr.left) && isZeroDerivative(expr.right);
189
+ if (expr.type === "binary" && expr.op === "*")
190
+ return isZeroDerivative(expr.left) || isZeroDerivative(expr.right);
191
+ if (expr.type === "binary" && expr.op === "/")
192
+ return isZeroDerivative(expr.left);
193
+ return false;
194
+ }
195
+ export function differentiateNls(expr, parameter) {
196
+ switch (expr.type) {
197
+ case "number": return num(0);
198
+ case "variable": return num(expr.name === parameter ? 1 : 0);
199
+ case "unary": return { type: "unary", op: expr.op, value: differentiateNls(expr.value, parameter) };
200
+ case "binary": {
201
+ const u = expr.left, v = expr.right, du = differentiateNls(u, parameter), dv = differentiateNls(v, parameter);
202
+ switch (expr.op) {
203
+ case "+": return binary("+", du, dv);
204
+ case "-": return binary("-", du, dv);
205
+ case "*": return binary("+", binary("*", du, v), binary("*", u, dv));
206
+ case "/": return binary("/", binary("-", binary("*", du, v), binary("*", u, dv)), binary("^", v, num(2)));
207
+ case "^": return isZeroDerivative(dv)
208
+ ? binary("*", binary("*", v, binary("^", u, binary("-", v, num(1)))), du)
209
+ : binary("*", binary("^", u, v), binary("+", binary("*", dv, call("log", u)), binary("/", binary("*", v, du), u)));
210
+ }
211
+ }
212
+ case "call": {
213
+ const x = expr.args[0];
214
+ const dx = differentiateNls(x, parameter);
215
+ switch (expr.name) {
216
+ case "exp": return binary("*", call("exp", x), dx);
217
+ case "log": return binary("/", dx, x);
218
+ case "log10": return binary("/", dx, binary("*", x, num(Math.LN10)));
219
+ case "log1p": return binary("/", dx, binary("+", num(1), x));
220
+ case "sqrt": return binary("/", dx, binary("*", num(2), call("sqrt", x)));
221
+ case "abs": return binary("*", call("sign", x), dx);
222
+ case "sin": return binary("*", call("cos", x), dx);
223
+ case "cos": return binary("*", { type: "unary", op: "-", value: call("sin", x) }, dx);
224
+ case "tan": return binary("/", dx, binary("^", call("cos", x), num(2)));
225
+ case "sinh": return binary("*", call("cosh", x), dx);
226
+ case "cosh": return binary("*", call("sinh", x), dx);
227
+ case "tanh": return binary("/", dx, binary("^", call("cosh", x), num(2)));
228
+ case "atan": return binary("/", dx, binary("+", num(1), binary("^", x, num(2))));
229
+ case "asin": return binary("/", dx, call("sqrt", binary("-", num(1), binary("^", x, num(2)))));
230
+ case "acos": return { type: "unary", op: "-", value: binary("/", dx, call("sqrt", binary("-", num(1), binary("^", x, num(2))))) };
231
+ }
232
+ }
233
+ }
234
+ return num(Number.NaN);
235
+ }
236
+ /** Evaluate an expression for one row and one parameter vector. */
237
+ export function evaluateNlsExpression(expr, data, parameters) {
238
+ switch (expr.type) {
239
+ case "number": return expr.value;
240
+ case "variable": {
241
+ if (expr.name === "pi" && Object.prototype.hasOwnProperty.call(data, "pi"))
242
+ return data.pi;
243
+ const value = Object.prototype.hasOwnProperty.call(parameters, expr.name) ? parameters[expr.name] : data[expr.name];
244
+ if (value !== undefined)
245
+ return value;
246
+ if (expr.name === "pi")
247
+ return Math.PI;
248
+ throw new Error("unknown variable in nonlinear formula: " + expr.name);
249
+ }
250
+ case "unary": {
251
+ const value = evaluateNlsExpression(expr.value, data, parameters);
252
+ return expr.op === "-" ? -value : value;
253
+ }
254
+ case "binary": {
255
+ const a = evaluateNlsExpression(expr.left, data, parameters), b = evaluateNlsExpression(expr.right, data, parameters);
256
+ switch (expr.op) {
257
+ case "+": return a + b;
258
+ case "-": return a - b;
259
+ case "*": return a * b;
260
+ case "/": return a / b;
261
+ case "^": return a ** b;
262
+ }
263
+ }
264
+ case "call": {
265
+ const x = evaluateNlsExpression(expr.args[0], data, parameters);
266
+ switch (expr.name) {
267
+ case "exp": return Math.exp(x);
268
+ case "log": return Math.log(x);
269
+ case "log10": return Math.log10(x);
270
+ case "log1p": return Math.log1p(x);
271
+ case "sqrt": return Math.sqrt(x);
272
+ case "abs": return Math.abs(x);
273
+ case "sign": return Math.sign(x);
274
+ case "sin": return Math.sin(x);
275
+ case "cos": return Math.cos(x);
276
+ case "tan": return Math.tan(x);
277
+ case "sinh": return Math.sinh(x);
278
+ case "cosh": return Math.cosh(x);
279
+ case "tanh": return Math.tanh(x);
280
+ case "atan": return Math.atan(x);
281
+ case "asin": return Math.asin(x);
282
+ case "acos": return Math.acos(x);
283
+ }
284
+ }
285
+ }
286
+ return Number.NaN;
287
+ }
288
+ /** Evaluate the mean and its symbolic parameter gradient for one observation. */
289
+ export function evaluateNlsWithGradient(expr, data, parameters, parameterNames) {
290
+ const value = evaluateNlsExpression(expr, data, parameters);
291
+ const gradient = parameterNames.map(name => evaluateNlsExpression(differentiateNls(expr, name), data, parameters));
292
+ return { value, gradient };
293
+ }
294
+ /** The supported built-in self-starting model names. */
295
+ export const nlsSelfStartNames = Object.freeze(Object.keys(SELF_START));
@@ -0,0 +1,341 @@
1
+ import { type FormulaNode } from "./formula.js";
2
+ import { type DesignContrast } from "./modelMatrix.js";
3
+ import type { DataFrame } from "./modelFrame.js";
4
+ import type { Sample } from "../htest/types.js";
5
+ /** Name of the cumulative distribution used by an ordinal regression.
6
+ *
7
+ * @category Regression
8
+ */
9
+ export type PolrMethod = "logistic" | "probit" | "cloglog" | "loglog" | "cauchit";
10
+ /**
11
+ * Options for {@link polr}.
12
+ *
13
+ * @category Regression
14
+ */
15
+ export interface PolrOptions {
16
+ /** Cumulative link. Default `"logistic"`. */
17
+ method?: PolrMethod;
18
+ /** Non-negative prior weights, or the name of a data column. */
19
+ weights?: Sample | string;
20
+ /** Offset added to the linear predictor. */
21
+ offset?: Sample;
22
+ /** Initial slopes followed by the ordered cut-points. */
23
+ start?: Sample;
24
+ /** Contrasts for categorical predictors. */
25
+ contrasts?: Record<string, "contr.treatment" | "contr.sum" | "contr.helmert">;
26
+ /** Explicit response and predictor levels. */
27
+ levels?: Record<string, readonly string[]>;
28
+ /** Maximum optimisation iterations. Default `1000`. */
29
+ maxit?: number;
30
+ /** Relative optimisation tolerance. Default `1e-12`. */
31
+ reltol?: number;
32
+ }
33
+ /** Stored formula, design metadata and observations needed by prediction and model comparison.
34
+ *
35
+ * @category Regression
36
+ */
37
+ export interface PolrModel {
38
+ /** Original model formula. */
39
+ formula: string;
40
+ /** Parsed formula syntax tree; internal implementation detail. @internal */
41
+ rhs: FormulaNode;
42
+ /** Predictor variable names in model-matrix order. */
43
+ predictorVariables: string[];
44
+ /** Observed or declared levels for categorical predictors. */
45
+ factorLevels: Record<string, readonly string[]>;
46
+ /** Contrast matrices used to construct the design; internal representation. @internal */
47
+ contrasts: Record<string, DesignContrast>;
48
+ /** Name of the data column used as an offset, when supplied by name. */
49
+ offsetColumn?: string;
50
+ /** Whether the offset was supplied separately from the formula. */
51
+ externalOffset: boolean;
52
+ /** Response column name. */
53
+ response: string;
54
+ /** Retained design matrix. */
55
+ x: number[][];
56
+ /** Names of design-matrix columns. */
57
+ columnNames: string[];
58
+ /** Response values encoded as ordered category indices. */
59
+ y: number[];
60
+ /** Ordered response category labels. */
61
+ responseLevels: string[];
62
+ /** Prior weights for retained observations. */
63
+ weights: number[];
64
+ /** Offset values for retained observations. */
65
+ offset: number[];
66
+ /** Original row indices retained after missing-value handling. */
67
+ rows: number[];
68
+ /** Cumulative-link distribution. */
69
+ method: PolrMethod;
70
+ /** Maximised log likelihood. */
71
+ logLikelihood: number;
72
+ /** Internal unconstrained optimisation parameters. */
73
+ theta: number[];
74
+ /** Observed Hessian in internal parameter coordinates. */
75
+ rawHessian: number[][];
76
+ }
77
+ /**
78
+ * Result of {@link polr}: cumulative-link estimates and their observed-information covariance.
79
+ *
80
+ * @category Regression
81
+ */
82
+ export interface PolrResult {
83
+ /** Named slope estimates, excluding the cut-points. */
84
+ coefficients: Record<string, number>;
85
+ /** Named ordered cut-points, separately from the slopes. */
86
+ zeta: Record<string, number>;
87
+ /** Fitted category probabilities, one row per retained observation. */
88
+ fittedValues: number[][];
89
+ /** Linear predictors, offset included. */
90
+ linearPredictors: number[];
91
+ /** Residual deviance, `-2 logLik`. */
92
+ deviance: number;
93
+ /** Maximised log likelihood. */
94
+ logLik: number;
95
+ /** Akaike information criterion. */
96
+ aic: number;
97
+ /** Bayesian information criterion. */
98
+ bic: number;
99
+ /** Number of estimated slopes and cut-points. */
100
+ edf: number;
101
+ /** Sum of the positive case weights. */
102
+ nobs: number;
103
+ /** Whether the numerical optimisation converged. */
104
+ converged: boolean;
105
+ /** Optimiser convergence code. */
106
+ convergence: number;
107
+ /** Distinct warnings in first-occurrence order. */
108
+ warnings: string[];
109
+ /** Data and numerical state retained for the companion methods. */
110
+ model: PolrModel;
111
+ }
112
+ /** Table of slope and cut-point estimates, standard errors and Wald statistics.
113
+ *
114
+ * @category Regression
115
+ */
116
+ export interface PolrSummaryResult {
117
+ /** Coefficient and cut-point names. */
118
+ rows: string[];
119
+ /** Summary statistic column names. */
120
+ columns: ["Value", "Std. Error", "t value"];
121
+ /** Rows of estimates, standard errors and test statistics. */
122
+ values: number[][];
123
+ /** Warnings produced while computing the summary. */
124
+ warnings: string[];
125
+ }
126
+ /** Covariance matrix of the slope and cut-point estimates in coefficient order.
127
+ *
128
+ * @category Regression
129
+ */
130
+ export interface PolrVcovResult {
131
+ /** Parameter names in matrix row order. */
132
+ rows: string[];
133
+ /** Parameter names in matrix column order. */
134
+ columns: string[];
135
+ /** Covariance matrix values. */
136
+ values: number[][];
137
+ /** Warnings produced while computing the covariance. */
138
+ warnings: string[];
139
+ }
140
+ /**
141
+ * Options for {@link polrConfint}.
142
+ *
143
+ * @category Regression
144
+ */
145
+ export interface PolrConfintOptions {
146
+ /** Interval method. Default "profile". */
147
+ method?: "profile" | "wald";
148
+ /** Confidence level. Default 0.95. */
149
+ level?: number;
150
+ /** Slope names or 1-based slope positions. Omitted means all slopes. */
151
+ parm?: string | number | readonly (string | number)[];
152
+ }
153
+ /**
154
+ * Confidence intervals for ordinal-regression slopes.
155
+ *
156
+ * @category Regression
157
+ */
158
+ export interface PolrConfintResult {
159
+ /** Parameter names for the intervals. */
160
+ rows: string[];
161
+ /** Lower and upper confidence-limit labels. */
162
+ columns: string[];
163
+ /** Confidence limits, one pair per parameter. */
164
+ values: number[][];
165
+ /** Warnings produced while computing the intervals. */
166
+ warnings: string[];
167
+ }
168
+ /**
169
+ * Options for {@link polrPredict}.
170
+ *
171
+ * @category Regression
172
+ */
173
+ export interface PolrPredictOptions {
174
+ /** New predictor columns; omitted to return predictions for the fitted observations. */
175
+ newdata?: DataFrame;
176
+ /** Row labels for a new data frame (default: "1", "2", ...). */
177
+ rowNames?: readonly string[];
178
+ /** Return the most likely category (default) or the category probabilities. */
179
+ type?: "class" | "probs";
180
+ }
181
+ /**
182
+ * Probability matrix returned when {@link PolrPredictOptions.type} is "probs".
183
+ *
184
+ * @category Regression
185
+ */
186
+ export interface PolrPredictProbs {
187
+ /** Prediction row labels. */
188
+ rows: string[];
189
+ /** Response category labels. */
190
+ columns: string[];
191
+ /** Predicted category probabilities; null marks an unavailable value. */
192
+ values: (number | null)[][];
193
+ /** Warnings produced while predicting. */
194
+ warnings: string[];
195
+ }
196
+ /**
197
+ * Predicted categories, or a probability matrix when type is "probs".
198
+ *
199
+ * @category Regression
200
+ */
201
+ export type PolrPredictResult = (string | null)[] | PolrPredictProbs;
202
+ type PolrDerivatives = {
203
+ value: number;
204
+ gradient: number[];
205
+ hessian: number[][];
206
+ };
207
+ /** Internal derivative hook used by finite-difference verification in the model tests. */
208
+ export declare function __polrDerivativesForTest(x: readonly (readonly number[])[], y: readonly number[], weights: readonly number[], offset: readonly number[], levels: number, method: PolrMethod, theta: readonly number[]): PolrDerivatives;
209
+ /**
210
+ * Fit a cumulative-link ordinal regression. Equivalent to R's `MASS::polr()`.
211
+ *
212
+ * @param formula A formula such as `"rating ~ treatment + age"`.
213
+ * @param data The data frame: an object of columns.
214
+ * @param options The link, weights, offset, starts, contrasts and optimisation controls.
215
+ * @returns The fitted slopes, cut-points, fitted probabilities and likelihood statistics.
216
+ *
217
+ * @example
218
+ * ```ts
219
+ * const fit = polr("rating ~ dose", { rating: ["low", "medium", "high", "low", "medium", "high"], dose: [0, 1, 2, 0, 1, 2] });
220
+ * fit.zeta;
221
+ * ```
222
+ *
223
+ * @category Regression
224
+ */
225
+ export declare function polr(formula: string, data: DataFrame, options?: PolrOptions): PolrResult;
226
+ /**
227
+ * Predict ordinal categories or their probabilities for new observations. Equivalent to R's `predict.polr()`.
228
+ *
229
+ * @param fit A fit returned by {@link polr}.
230
+ * @param options New predictor columns, optional row labels, and the prediction type.
231
+ * @returns Predicted category labels, or a matrix with one probability column per response level.
232
+ *
233
+ * @example
234
+ * ```ts
235
+ * const fit = polr("rating ~ dose", { rating: ["low", "medium", "high", "low", "medium", "high"], dose: [0, 1, 2, 0, 1, 2] });
236
+ * polrPredict(fit, { newdata: { dose: [0, 1, 2] } });
237
+ * ```
238
+ *
239
+ * @category Regression
240
+ */
241
+ export declare function polrPredict(fit: PolrResult, options?: PolrPredictOptions): PolrPredictResult;
242
+ /**
243
+ * Summary table of the slope and cut-point estimates. Equivalent to R's `summary.polr()`.
244
+ *
245
+ * @param fit A fit returned by {@link polr}.
246
+ * @returns Estimates, standard errors and Wald t statistics.
247
+ *
248
+ * @category Regression
249
+ */
250
+ export declare function polrSummary(fit: PolrResult): PolrSummaryResult;
251
+ /**
252
+ * Covariance matrix of the slopes and cut-points. Equivalent to R's `vcov.polr()`.
253
+ *
254
+ * @param fit A fit returned by {@link polr}.
255
+ * @returns The covariance matrix in slope-then-cut-point order.
256
+ *
257
+ * @category Regression
258
+ */
259
+ export declare function polrVcov(fit: PolrResult): PolrVcovResult;
260
+ /**
261
+ * Equivalent to R's `confint.polr()`.
262
+ *
263
+ * @param fit A fit returned by {@link polr}.
264
+ * @param options The interval method, confidence level and selected slope parameters.
265
+ * @returns A table of lower and upper confidence limits; cut-points are not included.
266
+ *
267
+ * @example
268
+ * ```ts
269
+ * const fit = polr("rating ~ dose", { rating: ["low", "medium", "high", "low", "medium", "high"], dose: [0, 1, 2, 0, 1, 2] });
270
+ * polrConfint(fit, { method: "wald", level: 0.95 });
271
+ * ```
272
+ *
273
+ * @category Regression
274
+ */
275
+ export declare function polrConfint(fit: PolrResult, options?: PolrConfintOptions): PolrConfintResult;
276
+ /** Result table from sequential likelihood-ratio comparisons of nested ordinal-regression fits.
277
+ *
278
+ * @category Regression
279
+ */
280
+ export interface PolrAnovaResult {
281
+ /** Likelihood-ratio analysis-of-deviance table. */
282
+ table: {
283
+ /** Formula or term label for each fitted model. */
284
+ Model: string[];
285
+ /** Residual degrees of freedom for each model. */
286
+ "Resid. df": number[];
287
+ /** Residual deviance for each model. */
288
+ "Resid. Dev": number[];
289
+ /** Label of each sequential model comparison. */
290
+ Test: string[];
291
+ /** Degrees of freedom for each likelihood-ratio test. */
292
+ " Df": (number | "NA")[];
293
+ /** Likelihood-ratio statistic for each comparison. */
294
+ "LR stat.": (number | "NA")[];
295
+ /** Chi-squared tail probability for each comparison. */
296
+ "Pr(Chi)": (number | "NA")[];
297
+ };
298
+ /** Model or term labels associated with the comparison. */
299
+ rows: string[];
300
+ /** Heading describing the comparison. */
301
+ heading: string[];
302
+ /** Warnings produced while comparing models. */
303
+ warnings: string[];
304
+ }
305
+ /**
306
+ * Equivalent to R's `anova.polr()`.
307
+ *
308
+ * @param fits Two or more nested fits, ordered from the smallest to the largest model.
309
+ * @returns The sequential likelihood-ratio chi-squared comparison table.
310
+ *
311
+ * @example
312
+ * ```ts
313
+ * const data = {
314
+ * rating: [
315
+ * "low", "low", "low", "medium", "medium", "high",
316
+ * "low", "low", "medium", "medium", "medium", "high",
317
+ * "low", "medium", "medium", "medium", "high", "high",
318
+ * "low", "low", "medium", "medium", "medium", "high",
319
+ * "low", "medium", "medium", "medium", "high", "high",
320
+ * "low", "medium", "medium", "high", "high", "high",
321
+ * ],
322
+ * dose: [
323
+ * 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1,
324
+ * 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0,
325
+ * 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
326
+ * ],
327
+ * treatment: [
328
+ * "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A",
329
+ * "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B",
330
+ * "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B",
331
+ * ],
332
+ * };
333
+ * const small = polr("rating ~ dose", data);
334
+ * const large = polr("rating ~ dose + treatment", data);
335
+ * polrAnova(small, large);
336
+ * ```
337
+ *
338
+ * @category Regression
339
+ */
340
+ export declare function polrAnova(...fits: PolrResult[]): PolrAnovaResult;
341
+ export {};