@mark1russell7/rigor-generators 0.1.8 → 0.1.11

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
@@ -92,6 +92,43 @@ Each table is a sample, and it does not show a general law:
92
92
 
93
93
  The npm package holds the notice of the Ptolemy II license, because the field `notice` is part of the build.
94
94
 
95
+ ## Input families and designs
96
+
97
+ An input family has named dimensions. Each dimension has a range from `min` to `max`. It can also have one of these:
98
+
99
+ - a `distribution`, cut to the range,
100
+ - the `scale` `log`, so the logarithm of the value is uniform,
101
+ - `integer: true`, so each value is an integer from `min` to `max`.
102
+
103
+ A design gives points of the unit cube. `familyMap` takes coordinate `i` of a point to a value of dimension `i`.
104
+
105
+ | Design | Points | Property |
106
+ | --- | --- | --- |
107
+ | `randomDesign(n, d, r)` | `n` | independent uniform points |
108
+ | `latinHypercube(n, d, r)` | `n` | each column has one point in each of the `n` strata |
109
+ | `stratifiedDesign(strata, d, r)` | `strata^d` | one point in each cell of the grid |
110
+ | `saltelliDesign(n, d, r)` | `n * (d + 2)` | the matrices `a`, `b` and `ab[i]` of the Sobol indices |
111
+
112
+ ```ts
113
+ import { familyPoints, latinHypercube, random } from "@mark1russell7/rigor-generators";
114
+
115
+ const family = {
116
+ name: "boxes",
117
+ dimensions: [
118
+ { name: "count", min: 1, max: 6, integer: true },
119
+ { name: "width", min: 10, max: 1000, scale: "log" },
120
+ { name: "area", min: 1, max: 50, distribution: { family: "lognormal", mu: 2, sigma: 1 } },
121
+ ],
122
+ } as const;
123
+ const points = familyPoints(family, latinHypercube(200, 3, random("design")), random("family"));
124
+ ```
125
+
126
+ A distribution of a dimension uses its `cdf` and its `quantile`, from `distributionOf`. The value of a coordinate `u` is the quantile of `u` in the probability of the range. Thus a Latin hypercube also gives one value in each stratum of the probability.
127
+
128
+ The parameters of a dimension come from `r.fork("dimension:" + name)`. The same seed gives the same points, and a new dimension does not change the values of the others.
129
+
130
+ For the mean of a sum of 3 inputs from 50 points, the Latin hypercube gives 0.00042 of the variance of the random design. A test holds the ratio below 1/1000.
131
+
95
132
  ## The input of `fnv1a32`
96
133
 
97
134
  The option `input` of `fnv1a32` selects the units that the hash reads. Use it to replace a local copy of FNV-1a with the same hashes.
@@ -0,0 +1,58 @@
1
+ import { Random } from "./random.js";
2
+ import { DistributionSpec } from "./distributions.js";
3
+ /** One dimension of an input family. */
4
+ export interface Dimension {
5
+ /** The name of the dimension. It is a key of each point. */
6
+ readonly name: string;
7
+ /** The smallest value. */
8
+ readonly min: number;
9
+ /** The largest value. A uniform or log dimension that is not `integer` gets values below `max`. */
10
+ readonly max: number;
11
+ /** The distribution of the values, cut to the range. Without it, the values are uniform in the range. */
12
+ readonly distribution?: DistributionSpec;
13
+ /** With `log`, the logarithm of the value is uniform. `min` must be above 0. A dimension with a distribution has no scale. */
14
+ readonly scale?: "linear" | "log";
15
+ /** With `true`, each value is an integer. `min` and `max` must be integers. */
16
+ readonly integer?: boolean;
17
+ }
18
+ /** An input family: its name and its dimensions. */
19
+ export interface InputFamily {
20
+ readonly name: string;
21
+ readonly dimensions: readonly Dimension[];
22
+ }
23
+ /** One point of a family: one value for each dimension, by name. */
24
+ export type Point = Readonly<Record<string, number>>;
25
+ /** The Saltelli design: the matrices `a` and `b`, and for each dimension `i` the matrix `ab[i]`. */
26
+ export interface SaltelliDesign {
27
+ readonly a: number[][];
28
+ readonly b: number[][];
29
+ /** `ab[i]` is `a` with the column `i` of `b`. */
30
+ readonly ab: number[][][];
31
+ }
32
+ /**
33
+ * This function gives the map from a point of the unit cube to a point of the family. Coordinate `i` gives the value of
34
+ * dimension `i`. The parameters of each distribution come from `r.fork("dimension:" + name)` one time. Thus the
35
+ * same seed gives the same map, and a new dimension does not change the others.
36
+ */
37
+ export declare function familyMap(family: InputFamily, r: Random): (unit: readonly number[]) => Point;
38
+ /** This function gives the points of the family at the points of a unit design. */
39
+ export declare function familyPoints(family: InputFamily, unit: readonly (readonly number[])[], r: Random): Point[];
40
+ /** This function gives `n` independent uniform points of the unit cube in `d` dimensions. The draws go row by row. */
41
+ export declare function randomDesign(n: number, d: number, r: Random): number[][];
42
+ /**
43
+ * This function gives a Latin hypercube of `n` points in `d` dimensions. Each column has exactly one point in each of
44
+ * the `n` strata `[k/n, (k+1)/n)`. For each column, the draws are one shuffle of the strata, then one draw in each point.
45
+ */
46
+ export declare function latinHypercube(n: number, d: number, r: Random): number[][];
47
+ /**
48
+ * This function gives a stratified grid: `strata` strata on each axis, so `strata^d` cells, and one uniform point in
49
+ * each cell. The cells go in the order of their index in base `strata`, with the first dimension as the last digit.
50
+ */
51
+ export declare function stratifiedDesign(strata: number, d: number, r: Random, limit?: number): number[][];
52
+ /**
53
+ * This function gives the Saltelli design for the Sobol indices of a model with `d` inputs: `a`, `b` and the `d`
54
+ * matrices `ab`. The design has `n * (d + 2)` points for the model. `a` comes from `r.fork("A")`, and `b` comes
55
+ * from `r.fork("B")`. With `base` `"latin"`, each is a Latin hypercube.
56
+ */
57
+ export declare function saltelliDesign(n: number, d: number, r: Random, base?: "random" | "latin"): SaltelliDesign;
58
+ //# sourceMappingURL=designs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"designs.d.ts","names":[],"sources":["../src/designs.ts"],"mappings":";;;iBAOiB;;WAEN;;WAEA;;WAEA;;WAEA,eAAe;;WAEf;;WAEA;;;iBAIM;WACN;WACA,qBAAqB;;;YAIpB,QAAQ,SAAS;;iBAGZ;WACN;WACA;;WAEA;;;;;;;wBAqEK,UAAU,QAAQ,aAAa,GAAG,UAAU,4BAA4B;;wBAmBxE,aAAa,QAAQ,aAAa,sCAAsC,GAAG,SAAS;;wBAMpF,aAAa,WAAW,WAAW,GAAG;;;;;wBAUtC,eAAe,WAAW,WAAW,GAAG;;;;;wBAgBxC,iBAAiB,gBAAgB,WAAW,GAAG,QAAQ;;;;;;wBAoBvD,eAAe,WAAW,WAAW,GAAG,QAAQ,4BAAsC"}
@@ -0,0 +1,134 @@
1
+ import { distributionOf } from "./quantiles.js";
2
+ // src/designs.ts
3
+ const BELOW_ONE = 1 - Number.EPSILON / 2;
4
+ /** This function gives the next double toward minus infinity. */
5
+ function nextDown(x) {
6
+ if (x === 0) return -Number.MIN_VALUE;
7
+ const f = new Float64Array([x]);
8
+ const bits = new BigInt64Array(f.buffer);
9
+ bits[0] = x > 0 ? bits[0] - 1n : bits[0] + 1n;
10
+ return f[0];
11
+ }
12
+ /** This function gives the next double toward plus infinity. */
13
+ function nextUp(x) {
14
+ return -nextDown(-x);
15
+ }
16
+ /** This function keeps a value below 1. A sum of a stratum and a draw can round up to 1. */
17
+ function belowOne(x) {
18
+ return x < 1 ? x : BELOW_ONE;
19
+ }
20
+ function count(fn, name, value) {
21
+ if (!Number.isSafeInteger(value) || value < 1) throw new RangeError(`${fn}: ${name} is ${value}, and it must be an integer from 1.`);
22
+ }
23
+ /** This function examines a dimension and gives the map from a uniform number in [0, 1) to a value of the dimension. */
24
+ function dimensionMap(family, dim, r) {
25
+ const where = `${family}.${dim.name}`;
26
+ if (!Number.isFinite(dim.min) || !Number.isFinite(dim.max) || dim.min > dim.max) throw new RangeError(`${where}: the range ${dim.min} to ${dim.max} is not a finite range.`);
27
+ if (dim.integer === true && (!Number.isSafeInteger(dim.min) || !Number.isSafeInteger(dim.max))) throw new RangeError(`${where}: an integer dimension needs integer ends, not ${dim.min} and ${dim.max}.`);
28
+ const end = dim.integer === true ? dim.max + 1 : dim.max;
29
+ const top = dim.integer === true ? nextDown(end) : end;
30
+ const whole = (x) => dim.integer === true ? Math.min(dim.max, Math.floor(x)) : x;
31
+ const clamp = (x) => Math.min(top, Math.max(dim.min, x));
32
+ if (dim.distribution !== void 0) {
33
+ if (dim.scale !== void 0) throw new RangeError(`${where}: a dimension with a distribution has no scale.`);
34
+ const d = distributionOf(dim.distribution, r);
35
+ const low = d.cdf(nextDown(dim.min));
36
+ const high = d.cdf(top);
37
+ if (!(high > low)) throw new RangeError(`${where}: the distribution has no probability from ${dim.min} to ${dim.max}.`);
38
+ const first = d.quantile(nextUp(low));
39
+ return (u) => {
40
+ const x = d.quantile(low + u * (high - low));
41
+ return whole(clamp(x < dim.min ? first : x));
42
+ };
43
+ }
44
+ if (dim.scale === "log") {
45
+ if (!(dim.min > 0)) throw new RangeError(`${where}: a log scale needs a minimum above 0, not ${dim.min}.`);
46
+ const span = Math.log(end / dim.min);
47
+ return (u) => whole(clamp(dim.min * Math.exp(u * span)));
48
+ }
49
+ return (u) => whole(clamp(dim.min + u * (end - dim.min)));
50
+ }
51
+ /**
52
+ * This function gives the map from a point of the unit cube to a point of the family. Coordinate `i` gives the value of
53
+ * dimension `i`. The parameters of each distribution come from `r.fork("dimension:" + name)` one time. Thus the
54
+ * same seed gives the same map, and a new dimension does not change the others.
55
+ */
56
+ function familyMap(family, r) {
57
+ if (family.dimensions.length === 0) throw new RangeError(`${family.name}: a family needs one dimension or more.`);
58
+ const names = family.dimensions.map((d) => d.name);
59
+ const twice = names.find((n, i) => n === "" || names.indexOf(n) !== i);
60
+ if (twice !== void 0) throw new RangeError(`${family.name}: the dimension name "${twice}" is empty or not unique.`);
61
+ const maps = family.dimensions.map((d) => dimensionMap(family.name, d, r.fork(`dimension:${d.name}`)));
62
+ return (unit) => {
63
+ if (unit.length !== maps.length) throw new RangeError(`${family.name}: a point needs ${maps.length} coordinates, not ${unit.length}.`);
64
+ const point = {};
65
+ maps.forEach((map, i) => {
66
+ const u = unit[i];
67
+ if (!(u >= 0 && u < 1)) throw new RangeError(`${family.name}: coordinate ${i} is ${u}, and it must be from 0 to below 1.`);
68
+ point[names[i]] = map(u);
69
+ });
70
+ return point;
71
+ };
72
+ }
73
+ /** This function gives the points of the family at the points of a unit design. */
74
+ function familyPoints(family, unit, r) {
75
+ const map = familyMap(family, r);
76
+ return unit.map(map);
77
+ }
78
+ /** This function gives `n` independent uniform points of the unit cube in `d` dimensions. The draws go row by row. */
79
+ function randomDesign(n, d, r) {
80
+ count("randomDesign", "n", n);
81
+ count("randomDesign", "d", d);
82
+ return Array.from({ length: n }, () => Array.from({ length: d }, () => r.next()));
83
+ }
84
+ /**
85
+ * This function gives a Latin hypercube of `n` points in `d` dimensions. Each column has exactly one point in each of
86
+ * the `n` strata `[k/n, (k+1)/n)`. For each column, the draws are one shuffle of the strata, then one draw in each point.
87
+ */
88
+ function latinHypercube(n, d, r) {
89
+ count("latinHypercube", "n", n);
90
+ count("latinHypercube", "d", d);
91
+ const rows = Array.from({ length: n }, () => new Array(d));
92
+ const strata = Array.from({ length: n }, (_, k) => k);
93
+ for (let j = 0; j < d; j++) {
94
+ const order = r.shuffle(strata);
95
+ for (let i = 0; i < n; i++) rows[i][j] = belowOne((order[i] + r.next()) / n);
96
+ }
97
+ return rows;
98
+ }
99
+ /**
100
+ * This function gives a stratified grid: `strata` strata on each axis, so `strata^d` cells, and one uniform point in
101
+ * each cell. The cells go in the order of their index in base `strata`, with the first dimension as the last digit.
102
+ */
103
+ function stratifiedDesign(strata, d, r, limit = 1e6) {
104
+ count("stratifiedDesign", "strata", strata);
105
+ count("stratifiedDesign", "d", d);
106
+ const n = strata ** d;
107
+ if (n > limit) throw new RangeError(`stratifiedDesign: ${strata}^${d} = ${n} cells is above the limit ${limit}.`);
108
+ return Array.from({ length: n }, (_, cell) => {
109
+ let rest = cell;
110
+ return Array.from({ length: d }, () => {
111
+ const k = rest % strata;
112
+ rest = Math.floor(rest / strata);
113
+ return belowOne((k + r.next()) / strata);
114
+ });
115
+ });
116
+ }
117
+ /**
118
+ * This function gives the Saltelli design for the Sobol indices of a model with `d` inputs: `a`, `b` and the `d`
119
+ * matrices `ab`. The design has `n * (d + 2)` points for the model. `a` comes from `r.fork("A")`, and `b` comes
120
+ * from `r.fork("B")`. With `base` `"latin"`, each is a Latin hypercube.
121
+ */
122
+ function saltelliDesign(n, d, r, base = "random") {
123
+ const make = base === "latin" ? latinHypercube : randomDesign;
124
+ const a = make(n, d, r.fork("A"));
125
+ const b = make(n, d, r.fork("B"));
126
+ return {
127
+ a,
128
+ b,
129
+ ab: Array.from({ length: d }, (_, i) => a.map((row, k) => row.map((x, j) => j === i ? b[k][j] : x)))
130
+ };
131
+ }
132
+ export { familyMap, familyPoints, latinHypercube, randomDesign, saltelliDesign, stratifiedDesign };
133
+
134
+ //# sourceMappingURL=designs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"designs.js","names":[],"sources":["../src/designs.ts"],"sourcesContent":["// Input families and the designs that draw their points (R5). A design gives points of the unit cube. `familyMap`\n// takes each point to a point of the family: a value from the range of each dimension.\nimport type { DistributionSpec } from \"./distributions.ts\";\nimport { distributionOf } from \"./quantiles.ts\";\nimport type { Random } from \"./random.ts\";\n\n/** One dimension of an input family. */\nexport interface Dimension {\n /** The name of the dimension. It is a key of each point. */\n readonly name: string;\n /** The smallest value. */\n readonly min: number;\n /** The largest value. A uniform or log dimension that is not `integer` gets values below `max`. */\n readonly max: number;\n /** The distribution of the values, cut to the range. Without it, the values are uniform in the range. */\n readonly distribution?: DistributionSpec;\n /** With `log`, the logarithm of the value is uniform. `min` must be above 0. A dimension with a distribution has no scale. */\n readonly scale?: \"linear\" | \"log\";\n /** With `true`, each value is an integer. `min` and `max` must be integers. */\n readonly integer?: boolean;\n}\n\n/** An input family: its name and its dimensions. */\nexport interface InputFamily {\n readonly name: string;\n readonly dimensions: readonly Dimension[];\n}\n\n/** One point of a family: one value for each dimension, by name. */\nexport type Point = Readonly<Record<string, number>>;\n\n/** The Saltelli design: the matrices `a` and `b`, and for each dimension `i` the matrix `ab[i]`. */\nexport interface SaltelliDesign {\n readonly a: number[][];\n readonly b: number[][];\n /** `ab[i]` is `a` with the column `i` of `b`. */\n readonly ab: number[][][];\n}\n\nconst BELOW_ONE = 1 - Number.EPSILON / 2;\n\n/** This function gives the next double toward minus infinity. */\nfunction nextDown(x: number): number {\n if (x === 0) return -Number.MIN_VALUE;\n const f = new Float64Array([x]);\n const bits = new BigInt64Array(f.buffer);\n bits[0] = x > 0 ? bits[0]! - 1n : bits[0]! + 1n;\n return f[0]!;\n}\n\n/** This function gives the next double toward plus infinity. */\nfunction nextUp(x: number): number {\n return -nextDown(-x);\n}\n\n/** This function keeps a value below 1. A sum of a stratum and a draw can round up to 1. */\nfunction belowOne(x: number): number {\n return x < 1 ? x : BELOW_ONE;\n}\n\nfunction count(fn: string, name: string, value: number): void {\n if (!Number.isSafeInteger(value) || value < 1) throw new RangeError(`${fn}: ${name} is ${value}, and it must be an integer from 1.`);\n}\n\n/** This function examines a dimension and gives the map from a uniform number in [0, 1) to a value of the dimension. */\nfunction dimensionMap(family: string, dim: Dimension, r: Random): (u: number) => number {\n const where = `${family}.${dim.name}`;\n if (!Number.isFinite(dim.min) || !Number.isFinite(dim.max) || dim.min > dim.max) {\n throw new RangeError(`${where}: the range ${dim.min} to ${dim.max} is not a finite range.`);\n }\n if (dim.integer === true && (!Number.isSafeInteger(dim.min) || !Number.isSafeInteger(dim.max))) {\n throw new RangeError(`${where}: an integer dimension needs integer ends, not ${dim.min} and ${dim.max}.`);\n }\n // An integer dimension takes the floor of a value from [min, max + 1).\n const end = dim.integer === true ? dim.max + 1 : dim.max;\n const top = dim.integer === true ? nextDown(end) : end;\n const whole = (x: number): number => (dim.integer === true ? Math.min(dim.max, Math.floor(x)) : x);\n const clamp = (x: number): number => Math.min(top, Math.max(dim.min, x));\n if (dim.distribution !== undefined) {\n if (dim.scale !== undefined) throw new RangeError(`${where}: a dimension with a distribution has no scale.`);\n const d = distributionOf(dim.distribution, r);\n const low = d.cdf(nextDown(dim.min));\n const high = d.cdf(top);\n if (!(high > low)) throw new RangeError(`${where}: the distribution has no probability from ${dim.min} to ${dim.max}.`);\n // A discrete quantile at `low` can be a value below `min`. The smallest value above `low` is then the first value in the range.\n const first = d.quantile(nextUp(low));\n return (u) => {\n const x = d.quantile(low + u * (high - low));\n return whole(clamp(x < dim.min ? first : x));\n };\n }\n if (dim.scale === \"log\") {\n if (!(dim.min > 0)) throw new RangeError(`${where}: a log scale needs a minimum above 0, not ${dim.min}.`);\n // The form `min * exp(u * span)` gives `min` exactly at 0.\n const span = Math.log(end / dim.min);\n return (u) => whole(clamp(dim.min * Math.exp(u * span)));\n }\n return (u) => whole(clamp(dim.min + u * (end - dim.min)));\n}\n\n/**\n * This function gives the map from a point of the unit cube to a point of the family. Coordinate `i` gives the value of\n * dimension `i`. The parameters of each distribution come from `r.fork(\"dimension:\" + name)` one time. Thus the\n * same seed gives the same map, and a new dimension does not change the others.\n */\nexport function familyMap(family: InputFamily, r: Random): (unit: readonly number[]) => Point {\n if (family.dimensions.length === 0) throw new RangeError(`${family.name}: a family needs one dimension or more.`);\n const names = family.dimensions.map((d) => d.name);\n const twice = names.find((n, i) => n === \"\" || names.indexOf(n) !== i);\n if (twice !== undefined) throw new RangeError(`${family.name}: the dimension name \"${twice}\" is empty or not unique.`);\n const maps = family.dimensions.map((d) => dimensionMap(family.name, d, r.fork(`dimension:${d.name}`)));\n return (unit) => {\n if (unit.length !== maps.length) throw new RangeError(`${family.name}: a point needs ${maps.length} coordinates, not ${unit.length}.`);\n const point: Record<string, number> = {};\n maps.forEach((map, i) => {\n const u = unit[i]!;\n if (!(u >= 0 && u < 1)) throw new RangeError(`${family.name}: coordinate ${i} is ${u}, and it must be from 0 to below 1.`);\n point[names[i]!] = map(u);\n });\n return point;\n };\n}\n\n/** This function gives the points of the family at the points of a unit design. */\nexport function familyPoints(family: InputFamily, unit: readonly (readonly number[])[], r: Random): Point[] {\n const map = familyMap(family, r);\n return unit.map(map);\n}\n\n/** This function gives `n` independent uniform points of the unit cube in `d` dimensions. The draws go row by row. */\nexport function randomDesign(n: number, d: number, r: Random): number[][] {\n count(\"randomDesign\", \"n\", n);\n count(\"randomDesign\", \"d\", d);\n return Array.from({ length: n }, () => Array.from({ length: d }, () => r.next()));\n}\n\n/**\n * This function gives a Latin hypercube of `n` points in `d` dimensions. Each column has exactly one point in each of\n * the `n` strata `[k/n, (k+1)/n)`. For each column, the draws are one shuffle of the strata, then one draw in each point.\n */\nexport function latinHypercube(n: number, d: number, r: Random): number[][] {\n count(\"latinHypercube\", \"n\", n);\n count(\"latinHypercube\", \"d\", d);\n const rows = Array.from({ length: n }, () => new Array<number>(d));\n const strata = Array.from({ length: n }, (_, k) => k);\n for (let j = 0; j < d; j++) {\n const order = r.shuffle(strata);\n for (let i = 0; i < n; i++) rows[i]![j] = belowOne((order[i]! + r.next()) / n);\n }\n return rows;\n}\n\n/**\n * This function gives a stratified grid: `strata` strata on each axis, so `strata^d` cells, and one uniform point in\n * each cell. The cells go in the order of their index in base `strata`, with the first dimension as the last digit.\n */\nexport function stratifiedDesign(strata: number, d: number, r: Random, limit = 1_000_000): number[][] {\n count(\"stratifiedDesign\", \"strata\", strata);\n count(\"stratifiedDesign\", \"d\", d);\n const n = strata ** d;\n if (n > limit) throw new RangeError(`stratifiedDesign: ${strata}^${d} = ${n} cells is above the limit ${limit}.`);\n return Array.from({ length: n }, (_, cell) => {\n let rest = cell;\n return Array.from({ length: d }, () => {\n const k = rest % strata;\n rest = Math.floor(rest / strata);\n return belowOne((k + r.next()) / strata);\n });\n });\n}\n\n/**\n * This function gives the Saltelli design for the Sobol indices of a model with `d` inputs: `a`, `b` and the `d`\n * matrices `ab`. The design has `n * (d + 2)` points for the model. `a` comes from `r.fork(\"A\")`, and `b` comes\n * from `r.fork(\"B\")`. With `base` `\"latin\"`, each is a Latin hypercube.\n */\nexport function saltelliDesign(n: number, d: number, r: Random, base: \"random\" | \"latin\" = \"random\"): SaltelliDesign {\n const make = base === \"latin\" ? latinHypercube : randomDesign;\n const a = make(n, d, r.fork(\"A\"));\n const b = make(n, d, r.fork(\"B\"));\n const ab = Array.from({ length: d }, (_, i) => a.map((row, k) => row.map((x, j) => (j === i ? b[k]![j]! : x))));\n return { a, b, ab };\n}\n"],"mappings":";;AAuCA,MAAM,YAAY,IAAI,OAAO,UAAU;;AAGvC,SAAS,SAAS,GAAmB;CACnC,IAAI,MAAM,GAAG,OAAO,CAAC,OAAO;CAC5B,MAAM,IAAI,IAAI,aAAa,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U,MAAM,KAAM,EAAE,KAAK,KAAK,CAAC;CAC/E;CACA,OAAO;AACT;;;;;AAMA,SAAgB,iBAAiB,QAAgB,GAAW,GAAW,QAAQ,KAAuB;CACpG,MAAM,oBAAoB,UAAU,MAAM;CAC1C,MAAM,oBAAoB,KAAK,CAAC;CAChC,MAAM,IAAI,UAAU;CACpB,IAAI,IAAI,OAAO,MAAM,IAAI,WAAW,qBAAqB,OAAO,GAAG,EAAE,KAAK,EAAE,4BAA4B,MAAM,EAAE;CAChH,OAAO,MAAM,KAAK,EAAE,QAAQ,EAAE,IAAI,GAAG,SAAS;EAC5C,IAAI,OAAO;EACX,OAAO,MAAM,KAAK,EAAE,QAAQ,EAAE,SAAS;GACrC,MAAM,IAAI,OAAO;GACjB,OAAO,KAAK,MAAM,OAAO,MAAM;GAC/B,OAAO,UAAU,IAAI,EAAE,KAAK,KAAK,MAAM;EACzC,CAAC;CACH,CAAC;AACH;;;;;;AAOA,SAAgB,eAAe,GAAW,GAAW,GAAW,OAA2B,UAA0B;CACnH,MAAM,OAAO,SAAS,UAAU,iBAAiB;CACjD,MAAM,IAAI,KAAK,GAAG,GAAG,EAAE,KAAK,GAAG,CAAC;CAChC,MAAM,IAAI,KAAK,GAAG,GAAG,EAAE,KAAK,GAAG,CAAC;CAEhC,OAAO;EAAE;EAAG;EAAG,IADJ,MAAM,KAAK,EAAE,QAAQ,EAAE,IAAI,GAAG,MAAM,EAAE,KAAK,KAAK,MAAM,IAAI,KAAK,GAAG,MAAO,MAAM,IAAI,EAAE,EAAE,CAAE,KAAM,CAAE,CAAC,CAC7F;CAAE;AACpB"}
package/build/index.d.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  import { Random, Source, deriveSeed, fnv1a32, mulberry32, random, randomOf, seedOf, seedsFrom, stablePick } from "./random.js";
2
2
  import { DistributionSpec, Param, dependsOnLibm, sampler } from "./distributions.js";
3
+ import { normalCdf, normalQuantile } from "./normal.js";
4
+ import { Distribution, betaCdf, distributionOf } from "./quantiles.js";
5
+ import { Dimension, InputFamily, Point, SaltelliDesign, familyMap, familyPoints, latinHypercube, randomDesign, saltelliDesign, stratifiedDesign } from "./designs.js";
3
6
  import { CanonicalOptions, Sha256Options, canonicalHash, canonicalJson, sha256Hex } from "./hash.js";
4
7
  import { DIAGRAM_BOX_AREA, GIT_BLOB_BYTES, RECORDED_TABLES, RecordedTable, recordedSpec } from "./recorded.js";
5
- export { type CanonicalOptions, DIAGRAM_BOX_AREA, type DistributionSpec, GIT_BLOB_BYTES, type Param, RECORDED_TABLES, type Random, type RecordedTable, type Sha256Options, type Source, canonicalHash, canonicalJson, dependsOnLibm, deriveSeed, fnv1a32, mulberry32, random, randomOf, recordedSpec, sampler, seedOf, seedsFrom, sha256Hex, stablePick };
8
+ export { type CanonicalOptions, DIAGRAM_BOX_AREA, type Dimension, type Distribution, type DistributionSpec, GIT_BLOB_BYTES, type InputFamily, type Param, type Point, RECORDED_TABLES, type Random, type RecordedTable, type SaltelliDesign, type Sha256Options, type Source, betaCdf, canonicalHash, canonicalJson, dependsOnLibm, deriveSeed, distributionOf, familyMap, familyPoints, fnv1a32, latinHypercube, mulberry32, normalCdf, normalQuantile, random, randomDesign, randomOf, recordedSpec, saltelliDesign, sampler, seedOf, seedsFrom, sha256Hex, stablePick, stratifiedDesign };
package/build/index.js CHANGED
@@ -1,5 +1,8 @@
1
1
  import { dependsOnLibm, sampler } from "./distributions.js";
2
+ import { normalCdf, normalQuantile } from "./normal.js";
3
+ import { betaCdf, distributionOf } from "./quantiles.js";
4
+ import { familyMap, familyPoints, latinHypercube, randomDesign, saltelliDesign, stratifiedDesign } from "./designs.js";
2
5
  import { canonicalHash, canonicalJson, sha256Hex } from "./hash.js";
3
6
  import { DIAGRAM_BOX_AREA, GIT_BLOB_BYTES, RECORDED_TABLES, recordedSpec } from "./recorded.js";
4
7
  import { deriveSeed, fnv1a32, mulberry32, random, randomOf, seedOf, seedsFrom, stablePick } from "./random.js";
5
- export { DIAGRAM_BOX_AREA, GIT_BLOB_BYTES, RECORDED_TABLES, canonicalHash, canonicalJson, dependsOnLibm, deriveSeed, fnv1a32, mulberry32, random, randomOf, recordedSpec, sampler, seedOf, seedsFrom, sha256Hex, stablePick };
8
+ export { DIAGRAM_BOX_AREA, GIT_BLOB_BYTES, RECORDED_TABLES, betaCdf, canonicalHash, canonicalJson, dependsOnLibm, deriveSeed, distributionOf, familyMap, familyPoints, fnv1a32, latinHypercube, mulberry32, normalCdf, normalQuantile, random, randomDesign, randomOf, recordedSpec, saltelliDesign, sampler, seedOf, seedsFrom, sha256Hex, stablePick, stratifiedDesign };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * This function gives the standard normal cumulative distribution, `P(Z <= x)`. Below 0.75 in size, `x` uses the
3
+ * series of `0.5 + phi(x) * (x + x^3/3 + x^5/15 + ...)`. The tails use the continued fraction of the Mills ratio, so a
4
+ * lower tail has no cancellation. On 2026-11-09 the error was at most 4.4 ulps from -38 to 9, against `mpmath`.
5
+ * `normalCdf(-37)` is approximately 5.7e-300, not 0.
6
+ *
7
+ * @param x - A number. `-Infinity` gives 0 and `Infinity` gives 1. `NaN` throws a `RangeError`.
8
+ */
9
+ export declare function normalCdf(x: number): number;
10
+ /**
11
+ * This function gives the quantile of the standard normal law: the `x` with `normalCdf(x) = p`. It uses PPND16 of
12
+ * Wichura (algorithm AS 241). Below 0.075, one step of Halley with `normalCdf` follows. Above 0.5, `p` uses the lower
13
+ * tail at `1 - p`. This subtraction is exact. On 2026-11-09 the error was at most 1.2 ulps in the tails and 5.5 ulps
14
+ * from 0.075 to 0.925, against `mpmath`.
15
+ *
16
+ * @param p - The share of the law below the result, from 0 to 1. A `p` of 0 gives `-Infinity` and 1 gives `Infinity`.
17
+ */
18
+ export declare function normalQuantile(p: number): number;
19
+ //# sourceMappingURL=normal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"normal.d.ts","names":[],"sources":["../src/normal.ts"],"mappings":";;;;;;;;wBAyBgB,UAAU;;;;;;;;;wBAiEV,eAAe"}
@@ -0,0 +1,138 @@
1
+ // src/normal.ts
2
+ const SQRT_2PI = Math.sqrt(2 * Math.PI);
3
+ /**
4
+ * This function gives `e^(-z^2/2)` for a `z` of 0 or more, with its relative digits for a large `z`. The rounding of
5
+ * `z^2` costs `z^2/2` ulps, so the function splits `z` into `hi + lo`. `hi` has 4 bits after the point, so `hi^2` is
6
+ * exact for each `z` below 2^20.
7
+ */
8
+ function halfSquareExp(z) {
9
+ const hi = Math.round(z * 16) / 16;
10
+ const lo = z - hi;
11
+ return Math.exp(-hi * hi / 2) * Math.exp(-lo * (z + hi) / 2);
12
+ }
13
+ /**
14
+ * This function gives the standard normal cumulative distribution, `P(Z <= x)`. Below 0.75 in size, `x` uses the
15
+ * series of `0.5 + phi(x) * (x + x^3/3 + x^5/15 + ...)`. The tails use the continued fraction of the Mills ratio, so a
16
+ * lower tail has no cancellation. On 2026-11-09 the error was at most 4.4 ulps from -38 to 9, against `mpmath`.
17
+ * `normalCdf(-37)` is approximately 5.7e-300, not 0.
18
+ *
19
+ * @param x - A number. `-Infinity` gives 0 and `Infinity` gives 1. `NaN` throws a `RangeError`.
20
+ */
21
+ function normalCdf(x) {
22
+ if (Number.isNaN(x)) throw new RangeError("normalCdf: x is NaN.");
23
+ const z = Math.abs(x);
24
+ if (z > 40) return x > 0 ? 1 : 0;
25
+ const density = halfSquareExp(z) / SQRT_2PI;
26
+ if (z < .75) {
27
+ let term = x;
28
+ let sum = x;
29
+ for (let k = 1; k < 200 && Math.abs(term) > Number.EPSILON * Math.abs(sum) * .01; k++) {
30
+ term *= x * x / (2 * k + 1);
31
+ sum += term;
32
+ }
33
+ return .5 + density * sum;
34
+ }
35
+ let fraction = z;
36
+ for (let k = Math.ceil(1e3 / (z * z)) + 50; k >= 1; k--) fraction = z + k / fraction;
37
+ const tail = density / fraction;
38
+ return x > 0 ? 1 - tail : tail;
39
+ }
40
+ const A = [
41
+ 3.3871328727963665,
42
+ 133.14166789178438,
43
+ 1971.5909503065513,
44
+ 13731.69376550946,
45
+ 45921.95393154987,
46
+ 67265.7709270087,
47
+ 33430.57558358813,
48
+ 2509.0809287301227
49
+ ];
50
+ const B = [
51
+ 1,
52
+ 42.31333070160091,
53
+ 687.1870074920579,
54
+ 5394.196021424751,
55
+ 21213.794301586597,
56
+ 39307.89580009271,
57
+ 28729.085735721943,
58
+ 5226.495278852854
59
+ ];
60
+ const C = [
61
+ 1.4234371107496835,
62
+ 4.630337846156546,
63
+ 5.769497221460691,
64
+ 3.6478483247632045,
65
+ 1.2704582524523684,
66
+ .2417807251774506,
67
+ .022723844989269184,
68
+ .0007745450142783414
69
+ ];
70
+ const D = [
71
+ 1,
72
+ 2.053191626637759,
73
+ 1.6763848301838038,
74
+ .6897673349851,
75
+ .14810397642748008,
76
+ .015198666563616457,
77
+ .0005475938084995345,
78
+ 1.0507500716444169e-9
79
+ ];
80
+ const E = [
81
+ 6.657904643501103,
82
+ 5.463784911164114,
83
+ 1.7848265399172913,
84
+ .29656057182850487,
85
+ .026532189526576124,
86
+ .0012426609473880784,
87
+ 27115555687434876e-21,
88
+ 2.0103343992922881e-7
89
+ ];
90
+ const F = [
91
+ 1,
92
+ .599832206555888,
93
+ .1369298809227358,
94
+ .014875361290850615,
95
+ .0007868691311456133,
96
+ 18463183175100548e-21,
97
+ 1.421511758316446e-7,
98
+ 20442631033899397e-31
99
+ ];
100
+ /** This function gives the value of the polynomial `c[0] + c[1] x + ...`, by the rule of Horner. */
101
+ function poly(c, x) {
102
+ let value = 0;
103
+ for (let i = c.length - 1; i >= 0; i--) value = value * x + c[i];
104
+ return value;
105
+ }
106
+ /**
107
+ * This function gives the quantile of the standard normal law: the `x` with `normalCdf(x) = p`. It uses PPND16 of
108
+ * Wichura (algorithm AS 241). Below 0.075, one step of Halley with `normalCdf` follows. Above 0.5, `p` uses the lower
109
+ * tail at `1 - p`. This subtraction is exact. On 2026-11-09 the error was at most 1.2 ulps in the tails and 5.5 ulps
110
+ * from 0.075 to 0.925, against `mpmath`.
111
+ *
112
+ * @param p - The share of the law below the result, from 0 to 1. A `p` of 0 gives `-Infinity` and 1 gives `Infinity`.
113
+ */
114
+ function normalQuantile(p) {
115
+ if (!(p >= 0 && p <= 1)) throw new RangeError(`normalQuantile: p is from 0 to 1, not ${p}.`);
116
+ if (p === 0) return Number.NEGATIVE_INFINITY;
117
+ if (p === 1) return Number.POSITIVE_INFINITY;
118
+ if (p > .5) return -normalQuantile(1 - p);
119
+ const q = p - .5;
120
+ if (q >= -.425) {
121
+ const r = .180625 - q * q;
122
+ return q * poly(A, r) / poly(B, r);
123
+ }
124
+ let r = Math.sqrt(-Math.log(p));
125
+ let x;
126
+ if (r <= 5) {
127
+ r -= 1.6;
128
+ x = -poly(C, r) / poly(D, r);
129
+ } else {
130
+ r -= 5;
131
+ x = -poly(E, r) / poly(F, r);
132
+ }
133
+ const u = (normalCdf(x) - p) * SQRT_2PI / halfSquareExp(-x);
134
+ return x - u / (1 + x * u / 2);
135
+ }
136
+ export { normalCdf, normalQuantile };
137
+
138
+ //# sourceMappingURL=normal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"normal.js","names":[],"sources":["../src/normal.ts"],"sourcesContent":["// The standard normal law: its cumulative distribution `normalCdf` and its quantile `normalQuantile`. This file is the\n// one home of the two functions. `@mark1russell7/rigor-statistics` exports them from here. The final home is the\n// probability layer, and a move to that layer keeps these exports.\n\nconst SQRT_2PI = Math.sqrt(2 * Math.PI);\n\n/**\n * This function gives `e^(-z^2/2)` for a `z` of 0 or more, with its relative digits for a large `z`. The rounding of\n * `z^2` costs `z^2/2` ulps, so the function splits `z` into `hi + lo`. `hi` has 4 bits after the point, so `hi^2` is\n * exact for each `z` below 2^20.\n */\nfunction halfSquareExp(z: number): number {\n const hi = Math.round(z * 16) / 16;\n const lo = z - hi;\n return Math.exp((-hi * hi) / 2) * Math.exp((-lo * (z + hi)) / 2);\n}\n\n/**\n * This function gives the standard normal cumulative distribution, `P(Z <= x)`. Below 0.75 in size, `x` uses the\n * series of `0.5 + phi(x) * (x + x^3/3 + x^5/15 + ...)`. The tails use the continued fraction of the Mills ratio, so a\n * lower tail has no cancellation. On 2026-11-09 the error was at most 4.4 ulps from -38 to 9, against `mpmath`.\n * `normalCdf(-37)` is approximately 5.7e-300, not 0.\n *\n * @param x - A number. `-Infinity` gives 0 and `Infinity` gives 1. `NaN` throws a `RangeError`.\n */\nexport function normalCdf(x: number): number {\n if (Number.isNaN(x)) throw new RangeError(\"normalCdf: x is NaN.\");\n const z = Math.abs(x);\n // Below -38.5, the value is below the smallest double.\n if (z > 40) return x > 0 ? 1 : 0;\n const density = halfSquareExp(z) / SQRT_2PI;\n if (z < 0.75) {\n let term = x;\n let sum = x;\n for (let k = 1; k < 200 && Math.abs(term) > Number.EPSILON * Math.abs(sum) * 0.01; k++) {\n term *= (x * x) / (2 * k + 1);\n sum += term;\n }\n return 0.5 + density * sum;\n }\n // The fraction has `1000 / x^2 + 50` terms. This count converges to the last bit from 0.75.\n let fraction = z;\n for (let k = Math.ceil(1000 / (z * z)) + 50; k >= 1; k--) fraction = z + k / fraction;\n const tail = density / fraction;\n return x > 0 ? 1 - tail : tail;\n}\n\n// The coefficients of PPND16 of Wichura (1988), algorithm AS 241. The first set is for |p - 0.5| <= 0.425.\nconst A = [\n 3.387132872796366608, 133.14166789178437745, 1971.5909503065514427, 13731.693765509461125, 45921.953931549871457,\n 67265.770927008700853, 33430.575583588128105, 2509.0809287301226727,\n];\nconst B = [\n 1, 42.313330701600911252, 687.1870074920579083, 5394.1960214247511077, 21213.794301586595867, 39307.89580009271061,\n 28729.085735721942674, 5226.495278852854561,\n];\n// The second set is for a tail with r = sqrt(-ln(tail)) of 5 or less.\nconst C = [\n 1.42343711074968357734, 4.6303378461565452959, 5.7694972214606914055, 3.64784832476320460504, 1.27045825245236838258,\n 0.24178072517745061177, 0.0227238449892691845833, 7.7454501427834140764e-4,\n];\nconst D = [\n 1, 2.05319162663775882187, 1.6763848301838038494, 0.68976733498510000455, 0.14810397642748007459,\n 0.0151986665636164571966, 5.475938084995344946e-4, 1.05075007164441684324e-9,\n];\n// The third set is for a far tail, with r above 5.\nconst E = [\n 6.6579046435011037772, 5.4637849111641143699, 1.7848265399172913358, 0.29656057182850489123, 0.026532189526576123093,\n 0.0012426609473880784386, 2.71155556874348757815e-5, 2.01033439929228813265e-7,\n];\nconst F = [\n 1, 0.59983220655588793769, 0.13692988092273580531, 0.0148753612908506148525, 7.868691311456132591e-4,\n 1.8463183175100546818e-5, 1.4215117583164458887e-7, 2.04426310338993978564e-15,\n];\n\n/** This function gives the value of the polynomial `c[0] + c[1] x + ...`, by the rule of Horner. */\nfunction poly(c: readonly number[], x: number): number {\n let value = 0;\n for (let i = c.length - 1; i >= 0; i--) value = value * x + c[i]!;\n return value;\n}\n\n/**\n * This function gives the quantile of the standard normal law: the `x` with `normalCdf(x) = p`. It uses PPND16 of\n * Wichura (algorithm AS 241). Below 0.075, one step of Halley with `normalCdf` follows. Above 0.5, `p` uses the lower\n * tail at `1 - p`. This subtraction is exact. On 2026-11-09 the error was at most 1.2 ulps in the tails and 5.5 ulps\n * from 0.075 to 0.925, against `mpmath`.\n *\n * @param p - The share of the law below the result, from 0 to 1. A `p` of 0 gives `-Infinity` and 1 gives `Infinity`.\n */\nexport function normalQuantile(p: number): number {\n if (!(p >= 0 && p <= 1)) throw new RangeError(`normalQuantile: p is from 0 to 1, not ${p}.`);\n if (p === 0) return Number.NEGATIVE_INFINITY;\n if (p === 1) return Number.POSITIVE_INFINITY;\n if (p > 0.5) return -normalQuantile(1 - p);\n const q = p - 0.5;\n if (q >= -0.425) {\n const r = 0.180625 - q * q;\n return (q * poly(A, r)) / poly(B, r);\n }\n let r = Math.sqrt(-Math.log(p));\n let x: number;\n if (r <= 5) {\n r -= 1.6;\n x = -poly(C, r) / poly(D, r);\n } else {\n r -= 5;\n x = -poly(E, r) / poly(F, r);\n }\n // One step of Halley. `u` is the error of the cdf over the density.\n const u = ((normalCdf(x) - p) * SQRT_2P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R;CAAG;CAAwB;CAAuB;CAAwB;CAC1E;CAA0B;CAAyB;AACrD;AAEA,MAAM,IAAI;CACR;CAAuB;CAAuB;CAAuB;CAAwB;CAC7F;CAA0B;CAA2B;AACvD;AACA,MAAM,IAAI;CACR;CAAG;CAAwB;CAAwB;CAA0B;CAC7E;CAA0B;CAA0B;AACtD;;AAGA,SAAS,KAAK,GAAsB,GAAmB;CACrD,IAAI,QAAQ;CACZ,KAAK,IAAI,IAAI,EAAE,SAAS,GAAG,KAAK,GAAG,KAAK,QAAQ,QAAQ,IAAI,EAAE;CAC9D,OAAO;AACT;;;;;;;;;AAUA,SAAgB,eAAe,GAAmB;CAChD,IAAI,EAAE,KAAK,KAAK,KAAK,IAAI,MAAM,IAAI,WAAW,yCAAyC,EAAE,EAAE;CAC3F,IAAI,MAAM,GAAG,OAAO,OAAO;CAC3B,IAAI,MAAM,GAAG,OAAO,OAAO;CAC3B,IAAI,IAAI,IAAK,OAAO,CAAC,eAAe,IAAI,CAAC;CACzC,MAAM,IAAI,IAAI;CACd,IAAI,KAAK,OAAQ;EACf,MAAM,IAAI,UAAW,IAAI;EACzB,OAAQ,IAAI,KAAK,GAAG,CAAC,IAAK,KAAK,GAAG,CAAC;CACrC;CACA,IAAI,IAAI,KAAK,KAAK,CAAC,KAAK,IAAI,CAAC,CAAC;CAC9B,IAAI;CACJ,IAAI,KAAK,GAAG;EACV,KAAK;EACL,IAAI,CAAC,KAAK,GAAG,CAAC,IAAI,KAAK,GAAG,CAAC;CAC7B,OAAO;EACL,KAAK;EACL,IAAI,CAAC,KAAK,GAAG,CAAC,IAAI,KAAK,GAAG,CAAC;CAC7B;CAEA,MAAM,KAAM,UAAU,CAAC,IAAI,KAAK,WAAY,cAAc,CAAC,CAAC;CAC5D,OAAO,IAAI,KAAK,IAAK,IAAI,IAAK;AAChC"}
@@ -0,0 +1,22 @@
1
+ import { Random } from "./random.js";
2
+ import { DistributionSpec } from "./distributions.js";
3
+ /** One point of a family: its parameters are fixed. */
4
+ export interface Distribution {
5
+ /** The family of the point. */
6
+ readonly family: DistributionSpec["family"];
7
+ /** True when the values are a finite set, as in `zipf` and `recorded`. */
8
+ readonly discrete: boolean;
9
+ /** This function gives the probability of a value at or below `x`. */
10
+ cdf(x: number): number;
11
+ /** This function gives the smallest value whose `cdf` is `u` or more. `u` is from 0 to 1. */
12
+ quantile(u: number): number;
13
+ }
14
+ /** This function gives the regularized incomplete beta function: the beta cumulative distribution at `x`. */
15
+ export declare function betaCdf(x: number, a: number, b: number): number;
16
+ /**
17
+ * This function gives one point of a family, with its `cdf` and its `quantile`. It draws the parameters from `r` in
18
+ * the order of `sampler`. Thus the same seed gives the same point of the family as `sampler`.
19
+ * The values use `Math.exp`, `Math.log` or `Math.pow` when `dependsOnLibm` of the family is true.
20
+ */
21
+ export declare function distributionOf(spec: DistributionSpec, r: Random): Distribution;
22
+ //# sourceMappingURL=quantiles.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"quantiles.d.ts","names":[],"sources":["../src/quantiles.ts"],"mappings":";;;iBAOiB;;WAEN,QAAQ;;WAER;;EAET,IAAI;;EAEJ,SAAS;;;wBAiDK,QAAQ,WAAW,WAAW;;;;;;wBA+C9B,eAAe,MAAM,kBAAkB,GAAG,SAAS"}
@@ -0,0 +1,218 @@
1
+ import { normalCdf, normalQuantile } from "./normal.js";
2
+ // src/quantiles.ts
3
+ const LANCZOS = [
4
+ .9999999999998099,
5
+ 676.5203681218851,
6
+ -1259.1392167224028,
7
+ 771.3234287776531,
8
+ -176.6150291621406,
9
+ 12.507343278686905,
10
+ -.13857109526572012,
11
+ 9984369578019572e-21,
12
+ 1.5056327351493116e-7
13
+ ];
14
+ /** This function gives the logarithm of the gamma function for `x` above 0 (Lanczos, g 7). */
15
+ function logGamma(x) {
16
+ if (x < .5) return Math.log(Math.PI / Math.sin(Math.PI * x)) - logGamma(1 - x);
17
+ const y = x - 1;
18
+ let sum = LANCZOS[0];
19
+ for (let i = 1; i < 9; i++) sum += LANCZOS[i] / (y + i);
20
+ const t = y + 7.5;
21
+ return .5 * Math.log(2 * Math.PI) + (y + .5) * Math.log(t) - t + Math.log(sum);
22
+ }
23
+ /** This function gives the continued fraction of the incomplete beta function (the method of Lentz). */
24
+ function betaFraction(a, b, x) {
25
+ const tiny = 1e-300;
26
+ let c = 1;
27
+ let d = 1 - (a + b) * x / (a + 1);
28
+ if (Math.abs(d) < tiny) d = tiny;
29
+ d = 1 / d;
30
+ let h = d;
31
+ for (let m = 1; m <= 1e3; m++) {
32
+ const m2 = 2 * m;
33
+ let aa = m * (b - m) * x / ((a + m2 - 1) * (a + m2));
34
+ d = 1 + aa * d;
35
+ if (Math.abs(d) < tiny) d = tiny;
36
+ c = 1 + aa / c;
37
+ if (Math.abs(c) < tiny) c = tiny;
38
+ d = 1 / d;
39
+ h *= d * c;
40
+ aa = -(a + m) * (a + b + m) * x / ((a + m2) * (a + m2 + 1));
41
+ d = 1 + aa * d;
42
+ if (Math.abs(d) < tiny) d = tiny;
43
+ c = 1 + aa / c;
44
+ if (Math.abs(c) < tiny) c = tiny;
45
+ d = 1 / d;
46
+ const step = d * c;
47
+ h *= step;
48
+ if (Math.abs(step - 1) < 1e-16) break;
49
+ }
50
+ return h;
51
+ }
52
+ /** This function gives the regularized incomplete beta function: the beta cumulative distribution at `x`. */
53
+ function betaCdf(x, a, b) {
54
+ if (Number.isNaN(x)) return NaN;
55
+ if (x <= 0) return 0;
56
+ if (x >= 1) return 1;
57
+ const front = Math.exp(logGamma(a + b) - logGamma(a) - logGamma(b) + a * Math.log(x) + b * Math.log1p(-x));
58
+ if (x < (a + 1) / (a + b + 2)) return front * betaFraction(a, b, x) / a;
59
+ return 1 - front * betaFraction(b, a, 1 - x) / b;
60
+ }
61
+ /**
62
+ * This function gives the smallest `x` from `lo` to `hi` whose `cdf` is `u` or more, by bisection.
63
+ * The caller makes sure that `cdf(lo)` is `u` or less and `cdf(hi)` is `u` or more.
64
+ */
65
+ function bisect(cdf, u, lo, hi) {
66
+ for (let i = 0; i < 2e3 && lo < hi; i++) {
67
+ const mid = lo + (hi - lo) / 2;
68
+ if (mid <= lo || mid >= hi) break;
69
+ if (cdf(mid) >= u) hi = mid;
70
+ else lo = mid;
71
+ }
72
+ return cdf(lo) >= u ? lo : hi;
73
+ }
74
+ /** This function examines a parameter, as `sampler` does. Both ends of a range must pass `valid`. */
75
+ function checked(family, name, param, valid, rule) {
76
+ const ends = typeof param === "number" ? [param] : param;
77
+ for (const value of ends) if (!Number.isFinite(value) || !valid(value)) throw new RangeError(`${family}: ${name} is ${value}, and it must be ${rule}.`);
78
+ if (typeof param !== "number" && param[0] > param[1]) throw new RangeError(`${family}: the range of ${name} starts above its end.`);
79
+ }
80
+ /** This function gives the value of a parameter: the number, or one draw from the range. */
81
+ function valueOf(param, r) {
82
+ return typeof param === "number" ? param : r.range(param[0], param[1]);
83
+ }
84
+ /** This function examines `u` of a quantile. */
85
+ function unit(u) {
86
+ if (!(u >= 0 && u <= 1)) throw new RangeError(`quantile: u is ${u}, and it must be from 0 to 1.`);
87
+ }
88
+ /**
89
+ * This function gives one point of a family, with its `cdf` and its `quantile`. It draws the parameters from `r` in
90
+ * the order of `sampler`. Thus the same seed gives the same point of the family as `sampler`.
91
+ * The values use `Math.exp`, `Math.log` or `Math.pow` when `dependsOnLibm` of the family is true.
92
+ */
93
+ function distributionOf(spec, r) {
94
+ switch (spec.family) {
95
+ case "lognormal": {
96
+ checked("lognormal", "sigma", spec.sigma, (v) => v >= 0, "0 or more");
97
+ checked("lognormal", "mu", spec.mu, () => true, "finite");
98
+ const mu = valueOf(spec.mu, r);
99
+ const sigma = valueOf(spec.sigma, r);
100
+ const median = Math.exp(mu);
101
+ return {
102
+ family: "lognormal",
103
+ discrete: false,
104
+ cdf: (x) => Number.isNaN(x) ? NaN : x <= 0 ? 0 : sigma === 0 ? x >= median ? 1 : 0 : normalCdf((Math.log(x) - mu) / sigma),
105
+ quantile: (u) => {
106
+ unit(u);
107
+ return sigma === 0 ? median : Math.exp(mu + sigma * normalQuantile(u));
108
+ }
109
+ };
110
+ }
111
+ case "pareto": {
112
+ checked("pareto", "scale", spec.scale, (v) => v > 0, "above 0");
113
+ checked("pareto", "shape", spec.shape, (v) => v > 0, "above 0");
114
+ const scale = valueOf(spec.scale, r);
115
+ const shape = valueOf(spec.shape, r);
116
+ return {
117
+ family: "pareto",
118
+ discrete: false,
119
+ cdf: (x) => x < scale ? 0 : 1 - Math.pow(scale / x, shape),
120
+ quantile: (u) => {
121
+ unit(u);
122
+ return scale / Math.pow(1 - u, 1 / shape);
123
+ }
124
+ };
125
+ }
126
+ case "zipf": {
127
+ 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.`);
128
+ checked("zipf", "exponent", spec.exponent, (v) => v >= 0, "0 or more");
129
+ const exponent = valueOf(spec.exponent, r);
130
+ const totals = [];
131
+ let total = 0;
132
+ for (let rank = 1; rank <= spec.n; rank++) {
133
+ total += Math.pow(rank, -exponent);
134
+ totals.push(total);
135
+ }
136
+ return {
137
+ family: "zipf",
138
+ discrete: true,
139
+ cdf: (x) => x < 1 ? 0 : x >= spec.n ? 1 : totals[Math.floor(x) - 1] / total,
140
+ quantile: (u) => {
141
+ unit(u);
142
+ const at = u * total;
143
+ let lo = 0;
144
+ let hi = spec.n - 1;
145
+ while (lo < hi) {
146
+ const mid = lo + hi >>> 1;
147
+ if (totals[mid] >= at) hi = mid;
148
+ else lo = mid + 1;
149
+ }
150
+ return lo + 1;
151
+ }
152
+ };
153
+ }
154
+ case "beta": {
155
+ checked("beta", "a", spec.a, (v) => v > 0, "above 0");
156
+ checked("beta", "b", spec.b, (v) => v > 0, "above 0");
157
+ const a = valueOf(spec.a, r);
158
+ const b = valueOf(spec.b, r);
159
+ const cdf = (x) => betaCdf(x, a, b);
160
+ return {
161
+ family: "beta",
162
+ discrete: false,
163
+ cdf,
164
+ quantile: (u) => {
165
+ unit(u);
166
+ return u === 0 ? 0 : u === 1 ? 1 : bisect(cdf, u, 0, 1);
167
+ }
168
+ };
169
+ }
170
+ case "mixture": {
171
+ if (spec.parts.length === 0) throw new RangeError("mixture: the list of the parts is empty.");
172
+ for (const { weight } of spec.parts) checked("mixture", "weight", weight, (v) => v > 0, "above 0");
173
+ const parts = spec.parts.map(({ part }) => distributionOf(part, r));
174
+ const sum = spec.parts.reduce((s, { weight }) => s + weight, 0);
175
+ const weights = spec.parts.map(({ weight }) => weight / sum);
176
+ const cdf = (x) => Math.min(1, parts.reduce((s, part, i) => s + weights[i] * part.cdf(x), 0));
177
+ return {
178
+ family: "mixture",
179
+ discrete: parts.every((part) => part.discrete),
180
+ cdf,
181
+ quantile: (u) => {
182
+ unit(u);
183
+ const ends = parts.map((part) => part.quantile(u));
184
+ const lo = Math.min(...ends);
185
+ const hi = Math.max(...ends);
186
+ return lo === hi || !Number.isFinite(hi) ? hi : bisect(cdf, u, lo, hi);
187
+ }
188
+ };
189
+ }
190
+ case "recorded": {
191
+ if (spec.values.length === 0) throw new RangeError("recorded: the list of the values is empty.");
192
+ for (const value of spec.values) checked("recorded", "value", value, () => true, "finite");
193
+ const sorted = [...spec.values].sort((x, y) => x - y);
194
+ const n = sorted.length;
195
+ return {
196
+ family: "recorded",
197
+ discrete: true,
198
+ cdf: (x) => {
199
+ let lo = 0;
200
+ let hi = n;
201
+ while (lo < hi) {
202
+ const mid = lo + hi >>> 1;
203
+ if (sorted[mid] <= x) lo = mid + 1;
204
+ else hi = mid;
205
+ }
206
+ return lo / n;
207
+ },
208
+ quantile: (u) => {
209
+ unit(u);
210
+ return sorted[Math.max(0, Math.ceil(u * n) - 1)];
211
+ }
212
+ };
213
+ }
214
+ }
215
+ }
216
+ export { betaCdf, distributionOf };
217
+
218
+ //# sourceMappingURL=quantiles.js.map
@@ -0,0 +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/** This function gives the logarithm of the gamma function for `x` above 0 (Lanczos, g 7). */\nfunction 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]!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Q,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"}
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.1.8",
4
+ "version": "0.1.11",
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 a content hash: SHA-256 and canonical JSON (RFC 8785).",
6
6
  "keywords": [
7
7
  "random",