@numero-uno-jpn/rstats 0.8.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +88 -0
- package/README.ja.md +89 -13
- package/README.md +90 -13
- package/THIRD_PARTY_NOTICES.md +12 -2
- package/dist/chunks/{chunk-OHPHNE3O.js → chunk-2XKG3DX4.js} +1 -1
- package/dist/chunks/{chunk-3I6EKGB6.js → chunk-4NM37MGA.js} +2 -2
- package/dist/chunks/chunk-7HPVUVZB.js +2 -0
- package/dist/chunks/{chunk-I3LAZE6C.js → chunk-AECGWZHD.js} +2 -2
- package/dist/chunks/chunk-ENL43FNO.js +2 -0
- package/dist/chunks/chunk-EWC6I75B.js +2 -0
- package/dist/chunks/chunk-IT354SHV.js +3 -0
- package/dist/chunks/{chunk-VIPSPG3Y.js → chunk-LIMZKONM.js} +2 -2
- package/dist/chunks/chunk-O6PT7IVU.js +2 -0
- package/dist/chunks/{chunk-YGWPU67I.js → chunk-QFULZNHL.js} +1 -1
- package/dist/chunks/{chunk-XU4BGFZ6.js → chunk-QJJWGNJP.js} +2 -2
- package/dist/chunks/{chunk-32PRRONF.js → chunk-QULPY6YM.js} +1 -1
- package/dist/chunks/chunk-XWTZ4RTR.js +2 -0
- package/dist/chunks/chunk-ZRIM4R4A.js +2 -0
- package/dist/descriptive/factanal.d.ts +56 -0
- package/dist/descriptive/factanal.js +186 -0
- package/dist/descriptive/omega.d.ts +56 -0
- package/dist/descriptive/omega.js +323 -0
- package/dist/descriptive.js +2 -2
- package/dist/distributions/bvnorm.d.ts +15 -0
- package/dist/distributions/bvnorm.js +131 -0
- package/dist/distributions/nbeta.js +34 -1
- package/dist/distributions/nchisq.d.ts +10 -0
- package/dist/distributions/nchisq.js +46 -0
- package/dist/distributions.js +2 -2
- package/dist/entries/distributions.d.ts +1 -0
- package/dist/entries/distributions.js +1 -0
- package/dist/entries/linalg.d.ts +2 -0
- package/dist/entries/linalg.js +2 -0
- package/dist/entries/numerics.d.ts +2 -0
- package/dist/entries/numerics.js +1 -0
- package/dist/entries/tests.d.ts +25 -1
- package/dist/entries/tests.js +22 -1
- package/dist/htest/agreement.d.ts +141 -0
- package/dist/htest/agreement.js +274 -0
- package/dist/htest/aov.d.ts +19 -0
- package/dist/htest/aov.js +22 -15
- package/dist/htest/core/simulate.d.ts +2 -0
- package/dist/htest/core/simulate.js +1 -1
- package/dist/htest/dunnett.d.ts +5 -0
- package/dist/htest/dunnett.js +89 -0
- package/dist/htest/effectSize.d.ts +112 -0
- package/dist/htest/effectSize.js +385 -0
- package/dist/htest/leveneTest.d.ts +30 -0
- package/dist/htest/leveneTest.js +41 -0
- package/dist/htest/multipleComparisons.d.ts +147 -0
- package/dist/htest/multipleComparisons.js +369 -0
- package/dist/htest/normalityTests.d.ts +44 -0
- package/dist/htest/normalityTests.js +164 -0
- package/dist/htest/polycor.d.ts +117 -0
- package/dist/htest/polycor.js +468 -0
- package/dist/htest/power.d.ts +132 -0
- package/dist/htest/power.js +227 -0
- package/dist/htest/pwr.d.ts +263 -0
- package/dist/htest/pwr.js +440 -0
- package/dist/htest/rankTests.d.ts +7 -0
- package/dist/htest/rankTests.js +11 -1
- package/dist/htest/trendTests.d.ts +57 -0
- package/dist/htest/trendTests.js +167 -0
- package/dist/linalg/eigen.d.ts +8 -0
- package/dist/linalg/eigen.js +5 -4
- package/dist/linalg/expm.d.ts +48 -0
- package/dist/linalg/expm.js +472 -0
- package/dist/linalg/schur.d.ts +48 -0
- package/dist/linalg/schur.js +225 -0
- package/dist/linalg.js +2 -2
- package/dist/models/anovaSequential.d.ts +58 -0
- package/dist/models/anovaSequential.js +138 -0
- package/dist/models/aovEz.d.ts +64 -0
- package/dist/models/aovEz.js +332 -0
- package/dist/models/aovStrata.d.ts +32 -0
- package/dist/models/aovStrata.js +104 -0
- package/dist/models/carAnova.d.ts +30 -0
- package/dist/models/carAnova.js +121 -0
- package/dist/models/coxph.d.ts +101 -0
- package/dist/models/coxph.js +502 -0
- package/dist/models/ddLeastSquares.d.ts +30 -0
- package/dist/models/ddLeastSquares.js +90 -0
- package/dist/models/ddMatrix.d.ts +10 -0
- package/dist/models/ddMatrix.js +91 -0
- package/dist/models/formula.d.ts +83 -0
- package/dist/models/formula.js +333 -0
- package/dist/models/glm.d.ts +226 -0
- package/dist/models/glm.js +546 -0
- package/dist/models/glmAnova.d.ts +31 -0
- package/dist/models/glmAnova.js +146 -0
- package/dist/models/glmConfint.d.ts +25 -0
- package/dist/models/glmConfint.js +139 -0
- package/dist/models/glmFamily.d.ts +66 -0
- package/dist/models/glmFamily.js +359 -0
- package/dist/models/lm.d.ts +84 -3
- package/dist/models/lm.js +141 -44
- package/dist/models/mauchly.d.ts +48 -0
- package/dist/models/mauchly.js +123 -0
- package/dist/models/modelFrame.d.ts +40 -0
- package/dist/models/modelFrame.js +131 -0
- package/dist/models/modelMatrix.d.ts +88 -0
- package/dist/models/modelMatrix.js +170 -0
- package/dist/models/survival.d.ts +87 -0
- package/dist/models/survival.js +238 -0
- package/dist/numerics.js +2 -2
- package/dist/optim/lbfgsb.d.ts +20 -0
- package/dist/optim/lbfgsb.js +1240 -0
- package/dist/optim/optim.d.ts +85 -0
- package/dist/optim/optim.js +610 -0
- package/dist/rstats.js +19 -3
- package/dist/special.js +2 -2
- package/dist/tests.js +18 -3
- package/llms.txt +102 -0
- package/package.json +3 -2
- package/dist/chunks/chunk-EJRCDJ76.js +0 -2
- package/dist/chunks/chunk-JERGQKZM.js +0 -2
- package/dist/chunks/chunk-JVYV4633.js +0 -2
- package/dist/chunks/chunk-LXMMKO26.js +0 -2
- package/dist/chunks/chunk-MJQLKEO5.js +0 -2
- package/dist/chunks/chunk-RZ7SBJEG.js +0 -2
- package/dist/chunks/chunk-SPQC445Q.js +0 -2
- package/dist/chunks/chunk-U633VFH3.js +0 -2
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
// Families and links of R's glm: variance functions, links with their inverses and derivatives (with R's clamps),
|
|
2
|
+
// deviance contributions, the AIC, the checks of the response and the starting means.
|
|
3
|
+
//
|
|
4
|
+
// Written for rStats.js (no ported code) from the description in oracle/glm-behaviour.md, R's help pages (?family,
|
|
5
|
+
// ?glm) and McCullagh and Nelder (1989), Generalized Linear Models, 2nd ed., chapter 2 (the variance functions and
|
|
6
|
+
// deviances of table 2.1).
|
|
7
|
+
import { pcauchy1, qcauchy1, dcauchy1 } from "../distributions/cauchy.js";
|
|
8
|
+
import { dbinom1 } from "../distributions/binomial.js";
|
|
9
|
+
import { dgamma1 } from "../distributions/gamma.js";
|
|
10
|
+
import { dnorm, pnorm, qnorm } from "../distributions/normal.js";
|
|
11
|
+
import { dpois1, nonInteger } from "../distributions/poisson.js";
|
|
12
|
+
import { roundHalfEven } from "../internal/integer.js";
|
|
13
|
+
const EPS = 2 ** -52;
|
|
14
|
+
const ALLOWED = {
|
|
15
|
+
gaussian: ["identity", "log", "inverse"],
|
|
16
|
+
binomial: ["logit", "probit", "cauchit", "log", "cloglog"],
|
|
17
|
+
quasibinomial: ["logit", "probit", "cauchit", "log", "cloglog"],
|
|
18
|
+
poisson: ["log", "identity", "sqrt"],
|
|
19
|
+
quasipoisson: ["log", "identity", "sqrt"],
|
|
20
|
+
Gamma: ["inverse", "identity", "log"],
|
|
21
|
+
"inverse.gaussian": ["1/mu^2", "inverse", "identity", "log"],
|
|
22
|
+
quasi: ["identity", "logit", "probit", "cloglog", "inverse", "log", "1/mu^2", "sqrt"],
|
|
23
|
+
};
|
|
24
|
+
const positive = (eta) => Number.isFinite(eta) && eta > 0;
|
|
25
|
+
const anyEta = () => true;
|
|
26
|
+
/** Collects warnings in order of first appearance, each once (as the fixtures list R's warnings) */
|
|
27
|
+
export class Warnings {
|
|
28
|
+
list = [];
|
|
29
|
+
add(message) {
|
|
30
|
+
if (!this.list.includes(message))
|
|
31
|
+
this.list.push(message);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** The warnings sink of the link functions that warn ("NaNs produced"); set while a fit runs */
|
|
35
|
+
let currentWarnings;
|
|
36
|
+
export function withWarnings(sink, f) {
|
|
37
|
+
const saved = currentWarnings;
|
|
38
|
+
currentWarnings = sink;
|
|
39
|
+
try {
|
|
40
|
+
return f();
|
|
41
|
+
}
|
|
42
|
+
finally {
|
|
43
|
+
currentWarnings = saved;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/** Square root that warns as R's sqrt does when it produces NaN */
|
|
47
|
+
function sqrtWarn(x) {
|
|
48
|
+
if (x < 0)
|
|
49
|
+
currentWarnings?.add("NaNs produced");
|
|
50
|
+
return Math.sqrt(x);
|
|
51
|
+
}
|
|
52
|
+
function namedLink(name) {
|
|
53
|
+
switch (name) {
|
|
54
|
+
case "identity":
|
|
55
|
+
return { name, link: (m) => m, linkinv: (e) => e, muEta: () => 1, etaOk: anyEta };
|
|
56
|
+
case "log":
|
|
57
|
+
return {
|
|
58
|
+
name,
|
|
59
|
+
link: Math.log,
|
|
60
|
+
linkinv: (e) => Math.max(Math.exp(e), EPS),
|
|
61
|
+
muEta: (e) => Math.max(Math.exp(e), EPS),
|
|
62
|
+
etaOk: anyEta,
|
|
63
|
+
};
|
|
64
|
+
case "inverse":
|
|
65
|
+
return {
|
|
66
|
+
name,
|
|
67
|
+
link: (m) => 1 / m,
|
|
68
|
+
linkinv: (e) => 1 / e,
|
|
69
|
+
muEta: (e) => -1 / (e * e),
|
|
70
|
+
etaOk: (e) => Number.isFinite(e) && e !== 0,
|
|
71
|
+
};
|
|
72
|
+
case "sqrt":
|
|
73
|
+
return { name, link: Math.sqrt, linkinv: (e) => e * e, muEta: (e) => 2 * e, etaOk: positive };
|
|
74
|
+
case "1/mu^2":
|
|
75
|
+
return {
|
|
76
|
+
name,
|
|
77
|
+
link: (m) => 1 / (m * m),
|
|
78
|
+
linkinv: (e) => 1 / sqrtWarn(e),
|
|
79
|
+
muEta: (e) => -1 / (2 * e ** 1.5),
|
|
80
|
+
etaOk: positive,
|
|
81
|
+
};
|
|
82
|
+
case "logit":
|
|
83
|
+
return {
|
|
84
|
+
name,
|
|
85
|
+
link: (m) => Math.log(m / (1 - m)),
|
|
86
|
+
linkinv: (e) => {
|
|
87
|
+
const t = e < -30 ? EPS : e > 30 ? 1 / EPS : Math.exp(e);
|
|
88
|
+
return t / (1 + t);
|
|
89
|
+
},
|
|
90
|
+
muEta: (e) => {
|
|
91
|
+
if (Math.abs(e) > 30)
|
|
92
|
+
return EPS;
|
|
93
|
+
const t = Math.exp(e);
|
|
94
|
+
return t / ((1 + t) * (1 + t));
|
|
95
|
+
},
|
|
96
|
+
etaOk: anyEta,
|
|
97
|
+
};
|
|
98
|
+
case "probit": {
|
|
99
|
+
const c = -qnorm(EPS);
|
|
100
|
+
return {
|
|
101
|
+
name,
|
|
102
|
+
link: (m) => qnorm(m),
|
|
103
|
+
linkinv: (e) => pnorm(Math.min(Math.max(e, -c), c)),
|
|
104
|
+
muEta: (e) => Math.max(dnorm(e), EPS),
|
|
105
|
+
etaOk: anyEta,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
case "cauchit": {
|
|
109
|
+
const c = -qcauchy1(EPS, 0, 1, true, false);
|
|
110
|
+
return {
|
|
111
|
+
name,
|
|
112
|
+
link: (m) => qcauchy1(m, 0, 1, true, false),
|
|
113
|
+
linkinv: (e) => pcauchy1(Math.min(Math.max(e, -c), c), 0, 1, true, false),
|
|
114
|
+
muEta: (e) => Math.max(dcauchy1(e, 0, 1, false), EPS),
|
|
115
|
+
etaOk: anyEta,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
case "cloglog":
|
|
119
|
+
return {
|
|
120
|
+
name,
|
|
121
|
+
link: (m) => Math.log(-Math.log(1 - m)),
|
|
122
|
+
linkinv: (e) => Math.min(Math.max(-Math.expm1(-Math.exp(e)), EPS), 1 - EPS),
|
|
123
|
+
muEta: (e) => {
|
|
124
|
+
const t = Math.min(e, 700);
|
|
125
|
+
return Math.max(Math.exp(t) * Math.exp(-Math.exp(t)), EPS);
|
|
126
|
+
},
|
|
127
|
+
etaOk: anyEta,
|
|
128
|
+
};
|
|
129
|
+
default:
|
|
130
|
+
throw new RangeError(`unknown link "${String(name)}"`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
/** R's power(lambda): the log link for lambda <= 0, the identity for 1, else mu^lambda */
|
|
134
|
+
function powerLink(lambda) {
|
|
135
|
+
if (!Number.isFinite(lambda))
|
|
136
|
+
throw new RangeError("invalid power for the power link");
|
|
137
|
+
if (lambda <= 0)
|
|
138
|
+
return namedLink("log");
|
|
139
|
+
if (lambda === 1)
|
|
140
|
+
return namedLink("identity");
|
|
141
|
+
const inv = 1 / lambda;
|
|
142
|
+
return {
|
|
143
|
+
name: `mu^${Math.round(lambda * 1000) / 1000}`,
|
|
144
|
+
link: (m) => m ** lambda,
|
|
145
|
+
linkinv: (e) => Math.max(e ** inv, EPS),
|
|
146
|
+
muEta: (e) => Math.max(inv * e ** (inv - 1), EPS),
|
|
147
|
+
etaOk: positive,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
function quasiVariance(v) {
|
|
151
|
+
switch (v) {
|
|
152
|
+
case "constant":
|
|
153
|
+
return { variance: () => 1, muOk: () => true, dev: (y, mu, w) => w * (y - mu) ** 2 };
|
|
154
|
+
case "mu(1-mu)":
|
|
155
|
+
return { variance: (m) => m * (1 - m), muOk: (m) => m > 0 && m < 1, dev: binomialDev };
|
|
156
|
+
case "mu":
|
|
157
|
+
return {
|
|
158
|
+
variance: (m) => m,
|
|
159
|
+
muOk: (m) => m > 0,
|
|
160
|
+
dev: (y, mu, w) => 2 * w * ((y === 0 ? 0 : y * Math.log(y / mu)) - (y - mu)),
|
|
161
|
+
};
|
|
162
|
+
case "mu^2":
|
|
163
|
+
return {
|
|
164
|
+
variance: (m) => m * m,
|
|
165
|
+
muOk: (m) => m > 0,
|
|
166
|
+
dev: (y, mu, w) => Math.max(-2 * w * (Math.log(y > 0 ? y / mu : 1 / mu) - (y - mu) / mu), 0),
|
|
167
|
+
};
|
|
168
|
+
case "mu^3":
|
|
169
|
+
return { variance: (m) => m * m * m, muOk: (m) => m > 0, dev: inverseGaussianDev };
|
|
170
|
+
default:
|
|
171
|
+
throw new RangeError(`'variance' "${String(v)}" is invalid: possible values are "mu(1-mu)", "mu", "mu^2", "mu^3" and "constant"`);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
function binomialDev(y, mu, w) {
|
|
175
|
+
const a = y === 0 ? 0 : y * Math.log(y / mu);
|
|
176
|
+
const b = y === 1 ? 0 : (1 - y) * Math.log((1 - y) / (1 - mu));
|
|
177
|
+
return 2 * w * (a + b);
|
|
178
|
+
}
|
|
179
|
+
function inverseGaussianDev(y, mu, w) {
|
|
180
|
+
return (w * (y - mu) ** 2) / (y * mu * mu);
|
|
181
|
+
}
|
|
182
|
+
/** Resolves a family name or specification (and a link given separately) to its functions */
|
|
183
|
+
export function makeFamily(family, link) {
|
|
184
|
+
const spec = typeof family === "string" ? { family } : family;
|
|
185
|
+
const name = spec.family;
|
|
186
|
+
const allowed = ALLOWED[name];
|
|
187
|
+
if (allowed === undefined)
|
|
188
|
+
throw new RangeError(`unknown family "${String(name)}"`);
|
|
189
|
+
const lk = link ?? spec.link ?? allowed[0];
|
|
190
|
+
let lf;
|
|
191
|
+
if (typeof lk === "object") {
|
|
192
|
+
if (name !== "quasi")
|
|
193
|
+
throw new RangeError(`link "power" not available for ${name} family`);
|
|
194
|
+
lf = powerLink(lk.power);
|
|
195
|
+
}
|
|
196
|
+
else {
|
|
197
|
+
if (!allowed.includes(lk)) {
|
|
198
|
+
throw new RangeError(`link "${lk}" not available for ${name} family; available links are ${allowed.map((a) => `'${a}'`).join(", ")}`);
|
|
199
|
+
}
|
|
200
|
+
lf = namedLink(lk);
|
|
201
|
+
}
|
|
202
|
+
if (spec.variance !== undefined && name !== "quasi")
|
|
203
|
+
throw new TypeError("'variance' is only used by the quasi family");
|
|
204
|
+
const base = { ...lf, family: name, varianceName: undefined, fixedDispersion: false };
|
|
205
|
+
switch (name) {
|
|
206
|
+
case "gaussian":
|
|
207
|
+
return { ...base, variance: () => 1, muOk: () => true, devContribution: (y, mu, w) => w * (y - mu) ** 2 };
|
|
208
|
+
case "binomial":
|
|
209
|
+
case "quasibinomial":
|
|
210
|
+
return {
|
|
211
|
+
...base,
|
|
212
|
+
fixedDispersion: name === "binomial",
|
|
213
|
+
variance: (m) => m * (1 - m),
|
|
214
|
+
muOk: (m) => Number.isFinite(m) && m > 0 && m < 1,
|
|
215
|
+
devContribution: binomialDev,
|
|
216
|
+
};
|
|
217
|
+
case "poisson":
|
|
218
|
+
case "quasipoisson":
|
|
219
|
+
return {
|
|
220
|
+
...base,
|
|
221
|
+
fixedDispersion: name === "poisson",
|
|
222
|
+
variance: (m) => m,
|
|
223
|
+
muOk: (m) => Number.isFinite(m) && m > 0,
|
|
224
|
+
devContribution: (y, mu, w) => (y > 0 ? 2 * w * (y * Math.log(y / mu) - (y - mu)) : 2 * w * mu),
|
|
225
|
+
};
|
|
226
|
+
case "Gamma":
|
|
227
|
+
return {
|
|
228
|
+
...base,
|
|
229
|
+
variance: (m) => m * m,
|
|
230
|
+
muOk: (m) => Number.isFinite(m) && m > 0,
|
|
231
|
+
devContribution: (y, mu, w) => -2 * w * ((y === 0 ? 0 : Math.log(y / mu)) - (y - mu) / mu),
|
|
232
|
+
};
|
|
233
|
+
case "inverse.gaussian":
|
|
234
|
+
return { ...base, variance: (m) => m * m * m, muOk: () => true, devContribution: inverseGaussianDev };
|
|
235
|
+
case "quasi": {
|
|
236
|
+
const vname = spec.variance ?? "constant";
|
|
237
|
+
const q = quasiVariance(vname);
|
|
238
|
+
return { ...base, varianceName: vname, variance: q.variance, muOk: q.muOk, devContribution: q.dev };
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Checks the response and computes the starting means (R's family initialize). `y` is a vector or, for the binomial
|
|
244
|
+
* families, rows (successes, failures). `hasStart`: starting values were given, so the gaussian check of the
|
|
245
|
+
* starting means is skipped.
|
|
246
|
+
*/
|
|
247
|
+
export function prepareResponse(fam, y, prior, hasStart, warnings) {
|
|
248
|
+
const name = fam.family;
|
|
249
|
+
const binomialLike = name === "binomial" || name === "quasibinomial";
|
|
250
|
+
const twoCol = y.length > 0 && Array.isArray(y[0]);
|
|
251
|
+
if (twoCol) {
|
|
252
|
+
const rows = y;
|
|
253
|
+
// a one-column matrix is a vector
|
|
254
|
+
if (rows.every((r) => r.length === 1))
|
|
255
|
+
return prepareResponse(fam, rows.map((r) => r[0]), prior, hasStart, warnings);
|
|
256
|
+
if (!binomialLike)
|
|
257
|
+
throw new TypeError("y must be a vector (or, for the binomial families, a two-column matrix)");
|
|
258
|
+
if (rows.some((r) => r.length !== 2)) {
|
|
259
|
+
throw new TypeError(`for the '${name}' family, y must be a vector of 0 and 1's\nor a 2 column matrix where col 1 is no. successes and col 2 is no. failures`);
|
|
260
|
+
}
|
|
261
|
+
if (name === "binomial" && rows.some((r) => Math.abs(r[0] - Math.round(r[0])) > 1e-3 || Math.abs(r[1] - Math.round(r[1])) > 1e-3)) {
|
|
262
|
+
warnings.add("non-integer counts in a binomial glm!");
|
|
263
|
+
}
|
|
264
|
+
const size = rows.map((r) => r[0] + r[1]);
|
|
265
|
+
const yy = rows.map((r, i) => (size[i] === 0 ? 0 : r[0] / size[i]));
|
|
266
|
+
const weights = prior.map((w, i) => w * size[i]);
|
|
267
|
+
const mustart = yy.map((v, i) => (size[i] * v + 0.5) / (size[i] + 1));
|
|
268
|
+
return { y: yy, weights, mustart, size };
|
|
269
|
+
}
|
|
270
|
+
const yv = y.slice();
|
|
271
|
+
const weights = prior.slice();
|
|
272
|
+
switch (name) {
|
|
273
|
+
case "binomial":
|
|
274
|
+
case "quasibinomial": {
|
|
275
|
+
for (let i = 0; i < yv.length; i++)
|
|
276
|
+
if (weights[i] === 0)
|
|
277
|
+
yv[i] = 0;
|
|
278
|
+
if (yv.some((v) => v < 0 || v > 1))
|
|
279
|
+
throw new RangeError("y values must be 0 <= y <= 1");
|
|
280
|
+
const mustart = yv.map((v, i) => (weights[i] * v + 0.5) / (weights[i] + 1));
|
|
281
|
+
if (name === "binomial" && yv.some((v, i) => Math.abs(weights[i] * v - Math.round(weights[i] * v)) > 1e-3)) {
|
|
282
|
+
warnings.add("non-integer #successes in a binomial glm!");
|
|
283
|
+
}
|
|
284
|
+
return { y: yv, weights, mustart, size: yv.map(() => 1) };
|
|
285
|
+
}
|
|
286
|
+
case "poisson":
|
|
287
|
+
case "quasipoisson":
|
|
288
|
+
if (yv.some((v) => v < 0))
|
|
289
|
+
throw new RangeError(`negative values not allowed for the '${name === "poisson" ? "Poisson" : "quasiPoisson"}' family`);
|
|
290
|
+
return { y: yv, weights, mustart: yv.map((v) => v + 0.1), size: undefined };
|
|
291
|
+
case "Gamma":
|
|
292
|
+
if (yv.some((v) => v <= 0))
|
|
293
|
+
throw new RangeError("non-positive values not allowed for the 'Gamma' family");
|
|
294
|
+
return { y: yv, weights, mustart: yv.slice(), size: undefined };
|
|
295
|
+
case "inverse.gaussian":
|
|
296
|
+
if (yv.some((v) => v <= 0))
|
|
297
|
+
throw new RangeError("positive values only are allowed for the 'inverse.gaussian' family");
|
|
298
|
+
return { y: yv, weights, mustart: yv.slice(), size: undefined };
|
|
299
|
+
case "gaussian":
|
|
300
|
+
if (!hasStart && ((fam.name === "inverse" && yv.some((v) => v === 0)) || (fam.name === "log" && yv.some((v) => v <= 0)))) {
|
|
301
|
+
throw new Error("cannot find valid starting values: please specify some");
|
|
302
|
+
}
|
|
303
|
+
return { y: yv, weights, mustart: yv.slice(), size: undefined };
|
|
304
|
+
case "quasi": {
|
|
305
|
+
const v = fam.varianceName;
|
|
306
|
+
const mustart = v === "constant" ? yv.slice() : v === "mu(1-mu)" ? yv.map((t) => Math.min(Math.max(t, 0.001), 0.999)) : yv.map((t) => t + (t === 0 ? 0.1 : 0));
|
|
307
|
+
return { y: yv, weights, mustart, size: undefined };
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
/** The family's AIC before the 2 rank term (R's family$aic); NaN for the quasi families */
|
|
312
|
+
export function familyAic(fam, y, mu, w, size, dev, warnings) {
|
|
313
|
+
const n = y.length;
|
|
314
|
+
let s = 0;
|
|
315
|
+
switch (fam.family) {
|
|
316
|
+
case "gaussian": {
|
|
317
|
+
let slw = 0;
|
|
318
|
+
for (const wi of w)
|
|
319
|
+
slw += Math.log(wi);
|
|
320
|
+
return n * (Math.log((2 * Math.PI * dev) / n) + 1) + 2 - slw;
|
|
321
|
+
}
|
|
322
|
+
case "binomial": {
|
|
323
|
+
const m = size !== undefined && size.some((v) => v > 1) ? size : w;
|
|
324
|
+
for (let i = 0; i < n; i++) {
|
|
325
|
+
// R's round: half to even
|
|
326
|
+
if (m[i] > 0)
|
|
327
|
+
s += (w[i] / m[i]) * dbinom1(roundHalfEven(m[i] * y[i]), roundHalfEven(m[i]), mu[i], true);
|
|
328
|
+
}
|
|
329
|
+
return -2 * s;
|
|
330
|
+
}
|
|
331
|
+
case "poisson":
|
|
332
|
+
for (let i = 0; i < n; i++) {
|
|
333
|
+
if (nonInteger(y[i]))
|
|
334
|
+
warnings.add(`non-integer x = ${y[i].toFixed(6)}`);
|
|
335
|
+
s += w[i] * dpois1(y[i], mu[i], true);
|
|
336
|
+
}
|
|
337
|
+
return -2 * s;
|
|
338
|
+
case "Gamma": {
|
|
339
|
+
let sw = 0;
|
|
340
|
+
for (const wi of w)
|
|
341
|
+
sw += wi;
|
|
342
|
+
const disp = dev / sw;
|
|
343
|
+
for (let i = 0; i < n; i++)
|
|
344
|
+
s += w[i] * dgamma1(y[i], 1 / disp, mu[i] * disp, true);
|
|
345
|
+
return -2 * s + 2;
|
|
346
|
+
}
|
|
347
|
+
case "inverse.gaussian": {
|
|
348
|
+
let sw = 0;
|
|
349
|
+
let sly = 0;
|
|
350
|
+
for (let i = 0; i < n; i++) {
|
|
351
|
+
sw += w[i];
|
|
352
|
+
sly += w[i] * Math.log(y[i]);
|
|
353
|
+
}
|
|
354
|
+
return sw * (Math.log((2 * Math.PI * dev) / sw) + 1) + 3 * sly + 2;
|
|
355
|
+
}
|
|
356
|
+
default:
|
|
357
|
+
return NaN;
|
|
358
|
+
}
|
|
359
|
+
}
|
package/dist/models/lm.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { MatrixInput } from "../linalg/matrix.js";
|
|
2
2
|
import { type QR } from "../linalg/qr.js";
|
|
3
3
|
import type { Sample } from "../htest/types.js";
|
|
4
|
+
import type { DataFrame } from "./modelFrame.js";
|
|
5
|
+
import { type Design, type ModelMatrixOptions } from "./modelMatrix.js";
|
|
4
6
|
/** Options for {@link lm}. */
|
|
5
7
|
export interface LmOptions {
|
|
6
8
|
/** Include an intercept (a column of ones before the columns of `x`). Default `true`. */
|
|
@@ -48,10 +50,74 @@ export interface LmResult {
|
|
|
48
50
|
/** The QR decomposition of the (weighted) model matrix. */
|
|
49
51
|
qr: QR;
|
|
50
52
|
}
|
|
53
|
+
/** Options of {@link lm} with a formula. */
|
|
54
|
+
export interface LmFormulaOptions extends ModelMatrixOptions {
|
|
55
|
+
/** Weights: an array parallel to the rows of `data`, or the name of a numeric column. */
|
|
56
|
+
weights?: Sample | string;
|
|
57
|
+
}
|
|
58
|
+
/** Result of {@link lm} with a formula: the fit of the model matrix, with the formula's terms. */
|
|
59
|
+
export interface LmFormulaResult extends LmResult {
|
|
60
|
+
/** The formula. */
|
|
61
|
+
formula: string;
|
|
62
|
+
/** The response's name. */
|
|
63
|
+
response: string;
|
|
64
|
+
/** Names of the coefficients (the model matrix's column names). */
|
|
65
|
+
coefNames: string[];
|
|
66
|
+
/** The term of each coefficient (0 for the intercept). */
|
|
67
|
+
assign: number[];
|
|
68
|
+
/** Labels of the terms. */
|
|
69
|
+
termLabels: string[];
|
|
70
|
+
/** Degree of each term. */
|
|
71
|
+
order: number[];
|
|
72
|
+
/** The variables of the formula, the response first. */
|
|
73
|
+
variables: string[];
|
|
74
|
+
/** R's factors attribute of the terms (one array per variable, one code per term). */
|
|
75
|
+
factors: number[][];
|
|
76
|
+
/** 0-based indices of the rows of `data` used. */
|
|
77
|
+
rows: number[];
|
|
78
|
+
/** The model matrix (rows used). */
|
|
79
|
+
x: number[][];
|
|
80
|
+
/** The response (rows used). */
|
|
81
|
+
y: number[];
|
|
82
|
+
/** The weights (rows used), if any. */
|
|
83
|
+
weights?: number[];
|
|
84
|
+
/** The effects Q'y of the (weighted) fit, one per row of non-zero weight. */
|
|
85
|
+
effects: number[];
|
|
86
|
+
/** The weighted residual sum of squares. */
|
|
87
|
+
rss: number;
|
|
88
|
+
/** Number of rows of non-zero weight. */
|
|
89
|
+
nObs: number;
|
|
90
|
+
/** Whether this is an `aov` fit. */
|
|
91
|
+
aov: boolean;
|
|
92
|
+
/** R's warnings (from the model matrix and from `summary()`). */
|
|
93
|
+
warnings: string[];
|
|
94
|
+
}
|
|
95
|
+
/** The formula fit (lm, and aov without Error()) */
|
|
96
|
+
export declare function lmFormulaFit(formula: string, d: Design, aov: boolean): LmFormulaResult;
|
|
51
97
|
/**
|
|
52
|
-
* Fit a linear model
|
|
53
|
-
*
|
|
54
|
-
*
|
|
98
|
+
* Fit a linear model from a formula. Equivalent to R's `lm(formula, data)` (with `weights` and `contrasts`)
|
|
99
|
+
* together with `summary()`.
|
|
100
|
+
*
|
|
101
|
+
* The model matrix is that of {@link modelMatrix} (but levels without rows are dropped, as R's
|
|
102
|
+
* `drop.unused.levels`); the fit is that of the matrix form (same pivoting and tolerance), its sums of squares computed
|
|
103
|
+
* in double-double so that data with a large mean keep their accuracy. Rows with a missing value in a variable of the
|
|
104
|
+
* formula or in the weights are dropped (`rows` lists those used).
|
|
105
|
+
*
|
|
106
|
+
* @param formula A formula such as `"y ~ A * B + x"`.
|
|
107
|
+
* @param data The data frame: an object of columns.
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* ```ts
|
|
111
|
+
* const fit = lm("y ~ g", { y: [2.1, 3.9, 6.2, 7.8, 10.1, 11.8], g: ["a", "a", "b", "b", "c", "c"] });
|
|
112
|
+
* fit.coefNames; // ["(Intercept)", "gb", "gc"]
|
|
113
|
+
* fit.coefficients; // [3, 4, 7.95]
|
|
114
|
+
* ```
|
|
115
|
+
*/
|
|
116
|
+
export declare function lm(formula: string, data: DataFrame, options?: LmFormulaOptions): LmFormulaResult;
|
|
117
|
+
/**
|
|
118
|
+
* Fit a linear model by least squares, the predictors given as a matrix. Equivalent to R's `lm(y ~ x)` (or
|
|
119
|
+
* `y ~ x - 1` without intercept, with `weights` for weighted least squares) together with `summary()`. Rows with a
|
|
120
|
+
* missing value in `x`, `y` or the weights are dropped.
|
|
55
121
|
*
|
|
56
122
|
* @param x Predictors: a matrix (array of rows, one column per predictor) or a vector (one predictor).
|
|
57
123
|
* @param y Response.
|
|
@@ -64,6 +130,21 @@ export interface LmResult {
|
|
|
64
130
|
* ```
|
|
65
131
|
*/
|
|
66
132
|
export declare function lm(x: MatrixInput | Sample, y: Sample, options?: LmOptions): LmResult;
|
|
133
|
+
/** The quantities of a fit that the formula interface and the analyses of variance need besides the result */
|
|
134
|
+
export interface LmCore {
|
|
135
|
+
result: LmResult;
|
|
136
|
+
/** The rows of non-zero weight (indices into the rows given) */
|
|
137
|
+
fitRows: number[];
|
|
138
|
+
/** The effects Q'y of the (weighted) fit, one per row of non-zero weight (only for a precise fit) */
|
|
139
|
+
effects: number[];
|
|
140
|
+
/** The weighted residual sum of squares */
|
|
141
|
+
rss: number;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Least squares on a full model matrix (the column of ones included when `intercept` is true). Rows of weight 0 are
|
|
145
|
+
* left out of the fit and of the counts.
|
|
146
|
+
*/
|
|
147
|
+
export declare function fitLm(Xall: number[][], Yall: number[], Wall: number[] | undefined, intercept: boolean, precise?: boolean): LmCore;
|
|
67
148
|
/** Options for {@link confint}. */
|
|
68
149
|
export interface ConfintOptions {
|
|
69
150
|
/** Confidence level. Default `0.95`. */
|