# Checked deletion localization and exact RAF robustness

This example implements the central constructions in *Certified localization of
reaction deletions in autocatalytic networks: ranked support witnesses, witness
selection, and exact robustness laws* (7 September 2026). It provides an exact
deletion-query engine, source-checked ranked witnesses, closure/pruning receipts,
witness portfolios, and exact random-availability calculations. The manuscript
hash is in the source. This is original Python from the paper's definitions,
not an implementation extracted from Lean.

## Inputs and semantics

USER INPUTS begins the source. The default network has three pairs of alternative
producers and one consumer requiring all three shared products, seven reactions
in total. Producer identifiers are 0/1, 2/3, 4/5; consumer 6 needs all three
inputs. Every reaction is food-catalysed. `DELETION=(0,3)` removes one producer
from each of two different pairs. The pair count, portfolio budget, retention
probabilities, functional parent map and proposed catalyst addition are editable.
All inputs are structural incidences or dimensionless probabilities, not kinetic
parameters. There are no concentrations or physical units.

A RAF has all reactants and at least one catalyst available in food closure.
Closure depends on reactants alone; catalysts may come from reactions later in
the generation order. Reaction identities are retained, even for duplicate
chemistry. The maximum RAF is computed by alternating food closure and pruning.
Every query is an independent deletion from one fixed baseline; this engine does
not treat a series of calls as cumulative edits and does not support insertions.

## How localization works

`ReactionSystem` owns literal chemistry, closure, maximum-RAF evaluation and
closure/pruning certificates. `RankedWitness` stores a parent set and a rank for
each baseline reaction. Every nonfood reactant must have a lower-ranked producer;
a catalyst producer may have any rank. `validate()` checks the actual source
incidences. `build()` generates a default witness and can prioritize a known
retained RAF to construct a witness perfect for one query. That perfect-query
construction already needs the surviving set and does not accelerate its first
discovery.

`DeletionEngine` checks and snapshots its witnesses. For a deletion, it follows
parent-to-consumer edges to get a cone, or intersects cones from a portfolio.
Reactions outside the region are retained. Their products are adjoined to food,
and one residual maximum-RAF solve determines which local reactions also remain.
If the region contains only deleted reactions, a closed-seed shortcut needs no
residual solve. An empty portfolio is allowed and gives a fresh solve.

The proposed residual answer includes a reaction schedule for every pruning
round. A checker replays only enabled available reactions, verifies closure is
saturated, verifies the decreasing candidate sets, and requires a terminal fixed
point. Invalid receipts trigger a fresh exact solve. Invalid source witnesses are
rejected during engine construction. Keep the source chemistry fixed for the
lifetime of an engine; construct a new one after a chemistry or catalyst change.

```python
from example import Reaction, ReactionSystem, RankedWitness, DeletionEngine

system = ReactionSystem([
    Reaction(0, {'f'}, {'x'}, {'f'}),
    Reaction(1, {'f'}, {'x'}, {'f'}),
    Reaction(2, {'x'}, {'y'}, {'f'}),
])
witness = RankedWitness.build(system)
engine = DeletionEngine(system, [witness])
print(engine.query({0})['loss'])       # [0]: the alternative producer rescues 2
print(engine.query({0, 1})['loss'])    # [0, 1, 2]: joint deletion loses the input
```

`greedy_portfolio()` chooses witnesses by new rescued (query,reaction) events
on a supplied training set. The standard coverage guarantee is relative to that
finite pool, training set and budget. It is not a wall-clock guarantee or an
optimality claim over all possible witnesses. Residual answers remain exact on
unseen queries regardless of the training coverage.

## Robustness components

`RobustnessPolynomial` enumerates availability subsets once and exports integer
coefficients for expected size, second moment and nonempty survival. Coefficients
are in ascending powers of retention p. `sensitivity()` computes singleton losses
and pair overlap/cooperation, and compares their derivative identities with the
independently accumulated polynomial. Exponential availability enumeration is
capped by `EXHAUSTIVE_REACTION_CAP`.

`FunctionalSource` is a narrower adapter: every reaction consumes food, produces
one private molecule, and has one catalytic parent. Its forward orbit is its
exposure set. `OneSiteExposure` permits a second catalyst at at most one reaction;
it uses two newly resolved parent maps, not a stale pre-addition witness. A target
survives exactly when at least one complete exposure is available. The class
returns exact probabilities, survival gains and all inclusion-minimal external
cuts, excluding deletion of the target itself. `catalyst_candidates()` scores
every single addition by total expected surviving-size gain.

```python
from fractions import Fraction
from example import FunctionalSource

source = FunctionalSource((0, 0))
addition = source.addition(site=1, parent=1)
print(addition.surviving({1}))              # {1}: its new self-loop survives
print(addition.probability(1, Fraction(1,2))) # 1/2, previously 1/4
print(addition.cuts(1))                    # no external cut can remove target 1
```

The orbit adapter must not be used for nonfood reactants, nonprivate products,
or multiple alternative-catalyst sites. General `ReactionSystem` evaluation still
applies to such networks. Candidate ranking concerns one addition from a supplied
family, not an optimum over simultaneous changes.

## Run

Python 3.11 or newer. The scientific model and tests use the standard library.
Matplotlib and its dependencies are needed for plots; the direct plotting
dependency is pinned, not the complete transitive environment.

Windows PowerShell:

```powershell
py -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements.txt
.\.venv\Scripts\python.exe example.py --output outputs
.\.venv\Scripts\python.exe -m unittest -v
```

POSIX:

```sh
python3 -m venv .venv
.venv/bin/python -m pip install -r requirements.txt
.venv/bin/python example.py --output outputs
.venv/bin/python -m unittest -v
```

## Results

All three strategies return the exact maximum RAF for all 128 deletion sets.
Their regions exceed actual loss on 19 queries for one witness, 12 for two
complementary witnesses, and none for all eight assignments. Two complementary
witnesses are perfect on every singleton, but deleting {0,3} puts consumer 6
in both cones even though it survives through producers 1 and 2. The residual
certificate rescues it. Greedy singleton training selects those complementary
witnesses and covers all 42 rescuable training events.

The full 2^k assignment pool gives exact regions for every deletion in the paired
family. Tests remove each witness and exhibit the missing query, demonstrating
why singleton success does not eliminate the exponential representation cost.
This is a cost of perfect regions; small portfolios still give exact answers.

For the two-producer, one-consumer source, expected size is
2p+2p^2-p^3 and curvature at p=1 is -2. For a three-cycle it is 3p^3 and curvature
18. Cooperative pair damage and overlapping singleton damage give opposite
signs. The second figure compares these with a twelve-reaction gateway, whose
nonempty survival probability remains exactly p.

The two five-reaction overlap controls have identical sorted exposure sizes
(1,2,2,3,3) and the same mean 5/4 at p=1/2, but variances 9/4 and 33/16.
Exposure overlap, not just exposure size, determines fluctuations. In the
default addition search at p=4/5, adding reaction 2's own product as a catalyst
for reaction 2 maximizes expected size among the 25 candidates, with gain
2196/3125. These are exact static availability calculations, not Monte Carlo.

## Outputs and validation

Outputs include source JSON, every witness, selected-query pruning certificates,
region profiles, robustness curves and polynomial coefficients, two-exposure
sets and external cuts, ranked catalyst additions, figures, console output and
run metadata. Metadata includes source/manuscript and output hashes, environment
and elapsed time. No random sampling is used. SVG metadata may vary between runs.

Seven test groups compare with an independent all-RAF-subsets oracle, audit all
paired deletions, remove each necessary assignment witness, construct perfect
queries, allow later catalytic parents while rejecting invalid reactant ranks,
corrupt certificates to exercise fallback, check greedy's finite-pool bound,
verify curvature on all 343 elementary three-reaction graphs with nonempty
catalyst lists, and exhaust all 27 functional maps and their one-site alternatives.
Cut, probability, gain, variance and newly created cycle examples are checked.

The example covers deletion localization, portfolios and structural robustness.
It does not implement the paper's insertion packets, executable charge tariffs,
native checker, complete Set Cover hardness reduction, or timing study. Region
sizes are not runtimes; no speedup is asserted. No Lean compilation, biological
network analysis, thermodynamic feasibility or kinetic persistence is claimed.

## License

MIT is proposed for this original example code, pending the owner's license
choice. No license grant is asserted here. This does not change the license of
the manuscript or any third-party dependency.
