rankbounds 0.3.0__tar.gz

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.
Files changed (53) hide show
  1. rankbounds-0.3.0/CLI_OUTPUT.md +48 -0
  2. rankbounds-0.3.0/CONTRIBUTING.md +7 -0
  3. rankbounds-0.3.0/DESIGN.md +119 -0
  4. rankbounds-0.3.0/EVIDENCE.md +44 -0
  5. rankbounds-0.3.0/FORMAT.md +268 -0
  6. rankbounds-0.3.0/JUDGMENT_VALUE.md +127 -0
  7. rankbounds-0.3.0/LICENSE +21 -0
  8. rankbounds-0.3.0/MANIFEST.in +6 -0
  9. rankbounds-0.3.0/PAIRED_VALIDATION.md +34 -0
  10. rankbounds-0.3.0/PKG-INFO +415 -0
  11. rankbounds-0.3.0/README.md +405 -0
  12. rankbounds-0.3.0/RECIPROCAL_VALIDATION.md +75 -0
  13. rankbounds-0.3.0/examples/judgment-value/candidates.csv +3 -0
  14. rankbounds-0.3.0/examples/judgment-value/judgments.csv +2 -0
  15. rankbounds-0.3.0/examples/judgment-value/ranking.csv +4 -0
  16. rankbounds-0.3.0/examples/judgment-value/right.csv +2 -0
  17. rankbounds-0.3.0/examples/judgment-value/universe.csv +5 -0
  18. rankbounds-0.3.0/examples/judgments.csv +3 -0
  19. rankbounds-0.3.0/examples/ranking.csv +4 -0
  20. rankbounds-0.3.0/examples/totals.csv +2 -0
  21. rankbounds-0.3.0/examples/universe.csv +5 -0
  22. rankbounds-0.3.0/examples/weighted/judgments.csv +5 -0
  23. rankbounds-0.3.0/examples/weighted/left.csv +3 -0
  24. rankbounds-0.3.0/examples/weighted/right.csv +3 -0
  25. rankbounds-0.3.0/examples/weighted/universe.csv +5 -0
  26. rankbounds-0.3.0/examples/weighted/weights.csv +3 -0
  27. rankbounds-0.3.0/pyproject.toml +20 -0
  28. rankbounds-0.3.0/setup.cfg +4 -0
  29. rankbounds-0.3.0/src/rankbounds/__init__.py +7 -0
  30. rankbounds-0.3.0/src/rankbounds/__main__.py +142 -0
  31. rankbounds-0.3.0/src/rankbounds/average_precision.py +91 -0
  32. rankbounds-0.3.0/src/rankbounds/core.py +542 -0
  33. rankbounds-0.3.0/src/rankbounds/paired.py +331 -0
  34. rankbounds-0.3.0/src/rankbounds/reciprocal.py +94 -0
  35. rankbounds-0.3.0/src/rankbounds.egg-info/PKG-INFO +415 -0
  36. rankbounds-0.3.0/src/rankbounds.egg-info/SOURCES.txt +51 -0
  37. rankbounds-0.3.0/src/rankbounds.egg-info/dependency_links.txt +1 -0
  38. rankbounds-0.3.0/src/rankbounds.egg-info/entry_points.txt +2 -0
  39. rankbounds-0.3.0/src/rankbounds.egg-info/top_level.txt +1 -0
  40. rankbounds-0.3.0/tests/test_ap_bits.py +73 -0
  41. rankbounds-0.3.0/tests/test_ap_pruning.py +123 -0
  42. rankbounds-0.3.0/tests/test_bounds.py +598 -0
  43. rankbounds-0.3.0/tests/test_cli_output.py +347 -0
  44. rankbounds-0.3.0/tests/test_incremental.py +131 -0
  45. rankbounds-0.3.0/tests/test_judgment_value.py +291 -0
  46. rankbounds-0.3.0/tests/test_paired.py +251 -0
  47. rankbounds-0.3.0/tests/test_paired_ap.py +202 -0
  48. rankbounds-0.3.0/tests/test_paired_judgment_value.py +335 -0
  49. rankbounds-0.3.0/tests/test_query_weights.py +242 -0
  50. rankbounds-0.3.0/tests/test_reciprocal.py +199 -0
  51. rankbounds-0.3.0/tests/test_reciprocal_masks.py +139 -0
  52. rankbounds-0.3.0/tests/test_regular_input.py +202 -0
  53. rankbounds-0.3.0/tests/test_total_ranges.py +320 -0
@@ -0,0 +1,48 @@
1
+ # CLI output handling
2
+
3
+ On a report command, exit 0 means the CLI rendered one report, its text stream
4
+ accepted every character, and an explicit flush completed. Successful `--help`
5
+ retains its usual exit 0, without a JSON report. The report bytes, indentation,
6
+ trailing newline and metric semantics are unchanged. Both `rankbounds` and
7
+ `python -m rankbounds` use the same process entry point. Parser help/error messages
8
+ also use checked writes, so immediate unbuffered failures cannot be hidden by
9
+ argparse's own error suppression.
10
+
11
+ A short or invalid write count, unavailable/closed stdout, write error, or delayed
12
+ flush error returns exit 2. The CLI does not retry a partial write: a stream might
13
+ already have accepted part of the report, and retrying could duplicate data.
14
+ Discard stdout whenever the exit status is nonzero. This is not atomic output,
15
+ a storage-durability guarantee, or proof that a downstream consumer read or
16
+ accepted the JSON. For durable reports, callers must also manage their destination
17
+ and its own storage/transaction rules.
18
+
19
+ Input errors still produce no report and return exit 2. Error diagnostics are
20
+ best effort. A closed/full/unavailable stderr must not turn a failure into success
21
+ or cause a diagnostic traceback.
22
+
23
+ ## Library calls and process shutdown
24
+
25
+ `rankbounds.__main__.main(argv)` borrows the caller's streams. It checks report
26
+ writes and flushes, but never closes or replaces either stream. It retains the
27
+ usual `argparse` `SystemExit` behavior for help and argument errors. The `audit`
28
+ and `compare` Python APIs are unchanged and do not write reports.
29
+
30
+ The console script and module launcher call `cli(argv)` instead. This process-only
31
+ wrapper also handles help/argument-error exits and final standard-stream flushes.
32
+ When a flush fails, it disables that failed standard-stream slot for the process
33
+ that is about to exit. This prevents Python's shutdown retry from replacing the
34
+ chosen exit 2 with exit 120 or printing an ignored-flush traceback. Do not use
35
+ `cli` as an embedding API: use `main`, `audit`, or `compare` instead.
36
+
37
+ ## Checks
38
+
39
+ `tests/test_cli_output.py` checks unchanged single-run/paired JSON, short and
40
+ invalid write counts, immediate and delayed errors, absent/closed streams,
41
+ best-effort diagnostics and borrowed-stream ownership. Subprocess checks cover
42
+ both launchers against a readerless pipe. On systems with `/dev/full`, they also
43
+ cover full report/help output and full argument-error diagnostics. Report/help
44
+ failures are checked with default buffering, `-u`, and `PYTHONUNBUFFERED=1`.
45
+ Neutral installed-wheel runs exercise the actual console-script file on POSIX,
46
+ not only an emulated entry-point import. These are
47
+ output-contract checks, not additional mathematical-oracle tests or proof of
48
+ all platform/stream implementations.
@@ -0,0 +1,7 @@
1
+ # Contributing
2
+
3
+ Open an issue before proposing new formats, metric conventions, constraints or
4
+ dependencies. Keep fail-closed validation and explicit finite-universe/binary
5
+ semantics. Add an independent exhaustive-completion regression for a new bound.
6
+ Do not use real sensitive identifiers or datasets in issues or tests. Follow the
7
+ checks in README.md. Contributions use MIT.
@@ -0,0 +1,119 @@
1
+ # Extremizers
2
+
3
+ For one query, let A be the known-relevant count in the entire declared
4
+ universe, M the unjudged count in the returned top-k, and O the unjudged count
5
+ outside that top-k. Fix t, the number of the M unknown top-k labels that become
6
+ positive. Then total relevance R ranges from A+t through A+t+O, intersected
7
+ with an optional exact total. An empty intersection is infeasible.
8
+
9
+ At a fixed t, choose the earliest t unjudged ranks for the largest numerator and
10
+ the latest t for the smallest. Moving an unknown positive earlier across an
11
+ unknown negative leaves hits unchanged, improves or preserves first-relevant
12
+ rank and DCG, and improves AP's numerator: its own precision term improves and
13
+ any intervening fixed positives see one more earlier positive. Other fixed
14
+ positives' contributions do not worsen. Repeated exchanges establish earliest
15
+ and latest extremizers without enumerating 2**M assignments.
16
+
17
+ At fixed t, the numerator does not depend on unknown outside labels. Recall/AP
18
+ have denominator R; nDCG has the monotone ideal DCG for min(R,k) positives.
19
+ Thus use the smallest feasible R for upper candidates and the largest for lower
20
+ candidates. Precision and RR ignore outside labels, so these choices also
21
+ provide compatible examples for them. The R=0 case has explicit all-zero scores.
22
+
23
+ Enumerate t=0..M, score both extremizers, and retain each metric's minimum and
24
+ maximum. Equal floating-point candidate values keep the first encountered t. This enumeration also permits exact
25
+ totals that force positives into top-k or outside it. For multiple queries,
26
+ constraints are independent and macro is linear, so averaging per-query minima
27
+ and maxima yields attainable macro endpoints *for each individual metric*.
28
+ Single-run audit makes no claim of joint attainability across metrics or
29
+ score-difference optimization. The separate paired API below optimizes three
30
+ shared-label metric differences.
31
+
32
+ ## Incremental scoring
33
+
34
+ Build a prefix count of fixed positives and a suffix sum of their reciprocal
35
+ ranks. Adding an unknown positive at rank r contributes its own precision
36
+ `(fixed_before + selected_before + 1)/r` to the AP numerator. It also adds
37
+ `sum(1/j)` for fixed and already selected positives after r. Earliest-first
38
+ additions have all previously selected positives before r; latest-first
39
+ additions have them all after. A compensated running sum maintains that latter
40
+ suffix. DCG adds one discount term and first-hit rank updates by minimum.
41
+ Ideal DCG is precomputed once as a compensated prefix over discount terms.
42
+
43
+ The candidate scan compares scores from these incremental states. After it
44
+ chooses endpoints, it re-scores at most ten selected completions using the
45
+ original `math.fsum` evaluator. Identical selected completions share this final
46
+ calculation. Examples are constructed only after selection, not every time an
47
+ endpoint improves. Reported scores are thus tied to actual finite completions,
48
+ not the incremental sums alone.
49
+
50
+ ## Cost and compatibility
51
+
52
+ Scoring is O(L + min(k,C) + M) time, with a fixed at-most-ten rescoring factor,
53
+ and O(L + min(k,C)) transient space plus input/report storage. L is the
54
+ returned length clipped at k, M its unknown count, and C the universe size.
55
+ No quadratic bit-vector rebuild, full score scan or repeated ideal summation
56
+ occurs for every t. Stored input dictionaries/sets remain proportional to rows
57
+ and identifier bytes. This is not a hard memory or runtime bound.
58
+
59
+ The v1 `scoring_work_units` formula, `max_work` acceptance set, JSON schema,
60
+ input validation and metric conventions are deliberately unchanged. Its
61
+ quadratic estimate is now a conservative compatibility admission rule rather
62
+ than a model of current operation count. Faster scoring does not silently
63
+ accept larger workloads. Users can explicitly raise the existing cap within
64
+ its supported range. No new option or file format is introduced.
65
+
66
+ The optimization can be slower when almost everything is judged: precomputing
67
+ recurrence state has overhead without many candidate counts to amortize it.
68
+ Local synthetic timings do not promise any portable speedup.
69
+
70
+ ## Numerical limits
71
+
72
+ Candidate score terms use Python doubles and compensated running sums; final
73
+ selected completions use the original `math.fsum` evaluator. Discrete extremizer selection
74
+ is exact mathematically, but close floating-point candidates can tie or differ
75
+ by roundoff. Near-tied candidate selection can shift emitted endpoints by floating-point
76
+ roundoff relative to the prior full-scan evaluator, not only select a different
77
+ witness. Final rescoring binds each emitted endpoint to a feasible completion's
78
+ score, but does not guarantee the exact extremum of all floating-point scores,
79
+ exact numeric baseline parity, or outward rounding. Small sampled differences
80
+ do not establish a universal bound or direction of drift.
81
+ No epsilon-based system
82
+ ranking, confidence interpretation or decision threshold is provided.
83
+
84
+ ## Shared-label paired differences
85
+
86
+ Paired precision, recall and binary nDCG have a common denominator for two runs
87
+ under the same completed labels: respectively k, total relevance R, or ideal
88
+ DCG(min(R,k)). Their difference numerator is a weighted sum of document labels.
89
+ A document's coefficient is its left-minus-right inclusion indicator for
90
+ precision/recall, or its left-minus-right rank discount for nDCG. A document
91
+ present in both runs has ONE label and the difference of its two coefficients.
92
+ Known labels contribute a fixed sum. Unknown documents outside both top-k sets
93
+ have zero coefficient but can change R. AP's numerator is not linear in labels;
94
+ this method makes no paired AP claim. RR is also excluded from this API.
95
+
96
+ Let t be the number of unknown positive labels in the union of the top-k sets.
97
+ At fixed t, sum the t smallest coefficients to minimize the numerator, or the
98
+ t largest to maximize it. An exchange from a larger selected coefficient to a
99
+ smaller unselected one cannot increase the sum. R ranges from known positives
100
+ plus t through that count plus unknown documents outside the union, intersected
101
+ with any exact total. An empty intersection is skipped. Unlike single-run
102
+ nonnegative scores, this numerator is SIGNED: for the lower endpoint, choose
103
+ small R for a negative numerator and large R for a positive numerator; reverse
104
+ those choices for the upper endpoint. Zero denominators imply zero total
105
+ relevance and explicitly yield zero scores. Precision ignores R.
106
+
107
+ Scan every feasible t for each metric/direction, retain the best candidate,
108
+ then re-score each selected labeling on BOTH runs with the existing score
109
+ function. Outside unknown positives need only a count because neither run
110
+ retrieves them above cutoff. This supplies actual shared-label witnesses.
111
+ Independent queries can attain their endpoints independently, so equal-weight
112
+ averages give per-metric macro extrema. Floating-point qualifications from
113
+ FORMAT.md still apply; this is not a certified numeric optimizer.
114
+
115
+ For one query, coefficient construction costs O(L+T), sorting O(M log M),
116
+ normalizer precomputation O(min(k,C)), and candidate scanning O(M). A fixed six
117
+ endpoint rescoring operations add O(L+T+min(k,C)). Transient storage is linear
118
+ in those sizes, plus stored inputs, known labels and requested witnesses.
119
+ These are algorithmic bounds, not demonstrated speedups or hard memory limits.
@@ -0,0 +1,44 @@
1
+ # Sources and scope, checked 2026-11-14
2
+
3
+ This tool implements an explicit finite-binary completion problem. It does not
4
+ claim a new research metric, a new missing-judgment method, or that worst-case
5
+ intervals are preferable to established estimators for every study.
6
+
7
+ The following sources were fetched and their relevant definitions/method
8
+ descriptions inspected while choosing the scope. Quotes below are limited to
9
+ short method/definition excerpts; production code is original.
10
+
11
+ 1. [ir-measures measure reference](https://ir-measur.es/en/latest/measures.html).
12
+ Its AP `judged_only` parameter says "ignore returned documents that do not
13
+ have relevance judgments". It also distinguishes recall from Success@k and
14
+ documents nDCG discount/gain options. We keep original ranks and explicitly
15
+ document our particular binary/log2/total-AP conventions instead of claiming
16
+ all-library parity.
17
+ 2. [ranx metrics](https://amenra.github.io/ranx/metrics/).
18
+ Recall is the ratio of retrieved relevant documents to total relevant
19
+ documents. It describes bpref as "designed for situations where relevance
20
+ judgments are known to be incomplete." Use that established evaluator when
21
+ it answers your question; rankbounds is not a new bpref implementation.
22
+ 3. [NIST trec_eval infAP implementation](https://github.com/usnistgov/trec_eval/blob/main/m_infap.c).
23
+ The measure's comment says "Assume a judgment pool with a random subset that
24
+ has been judged." That estimator's sampling assumptions differ from our
25
+ adversarial compatibility problem with no probabilities.
26
+ 4. [Froebe et al., Bootstrapped nDCG Estimation in the Presence of Unjudged Documents (2023)](https://downloads.webis.de/publications/papers/froebe_2023a.pdf).
27
+ The abstract contrasts condensed lists, naive bounds and bootstrapping;
28
+ naive bounds are described as often very "loose". We accept wide intervals
29
+ rather than predict likely relevance. This paper is context, not evidence
30
+ that our implementation reproduces its experimental results.
31
+ 5. [Sakai and Kando, On information retrieval metrics designed for evaluation with incomplete relevance assessments (2008)](https://link.springer.com/article/10.1007/s10791-008-9059-7).
32
+ The authors evaluate condensed metrics and report favorable robustness in
33
+ their studied collections. This is a reason **not** to claim our fixed-rank
34
+ sensitivity audit replaces condensed metrics or settles incomplete-judgment
35
+ evaluation generally. Different questions and assumptions remain useful.
36
+ 6. [Aslam, Pavlu and Yilmaz, A Sampling Technique for Efficiently Estimating Measures of Query Retrieval Performance Using Incomplete Judgments (2005)](https://www.ccs.neu.edu/home/jaa/papers/AslamPaYi05.pdf).
37
+ The paper notes that unretrieved relevant documents' precisions are zero,
38
+ with the retrieved precision sum "divided by R". It proposes random-sampling
39
+ estimators. We use the total-relevant denominator, but do not implement its
40
+ estimator, claim unbiased estimation, or borrow its empirical accuracy.
41
+
42
+ Worst-case bounds do not discover the real label distribution, fix biased
43
+ judgments, model dependence, determine statistical significance, or establish
44
+ which ranker is better. Finite pool bounds only describe the declared pool.
@@ -0,0 +1,268 @@
1
+ # Input, output and limits
2
+
3
+ UTF-8 CSV, optional initial UTF-8 BOM; exact ordered headers:
4
+
5
+ | File | Header | Meaning |
6
+ | --- | --- | --- |
7
+ | universe | `query_id,document_id` | Unique pair, defines finite candidate set |
8
+ | ranking | `query_id,document_id,rank` | Unique document and rank per query |
9
+ | judgments | `query_id,document_id,relevant` | Unique pair, binary 0/1 |
10
+ | totals (optional) | `query_id,total_relevant` | Exactly one row per universe query |
11
+ | query_weights (optional) | `query_id,weight` | Nonnegative integer counts, every query once, positive sum |
12
+ | total_ranges (optional) | `query_id,min_relevant,max_relevant` | Inclusive bounds, exactly one row per universe query |
13
+
14
+ All IDs are literal and case-sensitive. No trimming, normalization, inferred
15
+ negative labels or score-based tie breaking. CSV quoting and internal Unicode
16
+ are supported. Empty cells, leading/trailing whitespace, NUL, bad UTF-8,
17
+ malformed CSV, blank data rows, extra/missing cells, wrong headers and duplicates
18
+ are rejected. Integer cells use ASCII digits only, at most 18 digits, no sign or
19
+ decimal point; zero padding is accepted. Rank must be positive; per-query ranks
20
+ must be exactly 1..n. Input row order does not affect output. Rankings and
21
+ judgments must reference an existing universe pair, even below cutoff k.
22
+
23
+ The universe cannot be empty and cannot express a query with no documents.
24
+ Ranking/judgment files may have only their headers. A query absent from the
25
+ ranking gets an empty run. Totals cannot omit any query or add an unknown query.
26
+ Totals below known positives or above known positives plus unjudged documents
27
+ are contradictory and rejected. All validation completes before JSON is emitted.
28
+
29
+ ## JSON schema v1
30
+
31
+ - `mode`: `finite_binary_compatibility`; `k`; `query_count`.
32
+ - `scoring_work_units`: deterministic admission estimate (see below).
33
+ - `macro`: each metric's lower/upper endpoint, equal weight over all queries.
34
+ - `queries`: lexical query ID order. Each row contains `query_id`, inventory,
35
+ judgment, relevance, returned/top/unjudged counts; feasible total-relevant
36
+ interval; five metric intervals; and the compatible conventional all-unknown-
37
+ negative score (or `compatible:false,metrics:null`).
38
+ - Optional `endpoint_examples` for at most the first N lexical query IDs gives
39
+ per-metric/per-direction `total_relevant`, `unjudged_top_relevant` document IDs
40
+ in ranking order, and `unjudged_outside_relevant_count`. These are **hypothetical
41
+ completions, not proposed judgments**. All known labels remain fixed. All
42
+ unlisted unjudged top-k documents are negative. Choose any stated count of
43
+ unjudged documents outside the top-k to be positive; all other unknown labels
44
+ are negative. Documents ranked below k count as outside. The count never
45
+ selects known-positive or known-negative documents. No outside IDs are emitted.
46
+
47
+ Each emitted endpoint is a feasible completion score under the declared binary
48
+ constraints, subject to normal floating-point rounding. Near-tied selection can
49
+ also shift emitted endpoints by roundoff versus the prior full-scan evaluator.
50
+ There is no exact numeric baseline-parity, floating-point-extremum or certified
51
+ outward-rounding guarantee. Observed small differences do not prove a universal
52
+ drift size or direction. They do not cover label errors, missing
53
+ universe members, relevance grades, dependent-query constraints or alternative
54
+ metric conventions.
55
+
56
+ ## Admission and resource limits
57
+
58
+ `--max-rows` defaults to 1,000,000 **per input**, including rows below k.
59
+ `--max-work` defaults to 5,000,000. For query q, let L be the returned length
60
+ clipped at k, M its unjudged count there, and C its universe size. Work units are
61
+ `(M+1)*(L+min(k,C)+1)`. The sum over queries is checked before scoring starts.
62
+ Exact boundary is allowed; exceeding it fails rather than truncates. This v1
63
+ admission estimate is retained for compatibility after incremental scoring
64
+ removed its quadratic scan; it is not a current operation counter.
65
+
66
+ These are row/work admission caps, **not hard memory or wall-time bounds**.
67
+ Parsing and in-memory inventories are needed before the work check. Inputs,
68
+ strings and reports can be large. CSV parser field-size limits also apply;
69
+ oversized fields fail. Use trusted local inputs and OS-level isolation for
70
+ untrusted large files. No disk scratch or network calls are used.
71
+
72
+ `k`, `max_rows`, `max_work` must be integers from 1 through 1,000,000,000;
73
+ `examples` is 0..20, default 0. Boolean API arguments are rejected as integers.
74
+ There is no runtime override to silently skip bad rows or incomplete totals.
75
+
76
+ ## Paired mode
77
+
78
+ `compare(universe, left_ranking, right_ranking, judgments, k=..., ...)` and CLI
79
+ `--comparison-ranking RIGHT.csv` use the same strict files, optional totals,
80
+ option ranges and per-file row cap as single-run mode. The existing `--ranking`
81
+ is the left run. Both rankings are validated in full before scoring; malformed
82
+ or contradictory input, including below-cutoff rows in either ranking, yields
83
+ an error with no report JSON. Neither API writes or changes input files.
84
+
85
+ Paired schema version 1 uses the distinct mode
86
+ `finite_binary_paired_compatibility`, `difference: left_minus_right`, `k`,
87
+ `query_count`, `scoring_work_units`, `macro`, and lexical `queries`. Metrics are
88
+ by default `precision`, `recall`, `ndcg`, each with lower/upper differences.
89
+ Opt-in `include_rr=True` adds `rr` as described below. Scores
90
+ use the same conventions as single-run mode, including zero recall/nDCG when
91
+ there are no relevant documents and precision's denominator k for short runs.
92
+ A query row also has universe/judgment/known-relevant/unjudged counts,
93
+ left/right top counts, top-union and unjudged-top-union counts, and feasible
94
+ relevant-total bounds. There is no pass/fail or statistical significance field.
95
+
96
+ For the first `examples` lexical queries, each endpoint has `left_score`,
97
+ `right_score`, `total_relevant`, lexical `unjudged_union_relevant` IDs and an
98
+ `unjudged_outside_union_relevant_count`. Keep known labels fixed, assign listed
99
+ unknown union documents positive and all other unknown union documents negative.
100
+ Choose any stated number of unknown documents outside BOTH top-k sets to be
101
+ positive; all other unknown labels are negative. This single completed labeling
102
+ reproduces both scores and their difference, subject to floating-point rounding.
103
+ Ranked-below-cutoff documents are outside unless present in the other top-k.
104
+ Outside IDs are never emitted. Different metrics/directions can use different
105
+ completions; all endpoints are not claimed jointly attainable.
106
+
107
+ Let L and T be the two clipped ranking lengths, M the number of unknown documents
108
+ in their union, and C the universe size. Paired work admission units per query are
109
+ `(M+1)*(L+T+min(k,C)+1)`. Sum across all queries; exact cap equality is allowed.
110
+ Default `max_work` is 5,000,000. This is an admission estimate, not an operation,
111
+ hard memory or wall-time bound. Parsing, identifier storage and report generation
112
+ can still be large. Compared with single-run mode, there is one extra fully
113
+ validated ranking input. There is no scan of all binary label assignments.
114
+
115
+ Coefficient sums, normalizers and endpoint selection use ordinary double
116
+ precision with compensated or fsum accumulation where appropriate. Selected
117
+ completions are re-scored on each run and subtracted. Near ties or cancellation
118
+ can affect endpoint choice/value by roundoff. No guarantee of the exact extrema
119
+ of all floating-point computations, outward rounding, or numerical separation
120
+ from zero is made. Do not treat a tiny signed endpoint as a certified ranking.
121
+
122
+ ### Opt-in paired reciprocal rank
123
+
124
+ `compare(..., include_rr=True)` or CLI `--paired-rr` adds `rr` to paired `macro`,
125
+ per-query `metrics`, and (when requested) `endpoint_examples`. Default False
126
+ leaves all report fields and admission units unchanged. That option alone does not add paired AP; use the separate `include_ap` opt-in.
127
+ The same k, known labels, exact totals and finite universe apply; RR is zero
128
+ without a relevant returned document at or before k.
129
+
130
+ Add `(L+1)*(R+1)*(L+R+1)` units per query to the existing paired charge. Work is
131
+ checked across the whole query set before calling either scoring solver. The
132
+ charge is retained as a conservative compatibility admission rule; the current
133
+ solver uses integer masks and deferred witness expansion instead of per-pair
134
+ prefix sets. It is not exact CPU work or a hard resource bound. Endpoint witnesses
135
+ use the existing shared-completion layout and disclosure rules.
136
+
137
+
138
+ ### Opt-in paired AP
139
+
140
+ `compare(..., include_ap=True)` or CLI `--paired-ap` (with
141
+ `--comparison-ranking`) adds `ap_total` to paired macro, per-query metrics and
142
+ requested endpoint examples. The solver prunes impossible union-positive
143
+ cardinalities using the declared count interval, while preserving numeric-mask
144
+ scan order, report values and witness ties. [Details](AP_PRUNING.md). Defaults remain unchanged. AP sums precision at
145
+ each relevant retrieved rank through k, divided by the completed universe's
146
+ total relevant count R; R=0 gives zero. This is not AP divided by min(R,k).
147
+
148
+ Let U be the number of unjudged documents in the top-k union, and L and Rlen
149
+ the two truncated ranking lengths. Add `2**U * 2 * (L + Rlen + 1)` work units
150
+ per query to the existing paired charge (and RR charge, if requested). The
151
+ whole query set is checked before any solver runs. A bit-length guard rejects
152
+ obviously excessive exponent sizes without first constructing the huge integer.
153
+ These admission units model enumerated assignments and rank scans, not exact
154
+ CPU operations, a wall-clock promise or a hard memory limit.
155
+
156
+ For each union assignment, both AP numerators are fixed. Outside-union unknown
157
+ positives change only the shared denominator. Its feasible low and high totals
158
+ suffice for both signed-difference extrema; when an exact total is supplied,
159
+ only compatible assignments and that total are scored. Witnesses use the same
160
+ shared-label format as other paired metrics. Each endpoint is attainable, but
161
+ different metrics/directions can require different completions. Scores use
162
+ ordinary double precision, not certified outward-rounded intervals. Work-limit
163
+ failure emits no partial JSON. No AP quality threshold or deployment claim.
164
+
165
+
166
+ ## Total-relevant ranges
167
+
168
+ `audit(..., total_ranges=PATH)` and `compare(..., total_ranges=PATH)` use the
169
+ strict range CSV above; the CLI spelling is `--total-ranges PATH`. It is mutually
170
+ exclusive with `totals` / `--totals`. This is a new optional input, not a change
171
+ to existing totals headers. The same UTF-8, cell, integer, row-cap, identifier,
172
+ duplicate and exact-query-coverage checks apply. A file with only its header is
173
+ invalid because every universe query must have one row.
174
+
175
+ Require `0 <= min_relevant <= max_relevant <= universe_documents`. Intersect
176
+ this inclusive interval with `[known_relevant, known_relevant + unjudged_documents]`.
177
+ Reject an empty intersection. All count constraints, across all queries, are
178
+ checked before any metric solver runs. No partial report is emitted. Effective
179
+ intersections populate `feasible_total_relevant`, and endpoint examples select
180
+ only completions in that intersection. No new source paths or input document IDs
181
+ are added to the report. Existing query IDs are still always emitted.
182
+
183
+ The interval constrains total positives, not just retrieved positives. For a
184
+ fixed top-k (or paired top-k union) assignment, unknown outside documents can
185
+ realize every integer total between its feasible endpoints. Intersect before
186
+ choosing the denominator. Single-run metric extrema and paired precision,
187
+ recall, nDCG, RR and optional AP all use this same constraint. See
188
+ [TOTAL_RANGES.md](TOTAL_RANGES.md) for the denominator and witness argument.
189
+ Neither range input nor interval width changes `scoring_work_units`; no total
190
+ counts or outside subsets are enumerated. Existing paired AP admission remains
191
+ exponential in the unjudged top-k union, not interval width.
192
+
193
+
194
+ ## Optional fixed query-weighted aggregate
195
+
196
+ `query_weights` / `--query-weights` adds `query_weighted`, never replaces
197
+ `macro`. Its `total_weight` and `weights` counts use decimal strings;
198
+ `metrics` has the ordinary floating-point lower/upper layout for every metric
199
+ included by that mode. The input follows the same CSV/18-digit integer
200
+ rules and per-file max_rows limit as other inputs, including zero padding.
201
+ All queries must occur once and the nonnegative weights must have positive
202
+ sum. Invalid weights are rejected before any query solver runs. Zero weight
203
+ does not bypass parsing, scoring, constraints or work admission. Work units
204
+ continue to describe the existing metric solver estimate, not all parsing
205
+ or the extra linear aggregate/report work. The additional weights mapping
206
+ uses O(Q) memory/output and aggregation uses O(Q*M) floating-point operations
207
+ for Q queries and M included metrics. Existing input/report resource caveats
208
+ and lack of certified outward rounding still apply. See [semantics and
209
+ validation](QUERY_WEIGHTS.md).
210
+
211
+
212
+ ## Regular-file CSV inputs
213
+
214
+ Every CSV input, including optional totals, total ranges and query weights,
215
+ uses the same regular-file reader. Symlinks to regular files are allowed.
216
+ Directories, FIFOs, sockets and devices are refused. The reader checks the
217
+ path type before opening, then checks the opened descriptor. Where the OS
218
+ provides O_NONBLOCK, it is used to avoid waiting on a FIFO substituted between
219
+ those checks. Where unavailable, the precheck and descriptor check still
220
+ apply, but there is no guarantee against a blocking substitution race.
221
+ No hard I/O deadline or immutable snapshot is provided: regular files can
222
+ change during a read, and network, pseudo or other filesystems may still
223
+ block. CSV syntax, row/work admission, output and score semantics are
224
+ unchanged for accepted inputs. [Implementation and validation](REGULAR_INPUT.md).
225
+
226
+
227
+ ## Optional judgment-value report
228
+
229
+ `audit(..., judgment_candidates=...)`, `compare(..., judgment_candidates=...)`
230
+ or `--judgment-candidates` accepts strict
231
+ regular-file CSV with exact header `query_id,document_id`, 1 to 200 unique
232
+ currently unjudged universe pairs, literal IDs, standard BOM/UTF-8 handling
233
+ and the same per-file max_rows. Invalid candidates fail before any solver.
234
+ Both single and paired CLI/API modes support the shortlist.
235
+
236
+ For single-run mode, `judgment_value` has scope `single_query_interval_width` and a
237
+ lexical query/document `candidates` list. Each entry has both IDs, `outcomes`
238
+ (label string to all five metric endpoint pairs, only feasible labels) and
239
+ `metrics` (before_width, after_width_by_label, guaranteed_reduction,
240
+ best_case_reduction for each metric). Every entry considers one hypothetical
241
+ judgment against the same original labels, not prior entries' hypotheticals.
242
+ No extra endpoint examples or actual relevance recommendation is emitted.
243
+
244
+ For original per-query work estimate W_q, total scoring_work_units becomes
245
+ sum(W_q) + 2*sum(W_q for each candidate's query). Infeasible outcomes do not
246
+ reduce this conservative reservation. All admission happens before any
247
+ original or hypothetical score calculation. The formula is still a solver
248
+ estimate, not a parser, label-copying, report, total-RAM or time bound.
249
+ With C<=200 candidates and M<=5 enabled metrics, extra solver calls are at most 2C,
250
+ extra output O(C*M), and temporary label copies can use O(L_q) space and work
251
+ per call. No automatic document search, cost model, query-weighted importance or
252
+ expected utility is implied. IDs are always disclosed in
253
+ this opt-in even when examples=0. Floating-point width subtraction may produce
254
+ small negative reductions; values are not clipped. [Full contract](JUDGMENT_VALUE.md).
255
+
256
+
257
+ ### Paired judgment-value mode
258
+
259
+ `compare` accepts the same optional candidate CSV. The CLI accepts it with
260
+ `--comparison-ranking`, including opt-in paired RR/AP. The additional scope is
261
+ `single_query_paired_difference_interval_width`. Each feasible outcome contains
262
+ only the comparison's enabled metric endpoints under a shared new label.
263
+ Widths and reductions refer to that candidate's own-query left-minus-right
264
+ interval, not macro, weighted macro or independent single-run endpoints.
265
+ Both additional charges use the original complete paired W_q, including RR/AP,
266
+ and are admitted for every candidate before any solver. Default reports and
267
+ work remain unchanged when the option is absent/None. All 200-row, input,
268
+ privacy and floating-point rules of judgment-value mode still apply.
@@ -0,0 +1,127 @@
1
+ # Hypothetical judgment-value analysis
2
+
3
+ ## Question and scope
4
+
5
+ Given a retrieval ranking (or a shared-label pair of rankings) and incomplete binary judgments, how much narrower would a query's metric interval become if one particular currently unjudged document were labeled? The optional judgment_candidates CSV asks that question for an explicit shortlist. It does not predict labels, assign probabilities, optimize a batch, select a metric, model annotation cost or claim optimal active learning. Candidates are evaluated one at a time against the original judgments and original count constraints.
6
+
7
+ audit reports single-run metric width. compare reports the width of the shared-label left-minus-right metric difference, never the difference between independent single-run intervals. It is query-local even when fixed query weights are present; no cross-query priority or weighted importance is inferred. A narrow interval is not an accurate score estimate unless the declared universe, labels and other assumptions are correct.
8
+
9
+ ## Input and output
10
+
11
+ The candidate file has exact ordered header query_id,document_id. It must have 1 to 200 unique pairs. Each pair must exist in the declared universe and not already have a judgment. Other queries need not be represented. IDs are literal and case-sensitive; row order does not matter. The shared regular-file, UTF-8/BOM, strict CSV, cell-validation and max_rows rules apply. Invalid candidates fail before any original or hypothetical solver call.
12
+
13
+ The ordinary report is preserved, except that scoring_work_units includes the extra conservative work reservation. The added judgment_value object contains:
14
+
15
+ - scope = single_query_interval_width for audit, or single_query_paired_difference_interval_width for compare.
16
+ - candidates: list ordered lexically by query ID and document ID.
17
+ - Each candidate: query_id, document_id, outcomes, metrics.
18
+ - outcomes: label strings 0 and/or 1 mapped to all five single-run metric endpoint pairs, or exactly the paired metrics enabled in compare (precision/recall/nDCG, plus opt-in RR/AP). Impossible outcomes are absent, not null, zero-valued or assumed equally likely.
19
+ - metrics: for each metric, before_width, after_width_by_label, guaranteed_reduction and best_case_reduction.
20
+
21
+ Every requested document ID is disclosed when this option is used, regardless of examples=0. This is deliberate opt-in output, not an automatic scan of unjudged documents. Neither labels nor inputs are written, and hypothetical endpoint document examples are not added. Existing --examples behavior remains separate. The full endpoint report for each feasible label lets a reader distinguish a narrowed interval from a shifted interval.
22
+
23
+ ## Feasibility and width definitions
24
+
25
+ Let C be the original feasible binary completions for this query. For candidate d and label b, C_b contains the completions in C with d=b. These sets partition C. The original validated query has at least one completion, so at least one C_b is nonempty. With K known positives and U unknown documents before the hypothetical judgment, label b is feasible exactly when the original total-relevant range intersects [K+b, K+b+U-1]. This is the same finite-universe count-feasibility test already used by the solver. An exact total is a singleton range. Without a declared count constraint, both outcomes are possible.
26
+
27
+ The original total/range is retained, not reduced by b: the solver receives a new known label, so it already incorporates that known positive when checking the whole-universe total. Every feasible outcome is scored using the existing mode-specific single-query solver with a separate label dictionary. A hypothetical label from one candidate never becomes input to another candidate.
28
+
29
+ For each metric f, let W be max_C f - min_C f, and W_b be max_(C_b) f - min_(C_b) f for each feasible outcome. Then:
30
+
31
+ - guaranteed_reduction = W - max_b W_b.
32
+ - best_case_reduction = W - min_b W_b.
33
+
34
+ In real arithmetic, a subset's width cannot exceed its parent's, so 0 <= guaranteed_reduction <= best_case_reduction <= W. These are worst/best conditional reductions, not expected reductions. A forced label, already implied by the count constraints, cannot remove a feasible completion and has zero mathematical reduction. Each metric/direction can need a different completion. No joint endpoint vector is promised.
35
+
36
+ Production scores remain ordinary floating-point values from the existing solver. The new widths and reductions subtract those emitted endpoints. Near-tie selection and rounding can produce small negative reductions or differences from exact-arithmetic identities. Values are not clipped, certified outward-rounded or ranked with a hidden tolerance. Do not treat last-bit differences as meaningful annotation priorities.
37
+
38
+ ## Example
39
+
40
+ Universe a,b,c,d; returned ranking a,b,c; only b is known relevant; k=3. Candidates a and unreturned d are unjudged.
41
+
42
+ | Candidate | Metric | Guaranteed width reduction | Best-case width reduction |
43
+ | --- | --- | --- | --- |
44
+ | a | precision | about 0.33333 | about 0.33333 |
45
+ | a | recall | 0 | about 0.16667 |
46
+ | a | reciprocal rank | 0.5 | 0.5 |
47
+ | d | precision | 0 | 0 |
48
+ | d | recall | 0.25 | 0.5 |
49
+
50
+ The original recall interval width is 0.5. Learning d=0 makes recall certain for this finite universe, whereas d=1 leaves width 0.25. An unreturned document can therefore matter more for recall uncertainty than the first returned document. This is not a predicted label, a reason to skip unreturned documents generally, or a claim about annotation cost. The files under examples/judgment-value and the actual CLI output reproduce this case.
51
+
52
+ ## Admission and cost
53
+
54
+ For original per-query work estimate W_q, the opt-in admission sum is sum_q W_q + 2*sum_candidates W_(candidate query). Both hypothetical calls are reserved before any scoring, even when a count constraint will make one outcome impossible. This conservative estimate avoids making the admission limit depend on skipping forced labels. There are at most two additional solver calls per candidate, and no more than 200 candidates. A caller can lower max_work or use a smaller shortlist.
55
+
56
+ The estimate is not a complete operation count or an OS resource limit. Parsing, copying known-label dictionaries, validation, report construction, integer/ID sizes and aggregation have costs outside that solver formula. Extra mappings use O(Q) entries, reports use O(C*M) endpoint/metric records plus ID bytes, and each temporary label copy uses O(L_q) entries; each hypothetical also needs the existing query solver's workspace. Here Q is query count, C<=200 candidate count, M<=5 enabled metric count and L_q is that query's known-label count. No I/O deadline, total output-byte cap or hard wall-time/RAM guarantee is introduced.
57
+
58
+ ## Single-run baseline validation
59
+
60
+ These are the checks recorded for the original single-run addition. Paired support is checked separately below.
61
+
62
+ - 158 tests pass on Python 3.9 through 3.15. Thirteen new tests cover analytic top/returned-versus-unreturned behavior; worst/best-case distinction; 80 seeded two-query exhaustive completion oracles; exact/range counts and forced labels; None/default/weighted/report parity including zero-weight query candidates; work boundary and before-solver refusal; invalid/duplicate/known/missing candidates; 200/201 limits; row limit; BOM/order/literal ID/UTF-8 rules; single-run CLI and no partial JSON; and special candidate files.
63
+ - The independent oracle enumerates every binary completion, computes literal metric scores, and groups these completions by the candidate's true label. It compares all conditional endpoints, feasible outcome sets, widths and both reductions. It does not call the production candidate helper or production solver for expected values.
64
+ - Five behavioral mutants are caught with actual assertion failures inspected: optimistic best-case substituted for the guarantee, impossible outcome included, shared input labels mutated, analysis work omitted and label zero used twice. The work omission also triggers mocked-solver errors, but a separate real-solver refusal assertion supplies its evidence. Mutation of shared labels also has direct wrong-metric assertions, not only later exceptions.
65
+ - 450 complete default and 450 complete weighted reports match isolated current-public-base imports. For the 150 single-run cases, removing judgment_value and restoring only the old scoring_work_units yields the same weighted report. Default None leaves the report unchanged.
66
+ - The same-target base does not support this new opt-in API. Its expected TypeError is an additive-feature negative control, not a claim of an old numerical bug.
67
+ - A built wheel installed into a separate Python 3.9 environment passes 158 tests from a neutral directory with no local package import. Ruff check and format pass. The actual README CLI example is checked. No external adoption, annotation campaign or deployment claimed.
68
+
69
+
70
+ ## Paired ranking support
71
+
72
+ `compare(..., judgment_candidates=...)` and the CLI combination of
73
+ `--comparison-ranking` with `--judgment-candidates` use the same shortlist and
74
+ conditional-label semantics. Both rankings share each hypothetical label.
75
+ The conditional solver is `_paired_query`, not a subtraction of single-run
76
+ bounds. The original total/range remains a whole-universe constraint. Every
77
+ candidate is independent of all other candidates in the shortlist.
78
+
79
+ The scope is `single_query_paired_difference_interval_width`. Only metrics
80
+ enabled in the ordinary comparison appear in each outcome and width report:
81
+ precision/recall/nDCG by default, plus RR and/or AP when explicitly requested.
82
+ A narrower difference interval need not establish an ordering or statistical
83
+ significance. The report makes no automatic winner or annotation decision.
84
+ Identical rankings have a zero-width paired difference, even if both rankings'
85
+ single-run intervals are wide; no candidate can shrink that mathematical zero.
86
+
87
+ The original paired work estimate W_q includes its optional RR enumeration and
88
+ AP exponential admission charge. Both hypothetical copies of that full charge
89
+ are reserved per candidate, before **any** paired query is solved. A candidate
90
+ outside the top-k union is still evaluated: its relevance can change a shared
91
+ recall/AP/nDCG denominator. An expensive AP comparison may need a smaller
92
+ shortlist or may be refused. This is conservative admission, not a runtime,
93
+ RAM or output-size guarantee. Existing paired solver workspace requirements
94
+ still apply to each call. No combinations of multiple new labels are scored.
95
+
96
+ Example: universe a,b,c,d, b known relevant, left top 1 a, right top 1 c.
97
+ The precision difference interval is [-1,1], width 2. Learning a=0 leaves
98
+ [-1,0], while a=1 leaves [0,1]. Both widths are 1, so guaranteed and best-case
99
+ reductions are 1. Learning unreturned d leaves the precision interval unchanged.
100
+ This is a reduction in paired difference uncertainty, not a score gain.
101
+
102
+ The same privacy, floating-point, infeasible-outcome and own-query limitations
103
+ above apply. Query weights do not scale these widths or remove zero-weight
104
+ queries. There is no macro or cross-query priority in this feature.
105
+
106
+
107
+ ## Paired support validation
108
+
109
+ 171 tests pass on CPython 3.9 through 3.15. Thirteen new tests include 100 seeded
110
+ two-query exhaustive shared-label completion oracles, all enabled metric
111
+ combinations, forced outcomes, own-query independence and weights, exact work
112
+ boundaries, 200/201-row limits, no-partial-JSON CLI and invalid shortlist refusal.
113
+ The oracle independently enumerates completions and computes literal left and
114
+ right metrics before taking their difference and partitioning by candidate label.
115
+
116
+ 450 default and 450 weighted complete reports match isolated imports of the
117
+ public 1eaaa3db base. Removing only judgment_value and restoring work gives
118
+ report parity across single-run and paired modes. Five behavioral mutants
119
+ produce inspected direct assertion failures: optimistic guarantee, wrong right
120
+ ranking, mutating original labels, omitted work and scoring label 0 twice. Dropping
121
+ optional conditional metrics also causes KeyError, an interface failure rather
122
+ than a numerical assertion. The unchanged public base rejects the new compare
123
+ parameter with TypeError, an additive-feature control, not an old numerical bug.
124
+
125
+ A built wheel installed in a neutral Python 3.9 environment passes 171 tests;
126
+ Ruff check/format and the documented paired CLI example pass. No external use,
127
+ annotation campaign, score improvement or new scientific method is claimed.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Anish Pentyala
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.