rcc-refcert 0.1.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.
@@ -0,0 +1,63 @@
1
+ """Structure-fair analysis and reference certificates for quantum processes."""
2
+
3
+ from ._version import __version__
4
+ from .audit import (
5
+ CaseAnalysis,
6
+ DepthAgreement,
7
+ ModelAnalysis,
8
+ ReferenceSuite,
9
+ audit_case,
10
+ audit_model,
11
+ audit_reference_suite,
12
+ )
13
+ from .bellman_choi import BellmanChoiCertificate, BellmanChoiReport, verify_bellman_choi
14
+ from .cases import CASES, CaseStudy, get_case
15
+ from .domination import DominationResult, minimum_domination_constant
16
+ from .fixed_point import linear_value_choi_envelopes
17
+ from .gain_cost import (
18
+ ActionGainCost,
19
+ GainCostReport,
20
+ SyntaxGainCost,
21
+ analyze_reference_gain_cost,
22
+ )
23
+ from .model import Action, FiniteControlModel, ModelValidationError, require_valid_model
24
+ from .reference_potential import (
25
+ CertificateReport,
26
+ ReferencePotentialCertificate,
27
+ verify_reference_potential,
28
+ )
29
+ from .status import CheckOutcome, CheckResult, EvidenceLevel
30
+
31
+ __all__ = [
32
+ "CASES",
33
+ "Action",
34
+ "ActionGainCost",
35
+ "BellmanChoiCertificate",
36
+ "BellmanChoiReport",
37
+ "CaseAnalysis",
38
+ "CaseStudy",
39
+ "CertificateReport",
40
+ "CheckOutcome",
41
+ "CheckResult",
42
+ "DepthAgreement",
43
+ "DominationResult",
44
+ "EvidenceLevel",
45
+ "FiniteControlModel",
46
+ "GainCostReport",
47
+ "ModelAnalysis",
48
+ "ModelValidationError",
49
+ "ReferencePotentialCertificate",
50
+ "ReferenceSuite",
51
+ "SyntaxGainCost",
52
+ "__version__",
53
+ "analyze_reference_gain_cost",
54
+ "audit_case",
55
+ "audit_model",
56
+ "audit_reference_suite",
57
+ "get_case",
58
+ "linear_value_choi_envelopes",
59
+ "minimum_domination_constant",
60
+ "require_valid_model",
61
+ "verify_bellman_choi",
62
+ "verify_reference_potential",
63
+ ]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,3 @@
1
+ """Package version shared by source and distribution metadata."""
2
+
3
+ __version__ = "0.1.0"
rcc_refcert/audit.py ADDED
@@ -0,0 +1,421 @@
1
+ from __future__ import annotations
2
+
3
+ import itertools
4
+ from collections.abc import Iterable
5
+ from dataclasses import dataclass, field
6
+ from decimal import Decimal
7
+
8
+ import numpy as np
9
+
10
+ from .bellman_choi import BellmanChoiReport, verify_bellman_choi
11
+ from .cases import (
12
+ CASES,
13
+ H1_REALIZATION,
14
+ H2_LINEAR_FIXED_POINT,
15
+ H3_BELLMAN_CHOI,
16
+ H4_REFERENCE_POTENTIAL,
17
+ H6_GAIN_COST,
18
+ H34_DOMINATION,
19
+ CaseStudy,
20
+ )
21
+ from .domination import DominationResult, minimum_domination_constant
22
+ from .examples import (
23
+ gamma5_summary,
24
+ global_reset_family_constants,
25
+ make_f5_two_qubit_witness,
26
+ make_global_reset_loop_model,
27
+ make_same_space_reference_envelopes,
28
+ natural_c_gt_one_interval,
29
+ )
30
+ from .fixed_point import FixedPointResult, linear_fixed_point
31
+ from .gain_cost import GainCostReport, analyze_reference_gain_cost
32
+ from .model import FiniteControlModel, require_valid_model
33
+ from .quantum import Array
34
+ from .rank_encoding import decode_word, encode_word
35
+ from .reference_potential import CertificateReport, verify_reference_potential
36
+ from .semantics import (
37
+ depth_contribution_by_enumeration,
38
+ depth_contribution_by_maps,
39
+ truncated_semidensity,
40
+ )
41
+ from .status import CheckOutcome, EvidenceLevel
42
+
43
+
44
+ def _linear_fixed_point_outcome(
45
+ result: FixedPointResult,
46
+ tolerance: float,
47
+ ) -> CheckOutcome:
48
+ if not result.applicable:
49
+ return CheckOutcome.NOT_APPLICABLE
50
+ if (
51
+ result.output is None
52
+ or result.output_valid is not True
53
+ or result.condition_number is None
54
+ or result.solve_residual is None
55
+ or not np.isfinite(result.condition_number)
56
+ or not np.isfinite(result.solve_residual)
57
+ or result.solve_residual > tolerance
58
+ or result.condition_number * np.finfo(float).eps > tolerance
59
+ ):
60
+ return CheckOutcome.INCONCLUSIVE
61
+ return CheckOutcome.PASS
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class DepthAgreement:
66
+ """One finite-depth check of the Appendix-H realization identity."""
67
+
68
+ action_depth: int
69
+ spectral_norm_error: float
70
+ outcome: CheckOutcome
71
+ evidence: EvidenceLevel = EvidenceLevel.NUMERICAL
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class ModelAnalysis:
76
+ """Numerical H.1, H.2, and H.34 results for one finite-control model."""
77
+
78
+ model_name: str
79
+ tolerance: float
80
+ realization_checks: tuple[DepthAgreement, ...]
81
+ max_transient_steps: int
82
+ truncated_trace: float
83
+ fixed_point: FixedPointResult
84
+ fixed_model_domination: DominationResult | None
85
+ notes: tuple[str, ...]
86
+ truncated_output: Array = field(repr=False, compare=False)
87
+
88
+ @property
89
+ def maximum_realization_error(self) -> float:
90
+ return max(
91
+ (check.spectral_norm_error for check in self.realization_checks),
92
+ default=0.0,
93
+ )
94
+
95
+ @property
96
+ def realization_outcome(self) -> CheckOutcome:
97
+ return (
98
+ CheckOutcome.PASS
99
+ if all(
100
+ check.outcome is CheckOutcome.PASS for check in self.realization_checks
101
+ )
102
+ else CheckOutcome.FAIL
103
+ )
104
+
105
+ @property
106
+ def linear_fixed_point_outcome(self) -> CheckOutcome:
107
+ return _linear_fixed_point_outcome(self.fixed_point, self.tolerance)
108
+
109
+ @property
110
+ def domination_outcome(self) -> CheckOutcome:
111
+ if self.fixed_model_domination is None:
112
+ return CheckOutcome.INCONCLUSIVE
113
+ return self.fixed_model_domination.outcome
114
+
115
+
116
+ @dataclass(frozen=True)
117
+ class CaseAnalysis:
118
+ """A bundled case with every supplied certificate checked once."""
119
+
120
+ case: CaseStudy
121
+ model: FiniteControlModel = field(repr=False, compare=False)
122
+ model_analysis: ModelAnalysis
123
+ bellman_choi: BellmanChoiReport | None
124
+ reference_potentials: tuple[CertificateReport, ...]
125
+ gain_cost: GainCostReport | None
126
+
127
+ def observed_outcomes(self) -> tuple[tuple[str, CheckOutcome], ...]:
128
+ outcomes: list[tuple[str, CheckOutcome]] = [
129
+ (H1_REALIZATION, self.model_analysis.realization_outcome),
130
+ (H2_LINEAR_FIXED_POINT, self.model_analysis.linear_fixed_point_outcome),
131
+ (H34_DOMINATION, self.model_analysis.domination_outcome),
132
+ ]
133
+ if self.bellman_choi is not None:
134
+ outcomes.append((H3_BELLMAN_CHOI, self.bellman_choi.outcome))
135
+ if self.reference_potentials:
136
+ outcomes.append(
137
+ (
138
+ H4_REFERENCE_POTENTIAL,
139
+ _aggregate_outcomes(
140
+ report.outcome for report in self.reference_potentials
141
+ ),
142
+ )
143
+ )
144
+ if self.gain_cost is not None:
145
+ outcomes.append((H6_GAIN_COST, self.gain_cost.outcome))
146
+ return tuple(outcomes)
147
+
148
+ @property
149
+ def expectation_mismatches(self) -> tuple[str, ...]:
150
+ observed = dict(self.observed_outcomes())
151
+ mismatches = []
152
+ for name, expected in self.case.expected_outcomes:
153
+ actual = observed.get(name, CheckOutcome.NOT_APPLICABLE)
154
+ if actual is not expected:
155
+ mismatches.append(
156
+ f"{name}: expected {expected.value}, observed {actual.value}"
157
+ )
158
+ return tuple(mismatches)
159
+
160
+ @property
161
+ def matches_expectations(self) -> bool:
162
+ return not self.expectation_mismatches
163
+
164
+
165
+ @dataclass(frozen=True)
166
+ class AppendixFWitnesses:
167
+ """Structured results for executable witnesses outside the case models."""
168
+
169
+ rank_roundtrip_count: int
170
+ rank_roundtrip_failures: int
171
+ gamma5_reference_balance_error: float
172
+ gamma5_word_average_errors: tuple[float, ...]
173
+ gamma5_partial_kraft_mass: float
174
+ f5_reset_balance_error: float
175
+ f5_generation_error: float
176
+ f5_initial_purity: float
177
+ f5_final_purity: float
178
+ natural_constant_lower: Decimal
179
+ natural_constant_upper: Decimal
180
+ global_reset_constants: tuple[tuple[int, int], ...]
181
+ global_reset_gain_costs: tuple[GainCostReport, ...]
182
+
183
+ def matches_reference_expectations(self, tolerance: float) -> bool:
184
+ expected_rank_count = sum(5**length for length in range(5))
185
+ expected_reset_constants = tuple((n, 2**n) for n in range(1, 9))
186
+ natural_interval_ok = Decimal(
187
+ 1
188
+ ) < self.natural_constant_lower <= self.natural_constant_upper < Decimal(
189
+ 2
190
+ ) and self.natural_constant_upper - self.natural_constant_lower < Decimal(
191
+ "1e-29"
192
+ )
193
+ gain_cost_expected = all(
194
+ report.outcome is CheckOutcome.FAIL
195
+ and all(
196
+ syntax.suggested_condition_satisfied for syntax in report.syntax_reports
197
+ )
198
+ for report in self.global_reset_gain_costs
199
+ )
200
+ return (
201
+ self.rank_roundtrip_count == expected_rank_count
202
+ and self.rank_roundtrip_failures == 0
203
+ and self.gamma5_reference_balance_error <= tolerance
204
+ and len(self.gamma5_word_average_errors) == 5
205
+ and max(self.gamma5_word_average_errors, default=0.0) <= tolerance
206
+ and self.gamma5_partial_kraft_mass <= 1.0 + tolerance
207
+ and self.f5_reset_balance_error <= tolerance
208
+ and self.f5_generation_error <= tolerance
209
+ and abs(self.f5_initial_purity - 0.25) <= tolerance
210
+ and abs(self.f5_final_purity - 1.0) <= tolerance
211
+ and natural_interval_ok
212
+ and self.global_reset_constants == expected_reset_constants
213
+ and len(self.global_reset_gain_costs) == 4
214
+ and gain_cost_expected
215
+ )
216
+
217
+
218
+ @dataclass(frozen=True)
219
+ class ReferenceSuite:
220
+ """One deterministic execution of the bundled RCC reference suite."""
221
+
222
+ max_depth: int
223
+ max_transient_steps: int
224
+ tolerance: float
225
+ cases: tuple[CaseAnalysis, ...]
226
+ appendix_f: AppendixFWitnesses
227
+
228
+ @property
229
+ def matches_reference_expectations(self) -> bool:
230
+ return all(case.matches_expectations for case in self.cases) and (
231
+ self.appendix_f.matches_reference_expectations(self.tolerance)
232
+ )
233
+
234
+
235
+ def _aggregate_outcomes(outcomes: Iterable[CheckOutcome]) -> CheckOutcome:
236
+ values = tuple(outcomes)
237
+ if not values or all(value is CheckOutcome.NOT_APPLICABLE for value in values):
238
+ return CheckOutcome.NOT_APPLICABLE
239
+ if any(value is CheckOutcome.FAIL for value in values):
240
+ return CheckOutcome.FAIL
241
+ if any(value is CheckOutcome.INCONCLUSIVE for value in values):
242
+ return CheckOutcome.INCONCLUSIVE
243
+ return CheckOutcome.PASS
244
+
245
+
246
+ def audit_model(
247
+ model: FiniteControlModel,
248
+ *,
249
+ max_depth: int = 8,
250
+ max_transient_steps: int = 16,
251
+ tol: float = 1e-10,
252
+ ) -> ModelAnalysis:
253
+ """Compute bounded H.1 checks, H.2 diagnostics, and the H.34 constant."""
254
+
255
+ if max_depth < 1:
256
+ raise ValueError("max_depth must be at least one")
257
+ if max_transient_steps < 0:
258
+ raise ValueError("max_transient_steps must be nonnegative")
259
+ if not np.isfinite(tol) or tol <= 0:
260
+ raise ValueError("tol must be finite and positive")
261
+ require_valid_model(model, tol=tol)
262
+
263
+ realization: list[DepthAgreement] = []
264
+ for depth in range(1, max_depth + 1):
265
+ enumerated = depth_contribution_by_enumeration(model, depth)
266
+ realized = depth_contribution_by_maps(model, depth)
267
+ error = float(np.linalg.norm(enumerated - realized, ord=2))
268
+ realization.append(
269
+ DepthAgreement(
270
+ action_depth=depth,
271
+ spectral_norm_error=error,
272
+ outcome=(CheckOutcome.PASS if error <= tol else CheckOutcome.FAIL),
273
+ )
274
+ )
275
+
276
+ truncated = truncated_semidensity(model, max_transient_steps)
277
+ fixed = linear_fixed_point(model, tol=tol)
278
+ fixed_outcome = _linear_fixed_point_outcome(fixed, tol)
279
+ domination = (
280
+ minimum_domination_constant(fixed.output, model.reference_state, tol=tol)
281
+ if fixed_outcome is CheckOutcome.PASS and fixed.output is not None
282
+ else None
283
+ )
284
+ notes = [
285
+ "Finite-depth agreement provides numerical implementation evidence for H.1.",
286
+ "The H.34 constant belongs to this fixed model; family uniformity adds a uniform analytic bound.",
287
+ ]
288
+ if not fixed.applicable:
289
+ notes.append(
290
+ "The linear inverse is at its spectral boundary. The minimum fixed-point "
291
+ "semantics remains in force, and H.34 awaits the completed semidensity."
292
+ )
293
+ elif fixed_outcome is CheckOutcome.INCONCLUSIVE:
294
+ notes.append(
295
+ "The linear solve is inconclusive at this tolerance; inspect its condition "
296
+ "number, residual and output-validity diagnostic."
297
+ )
298
+
299
+ return ModelAnalysis(
300
+ model_name=model.name,
301
+ tolerance=float(tol),
302
+ realization_checks=tuple(realization),
303
+ max_transient_steps=max_transient_steps,
304
+ truncated_trace=float(np.trace(truncated).real),
305
+ fixed_point=fixed,
306
+ fixed_model_domination=domination,
307
+ notes=tuple(notes),
308
+ truncated_output=truncated,
309
+ )
310
+
311
+
312
+ def audit_case(
313
+ case: CaseStudy,
314
+ *,
315
+ max_depth: int = 8,
316
+ max_transient_steps: int = 16,
317
+ tol: float = 1e-10,
318
+ ) -> CaseAnalysis:
319
+ """Run the process and every supplied proof object for one bundled case."""
320
+
321
+ model = case.model_factory()
322
+ model_analysis = audit_model(
323
+ model,
324
+ max_depth=max_depth,
325
+ max_transient_steps=max_transient_steps,
326
+ tol=tol,
327
+ )
328
+ bellman = (
329
+ verify_bellman_choi(model, case.bellman_factory(model), tol=tol)
330
+ if case.bellman_factory is not None
331
+ else None
332
+ )
333
+ potentials = (
334
+ tuple(
335
+ verify_reference_potential(model, certificate, tol=tol)
336
+ for certificate in case.potential_factory(model)
337
+ )
338
+ if case.potential_factory is not None
339
+ else ()
340
+ )
341
+ gain_cost = (
342
+ analyze_reference_gain_cost(model, case.envelope_factory(model), tol=tol)
343
+ if case.envelope_factory is not None
344
+ else None
345
+ )
346
+ return CaseAnalysis(
347
+ case=case,
348
+ model=model,
349
+ model_analysis=model_analysis,
350
+ bellman_choi=bellman,
351
+ reference_potentials=potentials,
352
+ gain_cost=gain_cost,
353
+ )
354
+
355
+
356
+ def _appendix_f_witnesses(tol: float) -> AppendixFWitnesses:
357
+ gamma = 5
358
+ rank_count = 0
359
+ rank_failures = 0
360
+ for length in range(5):
361
+ for word in itertools.product(range(gamma), repeat=length):
362
+ rank_count += 1
363
+ if decode_word(encode_word(word, gamma), gamma) != word:
364
+ rank_failures += 1
365
+
366
+ gamma5 = gamma5_summary(5)
367
+ f5 = make_f5_two_qubit_witness()
368
+ lower, upper = natural_c_gt_one_interval(100)
369
+
370
+ reset_reports = []
371
+ for n in range(1, 5):
372
+ model = make_global_reset_loop_model(n)
373
+ reset_reports.append(
374
+ analyze_reference_gain_cost(
375
+ model,
376
+ make_same_space_reference_envelopes(model),
377
+ tol=tol,
378
+ )
379
+ )
380
+
381
+ return AppendixFWitnesses(
382
+ rank_roundtrip_count=rank_count,
383
+ rank_roundtrip_failures=rank_failures,
384
+ gamma5_reference_balance_error=gamma5.reference_balance_error,
385
+ gamma5_word_average_errors=gamma5.word_average_errors,
386
+ gamma5_partial_kraft_mass=gamma5.partial_kraft_mass,
387
+ f5_reset_balance_error=max(f5.reset_pair_balance_errors),
388
+ f5_generation_error=f5.generation_error,
389
+ f5_initial_purity=f5.initial_purity,
390
+ f5_final_purity=f5.final_purity,
391
+ natural_constant_lower=lower,
392
+ natural_constant_upper=upper,
393
+ global_reset_constants=tuple(global_reset_family_constants(8)),
394
+ global_reset_gain_costs=tuple(reset_reports),
395
+ )
396
+
397
+
398
+ def audit_reference_suite(
399
+ *,
400
+ max_depth: int = 8,
401
+ max_transient_steps: int = 16,
402
+ tol: float = 1e-10,
403
+ ) -> ReferenceSuite:
404
+ """Run every bundled case and Appendix F witness deterministically."""
405
+
406
+ cases = tuple(
407
+ audit_case(
408
+ case,
409
+ max_depth=max_depth,
410
+ max_transient_steps=max_transient_steps,
411
+ tol=tol,
412
+ )
413
+ for case in CASES
414
+ )
415
+ return ReferenceSuite(
416
+ max_depth=max_depth,
417
+ max_transient_steps=max_transient_steps,
418
+ tolerance=float(tol),
419
+ cases=cases,
420
+ appendix_f=_appendix_f_witnesses(tol),
421
+ )