accuracy-claim-kit 0.0.0-stage → 0.1.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.
@@ -0,0 +1,186 @@
1
+ import type { AgreementResult, AgreementStatistic } from './agreement.js';
2
+ import type { WilsonInterval } from './wilson.js';
3
+ /**
4
+ * Proportions the kit can judge, with what `sample.n` counts for each:
5
+ * accuracy (items checked), error-rate (items checked), precision (predicted
6
+ * positives; `correct` are the true positives), recall (actual positives;
7
+ * `correct` are the ones found), false-positive-rate (actual negatives;
8
+ * `errors` are the false positives), false-negative-rate (actual positives;
9
+ * `errors` are the misses), specificity (actual negatives; `correct` are the
10
+ * true negatives), npv (predicted negatives; `correct` are the true negatives).
11
+ * The rest are the same proportions under the names diagnostic tables use, so
12
+ * the statement speaks in the claimant's words: sensitivity and ppa are recall,
13
+ * ppv is precision, npa is specificity, and opa (overall percent agreement with
14
+ * a comparator) is accuracy.
15
+ */
16
+ export type ClaimMetric = 'accuracy' | 'error-rate' | 'precision' | 'recall' | 'false-positive-rate' | 'false-negative-rate' | 'specificity' | 'npv' | 'sensitivity' | 'ppa' | 'ppv' | 'npa' | 'opa';
17
+ /** Metrics the kit knows but refuses (`metric-not-supported`) instead of throwing. */
18
+ export type UnsupportedMetric = 'f1' | 'auc' | 'roc-auc' | 'wer' | 'cer' | 'bleu' | 'rouge' | 'map' | 'composite' | 'other';
19
+ /**
20
+ * Where the labels came from. `by-construction` means the ground truth was fixed by how
21
+ * the data was made (text from a known generator, labels taken from a corpus's language);
22
+ * it is accepted like `human` and is a declaration the kit cannot verify. `automated` means a deterministic procedure with
23
+ * known correct answers (a test suite, an exact search), never a model's judgment.
24
+ */
25
+ export type LabelSource = 'human' | 'automated' | 'by-construction' | 'model' | 'mixed' | 'unknown';
26
+ /**
27
+ * How the items were chosen. `complete` means the sample is the whole of a
28
+ * fixed, named set (a benchmark): the count is exact and no interval is used.
29
+ * `held-out-split` is the same for a fixed named test split. `cross-validation`
30
+ * is judged like `random`; folds are not independent, so the interval is optimistic.
31
+ */
32
+ export type SamplingMethod = 'random' | 'stratified' | 'ranked' | 'convenience' | 'unknown' | 'complete' | 'held-out-split' | 'cross-validation';
33
+ export interface Claim {
34
+ /**
35
+ * A judged metric in lower case, or the name of a metric the kit refuses. A refused name is
36
+ * matched in any case at run time; the types accept the lower-case (`f1`), upper-case (`F1`)
37
+ * and capitalized (`Auc`) forms people write. The result's `metric` is the lower-case name.
38
+ */
39
+ metric: ClaimMetric | UnsupportedMetric | Uppercase<UnsupportedMetric> | Capitalize<UnsupportedMetric>;
40
+ /** The claimed rate as a proportion from 0 to 1 (0.998 means 99.8%). */
41
+ value: number;
42
+ /**
43
+ * How the claim is printed, as a percent string such as "99.8%". When given,
44
+ * it must agree with `value` to the printed precision, and its number of
45
+ * decimals is checked against what the interval can support.
46
+ */
47
+ display?: string | undefined;
48
+ /**
49
+ * The claim's wording. For `sampling: 'complete'` it must name the benchmark, or the
50
+ * claim is refused as an unscoped general claim. On every path a figure in it that is
51
+ * not the figure judged is flagged (`text-figure-differs`), never judged. At most 2000 characters.
52
+ */
53
+ text?: string | undefined;
54
+ }
55
+ /**
56
+ * Counts for a sample. Give `correct` or `errors` (or both, if they add up to n).
57
+ * Both metrics accept either field.
58
+ */
59
+ export interface SampleCounts {
60
+ n: number;
61
+ correct?: number | undefined;
62
+ errors?: number | undefined;
63
+ }
64
+ /** A reported agreement statistic: a result from this kit, or a plain {statistic, value}. */
65
+ export type AgreementInput = AgreementResult | {
66
+ statistic: AgreementStatistic;
67
+ value: number;
68
+ status?: 'defined' | undefined;
69
+ n?: number | undefined;
70
+ };
71
+ export interface LabelProvenance {
72
+ source: LabelSource;
73
+ /** Number of independent human raters, if known. */
74
+ raters?: number | undefined;
75
+ agreement?: AgreementInput | undefined;
76
+ }
77
+ export interface Stratum extends SampleCounts {
78
+ name: string;
79
+ }
80
+ export interface Retractions {
81
+ /** Labels or records known to have been retracted. */
82
+ count: number;
83
+ /** Whether those retracted items are counted in the sample (as failures where they were wrong). */
84
+ includedInSample: boolean;
85
+ }
86
+ /** The fixed set a `complete` claim is about. */
87
+ export interface Benchmark {
88
+ /** Name of the set, as the claim text must mention it (at most 200 characters). */
89
+ name: string;
90
+ }
91
+ /** What the claim says it covers, and what was actually evaluated. Compared after Unicode and case folding. */
92
+ export interface PopulationScope {
93
+ claimed: string;
94
+ evaluated: string;
95
+ }
96
+ export interface AccuracyClaimInput {
97
+ claim: Claim;
98
+ /** Omit it (or leave out n and the counts) when the source does not say; the result is refused with `n-undisclosed`. */
99
+ sample?: SampleCounts | undefined;
100
+ provenance: LabelProvenance;
101
+ sampling: SamplingMethod;
102
+ strata?: readonly Stratum[] | undefined;
103
+ retractions?: Retractions | undefined;
104
+ /** Required with `sampling: 'complete'` or `'held-out-split'`; rejected with any other sampling. */
105
+ benchmark?: Benchmark | undefined;
106
+ /** Claimed versus evaluated population; a mismatch is refused. */
107
+ population?: PopulationScope | undefined;
108
+ /** Date the evaluation was run, "YYYY-MM-DD". Used with `options.maxAgeDays`. */
109
+ evaluatedAt?: string | undefined;
110
+ }
111
+ export interface AssessOptions {
112
+ /** Two-sided confidence level for the Wilson interval, from 0.5 up to (not including) 1. Default 0.95. A lower level throws: it is almost always a typo. */
113
+ confidence?: number | undefined;
114
+ /** Smallest sample size that can get a verdict. Default 30. Whole number, at least 1. */
115
+ minN?: number | undefined;
116
+ /** If given, the supplied agreement statistic must be at least this value (from -1 to 1). */
117
+ minAgreement?: number | undefined;
118
+ /** Refuse an evaluation older than this many days (whole number, 0 or more). Needs `now`. */
119
+ maxAgeDays?: number | undefined;
120
+ /** Reference date "YYYY-MM-DD" for `maxAgeDays`. The kit never reads a clock. */
121
+ now?: string | undefined;
122
+ /**
123
+ * Make excess printed precision (`precision-too-fine`) change a supported claim to
124
+ * overstated. By default it is only noted. Implied by `conservative`.
125
+ */
126
+ strictPrecision?: boolean | undefined;
127
+ /** Restore the strict rule: supported only at or below the interval's conservative end. Default false. */
128
+ conservative?: boolean | undefined;
129
+ /** Refuse a claim that does not declare `population`. Default false. */
130
+ requireScope?: boolean | undefined;
131
+ }
132
+ export type AccuracyVerdict = 'supported' | 'overstated' | 'contradicted' | 'refused';
133
+ export type ReasonCode = 'no-human-labels' | 'unknown-label-source' | 'mixed-label-source' | 'ranked-sample' | 'convenience-sample' | 'unknown-sampling' | 'sample-too-small' | 'merged-strata-differ' | 'retractions-not-included' | 'agreement-missing' | 'agreement-undefined' | 'agreement-below-minimum' | 'agreement-sample-too-small' | 'metric-not-supported' | 'n-undisclosed' | 'stratified-without-strata' | 'benchmark-unnamed' | 'claim-not-scoped-to-benchmark' | 'evaluation-date-missing' | 'evaluation-stale' | 'scope-mismatch' | 'scope-undeclared' | 'claim-outside-interval' | 'claim-differs-from-count' | 'claim-beyond-conservative-bound' | 'precision-too-fine' | 'claim-within-bound' | 'census-matches-count' | 'matches-observed-rate' | 'claim-worse-than-counts' | 'strata-not-reweighted' | 'text-figure-differs';
134
+ /** Whether an optional check ran for this call. */
135
+ export type GateStatus = 'applied' | 'not-supplied';
136
+ /**
137
+ * Which optional checks the call ran, so a check that was left out is visible
138
+ * in the result. `retractions`: a `retractions` block was supplied. `scope`: a
139
+ * `population` was supplied. `age`: `options.maxAgeDays` was set. `agreement`:
140
+ * `options.minAgreement` was set, or the supplied statistic carries its `n` so
141
+ * its size was checked (a hand-written statistic with no `n` that is only
142
+ * echoed is not a check). `strata`: `strata` were supplied for a sample (a complete set does
143
+ * not compare strata).
144
+ */
145
+ export interface GateChecks {
146
+ retractions: GateStatus;
147
+ scope: GateStatus;
148
+ age: GateStatus;
149
+ agreement: GateStatus;
150
+ strata: GateStatus;
151
+ }
152
+ export interface AccuracyAssessment {
153
+ verdict: AccuracyVerdict;
154
+ /** At least one code. A refusal lists every failed precondition. */
155
+ reasons: ReasonCode[];
156
+ /** One plain sentence per reason, in the same order. */
157
+ explanation: string[];
158
+ metric: ClaimMetric | UnsupportedMetric;
159
+ /** The claim's `value` as supplied. */
160
+ claimed: number;
161
+ /**
162
+ * The figure that was judged: the more favorable of `value` and the parsed
163
+ * `display` (the higher for accuracy, the lower for error rate). Equal to
164
+ * `claimed` when there is no display or the value is already the more favorable, except that
165
+ * a value within float noise of 0 or 1 (ten 0.1s added up) is the absolute claim and is reported as 0 or 1.
166
+ */
167
+ assessedValue: number;
168
+ /** Items in the sample; null when the counts were not disclosed. */
169
+ n: number | null;
170
+ /** How the printed `display` was read, or null when there was none. */
171
+ parsedDisplay: {
172
+ form: 'percent' | 'approx' | 'floor' | 'ceiling' | 'range' | 'one-in-n';
173
+ figure: number;
174
+ decimals: number | null;
175
+ } | null;
176
+ /** Which optional checks ran: `applied`, or `not-supplied` when the input or option that switches the check on was left out. */
177
+ checks: GateChecks;
178
+ /** `wilson-interval`: judged against an interval. `census`: compared with the exact count of a complete set. `none`: refused. */
179
+ basis: 'wilson-interval' | 'census' | 'none';
180
+ /** Wilson interval for the claimed metric (accuracy, or error rate). Null when refused or for a census. */
181
+ interval: WilsonInterval | null;
182
+ /** The end of the interval a claim should not beat: lower for accuracy, upper for error rate. Null when refused. */
183
+ conservativeBound: number | null;
184
+ /** Plain text that describes the evidence only. For a refusal it says why no figure can be given. */
185
+ suggestedStatement: string;
186
+ }
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { AgreementResult, AgreementStatistic } from './agreement.js'\nimport type { WilsonInterval } from './wilson.js'\n\n/**\n * Proportions the kit can judge, with what `sample.n` counts for each:\n * accuracy (items checked), error-rate (items checked), precision (predicted\n * positives; `correct` are the true positives), recall (actual positives;\n * `correct` are the ones found), false-positive-rate (actual negatives;\n * `errors` are the false positives), false-negative-rate (actual positives;\n * `errors` are the misses), specificity (actual negatives; `correct` are the\n * true negatives), npv (predicted negatives; `correct` are the true negatives).\n * The rest are the same proportions under the names diagnostic tables use, so\n * the statement speaks in the claimant's words: sensitivity and ppa are recall,\n * ppv is precision, npa is specificity, and opa (overall percent agreement with\n * a comparator) is accuracy.\n */\nexport type ClaimMetric =\n | 'accuracy'\n | 'error-rate'\n | 'precision'\n | 'recall'\n | 'false-positive-rate'\n | 'false-negative-rate'\n | 'specificity'\n | 'npv'\n | 'sensitivity'\n | 'ppa'\n | 'ppv'\n | 'npa'\n | 'opa'\n/** Metrics the kit knows but refuses (`metric-not-supported`) instead of throwing. */\nexport type UnsupportedMetric =\n | 'f1' | 'auc' | 'roc-auc' | 'wer' | 'cer' | 'bleu' | 'rouge' | 'map' | 'composite' | 'other'\n/**\n * Where the labels came from. `by-construction` means the ground truth was fixed by how\n * the data was made (text from a known generator, labels taken from a corpus's language);\n * it is accepted like `human` and is a declaration the kit cannot verify. `automated` means a deterministic procedure with\n * known correct answers (a test suite, an exact search), never a model's judgment.\n */\nexport type LabelSource = 'human' | 'automated' | 'by-construction' | 'model' | 'mixed' | 'unknown'\n/**\n * How the items were chosen. `complete` means the sample is the whole of a\n * fixed, named set (a benchmark): the count is exact and no interval is used.\n * `held-out-split` is the same for a fixed named test split. `cross-validation`\n * is judged like `random`; folds are not independent, so the interval is optimistic.\n */\nexport type SamplingMethod =\n | 'random'\n | 'stratified'\n | 'ranked'\n | 'convenience'\n | 'unknown'\n | 'complete'\n | 'held-out-split'\n | 'cross-validation'\n\nexport interface Claim {\n /**\n * A judged metric in lower case, or the name of a metric the kit refuses. A refused name is\n * matched in any case at run time; the types accept the lower-case (`f1`), upper-case (`F1`)\n * and capitalized (`Auc`) forms people write. The result's `metric` is the lower-case name.\n */\n metric: ClaimMetric | UnsupportedMetric | Uppercase<UnsupportedMetric> | Capitalize<UnsupportedMetric>\n /** The claimed rate as a proportion from 0 to 1 (0.998 means 99.8%). */\n value: number\n /**\n * How the claim is printed, as a percent string such as \"99.8%\". When given,\n * it must agree with `value` to the printed precision, and its number of\n * decimals is checked against what the interval can support.\n */\n display?: string | undefined\n /**\n * The claim's wording. For `sampling: 'complete'` it must name the benchmark, or the\n * claim is refused as an unscoped general claim. On every path a figure in it that is\n * not the figure judged is flagged (`text-figure-differs`), never judged. At most 2000 characters.\n */\n text?: string | undefined\n}\n\n/**\n * Counts for a sample. Give `correct` or `errors` (or both, if they add up to n).\n * Both metrics accept either field.\n */\nexport interface SampleCounts {\n n: number\n correct?: number | undefined\n errors?: number | undefined\n}\n\n/** A reported agreement statistic: a result from this kit, or a plain {statistic, value}. */\nexport type AgreementInput =\n | AgreementResult\n | { statistic: AgreementStatistic; value: number; status?: 'defined' | undefined; n?: number | undefined }\n\nexport interface LabelProvenance {\n source: LabelSource\n /** Number of independent human raters, if known. */\n raters?: number | undefined\n agreement?: AgreementInput | undefined\n}\n\nexport interface Stratum extends SampleCounts {\n name: string\n}\n\nexport interface Retractions {\n /** Labels or records known to have been retracted. */\n count: number\n /** Whether those retracted items are counted in the sample (as failures where they were wrong). */\n includedInSample: boolean\n}\n\n/** The fixed set a `complete` claim is about. */\nexport interface Benchmark {\n /** Name of the set, as the claim text must mention it (at most 200 characters). */\n name: string\n}\n\n/** What the claim says it covers, and what was actually evaluated. Compared after Unicode and case folding. */\nexport interface PopulationScope {\n claimed: string\n evaluated: string\n}\n\nexport interface AccuracyClaimInput {\n claim: Claim\n /** Omit it (or leave out n and the counts) when the source does not say; the result is refused with `n-undisclosed`. */\n sample?: SampleCounts | undefined\n provenance: LabelProvenance\n sampling: SamplingMethod\n strata?: readonly Stratum[] | undefined\n retractions?: Retractions | undefined\n /** Required with `sampling: 'complete'` or `'held-out-split'`; rejected with any other sampling. */\n benchmark?: Benchmark | undefined\n /** Claimed versus evaluated population; a mismatch is refused. */\n population?: PopulationScope | undefined\n /** Date the evaluation was run, \"YYYY-MM-DD\". Used with `options.maxAgeDays`. */\n evaluatedAt?: string | undefined\n}\n\nexport interface AssessOptions {\n /** Two-sided confidence level for the Wilson interval, from 0.5 up to (not including) 1. Default 0.95. A lower level throws: it is almost always a typo. */\n confidence?: number | undefined\n /** Smallest sample size that can get a verdict. Default 30. Whole number, at least 1. */\n minN?: number | undefined\n /** If given, the supplied agreement statistic must be at least this value (from -1 to 1). */\n minAgreement?: number | undefined\n /** Refuse an evaluation older than this many days (whole number, 0 or more). Needs `now`. */\n maxAgeDays?: number | undefined\n /** Reference date \"YYYY-MM-DD\" for `maxAgeDays`. The kit never reads a clock. */\n now?: string | undefined\n /**\n * Make excess printed precision (`precision-too-fine`) change a supported claim to\n * overstated. By default it is only noted. Implied by `conservative`.\n */\n strictPrecision?: boolean | undefined\n /** Restore the strict rule: supported only at or below the interval's conservative end. Default false. */\n conservative?: boolean | undefined\n /** Refuse a claim that does not declare `population`. Default false. */\n requireScope?: boolean | undefined\n}\n\nexport type AccuracyVerdict = 'supported' | 'overstated' | 'contradicted' | 'refused'\n\nexport type ReasonCode =\n // refused\n | 'no-human-labels'\n | 'unknown-label-source'\n | 'mixed-label-source'\n | 'ranked-sample'\n | 'convenience-sample'\n | 'unknown-sampling'\n | 'sample-too-small'\n | 'merged-strata-differ'\n | 'retractions-not-included'\n | 'agreement-missing'\n | 'agreement-undefined'\n | 'agreement-below-minimum'\n | 'agreement-sample-too-small'\n | 'metric-not-supported'\n | 'n-undisclosed'\n | 'stratified-without-strata'\n | 'benchmark-unnamed'\n | 'claim-not-scoped-to-benchmark'\n | 'evaluation-date-missing'\n | 'evaluation-stale'\n | 'scope-mismatch'\n | 'scope-undeclared'\n // contradicted\n | 'claim-outside-interval'\n | 'claim-differs-from-count'\n // overstated\n | 'claim-beyond-conservative-bound'\n | 'precision-too-fine'\n // supported\n | 'claim-within-bound'\n | 'census-matches-count'\n | 'matches-observed-rate'\n // informational, never changes the verdict\n | 'claim-worse-than-counts'\n | 'strata-not-reweighted'\n | 'text-figure-differs'\n\n/** Whether an optional check ran for this call. */\nexport type GateStatus = 'applied' | 'not-supplied'\n\n/**\n * Which optional checks the call ran, so a check that was left out is visible\n * in the result. `retractions`: a `retractions` block was supplied. `scope`: a\n * `population` was supplied. `age`: `options.maxAgeDays` was set. `agreement`:\n * `options.minAgreement` was set, or the supplied statistic carries its `n` so\n * its size was checked (a hand-written statistic with no `n` that is only\n * echoed is not a check). `strata`: `strata` were supplied for a sample (a complete set does\n * not compare strata).\n */\nexport interface GateChecks {\n retractions: GateStatus\n scope: GateStatus\n age: GateStatus\n agreement: GateStatus\n strata: GateStatus\n}\n\nexport interface AccuracyAssessment {\n verdict: AccuracyVerdict\n /** At least one code. A refusal lists every failed precondition. */\n reasons: ReasonCode[]\n /** One plain sentence per reason, in the same order. */\n explanation: string[]\n metric: ClaimMetric | UnsupportedMetric\n /** The claim's `value` as supplied. */\n claimed: number\n /**\n * The figure that was judged: the more favorable of `value` and the parsed\n * `display` (the higher for accuracy, the lower for error rate). Equal to\n * `claimed` when there is no display or the value is already the more favorable, except that\n * a value within float noise of 0 or 1 (ten 0.1s added up) is the absolute claim and is reported as 0 or 1.\n */\n assessedValue: number\n /** Items in the sample; null when the counts were not disclosed. */\n n: number | null\n /** How the printed `display` was read, or null when there was none. */\n parsedDisplay: { form: 'percent' | 'approx' | 'floor' | 'ceiling' | 'range' | 'one-in-n'; figure: number; decimals: number | null } | null\n /** Which optional checks ran: `applied`, or `not-supplied` when the input or option that switches the check on was left out. */\n checks: GateChecks\n /** `wilson-interval`: judged against an interval. `census`: compared with the exact count of a complete set. `none`: refused. */\n basis: 'wilson-interval' | 'census' | 'none'\n /** Wilson interval for the claimed metric (accuracy, or error rate). Null when refused or for a census. */\n interval: WilsonInterval | null\n /** The end of the interval a claim should not beat: lower for accuracy, upper for error rate. Null when refused. */\n conservativeBound: number | null\n /** Plain text that describes the evidence only. For a refusal it says why no figure can be given. */\n suggestedStatement: string\n}\n"]}
@@ -0,0 +1,44 @@
1
+ export declare const MAX_COUNT: number;
2
+ /**
3
+ * Most elements read from one caller-supplied array (pairs or strata). A
4
+ * Proxy can claim any length, and a loop that trusts it can run for as long as
5
+ * the caller likes, so a length is checked before it is used.
6
+ */
7
+ export declare const MAX_ITEMS = 10000000;
8
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
9
+ export declare function requireRecord(value: unknown, name: string): Record<string, unknown>;
10
+ /**
11
+ * Throws TypeError for a built-in object that is not a plain record (a Map, a
12
+ * boxed Number or String, a Date, a Set). Such a value has no own keys, so for
13
+ * an object whose fields are all optional and whose absence turns a check off
14
+ * (the options) it would read as "nothing was asked for" and fail open. Class
15
+ * instances, null-prototype objects, Proxies of plain objects and objects from
16
+ * another realm are plain. The caller's Symbol.toStringTag is read once here.
17
+ */
18
+ export declare function assertPlainObject(value: Record<string, unknown>, name: string): void;
19
+ /** Reads a whole number in [min, MAX_COUNT]. Normalizes -0 to 0. */
20
+ export declare function readCount(value: unknown, name: string, min?: number): number;
21
+ /** Validates a captured `.length`: a whole number from 0 to MAX_ITEMS. */
22
+ export declare function readLength(value: unknown, name: string): number;
23
+ /** Reads a finite number in [min, max], inclusive. Normalizes -0 to 0. */
24
+ export declare function readFiniteInRange(value: unknown, name: string, min: number, max: number): number;
25
+ /** Reads a number strictly between 0 and 1 (a confidence level). */
26
+ export declare function readOpenUnit(value: unknown, name: string): number;
27
+ /**
28
+ * Makes a caller-supplied string safe to quote in a message: every control
29
+ * (a newline, an escape), line separator, bidirectional or invisible character
30
+ * is written as its code point (\u000A), so a message can never carry a forged
31
+ * log line or a terminal escape, then the text is cut without splitting a
32
+ * surrogate pair.
33
+ */
34
+ export declare function clip(text: string, max?: number): string;
35
+ /** The allowed key a misspelled `key` most likely meant, or undefined when nothing is close. */
36
+ export declare function nearestKey(key: string, allowed: readonly string[]): string | undefined;
37
+ /**
38
+ * Throws a TypeError naming the first own enumerable key of `value` that is not
39
+ * in `allowed`, with the closest allowed key when there is one. A misspelled
40
+ * optional key ("retraction", "maxAgeDay") would otherwise be ignored and turn
41
+ * the check it configures off. Keys are listed once and no value is read, so a
42
+ * getter is never triggered; inherited and symbol keys are not looked at.
43
+ */
44
+ export declare function assertKnownKeys(value: Record<string, unknown>, allowed: readonly string[], label: string): void;
@@ -0,0 +1,156 @@
1
+ // Small input readers shared by every public function. Wrong runtime type
2
+ // throws TypeError; right type but unusable value throws RangeError. Nothing
3
+ // here coerces: a string "5" is not a count, a Number object is not a number.
4
+ import { codeLabel, MESSAGE_UNSAFE } from './text.js';
5
+ export const MAX_COUNT = Number.MAX_SAFE_INTEGER;
6
+ /**
7
+ * Most elements read from one caller-supplied array (pairs or strata). A
8
+ * Proxy can claim any length, and a loop that trusts it can run for as long as
9
+ * the caller likes, so a length is checked before it is used.
10
+ */
11
+ export const MAX_ITEMS = 10_000_000;
12
+ export function isRecord(value) {
13
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
14
+ }
15
+ export function requireRecord(value, name) {
16
+ if (!isRecord(value)) {
17
+ throw new TypeError(`${name} must be a plain object`);
18
+ }
19
+ return value;
20
+ }
21
+ /**
22
+ * Throws TypeError for a built-in object that is not a plain record (a Map, a
23
+ * boxed Number or String, a Date, a Set). Such a value has no own keys, so for
24
+ * an object whose fields are all optional and whose absence turns a check off
25
+ * (the options) it would read as "nothing was asked for" and fail open. Class
26
+ * instances, null-prototype objects, Proxies of plain objects and objects from
27
+ * another realm are plain. The caller's Symbol.toStringTag is read once here.
28
+ */
29
+ export function assertPlainObject(value, name) {
30
+ const tag = Object.prototype.toString.call(value);
31
+ if (tag !== '[object Object]')
32
+ throw new TypeError(`${name} must be a plain object, got ${clip(tag)}`);
33
+ }
34
+ /** Reads a whole number in [min, MAX_COUNT]. Normalizes -0 to 0. */
35
+ export function readCount(value, name, min = 0) {
36
+ if (typeof value !== 'number') {
37
+ throw new TypeError(`${name} must be a number`);
38
+ }
39
+ if (!Number.isFinite(value) || !Number.isInteger(value)) {
40
+ throw new RangeError(`${name} must be a whole number, got ${String(value)}`);
41
+ }
42
+ if (value < min || value > MAX_COUNT) {
43
+ throw new RangeError(`${name} must be between ${min} and ${MAX_COUNT}, got ${String(value)}`);
44
+ }
45
+ return value + 0; // turns -0 into 0
46
+ }
47
+ /** Validates a captured `.length`: a whole number from 0 to MAX_ITEMS. */
48
+ export function readLength(value, name) {
49
+ if (typeof value !== 'number') {
50
+ throw new TypeError(`${name}.length must be a number`);
51
+ }
52
+ if (!Number.isInteger(value) || value < 0 || value > MAX_ITEMS) {
53
+ throw new RangeError(`${name}.length must be a whole number from 0 to ${MAX_ITEMS}, got ${String(value)}`);
54
+ }
55
+ return value + 0;
56
+ }
57
+ /** Reads a finite number in [min, max], inclusive. Normalizes -0 to 0. */
58
+ export function readFiniteInRange(value, name, min, max) {
59
+ if (typeof value !== 'number') {
60
+ throw new TypeError(`${name} must be a number`);
61
+ }
62
+ if (!Number.isFinite(value) || value < min || value > max) {
63
+ throw new RangeError(`${name} must be a finite number between ${min} and ${max}, got ${String(value)}`);
64
+ }
65
+ return value + 0;
66
+ }
67
+ /** Reads a number strictly between 0 and 1 (a confidence level). */
68
+ export function readOpenUnit(value, name) {
69
+ if (typeof value !== 'number') {
70
+ throw new TypeError(`${name} must be a number`);
71
+ }
72
+ if (!Number.isFinite(value) || !(value > 0) || !(value < 1)) {
73
+ throw new RangeError(`${name} must be a number strictly between 0 and 1, got ${String(value)}`);
74
+ }
75
+ return value;
76
+ }
77
+ /**
78
+ * Makes a caller-supplied string safe to quote in a message: every control
79
+ * (a newline, an escape), line separator, bidirectional or invisible character
80
+ * is written as its code point (\u000A), so a message can never carry a forged
81
+ * log line or a terminal escape, then the text is cut without splitting a
82
+ * surrogate pair.
83
+ */
84
+ export function clip(text, max = 60) {
85
+ const plain = text.replace(MESSAGE_UNSAFE, (char) => `\\u${codeLabel(char).slice(2)}`);
86
+ if (plain.length <= max)
87
+ return plain;
88
+ let end = max;
89
+ const code = plain.charCodeAt(end - 1);
90
+ if (code >= 0xd800 && code <= 0xdbff)
91
+ end -= 1;
92
+ return `${plain.slice(0, end)}...`;
93
+ }
94
+ /** Keys longer than this are reported but never searched for a near match. */
95
+ const MAX_SUGGEST_LENGTH = 64;
96
+ /** Lower case with everything but letters and digits removed, so "min_agreement" and "minAgreement" compare equal. */
97
+ function simplify(text) {
98
+ return text.toLowerCase().replace(/[^\p{L}\p{N}]/gu, '');
99
+ }
100
+ /** Levenshtein distance between two short strings. */
101
+ function editDistance(a, b) {
102
+ let previous = Array.from({ length: b.length + 1 }, (_, j) => j);
103
+ for (let i = 1; i <= a.length; i++) {
104
+ const row = [i];
105
+ for (let j = 1; j <= b.length; j++) {
106
+ const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1;
107
+ row.push(Math.min(previous[j] + 1, row[j - 1] + 1, previous[j - 1] + cost));
108
+ }
109
+ previous = row;
110
+ }
111
+ return previous[b.length];
112
+ }
113
+ /** The allowed key a misspelled `key` most likely meant, or undefined when nothing is close. */
114
+ export function nearestKey(key, allowed) {
115
+ if (key.length > MAX_SUGGEST_LENGTH)
116
+ return undefined;
117
+ const wanted = simplify(key);
118
+ if (wanted === '')
119
+ return undefined;
120
+ let best;
121
+ let bestScore = Infinity;
122
+ for (const candidate of allowed) {
123
+ const other = simplify(candidate);
124
+ const raw = editDistance(wanted, other);
125
+ let distance = raw;
126
+ // "maxAge" for "maxAgeDays": one name inside the other
127
+ if (Math.min(wanted.length, other.length) >= 5 && (wanted.includes(other) || other.includes(wanted))) {
128
+ distance = Math.min(distance, 1);
129
+ }
130
+ const limit = wanted.length <= 4 ? 1 : 2;
131
+ // the closest wins; a tie goes to the one that differs least as written
132
+ const score = distance * 1000 + raw;
133
+ if (distance <= limit && score < bestScore) {
134
+ best = candidate;
135
+ bestScore = score;
136
+ }
137
+ }
138
+ return best;
139
+ }
140
+ /**
141
+ * Throws a TypeError naming the first own enumerable key of `value` that is not
142
+ * in `allowed`, with the closest allowed key when there is one. A misspelled
143
+ * optional key ("retraction", "maxAgeDay") would otherwise be ignored and turn
144
+ * the check it configures off. Keys are listed once and no value is read, so a
145
+ * getter is never triggered; inherited and symbol keys are not looked at.
146
+ */
147
+ export function assertKnownKeys(value, allowed, label) {
148
+ for (const key of Object.keys(value)) {
149
+ if (allowed.includes(key))
150
+ continue;
151
+ const near = nearestKey(key, allowed);
152
+ const hint = near === undefined ? '.' : `; did you mean "${near}"?`;
153
+ throw new TypeError(`${label} has an unknown key "${clip(key)}"${hint} Allowed keys: ${allowed.join(', ')}.`);
154
+ }
155
+ }
156
+ //# sourceMappingURL=validate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate.js","sourceRoot":"","sources":["../src/validate.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,6EAA6E;AAC7E,8EAA8E;AAE9E,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,WAAW,CAAA;AAErD,MAAM,CAAC,MAAM,SAAS,GAAG,MAAM,CAAC,gBAAgB,CAAA;AAEhD;;;;GAIG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,UAAU,CAAA;AAEnC,MAAM,UAAU,QAAQ,CAAC,KAAc;IACrC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAA;AAC7E,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,KAAc,EAAE,IAAY;IACxD,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QACrB,MAAM,IAAI,SAAS,CAAC,GAAG,IAAI,yBAAyB,CAAC,CAAA;IACvD,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,iBAAiB,CAAC,KAA8B,EAAE,IAAY;IAC5E,MAAM,GAAG,GAAG,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;IACjD,IAAI,GAAG,KAAK,iBAAiB;QAAE,MAAM,IAAI,SAAS,CAAC,GAAG,IAAI,gCAAgC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;AACxG,CAAC;AAED,oEAAoE;AACpE,MA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,QAAQ,IAAI,KAAK,IAAI,KAAK,GAAG,SAAS,EAAE,CAAC;YAC3C,IAAI,GAAG,SAAS,CAAA;YAChB,SAAS,GAAG,KAAK,CAAA;QACnB,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAA;AACb,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAAC,KAA8B,EAAE,OAA0B,EAAE,KAAa;IACvG,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QACrC,IAAI,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC;YAAE,SAAQ;QACnC,MAAM,IAAI,GAAG,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC,CAAA;QACrC,MAAM,IAAI,GAAG,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,mBAAmB,IAAI,IAAI,CAAA;QACnE,MAAM,IAAI,SAAS,CAAC,GAAG,KAAK,wBAAwB,IAAI,CAAC,GAAG,CAAC,IAAI,IAAI,kBAAkB,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;IAC/G,CAAC;AACH,CAAC","sourcesContent":["// Small input readers shared by every public function. Wrong runtime type\n// throws TypeError; right type but unusable value throws RangeError. Nothing\n// here coerces: a string \"5\" is not a count, a Number object is not a number.\n\nimport { codeLabel, MESSAGE_UNSAFE } from './text.js'\n\nexport const MAX_COUNT = Number.MAX_SAFE_INTEGER\n\n/**\n * Most elements read from one caller-supplied array (pairs or strata). A\n * Proxy can claim any length, and a loop that trusts it can run for as long as\n * the caller likes, so a length is checked before it is used.\n */\nexport const MAX_ITEMS = 10_000_000\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nexport function requireRecord(value: unknown, name: string): Record<string, unknown> {\n if (!isRecord(value)) {\n throw new TypeError(`${name} must be a plain object`)\n }\n return value\n}\n\n/**\n * Throws TypeError for a built-in object that is not a plain record (a Map, a\n * boxed Number or String, a Date, a Set). Such a value has no own keys, so for\n * an object whose fields are all optional and whose absence turns a check off\n * (the options) it would read as \"nothing was asked for\" and fail open. Class\n * instances, null-prototype objects, Proxies of plain objects and objects from\n * another realm are plain. The caller's Symbol.toStringTag is read once here.\n */\nexport function assertPlainObject(value: Record<string, unknown>, name: string): void {\n const tag = Object.prototype.toString.call(value)\n if (tag !== '[object Object]') throw new TypeError(`${name} must be a plain object, got ${clip(tag)}`)\n}\n\n/** Reads a whole number in [min, MAX_COUNT]. Normalizes -0 to 0. */\nexport function readCount(value: unknown, name: string, min = 0): number {\n if (typeof value !== 'number') {\n throw new TypeError(`${name} must be a number`)\n }\n if (!Number.isFinite(value) || !Number.isInteger(value)) {\n throw new RangeError(`${name} must be a whole number, got ${String(value)}`)\n }\n if (value < min || value > MAX_COUNT) {\n throw new RangeError(`${name} must be between ${min} and ${MAX_COUNT}, got ${String(value)}`)\n }\n return value + 0 // turns -0 into 0\n}\n\n/** Validates a captured `.length`: a whole number from 0 to MAX_ITEMS. */\nexport function readLength(value: unknown, name: string): number {\n if (typeof value !== 'number') {\n throw new TypeError(`${name}.length must be a number`)\n }\n if (!Number.isInteger(value) || value < 0 || value > MAX_ITEMS) {\n throw new RangeError(`${name}.length must be a whole number from 0 to ${MAX_ITEMS}, got ${String(value)}`)\n }\n return value + 0\n}\n\n/** Reads a finite number in [min, max], inclusive. Normalizes -0 to 0. */\nexport function readFiniteInRange(value: unknown, name: string, min: number, max: number): number {\n if (typeof value !== 'number') {\n throw new TypeError(`${name} must be a number`)\n }\n if (!Number.isFinite(value) || value < min || value > max) {\n throw new RangeError(`${name} must be a finite number between ${min} and ${max}, got ${String(value)}`)\n }\n return value + 0\n}\n\n/** Reads a number strictly between 0 and 1 (a confidence level). */\nexport function readOpenUnit(value: unknown, name: string): number {\n if (typeof value !== 'number') {\n throw new TypeError(`${name} must be a number`)\n }\n if (!Number.isFinite(value) || !(value > 0) || !(value < 1)) {\n throw new RangeError(`${name} must be a number strictly between 0 and 1, got ${String(value)}`)\n }\n return value\n}\n\n/**\n * Makes a caller-supplied string safe to quote in a message: every control\n * (a newline, an escape), line separator, bidirectional or invisible character\n * is written as its code point (\\u000A), so a message can never carry a forged\n * log line or a terminal escape, then the text is cut without splitting a\n * surrogate pair.\n */\nexport function clip(text: string, max = 60): string {\n const plain = text.replace(MESSAGE_UNSAFE, (char) => `\\\\u${codeLabel(char).slice(2)}`)\n if (plain.length <= max) return plain\n let end = max\n const code = plain.charCodeAt(end - 1)\n if (code >= 0xd800 && code <= 0xdbff) end -= 1\n return `${plain.slice(0, end)}...`\n}\n\n/** Keys longer than this are reported but never searched for a near match. */\nconst MAX_SUGGEST_LENGTH = 64\n\n/** Lower case with everything but letters and digits removed, so \"min_agreement\" and \"minAgreement\" compare equal. */\nfunction simplify(text: string): string {\n return text.toLowerCase().replace(/[^\\p{L}\\p{N}]/gu, '')\n}\n\n/** Levenshtein distance between two short strings. */\nfunction editDistance(a: string, b: string): number {\n let previous = Array.from({ length: b.length + 1 }, (_, j) => j)\n for (let i = 1; i <= a.length; i++) {\n const row = [i]\n for (let j = 1; j <= b.length; j++) {\n const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1\n row.push(Math.min((previous[j] as number) + 1, (row[j - 1] as number) + 1, (previous[j - 1] as number) + cost))\n }\n previous = row\n }\n return previous[b.length] as number\n}\n\n/** The allowed key a misspelled `key` most likely meant, or undefined when nothing is close. */\nexport function nearestKey(key: string, allowed: readonly string[]): string | undefined {\n if (key.length > MAX_SUGGEST_LENGTH) return undefined\n const wanted = simplify(key)\n if (wanted === '') return undefined\n let best: string | undefined\n let bestScore = Infinity\n for (const candidate of allowed) {\n const other = simplify(candidate)\n const raw = editDistance(wanted, other)\n let distance = raw\n // \"maxAge\" for \"maxAgeDays\": one name inside the other\n if (Math.min(wanted.length, other.length) >= 5 && (wanted.includes(other) || other.includes(wanted))) {\n distance = Math.min(distance, 1)\n }\n const limit = wanted.length <= 4 ? 1 : 2\n // the closest wins; a tie goes to the one that differs least as written\n const score = distance * 1000 + raw\n if (distance <= limit && score < bestScore) {\n best = candidate\n bestScore = score\n }\n }\n return best\n}\n\n/**\n * Throws a TypeError naming the first own enumerable key of `value` that is not\n * in `allowed`, with the closest allowed key when there is one. A misspelled\n * optional key (\"retraction\", \"maxAgeDay\") would otherwise be ignored and turn\n * the check it configures off. Keys are listed once and no value is read, so a\n * getter is never triggered; inherited and symbol keys are not looked at.\n */\nexport function assertKnownKeys(value: Record<string, unknown>, allowed: readonly string[], label: string): void {\n for (const key of Object.keys(value)) {\n if (allowed.includes(key)) continue\n const near = nearestKey(key, allowed)\n const hint = near === undefined ? '.' : `; did you mean \"${near}\"?`\n throw new TypeError(`${label} has an unknown key \"${clip(key)}\"${hint} Allowed keys: ${allowed.join(', ')}.`)\n }\n}\n"]}
@@ -0,0 +1,41 @@
1
+ export declare const DEFAULT_CONFIDENCE = 0.95;
2
+ export interface WilsonInterval {
3
+ /** Lower limit, in [0, point]. Exactly 0 when successes is 0. */
4
+ low: number;
5
+ /** Upper limit, in [point, 1]. Exactly 1 when successes equals n, and below 1 otherwise. */
6
+ high: number;
7
+ /** successes / n. */
8
+ point: number;
9
+ /** The two-sided confidence level used. */
10
+ confidence: number;
11
+ /** The normal quantile used for that level. */
12
+ z: number;
13
+ successes: number;
14
+ n: number;
15
+ }
16
+ export interface WilsonOptions {
17
+ /** Two-sided confidence level, strictly between 0 and 1. Default 0.95. */
18
+ confidence?: number | undefined;
19
+ }
20
+ /**
21
+ * Two-sided standard normal quantile for a confidence level, e.g. 1.959963984540054
22
+ * for 0.95. Throws TypeError / RangeError unless 0 < confidence < 1.
23
+ */
24
+ export declare function zForConfidence(confidence: number): number;
25
+ /** z such that a standard normal has probability `tail` above it; 0 < tail < 0.5. */
26
+ export declare function zForTail(tail: number): number;
27
+ /** Interval for already-validated counts and an already-computed z. */
28
+ export declare function wilsonWithZ(s: number, n: number, z: number): {
29
+ low: number;
30
+ high: number;
31
+ point: number;
32
+ };
33
+ /**
34
+ * Wilson (1927) score interval for a binomial proportion.
35
+ *
36
+ * Throws TypeError when an argument is not a number, RangeError when n is not
37
+ * a whole number from 1 to Number.MAX_SAFE_INTEGER, when successes is not a
38
+ * whole number from 0 to n, or when confidence is not strictly between 0 and
39
+ * 1. -0 is read as 0.
40
+ */
41
+ export declare function wilsonInterval(successes: number, n: number, options?: WilsonOptions): WilsonInterval;
package/dist/wilson.js ADDED
@@ -0,0 +1,86 @@
1
+ import { centralQuantile, normalQuantile } from './normal.js';
2
+ import { assertKnownKeys, assertPlainObject, readCount, readOpenUnit, requireRecord } from './validate.js';
3
+ export const DEFAULT_CONFIDENCE = 0.95;
4
+ const TINY_CONFIDENCE = 1e-9;
5
+ const SQRT_HALF_PI = Math.sqrt(Math.PI / 2);
6
+ /** The largest double below 1 (2^-53 under it). */
7
+ const BELOW_ONE = 1 - 2 ** -53;
8
+ /**
9
+ * Two-sided standard normal quantile for a confidence level, e.g. 1.959963984540054
10
+ * for 0.95. Throws TypeError / RangeError unless 0 < confidence < 1.
11
+ */
12
+ export function zForConfidence(confidence) {
13
+ const c = readOpenUnit(confidence, 'confidence');
14
+ // Use whichever form keeps the small quantity exact. Up to 0.5 the displacement
15
+ // c / 2 from the median is solved for directly (0.5 + c / 2 would round away
16
+ // the digits of a tiny c); above 0.5 the tail (1 - c) / 2 is exact.
17
+ // Below 1e-9 the first series term is the answer to double precision
18
+ // (the next one is smaller by a factor of about 0.26 * c^2), and unlike c / 2
19
+ // the product cannot underflow to 0 for denormal c.
20
+ if (c < TINY_CONFIDENCE)
21
+ return c * SQRT_HALF_PI;
22
+ return c <= 0.5 ? centralQuantile(c / 2) : zForTail((1 - c) / 2);
23
+ }
24
+ /** z such that a standard normal has probability `tail` above it; 0 < tail < 0.5. */
25
+ export function zForTail(tail) {
26
+ return -normalQuantile(tail);
27
+ }
28
+ /**
29
+ * Lower Wilson limit. Written as s^2 / (n (A + B)), which equals the textbook
30
+ * (A - B) / (n + z^2) but has no subtractive cancellation when s is small.
31
+ */
32
+ function lowerLimit(s, n, z) {
33
+ if (s === 0)
34
+ return 0;
35
+ const z2 = z * z;
36
+ const a = s + z2 / 2;
37
+ const b = z * Math.sqrt((s * (n - s)) / n + z2 / 4);
38
+ return (s * s) / (n * (a + b));
39
+ }
40
+ /** Upper Wilson limit, (A + B) / (n + z^2): every term is positive, so no cancellation. */
41
+ function upperLimit(s, n, z) {
42
+ const z2 = z * z;
43
+ const a = s + z2 / 2;
44
+ const b = z * Math.sqrt((s * (n - s)) / n + z2 / 4);
45
+ return (a + b) / (n + z2);
46
+ }
47
+ /** Interval for already-validated counts and an already-computed z. */
48
+ export function wilsonWithZ(s, n, z) {
49
+ const point = s / n;
50
+ // Each limit is computed in the form that is accurate in relative terms where
51
+ // it is small. Past the midpoint the upper limit is the mirror image of the
52
+ // lower limit for the failures, which also makes the edge s = n give exactly 1.
53
+ const low = Math.min(lowerLimit(s, n, z), point);
54
+ const rawHigh = 2 * s <= n ? upperLimit(s, n, z) : 1 - lowerLimit(n - s, n, z);
55
+ // With one failure at about 4.5e15 items or more the true limit is nearer 1 than the next double
56
+ // below it, so 1 - lowerLimit rounds to exactly 1. The limit is only 1 when nothing failed; any
57
+ // other sample keeps it at the double just below 1, which no claim except exactly 1 can exceed.
58
+ const high = s < n ? Math.min(BELOW_ONE, Math.max(rawHigh, point)) : 1;
59
+ return { low, high, point };
60
+ }
61
+ /**
62
+ * Wilson (1927) score interval for a binomial proportion.
63
+ *
64
+ * Throws TypeError when an argument is not a number, RangeError when n is not
65
+ * a whole number from 1 to Number.MAX_SAFE_INTEGER, when successes is not a
66
+ * whole number from 0 to n, or when confidence is not strictly between 0 and
67
+ * 1. -0 is read as 0.
68
+ */
69
+ export function wilsonInterval(successes, n, options) {
70
+ if (options !== undefined) {
71
+ const record = requireRecord(options, 'options');
72
+ assertPlainObject(record, 'options');
73
+ assertKnownKeys(record, ['confidence'], 'options');
74
+ }
75
+ const confidenceInput = options === undefined ? undefined : options.confidence;
76
+ const nValue = readCount(n, 'n', 1);
77
+ const s = readCount(successes, 'successes', 0);
78
+ if (s > nValue) {
79
+ throw new RangeError(`successes must not exceed n (${String(s)} > ${String(nValue)})`);
80
+ }
81
+ const confidence = confidenceInput === undefined ? DEFAULT_CONFIDENCE : confidenceInput;
82
+ const z = zForConfidence(confidence);
83
+ const { low, high, point } = wilsonWithZ(s, nValue, z);
84
+ return { low, high, point, confidence, z, successes: s, n: nValue };
85
+ }
86
+ //# sourceMappingURL=wilson.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wilson.js","sourceRoot":"","sources":["../src/wilson.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAC7D,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,eAAe,CAAA;AAE1G,MAAM,CAAC,MAAM,kBAAkB,GAAG,IAAI,CAAA;AAEtC,MAAM,eAAe,GAAG,IAAI,CAAA;AAC5B,MAAM,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,CAAC,CAAC,CAAA;AAC3C,mDAAmD;AACnD,MAAM,SAAS,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAA;AAsB9B;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,UAAkB;IAC/C,MAAM,CAAC,GAAG,YAAY,CAAC,UAAU,EAAE,YAAY,CAAC,CAAA;IAChD,gFAAgF;IAChF,6EAA6E;IAC7E,oEAAoE;IACpE,qEAAqE;IACrE,8EAA8E;IAC9E,oDAAoD;IACpD,IAAI,CAAC,GAAG,eAAe;QAAE,OAAO,CAAC,GAAG,YAAY,CAAA;IAChD,OAAO,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC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C,MAAM,CAAC,GAAG,SAAS,CAAC,SAAS,EAAE,WAAW,EAAE,CAAC,CAAC,CAAA;IAC9C,IAAI,CAAC,GAAG,MAAM,EAAE,CAAC;QACf,MAAM,IAAI,UAAU,CAAC,gCAAgC,MAAM,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;IACxF,CAAC;IACD,MAAM,UAAU,GAAG,eAAe,KAAK,SAAS,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,eAAe,CAAA;IACvF,MAAM,CAAC,GAAG,cAAc,CAAC,UAAU,CAAC,CAAA;IACpC,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,WAAW,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAA;IACtD,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC,EAAE,MAAM,EAAE,CAAA;AACrE,CAAC","sourcesContent":["import { centralQuantile, normalQuantile } from './normal.js'\nimport { assertKnownKeys, assertPlainObject, readCount, readOpenUnit, requireRecord } from './validate.js'\n\nexport const DEFAULT_CONFIDENCE = 0.95\n\nconst TINY_CONFIDENCE = 1e-9\nconst SQRT_HALF_PI = Math.sqrt(Math.PI / 2)\n/** The largest double below 1 (2^-53 under it). */\nconst BELOW_ONE = 1 - 2 ** -53\n\nexport interface WilsonInterval {\n /** Lower limit, in [0, point]. Exactly 0 when successes is 0. */\n low: number\n /** Upper limit, in [point, 1]. Exactly 1 when successes equals n, and below 1 otherwise. */\n high: number\n /** successes / n. */\n point: number\n /** The two-sided confidence level used. */\n confidence: number\n /** The normal quantile used for that level. */\n z: number\n successes: number\n n: number\n}\n\nexport interface WilsonOptions {\n /** Two-sided confidence level, strictly between 0 and 1. Default 0.95. */\n confidence?: number | undefined\n}\n\n/**\n * Two-sided standard normal quantile for a confidence level, e.g. 1.959963984540054\n * for 0.95. Throws TypeError / RangeError unless 0 < confidence < 1.\n */\nexport function zForConfidence(confidence: number): number {\n const c = readOpenUnit(confidence, 'confidence')\n // Use whichever form keeps the small quantity exact. Up to 0.5 the displacement\n // c / 2 from the median is solved for directly (0.5 + c / 2 would round away\n // the digits of a tiny c); above 0.5 the tail (1 - c) / 2 is exact.\n // Below 1e-9 the first series term is the answer to double precision\n // (the next one is smaller by a factor of about 0.26 * c^2), and unlike c / 2\n // the product cannot underflow to 0 for denormal c.\n if (c < TINY_CONFIDENCE) return c * SQRT_HALF_PI\n return c <= 0.5 ? centralQuantile(c / 2) : zForTail((1 - c) / 2)\n}\n\n/** z such that a standard normal has probability `tail` above it; 0 < tail < 0.5. */\nexport function zForTail(tail: number): number {\n return -normalQuantile(tail)\n}\n\n/**\n * Lower Wilson limit. Written as s^2 / (n (A + B)), which equals the textbook\n * (A - B) / (n + z^2) but has no subtractive cancellation when s is small.\n */\nfunction lowerLimit(s: number, n: number, z: number): number {\n if (s === 0) return 0\n const z2 = z * z\n const a = s + z2 / 2\n const b = z * Math.sqrt((s * (n - s)) / n + z2 / 4)\n return (s * s) / (n * (a + b))\n}\n\n/** Upper Wilson limit, (A + B) / (n + z^2): every term is positive, so no cancellation. */\nfunction upperLimit(s: number, n: number, z: number): number {\n const z2 = z * z\n const a = s + z2 / 2\n const b = z * Math.sqrt((s * (n - s)) / n + z2 / 4)\n return (a + b) / (n + z2)\n}\n\n/** Interval for already-validated counts and an already-computed z. */\nexport function wilsonWithZ(s: number, n: number, z: number): { low: number; high: number; point: number } {\n const point = s / n\n // Each limit is computed in the form that is accurate in relative terms where\n // it is small. Past the midpoint the upper limit is the mirror image of the\n // lower limit for the failures, which also makes the edge s = n give exactly 1.\n const low = Math.min(lowerLimit(s, n, z), point)\n const rawHigh = 2 * s <= n ? upperLimit(s, n, z) : 1 - lowerLimit(n - s, n, z)\n // With one failure at about 4.5e15 items or more the true limit is nearer 1 than the next double\n // below it, so 1 - lowerLimit rounds to exactly 1. The limit is only 1 when nothing failed; any\n // other sample keeps it at the double just below 1, which no claim except exactly 1 can exceed.\n const high = s < n ? Math.min(BELOW_ONE, Math.max(rawHigh, point)) : 1\n return { low, high, point }\n}\n\n/**\n * Wilson (1927) score interval for a binomial proportion.\n *\n * Throws TypeError when an argument is not a number, RangeError when n is not\n * a whole number from 1 to Number.MAX_SAFE_INTEGER, when successes is not a\n * whole number from 0 to n, or when confidence is not strictly between 0 and\n * 1. -0 is read as 0.\n */\nexport function wilsonInterval(\n successes: number,\n n: number,\n options?: WilsonOptions,\n): WilsonInterval {\n if (options !== undefined) {\n const record = requireRecord(options, 'options')\n assertPlainObject(record, 'options')\n assertKnownKeys(record, ['confidence'], 'options')\n }\n const confidenceInput = options === undefined ? undefined : options.confidence\n const nValue = readCount(n, 'n', 1)\n const s = readCount(successes, 'successes', 0)\n if (s > nValue) {\n throw new RangeError(`successes must not exceed n (${String(s)} > ${String(nValue)})`)\n }\n const confidence = confidenceInput === undefined ? DEFAULT_CONFIDENCE : confidenceInput\n const z = zForConfidence(confidence)\n const { low, high, point } = wilsonWithZ(s, nValue, z)\n return { low, high, point, confidence, z, successes: s, n: nValue }\n}\n\n"]}