@ac-kit/math-stats 0.6.0 → 0.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.
- package/CHANGELOG.md +123 -0
- package/README.md +43 -2
- package/dist/_digamma.d.ts +10 -0
- package/dist/_digamma.d.ts.map +1 -0
- package/dist/_digamma.js +38 -0
- package/dist/_digamma.js.map +1 -0
- package/dist/_dilogarithm.d.ts +14 -0
- package/dist/_dilogarithm.d.ts.map +1 -0
- package/dist/_dilogarithm.js +77 -0
- package/dist/_dilogarithm.js.map +1 -0
- package/dist/_incomplete-gamma-shape-derivative.d.ts +17 -0
- package/dist/_incomplete-gamma-shape-derivative.d.ts.map +1 -0
- package/dist/_incomplete-gamma-shape-derivative.js +90 -0
- package/dist/_incomplete-gamma-shape-derivative.js.map +1 -0
- package/dist/_logistic.d.ts +14 -0
- package/dist/_logistic.d.ts.map +1 -0
- package/dist/_logistic.js +29 -0
- package/dist/_logistic.js.map +1 -0
- package/dist/_normal-tail.d.ts +43 -0
- package/dist/_normal-tail.d.ts.map +1 -0
- package/dist/_normal-tail.js +124 -0
- package/dist/_normal-tail.js.map +1 -0
- package/dist/_rank-test.d.ts +71 -0
- package/dist/_rank-test.d.ts.map +1 -0
- package/dist/_rank-test.js +130 -0
- package/dist/_rank-test.js.map +1 -0
- package/dist/average.js +2 -2
- package/dist/average.js.map +1 -1
- package/dist/bootstrap.d.ts +67 -0
- package/dist/bootstrap.d.ts.map +1 -0
- package/dist/bootstrap.js +154 -0
- package/dist/bootstrap.js.map +1 -0
- package/dist/censored-logistic-distribution.d.ts +23 -0
- package/dist/censored-logistic-distribution.d.ts.map +1 -0
- package/dist/censored-logistic-distribution.js +63 -0
- package/dist/censored-logistic-distribution.js.map +1 -0
- package/dist/censored-shifted-gamma-distribution.d.ts +23 -0
- package/dist/censored-shifted-gamma-distribution.d.ts.map +1 -0
- package/dist/censored-shifted-gamma-distribution.js +73 -0
- package/dist/censored-shifted-gamma-distribution.js.map +1 -0
- package/dist/confidence-interval.d.ts +53 -0
- package/dist/confidence-interval.d.ts.map +1 -1
- package/dist/confidence-interval.js +73 -0
- package/dist/confidence-interval.js.map +1 -1
- package/dist/correlation.d.ts +41 -0
- package/dist/correlation.d.ts.map +1 -1
- package/dist/correlation.js +168 -2
- package/dist/correlation.js.map +1 -1
- package/dist/descriptive.d.ts +129 -0
- package/dist/descriptive.d.ts.map +1 -0
- package/dist/descriptive.js +289 -0
- package/dist/descriptive.js.map +1 -0
- package/dist/forecast/_forecast-checks.d.ts +30 -0
- package/dist/forecast/_forecast-checks.d.ts.map +1 -0
- package/dist/forecast/_forecast-checks.js +119 -0
- package/dist/forecast/_forecast-checks.js.map +1 -0
- package/dist/forecast/_score-kernels.d.ts +63 -0
- package/dist/forecast/_score-kernels.d.ts.map +1 -0
- package/dist/forecast/_score-kernels.js +264 -0
- package/dist/forecast/_score-kernels.js.map +1 -0
- package/dist/forecast/brier-score.d.ts +102 -0
- package/dist/forecast/brier-score.d.ts.map +1 -0
- package/dist/forecast/brier-score.js +163 -0
- package/dist/forecast/brier-score.js.map +1 -0
- package/dist/forecast/crps-closed-form.d.ts +64 -0
- package/dist/forecast/crps-closed-form.d.ts.map +1 -0
- package/dist/forecast/crps-closed-form.js +106 -0
- package/dist/forecast/crps-closed-form.js.map +1 -0
- package/dist/forecast/crps-ensemble.d.ts +53 -0
- package/dist/forecast/crps-ensemble.d.ts.map +1 -0
- package/dist/forecast/crps-ensemble.js +121 -0
- package/dist/forecast/crps-ensemble.js.map +1 -0
- package/dist/forecast/emos.d.ts +158 -0
- package/dist/forecast/emos.d.ts.map +1 -0
- package/dist/forecast/emos.js +397 -0
- package/dist/forecast/emos.js.map +1 -0
- package/dist/forecast/exceedance-probability.d.ts +54 -0
- package/dist/forecast/exceedance-probability.d.ts.map +1 -0
- package/dist/forecast/exceedance-probability.js +125 -0
- package/dist/forecast/exceedance-probability.js.map +1 -0
- package/dist/forecast/log-score.d.ts +18 -0
- package/dist/forecast/log-score.d.ts.map +1 -0
- package/dist/forecast/log-score.js +19 -0
- package/dist/forecast/log-score.js.map +1 -0
- package/dist/forecast/logistic-regression.d.ts +123 -0
- package/dist/forecast/logistic-regression.d.ts.map +1 -0
- package/dist/forecast/logistic-regression.js +282 -0
- package/dist/forecast/logistic-regression.js.map +1 -0
- package/dist/forecast/rank-histogram.d.ts +32 -0
- package/dist/forecast/rank-histogram.d.ts.map +1 -0
- package/dist/forecast/rank-histogram.js +63 -0
- package/dist/forecast/rank-histogram.js.map +1 -0
- package/dist/forecast/reliability-diagram.d.ts +70 -0
- package/dist/forecast/reliability-diagram.d.ts.map +1 -0
- package/dist/forecast/reliability-diagram.js +126 -0
- package/dist/forecast/reliability-diagram.js.map +1 -0
- package/dist/forecast/roc-curve.d.ts +58 -0
- package/dist/forecast/roc-curve.d.ts.map +1 -0
- package/dist/forecast/roc-curve.js +124 -0
- package/dist/forecast/roc-curve.js.map +1 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +21 -0
- package/dist/index.js.map +1 -1
- package/dist/mann-whitney-u.d.ts +27 -0
- package/dist/mann-whitney-u.d.ts.map +1 -0
- package/dist/mann-whitney-u.js +94 -0
- package/dist/mann-whitney-u.js.map +1 -0
- package/dist/multiple-regression.d.ts +123 -0
- package/dist/multiple-regression.d.ts.map +1 -0
- package/dist/multiple-regression.js +208 -0
- package/dist/multiple-regression.js.map +1 -0
- package/dist/principal-components.d.ts +66 -0
- package/dist/principal-components.d.ts.map +1 -0
- package/dist/principal-components.js +105 -0
- package/dist/principal-components.js.map +1 -0
- package/dist/quantile.d.ts +97 -9
- package/dist/quantile.d.ts.map +1 -1
- package/dist/quantile.js +298 -44
- package/dist/quantile.js.map +1 -1
- package/dist/regression.d.ts +46 -0
- package/dist/regression.d.ts.map +1 -1
- package/dist/regression.js +99 -1
- package/dist/regression.js.map +1 -1
- package/dist/sample.d.ts +29 -0
- package/dist/sample.d.ts.map +1 -0
- package/dist/sample.js +39 -0
- package/dist/sample.js.map +1 -0
- package/dist/t-digest.d.ts +136 -0
- package/dist/t-digest.d.ts.map +1 -0
- package/dist/t-digest.js +424 -0
- package/dist/t-digest.js.map +1 -0
- package/dist/truncated-normal-distribution.d.ts +28 -0
- package/dist/truncated-normal-distribution.d.ts.map +1 -0
- package/dist/truncated-normal-distribution.js +198 -0
- package/dist/truncated-normal-distribution.js.map +1 -0
- package/dist/wilcoxon-signed-rank.d.ts +42 -0
- package/dist/wilcoxon-signed-rank.d.ts.map +1 -0
- package/dist/wilcoxon-signed-rank.js +117 -0
- package/dist/wilcoxon-signed-rank.js.map +1 -0
- package/package.json +14 -10
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { type Matrix } from "@ac-kit/math-linear";
|
|
2
|
+
/** Options of {@link multipleRegression} and `linearRegression`. */
|
|
3
|
+
export type RegressionOptions = {
|
|
4
|
+
/**
|
|
5
|
+
* One finite non-negative weight per case: weighted least squares, minimising
|
|
6
|
+
* `Σ wᵢ (yᵢ − ŷᵢ)²` with `wᵢ` the inverse of case `i`'s error variance (up to
|
|
7
|
+
* a common factor). A zero weight drops the case from the fit and from the
|
|
8
|
+
* count of observations, as R's `lm`. `null` or absent: every weight `1`.
|
|
9
|
+
*/
|
|
10
|
+
readonly weights?: ArrayLike<number> | null;
|
|
11
|
+
/**
|
|
12
|
+
* The reciprocal condition below which a pivot column counts as aliased with
|
|
13
|
+
* the others (`QrDecomposition`'s `rankTolerance`), in `[0, 1)`. Defaults to
|
|
14
|
+
* `max(n, p) · ε`, NumPy's `lstsq` threshold; R's `lm` uses about `1e-7`,
|
|
15
|
+
* which also drops nearly collinear predictors.
|
|
16
|
+
*/
|
|
17
|
+
readonly rankTolerance?: number;
|
|
18
|
+
};
|
|
19
|
+
/** What {@link multipleRegression} returns. */
|
|
20
|
+
export type RegressionResult = {
|
|
21
|
+
/**
|
|
22
|
+
* One coefficient per design column; `0` for a column aliased with others
|
|
23
|
+
* (rank deficiency), whose standard error, statistic and p-value are then
|
|
24
|
+
* `NaN`.
|
|
25
|
+
*/
|
|
26
|
+
readonly coefficients: Float64Array;
|
|
27
|
+
/** Whether each design column is aliased (left out of the fit). */
|
|
28
|
+
readonly aliased: readonly boolean[];
|
|
29
|
+
/** The coefficients' covariance `σ̂² (XᵀWX)⁻¹`, `NaN` on aliased columns. */
|
|
30
|
+
readonly covariance: Matrix;
|
|
31
|
+
/** Square roots of the covariance's diagonal. */
|
|
32
|
+
readonly standardErrors: Float64Array;
|
|
33
|
+
/** `coefficient / standardError`, for the null hypothesis of zero. */
|
|
34
|
+
readonly tStatistics: Float64Array;
|
|
35
|
+
/** Two-sided p-values of the t statistics, on the residual degrees of freedom. */
|
|
36
|
+
readonly pValues: Float64Array;
|
|
37
|
+
/** The fitted values `Xβ`, one per case. */
|
|
38
|
+
readonly fitted: Float64Array;
|
|
39
|
+
/** `y − Xβ`, one per case (unweighted). */
|
|
40
|
+
readonly residuals: Float64Array;
|
|
41
|
+
/**
|
|
42
|
+
* The diagonal of the (weighted) hat matrix, each in `[0, 1]`, summing to the
|
|
43
|
+
* rank: the input of studentised residuals and Cook's distance.
|
|
44
|
+
*/
|
|
45
|
+
readonly leverages: Float64Array;
|
|
46
|
+
/** Cases with a positive weight: `n`. */
|
|
47
|
+
readonly observations: number;
|
|
48
|
+
/** The numerical rank of the (weighted) design. */
|
|
49
|
+
readonly rank: number;
|
|
50
|
+
/**
|
|
51
|
+
* The `QrDecomposition`'s estimate of `σmin / σmax` of the independent
|
|
52
|
+
* columns: near `0`, the coefficients are ill determined.
|
|
53
|
+
*/
|
|
54
|
+
readonly reciprocalCondition: number;
|
|
55
|
+
/** Whether a design column is constant over the weighted cases (an intercept). */
|
|
56
|
+
readonly hasConstant: boolean;
|
|
57
|
+
/** `Σ wᵢ rᵢ²`. */
|
|
58
|
+
readonly residualSumOfSquares: number;
|
|
59
|
+
/** `n − rank`. */
|
|
60
|
+
readonly residualDegreesOfFreedom: number;
|
|
61
|
+
/** `rank − 1` with a constant, `rank` without. */
|
|
62
|
+
readonly modelDegreesOfFreedom: number;
|
|
63
|
+
/** `σ̂ = √(RSS / (n − rank))`; `NaN` with no residual degree of freedom. */
|
|
64
|
+
readonly residualStandardError: number;
|
|
65
|
+
/**
|
|
66
|
+
* `1 − RSS/TSS`, the total sum of squares about the weighted mean with a
|
|
67
|
+
* constant, about zero without (the uncentred R², as statsmodels and R).
|
|
68
|
+
*/
|
|
69
|
+
readonly rSquared: number;
|
|
70
|
+
/** `1 − (1 − R²)(n − c)/(n − rank)`, `c` 1 with a constant and 0 without. */
|
|
71
|
+
readonly adjustedRSquared: number;
|
|
72
|
+
/**
|
|
73
|
+
* The overall F statistic against the constant-only model (against zero
|
|
74
|
+
* without a constant); `NaN` when the model has no degree of freedom.
|
|
75
|
+
*/
|
|
76
|
+
readonly fStatistic: number;
|
|
77
|
+
/** The upper-tail p-value of the F statistic. */
|
|
78
|
+
readonly fPValue: number;
|
|
79
|
+
/**
|
|
80
|
+
* The Gaussian log likelihood at the estimate, `−n/2 · (ln(2π·RSS/n) + 1)
|
|
81
|
+
*
|
|
82
|
+
* - ½ Σ ln wᵢ`.
|
|
83
|
+
*/
|
|
84
|
+
readonly logLikelihood: number;
|
|
85
|
+
/** `−2ℓ + 2·rank`. */
|
|
86
|
+
readonly aic: number;
|
|
87
|
+
/** `−2ℓ + rank · ln n`. */
|
|
88
|
+
readonly bic: number;
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* Ordinary or weighted least-squares regression of `y` on the columns of
|
|
92
|
+
* `design` (`n` cases × `p` predictors, an intercept being a column of ones),
|
|
93
|
+
* with the inference of R's `summary.lm` and statsmodels' `OLS`/`WLS`:
|
|
94
|
+
* coefficients, their covariance, standard errors, t tests, R², the overall F
|
|
95
|
+
* test, fitted values, residuals, leverages and information criteria.
|
|
96
|
+
*
|
|
97
|
+
* Solved by the pivoted Householder QR of `√W·X` (`QrDecomposition` from
|
|
98
|
+
* `@ac-kit/math-linear`), never the normal equations, so a nearly collinear
|
|
99
|
+
* design loses digits only as its condition number; an exactly collinear one
|
|
100
|
+
* gets the basic solution (aliased coefficients `0`, their statistics `NaN`, as
|
|
101
|
+
* R's `NA`). A constant column is detected (`hasConstant`) and decides the
|
|
102
|
+
* centred R² and the F test's null model, as statsmodels does.
|
|
103
|
+
*
|
|
104
|
+
* O(n · p²) time, O(n · p) memory.
|
|
105
|
+
*
|
|
106
|
+
* @example
|
|
107
|
+
* ```ts
|
|
108
|
+
* const design = matrixOfRows(x.map((xi, i) => [1, xi, z[i]]));
|
|
109
|
+
* const fit = multipleRegression(design, y);
|
|
110
|
+
* fit.coefficients; // [intercept, βx, βz]
|
|
111
|
+
* fit.pValues; // their two-sided t-test p-values
|
|
112
|
+
* ```;
|
|
113
|
+
*
|
|
114
|
+
* @param design The `n × p` design matrix. Not modified.
|
|
115
|
+
* @param y The `n` responses. Not modified.
|
|
116
|
+
* @param options Weights and the rank tolerance.
|
|
117
|
+
* @returns The fit and its inference.
|
|
118
|
+
* @throws {RangeError} When `y` or `weights` does not hold one finite number
|
|
119
|
+
* per row (weights non-negative, not all zero), a design entry is not finite,
|
|
120
|
+
* or `rankTolerance` is outside `[0, 1)`.
|
|
121
|
+
*/
|
|
122
|
+
export declare function multipleRegression(design: Matrix, y: ArrayLike<number>, options?: RegressionOptions): RegressionResult;
|
|
123
|
+
//# sourceMappingURL=multiple-regression.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"multiple-regression.d.ts","sourceRoot":"","sources":["../src/multiple-regression.ts"],"names":[],"mappings":"AACA,OAAO,EACN,KAAK,MAAM,EAGX,MAAM,qBAAqB,CAAC;AAM7B,oEAAoE;AACpE,MAAM,MAAM,iBAAiB,GAAG;IAC/B;;;;;OAKG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,SAAS,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;IAE5C;;;;;OAKG;IACH,QAAQ,CAAC,aAAa,CAAC,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;;OAGG;IACH,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAE5B,iDAAiD;IACjD,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAEzB;;;;OAIG;IACH,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAE/B,sBAAsB;IACtB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IAErB,2BAA2B;IAC3B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAgB,kBAAkB,CACjC,MAAM,EAAE,MAAM,EACd,CAAC,EAAE,SAAS,CAAC,MAAM,CAAC,EACpB,OAAO,CAAC,EAAE,iBAAiB,GACzB,gBAAgB,CAmKlB"}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { describeValue, PreciseSum } from "@ac-kit/core";
|
|
2
|
+
import { matrixCreate, QrDecomposition, } from "@ac-kit/math-linear";
|
|
3
|
+
import { fDistribution } from "./f-distribution.js";
|
|
4
|
+
import { weightTotal_ } from "./forecast/_forecast-checks.js";
|
|
5
|
+
import { studentTDistribution } from "./student-t-distribution.js";
|
|
6
|
+
/**
|
|
7
|
+
* Ordinary or weighted least-squares regression of `y` on the columns of
|
|
8
|
+
* `design` (`n` cases × `p` predictors, an intercept being a column of ones),
|
|
9
|
+
* with the inference of R's `summary.lm` and statsmodels' `OLS`/`WLS`:
|
|
10
|
+
* coefficients, their covariance, standard errors, t tests, R², the overall F
|
|
11
|
+
* test, fitted values, residuals, leverages and information criteria.
|
|
12
|
+
*
|
|
13
|
+
* Solved by the pivoted Householder QR of `√W·X` (`QrDecomposition` from
|
|
14
|
+
* `@ac-kit/math-linear`), never the normal equations, so a nearly collinear
|
|
15
|
+
* design loses digits only as its condition number; an exactly collinear one
|
|
16
|
+
* gets the basic solution (aliased coefficients `0`, their statistics `NaN`, as
|
|
17
|
+
* R's `NA`). A constant column is detected (`hasConstant`) and decides the
|
|
18
|
+
* centred R² and the F test's null model, as statsmodels does.
|
|
19
|
+
*
|
|
20
|
+
* O(n · p²) time, O(n · p) memory.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```ts
|
|
24
|
+
* const design = matrixOfRows(x.map((xi, i) => [1, xi, z[i]]));
|
|
25
|
+
* const fit = multipleRegression(design, y);
|
|
26
|
+
* fit.coefficients; // [intercept, βx, βz]
|
|
27
|
+
* fit.pValues; // their two-sided t-test p-values
|
|
28
|
+
* ```;
|
|
29
|
+
*
|
|
30
|
+
* @param design The `n × p` design matrix. Not modified.
|
|
31
|
+
* @param y The `n` responses. Not modified.
|
|
32
|
+
* @param options Weights and the rank tolerance.
|
|
33
|
+
* @returns The fit and its inference.
|
|
34
|
+
* @throws {RangeError} When `y` or `weights` does not hold one finite number
|
|
35
|
+
* per row (weights non-negative, not all zero), a design entry is not finite,
|
|
36
|
+
* or `rankTolerance` is outside `[0, 1)`.
|
|
37
|
+
*/
|
|
38
|
+
export function multipleRegression(design, y, options) {
|
|
39
|
+
const rows = design.rows;
|
|
40
|
+
const columns = design.columns;
|
|
41
|
+
if (y.length !== rows) {
|
|
42
|
+
throw new RangeError(`multipleRegression: y needs ${rows} values, one per design row, got ${y.length}`);
|
|
43
|
+
}
|
|
44
|
+
const response = new Float64Array(rows);
|
|
45
|
+
for (let row = 0; row < rows; row++) {
|
|
46
|
+
const value = y[row];
|
|
47
|
+
if (value - value !== 0) {
|
|
48
|
+
throw new RangeError(`multipleRegression: y must be finite, got ${describeValue(value)} at ${row}`);
|
|
49
|
+
}
|
|
50
|
+
response[row] = value;
|
|
51
|
+
}
|
|
52
|
+
const given = options?.weights ?? null;
|
|
53
|
+
weightTotal_("multipleRegression", given, rows);
|
|
54
|
+
const weights = given === null ? null : Float64Array.from(given);
|
|
55
|
+
const qr = new QrDecomposition(rows, columns);
|
|
56
|
+
const decomposeOptions = options?.rankTolerance === undefined
|
|
57
|
+
? { weights }
|
|
58
|
+
: { weights, rankTolerance: options.rankTolerance };
|
|
59
|
+
if (!qr.decompose(design, decomposeOptions)) {
|
|
60
|
+
throw new RangeError("multipleRegression: the design must be finite");
|
|
61
|
+
}
|
|
62
|
+
const coefficients = qr.solve(new Float64Array(columns), response);
|
|
63
|
+
const rank = qr.rank;
|
|
64
|
+
const aliased = Array.from({ length: columns }, () => true);
|
|
65
|
+
for (let index = 0; index < rank; index++) {
|
|
66
|
+
aliased[qr.pivots[index]] = false;
|
|
67
|
+
}
|
|
68
|
+
const fitted = new Float64Array(rows);
|
|
69
|
+
for (let column = 0; column < columns; column++) {
|
|
70
|
+
const coefficient = coefficients[column];
|
|
71
|
+
if (coefficient === 0) {
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
const offset = rows * column;
|
|
75
|
+
for (let row = 0; row < rows; row++) {
|
|
76
|
+
fitted[row] = fitted[row] + coefficient * design.data[offset + row];
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const residuals = new Float64Array(rows);
|
|
80
|
+
let observations = 0;
|
|
81
|
+
let logWeights = 0;
|
|
82
|
+
const residualSum = new PreciseSum();
|
|
83
|
+
const weightSum = new PreciseSum();
|
|
84
|
+
const weightedResponse = new PreciseSum();
|
|
85
|
+
for (let row = 0; row < rows; row++) {
|
|
86
|
+
const weight = weights === null ? 1 : weights[row];
|
|
87
|
+
const residual = response[row] - fitted[row];
|
|
88
|
+
residuals[row] = residual;
|
|
89
|
+
if (weight > 0) {
|
|
90
|
+
observations++;
|
|
91
|
+
logWeights += Math.log(weight);
|
|
92
|
+
}
|
|
93
|
+
residualSum.add(weight * residual * residual);
|
|
94
|
+
weightSum.add(weight);
|
|
95
|
+
weightedResponse.add(weight * response[row]);
|
|
96
|
+
}
|
|
97
|
+
const residualSumOfSquares = residualSum.value;
|
|
98
|
+
const hasConstant = hasConstantColumn_(design, weights);
|
|
99
|
+
const centre = hasConstant ? weightedResponse.value / weightSum.value : 0;
|
|
100
|
+
const totalSum = new PreciseSum();
|
|
101
|
+
for (let row = 0; row < rows; row++) {
|
|
102
|
+
const weight = weights === null ? 1 : weights[row];
|
|
103
|
+
const deviation = response[row] - centre;
|
|
104
|
+
totalSum.add(weight * deviation * deviation);
|
|
105
|
+
}
|
|
106
|
+
const totalSumOfSquares = totalSum.value;
|
|
107
|
+
const residualDegreesOfFreedom = observations - rank;
|
|
108
|
+
const constantTerms = hasConstant ? 1 : 0;
|
|
109
|
+
const modelDegreesOfFreedom = rank - constantTerms;
|
|
110
|
+
const variance = residualDegreesOfFreedom > 0
|
|
111
|
+
? residualSumOfSquares / residualDegreesOfFreedom
|
|
112
|
+
: Number.NaN;
|
|
113
|
+
const covariance = matrixCreate(columns, columns);
|
|
114
|
+
if (variance === variance) {
|
|
115
|
+
qr.covariance(covariance, { scale: variance });
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
covariance.data.fill(Number.NaN);
|
|
119
|
+
}
|
|
120
|
+
const standardErrors = new Float64Array(columns);
|
|
121
|
+
const tStatistics = new Float64Array(columns);
|
|
122
|
+
const pValues = new Float64Array(columns);
|
|
123
|
+
const tDistribution = residualDegreesOfFreedom > 0
|
|
124
|
+
? studentTDistribution(residualDegreesOfFreedom)
|
|
125
|
+
: null;
|
|
126
|
+
for (let column = 0; column < columns; column++) {
|
|
127
|
+
const error = Math.sqrt(covariance.data[(columns + 1) * column]);
|
|
128
|
+
const statistic = coefficients[column] / error;
|
|
129
|
+
standardErrors[column] = error;
|
|
130
|
+
tStatistics[column] = statistic;
|
|
131
|
+
pValues[column] =
|
|
132
|
+
tDistribution === null || statistic !== statistic
|
|
133
|
+
? Number.NaN
|
|
134
|
+
: Math.min(1, 2 * tDistribution.survival(Math.abs(statistic)));
|
|
135
|
+
}
|
|
136
|
+
const rSquared = totalSumOfSquares > 0
|
|
137
|
+
? 1 - residualSumOfSquares / totalSumOfSquares
|
|
138
|
+
: Number.NaN;
|
|
139
|
+
const adjustedRSquared = residualDegreesOfFreedom > 0
|
|
140
|
+
? 1 -
|
|
141
|
+
((1 - rSquared) * (observations - constantTerms)) /
|
|
142
|
+
residualDegreesOfFreedom
|
|
143
|
+
: Number.NaN;
|
|
144
|
+
let fStatistic = Number.NaN;
|
|
145
|
+
let fPValue = Number.NaN;
|
|
146
|
+
if (modelDegreesOfFreedom > 0 && residualDegreesOfFreedom > 0) {
|
|
147
|
+
fStatistic =
|
|
148
|
+
(totalSumOfSquares - residualSumOfSquares) /
|
|
149
|
+
modelDegreesOfFreedom /
|
|
150
|
+
variance;
|
|
151
|
+
fPValue = fDistribution(modelDegreesOfFreedom, residualDegreesOfFreedom).survival(fStatistic);
|
|
152
|
+
}
|
|
153
|
+
const logLikelihood = -(observations / 2) *
|
|
154
|
+
(Math.log((2 * Math.PI * residualSumOfSquares) / observations) + 1) +
|
|
155
|
+
logWeights / 2;
|
|
156
|
+
return {
|
|
157
|
+
coefficients,
|
|
158
|
+
aliased,
|
|
159
|
+
covariance,
|
|
160
|
+
standardErrors,
|
|
161
|
+
tStatistics,
|
|
162
|
+
pValues,
|
|
163
|
+
fitted,
|
|
164
|
+
residuals,
|
|
165
|
+
leverages: qr.leverages(new Float64Array(rows)),
|
|
166
|
+
observations,
|
|
167
|
+
rank,
|
|
168
|
+
reciprocalCondition: qr.reciprocalCondition,
|
|
169
|
+
hasConstant,
|
|
170
|
+
residualSumOfSquares,
|
|
171
|
+
residualDegreesOfFreedom,
|
|
172
|
+
modelDegreesOfFreedom,
|
|
173
|
+
residualStandardError: Math.sqrt(variance),
|
|
174
|
+
rSquared,
|
|
175
|
+
adjustedRSquared,
|
|
176
|
+
fStatistic,
|
|
177
|
+
fPValue,
|
|
178
|
+
logLikelihood,
|
|
179
|
+
aic: -2 * logLikelihood + 2 * rank,
|
|
180
|
+
bic: -2 * logLikelihood + rank * Math.log(observations),
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
/** Whether some column is one non-zero value over every weighted row. */
|
|
184
|
+
function hasConstantColumn_(design, weights) {
|
|
185
|
+
const rows = design.rows;
|
|
186
|
+
for (let column = 0; column < design.columns; column++) {
|
|
187
|
+
const offset = rows * column;
|
|
188
|
+
let value = Number.NaN;
|
|
189
|
+
let constant = true;
|
|
190
|
+
for (let row = 0; row < rows && constant; row++) {
|
|
191
|
+
if (weights !== null && !(weights[row] > 0)) {
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
const entry = design.data[offset + row];
|
|
195
|
+
if (value !== value) {
|
|
196
|
+
value = entry;
|
|
197
|
+
}
|
|
198
|
+
else if (entry !== value) {
|
|
199
|
+
constant = false;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
if (constant && value === value && value !== 0) {
|
|
203
|
+
return true;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return false;
|
|
207
|
+
}
|
|
208
|
+
//# sourceMappingURL=multiple-regression.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"multiple-regression.js","sourceRoot":"","sources":["../src/multiple-regression.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,EAEN,YAAY,EACZ,eAAe,GACf,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAC9D,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AAoHnE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAM,UAAU,kBAAkB,CACjC,MAAc,EACd,CAAoB,EACpB,OAA2B;IAE3B,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC;IACzB,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;IAC/B,IAAI,CAAC,CAAC,MAAM,KAAK,IAAI,EAAE,CAAC;QACvB,MAAM,IAAI,UAAU,CACnB,+BAA+B,IAAI,oCAAoC,CAAC,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AAI,IAAI,CAAC,CAAC,OAAO,CAAC,GAAG,CAAE,GAAG,CAAC,CAAC,EAAE,CAAC;gBAC9C,SAAS;YACV,CAAC;YACD,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,GAAG,GAAG,CAAE,CAAC;YACzC,IAAI,KAAK,KAAK,KAAK,EAAE,CAAC;gBACrB,KAAK,GAAG,KAAK,CAAC;YACf,CAAC;iBAAM,IAAI,KAAK,KAAK,KAAK,EAAE,CAAC;gBAC5B,QAAQ,GAAG,KAAK,CAAC;YAClB,CAAC;QACF,CAAC;QACD,IAAI,QAAQ,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC;YAChD,OAAO,IAAI,CAAC;QACb,CAAC;IACF,CAAC;IACD,OAAO,KAAK,CAAC;AACd,CAAC"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { type Matrix } from "@ac-kit/math-linear";
|
|
2
|
+
/** Options of {@link principalComponents}. */
|
|
3
|
+
export type PrincipalComponentsOptions = {
|
|
4
|
+
/**
|
|
5
|
+
* How many leading components to keep, in `[0, min(n, p)]`. Defaults to all
|
|
6
|
+
* `min(n, p)`.
|
|
7
|
+
*/
|
|
8
|
+
readonly components?: number;
|
|
9
|
+
/**
|
|
10
|
+
* Divide each centred variable by its sample standard deviation first: the
|
|
11
|
+
* PCA of the correlation matrix rather than the covariance matrix (R's
|
|
12
|
+
* `prcomp(scale. = TRUE)`), for variables in different units. A constant
|
|
13
|
+
* variable is then left at zero rather than divided by zero. Defaults to
|
|
14
|
+
* `false`.
|
|
15
|
+
*/
|
|
16
|
+
readonly scale?: boolean;
|
|
17
|
+
};
|
|
18
|
+
/** The principal components of a data matrix; see {@link principalComponents}. */
|
|
19
|
+
export type PrincipalComponents = {
|
|
20
|
+
/** The mean of each variable, subtracted before the decomposition (`p`). */
|
|
21
|
+
readonly mean: Float64Array;
|
|
22
|
+
/**
|
|
23
|
+
* The standard deviation each centred variable was divided by (`p`), all `1`
|
|
24
|
+
* without `scale`.
|
|
25
|
+
*/
|
|
26
|
+
readonly scale: Float64Array;
|
|
27
|
+
/**
|
|
28
|
+
* The loadings, `p × k`: column `j` is the unit direction of component `j` in
|
|
29
|
+
* variable space, the sign chosen so its largest-magnitude entry is positive
|
|
30
|
+
* (scikit-learn's convention), so results are reproducible.
|
|
31
|
+
*/
|
|
32
|
+
readonly loadings: Matrix;
|
|
33
|
+
/** The coordinates of each observation on the components, `n × k`. */
|
|
34
|
+
readonly scores: Matrix;
|
|
35
|
+
/**
|
|
36
|
+
* The variance along each component, `σⱼ² / (n − 1)`, descending (`k`): the
|
|
37
|
+
* eigenvalues of the (correlation, with `scale`) covariance matrix.
|
|
38
|
+
*/
|
|
39
|
+
readonly explainedVariance: Float64Array;
|
|
40
|
+
/**
|
|
41
|
+
* Each component's share of the total variance of all `min(n, p)` components,
|
|
42
|
+
* kept or not (`k`).
|
|
43
|
+
*/
|
|
44
|
+
readonly explainedVarianceRatio: Float64Array;
|
|
45
|
+
/** The singular values of the centred (and scaled) data (`k`). */
|
|
46
|
+
readonly singularValues: Float64Array;
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Principal component analysis of `data`, `n` observations (rows) of `p`
|
|
50
|
+
* variables (columns): the orthogonal directions of decreasing variance, from
|
|
51
|
+
* the singular value decomposition of the centred data `X − 1·μᵀ = U·Σ·Vᵀ`
|
|
52
|
+
* (`SingularValueDecomposition` of `@ac-kit/math-linear`) rather than the
|
|
53
|
+
* eigenvectors of the covariance matrix, which square its condition number.
|
|
54
|
+
* Loadings are `V`, scores `U·Σ`, variances `σ²/(n − 1)`.
|
|
55
|
+
*
|
|
56
|
+
* Columns are centred about means accumulated exactly. Time O(n · p · min(n,
|
|
57
|
+
* p)) per Jacobi sweep; memory O(n · p).
|
|
58
|
+
*
|
|
59
|
+
* @param data The observations, `n × p`. Not modified.
|
|
60
|
+
* @param options How many components, and whether to scale.
|
|
61
|
+
* @returns The components, their variances and the scores.
|
|
62
|
+
* @throws {RangeError} When `data` has fewer than two rows or a non-finite
|
|
63
|
+
* entry, or `components` is not an integer in `[0, min(n, p)]`.
|
|
64
|
+
*/
|
|
65
|
+
export declare function principalComponents(data: Matrix, options?: PrincipalComponentsOptions): PrincipalComponents;
|
|
66
|
+
//# sourceMappingURL=principal-components.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"principal-components.d.ts","sourceRoot":"","sources":["../src/principal-components.ts"],"names":[],"mappings":"AACA,OAAO,EACN,KAAK,MAAM,EAGX,MAAM,qBAAqB,CAAC;AAE7B,8CAA8C;AAC9C,MAAM,MAAM,0BAA0B,GAAG;IACxC;;;OAGG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAE7B;;;;;;OAMG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;CACzB,CAAC;AAEF,kFAAkF;AAClF,MAAM,MAAM,mBAAmB,GAAG;IACjC,4EAA4E;IAC5E,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAC;IAE5B;;;OAGG;IACH,QAAQ,CAAC,KAAK,EAAE,YAAY,CAAC;IAE7B;;;;OAIG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAE1B,sEAAsE;IACtE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAExB;;;OAGG;IACH,QAAQ,CAAC,iBAAiB,EAAE,YAAY,CAAC;IAEzC;;;OAGG;IACH,QAAQ,CAAC,sBAAsB,EAAE,YAAY,CAAC;IAE9C,kEAAkE;IAClE,QAAQ,CAAC,cAAc,EAAE,YAAY,CAAC;CACtC,CAAC;AAEF;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,mBAAmB,CAClC,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,0BAA0B,GAClC,mBAAmB,CA8FrB"}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { PreciseSum } from "@ac-kit/core";
|
|
2
|
+
import { matrixCreate, SingularValueDecomposition, } from "@ac-kit/math-linear";
|
|
3
|
+
/**
|
|
4
|
+
* Principal component analysis of `data`, `n` observations (rows) of `p`
|
|
5
|
+
* variables (columns): the orthogonal directions of decreasing variance, from
|
|
6
|
+
* the singular value decomposition of the centred data `X − 1·μᵀ = U·Σ·Vᵀ`
|
|
7
|
+
* (`SingularValueDecomposition` of `@ac-kit/math-linear`) rather than the
|
|
8
|
+
* eigenvectors of the covariance matrix, which square its condition number.
|
|
9
|
+
* Loadings are `V`, scores `U·Σ`, variances `σ²/(n − 1)`.
|
|
10
|
+
*
|
|
11
|
+
* Columns are centred about means accumulated exactly. Time O(n · p · min(n,
|
|
12
|
+
* p)) per Jacobi sweep; memory O(n · p).
|
|
13
|
+
*
|
|
14
|
+
* @param data The observations, `n × p`. Not modified.
|
|
15
|
+
* @param options How many components, and whether to scale.
|
|
16
|
+
* @returns The components, their variances and the scores.
|
|
17
|
+
* @throws {RangeError} When `data` has fewer than two rows or a non-finite
|
|
18
|
+
* entry, or `components` is not an integer in `[0, min(n, p)]`.
|
|
19
|
+
*/
|
|
20
|
+
export function principalComponents(data, options) {
|
|
21
|
+
const rows = data.rows;
|
|
22
|
+
const columns = data.columns;
|
|
23
|
+
if (rows < 2) {
|
|
24
|
+
throw new RangeError(`principalComponents: needs at least two observations, got ${rows}`);
|
|
25
|
+
}
|
|
26
|
+
const size = Math.min(rows, columns);
|
|
27
|
+
const kept = options?.components ?? size;
|
|
28
|
+
if (!Number.isInteger(kept) || kept < 0 || kept > size) {
|
|
29
|
+
throw new RangeError(`principalComponents: components must be an integer in [0, ${size}], got ${kept}`);
|
|
30
|
+
}
|
|
31
|
+
const centred = matrixCreate(rows, columns);
|
|
32
|
+
const mean = new Float64Array(columns);
|
|
33
|
+
const scale = new Float64Array(columns).fill(1);
|
|
34
|
+
for (let column = 0; column < columns; column++) {
|
|
35
|
+
const offset = rows * column;
|
|
36
|
+
const sum = new PreciseSum();
|
|
37
|
+
for (let row = 0; row < rows; row++) {
|
|
38
|
+
const entry = data.data[offset + row];
|
|
39
|
+
if (entry - entry !== 0) {
|
|
40
|
+
throw new RangeError(`principalComponents: entry (${row}, ${column}) is not finite`);
|
|
41
|
+
}
|
|
42
|
+
sum.add(entry);
|
|
43
|
+
}
|
|
44
|
+
const columnMean = sum.value / rows;
|
|
45
|
+
mean[column] = columnMean;
|
|
46
|
+
const squares = new PreciseSum();
|
|
47
|
+
for (let row = 0; row < rows; row++) {
|
|
48
|
+
const deviation = data.data[offset + row] - columnMean;
|
|
49
|
+
centred.data[offset + row] = deviation;
|
|
50
|
+
squares.add(deviation * deviation);
|
|
51
|
+
}
|
|
52
|
+
if (options?.scale === true) {
|
|
53
|
+
const deviation = Math.sqrt(squares.value / (rows - 1));
|
|
54
|
+
if (deviation > 0) {
|
|
55
|
+
scale[column] = deviation;
|
|
56
|
+
for (let row = 0; row < rows; row++) {
|
|
57
|
+
centred.data[offset + row] = centred.data[offset + row] / deviation;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const svd = new SingularValueDecomposition(rows, columns);
|
|
63
|
+
svd.decompose(centred);
|
|
64
|
+
const loadings = matrixCreate(columns, kept);
|
|
65
|
+
const scores = matrixCreate(rows, kept);
|
|
66
|
+
const explainedVariance = new Float64Array(kept);
|
|
67
|
+
const explainedVarianceRatio = new Float64Array(kept);
|
|
68
|
+
const singularValues = svd.singularValues.slice(0, kept);
|
|
69
|
+
let total = 0;
|
|
70
|
+
for (let index = 0; index < size; index++) {
|
|
71
|
+
total += svd.singularValues[index] ** 2;
|
|
72
|
+
}
|
|
73
|
+
for (let component = 0; component < kept; component++) {
|
|
74
|
+
const vOffset = columns * component;
|
|
75
|
+
const uOffset = rows * component;
|
|
76
|
+
let largest = 0;
|
|
77
|
+
let sign = 1;
|
|
78
|
+
for (let row = 0; row < columns; row++) {
|
|
79
|
+
const entry = svd.v.data[vOffset + row];
|
|
80
|
+
if (Math.abs(entry) > largest) {
|
|
81
|
+
largest = Math.abs(entry);
|
|
82
|
+
sign = entry < 0 ? -1 : 1;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
for (let row = 0; row < columns; row++) {
|
|
86
|
+
loadings.data[vOffset + row] = sign * svd.v.data[vOffset + row];
|
|
87
|
+
}
|
|
88
|
+
const value = singularValues[component];
|
|
89
|
+
for (let row = 0; row < rows; row++) {
|
|
90
|
+
scores.data[uOffset + row] = sign * value * svd.u.data[uOffset + row];
|
|
91
|
+
}
|
|
92
|
+
explainedVariance[component] = (value * value) / (rows - 1);
|
|
93
|
+
explainedVarianceRatio[component] = total > 0 ? (value * value) / total : 0;
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
mean,
|
|
97
|
+
scale,
|
|
98
|
+
loadings,
|
|
99
|
+
scores,
|
|
100
|
+
explainedVariance,
|
|
101
|
+
explainedVarianceRatio,
|
|
102
|
+
singularValues,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
//# sourceMappingURL=principal-components.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"principal-components.js","sourceRoot":"","sources":["../src/principal-components.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAEN,YAAY,EACZ,0BAA0B,GAC1B,MAAM,qBAAqB,CAAC;AAyD7B;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,mBAAmB,CAClC,IAAY,EACZ,OAAoC;IAEpC,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;IACvB,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;IAC7B,IAAI,IAAI,GAAG,CAAC,EAAE,CAAC;QACd,MAAM,IAAI,UAAU,CACnB,6DAA6D,IAAI,EAAE,CACnE,CAAC;IACH,CAAC;IACD,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,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AM,KAAK,GAAG,cAAc,CAAC,SAAS,CAAE,CAAC;QACzC,KAAK,IAAI,GAAG,GAAG,CAAC,EAAE,GAAG,GAAG,IAAI,EAAE,GAAG,EAAE,EAAE,CAAC;YACrC,MAAM,CAAC,IAAI,CAAC,OAAO,GAAG,GAAG,CAAC,GAAG,IAAI,GAAG,KAAK,GAAG,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,GAAG,GAAG,CAAE,CAAC;QACxE,CAAC;QACD,iBAAiB,CAAC,SAAS,CAAC,GAAG,CAAC,KAAK,GAAG,KAAK,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC;QAC5D,sBAAsB,CAAC,SAAS,CAAC,GAAG,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,KAAK,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAC7E,CAAC;IAED,OAAO;QACN,IAAI;QACJ,KAAK;QACL,QAAQ;QACR,MAAM;QACN,iBAAiB;QACjB,sBAAsB;QACtB,cAAc;KACd,CAAC;AACH,CAAC"}
|
package/dist/quantile.d.ts
CHANGED
|
@@ -1,18 +1,72 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* How a sample quantile is read off the order statistics `x₍₁₎ ≤ … ≤ x₍ₙ₎`. The
|
|
3
|
+
* nine estimators of Hyndman and Fan ("Sample quantiles in statistical
|
|
4
|
+
* packages", 1996), under NumPy's names, and NumPy's four other readings of the
|
|
5
|
+
* `"linear"` position:
|
|
6
|
+
*
|
|
7
|
+
* | Method | Hyndman–Fan | Definition |
|
|
8
|
+
* | ----------------------------- | ----------- | ---------------------------------------------------------- |
|
|
9
|
+
* | `"inverted-cdf"` | 1 | the inverse of the empirical CDF |
|
|
10
|
+
* | `"averaged-inverted-cdf"` | 2 | type 1, averaged where the CDF is flat |
|
|
11
|
+
* | `"closest-observation"` | 3 | the order statistic nearest `np`, ties to even (SAS) |
|
|
12
|
+
* | `"interpolated-inverted-cdf"` | 4 | linear in the empirical CDF, `p(n) = k/n` |
|
|
13
|
+
* | `"hazen"` | 5 | `p(k) = (k − ½)/n` |
|
|
14
|
+
* | `"weibull"` | 6 | `p(k) = k/(n + 1)` (Excel `PERCENTILE.EXC`) |
|
|
15
|
+
* | `"linear"` | 7 | `p(k) = (k − 1)/(n − 1)`: R's, NumPy's and Excel's default |
|
|
16
|
+
* | `"median-unbiased"` | 8 | `p(k) = (k − ⅓)/(n + ⅓)`, Hyndman and Fan's pick |
|
|
17
|
+
* | `"normal-unbiased"` | 9 | `p(k) = (k − ⅜)/(n + ¼)`, unbiased for normal data |
|
|
18
|
+
* | `"lower"`, `"higher"` | — | the order statistic below or above the type-7 position |
|
|
19
|
+
* | `"nearest"` | — | the nearer of the two, ties to the even index |
|
|
20
|
+
* | `"midpoint"` | — | the mean of the two |
|
|
21
|
+
*
|
|
22
|
+
* The methods disagree most in small samples and in the tails; state the one a
|
|
23
|
+
* result uses.
|
|
24
|
+
*/
|
|
25
|
+
export type QuantileMethod = "inverted-cdf" | "averaged-inverted-cdf" | "closest-observation" | "interpolated-inverted-cdf" | "hazen" | "weibull" | "linear" | "median-unbiased" | "normal-unbiased" | "lower" | "higher" | "nearest" | "midpoint";
|
|
26
|
+
/** Options of {@link quantile} and {@link writeQuantile} over sorted data. */
|
|
27
|
+
export type QuantileOptions = {
|
|
28
|
+
/** Defaults to `"linear"` (Hyndman–Fan type 7). */
|
|
29
|
+
readonly method?: QuantileMethod;
|
|
30
|
+
/**
|
|
31
|
+
* First position of the sample in `sorted`: one group's slice of a scratch
|
|
32
|
+
* buffer reads in place, without a `subarray` view. Default `0`.
|
|
33
|
+
*/
|
|
34
|
+
readonly from?: number;
|
|
35
|
+
/** End position, excluded. Default `sorted.length`. */
|
|
36
|
+
readonly to?: number;
|
|
37
|
+
};
|
|
38
|
+
/** Options of {@link sampleQuantile} and {@link sampleQuantiles}. */
|
|
39
|
+
export type SampleQuantileOptions = {
|
|
40
|
+
/** Defaults to `"linear"` (Hyndman–Fan type 7). */
|
|
41
|
+
readonly method?: QuantileMethod;
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* The `fraction` quantile of an already-sorted sample, by `method`
|
|
45
|
+
* ({@link QuantileMethod}, `"linear"` by default). {@link sampleQuantile} takes
|
|
46
|
+
* the sample in any order.
|
|
3
47
|
*
|
|
4
48
|
* Exact at the sample's values and free of overflow between them, even when two
|
|
5
|
-
* neighbours are further apart than `Number.MAX_VALUE`.
|
|
49
|
+
* neighbours are further apart than `Number.MAX_VALUE`. O(1).
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* ```ts
|
|
53
|
+
* quantile([1, 2, 3, 4], 0.25); // 1.75
|
|
54
|
+
* quantile([1, 2, 3, 4], 0.25, { method: "weibull" }); // 1.25
|
|
55
|
+
* ```;
|
|
6
56
|
*
|
|
7
57
|
* @param sorted Values in ascending order within the range, any array-like (a
|
|
8
58
|
* typed array included). Not modified, not re-checked.
|
|
9
59
|
* @param fraction Quantile to compute, in `[0, 1]`.
|
|
10
|
-
* @param
|
|
11
|
-
* scratch buffer reads in place, without a `subarray` view. Default `0`.
|
|
12
|
-
* @param to End position, excluded. Default `sorted.length`.
|
|
60
|
+
* @param options The method and the range read.
|
|
13
61
|
* @returns The quantile, or `NaN` for an empty sample.
|
|
14
|
-
* @throws {RangeError} When `
|
|
15
|
-
* to ≤
|
|
62
|
+
* @throws {RangeError} When `fraction` is outside `[0, 1]`, `method` is not a
|
|
63
|
+
* {@link QuantileMethod}, or `from` and `to` are not integers with `0 ≤ from
|
|
64
|
+
* ≤ to ≤ sorted.length`.
|
|
65
|
+
*/
|
|
66
|
+
export declare function quantile(sorted: ArrayLike<number>, fraction: number, options?: QuantileOptions): number;
|
|
67
|
+
/**
|
|
68
|
+
* The `"linear"` quantile of the sorted range `[from, to)`: the positional form
|
|
69
|
+
* of {@link quantile} with `{ from, to }`.
|
|
16
70
|
*/
|
|
17
71
|
export declare function quantile(sorted: ArrayLike<number>, fraction: number, from?: number, to?: number): number;
|
|
18
72
|
/**
|
|
@@ -25,9 +79,43 @@ export declare function quantile(sorted: ArrayLike<number>, fraction: number, fr
|
|
|
25
79
|
* @param index The position written.
|
|
26
80
|
* @param sorted As for {@link quantile}.
|
|
27
81
|
* @param fraction As for {@link quantile}.
|
|
28
|
-
* @param
|
|
29
|
-
* @param to As for {@link quantile}.
|
|
82
|
+
* @param options As for {@link quantile}.
|
|
30
83
|
* @throws {RangeError} As {@link quantile}.
|
|
31
84
|
*/
|
|
85
|
+
export declare function writeQuantile(target: Float64Array | number[], index: number, sorted: ArrayLike<number>, fraction: number, options?: QuantileOptions): void;
|
|
86
|
+
/** The positional form of {@link writeQuantile} with `{ from, to }`. */
|
|
32
87
|
export declare function writeQuantile(target: Float64Array | number[], index: number, sorted: ArrayLike<number>, fraction: number, from?: number, to?: number): void;
|
|
88
|
+
/**
|
|
89
|
+
* The `fraction` quantile of a sample in any order, by `method` ({@link
|
|
90
|
+
* QuantileMethod}, `"linear"` by default): the one or two order statistics it
|
|
91
|
+
* needs are found by selection (`quickselectInPlace` from `@ac-kit/algo`) on a
|
|
92
|
+
* copy, so O(n) expected time rather than a sort. A `NaN` in the sample gives
|
|
93
|
+
* `NaN`, as NumPy's `quantile` does.
|
|
94
|
+
*
|
|
95
|
+
* @example
|
|
96
|
+
* ```ts
|
|
97
|
+
* sampleQuantile([4, 1, 3, 2], 0.5); // 2.5
|
|
98
|
+
* sampleQuantile([4, 1, 3, 2], 0.5, { method: "inverted-cdf" }); // 2
|
|
99
|
+
* ```;
|
|
100
|
+
*
|
|
101
|
+
* @param values The sample. Not modified.
|
|
102
|
+
* @param fraction Quantile to compute, in `[0, 1]`.
|
|
103
|
+
* @param options The method.
|
|
104
|
+
* @returns The quantile, or `NaN` for an empty sample.
|
|
105
|
+
* @throws {RangeError} When `fraction` is outside `[0, 1]` or `method` is not a
|
|
106
|
+
* {@link QuantileMethod}.
|
|
107
|
+
*/
|
|
108
|
+
export declare function sampleQuantile(values: ArrayLike<number>, fraction: number, options?: SampleQuantileOptions): number;
|
|
109
|
+
/**
|
|
110
|
+
* {@link sampleQuantile} at several fractions: the sample is copied and sorted
|
|
111
|
+
* once, O(n log n + m).
|
|
112
|
+
*
|
|
113
|
+
* @param values The sample, in any order. Not modified.
|
|
114
|
+
* @param fractions The quantiles to compute, each in `[0, 1]`.
|
|
115
|
+
* @param options The method.
|
|
116
|
+
* @returns A new array of one quantile per fraction; all `NaN` for an empty
|
|
117
|
+
* sample or one holding `NaN`.
|
|
118
|
+
* @throws {RangeError} As {@link sampleQuantile}.
|
|
119
|
+
*/
|
|
120
|
+
export declare function sampleQuantiles(values: ArrayLike<number>, fractions: ArrayLike<number>, options?: SampleQuantileOptions): Float64Array;
|
|
33
121
|
//# sourceMappingURL=quantile.d.ts.map
|