@seanhogg/builderforce-memory 2026.10.60 → 2026.10.63
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/dist/knowledge/assetFile.d.ts +3 -1
- package/dist/knowledge/assetFile.d.ts.map +1 -1
- package/dist/knowledge/assetFile.js +2 -2
- package/dist/knowledge/assetFile.js.map +1 -1
- package/dist/knowledge/extractFile.d.ts +2 -0
- package/dist/knowledge/extractFile.d.ts.map +1 -1
- package/dist/knowledge/extractFile.js +2 -2
- package/dist/knowledge/extractFile.js.map +1 -1
- package/dist/knowledge/extractJob.d.ts +3 -1
- package/dist/knowledge/extractJob.d.ts.map +1 -1
- package/dist/knowledge/extractJob.js +1 -1
- package/dist/knowledge/extractJob.js.map +1 -1
- package/dist/knowledge/outline.js +1 -1
- package/dist/knowledge/outline.js.map +1 -1
- package/dist/knowledge/owedFiles.d.ts +2 -0
- package/dist/knowledge/owedFiles.d.ts.map +1 -1
- package/dist/knowledge/owedFiles.js +2 -0
- package/dist/knowledge/owedFiles.js.map +1 -1
- package/dist/knowledge/plan.d.ts +4 -1
- package/dist/knowledge/plan.d.ts.map +1 -1
- package/dist/knowledge/plan.js +11 -4
- package/dist/knowledge/plan.js.map +1 -1
- package/dist/knowledge/reviewModel.d.ts +10 -1
- package/dist/knowledge/reviewModel.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.js +11 -5
- package/dist/knowledge/reviewPrefetch.js.map +1 -1
- package/dist/knowledge/sources.d.ts +2 -1
- package/dist/knowledge/sources.d.ts.map +1 -1
- package/dist/knowledge/sources.js +3 -1
- package/dist/knowledge/sources.js.map +1 -1
- package/dist/stats/distributions.d.ts +34 -0
- package/dist/stats/distributions.d.ts.map +1 -0
- package/dist/stats/distributions.js +180 -0
- package/dist/stats/distributions.js.map +1 -0
- package/dist/stats/estimators.d.ts +53 -0
- package/dist/stats/estimators.d.ts.map +1 -0
- package/dist/stats/estimators.js +79 -0
- package/dist/stats/estimators.js.map +1 -0
- package/dist/stats/fitting.d.ts +48 -0
- package/dist/stats/fitting.d.ts.map +1 -0
- package/dist/stats/fitting.js +209 -0
- package/dist/stats/fitting.js.map +1 -0
- package/dist/stats/index.d.ts +26 -0
- package/dist/stats/index.d.ts.map +1 -0
- package/dist/stats/index.js +18 -0
- package/dist/stats/index.js.map +1 -0
- package/dist/stats/information.d.ts +9 -0
- package/dist/stats/information.d.ts.map +1 -0
- package/dist/stats/information.js +21 -0
- package/dist/stats/information.js.map +1 -0
- package/dist/stats/multivariate.d.ts +25 -0
- package/dist/stats/multivariate.d.ts.map +1 -0
- package/dist/stats/multivariate.js +89 -0
- package/dist/stats/multivariate.js.map +1 -0
- package/dist/stats/policies.d.ts +19 -0
- package/dist/stats/policies.d.ts.map +1 -0
- package/dist/stats/policies.js +75 -0
- package/dist/stats/policies.js.map +1 -0
- package/dist/stats/prng.d.ts +11 -0
- package/dist/stats/prng.d.ts.map +1 -0
- package/dist/stats/prng.js +41 -0
- package/dist/stats/prng.js.map +1 -0
- package/dist/stats/scores.d.ts +33 -0
- package/dist/stats/scores.d.ts.map +1 -0
- package/dist/stats/scores.js +134 -0
- package/dist/stats/scores.js.map +1 -0
- package/dist/stats/tests.d.ts +48 -0
- package/dist/stats/tests.d.ts.map +1 -0
- package/dist/stats/tests.js +143 -0
- package/dist/stats/tests.js.map +1 -0
- package/dist/stats/timeSeries.d.ts +34 -0
- package/dist/stats/timeSeries.d.ts.map +1 -0
- package/dist/stats/timeSeries.js +71 -0
- package/dist/stats/timeSeries.js.map +1 -0
- package/dist/working/fold.d.ts +51 -0
- package/dist/working/fold.d.ts.map +1 -0
- package/dist/working/fold.js +218 -0
- package/dist/working/fold.js.map +1 -0
- package/dist/working/index.d.ts +1 -0
- package/dist/working/index.d.ts.map +1 -1
- package/dist/working/index.js +1 -0
- package/dist/working/index.js.map +1 -1
- package/package.json +7 -3
- package/src/contract/exports.snapshot.json +41 -0
- package/src/contract/regression.assets.test.ts +41 -1
- package/src/contract/regression.review.test.ts +56 -0
- package/src/contract/types.contract.test.ts +15 -2
- package/src/knowledge/assetFile.ts +4 -4
- package/src/knowledge/extractFile.ts +4 -2
- package/src/knowledge/extractJob.ts +3 -3
- package/src/knowledge/outline.ts +1 -1
- package/src/knowledge/owedFiles.ts +3 -0
- package/src/knowledge/plan.ts +14 -5
- package/src/knowledge/reviewModel.ts +10 -1
- package/src/knowledge/reviewPrefetch.ts +11 -5
- package/src/knowledge/sources.ts +3 -1
- package/src/stats/distributions.ts +180 -0
- package/src/stats/estimators.ts +101 -0
- package/src/stats/fitting.ts +252 -0
- package/src/stats/index.ts +59 -0
- package/src/stats/information.ts +20 -0
- package/src/stats/multivariate.ts +93 -0
- package/src/stats/policies.ts +84 -0
- package/src/stats/prng.ts +45 -0
- package/src/stats/scores.ts +135 -0
- package/src/stats/stats.test.ts +294 -0
- package/src/stats/tests.ts +164 -0
- package/src/stats/timeSeries.ts +92 -0
- package/src/working/fold.test.ts +196 -0
- package/src/working/fold.ts +241 -0
- package/src/working/index.ts +1 -0
|
@@ -52,6 +52,8 @@ export interface ExtractorState {
|
|
|
52
52
|
documentsNow?: string;
|
|
53
53
|
/** Document extensions whose asset-ness changed between `documents` and `documentsNow`: their files are owed a re-processing. */
|
|
54
54
|
flipped?: ReadonlySet<string>;
|
|
55
|
+
/** Claimed documents over the plan's size cap: planned as assets (never read), so they owe no calls. Set by the plan, carried to *Continue*. */
|
|
56
|
+
oversized?: ReadonlySet<string>;
|
|
55
57
|
}
|
|
56
58
|
|
|
57
59
|
/**
|
|
@@ -111,6 +113,7 @@ export const isOwed = (state: ExtractorState, path: string): boolean =>
|
|
|
111
113
|
const isAssetNow = (state: ExtractorState, path: string): boolean => {
|
|
112
114
|
if (!isBinaryPath(path)) return false;
|
|
113
115
|
if (!isDocumentPath(path)) return true;
|
|
116
|
+
if (state.oversized?.has(path)) return true; // claimed, but over the size cap: an asset like an unclaimed one
|
|
114
117
|
const claimed = state.documentsNow;
|
|
115
118
|
return claimed === undefined || claimed === NO_DOCUMENTS || !claimed.split(',').includes(extOf(path));
|
|
116
119
|
};
|
package/src/knowledge/plan.ts
CHANGED
|
@@ -57,10 +57,13 @@ export interface PlannedFile {
|
|
|
57
57
|
*/
|
|
58
58
|
owed: boolean;
|
|
59
59
|
/**
|
|
60
|
-
* An asset: binary by extension and not claimed as a document by a host parser
|
|
60
|
+
* An asset: binary by extension and not claimed as a document by a host parser, OR a claimed document over the size cap
|
|
61
|
+
* (`maxFileBytes`, see `oversized`). Counted in `files` (and in `ReviewPlan.assets`,
|
|
61
62
|
* not in `byPack`), diffed by hash like any file, but never read, extracted or judged; the review writes its file node (assetFile.ts).
|
|
62
63
|
*/
|
|
63
64
|
asset?: true;
|
|
65
|
+
/** An asset only because a claimed document exceeds the size cap: its node carries `badges.oversized` so a UI can say why it has no text. */
|
|
66
|
+
oversized?: true;
|
|
64
67
|
}
|
|
65
68
|
|
|
66
69
|
export interface PlanDetail {
|
|
@@ -114,7 +117,8 @@ export async function planDetail(
|
|
|
114
117
|
// left unfinished: those are owed a re-extraction. `prior` stays the real manifest (removals).
|
|
115
118
|
// A file's asset-ness depends on the packs (a pdf is an asset until a host parser claims it): a change in the document types the
|
|
116
119
|
// packs claim since the last run owes the files of those types a re-processing, whatever their hash (see withDocuments).
|
|
117
|
-
const
|
|
120
|
+
const oversized = new Set<string>();
|
|
121
|
+
const extractor: ExtractorState = { ...withDocuments(await loadExtractorState(manifest, source.rootId), claimedDocumentExts(composed)), oversized };
|
|
118
122
|
const packById = new Map(packs.map((p) => [p.id, p] as const));
|
|
119
123
|
|
|
120
124
|
const files: PlannedFile[] = [];
|
|
@@ -127,9 +131,11 @@ export async function planDetail(
|
|
|
127
131
|
if (ignored(e.path)) { skipped.push({ path: e.path, reason: 'ignored' }); continue; }
|
|
128
132
|
const document = isDocumentPath(e.path) ? resolveDocument(composed, e.path) : undefined;
|
|
129
133
|
// An asset is never read, so the size cap does not apply: it is planned, hashed and diffed, and costs no model call.
|
|
130
|
-
|
|
134
|
+
// A claimed document over the cap stays an asset (as before host parsers existed): never read, no calls (owedFiles isAssetNow agrees via `oversized`).
|
|
135
|
+
if (document && e.size > maxBytes) oversized.add(e.path);
|
|
136
|
+
if (isAssetPath(e.path, !!document && e.size <= maxBytes)) {
|
|
131
137
|
const { owed, changed } = classify(extractor, prior, e.path, e.hash, opts.force === true);
|
|
132
|
-
files.push({ path: e.path, hash: e.hash, size: e.size, pack: FALLBACK_PACK_ID, changed, owed, asset: true });
|
|
138
|
+
files.push({ path: e.path, hash: e.hash, size: e.size, pack: FALLBACK_PACK_ID, changed, owed, asset: true, ...(document && e.size > maxBytes ? { oversized: true as const } : {}) });
|
|
133
139
|
assets += 1;
|
|
134
140
|
continue;
|
|
135
141
|
}
|
|
@@ -188,7 +194,10 @@ export async function planDetail(
|
|
|
188
194
|
*/
|
|
189
195
|
export async function refreshPlan(detail: PlanDetail, manifest: IngestManifest): Promise<PlanDetail> {
|
|
190
196
|
const prior = await manifestMap(manifest, filesManifestKey(detail.plan.rootId));
|
|
191
|
-
const extractor =
|
|
197
|
+
const extractor: ExtractorState = {
|
|
198
|
+
...withDocuments(await loadExtractorState(manifest, detail.plan.rootId), detail.extractor.documentsNow),
|
|
199
|
+
...(detail.extractor.oversized ? { oversized: detail.extractor.oversized } : {}),
|
|
200
|
+
};
|
|
192
201
|
const files = detail.files.map((f) => {
|
|
193
202
|
const { owed, changed } = classify(extractor, prior, f.path, f.hash);
|
|
194
203
|
return { ...f, changed, owed };
|
|
@@ -22,8 +22,17 @@ export interface DirectorySource {
|
|
|
22
22
|
* The function that produced the `hash` of `list()` entries, over a text file's content. When given, the review hashes the
|
|
23
23
|
* text it read (once) and a file whose bytes no longer match the planned hash fails with "changed since plan" and stays owed.
|
|
24
24
|
* Optional: a source whose hash is not a pure function of the text (or that cannot say) is not checked in-thread.
|
|
25
|
+
* The `path` lets a host whose read() transforms bytes (document text) return the listing hash for that path.
|
|
26
|
+
* A transforming host must return the hash of the bytes it ACTUALLY read on that call, never the cached listing hash,
|
|
27
|
+
* or the changed-since-plan check becomes vacuous.
|
|
28
|
+
* A host that declares `hashOf(text)` still works: the extra argument is ignored.
|
|
25
29
|
*/
|
|
26
|
-
hashOf?(text: string): string;
|
|
30
|
+
hashOf?(text: string, path: string): string;
|
|
31
|
+
/**
|
|
32
|
+
* The read deadline for `path`, in ms, when it differs from the default (5 s). A finite number above 0 is used for that path's read;
|
|
33
|
+
* anything else keeps the default. For slow transforming reads such as document extraction.
|
|
34
|
+
*/
|
|
35
|
+
readTimeoutMs?(path: string): number | undefined;
|
|
27
36
|
}
|
|
28
37
|
|
|
29
38
|
export interface ReviewPlan {
|
|
@@ -76,7 +76,13 @@ export function createPrefetch(c: PrefetchContext): (f: PrefetchFile) => Promise
|
|
|
76
76
|
const lanes = new Lanes(c.extractWidth ?? c.width);
|
|
77
77
|
const extractSlots = createModelLimiter(c.extractWidth ?? c.width);
|
|
78
78
|
const withDeadline = createDeadlines(c.signal);
|
|
79
|
-
const
|
|
79
|
+
const defaultReadMs = c.args.timeouts?.readMs ?? DEFAULT_READ_TIMEOUT_MS;
|
|
80
|
+
/** The source's own read deadline for `path`, when it sets a usable one (finite, above 0). */
|
|
81
|
+
const readOverrideOf = (path: string): number | undefined => {
|
|
82
|
+
const ms = c.args.source.readTimeoutMs?.(path);
|
|
83
|
+
return typeof ms === 'number' && Number.isFinite(ms) && ms > 0 ? ms : undefined;
|
|
84
|
+
};
|
|
85
|
+
const readMsOf = (path: string): number => readOverrideOf(path) ?? defaultReadMs;
|
|
80
86
|
const extractMs = c.args.timeouts?.extractMs ?? DEFAULT_EXTRACT_TIMEOUT_MS;
|
|
81
87
|
// Judging is a later pass in a mechanical review: no sections are wanted from the pool.
|
|
82
88
|
const wantsSections = (pack: KnowledgePack) => !c.args.mechanical && judgesPack(c.args.judgement, pack);
|
|
@@ -90,7 +96,7 @@ export function createPrefetch(c: PrefetchContext): (f: PrefetchFile) => Promise
|
|
|
90
96
|
let doc: SourceDocument | undefined;
|
|
91
97
|
const t0 = Date.now();
|
|
92
98
|
if (!byPool) {
|
|
93
|
-
try { doc = await withDeadline(
|
|
99
|
+
try { doc = await withDeadline(readMsOf(f.path), (signal) => c.args.source.read(f.path, signal)); } catch (error) {
|
|
94
100
|
return { kind: 'read-error', reason: reasonOf(error) };
|
|
95
101
|
}
|
|
96
102
|
parts.readMs = Date.now() - t0;
|
|
@@ -99,11 +105,11 @@ export function createPrefetch(c: PrefetchContext): (f: PrefetchFile) => Promise
|
|
|
99
105
|
if (doc && doc.content.kind === 'text' && isBinaryText(doc.content.text)) return { kind: 'binary' };
|
|
100
106
|
const extraction = await extractSlots.run(async () => {
|
|
101
107
|
held.lane = lanes.take();
|
|
102
|
-
try { return await withDeadline(extractMs
|
|
108
|
+
try { return await withDeadline(byPool ? extractMs + (readOverrideOf(f.path) ?? 0) : extractMs,(signal) => extractFileDetailed({
|
|
103
109
|
rootId: c.rootId, path: f.path, hash: f.hash, ...(doc ? { doc } : {}), packs: c.packs, store: c.store, composed: c.composed,
|
|
104
110
|
knownKeys: c.knownKeys, writeCache: false,
|
|
105
111
|
onTiming: (t) => { parts.lookupMs = t.lookupMs; parts.poolMs = t.poolMs; },
|
|
106
|
-
...(c.args.extractPool ? { pool: c.args.extractPool, signal, wantsSections, ...(byPool ? { readByPool: true } : {}) } : {}),
|
|
112
|
+
...(c.args.extractPool ? { pool: c.args.extractPool, signal, wantsSections, ...(byPool ? { readByPool: true, ...(readOverrideOf(f.path) ? { readMs: readOverrideOf(f.path)! } : {}) } : {}) } : {}),
|
|
107
113
|
})); } finally { lanes.free(held.lane); }
|
|
108
114
|
}, byPool ? c.signal : undefined);
|
|
109
115
|
if (!extraction) return { kind: 'none' };
|
|
@@ -111,7 +117,7 @@ export function createPrefetch(c: PrefetchContext): (f: PrefetchFile) => Promise
|
|
|
111
117
|
// stored, the bytes read must be the bytes planned: hashed once, from the text already in hand. The review writes the
|
|
112
118
|
// extract cache only for an 'extracted' job, so nothing is stored under the stale hash.
|
|
113
119
|
const hashOf = c.args.source.hashOf;
|
|
114
|
-
if (hashOf && doc && doc.content.kind === 'text' && hashOf(doc.content.text) !== f.hash) return { kind: 'failed', reason: CHANGED_SINCE_PLAN, transient: true };
|
|
120
|
+
if (hashOf && doc && doc.content.kind === 'text' && hashOf.call(c.args.source, doc.content.text, f.path) !== f.hash) return { kind: 'failed', reason: CHANGED_SINCE_PLAN, transient: true };
|
|
115
121
|
return { kind: 'extracted', ...(doc ? { doc } : {}), extraction };
|
|
116
122
|
} catch (error) {
|
|
117
123
|
if (error instanceof BinaryContent) return { kind: 'binary' };
|
package/src/knowledge/sources.ts
CHANGED
|
@@ -12,6 +12,7 @@ import { matchGlob } from './partitions.js';
|
|
|
12
12
|
import { compareStr, walkRelative } from './refs.js';
|
|
13
13
|
|
|
14
14
|
/** Default per-file size cap (bytes). */
|
|
15
|
+
// Changing this cap changes which claimed documents are assets (plan.ts), so it requires an EXTRACTOR_VERSION bump.
|
|
15
16
|
export const DEFAULT_MAX_FILE_BYTES = 2 * 1024 * 1024;
|
|
16
17
|
/**
|
|
17
18
|
* Version of the extractors' output. Bump it whenever an extractor emits different nodes,
|
|
@@ -90,7 +91,8 @@ export function isBinaryPath(path: string): boolean {
|
|
|
90
91
|
}
|
|
91
92
|
|
|
92
93
|
/**
|
|
93
|
-
* The ONE decision "this listed file is an asset": binary by extension and not claimed as a document by a host parser.
|
|
94
|
+
* The ONE decision "this listed file is an asset": binary by extension and not claimed as a document by a host parser. The plan passes
|
|
95
|
+
* `claimedAsDocument` false for a claimed document over the size cap (`maxFileBytes`): it stays an asset, as before host parsers existed.
|
|
94
96
|
* An asset is planned, hashed and diffed like any file but never read, extracted or judged (assetFile.ts writes its node).
|
|
95
97
|
*/
|
|
96
98
|
export function isAssetPath(path: string, claimedAsDocument: boolean): boolean {
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Distribution functions for the stats module (PRD 41 Part D / D13): Beta posterior
|
|
3
|
+
* and quantile, Gamma quantile and the exact Poisson (Garwood) interval. Pure and
|
|
4
|
+
* deterministic; the incomplete-beta and incomplete-gamma implementations follow the
|
|
5
|
+
* continued-fraction / series methods (Numerical Recipes), which are stable for the
|
|
6
|
+
* shape ranges Part D uses (posterior counts and sample sizes).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const MAX_ITER = 200;
|
|
10
|
+
const EPS = 3e-14;
|
|
11
|
+
const FPMIN = 1e-300;
|
|
12
|
+
|
|
13
|
+
function logGamma(x: number): number {
|
|
14
|
+
// Lanczos approximation, sufficient for the moderate arguments here.
|
|
15
|
+
const p = [
|
|
16
|
+
676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059,
|
|
17
|
+
12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7,
|
|
18
|
+
];
|
|
19
|
+
if (x < 0.5) {
|
|
20
|
+
return Math.log(Math.PI / Math.sin(Math.PI * x)) - logGamma(1 - x);
|
|
21
|
+
}
|
|
22
|
+
const z = x - 1;
|
|
23
|
+
let sum = 0.99999999999980993;
|
|
24
|
+
for (let i = 0; i < p.length; i++) sum += p[i]! / (z + i + 1);
|
|
25
|
+
const t = z + p.length - 0.5;
|
|
26
|
+
return 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(sum);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function betaCf(a: number, b: number, x: number): number {
|
|
30
|
+
const qab = a + b;
|
|
31
|
+
const qap = a + 1;
|
|
32
|
+
const qam = a - 1;
|
|
33
|
+
let c = 1;
|
|
34
|
+
let d = 1 - (qab * x) / qap;
|
|
35
|
+
if (Math.abs(d) < FPMIN) d = FPMIN;
|
|
36
|
+
d = 1 / d;
|
|
37
|
+
let h = d;
|
|
38
|
+
for (let m = 1; m <= MAX_ITER; m++) {
|
|
39
|
+
const m2 = 2 * m;
|
|
40
|
+
let aa = (m * (b - m) * x) / ((qam + m2) * (a + m2));
|
|
41
|
+
d = 1 + aa * d;
|
|
42
|
+
if (Math.abs(d) < FPMIN) d = FPMIN;
|
|
43
|
+
c = 1 + aa / c;
|
|
44
|
+
if (Math.abs(c) < FPMIN) c = FPMIN;
|
|
45
|
+
d = 1 / d;
|
|
46
|
+
h *= d * c;
|
|
47
|
+
aa = (-(a + m) * (qab + m) * x) / ((a + m2) * (qap + m2));
|
|
48
|
+
d = 1 + aa * d;
|
|
49
|
+
if (Math.abs(d) < FPMIN) d = FPMIN;
|
|
50
|
+
c = 1 + aa / c;
|
|
51
|
+
if (Math.abs(c) < FPMIN) c = FPMIN;
|
|
52
|
+
d = 1 / d;
|
|
53
|
+
const del = d * c;
|
|
54
|
+
h *= del;
|
|
55
|
+
if (Math.abs(del - 1) < EPS) break;
|
|
56
|
+
}
|
|
57
|
+
return h;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Regularized incomplete beta I_x(a, b). */
|
|
61
|
+
export function regularizedIncompleteBeta(x: number, a: number, b: number): number {
|
|
62
|
+
if (x <= 0) return 0;
|
|
63
|
+
if (x >= 1) return 1;
|
|
64
|
+
const bt = Math.exp(
|
|
65
|
+
logGamma(a + b) - logGamma(a) - logGamma(b) + a * Math.log(x) + b * Math.log(1 - x),
|
|
66
|
+
);
|
|
67
|
+
if (x < (a + 1) / (a + b + 2)) return (bt * betaCf(a, b, x)) / a;
|
|
68
|
+
return 1 - (bt * betaCf(b, a, 1 - x)) / b;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Inverse of the regularized incomplete beta, by bisection. Deterministic. */
|
|
72
|
+
export function inverseRegularizedIncompleteBeta(p: number, a: number, b: number): number {
|
|
73
|
+
if (p <= 0) return 0;
|
|
74
|
+
if (p >= 1) return 1;
|
|
75
|
+
let lo = 0;
|
|
76
|
+
let hi = 1;
|
|
77
|
+
for (let i = 0; i < 100; i++) {
|
|
78
|
+
const mid = (lo + hi) / 2;
|
|
79
|
+
if (regularizedIncompleteBeta(mid, a, b) < p) lo = mid;
|
|
80
|
+
else hi = mid;
|
|
81
|
+
}
|
|
82
|
+
return (lo + hi) / 2;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Posterior Beta(α₀ + k, β₀ + n − k): mean and credible quantiles. */
|
|
86
|
+
export interface BetaPosterior {
|
|
87
|
+
alpha: number;
|
|
88
|
+
beta: number;
|
|
89
|
+
mean: number;
|
|
90
|
+
quantile(p: number): number;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function betaPosterior(alpha0: number, beta0: number, k: number, n: number): BetaPosterior {
|
|
94
|
+
const alpha = alpha0 + k;
|
|
95
|
+
const beta = beta0 + (n - k);
|
|
96
|
+
return {
|
|
97
|
+
alpha,
|
|
98
|
+
beta,
|
|
99
|
+
mean: alpha / (alpha + beta),
|
|
100
|
+
quantile: (p) => inverseRegularizedIncompleteBeta(p, alpha, beta),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function gammaQ(a: number, x: number): number {
|
|
105
|
+
// Regularized upper incomplete gamma Q(a, x) via continued fraction.
|
|
106
|
+
let b = x + 1 - a;
|
|
107
|
+
let c = 1 / FPMIN;
|
|
108
|
+
let d = 1 / b;
|
|
109
|
+
let h = d;
|
|
110
|
+
for (let i = 1; i <= MAX_ITER; i++) {
|
|
111
|
+
const an = -i * (i - a);
|
|
112
|
+
b += 2;
|
|
113
|
+
d = an * d + b;
|
|
114
|
+
if (Math.abs(d) < FPMIN) d = FPMIN;
|
|
115
|
+
c = b + an / c;
|
|
116
|
+
if (Math.abs(c) < FPMIN) c = FPMIN;
|
|
117
|
+
d = 1 / d;
|
|
118
|
+
const del = d * c;
|
|
119
|
+
h *= del;
|
|
120
|
+
if (Math.abs(del - 1) < EPS) break;
|
|
121
|
+
}
|
|
122
|
+
return Math.exp(-x + a * Math.log(x) - logGamma(a)) * h;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Regularized lower incomplete gamma P(a, x). */
|
|
126
|
+
export function regularizedIncompleteGamma(a: number, x: number): number {
|
|
127
|
+
if (x <= 0) return 0;
|
|
128
|
+
if (x < a + 1) {
|
|
129
|
+
// Series representation for P.
|
|
130
|
+
let sum = 1 / a;
|
|
131
|
+
let term = sum;
|
|
132
|
+
for (let n = 1; n <= MAX_ITER; n++) {
|
|
133
|
+
term *= x / (a + n);
|
|
134
|
+
sum += term;
|
|
135
|
+
if (Math.abs(term) < Math.abs(sum) * EPS) break;
|
|
136
|
+
}
|
|
137
|
+
return Math.exp(-x + a * Math.log(x) - logGamma(a)) * sum;
|
|
138
|
+
}
|
|
139
|
+
return 1 - gammaQ(a, x);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Gamma(shape, scale) quantile by bisection on the CDF. Deterministic. */
|
|
143
|
+
export function gammaQuantile(p: number, shape: number, scale = 1): number {
|
|
144
|
+
if (p <= 0) return 0;
|
|
145
|
+
if (p >= 1) return Infinity;
|
|
146
|
+
let lo = 0;
|
|
147
|
+
let hi = Math.max(shape * scale * 2, scale, 1e-9);
|
|
148
|
+
while (regularizedIncompleteGamma(shape, hi / scale) < p) {
|
|
149
|
+
hi *= 2;
|
|
150
|
+
if (hi > 1e12) break;
|
|
151
|
+
}
|
|
152
|
+
for (let i = 0; i < 100; i++) {
|
|
153
|
+
const mid = (lo + hi) / 2;
|
|
154
|
+
if (regularizedIncompleteGamma(shape, mid / scale) < p) lo = mid;
|
|
155
|
+
else hi = mid;
|
|
156
|
+
}
|
|
157
|
+
return (lo + hi) / 2;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Exact Poisson confidence interval (Garwood, 1936): the equal-tailed interval
|
|
162
|
+
* built from chi-square / gamma quantiles. `count` events over `exposure`.
|
|
163
|
+
*/
|
|
164
|
+
export function garwoodPoissonInterval(
|
|
165
|
+
count: number,
|
|
166
|
+
exposure = 1,
|
|
167
|
+
confidence = 0.95,
|
|
168
|
+
): { low: number; high: number; rateLow: number; rateHigh: number } {
|
|
169
|
+
const alpha = 1 - confidence;
|
|
170
|
+
// Gamma quantiles with chi-square scaling: χ²_{2k, α} = 2·GammaQuantile(α, k).
|
|
171
|
+
const low =
|
|
172
|
+
count === 0 ? 0 : gammaQuantile(alpha / 2, count) * 2;
|
|
173
|
+
const high = gammaQuantile(1 - alpha / 2, count + 1) * 2;
|
|
174
|
+
return {
|
|
175
|
+
low,
|
|
176
|
+
high,
|
|
177
|
+
rateLow: low / (2 * exposure),
|
|
178
|
+
rateHigh: high / (2 * exposure),
|
|
179
|
+
};
|
|
180
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Estimators for the stats module (PRD 41 Part D / D13): capture–recapture
|
|
3
|
+
* (Chapman / Lincoln–Petersen), Kaplan–Meier with Greenwood variance, the
|
|
4
|
+
* Goel–Okumoto reliability-growth MLE and Gamma–Poisson empirical Bayes. Pure and
|
|
5
|
+
* deterministic; `insufficient-data` is reported, never guessed around.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export type InsufficientData = { status: "insufficient-data" };
|
|
9
|
+
|
|
10
|
+
/** Chapman estimator: n̂ = ((m+1)(c+1)/(r+1)) − 1. Needs r ≥ 1 (and m, c ≥ 3 by the D-done-check). */
|
|
11
|
+
export function chapmanEstimate(
|
|
12
|
+
capturedM: number,
|
|
13
|
+
capturedC: number,
|
|
14
|
+
recapturedR: number,
|
|
15
|
+
): { estimate: number } | InsufficientData {
|
|
16
|
+
if (recapturedR < 1) return { status: "insufficient-data" };
|
|
17
|
+
return { estimate: ((capturedM + 1) * (capturedC + 1)) / (recapturedR + 1) - 1 };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Lincoln–Petersen: n̂ = m·c / r (the biased form; Chapman above is preferred). */
|
|
21
|
+
export function lincolnPetersenEstimate(
|
|
22
|
+
capturedM: number,
|
|
23
|
+
capturedC: number,
|
|
24
|
+
recapturedR: number,
|
|
25
|
+
): { estimate: number } | InsufficientData {
|
|
26
|
+
if (recapturedR < 1) return { status: "insufficient-data" };
|
|
27
|
+
return { estimate: (capturedM * capturedC) / recapturedR };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface KaplanMeierResult {
|
|
31
|
+
/** Survival probability after the last event time (the "current" survival). */
|
|
32
|
+
survival: number;
|
|
33
|
+
/** Greenwood variance of that survival. */
|
|
34
|
+
variance: number;
|
|
35
|
+
/** (time, survival) steps at each distinct event time. */
|
|
36
|
+
curve: Array<{ time: number; survival: number }>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Kaplan–Meier product-limit estimator on (time, event) rows; censored rows have event = 0. */
|
|
40
|
+
export function kaplanMeier(rows: readonly { time: number; event: 0 | 1 }[]): KaplanMeierResult {
|
|
41
|
+
const times = [...new Set(rows.map((r) => r.time))].sort((a, b) => a - b);
|
|
42
|
+
let survival = 1;
|
|
43
|
+
let greenwood = 0;
|
|
44
|
+
const curve: Array<{ time: number; survival: number }> = [];
|
|
45
|
+
for (const t of times) {
|
|
46
|
+
const atRisk = rows.filter((r) => r.time >= t).length;
|
|
47
|
+
const events = rows.filter((r) => r.time === t && r.event === 1).length;
|
|
48
|
+
if (atRisk > 0 && events > 0) {
|
|
49
|
+
survival *= 1 - events / atRisk;
|
|
50
|
+
if (atRisk - events > 0) greenwood += events / (atRisk * (atRisk - events));
|
|
51
|
+
}
|
|
52
|
+
curve.push({ time: t, survival });
|
|
53
|
+
}
|
|
54
|
+
return { survival, variance: survival * survival * greenwood, curve };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Goel–Okumoto NHPP MLE: mean failures μ(t) = a(1 − e^{−bt}). a is solved in
|
|
59
|
+
* closed form given b; b is refined by bisection on the score equation
|
|
60
|
+
* Σ tᵢ = n/b − n·t̄·e^{−b·t̄}/(1 − e^{−b·t̄}). Needs n ≥ 2 distinct times.
|
|
61
|
+
*/
|
|
62
|
+
export function goelOkumotoMLE(
|
|
63
|
+
times: readonly number[],
|
|
64
|
+
): { a: number; b: number } | InsufficientData {
|
|
65
|
+
const sorted = [...times].sort((a, b) => a - b);
|
|
66
|
+
const n = sorted.length;
|
|
67
|
+
if (n < 2) return { status: "insufficient-data" };
|
|
68
|
+
const tMax = sorted[n - 1]!;
|
|
69
|
+
const tMean = sorted.reduce((a, b) => a + b, 0) / n;
|
|
70
|
+
const score = (b: number) => {
|
|
71
|
+
if (b <= 0) return Infinity;
|
|
72
|
+
const denom = 1 - Math.exp(-b * tMax);
|
|
73
|
+
return n / b - (n * tMean * Math.exp(-b * tMean)) / denom;
|
|
74
|
+
};
|
|
75
|
+
let lo = 1e-9;
|
|
76
|
+
let hi = 1;
|
|
77
|
+
while (score(hi) > 0 && hi < 1e6) hi *= 2;
|
|
78
|
+
for (let i = 0; i < 100; i++) {
|
|
79
|
+
const mid = (lo + hi) / 2;
|
|
80
|
+
if (score(mid) > 0) lo = mid;
|
|
81
|
+
else hi = mid;
|
|
82
|
+
}
|
|
83
|
+
const b = (lo + hi) / 2;
|
|
84
|
+
const a = n / (1 - Math.exp(-b * tMax));
|
|
85
|
+
return { a, b };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Gamma–Poisson empirical Bayes rate posterior. Prior Gamma(α₀, β₀) over the rate;
|
|
90
|
+
* observing `count` events over `exposure` gives Gamma(α₀ + count, β₀ + exposure).
|
|
91
|
+
*/
|
|
92
|
+
export function gammaPoissonPosterior(
|
|
93
|
+
alpha0: number,
|
|
94
|
+
beta0: number,
|
|
95
|
+
count: number,
|
|
96
|
+
exposure: number,
|
|
97
|
+
): { alpha: number; beta: number; mean: number; variance: number } {
|
|
98
|
+
const alpha = alpha0 + count;
|
|
99
|
+
const beta = beta0 + exposure;
|
|
100
|
+
return { alpha, beta, mean: alpha / beta, variance: alpha / (beta * beta) };
|
|
101
|
+
}
|