@ac-kit/math-stats 0.5.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.
Files changed (165) hide show
  1. package/CHANGELOG.md +205 -0
  2. package/README.md +86 -6
  3. package/dist/_digamma.d.ts +10 -0
  4. package/dist/_digamma.d.ts.map +1 -0
  5. package/dist/_digamma.js +38 -0
  6. package/dist/_digamma.js.map +1 -0
  7. package/dist/_dilogarithm.d.ts +14 -0
  8. package/dist/_dilogarithm.d.ts.map +1 -0
  9. package/dist/_dilogarithm.js +77 -0
  10. package/dist/_dilogarithm.js.map +1 -0
  11. package/dist/_histogram-rules.d.ts +15 -0
  12. package/dist/_histogram-rules.d.ts.map +1 -0
  13. package/dist/_histogram-rules.js +208 -0
  14. package/dist/_histogram-rules.js.map +1 -0
  15. package/dist/_incomplete-gamma-shape-derivative.d.ts +17 -0
  16. package/dist/_incomplete-gamma-shape-derivative.d.ts.map +1 -0
  17. package/dist/_incomplete-gamma-shape-derivative.js +90 -0
  18. package/dist/_incomplete-gamma-shape-derivative.js.map +1 -0
  19. package/dist/_logistic.d.ts +14 -0
  20. package/dist/_logistic.d.ts.map +1 -0
  21. package/dist/_logistic.js +29 -0
  22. package/dist/_logistic.js.map +1 -0
  23. package/dist/_normal-tail.d.ts +43 -0
  24. package/dist/_normal-tail.d.ts.map +1 -0
  25. package/dist/_normal-tail.js +124 -0
  26. package/dist/_normal-tail.js.map +1 -0
  27. package/dist/_rank-test.d.ts +71 -0
  28. package/dist/_rank-test.d.ts.map +1 -0
  29. package/dist/_rank-test.js +130 -0
  30. package/dist/_rank-test.js.map +1 -0
  31. package/dist/average.js +2 -2
  32. package/dist/average.js.map +1 -1
  33. package/dist/bootstrap.d.ts +67 -0
  34. package/dist/bootstrap.d.ts.map +1 -0
  35. package/dist/bootstrap.js +154 -0
  36. package/dist/bootstrap.js.map +1 -0
  37. package/dist/censored-logistic-distribution.d.ts +23 -0
  38. package/dist/censored-logistic-distribution.d.ts.map +1 -0
  39. package/dist/censored-logistic-distribution.js +63 -0
  40. package/dist/censored-logistic-distribution.js.map +1 -0
  41. package/dist/censored-shifted-gamma-distribution.d.ts +23 -0
  42. package/dist/censored-shifted-gamma-distribution.d.ts.map +1 -0
  43. package/dist/censored-shifted-gamma-distribution.js +73 -0
  44. package/dist/censored-shifted-gamma-distribution.js.map +1 -0
  45. package/dist/confidence-interval.d.ts +53 -0
  46. package/dist/confidence-interval.d.ts.map +1 -1
  47. package/dist/confidence-interval.js +73 -0
  48. package/dist/confidence-interval.js.map +1 -1
  49. package/dist/correlation.d.ts +41 -0
  50. package/dist/correlation.d.ts.map +1 -1
  51. package/dist/correlation.js +168 -2
  52. package/dist/correlation.js.map +1 -1
  53. package/dist/descriptive.d.ts +129 -0
  54. package/dist/descriptive.d.ts.map +1 -0
  55. package/dist/descriptive.js +289 -0
  56. package/dist/descriptive.js.map +1 -0
  57. package/dist/forecast/_forecast-checks.d.ts +30 -0
  58. package/dist/forecast/_forecast-checks.d.ts.map +1 -0
  59. package/dist/forecast/_forecast-checks.js +119 -0
  60. package/dist/forecast/_forecast-checks.js.map +1 -0
  61. package/dist/forecast/_score-kernels.d.ts +63 -0
  62. package/dist/forecast/_score-kernels.d.ts.map +1 -0
  63. package/dist/forecast/_score-kernels.js +264 -0
  64. package/dist/forecast/_score-kernels.js.map +1 -0
  65. package/dist/forecast/brier-score.d.ts +102 -0
  66. package/dist/forecast/brier-score.d.ts.map +1 -0
  67. package/dist/forecast/brier-score.js +163 -0
  68. package/dist/forecast/brier-score.js.map +1 -0
  69. package/dist/forecast/crps-closed-form.d.ts +64 -0
  70. package/dist/forecast/crps-closed-form.d.ts.map +1 -0
  71. package/dist/forecast/crps-closed-form.js +106 -0
  72. package/dist/forecast/crps-closed-form.js.map +1 -0
  73. package/dist/forecast/crps-ensemble.d.ts +53 -0
  74. package/dist/forecast/crps-ensemble.d.ts.map +1 -0
  75. package/dist/forecast/crps-ensemble.js +121 -0
  76. package/dist/forecast/crps-ensemble.js.map +1 -0
  77. package/dist/forecast/emos.d.ts +158 -0
  78. package/dist/forecast/emos.d.ts.map +1 -0
  79. package/dist/forecast/emos.js +397 -0
  80. package/dist/forecast/emos.js.map +1 -0
  81. package/dist/forecast/exceedance-probability.d.ts +54 -0
  82. package/dist/forecast/exceedance-probability.d.ts.map +1 -0
  83. package/dist/forecast/exceedance-probability.js +125 -0
  84. package/dist/forecast/exceedance-probability.js.map +1 -0
  85. package/dist/forecast/log-score.d.ts +18 -0
  86. package/dist/forecast/log-score.d.ts.map +1 -0
  87. package/dist/forecast/log-score.js +19 -0
  88. package/dist/forecast/log-score.js.map +1 -0
  89. package/dist/forecast/logistic-regression.d.ts +123 -0
  90. package/dist/forecast/logistic-regression.d.ts.map +1 -0
  91. package/dist/forecast/logistic-regression.js +282 -0
  92. package/dist/forecast/logistic-regression.js.map +1 -0
  93. package/dist/forecast/rank-histogram.d.ts +32 -0
  94. package/dist/forecast/rank-histogram.d.ts.map +1 -0
  95. package/dist/forecast/rank-histogram.js +63 -0
  96. package/dist/forecast/rank-histogram.js.map +1 -0
  97. package/dist/forecast/reliability-diagram.d.ts +70 -0
  98. package/dist/forecast/reliability-diagram.d.ts.map +1 -0
  99. package/dist/forecast/reliability-diagram.js +126 -0
  100. package/dist/forecast/reliability-diagram.js.map +1 -0
  101. package/dist/forecast/roc-curve.d.ts +58 -0
  102. package/dist/forecast/roc-curve.d.ts.map +1 -0
  103. package/dist/forecast/roc-curve.js +124 -0
  104. package/dist/forecast/roc-curve.js.map +1 -0
  105. package/dist/hierarchical-cluster.d.ts.map +1 -1
  106. package/dist/hierarchical-cluster.js +10 -5
  107. package/dist/hierarchical-cluster.js.map +1 -1
  108. package/dist/histogram-edges.d.ts +92 -0
  109. package/dist/histogram-edges.d.ts.map +1 -0
  110. package/dist/histogram-edges.js +325 -0
  111. package/dist/histogram-edges.js.map +1 -0
  112. package/dist/histogram.d.ts +55 -21
  113. package/dist/histogram.d.ts.map +1 -1
  114. package/dist/histogram.js +56 -83
  115. package/dist/histogram.js.map +1 -1
  116. package/dist/index.d.ts +23 -0
  117. package/dist/index.d.ts.map +1 -1
  118. package/dist/index.js +23 -0
  119. package/dist/index.js.map +1 -1
  120. package/dist/kmeans.d.ts.map +1 -1
  121. package/dist/kmeans.js +11 -6
  122. package/dist/kmeans.js.map +1 -1
  123. package/dist/kmedoids.js +2 -1
  124. package/dist/kmedoids.js.map +1 -1
  125. package/dist/mann-whitney-u.d.ts +27 -0
  126. package/dist/mann-whitney-u.d.ts.map +1 -0
  127. package/dist/mann-whitney-u.js +94 -0
  128. package/dist/mann-whitney-u.js.map +1 -0
  129. package/dist/multiple-regression.d.ts +123 -0
  130. package/dist/multiple-regression.d.ts.map +1 -0
  131. package/dist/multiple-regression.js +208 -0
  132. package/dist/multiple-regression.js.map +1 -0
  133. package/dist/principal-components.d.ts +66 -0
  134. package/dist/principal-components.d.ts.map +1 -0
  135. package/dist/principal-components.js +105 -0
  136. package/dist/principal-components.js.map +1 -0
  137. package/dist/quantile.d.ts +113 -5
  138. package/dist/quantile.d.ts.map +1 -1
  139. package/dist/quantile.js +318 -19
  140. package/dist/quantile.js.map +1 -1
  141. package/dist/regression.d.ts +46 -0
  142. package/dist/regression.d.ts.map +1 -1
  143. package/dist/regression.js +99 -1
  144. package/dist/regression.js.map +1 -1
  145. package/dist/running-statistics.d.ts +103 -0
  146. package/dist/running-statistics.d.ts.map +1 -0
  147. package/dist/running-statistics.js +283 -0
  148. package/dist/running-statistics.js.map +1 -0
  149. package/dist/sample.d.ts +29 -0
  150. package/dist/sample.d.ts.map +1 -0
  151. package/dist/sample.js +39 -0
  152. package/dist/sample.js.map +1 -0
  153. package/dist/t-digest.d.ts +136 -0
  154. package/dist/t-digest.d.ts.map +1 -0
  155. package/dist/t-digest.js +424 -0
  156. package/dist/t-digest.js.map +1 -0
  157. package/dist/truncated-normal-distribution.d.ts +28 -0
  158. package/dist/truncated-normal-distribution.d.ts.map +1 -0
  159. package/dist/truncated-normal-distribution.js +198 -0
  160. package/dist/truncated-normal-distribution.js.map +1 -0
  161. package/dist/wilcoxon-signed-rank.d.ts +42 -0
  162. package/dist/wilcoxon-signed-rank.d.ts.map +1 -0
  163. package/dist/wilcoxon-signed-rank.js +117 -0
  164. package/dist/wilcoxon-signed-rank.js.map +1 -0
  165. package/package.json +14 -10
@@ -1,13 +1,121 @@
1
1
  /**
2
- * Linear-interpolated quantile of an already-sorted sample.
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
- * @param sorted Values in ascending order, any array-like (a typed array
8
- * included). Not modified, not re-checked.
57
+ * @param sorted Values in ascending order within the range, any array-like (a
58
+ * typed array included). Not modified, not re-checked.
9
59
  * @param fraction Quantile to compute, in `[0, 1]`.
60
+ * @param options The method and the range read.
10
61
  * @returns The quantile, or `NaN` for an empty sample.
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 }`.
70
+ */
71
+ export declare function quantile(sorted: ArrayLike<number>, fraction: number, from?: number, to?: number): number;
72
+ /**
73
+ * Writes {@link quantile} to `target[index]`, which allocates nothing: a double
74
+ * returned by a call the engine does not inline is boxed, one written to an
75
+ * array is not. One sorted scratch buffer can so fill an output column group by
76
+ * group.
77
+ *
78
+ * @param target A `Float64Array`, or a `number[]` of doubles.
79
+ * @param index The position written.
80
+ * @param sorted As for {@link quantile}.
81
+ * @param fraction As for {@link quantile}.
82
+ * @param options As for {@link quantile}.
83
+ * @throws {RangeError} As {@link quantile}.
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 }`. */
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}.
11
119
  */
12
- export declare function quantile(sorted: ArrayLike<number>, fraction: number): number;
120
+ export declare function sampleQuantiles(values: ArrayLike<number>, fractions: ArrayLike<number>, options?: SampleQuantileOptions): Float64Array;
13
121
  //# sourceMappingURL=quantile.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"quantile.d.ts","sourceRoot":"","sources":["../src/quantile.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,wBAAgB,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC,MAAM,CAAC,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CA4B5E"}
1
+ {"version":3,"file":"quantile.d.ts","sourceRoot":"","sources":["../src/quantile.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,MAAM,cAAc,GACvB,cAAc,GACd,uBAAuB,GACvB,qBAAqB,GACrB,2BAA2B,GAC3B,OAAO,GACP,SAAS,GACT,QAAQ,GACR,iBAAiB,GACjB,iBAAiB,GACjB,OAAO,GACP,QAAQ,GACR,SAAS,GACT,UAAU,CAAC;AAEd,8EAA8E;AAC9E,MAAM,MAAM,eAAe,GAAG;IAC7B,mDAAmD;IACnD,QAAQ,CAAC,MAAM,CAAC,EAAE,cAAc,CAAC;IAEjC;;;OAGG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IAEvB,uDAAuD;IACvD,QAAQ,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF,qEAAqE;AACrE,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AC5B,OAAO,CAAC,EAAE,qBAAqB,GAC7B,YAAY,CAmBd"}
package/dist/quantile.js CHANGED
@@ -1,38 +1,337 @@
1
+ import { quickselectInPlace } from "@ac-kit/algo";
2
+ import { compareNaturalAscending, describeValue } from "@ac-kit/core";
3
+ export function quantile(sorted, fraction, fromOrOptions, to) {
4
+ FRACTION_[0] = fraction;
5
+ if (typeof fromOrOptions === "object") {
6
+ writeOptions_("quantile", RESULT_, 0, sorted, fromOrOptions);
7
+ }
8
+ else {
9
+ writeRange_("quantile", RESULT_, 0, sorted, fromOrOptions ?? 0, to ?? sorted.length);
10
+ }
11
+ return RESULT_[0];
12
+ }
13
+ /** Where {@link quantile} reads its result back. */
14
+ const RESULT_ = new Float64Array(1);
15
+ export function writeQuantile(target, index, sorted, fraction, fromOrOptions, to) {
16
+ FRACTION_[0] = fraction;
17
+ if (typeof fromOrOptions === "object") {
18
+ writeOptions_("writeQuantile", target, index, sorted, fromOrOptions);
19
+ }
20
+ else {
21
+ writeRange_("writeQuantile", target, index, sorted, fromOrOptions ?? 0, to ?? sorted.length);
22
+ }
23
+ }
1
24
  /**
2
- * Linear-interpolated quantile of an already-sorted sample.
25
+ * The `fraction` quantile of a sample in any order, by `method` ({@link
26
+ * QuantileMethod}, `"linear"` by default): the one or two order statistics it
27
+ * needs are found by selection (`quickselectInPlace` from `@ac-kit/algo`) on a
28
+ * copy, so O(n) expected time rather than a sort. A `NaN` in the sample gives
29
+ * `NaN`, as NumPy's `quantile` does.
3
30
  *
4
- * Exact at the sample's values and free of overflow between them, even when two
5
- * neighbours are further apart than `Number.MAX_VALUE`.
31
+ * @example
32
+ * ```ts
33
+ * sampleQuantile([4, 1, 3, 2], 0.5); // 2.5
34
+ * sampleQuantile([4, 1, 3, 2], 0.5, { method: "inverted-cdf" }); // 2
35
+ * ```;
6
36
  *
7
- * @param sorted Values in ascending order, any array-like (a typed array
8
- * included). Not modified, not re-checked.
37
+ * @param values The sample. Not modified.
9
38
  * @param fraction Quantile to compute, in `[0, 1]`.
39
+ * @param options The method.
10
40
  * @returns The quantile, or `NaN` for an empty sample.
41
+ * @throws {RangeError} When `fraction` is outside `[0, 1]` or `method` is not a
42
+ * {@link QuantileMethod}.
11
43
  */
12
- export function quantile(sorted, fraction) {
13
- if (sorted.length === 0) {
44
+ export function sampleQuantile(values, fraction, options) {
45
+ const method = options?.method ?? "linear";
46
+ FRACTION_[0] = fraction;
47
+ checkArguments_("sampleQuantile", method);
48
+ const count = values.length;
49
+ if (count === 0) {
14
50
  return Number.NaN;
15
51
  }
16
- if (sorted.length === 1) {
17
- return sorted[0];
52
+ const working = Array.from({ length: count });
53
+ for (let index = 0; index < count; index++) {
54
+ const value = values[index];
55
+ if (value !== value) {
56
+ return Number.NaN;
57
+ }
58
+ working[index] = value;
59
+ }
60
+ position_(count, method);
61
+ const lower = INDICES_[0];
62
+ const pair = PAIR_;
63
+ pair[0] = quickselectInPlace(working, lower, compareNaturalAscending);
64
+ pair[1] = pair[0];
65
+ if (INDICES_[1] > lower) {
66
+ // Selection leaves every larger element on the right: the next order
67
+ // statistic is their least.
68
+ pair[1] = Number.POSITIVE_INFINITY;
69
+ for (let index = lower + 1; index < count; index++) {
70
+ if (working[index] < pair[1]) {
71
+ pair[1] = working[index];
72
+ }
73
+ }
74
+ }
75
+ interpolate_(RESULT_, 0, PAIR_, 0, 1);
76
+ return RESULT_[0];
77
+ }
78
+ /** The two order statistics {@link sampleQuantile} selected. */
79
+ const PAIR_ = new Float64Array(2);
80
+ /**
81
+ * {@link sampleQuantile} at several fractions: the sample is copied and sorted
82
+ * once, O(n log n + m).
83
+ *
84
+ * @param values The sample, in any order. Not modified.
85
+ * @param fractions The quantiles to compute, each in `[0, 1]`.
86
+ * @param options The method.
87
+ * @returns A new array of one quantile per fraction; all `NaN` for an empty
88
+ * sample or one holding `NaN`.
89
+ * @throws {RangeError} As {@link sampleQuantile}.
90
+ */
91
+ export function sampleQuantiles(values, fractions, options) {
92
+ const method = options?.method ?? "linear";
93
+ for (let index = 0; index < fractions.length; index++) {
94
+ FRACTION_[0] = fractions[index];
95
+ checkArguments_("sampleQuantiles", method);
96
+ }
97
+ const out = new Float64Array(fractions.length);
98
+ const sorted = Float64Array.from(values);
99
+ for (let index = 0; index < sorted.length; index++) {
100
+ if (sorted[index] !== sorted[index]) {
101
+ return out.fill(Number.NaN);
102
+ }
103
+ }
104
+ sorted.sort();
105
+ for (let index = 0; index < fractions.length; index++) {
106
+ FRACTION_[0] = fractions[index];
107
+ writeSorted_(out, index, sorted, method, 0, sorted.length);
108
+ }
109
+ return out;
110
+ }
111
+ // A switch rather than a `Set`: `Set#has` of a string allocates in V8.
112
+ function isQuantileMethod_(method) {
113
+ switch (method) {
114
+ case "inverted-cdf":
115
+ case "averaged-inverted-cdf":
116
+ case "closest-observation":
117
+ case "interpolated-inverted-cdf":
118
+ case "hazen":
119
+ case "weibull":
120
+ case "linear":
121
+ case "median-unbiased":
122
+ case "normal-unbiased":
123
+ case "lower":
124
+ case "higher":
125
+ case "nearest":
126
+ case "midpoint": {
127
+ return true;
128
+ }
129
+ default: {
130
+ return false;
131
+ }
132
+ }
133
+ }
134
+ /**
135
+ * The fraction being computed, set once at each entry point: a double passed
136
+ * through a call the engine does not inline is boxed, one read from an array is
137
+ * not.
138
+ */
139
+ const FRACTION_ = new Float64Array(1);
140
+ function checkArguments_(name, method) {
141
+ const fraction = FRACTION_[0];
142
+ if (!(fraction >= 0 && fraction <= 1)) {
143
+ throw new RangeError(`${name}: fraction must be in [0, 1], got ${describeValue(fraction)}`);
144
+ }
145
+ if (!isQuantileMethod_(method)) {
146
+ throw new RangeError(`${name}: unknown quantile method ${describeValue(method)}`);
147
+ }
148
+ }
149
+ // Two paths rather than one taking `number | QuantileOptions`: with both shapes
150
+ // in its feedback, the positional hot path allocates.
151
+ function writeOptions_(name, target, index, sorted, options) {
152
+ const from = options.from ?? 0;
153
+ const end = options.to ?? sorted.length;
154
+ const method = options.method ?? "linear";
155
+ assertRange_(name, sorted, from, end);
156
+ if (!(FRACTION_[0] >= 0 && FRACTION_[0] <= 1) ||
157
+ !isQuantileMethod_(method)) {
158
+ checkArguments_(name, method);
159
+ }
160
+ writeSorted_(target, index, sorted, method, from, end);
161
+ }
162
+ function writeRange_(name, target, index, sorted, from, to) {
163
+ assertRange_(name, sorted, from, to);
164
+ // Checked here, the throw out of line, so the hot path reads the fraction
165
+ // in optimised code only.
166
+ if (!(FRACTION_[0] >= 0 && FRACTION_[0] <= 1)) {
167
+ checkArguments_(name, "linear");
168
+ }
169
+ const length = to - from;
170
+ if (length === 0) {
171
+ target[index] = Number.NaN;
172
+ return;
173
+ }
174
+ const scaled = (length - 1) * FRACTION_[0];
175
+ const lower = Math.floor(scaled);
176
+ const weight = scaled - lower;
177
+ const lowerValue = sorted[from + lower];
178
+ if (weight === 0) {
179
+ target[index] = lowerValue;
180
+ return;
181
+ }
182
+ const upperValue = sorted[from + lower + 1];
183
+ const difference = upperValue - lowerValue;
184
+ target[index] =
185
+ difference === Infinity &&
186
+ lowerValue !== -Infinity &&
187
+ upperValue !== Infinity
188
+ ? 2 * (lowerValue / 2 + (upperValue / 2 - lowerValue / 2) * weight)
189
+ : lowerValue + difference * weight;
190
+ }
191
+ function assertRange_(name, sorted, from, to) {
192
+ if (!Number.isInteger(from) ||
193
+ !Number.isInteger(to) ||
194
+ from < 0 ||
195
+ from > to ||
196
+ to > sorted.length) {
197
+ throw new RangeError(`${name}: [${from}, ${to}) is not a range of [0, ${sorted.length})`);
198
+ }
199
+ }
200
+ function writeSorted_(target, index, sorted, method, from, to) {
201
+ const length = to - from;
202
+ if (length === 0) {
203
+ target[index] = Number.NaN;
204
+ return;
205
+ }
206
+ position_(length, method);
207
+ interpolate_(target, index, sorted, from + INDICES_[0], from + INDICES_[1]);
208
+ }
209
+ /**
210
+ * `[lower, upper, weight]` of a quantile: the 0-based order statistics it reads
211
+ * and the weight of the upper one. Through an array, so no double is returned
212
+ * boxed.
213
+ */
214
+ const POSITION_ = new Float64Array(3);
215
+ /** `(α, β)` of the continuous Hyndman–Fan types: `h = p(n + 1 − α − β) + α`. */
216
+ const PLOTTING_POSITIONS_ = {
217
+ "interpolated-inverted-cdf": [0, 1],
218
+ hazen: [0.5, 0.5],
219
+ weibull: [0, 0],
220
+ "median-unbiased": [1 / 3, 1 / 3],
221
+ "normal-unbiased": [3 / 8, 3 / 8],
222
+ };
223
+ function position_(count, method) {
224
+ const fraction = FRACTION_[0];
225
+ const last = count - 1;
226
+ const position = POSITION_;
227
+ switch (method) {
228
+ case "inverted-cdf":
229
+ case "averaged-inverted-cdf":
230
+ case "closest-observation": {
231
+ // Hyndman and Fan's j and g, 1-based: j = ⌊np + m⌋, g = np + m − j.
232
+ const shifted = count * fraction - (method === "closest-observation" ? 0.5 : 0);
233
+ const j = Math.floor(shifted);
234
+ position[2] =
235
+ shifted - j > 0
236
+ ? 1
237
+ : method === "averaged-inverted-cdf"
238
+ ? 0.5
239
+ : method === "closest-observation" && j % 2 !== 0
240
+ ? 1
241
+ : 0;
242
+ position[0] = j - 1;
243
+ position[1] = j;
244
+ setPosition_(last);
245
+ return;
246
+ }
247
+ case "linear":
248
+ case "lower":
249
+ case "higher":
250
+ case "nearest":
251
+ case "midpoint": {
252
+ const scaled = last * fraction;
253
+ const lower = Math.floor(scaled);
254
+ const weight = scaled - lower;
255
+ if (method === "linear") {
256
+ position[2] = weight;
257
+ }
258
+ else if (method === "lower") {
259
+ position[2] = 0;
260
+ }
261
+ else if (method === "higher") {
262
+ position[2] = weight > 0 ? 1 : 0;
263
+ }
264
+ else if (method === "midpoint") {
265
+ position[2] = weight > 0 ? 0.5 : 0;
266
+ }
267
+ else {
268
+ // Round half to even, as NumPy's `around` of the position.
269
+ position[2] =
270
+ weight > 0.5 || (weight === 0.5 && lower % 2 !== 0) ? 1 : 0;
271
+ }
272
+ position[0] = lower;
273
+ position[1] = lower + 1;
274
+ setPosition_(last);
275
+ return;
276
+ }
277
+ default: {
278
+ const plotting = PLOTTING_POSITIONS_[method];
279
+ const alpha = plotting[0];
280
+ const h = fraction * (count + 1 - alpha - plotting[1]) + alpha;
281
+ const j = Math.floor(h);
282
+ position[2] = h - j;
283
+ position[0] = j - 1;
284
+ position[1] = j;
285
+ setPosition_(last);
286
+ }
287
+ }
288
+ }
289
+ // Clamps the 0-based candidates POSITION_[0…1] into the sample, and the weight
290
+ // POSITION_[2] to the clamped pair, into INDICES_. Read and written through
291
+ // arrays: a double passed to a call can be boxed.
292
+ function setPosition_(last) {
293
+ const position = POSITION_;
294
+ const indices = INDICES_;
295
+ const lower = position[0];
296
+ const upper = position[1];
297
+ if (lower < 0) {
298
+ indices[0] = 0;
299
+ indices[1] = 0;
300
+ position[2] = 0;
301
+ return;
18
302
  }
19
- const position = (sorted.length - 1) * fraction;
20
- const lower = Math.floor(position);
21
- const upper = Math.ceil(position);
22
- if (lower === upper) {
23
- return sorted[lower];
303
+ if (upper > last) {
304
+ indices[0] = last;
305
+ indices[1] = last;
306
+ position[2] = 0;
307
+ return;
308
+ }
309
+ const weight = position[2];
310
+ const settled = weight === 0 || weight === 1;
311
+ indices[0] = weight === 1 ? upper : lower;
312
+ indices[1] = settled ? indices[0] : upper;
313
+ position[2] = settled ? 0 : weight;
314
+ }
315
+ /** `[lower, upper]`: the 0-based order statistics a quantile reads. */
316
+ const INDICES_ = new Int32Array(2);
317
+ function interpolate_(target, index, values, lowerIndex, upperIndex) {
318
+ const lowerValue = values[lowerIndex];
319
+ const weight = POSITION_[2];
320
+ if (weight === 0) {
321
+ target[index] = lowerValue;
322
+ return;
24
323
  }
25
- const lowerValue = sorted[lower];
26
- const upperValue = sorted[upper];
27
- const weight = position - lower;
324
+ const upperValue = values[upperIndex];
28
325
  const difference = upperValue - lowerValue;
29
326
  if (difference === Infinity &&
30
327
  lowerValue !== -Infinity &&
31
328
  upperValue !== Infinity) {
32
329
  // Finite neighbours further apart than the largest double: their halves,
33
330
  // exact at that magnitude, interpolate without overflow.
34
- return 2 * (lowerValue / 2 + (upperValue / 2 - lowerValue / 2) * weight);
331
+ target[index] =
332
+ 2 * (lowerValue / 2 + (upperValue / 2 - lowerValue / 2) * weight);
333
+ return;
35
334
  }
36
- return lowerValue + difference * weight;
335
+ target[index] = lowerValue + difference * weight;
37
336
  }
38
337
  //# sourceMappingURL=quantile.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"quantile.js","sourceRoot":"","sources":["../src/quantile.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,MAAM,UAAU,QAAQ,CAAC,MAAyB,EAAE,QAAgB;IACnE,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,MAAM,CAAC,GAAG,CAAC;IACnB,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,MAAM,CAAC,CAAC,CAAE,CAAC;IACnB,CAAC;IAED,MAAM,QAAQ,GAAG,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,QAAQ,CAAC;IAChD,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACnC,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAClC,IAAI,KAAK,KAAK,KAAK,EAAE,CAAC;QACrB,OAAO,MAAM,CAAC,KAAK,CAAE,CAAC;IACvB,CAAC;IACD,MAAM,UAAU,GAAG,MAAM,CAAC,KAAK,CAAE,CAAC;IAClC,MAAM,UAAU,GAAG,MAAM,CAAC,KAAK,CAAE,CAAC;IAClC,MAAM,MAAM,GAAG,QAAQ,GAAG,KAAK,CAAC;IAChC,MAAM,UAAU,GAAG,UAAU,GAAG,UAAU,CAAC;IAC3C,IACC,UAAU,KAAK,QAAQ;QACvB,UAAU,KAAK,CAAC,QAAQ;QACxB,UAAU,KAAK,QAAQ,EACtB,CAAC;QACF,yEAAyE;QACzE,yDAAyD;QACzD,OAAO,CAAC,GAAG,CAAC,UAAU,GAAG,CA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AAC,CAAC,CAAC,KAAK,CAAC;IAC1C,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IAC1C,QAAQ,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;AACpC,CAAC;AAED,uEAAuE;AACvE,MAAM,QAAQ,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;AAEnC,SAAS,YAAY,CACpB,MAA+B,EAC/B,KAAa,EACb,MAAyB,EACzB,UAAkB,EAClB,UAAkB;IAElB,MAAM,UAAU,GAAG,MAAM,CAAC,UAAU,CAAE,CAAC;IACvC,MAAM,MAAM,GAAG,SAAS,CAAC,CAAC,CAAE,CAAC;IAC7B,IAAI,MAAM,KAAK,CAAC,EAAE,CAAC;QAClB,MAAM,CAAC,KAAK,CAAC,GAAG,UAAU,CAAC;QAC3B,OAAO;IACR,CAAC;IACD,MAAM,UAAU,GAAG,MAAM,CAAC,UAAU,CAAE,CAAC;IACvC,MAAM,UAAU,GAAG,UAAU,GAAG,UAAU,CAAC;IAC3C,IACC,UAAU,KAAK,QAAQ;QACvB,UAAU,KAAK,CAAC,QAAQ;QACxB,UAAU,KAAK,QAAQ,EACtB,CAAC;QACF,yEAAyE;QACzE,yDAAyD;QACzD,MAAM,CAAC,KAAK,CAAC;YACZ,CAAC,GAAG,CAAC,UAAU,GAAG,CAAC,GAAG,CAAC,UAAU,GAAG,CAAC,GAAG,UAAU,GAAG,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC;QACnE,OAAO;IACR,CAAC;IACD,MAAM,CAAC,KAAK,CAAC,GAAG,UAAU,GAAG,UAAU,GAAG,MAAM,CAAC;AAClD,CAAC"}
@@ -1,3 +1,49 @@
1
+ import { type RegressionOptions, type RegressionResult } from "./multiple-regression.js";
2
+ /** What {@link linearRegression} returns: a two-coefficient regression. */
3
+ export type LinearRegressionResult = RegressionResult & {
4
+ /** The slope `β₁`; `0` when every `x` is equal. */
5
+ readonly slope: number;
6
+ /** The intercept `β₀`, the fitted value at `x = 0`. */
7
+ readonly intercept: number;
8
+ /** The slope's standard error (SciPy's `stderr`). */
9
+ readonly slopeStandardError: number;
10
+ /** The intercept's standard error (SciPy's `intercept_stderr`). */
11
+ readonly interceptStandardError: number;
12
+ /**
13
+ * Pearson's (weighted) correlation `r`, the signed square root of R² (SciPy's
14
+ * `rvalue`); `NaN` when either side is constant.
15
+ */
16
+ readonly correlation: number;
17
+ };
18
+ /**
19
+ * The least-squares line `y ≈ β₀ + β₁x` through paired samples, with the
20
+ * inference of SciPy's `linregress` and R's `lm(y ~ x)`: slope, intercept,
21
+ * their standard errors and t tests (`pValues[1]` tests the slope), R², the
22
+ * correlation, residuals, fitted values and the rest of a
23
+ * {@link RegressionResult} (`coefficients` is `[β₀, β₁]`).
24
+ *
25
+ * The fit is {@link multipleRegression} on the design `[1, x − x̄]`, `x̄` the
26
+ * exactly summed (weighted) mean: centring makes the two columns orthogonal, so
27
+ * the QR loses nothing to an `x` far from the origin, and constant `x` leaves
28
+ * the slope aliased (`0`, statistics `NaN`) rather than the intercept. The
29
+ * intercept and its variance are then carried back exactly, `β₀ = b₀ − x̄β₁`.
30
+ * {@link linearRegressionSlope} is the slope alone, without allocating.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * const fit = linearRegression([1, 2, 3, 4], [2.1, 3.9, 6.2, 7.8]);
35
+ * fit.slope; // 1.93
36
+ * fit.pValues[1]; // the slope's two-sided p-value
37
+ * ```;
38
+ *
39
+ * @param xValues Independent-variable samples. Not modified.
40
+ * @param yValues Dependent-variable samples paired by index. Not modified.
41
+ * @param options Weights and the rank tolerance.
42
+ * @returns The fit.
43
+ * @throws {RangeError} When the lengths differ, a value or weight is not finite
44
+ * (weights non-negative), or no case has a positive weight.
45
+ */
46
+ export declare function linearRegression(xValues: ArrayLike<number>, yValues: ArrayLike<number>, options?: RegressionOptions): LinearRegressionResult;
1
47
  /**
2
48
  * Slope of the ordinary-least-squares line through paired `xValues` and
3
49
  * `yValues`.
@@ -1 +1 @@
1
- {"version":3,"file":"regression.d.ts","sourceRoot":"","sources":["../src/regression.ts"],"names":[],"mappings":"AAeA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,wBAAgB,qBAAqB,CACpC,OAAO,EAAE,SAAS,MAAM,EAAE,EAC1B,OAAO,EAAE,SAAS,MAAM,EAAE,GACxB,MAAM,CA8BR"}
1
+ {"version":3,"file":"regression.d.ts","sourceRoot":"","sources":["../src/regression.ts"],"names":[],"mappings":"AAUA,OAAO,EAEN,KAAK,iBAAiB,EACtB,KAAK,gBAAgB,EACrB,MAAM,0BAA0B,CAAC;AAGlC,2EAA2E;AAC3E,MAAM,MAAM,sBAAsB,GAAG,gBAAgB,GAAG;IACvD,mDAAmD;IACnD,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IAEvB,uDAAuD;IACvD,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAE3B,qDAAqD;IACrD,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC;IAEpC,mEAAmE;IACnE,QAAQ,CAAC,sBAAsB,EAAE,MAAM,CAAC;IAExC;;;OAGG;IACH,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;CAC7B,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,gBAAgB,CAC/B,OAAO,EAAE,SAAS,CAAC,MAAM,CAAC,EAC1B,OAAO,EAAE,SAAS,CAAC,MAAM,CAAC,EAC1B,OAAO,CAAC,EAAE,iBAAiB,GACzB,sBAAsB,CA6ExB;AAcD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,wBAAgB,qBAAqB,CACpC,OAAO,EAAE,SAAS,MAAM,EAAE,EAC1B,OAAO,EAAE,SAAS,MAAM,EAAE,GACxB,MAAM,CA8BR"}