File size: 13,636 Bytes
868c741
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
#!/usr/bin/env python3
"""Auditable comparison gate and resource ledger from Chapter 9.

All externally supplied numbers must be integers, decimal/rational strings,
or fractions.Fraction values. Float inputs are deliberately rejected.
The statistical radius uses a rational upper bound for log followed by
an upward rational-grid square root, so rounding cannot make it smaller
than the manuscript's Hoeffding radius.

This module does not establish that an evaluation data source is fresh,
that its conditional mean is the declared risk difference, or that a
claimed numerical-error bound is true. Those are the explicit modeling
obligations in the manuscript. It also does not generate candidates or
claim an empirical RSI speedup.
"""
from __future__ import annotations

import argparse
import json
from dataclasses import dataclass
from fractions import Fraction
from math import isqrt
from pathlib import Path
from typing import Iterable, Optional

F = Fraction


def exact(value) -> F:
    if isinstance(value, float):
        raise TypeError("Use an exact decimal string or Fraction, not a float.")
    if isinstance(value, (int, str, F)):
        return F(value)
    raise TypeError("Expected int, str, or fractions.Fraction.")


def log_series_interval(w: F, terms: int = 24):
    """Bounds for log((1+w)/(1-w)), for 0<=w<=1/3.

    log((1+w)/(1-w)) = 2 sum_{j>=0} w^(2j+1)/(2j+1).
    Its positive omitted tail is at most
    2*w^(2N+1)/((2N+1)*(1-w*w)).
    """
    w = exact(w)
    if not 0 <= w <= F(1, 3) or terms < 1:
        raise ValueError("Require 0<=w<=1/3 and terms>=1.")
    total = F(0)
    power = w
    for j in range(terms):
        total += 2 * power / (2 * j + 1)
        power *= w * w
    tail = 2 * power / ((2 * terms + 1) * (1 - w * w))
    return total, total + tail


def rational_log_upper(x, terms: int = 24) -> F:
    """A rigorous rational upper bound for log(x), x>=1."""
    x = exact(x)
    if x < 1:
        raise ValueError("This function is defined here only for x>=1.")
    k = 0
    y = x
    while y >= 2:
        y /= 2
        k += 1
    _, log_two_upper = log_series_interval(F(1, 3), terms)
    _, log_y_upper = log_series_interval((y - 1) / (y + 1), terms)
    return k * log_two_upper + log_y_upper


def rational_sqrt_upper(x, scale: int = 10**12) -> F:
    """Least multiple of 1/scale whose square is at least exact x."""
    x = exact(x)
    if x < 0 or scale < 1:
        raise ValueError("Require x>=0 and a positive integer grid scale.")
    squared_grid = x * scale * scale
    root = isqrt(squared_grid.numerator // squared_grid.denominator)
    if root * root * squared_grid.denominator < squared_grid.numerator:
        root += 1
    result = F(root, scale)
    assert result * result >= x
    if root:
        assert F(root - 1, scale) ** 2 < x
    return result


def anytime_radius(trial: int, n: int, delta, *, terms: int = 24,
                   scale: int = 10**12) -> F:
    """Rational upper bound for sqrt(2/n log(2t(t+1)n(n+1)/delta))."""
    delta = exact(delta)
    if trial < 1 or n < 1 or not 0 < delta < 1:
        raise ValueError("Require trial,n>=1 and 0<delta<1.")
    log_argument = F(2 * trial * (trial + 1) * n * (n + 1)) / delta
    log_bound = rational_log_upper(log_argument, terms)
    return rational_sqrt_upper(2 * log_bound / n, scale)


@dataclass(frozen=True)
class ComparisonCertificate:
    trial: int
    n: int
    mean: F
    statistical_radius: F
    measurement_radius: F
    delta: F

    @property
    def radius(self):
        return self.statistical_radius + self.measurement_radius

    @property
    def lower(self):
        return self.mean - self.radius

    @property
    def upper(self):
        return self.mean + self.radius

    def to_dict(self):
        return {"trial": self.trial, "n": self.n,
                "mean": str(self.mean), "statistical_radius": str(self.statistical_radius),
                "measurement_radius": str(self.measurement_radius),
                "lower": str(self.lower), "upper": str(self.upper),
                "whole_run_delta": str(self.delta)}


def compare(values: Iterable, *, trial: int, delta,
            measurement_errors: Optional[Iterable] = None) -> ComparisonCertificate:
    """Certify a single frozen paired comparison at any collected sample size.

    values[j] is the recorded incumbent-minus-candidate loss on paired task j.
    measurement_errors[j], if supplied, is a true bound on its recording error.
    Repeated calls may use longer prefixes of the same frozen comparison.
    Use the same whole-run delta and a unique positive trial index per proposal.
    """
    values = [exact(x) for x in values]
    if not values:
        raise ValueError("At least one paired observation is required.")
    if measurement_errors is None:
        errors = [F(0)] * len(values)
    else:
        errors = [exact(x) for x in measurement_errors]
        if len(errors) != len(values):
            raise ValueError("Each observation needs its own error bound.")
    for value, error in zip(values, errors):
        if error < 0 or abs(value) > 1 + error:
            raise ValueError("Error interval must be compatible with a true value in [-1,1].")
    n = len(values)
    return ComparisonCertificate(trial, n, sum(values, F(0)) / n,
                                 anytime_radius(trial, n, delta),
                                 sum(errors, F(0)) / n, exact(delta))


def should_accept(certificate: ComparisonCertificate, margin=0) -> bool:
    margin = exact(margin)
    if margin < 0:
        raise ValueError("The required improvement must be nonnegative.")
    return certificate.lower >= margin


def comparison_action(certificate: ComparisonCertificate, margin=0,
                      *, force_decision: bool = False) -> str:
    """Return accept, reject, or continue for one frozen comparison.

    A resource cap can force a rejection when acceptance is not certified.
    This still obeys the manuscript's finite oracle inequality, with the
    confidence radius at the actual stopping sample size.
    """
    margin = exact(margin)
    if margin < 0:
        raise ValueError("The required improvement must be nonnegative.")
    if certificate.lower >= margin:
        return "accept"
    if certificate.upper < margin or force_decision:
        return "reject"
    return "continue"


class CreditLedger:
    """Exact cost reservation and settlement; rejected trials are charged.

    Credit is in risk-improvement units, cost_weight converts cost units.
    A caller must reserve before undertaking a trial and honor the cap.
    An accepted gain must be a valid nonnegative lower certificate.
    The ledger verifies arithmetic and caps, not the certificate's provenance.
    """

    def __init__(self, initial_credit, cost_weight):
        self.initial_credit = exact(initial_credit)
        self.cost_weight = exact(cost_weight)
        if self.initial_credit < 0 or self.cost_weight <= 0:
            raise ValueError("Require nonnegative credit and positive cost weight.")
        self.credit = self.initial_credit
        self.total_cost = F(0)
        self.total_certified_gain = F(0)
        self.completed_trials = 0
        self._reserved_cap = None

    def _check_accounting(self):
        escrow_cost = self._reserved_cap if self._reserved_cap is not None else F(0)
        assert self.credit >= 0
        assert self.credit + self.cost_weight * escrow_cost == (
            self.initial_credit - self.cost_weight * self.total_cost
            + self.total_certified_gain)

    def reserve(self, cost_cap):
        cap = exact(cost_cap)
        if self._reserved_cap is not None:
            raise RuntimeError("Settle the active reservation before starting another.")
        if cap < 0 or self.cost_weight * cap > self.credit:
            raise ValueError("The full cost cap must fit the available credit.")
        self.credit -= self.cost_weight * cap
        self._reserved_cap = cap
        self._check_accounting()

    def settle(self, actual_cost, *, accepted=False, certified_lower_gain=0):
        cost = exact(actual_cost)
        gain = exact(certified_lower_gain) if accepted else F(0)
        if self._reserved_cap is None:
            raise RuntimeError("Reserve a cost cap before settling a trial.")
        if cost < 0 or cost > self._reserved_cap:
            raise ValueError("Actual cost must stay within the reserved cap.")
        if accepted and not 0 <= gain <= 1:
            raise ValueError("Accepted risk-improvement certificate must lie in [0,1].")
        self.credit += self.cost_weight * (self._reserved_cap - cost) + gain
        self.total_cost += cost
        self.total_certified_gain += gain
        self.completed_trials += 1
        self._reserved_cap = None
        self._check_accounting()

    def to_dict(self):
        return {"initial_credit": str(self.initial_credit),
                "cost_weight": str(self.cost_weight),
                "available_credit": str(self.credit),
                "reserved_cost_cap": (str(self._reserved_cap)
                                      if self._reserved_cap is not None else None),
                "total_cost": str(self.total_cost),
                "total_certified_gain": str(self.total_certified_gain),
                "completed_trials": self.completed_trials}


def self_test():
    assertions = 0
    for w in [F(0), F(1, 10), F(1, 3)]:
        lo, hi = log_series_interval(w, 24)
        lo_more, hi_more = log_series_interval(w, 25)
        assert lo <= lo_more <= hi_more <= hi
        assertions += 1
    lo2, hi2 = log_series_interval(F(1, 3), 24)
    assert F(2, 3) < lo2 < hi2 < F(7, 10)
    assert rational_log_upper(F(1)) == 0
    assert rational_log_upper(F(8)) == 3 * hi2
    assertions += 3
    for x in [F(0), F(1), F(2), F(7, 9), F(137, 17)]:
        b = rational_sqrt_upper(x, scale=10**6)
        assert b * b >= x
        if b:
            assert (b - F(1, 10**6)) ** 2 < x
        assertions += 1
    for T in [1, 2, 7, 50]:
        total = sum((F(1, t * (t + 1)) for t in range(1, T + 1)), F(0))
        assert total == F(T, T + 1) < 1
        assertions += 1

    cert = compare(["3/4"] * 1000, trial=1, delta="1/20")
    assert should_accept(cert, "1/2")
    cert_error = compare(["3/4"] * 1000, trial=1, delta="1/20",
                         measurement_errors=["1/100"] * 1000)
    assert cert_error.lower == cert.lower - F(1, 100)
    assert cert_error.upper == cert.upper + F(1, 100)
    negative = compare(["-1/2"] * 1000, trial=2, delta="1/20")
    assert not should_accept(negative)
    assertions += 4
    ambiguous = compare([0] * 1000, trial=3, delta="1/20")
    assert comparison_action(cert, "1/2") == "accept"
    assert comparison_action(negative) == "reject"
    assert comparison_action(ambiguous) == "continue"
    assert comparison_action(ambiguous, force_decision=True) == "reject"
    assertions += 4

    ledger = CreditLedger("1/10", "1/1000")
    ledger.reserve(50)
    ledger.settle(40, accepted=False)
    assert ledger.credit == F(3, 50)
    ledger.reserve(50)
    ledger.settle(50, accepted=True, certified_lower_gain=cert.lower)
    assert ledger.credit == F(1, 100) + cert.lower
    ledger.reserve(60)
    ledger.settle(30, accepted=False)
    assert ledger.total_cost == 120
    assert ledger.cost_weight * ledger.total_cost <= (
        ledger.initial_credit + ledger.total_certified_gain)
    assertions += 4

    # Pathwise oracle inequality under declared valid intervals.
    incumbent = F(9, 10)
    initial = incumbent
    candidates = [F(7, 10), F(4, 5), F(1, 5), F(1, 4)]
    radius, margin = F(1, 20), F(1, 50)
    offsets = [-radius / 2, radius / 2, -radius / 2, radius / 2]
    accepted_margins = F(0)
    for candidate, offset in zip(candidates, offsets):
        delta = incumbent - candidate
        lower = delta + offset - radius
        upper = delta + offset + radius
        assert lower <= delta <= upper
        if lower >= margin:
            incumbent = candidate
            accepted_margins += margin
        assert incumbent <= initial - accepted_margins
        assertions += 2
    assert incumbent == F(1, 5)
    assert incumbent <= min(candidates) + margin + 2 * radius
    assertions += 2

    # API guard checks must fail before any incorrect ledger mutation.
    try:
        exact(0.1)
        raise AssertionError("Float guard did not trigger")
    except TypeError:
        assertions += 1
    before = ledger.to_dict()
    try:
        ledger.reserve(10**10)
        raise AssertionError("Unaffordable reservation was accepted")
    except ValueError:
        assert ledger.to_dict() == before
        assertions += 1

    return {"all_checks_passed": True, "reported_assertion_groups": assertions,
            "arithmetic": "exact rational log-series bound and upward square-root grid",
            "acceptance_example": cert.to_dict(),
            "ledger_example": ledger.to_dict(),
            "scope": "Arithmetic and accounting audits; probability and data contracts are proved/stated in Chapter 9."}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--self-test", action="store_true")
    parser.add_argument("--output", type=Path)
    args = parser.parse_args()
    if not args.self_test:
        parser.print_help()
        return
    report = self_test()
    if args.output:
        args.output.parent.mkdir(parents=True, exist_ok=True)
        args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
    print(json.dumps(report, indent=2))


if __name__ == "__main__":
    main()