@mark1russell7/rigor-generators 0.2.4 → 0.2.5

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/README.md CHANGED
@@ -106,6 +106,15 @@ Each table is a sample, and it does not show a general law:
106
106
 
107
107
  The npm package holds the notice of the Ptolemy II license, because the field `notice` is part of the build.
108
108
 
109
+ ### The beta and gamma functions
110
+
111
+ `logGamma(x)`, `logBeta(a, b)`, `betaCdf(x, a, b)` and `betaShares(x, y, a, b)` give the special functions of the families.
112
+
113
+ - `logBeta` keeps the digits of its value when a parameter is near 1e13. There, the sum of `logGamma` loses all of them.
114
+ - `betaShares` takes the point `x` and its distance `y = 1 - x` from 1. Thus a point near 1 keeps its digits. The function gives the shares of the law below and above the point.
115
+
116
+ The Student t law with `df` degrees of freedom has its shares between `-t` and `t` and above `|t|` in `betaShares(t^2 / (df + t^2), df / (df + t^2), 0.5, df / 2)`.
117
+
109
118
  ## Input families and designs
110
119
 
111
120
  An input family has named dimensions. Each dimension has a range from `min` to `max`. It can also have one of these:
package/build/index.d.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  import { COVERING_CANDIDATES, COVERING_LIMIT, Coverage, CoveringOptions, coveringArray, coveringRows, tupleCoverage } from "./covering.js";
2
2
  import { DistributionSpec, Param, dependsOnLibm, sampler } from "./distributions.js";
3
3
  import { normalCdf, normalQuantile } from "./normal.js";
4
- import { Distribution, betaCdf, distributionOf, logGamma } from "./quantiles.js";
4
+ import { BetaShares, Distribution, betaCdf, betaShares, distributionOf, logBeta, logGamma } from "./quantiles.js";
5
5
  import { Dimension, InputFamily, Point, SaltelliDesign, familyMap, familyPoints, latinHypercube, oneAtATimePoints, randomDesign, saltelliDesign, stratifiedDesign } from "./designs.js";
6
6
  import { CanonicalOptions, Sha256Options, canonicalHash, canonicalJson, sha256Hex } from "./hash.js";
7
7
  import { SHRINK_CHECKS, SHRINK_TOLERANCE, ShrinkOptions, ShrinkStep, Shrunk, shrinkPoint, shrinkPointAsync, shrinkTarget } from "./shrink.js";
8
8
  import { DIAGRAM_BOX_AREA, GIT_BLOB_BYTES, RECORDED_TABLES, RecordedTable, recordedSpec } from "./recorded.js";
9
9
  import { Random, Source, deriveSeed, fnv1a32, mulberry32, plackettLuceOrder, random, randomOf, seedOf, seedsFrom, stablePick } from "./random.js";
10
- export { COVERING_CANDIDATES, COVERING_LIMIT, type CanonicalOptions, type Coverage, type CoveringOptions, DIAGRAM_BOX_AREA, type Dimension, type Distribution, type DistributionSpec, GIT_BLOB_BYTES, type InputFamily, type Param, type Point, RECORDED_TABLES, type Random, type RecordedTable, SHRINK_CHECKS, SHRINK_TOLERANCE, type SaltelliDesign, type Sha256Options, type ShrinkOptions, type ShrinkStep, type Shrunk, type Source, betaCdf, canonicalHash, canonicalJson, coveringArray, coveringRows, dependsOnLibm, deriveSeed, distributionOf, familyMap, familyPoints, fnv1a32, latinHypercube, logGamma, mulberry32, normalCdf, normalQuantile, oneAtATimePoints, plackettLuceOrder, random, randomDesign, randomOf, recordedSpec, saltelliDesign, sampler, seedOf, seedsFrom, sha256Hex, shrinkPoint, shrinkPointAsync, shrinkTarget, stablePick, stratifiedDesign, tupleCoverage };
10
+ export { type BetaShares, COVERING_CANDIDATES, COVERING_LIMIT, type CanonicalOptions, type Coverage, type CoveringOptions, DIAGRAM_BOX_AREA, type Dimension, type Distribution, type DistributionSpec, GIT_BLOB_BYTES, type InputFamily, type Param, type Point, RECORDED_TABLES, type Random, type RecordedTable, SHRINK_CHECKS, SHRINK_TOLERANCE, type SaltelliDesign, type Sha256Options, type ShrinkOptions, type ShrinkStep, type Shrunk, type Source, betaCdf, betaShares, canonicalHash, canonicalJson, coveringArray, coveringRows, dependsOnLibm, deriveSeed, distributionOf, familyMap, familyPoints, fnv1a32, latinHypercube, logBeta, logGamma, mulberry32, normalCdf, normalQuantile, oneAtATimePoints, plackettLuceOrder, random, randomDesign, randomOf, recordedSpec, saltelliDesign, sampler, seedOf, seedsFrom, sha256Hex, shrinkPoint, shrinkPointAsync, shrinkTarget, stablePick, stratifiedDesign, tupleCoverage };
package/build/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { COVERING_CANDIDATES, COVERING_LIMIT, coveringArray, coveringRows, tupleCoverage } from "./covering.js";
2
2
  import { dependsOnLibm, sampler } from "./distributions.js";
3
3
  import { normalCdf, normalQuantile } from "./normal.js";
4
- import { betaCdf, distributionOf, logGamma } from "./quantiles.js";
4
+ import { betaCdf, betaShares, distributionOf, logBeta, logGamma } from "./quantiles.js";
5
5
  import { familyMap, familyPoints, latinHypercube, oneAtATimePoints, randomDesign, saltelliDesign, stratifiedDesign } from "./designs.js";
6
6
  import { canonicalHash, canonicalJson, sha256Hex } from "./hash.js";
7
7
  import { SHRINK_CHECKS, SHRINK_TOLERANCE, shrinkPoint, shrinkPointAsync, shrinkTarget } from "./shrink.js";
8
8
  import { DIAGRAM_BOX_AREA, GIT_BLOB_BYTES, RECORDED_TABLES, recordedSpec } from "./recorded.js";
9
9
  import { deriveSeed, fnv1a32, mulberry32, plackettLuceOrder, random, randomOf, seedOf, seedsFrom, stablePick } from "./random.js";
10
- export { COVERING_CANDIDATES, COVERING_LIMIT, DIAGRAM_BOX_AREA, GIT_BLOB_BYTES, RECORDED_TABLES, SHRINK_CHECKS, SHRINK_TOLERANCE, betaCdf, canonicalHash, canonicalJson, coveringArray, coveringRows, dependsOnLibm, deriveSeed, distributionOf, familyMap, familyPoints, fnv1a32, latinHypercube, logGamma, mulberry32, normalCdf, normalQuantile, oneAtATimePoints, plackettLuceOrder, random, randomDesign, randomOf, recordedSpec, saltelliDesign, sampler, seedOf, seedsFrom, sha256Hex, shrinkPoint, shrinkPointAsync, shrinkTarget, stablePick, stratifiedDesign, tupleCoverage };
10
+ export { COVERING_CANDIDATES, COVERING_LIMIT, DIAGRAM_BOX_AREA, GIT_BLOB_BYTES, RECORDED_TABLES, SHRINK_CHECKS, SHRINK_TOLERANCE, betaCdf, betaShares, canonicalHash, canonicalJson, coveringArray, coveringRows, dependsOnLibm, deriveSeed, distributionOf, familyMap, familyPoints, fnv1a32, latinHypercube, logBeta, logGamma, mulberry32, normalCdf, normalQuantile, oneAtATimePoints, plackettLuceOrder, random, randomDesign, randomOf, recordedSpec, saltelliDesign, sampler, seedOf, seedsFrom, sha256Hex, shrinkPoint, shrinkPointAsync, shrinkTarget, stablePick, stratifiedDesign, tupleCoverage };
@@ -16,7 +16,33 @@ export interface Distribution {
16
16
  * The relative error is below 1e-14, away from the zeros at 1 and 2. Below 0.5, the reflection formula gives the value.
17
17
  */
18
18
  export declare function logGamma(x: number): number;
19
- /** This function gives the regularized incomplete beta function: the beta cumulative distribution at `x`. */
19
+ /**
20
+ * This function gives the logarithm of the beta function, `logGamma(a) + logGamma(b) - logGamma(a + b)`, for `a` and `b` above 0.
21
+ * - When an argument is 10 or more, the Stirling series gives the difference of the large terms (as `lbeta` of R).
22
+ * Thus the value is accurate also when `a + b` is near 1e13. There, the sum of `logGamma` loses all digits of the difference.
23
+ * - When both arguments are below 10, the value is the sum of `logGamma`.
24
+ */
25
+ export declare function logBeta(a: number, b: number): number;
26
+ /** The shares of a beta law below and above a point. */
27
+ export interface BetaShares {
28
+ /** The share of the law below the point: the regularized incomplete beta function. */
29
+ readonly below: number;
30
+ /** The share of the law above the point. */
31
+ readonly above: number;
32
+ }
33
+ /**
34
+ * This function gives the shares of the beta law with the parameters `a` and `b` below and above `x`.
35
+ * - The caller gives `x` and `y = 1 - x`, each with its full digits. Thus a point near 1 keeps the digits of its distance from 1.
36
+ * For example, `df / (df + t^2)` and `t^2 / (df + t^2)` give both shares of the Student t law with no rounding near 1.
37
+ * - The continued fraction gives the smaller share with its relative digits. The other share is 1 less that share.
38
+ * - The fraction loses digits when its point is near 1 and its first parameter is large. This is the share above `x` when `x` is above `(a + 1) / (a + b + 2)`.
39
+ * The tests hold the relative error of that share below `2e-16 * b`, for `b` from 5e5 to 5e8.
40
+ * - The logs of the front factor use the smaller of `x` and `y`, and the factor uses `logBeta`. Thus a parameter near 1e13 keeps the digits of the shares.
41
+ *
42
+ * @throws RangeError when `x` or `y` is not from 0 to 1, or when `x + y` is not 1
43
+ */
44
+ export declare function betaShares(x: number, y: number, a: number, b: number): BetaShares;
45
+ /** This function gives the regularized incomplete beta function: the beta cumulative distribution at `x` (`betaShares` with `1 - x`). */
20
46
  export declare function betaCdf(x: number, a: number, b: number): number;
21
47
  /**
22
48
  * This function gives one point of a family, with its `cdf` and its `quantile`. It draws the parameters from `r` in
@@ -1 +1 @@
1
- {"version":3,"file":"quantiles.d.ts","names":[],"sources":["../src/quantiles.ts"],"mappings":";;;iBAOiB;;WAEN,QAAQ;;WAER;;EAET,IAAI;;EAEJ,SAAS;;;;;;wBAYK,SAAS;;wBAwCT,QAAQ,WAAW,WAAW;;;;;;wBA+C9B,eAAe,MAAM,kBAAkB,GAAG,SAAS"}
1
+ {"version":3,"file":"quantiles.d.ts","names":[],"sources":["../src/quantiles.ts"],"mappings":";;;iBAOiB;;WAEN,QAAQ;;WAER;;EAET,IAAI;;EAEJ,SAAS;;;;;;wBAYK,SAAS;;;;;;;wBA6BT,QAAQ,WAAW;;iBA8ClB;;WAEN;;WAEA;;;;;;;;;;;;;wBAcK,WAAW,WAAW,WAAW,WAAW,YAAY;;wBAkBxD,QAAQ,WAAW,WAAW;;;;;;wBA6C9B,eAAe,MAAM,kBAAkB,GAAG,SAAS"}
@@ -23,6 +23,47 @@ function logGamma(x) {
23
23
  const t = y + 7.5;
24
24
  return .5 * Math.log(2 * Math.PI) + (y + .5) * Math.log(t) - t + Math.log(sum);
25
25
  }
26
+ /** The coefficients of the Stirling series of the log of the gamma function: B(2k) / (2k (2k - 1)) for k from 1 to 8. */
27
+ const STIRLING = [
28
+ 1 / 12,
29
+ -1 / 360,
30
+ 1 / 1260,
31
+ -1 / 1680,
32
+ 1 / 1188,
33
+ -691 / 360360,
34
+ 1 / 156,
35
+ -3617 / 122400
36
+ ];
37
+ /**
38
+ * This function gives the Stirling correction: `logGamma(x)` less `(x - 0.5) log x - x + log(2 pi) / 2`, for `x` of 10 or more.
39
+ * At 10, the first term that the series omits is below 2e-18.
40
+ */
41
+ function stirlingCorrection(x) {
42
+ const square = 1 / (x * x);
43
+ let sum = 0;
44
+ for (let i = STIRLING.length - 1; i >= 0; i--) sum = sum * square + STIRLING[i];
45
+ return sum / x;
46
+ }
47
+ /**
48
+ * This function gives the logarithm of the beta function, `logGamma(a) + logGamma(b) - logGamma(a + b)`, for `a` and `b` above 0.
49
+ * - When an argument is 10 or more, the Stirling series gives the difference of the large terms (as `lbeta` of R).
50
+ * Thus the value is accurate also when `a + b` is near 1e13. There, the sum of `logGamma` loses all digits of the difference.
51
+ * - When both arguments are below 10, the value is the sum of `logGamma`.
52
+ */
53
+ function logBeta(a, b) {
54
+ const p = Math.min(a, b);
55
+ const q = Math.max(a, b);
56
+ const share = p / (p + q);
57
+ if (p >= 10) {
58
+ const correction = stirlingCorrection(p) + stirlingCorrection(q) - stirlingCorrection(p + q);
59
+ return -.5 * Math.log(q) + .5 * Math.log(2 * Math.PI) + correction + (p - .5) * Math.log(share) + q * Math.log1p(-share);
60
+ }
61
+ if (q >= 10) {
62
+ const correction = stirlingCorrection(q) - stirlingCorrection(p + q);
63
+ return logGamma(p) + correction + p - p * Math.log(p + q) + (q - .5) * Math.log1p(-share);
64
+ }
65
+ return logGamma(p) + logGamma(q) - logGamma(p + q);
66
+ }
26
67
  /** This function gives the continued fraction of the incomplete beta function (the method of Lentz). */
27
68
  function betaFraction(a, b, x) {
28
69
  const tiny = 1e-300;
@@ -52,14 +93,49 @@ function betaFraction(a, b, x) {
52
93
  }
53
94
  return h;
54
95
  }
55
- /** This function gives the regularized incomplete beta function: the beta cumulative distribution at `x`. */
96
+ /**
97
+ * This function gives the shares of the beta law with the parameters `a` and `b` below and above `x`.
98
+ * - The caller gives `x` and `y = 1 - x`, each with its full digits. Thus a point near 1 keeps the digits of its distance from 1.
99
+ * For example, `df / (df + t^2)` and `t^2 / (df + t^2)` give both shares of the Student t law with no rounding near 1.
100
+ * - The continued fraction gives the smaller share with its relative digits. The other share is 1 less that share.
101
+ * - The fraction loses digits when its point is near 1 and its first parameter is large. This is the share above `x` when `x` is above `(a + 1) / (a + b + 2)`.
102
+ * The tests hold the relative error of that share below `2e-16 * b`, for `b` from 5e5 to 5e8.
103
+ * - The logs of the front factor use the smaller of `x` and `y`, and the factor uses `logBeta`. Thus a parameter near 1e13 keeps the digits of the shares.
104
+ *
105
+ * @throws RangeError when `x` or `y` is not from 0 to 1, or when `x + y` is not 1
106
+ */
107
+ function betaShares(x, y, a, b) {
108
+ if (!(x >= 0 && x <= 1 && y >= 0 && y <= 1 && Math.abs(x + y - 1) <= 1e-12)) throw new RangeError(`betaShares: x and y are from 0 to 1 and their sum is 1, not ${x} and ${y}.`);
109
+ if (x === 0) return {
110
+ below: 0,
111
+ above: 1
112
+ };
113
+ if (y === 0) return {
114
+ below: 1,
115
+ above: 0
116
+ };
117
+ const logX = x < .5 ? Math.log(x) : Math.log1p(-y);
118
+ const logY = y < .5 ? Math.log(y) : Math.log1p(-x);
119
+ const front = Math.exp(a * logX + b * logY - logBeta(a, b));
120
+ if (x < (a + 1) / (a + b + 2)) {
121
+ const below = front * betaFraction(a, b, x) / a;
122
+ return {
123
+ below,
124
+ above: 1 - below
125
+ };
126
+ }
127
+ const above = front * betaFraction(b, a, y) / b;
128
+ return {
129
+ below: 1 - above,
130
+ above
131
+ };
132
+ }
133
+ /** This function gives the regularized incomplete beta function: the beta cumulative distribution at `x` (`betaShares` with `1 - x`). */
56
134
  function betaCdf(x, a, b) {
57
135
  if (Number.isNaN(x)) return NaN;
58
136
  if (x <= 0) return 0;
59
137
  if (x >= 1) return 1;
60
- const front = Math.exp(logGamma(a + b) - logGamma(a) - logGamma(b) + a * Math.log(x) + b * Math.log1p(-x));
61
- if (x < (a + 1) / (a + b + 2)) return front * betaFraction(a, b, x) / a;
62
- return 1 - front * betaFraction(b, a, 1 - x) / b;
138
+ return betaShares(x, 1 - x, a, b).below;
63
139
  }
64
140
  /**
65
141
  * This function gives the smallest `x` from `lo` to `hi` whose `cdf` is `u` or more, by bisection.
@@ -216,6 +292,6 @@ function distributionOf(spec, r) {
216
292
  }
217
293
  }
218
294
  }
219
- export { betaCdf, distributionOf, logGamma };
295
+ export { betaCdf, betaShares, distributionOf, logBeta, logGamma };
220
296
 
221
297
  //# sourceMappingURL=quantiles.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"quantiles.js","names":[],"sources":["../src/quantiles.ts"],"sourcesContent":["// The cumulative distribution and the quantile of each family of `distributions.ts`. A design draws a uniform number u\n// in each stratum and gives the quantile of u. So the Latin hypercube and the stratified designs work with each family.\nimport type { DistributionSpec, Param } from \"./distributions.ts\";\nimport { normalCdf, normalQuantile } from \"./normal.ts\";\nimport type { Random } from \"./random.ts\";\n\n/** One point of a family: its parameters are fixed. */\nexport interface Distribution {\n /** The family of the point. */\n readonly family: DistributionSpec[\"family\"];\n /** True when the values are a finite set, as in `zipf` and `recorded`. */\n readonly discrete: boolean;\n /** This function gives the probability of a value at or below `x`. */\n cdf(x: number): number;\n /** This function gives the smallest value whose `cdf` is `u` or more. `u` is from 0 to 1. */\n quantile(u: number): number;\n}\n\nconst LANCZOS = [\n 0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012,\n 9.9843695780195716e-6, 1.5056327351493116e-7,\n];\n\n/**\n * This function gives the logarithm of the gamma function for `x` above 0 (Lanczos, g 7, 9 terms).\n * The relative error is below 1e-14, away from the zeros at 1 and 2. Below 0.5, the reflection formula gives the value.\n */\nexport function logGamma(x: number): number {\n if (x < 0.5) return Math.log(Math.PI / Math.sin(Math.PI * x)) - logGamma(1 - x);\n const y = x - 1;\n let sum = LANCZOS[0]!;\n for (let i = 1; i < 9; i++) sum += LANCZOS[i]! / (y + i);\n const t = y + 7.5;\n return 0.5 * Math.log(2 * Math.PI) + (y + 0.5) * Math.log(t) - t + Math.log(sum);\n}\n\n/** This function gives the continued fraction of the incomplete beta function (the method of Lentz). */\nfunction betaFraction(a: number, b: number, x: number): number {\n const tiny = 1e-300;\n let c = 1;\n let d = 1 - ((a + b) * x) / (a + 1);\n if (Math.abs(d) < tiny) d = tiny;\n d = 1 / d;\n let h = d;\n for (let m = 1; m <= 1000; m++) {\n const m2 = 2 * m;\n let aa = (m * (b - m) * x) / ((a + m2 - 1) * (a + m2));\n d = 1 + aa * d;\n if (Math.abs(d) < tiny) d = tiny;\n c = 1 + aa / c;\n if (Math.abs(c) < tiny) c = tiny;\n d = 1 / d;\n h *= d * c;\n aa = (-(a + m) * (a + b + m) * x) / ((a + m2) * (a + m2 + 1));\n d = 1 + aa * d;\n if (Math.abs(d) < tiny) d = tiny;\n c = 1 + aa / c;\n if (Math.abs(c) < tiny) c = tiny;\n d = 1 / d;\n const step = d * c;\n h *= step;\n if (Math.abs(step - 1) < 1e-16) break;\n }\n return h;\n}\n\n/** This function gives the regularized incomplete beta function: the beta cumulative distribution at `x`. */\nexport function betaCdf(x: number, a: number, b: number): number {\n if (Number.isNaN(x)) return Number.NaN;\n if (x <= 0) return 0;\n if (x >= 1) return 1;\n const front = Math.exp(logGamma(a + b) - logGamma(a) - logGamma(b) + a * Math.log(x) + b * Math.log1p(-x));\n if (x < (a + 1) / (a + b + 2)) return (front * betaFraction(a, b, x)) / a;\n return 1 - (front * betaFraction(b, a, 1 - x)) / b;\n}\n\n/**\n * This function gives the smallest `x` from `lo` to `hi` whose `cdf` is `u` or more, by bisection.\n * The caller makes sure that `cdf(lo)` is `u` or less and `cdf(hi)` is `u` or more.\n */\nfunction bisect(cdf: (x: number) => number, u: number, lo: number, hi: number): number {\n for (let i = 0; i < 2000 && lo < hi; i++) {\n const mid = lo + (hi - lo) / 2;\n if (mid <= lo || mid >= hi) break;\n if (cdf(mid) >= u) hi = mid;\n else lo = mid;\n }\n return cdf(lo) >= u ? lo : hi;\n}\n\n/** This function examines a parameter, as `sampler` does. Both ends of a range must pass `valid`. */\nfunction checked(family: string, name: string, param: Param, valid: (value: number) => boolean, rule: string): void {\n const ends = typeof param === \"number\" ? [param] : param;\n for (const value of ends) {\n if (!Number.isFinite(value) || !valid(value)) throw new RangeError(`${family}: ${name} is ${value}, and it must be ${rule}.`);\n }\n if (typeof param !== \"number\" && param[0] > param[1]) throw new RangeError(`${family}: the range of ${name} starts above its end.`);\n}\n\n/** This function gives the value of a parameter: the number, or one draw from the range. */\nfunction valueOf(param: Param, r: Random): number {\n return typeof param === \"number\" ? param : r.range(param[0], param[1]);\n}\n\n/** This function examines `u` of a quantile. */\nfunction unit(u: number): void {\n if (!(u >= 0 && u <= 1)) throw new RangeError(`quantile: u is ${u}, and it must be from 0 to 1.`);\n}\n\n/**\n * This function gives one point of a family, with its `cdf` and its `quantile`. It draws the parameters from `r` in\n * the order of `sampler`. Thus the same seed gives the same point of the family as `sampler`.\n * The values use `Math.exp`, `Math.log` or `Math.pow` when `dependsOnLibm` of the family is true.\n */\nexport function distributionOf(spec: DistributionSpec, r: Random): Distribution {\n switch (spec.family) {\n case \"lognormal\": {\n checked(\"lognormal\", \"sigma\", spec.sigma, (v) => v >= 0, \"0 or more\");\n checked(\"lognormal\", \"mu\", spec.mu, () => true, \"finite\");\n const mu = valueOf(spec.mu, r);\n const sigma = valueOf(spec.sigma, r);\n const median = Math.exp(mu);\n return {\n family: \"lognormal\",\n discrete: false,\n cdf: (x) => (Number.isNaN(x) ? Number.NaN : x <= 0 ? 0 : sigma === 0 ? (x >= median ? 1 : 0) : normalCdf((Math.log(x) - mu) / sigma)),\n quantile: (u) => {\n unit(u);\n return sigma === 0 ? median : Math.exp(mu + sigma * normalQuantile(u));\n },\n };\n }\n case \"pareto\": {\n checked(\"pareto\", \"scale\", spec.scale, (v) => v > 0, \"above 0\");\n checked(\"pareto\", \"shape\", spec.shape, (v) => v > 0, \"above 0\");\n const scale = valueOf(spec.scale, r);\n const shape = valueOf(spec.shape, r);\n return {\n family: \"pareto\",\n discrete: false,\n cdf: (x) => (x < scale ? 0 : 1 - Math.pow(scale / x, shape)),\n quantile: (u) => {\n unit(u);\n return scale / Math.pow(1 - u, 1 / shape);\n },\n };\n }\n case \"zipf\": {\n if (!Number.isSafeInteger(spec.n) || spec.n < 1) throw new RangeError(`zipf: n is ${spec.n}, and it must be a whole number of 1 or more.`);\n checked(\"zipf\", \"exponent\", spec.exponent, (v) => v >= 0, \"0 or more\");\n const exponent = valueOf(spec.exponent, r);\n const totals: number[] = [];\n let total = 0;\n for (let rank = 1; rank <= spec.n; rank++) {\n total += Math.pow(rank, -exponent);\n totals.push(total);\n }\n return {\n family: \"zipf\",\n discrete: true,\n cdf: (x) => (x < 1 ? 0 : x >= spec.n ? 1 : totals[Math.floor(x) - 1]! / total),\n quantile: (u) => {\n unit(u);\n const at = u * total;\n let lo = 0;\n let hi = spec.n - 1;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (totals[mid]! >= at) hi = mid;\n else lo = mid + 1;\n }\n return lo + 1;\n },\n };\n }\n case \"beta\": {\n checked(\"beta\", \"a\", spec.a, (v) => v > 0, \"above 0\");\n checked(\"beta\", \"b\", spec.b, (v) => v > 0, \"above 0\");\n const a = valueOf(spec.a, r);\n const b = valueOf(spec.b, r);\n const cdf = (x: number): number => betaCdf(x, a, b);\n return {\n family: \"beta\",\n discrete: false,\n cdf,\n quantile: (u) => {\n unit(u);\n return u === 0 ? 0 : u === 1 ? 1 : bisect(cdf, u, 0, 1);\n },\n };\n }\n case \"mixture\": {\n if (spec.parts.length === 0) throw new RangeError(\"mixture: the list of the parts is empty.\");\n for (const { weight } of spec.parts) checked(\"mixture\", \"weight\", weight, (v) => v > 0, \"above 0\");\n const parts = spec.parts.map(({ part }) => distributionOf(part, r));\n const sum = spec.parts.reduce((s, { weight }) => s + weight, 0);\n const weights = spec.parts.map(({ weight }) => weight / sum);\n const cdf = (x: number): number => Math.min(1, parts.reduce((s, part, i) => s + weights[i]! * part.cdf(x), 0));\n return {\n family: \"mixture\",\n discrete: parts.every((part) => part.discrete),\n cdf,\n quantile: (u) => {\n unit(u);\n const ends = parts.map((part) => part.quantile(u));\n const lo = Math.min(...ends);\n const hi = Math.max(...ends);\n return lo === hi || !Number.isFinite(hi) ? hi : bisect(cdf, u, lo, hi);\n },\n };\n }\n case \"recorded\": {\n if (spec.values.length === 0) throw new RangeError(\"recorded: the list of the values is empty.\");\n for (const value of spec.values) checked(\"recorded\", \"value\", value, () => true, \"finite\");\n const sorted = [...spec.values].sort((x, y) => x - y);\n const n = sorted.length;\n return {\n family: \"recorded\",\n discrete: true,\n cdf: (x) => {\n let lo = 0;\n let hi = n;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (sorted[mid]! <= x) lo = mid + 1;\n else hi = mid;\n }\n return lo / n;\n },\n quantile: (u) => {\n unit(u);\n return sorted[Math.max(0, Math.ceil(u * n) - 1)]!;\n },\n };\n }\n }\n}\n"],"mappings":";;AAkBA,MAAM,UAAU;CACd;CAAqB;CAAmB;CAAqB;CAAoB;CAAqB;CAAoB;CAC1H;CAAuB;AACzB;;;;;AAMA,SAAgB,SAAS,GAAmB;CAC1C,IAAI,IAAI,IAAK,OAAO,KAAK,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,CAAC,CAAC,IAAI,SAAS,IAAI,CAAC;CAC9E,MAAM,IAAI,IAAI;CACd,IAAI,MAAM,QAAQ;CAClB,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK,OAAO,QAAQ,MAAO,IAAI;CACtD,MAAM,IAAI,IAAI;CACd,OAAO,KAAM,KAAK,IAAI,IAAI,KAAK,EAAE,KAAK,IAAI,MAAO,KAAK,IAAI,CAAC,IAAI,IAAI,KAAK,IAAI,GAAG;AACjF;;AAGA,SAAS,aAAa,GAAW,GAAW,GAAmB;CAC7D,MAAM,OAAO;CACb,IAAI,IAAI;CACR,IAAI,IAAI,KAAM,IAAI,KAAK,KAAM,IAAI;CACjC,IAAI,KAAK,IAAI,CAAC,IAA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IACR,UAAU,MAAM,OAAO,SAAS,KAAK,QAAQ;IAC7C;IACA,WAAW,MAAM;KACf,KAAK,CAAC;KACN,MAAM,OAAO,MAAM,KAAK,SAAS,KAAK,SAAS,CAAC,CAAC;KACjD,MAAM,KAAK,KAAK,IAAI,GAAG,IAAI;KAC3B,MAAM,KAAK,KAAK,IAAI,GAAG,IAAI;KAC3B,OAAO,OAAO,MAAM,CAAC,OAAO,SAAS,EAAE,IAAI,KAAK,OAAO,KAAK,GAAG,IAAI,EAAE;IACvE;GACF;EACF;EACA,KAAK,YAAY;GACf,IAAI,KAAK,OAAO,WAAW,GAAG,MAAM,IAAI,WAAW,4CAA4C;GAC/F,KAAK,MAAM,SAAS,KAAK,QAAQ,QAAQ,YAAY,SAAS,aAAa,MAAM,QAAQ;GACzF,MAAM,SAAS,CAAC,GAAG,KAAK,MAAM,CAAC,CAAC,MAAM,GAAG,MAAM,IAAI,CAAC;GACpD,MAAM,IAAI,OAAO;GACjB,OAAO;IACL,QAAQ;IACR,UAAU;IACV,MAAM,MAAM;KACV,IAAI,KAAK;KACT,IAAI,KAAK;KACT,OAAO,KAAK,IAAI;MACd,MAAM,MAAO,KAAK,OAAQ;MAC1B,IAAI,OAAO,QAAS,GAAG,KAAK,MAAM;WAC7B,KAAK;KACZ;KACA,OAAO,KAAK;IACd;IACA,WAAW,MAAM;KACf,KAAK,CAAC;KACN,OAAO,OAAO,KAAK,IAAI,GAAG,KAAK,KAAK,IAAI,CAAC,IAAI,CAAC;IAChD;GACF;EACF;CACF;AACF"}
1
+ {"version":3,"file":"quantiles.js","names":[],"sources":["../src/quantiles.ts"],"sourcesContent":["// The cumulative distribution and the quantile of each family of `distributions.ts`. A design draws a uniform number u\n// in each stratum and gives the quantile of u. So the Latin hypercube and the stratified designs work with each family.\nimport type { DistributionSpec, Param } from \"./distributions.ts\";\nimport { normalCdf, normalQuantile } from \"./normal.ts\";\nimport type { Random } from \"./random.ts\";\n\n/** One point of a family: its parameters are fixed. */\nexport interface Distribution {\n /** The family of the point. */\n readonly family: DistributionSpec[\"family\"];\n /** True when the values are a finite set, as in `zipf` and `recorded`. */\n readonly discrete: boolean;\n /** This function gives the probability of a value at or below `x`. */\n cdf(x: number): number;\n /** This function gives the smallest value whose `cdf` is `u` or more. `u` is from 0 to 1. */\n quantile(u: number): number;\n}\n\nconst LANCZOS = [\n 0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012,\n 9.9843695780195716e-6, 1.5056327351493116e-7,\n];\n\n/**\n * This function gives the logarithm of the gamma function for `x` above 0 (Lanczos, g 7, 9 terms).\n * The relative error is below 1e-14, away from the zeros at 1 and 2. Below 0.5, the reflection formula gives the value.\n */\nexport function logGamma(x: number): number {\n if (x < 0.5) return Math.log(Math.PI / Math.sin(Math.PI * x)) - logGamma(1 - x);\n const y = x - 1;\n let sum = LANCZOS[0]!;\n for (let i = 1; i < 9; i++) sum += LANCZOS[i]! / (y + i);\n const t = y + 7.5;\n return 0.5 * Math.log(2 * Math.PI) + (y + 0.5) * Math.log(t) - t + Math.log(sum);\n}\n\n/** The coefficients of the Stirling series of the log of the gamma function: B(2k) / (2k (2k - 1)) for k from 1 to 8. */\nconst STIRLING = [1 / 12, -1 / 360, 1 / 1260, -1 / 1680, 1 / 1188, -691 / 360360, 1 / 156, -3617 / 122400];\n\n/**\n * This function gives the Stirling correction: `logGamma(x)` less `(x - 0.5) log x - x + log(2 pi) / 2`, for `x` of 10 or more.\n * At 10, the first term that the series omits is below 2e-18.\n */\nfunction stirlingCorrection(x: number): number {\n const square = 1 / (x * x);\n let sum = 0;\n for (let i = STIRLING.length - 1; i >= 0; i--) sum = sum * square + STIRLING[i]!;\n return sum / x;\n}\n\n/**\n * This function gives the logarithm of the beta function, `logGamma(a) + logGamma(b) - logGamma(a + b)`, for `a` and `b` above 0.\n * - When an argument is 10 or more, the Stirling series gives the difference of the large terms (as `lbeta` of R).\n * Thus the value is accurate also when `a + b` is near 1e13. There, the sum of `logGamma` loses all digits of the difference.\n * - When both arguments are below 10, the value is the sum of `logGamma`.\n */\nexport function logBeta(a: number, b: number): number {\n const p = Math.min(a, b);\n const q = Math.max(a, b);\n const share = p / (p + q);\n if (p >= 10) {\n const correction = stirlingCorrection(p) + stirlingCorrection(q) - stirlingCorrection(p + q);\n return -0.5 * Math.log(q) + 0.5 * Math.log(2 * Math.PI) + correction + (p - 0.5) * Math.log(share) + q * Math.log1p(-share);\n }\n if (q >= 10) {\n const correction = stirlingCorrection(q) - stirlingCorrection(p + q);\n return logGamma(p) + correction + p - p * Math.log(p + q) + (q - 0.5) * Math.log1p(-share);\n }\n return logGamma(p) + logGamma(q) - logGamma(p + q);\n}\n\n/** This function gives the continued fraction of the incomplete beta function (the method of Lentz). */\nfunction betaFraction(a: number, b: number, x: number): number {\n const tiny = 1e-300;\n let c = 1;\n let d = 1 - ((a + b) * x) / (a + 1);\n if (Math.abs(d) < tiny) d = tiny;\n d = 1 / d;\n let h = d;\n for (let m = 1; m <= 1000; m++) {\n const m2 = 2 * m;\n let aa = (m * (b - m) * x) / ((a + m2 - 1) * (a + m2));\n d = 1 + aa * d;\n if (Math.abs(d) < tiny) d = tiny;\n c = 1 + aa / c;\n if (Math.abs(c) < tiny) c = tiny;\n d = 1 / d;\n h *= d * c;\n aa = (-(a + m) * (a + b + m) * x) / ((a + m2) * (a + m2 + 1));\n d = 1 + aa * d;\n if (Math.abs(d) < tiny) d = tiny;\n c = 1 + aa / c;\n if (Math.abs(c) < tiny) c = tiny;\n d = 1 / d;\n const step = d * c;\n h *= step;\n if (Math.abs(step - 1) < 1e-16) break;\n }\n return h;\n}\n\n/** The shares of a beta law below and above a point. */\nexport interface BetaShares {\n /** The share of the law below the point: the regularized incomplete beta function. */\n readonly below: number;\n /** The share of the law above the point. */\n readonly above: number;\n}\n\n/**\n * This function gives the shares of the beta law with the parameters `a` and `b` below and above `x`.\n * - The caller gives `x` and `y = 1 - x`, each with its full digits. Thus a point near 1 keeps the digits of its distance from 1.\n * For example, `df / (df + t^2)` and `t^2 / (df + t^2)` give both shares of the Student t law with no rounding near 1.\n * - The continued fraction gives the smaller share with its relative digits. The other share is 1 less that share.\n * - The fraction loses digits when its point is near 1 and its first parameter is large. This is the share above `x` when `x` is above `(a + 1) / (a + b + 2)`.\n * The tests hold the relative error of that share below `2e-16 * b`, for `b` from 5e5 to 5e8.\n * - The logs of the front factor use the smaller of `x` and `y`, and the factor uses `logBeta`. Thus a parameter near 1e13 keeps the digits of the shares.\n *\n * @throws RangeError when `x` or `y` is not from 0 to 1, or when `x + y` is not 1\n */\nexport function betaShares(x: number, y: number, a: number, b: number): BetaShares {\n if (!(x >= 0 && x <= 1 && y >= 0 && y <= 1 && Math.abs(x + y - 1) <= 1e-12)) {\n throw new RangeError(`betaShares: x and y are from 0 to 1 and their sum is 1, not ${x} and ${y}.`);\n }\n if (x === 0) return { below: 0, above: 1 };\n if (y === 0) return { below: 1, above: 0 };\n const logX = x < 0.5 ? Math.log(x) : Math.log1p(-y);\n const logY = y < 0.5 ? Math.log(y) : Math.log1p(-x);\n const front = Math.exp(a * logX + b * logY - logBeta(a, b));\n if (x < (a + 1) / (a + b + 2)) {\n const below = (front * betaFraction(a, b, x)) / a;\n return { below, above: 1 - below };\n }\n const above = (front * betaFraction(b, a, y)) / b;\n return { below: 1 - above, above };\n}\n\n/** This function gives the regularized incomplete beta function: the beta cumulative distribution at `x` (`betaShares` with `1 - x`). */\nexport function betaCdf(x: number, a: number, b: number): number {\n if (Number.isNaN(x)) return Number.NaN;\n if (x <= 0) return 0;\n if (x >= 1) return 1;\n return betaShares(x, 1 - x, a, b).below;\n}\n\n/**\n * This function gives the smallest `x` from `lo` to `hi` whose `cdf` is `u` or more, by bisection.\n * The caller makes sure that `cdf(lo)` is `u` or less and `cdf(hi)` is `u` or more.\n */\nfunction bisect(cdf: (x: number) => number, u: number, lo: number, hi: number): number {\n for (let i = 0; i < 2000 && lo < hi; i++) {\n const mid = lo + (hi - lo) / 2;\n if (mid <= lo || mid >= hi) break;\n if (cdf(mid) >= u) hi = mid;\n else lo = mid;\n }\n return cdf(lo) >= u ? lo : hi;\n}\n\n/** This function examines a parameter, as `sampler` does. Both ends of a range must pass `valid`. */\nfunction checked(family: string, name: string, param: Param, valid: (value: number) => boolean, rule: string): void {\n const ends = typeof param === \"number\" ? [param] : param;\n for (const value of ends) {\n if (!Number.isFinite(value) || !valid(value)) throw new RangeError(`${family}: ${name} is ${value}, and it must be ${rule}.`);\n }\n if (typeof param !== \"number\" && param[0] > param[1]) throw new RangeError(`${family}: the range of ${name} starts above its end.`);\n}\n\n/** This function gives the value of a parameter: the number, or one draw from the range. */\nfunction valueOf(param: Param, r: Random): number {\n return typeof param === \"number\" ? param : r.range(param[0], param[1]);\n}\n\n/** This function examines `u` of a quantile. */\nfunction unit(u: number): void {\n if (!(u >= 0 && u <= 1)) throw new RangeError(`quantile: u is ${u}, and it must be from 0 to 1.`);\n}\n\n/**\n * This function gives one point of a family, with its `cdf` and its `quantile`. It draws the parameters from `r` in\n * the order of `sampler`. Thus the same seed gives the same point of the family as `sampler`.\n * The values use `Math.exp`, `Math.log` or `Math.pow` when `dependsOnLibm` of the family is true.\n */\nexport function distributionOf(spec: DistributionSpec, r: Random): Distribution {\n switch (spec.family) {\n case \"lognormal\": {\n checked(\"lognormal\", \"sigma\", spec.sigma, (v) => v >= 0, \"0 or more\");\n checked(\"lognormal\", \"mu\", spec.mu, () => true, \"finite\");\n const mu = valueOf(spec.mu, r);\n const sigma = valueOf(spec.sigma, r);\n const median = Math.exp(mu);\n return {\n family: \"lognormal\",\n discrete: false,\n cdf: (x) => (Number.isNaN(x) ? Number.NaN : x <= 0 ? 0 : sigma === 0 ? (x >= median ? 1 : 0) : normalCdf((Math.log(x) - mu) / sigma)),\n quantile: (u) => {\n unit(u);\n return sigma === 0 ? median : Math.exp(mu + sigma * normalQuantile(u));\n },\n };\n }\n case \"pareto\": {\n checked(\"pareto\", \"scale\", spec.scale, (v) => v > 0, \"above 0\");\n checked(\"pareto\", \"shape\", spec.shape, (v) => v > 0, \"above 0\");\n const scale = valueOf(spec.scale, r);\n const shape = valueOf(spec.shape, r);\n return {\n family: \"pareto\",\n discrete: false,\n cdf: (x) => (x < scale ? 0 : 1 - Math.pow(scale / x, shape)),\n quantile: (u) => {\n unit(u);\n return scale / Math.pow(1 - u, 1 / shape);\n },\n };\n }\n case \"zipf\": {\n if (!Number.isSafeInteger(spec.n) || spec.n < 1) throw new RangeError(`zipf: n is ${spec.n}, and it must be a whole number of 1 or more.`);\n checked(\"zipf\", \"exponent\", spec.exponent, (v) => v >= 0, \"0 or more\");\n const exponent = valueOf(spec.exponent, r);\n const totals: number[] = [];\n let total = 0;\n for (let rank = 1; rank <= spec.n; rank++) {\n total += Math.pow(rank, -exponent);\n totals.push(total);\n }\n return {\n family: \"zipf\",\n discrete: true,\n cdf: (x) => (x < 1 ? 0 : x >= spec.n ? 1 : totals[Math.floor(x) - 1]! / total),\n quantile: (u) => {\n unit(u);\n const at = u * total;\n let lo = 0;\n let hi = spec.n - 1;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (totals[mid]! >= at) hi = mid;\n else lo = mid + 1;\n }\n return lo + 1;\n },\n };\n }\n case \"beta\": {\n checked(\"beta\", \"a\", spec.a, (v) => v > 0, \"above 0\");\n checked(\"beta\", \"b\", spec.b, (v) => v > 0, \"above 0\");\n const a = valueOf(spec.a, r);\n const b = valueOf(spec.b, r);\n const cdf = (x: number): number => betaCdf(x, a, b);\n return {\n family: \"beta\",\n discrete: false,\n cdf,\n quantile: (u) => {\n unit(u);\n return u === 0 ? 0 : u === 1 ? 1 : bisect(cdf, u, 0, 1);\n },\n };\n }\n case \"mixture\": {\n if (spec.parts.length === 0) throw new RangeError(\"mixture: the list of the parts is empty.\");\n for (const { weight } of spec.parts) checked(\"mixture\", \"weight\", weight, (v) => v > 0, \"above 0\");\n const parts = spec.parts.map(({ part }) => distributionOf(part, r));\n const sum = spec.parts.reduce((s, { weight }) => s + weight, 0);\n const weights = spec.parts.map(({ weight }) => weight / sum);\n const cdf = (x: number): number => Math.min(1, parts.reduce((s, part, i) => s + weights[i]! * part.cdf(x), 0));\n return {\n family: \"mixture\",\n discrete: parts.every((part) => part.discrete),\n cdf,\n quantile: (u) => {\n unit(u);\n const ends = parts.map((part) => part.quantile(u));\n const lo = Math.min(...ends);\n const hi = Math.max(...ends);\n return lo === hi || !Number.isFinite(hi) ? hi : bisect(cdf, u, lo, hi);\n },\n };\n }\n case \"recorded\": {\n if (spec.values.length === 0) throw new RangeError(\"recorded: the list of the values is empty.\");\n for (const value of spec.values) checked(\"recorded\", \"value\", value, () => true, \"finite\");\n const sorted = [...spec.values].sort((x, y) => x - y);\n const n = sorted.length;\n return {\n family: \"recorded\",\n discrete: true,\n cdf: (x) => {\n let lo = 0;\n let hi = n;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (sorted[mid]! <= x) lo = mid + 1;\n else hi = mid;\n }\n return lo / n;\n },\n quantile: (u) => {\n unit(u);\n return sorted[Math.max(0, Math.ceil(u * n) - 1)]!;\n },\n };\n }\n }\n}\n"],"mappings":";;AAkBA,MAAM,UAAU;CACd;CAAqB;CAAmB;CAAqB;CAAoB;CAAqB;CAAoB;CAC1H;CAAuB;AACzB;;;;;AAMA,SAAgB,SAAS,GAAmB;CAC1C,IAAI,IAAI,IAAK,OAAO,KAAK,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,CAAC,CAAC,IAAI,SAAS,IAAI,CAAC;CAC9E,MAAM,IAAI,IAAI;CACd,IAAI,MAAM,QAAQ;CAClB,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK,OAAO,QAAQ,MAAO,IAAI;CACtD,MAAM,IAAI,IAAI;CACd,OAAO,KAAM,KAAK,IAAI,IAAI,KAAK,EAAE,KAAK,IAAI,MAAO,KAAK,IAAI,CAAC,IAAI,IAAI,KAAK,IAAI,GAAG;AACjF;;AAGA,MAAM,WAAW;CAA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1B,IAAI,OAAO,QAAS,GAAG,KAAK,MAAM;WAC7B,KAAK;KACZ;KACA,OAAO,KAAK;IACd;IACA,WAAW,MAAM;KACf,KAAK,CAAC;KACN,OAAO,OAAO,KAAK,IAAI,GAAG,KAAK,KAAK,IAAI,CAAC,IAAI,CAAC;IAChD;GACF;EACF;CACF;AACF"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/rigor-generators",
4
- "version": "0.2.4",
4
+ "version": "0.2.5",
5
5
  "description": "A seeded random number generator (mulberry32) with the draws that tests and benchmarks make: integers, picks, weights, shuffles, samples, normal values and named streams. It also gives covering arrays (pairwise and of strength t), and a content hash: SHA-256 and canonical JSON (RFC 8785).",
6
6
  "keywords": [
7
7
  "random",