#!/usr/bin/env python3 """Independent finite checks for scenario cover and joint failure severity. Only the Python standard library is used. The scalar rank oracle and rational row elimination below are independent of the package's calibration code. These exhaustive finite examples check formulas; they are not formal proofs or evidence that an arbitrary large design is robust. """ from __future__ import annotations import argparse from fractions import Fraction from itertools import product from math import comb from pathlib import Path import json def rational_rank(rows: list[list[Fraction]]) -> int: if not rows: return 0 a = [list(map(Fraction, row)) for row in rows] ncols = len(a[0]) pivot_row = 0 for col in range(ncols): pivot = next((i for i in range(pivot_row, len(a)) if a[i][col]), None) if pivot is None: continue a[pivot_row], a[pivot] = a[pivot], a[pivot_row] scale = a[pivot_row][col] a[pivot_row] = [x / scale for x in a[pivot_row]] for i in range(pivot_row + 1, len(a)): scale = a[i][col] if scale: a[i] = [x - scale * y for x, y in zip(a[i], a[pivot_row])] pivot_row += 1 if pivot_row == len(a): break return pivot_row def members(mask: int, n: int) -> list[int]: return [i for i in range(n) if mask & (1 << i)] def frac_string(value: Fraction) -> str: return str(value.numerator) if value.denominator == 1 else str(value) def scalar_checks() -> dict: n = 4 full = (1 << n) - 1 # Column j is visible to precisely the channels indicated by visible[j]. # Channel visibility sets are {0,1}, {1,2}, {0,2}, {0,1,2}. visible = [0b1101, 0b1011, 0b1110] masks = list(range(1 << n)) records = [] total_submodular_pairs = total_monotone_pairs = 0 total_target_checks = total_cost_instances = 0 zero_optimum_instances = 0 worst_ratio = Fraction(1) worst_instance = None equal_cost_one_failure = None for budget in range(3): scenarios = [f for f in masks if f.bit_count() <= budget] target = len(scenarios) * len(visible) values = { s: sum(bool((s & ~f) & v) for f in scenarios for v in visible) for s in masks } assert values[0] == 0 and values[full] == target for s in masks: assert isinstance(values[s], int) and 0 <= values[s] <= target coverage = [(s & v).bit_count() for v in visible] assert (values[s] == target) == all(c >= budget + 1 for c in coverage) total_target_checks += 1 for t in masks: assert values[s] + values[t] >= values[s | t] + values[s & t] total_submodular_pairs += 1 if s & t == s: assert values[s] <= values[t] total_monotone_pairs += 1 budget_worst = Fraction(1) for costs in product(range(4), repeat=n): initial = sum(1 << a for a, cost in enumerate(costs) if cost == 0) selected = initial initial_deficit = target - values[initial] path = [] while values[selected] < target: options = [] for a, cost in enumerate(costs): if selected & (1 << a): continue gain = values[selected | (1 << a)] - values[selected] if gain > 0: options.append((Fraction(cost, gain), a, gain)) assert options ratio, a, gain = min(options) selected |= 1 << a path.append({"channel": a, "gain": gain, "cost_per_gain": frac_string(ratio)}) greedy_cost = sum(costs[a] for a in members(selected, n)) optimal_cost, optimal_mask = min( (sum(costs[a] for a in members(s, n)), s) for s in masks if values[s] == target ) harmonic = sum((Fraction(1, i) for i in range(1, initial_deficit + 1)), start=Fraction(0)) if initial_deficit == 0: assert greedy_cost == optimal_cost == 0 else: assert greedy_cost <= harmonic * optimal_cost if optimal_cost == 0: zero_optimum_instances += 1 assert greedy_cost == 0 else: ratio = Fraction(greedy_cost, optimal_cost) budget_worst = max(budget_worst, ratio) if ratio > worst_ratio: worst_ratio = ratio worst_instance = { "failure_budget": budget, "costs": list(costs), "initial_zero_cost_channels": members(initial, n), "initial_deficit": initial_deficit, "harmonic_bound_factor": frac_string(harmonic), "greedy_channels": members(selected, n), "greedy_cost": greedy_cost, "optimal_channels": members(optimal_mask, n), "optimal_cost": optimal_cost, "greedy_to_optimal_ratio": frac_string(ratio), "greedy_path": path, } if budget == 1 and costs == (1, 1, 1, 1): assert optimal_cost == greedy_cost == 3 equal_cost_one_failure = { "costs": list(costs), "optimal_cost": optimal_cost, "one_optimal_selection": members(optimal_mask, n), "greedy_selection": members(selected, n), "greedy_path": path, } total_cost_instances += 1 records.append({ "failure_budget": budget, "scenario_count": len(scenarios), "target": target, "objective_by_selection_mask": values, "cost_vectors_checked": 4 ** n, "worst_greedy_to_optimal_ratio": frac_string(budget_worst), }) # The pointwise minimum of deletion ranks does not inherit submodularity. def minimum_surviving_rank(s: int) -> int: return min(int(bool(s & ~f)) for f in range(4) if f & s == f and f.bit_count() <= 1) g = [minimum_surviving_rank(s) for s in range(4)] assert g == [0, 0, 0, 1] assert g[1] + g[2] < g[0] + g[3] # A specified scenario list only certifies that list. The empty deletion # scenario certifies scalar identification with one channel, not 1-error # correction, which would require distance greater than two. arbitrary_family_target = 1 arbitrary_family_value = int(bool(1)) one_channel_distance = 1 assert arbitrary_family_value == arbitrary_family_target assert not one_channel_distance > 2 return { "catalogue_visibility_by_channel": [[0, 1], [1, 2], [0, 2], [0, 1, 2]], "budgets_checked": [0, 1, 2], "submodular_ordered_pairs_checked": total_submodular_pairs, "monotone_ordered_pairs_checked": total_monotone_pairs, "target_equivalence_checks": total_target_checks, "greedy_cost_instances_checked": total_cost_instances, "zero_optimum_cost_instances": zero_optimum_instances, "worst_greedy_to_optimal_ratio": frac_string(worst_ratio), "worst_instance": worst_instance, "equal_cost_one_failure": equal_cost_one_failure, "per_budget": records, "minimum_rank_non_submodularity": { "values_empty_a_b_ab": g, "left_side": g[1] + g[2], "right_side": g[0] + g[3], "strict_violation": True, }, "arbitrary_scenario_scope_regression": { "scenario_family": [[]], "selected_channels": [0], "target_reached": True, "distance": one_channel_distance, "corrects_one_arbitrary_error": False, }, } def severity_checks() -> dict: n = 6 full = (1 << n) - 1 sensor_rows = [[Fraction(t) ** j for j in range(4)] for t in range(1, n + 1)] column_coordinate_sets = [[1, 2, 3], [2, 3], [3], []] dimensions = [len(coords) for coords in column_coordinate_sets] failures = [] loss_by_failure_count = {e: set() for e in range(n + 1)} restriction_rank_checks = 0 p = Fraction(1, 10) reliability = Fraction(0) for failed in range(1 << n): retained = full & ~failed ranks = [] for coords in column_coordinate_sets: rows = [[sensor_rows[a][j] for j in coords] for a in members(retained, n)] rank = rational_rank(rows) assert rank == min(retained.bit_count(), len(coords)) ranks.append(rank) restriction_rank_checks += 1 losses = [d - rank for d, rank in zip(dimensions, ranks)] loss = sum(losses) e = failed.bit_count() assert loss == sum(max(0, e - threshold) for threshold in (3, 4, 5)) loss_by_failure_count[e].add(loss) failures.append({"failed_channels": members(failed, n), "surviving_ranks": ranks, "column_nullities": losses, "total_nullity": loss}) if loss == 0: reliability += p ** e * (1 - p) ** (n - e) assert all(len(values) == 1 for values in loss_by_failure_count.values()) loss_profile = [next(iter(loss_by_failure_count[e])) for e in range(n + 1)] assert loss_profile == [0, 0, 0, 0, 1, 3, 6] thresholds = [min(len(row["failed_channels"]) for row in failures if row["total_nullity"] >= k) for k in range(1, 7)] assert thresholds == [4, 5, 5, 6, 6, 6] binomial_reliability = sum( (Fraction(comb(n, e)) * p ** e * (1 - p) ** (n - e) for e in range(4)), start=Fraction(0), ) assert reliability == binomial_reliability def scalar_severity(visibility: list[int], count: int) -> dict: table = [] all_channels = (1 << count) - 1 for failed in range(1 << count): survivors = all_channels & ~failed loss = sum(not bool(survivors & v) for v in visibility) table.append((failed.bit_count(), loss)) thresholds = [min(e for e, loss in table if loss >= k) for k in range(1, len(visibility) + 1)] return {"individual_distances": [v.bit_count() for v in visibility], "global_thresholds": thresholds} disjoint = scalar_severity([0b01, 0b10], 2) shared = scalar_severity([0b1, 0b1], 1) assert disjoint["individual_distances"] == shared["individual_distances"] == [1, 1] assert disjoint["global_thresholds"] == [1, 2] assert shared["global_thresholds"] == [1, 1] return { "exact_rational_restriction_ranks_checked": restriction_rank_checks, "failure_sets_checked": 1 << n, "sensor_rows": [[str(x) for x in row] for row in sensor_rows], "column_coordinate_sets": column_coordinate_sets, "column_dimensions": dimensions, "total_nullity_by_erasure_count": loss_profile, "global_thresholds_for_k_1_to_6": thresholds, "independent_failure_probability": frac_string(p), "exact_probability_of_identification": frac_string(reliability), "probability_decimal": float(reliability), "binomial_reliability_cross_check": True, "shared_vs_disjoint_counterexample": {"disjoint": disjoint, "shared": shared}, "full_failure_table": failures, } def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, default=Path(__file__).resolve().parents[1] / "results" / "selection_results.json") args = parser.parse_args() scalar = scalar_checks() severity = severity_checks() result = { "status": "all finite checks passed", "arithmetic": "Python standard library integers and fractions.Fraction", "scope": "Independent finite example checks; not a formal proof or external review.", "scenario_cover": scalar, "global_failure_severity": severity, } args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") print(json.dumps({ "status": result["status"], "submodular_pairs": scalar["submodular_ordered_pairs_checked"], "monotone_pairs": scalar["monotone_ordered_pairs_checked"], "target_equivalence_checks": scalar["target_equivalence_checks"], "greedy_cost_instances": scalar["greedy_cost_instances_checked"], "exact_rational_restriction_ranks": severity["exact_rational_restriction_ranks_checked"], "failure_sets": severity["failure_sets_checked"], "output": str(args.output), }, indent=2)) if __name__ == "__main__": main()