@mark1russell7/layout-contract 0.6.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/layout-contract",
4
- "version": "0.6.2",
4
+ "version": "0.8.0",
5
5
  "description": "The shared contract of the packing and highways layout engines: the input and record formats, the turn rule, margins, tolerances and hard rules.",
6
6
  "keywords": [
7
7
  "layout",
@@ -59,8 +59,9 @@
59
59
  "vitest": "^5.0.3"
60
60
  },
61
61
  "dependencies": {
62
- "@mark1russell7/rigor-generators": "^0.1.0",
63
- "@mark1russell7/typeset": "^0.1.8"
62
+ "@mark1russell7/rigor-generators": "^0.1.8",
63
+ "@mark1russell7/rigor-statistics": "^0.1.23",
64
+ "@mark1russell7/typeset": "^0.2.0"
64
65
  },
65
66
  "scripts": {
66
67
  "build": "tsdown",
package/src/hash.ts CHANGED
@@ -1,85 +1,24 @@
1
+ import { canonicalJson as homeCanonicalJson, sha256Hex as homeSha256Hex } from "@mark1russell7/rigor-generators";
1
2
  import { canonicalInput, type LayoutInput } from "./input.ts";
2
3
  import type { PackOutput } from "./output.ts";
3
4
  import { RECORD_EPS } from "./tolerance.ts";
4
- import { utf8Write } from "./utf8.ts";
5
-
6
- /** The round constants of SHA-256. */
7
- const K: readonly number[] = [
8
- 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
9
- 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
10
- 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
11
- 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
12
- 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
13
- ];
14
5
 
15
6
  /**
16
- * This function gives the SHA-256 digest of the UTF-8 bytes of a string, as 64 lowercase hex characters.
17
- * It uses no API of Node or of the browser.
7
+ * This function gives the SHA-256 digest of the bytes of a string, as 64 lowercase hex characters. A lone surrogate gives the 3 bytes of its code.
8
+ * Its home is `sha256Hex` of `@mark1russell7/rigor-generators`, with the option `input: "wtf8"`. This function keeps the name and the signature of the API.
18
9
  */
19
10
  export function sha256Hex(text: string): string {
20
- // The bytes go straight into the padded buffer, so the digest makes one array, not a list of the bytes and a copy.
21
- const length = utf8Write(text);
22
- const bits = length * 8;
23
- const total = Math.ceil((length + 9) / 64) * 64;
24
- const data = new Uint8Array(total);
25
- utf8Write(text, data);
26
- data[length] = 0x80;
27
- const view = new DataView(data.buffer);
28
- view.setUint32(total - 8, Math.floor(bits / 0x100000000));
29
- view.setUint32(total - 4, bits >>> 0);
30
- const h = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
31
- const w = new Uint32Array(64);
32
- const rotr = (x: number, n: number): number => (x >>> n) | (x << (32 - n));
33
- for (let off = 0; off < total; off += 64) {
34
- for (let i = 0; i < 16; i++) w[i] = view.getUint32(off + 4 * i);
35
- for (let i = 16; i < 64; i++) {
36
- const a = w[i - 15]!;
37
- const b = w[i - 2]!;
38
- const s0 = rotr(a, 7) ^ rotr(a, 18) ^ (a >>> 3);
39
- const s1 = rotr(b, 17) ^ rotr(b, 19) ^ (b >>> 10);
40
- w[i] = (w[i - 16]! + s0 + w[i - 7]! + s1) >>> 0;
41
- }
42
- let [a, b, c, d, e, f, g, k] = h as [number, number, number, number, number, number, number, number];
43
- for (let i = 0; i < 64; i++) {
44
- const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
45
- const ch = (e & f) ^ (~e & g);
46
- const t1 = (k + s1 + ch + K[i]! + w[i]!) >>> 0;
47
- const s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
48
- const maj = (a & b) ^ (a & c) ^ (b & c);
49
- const t2 = (s0 + maj) >>> 0;
50
- k = g;
51
- g = f;
52
- f = e;
53
- e = (d + t1) >>> 0;
54
- d = c;
55
- c = b;
56
- b = a;
57
- a = (t1 + t2) >>> 0;
58
- }
59
- h[0] = (h[0]! + a) >>> 0;
60
- h[1] = (h[1]! + b) >>> 0;
61
- h[2] = (h[2]! + c) >>> 0;
62
- h[3] = (h[3]! + d) >>> 0;
63
- h[4] = (h[4]! + e) >>> 0;
64
- h[5] = (h[5]! + f) >>> 0;
65
- h[6] = (h[6]! + g) >>> 0;
66
- h[7] = (h[7]! + k) >>> 0;
67
- }
68
- return h.map((x) => x.toString(16).padStart(8, "0")).join("");
11
+ return homeSha256Hex(text, { input: "wtf8" });
69
12
  }
70
13
 
71
14
  /**
72
15
  * This function gives the canonical form of a value: sorted keys and no whitespace, with the numbers of `JSON.stringify`.
73
16
  * A key with the value `undefined` is not in the form. An `undefined` in an array becomes `null`.
17
+ * Its home is `canonicalJson` of `@mark1russell7/rigor-generators`, with the option `form: "json"`.
18
+ * So a value with a method `toJSON`, for example a `Date`, gives the form of the result of that method. A function, a symbol and a cycle cause a `TypeError`.
74
19
  */
75
20
  export function canonicalJson(value: unknown): string {
76
- if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
77
- if (Array.isArray(value)) return `[${value.map((v: unknown) => (v === undefined ? "null" : canonicalJson(v))).join(",")}]`;
78
- const o = value as Record<string, unknown>;
79
- const keys = Object.keys(o)
80
- .filter((k) => o[k] !== undefined)
81
- .sort();
82
- return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(o[k])}`).join(",")}}`;
21
+ return homeCanonicalJson(value, { form: "json" });
83
22
  }
84
23
 
85
24
  /** The options of `outputHash` and `documentHash`. */
package/src/random.ts CHANGED
@@ -1,5 +1,4 @@
1
- import { mulberry32 as homeMulberry32 } from "@mark1russell7/rigor-generators";
2
- import { utf8 } from "./utf8.ts";
1
+ import { fnv1a32 as homeFnv1a32, mulberry32 as homeMulberry32 } from "@mark1russell7/rigor-generators";
3
2
 
4
3
  /**
5
4
  * This function gives a generator of random numbers in [0, 1). It is `mulberry32`, as in `docs/FORMAT.md` of `packing`.
@@ -10,13 +9,11 @@ export function mulberry32(seed: number): () => number {
10
9
  }
11
10
 
12
11
  /**
13
- * This function gives the FNV-1a hash of 32 bits of the UTF-8 bytes of a string.
14
- * It stays here because `fnv1a32` of `@mark1russell7/rigor-generators` encodes a lone surrogate as U+FFFD. This function encodes the 3 bytes of its code.
12
+ * This function gives the FNV-1a hash of 32 bits of the UTF-8 bytes of a string. A lone surrogate gives the 3 bytes of its code.
13
+ * Its home is `fnv1a32` of `@mark1russell7/rigor-generators`, with the option `input: "wtf8"`. This function keeps the name and the signature of the API.
15
14
  */
16
15
  export function fnv1a32(text: string): number {
17
- let h = 0x811c9dc5;
18
- for (const b of utf8(text)) h = Math.imul(h ^ b, 0x01000193) >>> 0;
19
- return h;
16
+ return homeFnv1a32(text, { input: "wtf8" });
20
17
  }
21
18
 
22
19
  /** This function gives the generator of one step of a seeded generator: `mulberry32(fnv1a32("<seed>:<step>"))`. */
package/src/verdict.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // The verdict over families (`docs/VERDICT.md`). highways, packing and the joint bench use the same rule, so they give the same verdict.
2
+ import { deriveSeed } from "@mark1russell7/rigor-generators";
3
+ import { bootstrap, bootstrapStrata, type Interval, signFlipTest, signTest } from "@mark1russell7/rigor-statistics";
2
4
  import { compareMeasure, type MeasureSpec } from "./measures.ts";
3
- import { stepRandom } from "./random.ts";
4
5
  import type { LayoutRecord } from "./record.ts";
5
6
 
6
7
  /**
@@ -148,37 +149,26 @@ interface Pair {
148
149
  /** This function gives the mean of a list that is not empty. */
149
150
  const meanOf = (values: readonly number[]): number => values.reduce((s, v) => s + v, 0) / values.length;
150
151
 
151
- /** This function gives the `q` quantile of sorted values, with linear interpolation. */
152
- function quantileOf(sorted: readonly number[], q: number): number {
153
- const at = (sorted.length - 1) * q;
154
- const lo = Math.floor(at);
155
- const hi = Math.ceil(at);
156
- return sorted[lo]! + (sorted[hi]! - sorted[lo]!) * (at - lo);
152
+ /** This function gives the mean of a sample of the differences, in the order of the sample. */
153
+ function sampleMean(list: readonly number[]): number {
154
+ let s = 0;
155
+ for (const d of list) s += d;
156
+ return s / list.length;
157
157
  }
158
158
 
159
- /** This function gives the interval of the samples of a bootstrap at the level `1 - level`. */
160
- function intervalOf(mean: number, samples: number[], level: number): VerdictInterval {
161
- samples.sort((x, y) => x - y);
162
- return { mean, lo: quantileOf(samples, level / 2), hi: quantileOf(samples, 1 - level / 2) };
159
+ /** This function gives the mean of the means of the samples of the families. */
160
+ function meanOfMeans(lists: readonly (readonly number[])[]): number {
161
+ let sum = 0;
162
+ for (const list of lists) sum += sampleMean(list);
163
+ return sum / lists.length;
163
164
  }
164
165
 
166
+ /** This function gives the interval of a bootstrap, with the mean of the data. */
167
+ const intervalOf = (mean: number, i: Interval): VerdictInterval => ({ mean, lo: i.low, hi: i.high });
168
+
165
169
  /** This function tells if an interval is clear of 0 on the side of the sign `sign`. */
166
170
  const clearOn = (i: VerdictInterval, sign: number): boolean => (sign > 0 ? i.lo > 0 : sign < 0 ? i.hi < 0 : false);
167
171
 
168
- /** This function gives the two-sided p of the exact binomial sign test, with `p = 0.5`. No count gives 1. */
169
- function signP(wins: number, losses: number): number {
170
- const n = wins + losses;
171
- if (n === 0) return 1;
172
- const k = Math.min(wins, losses);
173
- let tail = 0;
174
- let c = 1;
175
- for (let i = 0; i <= k; i++) {
176
- tail += c;
177
- c = (c * (n - i)) / (i + 1);
178
- }
179
- return Math.min(1, (2 * tail) / 2 ** n);
180
- }
181
-
182
172
  /** This function gives the breadth of a verdict with the side `side`: 1, -1, or 0 for no side. */
183
173
  function breadthOf(families: readonly FamilyVerdict[], side: number): VerdictBreadth {
184
174
  const ties = families.filter((f) => f.sign === 0).length;
@@ -278,65 +268,29 @@ export function verdict<R extends VerdictRecord>(records: Iterable<R>, options:
278
268
  return { family: list[0]!.family, n: list.length, mean: meanOf(list.map((p) => p.d)), sign: verdictOf === "better" ? 1 : verdictOf === "worse" ? -1 : 0 };
279
269
  });
280
270
 
281
- // The stratified bootstrap draws the seeds of each family with replacement. The pooled bootstrap draws all the inputs.
271
+ // The bootstraps of `@mark1russell7/rigor-statistics`. The stream of a step is `random(deriveSeed(seed, step))`, which is `stepRandom(seed, step)`.
272
+ // `bootstrapStrata` draws the seeds of each family with replacement, in the order of the families. `bootstrap` draws all the inputs.
273
+ const ends: readonly [number, number] = [level / 2, 1 - level / 2];
274
+ const diffs = lists.map((list) => list.map((p) => p.d));
282
275
  const stratMean = meanOf(families.map((f) => f.mean));
283
- const rs = stepRandom(seed, "verdict.stratified");
284
- const stratSamples: number[] = [];
285
- for (let run = 0; run < runs; run++) {
286
- let sum = 0;
287
- for (const list of lists) {
288
- let s = 0;
289
- for (let j = 0; j < list.length; j++) s += list[Math.floor(rs() * list.length)]!.d;
290
- sum += s / list.length;
291
- }
292
- stratSamples.push(sum / lists.length);
293
- }
294
- const stratified = intervalOf(stratMean, stratSamples, level);
295
-
276
+ const stratified = intervalOf(stratMean, bootstrapStrata(diffs, meanOfMeans, { runs, ends, seed: deriveSeed(seed, "verdict.stratified") }));
296
277
  const pooledMean = meanOf(pairs.map((p) => p.d));
297
- const rp = stepRandom(seed, "verdict.pooled");
298
- const pooledSamples: number[] = [];
299
- for (let run = 0; run < runs; run++) {
300
- let s = 0;
301
- for (let j = 0; j < n; j++) s += pairs[Math.floor(rp() * n)]!.d;
302
- pooledSamples.push(s / n);
303
- }
304
- const pooled = intervalOf(pooledMean, pooledSamples, level);
278
+ const pooled = intervalOf(pooledMean, bootstrap(diffs.flat(), sampleMean, { runs, ends, seed: deriveSeed(seed, "verdict.pooled") }));
305
279
 
306
280
  // The statistic is a weighted sum: the weight of an input is 1 / (the count of families × the count of its family).
281
+ // `signFlipTest` enumerates the sign sets up to `exactMax` terms. Above it, a drawn p counts the observed sign set as one draw.
307
282
  const terms = lists.flatMap((list) => list.map((p) => p.d / (lists.length * list.length)));
308
- const observed = Math.abs(terms.reduce((s, t) => s + t, 0));
309
- const slack = 1e-12 * terms.reduce((s, t) => s + Math.abs(t), 0);
310
- const exact = n <= exactMax;
311
- let hits = 0;
312
- let total: number;
313
- if (exact) {
314
- total = 2 ** n;
315
- for (let mask = 0; mask < total; mask++) {
316
- let t = 0;
317
- for (let i = 0; i < n; i++) t += mask & (1 << i) ? -terms[i]! : terms[i]!;
318
- if (Math.abs(t) >= observed - slack) hits++;
319
- }
320
- } else {
321
- total = draws;
322
- const rf = stepRandom(seed, "verdict.permutation");
323
- for (let k = 0; k < draws; k++) {
324
- let t = 0;
325
- for (let i = 0; i < n; i++) t += rf() < 0.5 ? -terms[i]! : terms[i]!;
326
- if (Math.abs(t) >= observed - slack) hits++;
327
- }
328
- }
329
- // A drawn p counts the observed sign set as one draw, so it is always above 0.
330
- const permutation: VerdictPermutation = { p: exact ? hits / total : (hits + 1) / (total + 1), exact, draws: total, seed };
283
+ const flips = signFlipTest(terms, { exactMax, runs: draws, seed: deriveSeed(seed, "verdict.permutation") });
284
+ const permutation: VerdictPermutation = { p: flips.p, exact: flips.exact, draws: flips.runs, seed };
331
285
 
332
286
  const wins = families.filter((f) => f.sign === 1).length;
333
287
  const losses = families.filter((f) => f.sign === -1).length;
334
- const signTest: VerdictSignTest = { wins, losses, ties: families.length - wins - losses, p: signP(wins, losses) };
288
+ const signs: VerdictSignTest = { wins, losses, ties: families.length - wins - losses, p: signTest(wins, losses, 2) };
335
289
 
336
290
  const sign = Math.sign(stratified.mean);
337
291
  const agree = sign !== 0 && sign === Math.sign(pooled.mean) && clearOn(stratified, sign) && clearOn(pooled, sign) && permutation.p < level;
338
292
  const label: VerdictLabel = agree ? (sign > 0 ? "better" : "worse") : sign * Math.sign(pooled.mean) < 0 ? "depends on the mix" : "no verdict";
339
293
  const breadth = breadthOf(families, sign);
340
294
  const summary = summaryOf(label, sign, breadth);
341
- return { measure: measure.id, n, stratified, pooled, permutation, families, signTest, agree, label, scope: "these families", breadth, summary, dropped };
295
+ return { measure: measure.id, n, stratified, pooled, permutation, families, signTest: signs, agree, label, scope: "these families", breadth, summary, dropped };
342
296
  }
package/src/utf8.ts DELETED
@@ -1,51 +0,0 @@
1
- /**
2
- * This function writes the UTF-8 bytes of a string into `out`, from the index `at`, and gives the index after the last byte.
3
- * With no `out`, it writes nothing and gives the count of the bytes. A lone surrogate gives the 3 bytes of its code.
4
- * It reads the UTF-16 code units, so it makes no string for each character (L81: `sha256Hex` allocated 2 GB in one pair).
5
- */
6
- export function utf8Write(text: string, out?: Uint8Array, at = 0): number {
7
- let n = at;
8
- for (let i = 0; i < text.length; i++) {
9
- let c = text.charCodeAt(i);
10
- if (c >= 0xd800 && c < 0xdc00 && i + 1 < text.length) {
11
- const low = text.charCodeAt(i + 1);
12
- if (low >= 0xdc00 && low < 0xe000) {
13
- c = 0x10000 + ((c - 0xd800) << 10) + (low - 0xdc00);
14
- i++;
15
- }
16
- }
17
- if (c < 0x80) {
18
- if (out !== undefined) out[n] = c;
19
- n += 1;
20
- } else if (c < 0x800) {
21
- if (out !== undefined) {
22
- out[n] = 0xc0 | (c >> 6);
23
- out[n + 1] = 0x80 | (c & 63);
24
- }
25
- n += 2;
26
- } else if (c < 0x10000) {
27
- if (out !== undefined) {
28
- out[n] = 0xe0 | (c >> 12);
29
- out[n + 1] = 0x80 | ((c >> 6) & 63);
30
- out[n + 2] = 0x80 | (c & 63);
31
- }
32
- n += 3;
33
- } else {
34
- if (out !== undefined) {
35
- out[n] = 0xf0 | (c >> 18);
36
- out[n + 1] = 0x80 | ((c >> 12) & 63);
37
- out[n + 2] = 0x80 | ((c >> 6) & 63);
38
- out[n + 3] = 0x80 | (c & 63);
39
- }
40
- n += 4;
41
- }
42
- }
43
- return n;
44
- }
45
-
46
- /** This function gives the UTF-8 bytes of a string. It does not use `TextEncoder`, because `TextEncoder` encodes a lone surrogate as U+FFFD. */
47
- export function utf8(text: string): Uint8Array {
48
- const bytes = new Uint8Array(utf8Write(text));
49
- utf8Write(text, bytes);
50
- return bytes;
51
- }