rankbounds 0.3.0__py3-none-any.whl

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.
rankbounds/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Deterministic bounds, not predictions of unknown relevance."""
2
+
3
+ from .core import BoundsError, audit
4
+ from .paired import compare
5
+
6
+ __version__ = "0.3.0"
7
+ __all__ = ["BoundsError", "audit", "compare"]
rankbounds/__main__.py ADDED
@@ -0,0 +1,142 @@
1
+ """Read-only local CSV command line."""
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+
7
+ from .core import BoundsError, audit
8
+ from .paired import compare
9
+
10
+
11
+ def _write_text(stream, text):
12
+ if stream is None:
13
+ raise OSError("output stream is unavailable")
14
+ written = stream.write(text)
15
+ if type(written) is not int or written != len(text):
16
+ raise OSError("output stream did not accept the complete text")
17
+ stream.flush()
18
+
19
+
20
+ class _ArgumentParser(argparse.ArgumentParser):
21
+ def _print_message(self, message, file=None):
22
+ # Recent argparse versions suppress immediate write errors. Keep them
23
+ # visible to main's error boundary, including unbuffered --help output.
24
+ if message:
25
+ _write_text(sys.stderr if file is None else file, message)
26
+
27
+
28
+ def _error(message):
29
+ """Diagnostics are best effort; a broken stderr must not hide failure."""
30
+ try:
31
+ _write_text(sys.stderr, "rankbounds: " + message + "\n")
32
+ except (OSError, ValueError):
33
+ pass
34
+ return 2
35
+
36
+
37
+ def _parser():
38
+ parser = _ArgumentParser(
39
+ description="Binary retrieval metric compatibility intervals, not confidence intervals."
40
+ )
41
+ parser.add_argument("--universe", required=True)
42
+ parser.add_argument("--ranking", required=True)
43
+ parser.add_argument("--judgments", required=True)
44
+ parser.add_argument(
45
+ "--comparison-ranking",
46
+ help="Right ranking for shared-label left-minus-right bounds",
47
+ )
48
+ parser.add_argument(
49
+ "--paired-rr",
50
+ action="store_true",
51
+ help="Also bound paired reciprocal rank; requires --comparison-ranking",
52
+ )
53
+ parser.add_argument(
54
+ "--paired-ap",
55
+ action="store_true",
56
+ help="Also bound paired AP/total-R by budgeted enumeration; requires --comparison-ranking",
57
+ )
58
+ constraints = parser.add_mutually_exclusive_group()
59
+ constraints.add_argument("--totals")
60
+ constraints.add_argument("--total-ranges")
61
+ parser.add_argument(
62
+ "--query-weights",
63
+ help="CSV query_id,weight for an additional fixed-weight aggregate",
64
+ )
65
+ parser.add_argument(
66
+ "--judgment-candidates",
67
+ help="CSV query_id,document_id for hypothetical own-query judgment values",
68
+ )
69
+ parser.add_argument("--k", type=int, required=True)
70
+ parser.add_argument("--examples", type=int, default=0)
71
+ parser.add_argument("--max-rows", type=int, default=1_000_000)
72
+ parser.add_argument("--max-work", type=int, default=5_000_000)
73
+ return parser
74
+
75
+
76
+ def main(argv=None):
77
+ try:
78
+ args = _parser().parse_args(argv)
79
+ except (OSError, ValueError) as exc:
80
+ return _error("output failed: " + str(exc))
81
+ try:
82
+ if args.paired_rr and not args.comparison_ranking:
83
+ raise BoundsError("--paired-rr requires --comparison-ranking")
84
+ if args.paired_ap and not args.comparison_ranking:
85
+ raise BoundsError("--paired-ap requires --comparison-ranking")
86
+ options = (
87
+ {"include_rr": args.paired_rr, "include_ap": args.paired_ap}
88
+ if args.comparison_ranking
89
+ else {}
90
+ )
91
+ if args.judgment_candidates is not None:
92
+ options["judgment_candidates"] = args.judgment_candidates
93
+ function = compare if args.comparison_ranking else audit
94
+ inputs = [args.universe, args.ranking]
95
+ if args.comparison_ranking:
96
+ inputs.append(args.comparison_ranking)
97
+ inputs.append(args.judgments)
98
+ report = function(
99
+ *inputs,
100
+ k=args.k,
101
+ totals=args.totals,
102
+ total_ranges=args.total_ranges,
103
+ query_weights=args.query_weights,
104
+ examples=args.examples,
105
+ max_rows=args.max_rows,
106
+ max_work=args.max_work,
107
+ **options,
108
+ )
109
+ except BoundsError as exc:
110
+ return _error(str(exc))
111
+ payload = json.dumps(report, sort_keys=True, indent=2, allow_nan=False) + "\n"
112
+ try:
113
+ _write_text(sys.stdout, payload)
114
+ except (OSError, ValueError) as exc:
115
+ return _error("output failed: " + str(exc))
116
+ return 0
117
+
118
+
119
+ def cli(argv=None):
120
+ """Process entry point, including help/error exits and final stream flushes."""
121
+ try:
122
+ status = main(argv)
123
+ except SystemExit as exc:
124
+ status = exc.code if isinstance(exc.code, int) else 0 if exc.code is None else 1
125
+ for name in ("stdout", "stderr"):
126
+ stream = getattr(sys, name)
127
+ if stream is None:
128
+ continue
129
+ try:
130
+ stream.flush()
131
+ except (OSError, ValueError) as exc:
132
+ if name == "stdout" and status == 0:
133
+ _error("output failed: " + str(exc))
134
+ # This wrapper is only for the terminating CLI process. Do not let
135
+ # Python retry a failed flush at shutdown and replace exit 2 with 120.
136
+ setattr(sys, name, None)
137
+ status = 2
138
+ return status
139
+
140
+
141
+ if __name__ == "__main__":
142
+ sys.exit(cli())
@@ -0,0 +1,91 @@
1
+ """Budgeted shared-label enumeration for paired AP with total-R denominator."""
2
+
3
+ import math
4
+
5
+ from .core import _total_limits
6
+
7
+
8
+ def _ap_numerator(run_bits, positive_mask):
9
+ hits = 0
10
+ terms = []
11
+ for rank, bit in enumerate(run_bits, 1):
12
+ if bit & positive_mask:
13
+ hits += 1
14
+ terms.append(hits / rank)
15
+ return math.fsum(terms)
16
+
17
+
18
+ def _feasible_masks(width, lower, upper):
19
+ """Yield ascending masks whose popcount is in the inclusive count range."""
20
+ if lower == 0 and upper == width:
21
+ yield from range(1 << width)
22
+ return
23
+
24
+ def visit(bits, low, high, prefix):
25
+ if low > bits or high < 0:
26
+ return
27
+ if low <= 0 and high >= bits:
28
+ yield from range(prefix, prefix + (1 << bits))
29
+ return
30
+ # Highest remaining bit off before on preserves the old integer order.
31
+ yield from visit(bits - 1, low, high, prefix)
32
+ yield from visit(bits - 1, low - 1, high - 1, prefix | (1 << (bits - 1)))
33
+
34
+ yield from visit(width, lower, upper, 0)
35
+
36
+
37
+ def _average_precision_bounds(left, right, labels, size, total, examples):
38
+ """Only called after whole-audit exponential-work admission succeeds."""
39
+ unknown = sorted((set(left) | set(right)) - set(labels))
40
+ fixed = {doc for doc, value in labels.items() if value}
41
+ outside = size - len(labels) - len(unknown)
42
+ total_low, total_high = _total_limits(total, len(fixed), size - len(labels))
43
+ bounds = {"lower": None, "upper": None}
44
+ witnesses = {}
45
+ # A union subset with c positives is feasible iff its total interval
46
+ # [known+c, known+c+outside] intersects the declared total interval.
47
+ count_low = max(0, total_low - len(fixed) - outside)
48
+ count_high = min(len(unknown), total_high - len(fixed))
49
+ # Unknown bits retain the lexical subset indices used by _feasible_masks.
50
+ # A separate always-on bit represents every known-positive document.
51
+ fixed_bit = 1 << len(unknown)
52
+ bits = {doc: 1 << index for index, doc in enumerate(unknown)}
53
+ run_bits = [
54
+ [bits.get(doc, fixed_bit if labels.get(doc) == 1 else 0) for doc in run]
55
+ for run in (left, right)
56
+ ]
57
+ popcount = getattr(int, "bit_count", None)
58
+ for mask in _feasible_masks(len(unknown), count_low, count_high):
59
+ count = popcount(mask) if popcount else bin(mask).count("1")
60
+ low = len(fixed) + count
61
+ high = low + outside
62
+ union_relevant = low
63
+ low, high = max(low, total_low), min(high, total_high)
64
+ if low > high:
65
+ continue
66
+ # For this shared union assignment only the common denominator varies.
67
+ totals = (low,) if low == high else (low, high)
68
+ numerators = [_ap_numerator(run, mask | fixed_bit) for run in run_bits]
69
+ for relevant in totals:
70
+ scores = [value / relevant if relevant else 0.0 for value in numerators]
71
+ value = scores[0] - scores[1]
72
+ for direction in ("lower", "upper"):
73
+ previous = bounds[direction]
74
+ if previous is None or (
75
+ value < previous if direction == "lower" else value > previous
76
+ ):
77
+ bounds[direction] = value
78
+ if examples:
79
+ witnesses[direction] = {
80
+ "total_relevant": relevant,
81
+ "unjudged_union_relevant": [
82
+ doc
83
+ for index, doc in enumerate(unknown)
84
+ if mask & (1 << index)
85
+ ],
86
+ "unjudged_outside_union_relevant_count": relevant
87
+ - union_relevant,
88
+ "left_score": scores[0],
89
+ "right_score": scores[1],
90
+ }
91
+ return bounds, witnesses