# Conservative exchange preserves repeated production

This standalone example implements the actual six-species deterministic chemistry
at every node, synchronized withdrawal/loss/refill pulses, and conservative movement
between equal-volume reactors. It combines runnable models with fresh exact checks
of the paper's argument and explicit supply/output accounts.

## Run and reuse

Python 3.11 was used. Create a virtual environment, then run:

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

Edit the input block first. Defaults are the paper's four heterogeneous ready
states, fixed node release/cleavage rates, a path graph and 32 routine cycles after
conditioning. The illustrative calibration is 1 mM, 1 mL per reactor, one minute
per time unit: one normalized amount is one micromole. These are transparent
placeholders, not measured kinetic constants or a laboratory validation. For
example, a normalized bimolecular constant 20 becomes 333.33 M^-1 s^-1;
a first-order constant 20 becomes 1/3 s^-1.

Classes have separate responsibilities:

- `LocalChemistry` supplies six reversible net fluxes, unit food feed and unit
  washout. Its node rates may differ. Unsupported rates can be simulated directly,
  but the mission certificate rejects them.
- `CommonExchange` accepts any finite symmetric nonnegative zero-diagonal matrix,
  including disconnected and one-node graphs. It applies one operator to all six
  species. Its directed labels and handling counter count each molecule moved
  once per directed crossing, without declaring transport to be export or food.
- `Pulse` accepts one retained fraction per node, common or node-specific survival
  fractions and refill errors. It returns retained state, withdrawal, loss and new
  food separately. Node volumes are restored immediately.
- `ReactorNetwork` composes these components, integrates the full 6N-dimensional
  nonlinear model and 4N+1 accounting states, and compares material trajectories
  with their independent linear matrix-exponential solution.
- `HistoryPolicy` demonstrates bounded feedback using completed outputs. The
  mission passes snapshots; actual endpoints initialize the next pulse. To use N
  other than four, provide a policy returning N retentions and N node rates/states.
- `HarvestMission` runs conditioning and routine cycles, retaining all-time
  effluent, pulse withdrawals, handling losses, chemical service and transport.
- `MissionCertificate` sizes deterministic missions in exact rational arithmetic.
  It evaluates imported theorem bounds, not a numerical proof of them. It rejects
  budgets that cannot fund conditioning. Initial preparation and exchange handling
  must be funded separately from its food/service budgets.
- `PhaseCertificate` constructs nonnegative polynomial weights for the four-phase
  lower system. It can vary the truncation degree; its certified free-X floor uses
  the paper's rational lag and an explicit exponential upper bound.

For example, use `CommonExchange([[0, 2], [2, 0]])` with two node rates, two states
and a two-node pulse policy. Call `network.evolve(state, duration)` for a continuous
experiment without claiming the pulsed theorem. A parameter sweep must preserve
the same operator for every species if it invokes the network certificate.

## What makes the network argument work

Species order is U, W, X, C1, C2, Z. The material inventories A and B, catalytic
observable Y, and covalent-template inventory I are explicit weight vectors in
the source. The local identities are A'=1-A, B'=1-B and
I'=j0+j3-j5-I. Common exchange adds D times each observable, which is nonnegative
at its minimum node; symmetry cancels it in the total inventory. This is the
reason the proof does not require connectivity, weak coupling, synchronization
of concentrations, or an equilibrium assumption.

While .9<=A,B<=1.1 and Y<=1/20, a freshly expanded nonnegative slack polynomial
checks the local inequality Y'>=(2/3)Y. Pulses retain at least 49/200 of Y.
Exact Taylor lower bounds check conditioning/recovery constants. Catalytic stock
alone need not be free X: it may be stored in complexes. Nonnegative backward
weights for the Metzler **lower matrix, not the Jacobian**, carry this stock through
the phases to free X. The degree-four certificate at lag 1/28 verifies a floor
strictly above 1/160 using rational arithmetic, without evaluating an exponential
in floating point.

`algebra_checks()` also checks the three-element completion with F and P, and
all six thermochemical rate ratios. The driven cleavage pair is XF <-> UWP;
fixed unit reservoir activities give the six-species source. Common exchange
preserves these chemical identities because it only changes location. Maintained
reservoirs are not a finite-bath model.

## Production, supplies and stock depletion

Each credited interval [3,4] after a routine pulse exports at least 1/28 of I and
1/160 of free X **per node**. X is part of I; these outputs must not be added.
Conditioning lasts 12 units and is not credited as a routine collection. The
initial admitted region is .9<=A,B<=1.1, Y>=1/5000; a ready start has
159/160<=A,B<=161/160, Y>=1/20. The default starts ready but includes conditioning
to illustrate the full admitted-start protocol.

For N nodes and m cycles including conditioning, each food allowance is
N(2551+951m)/200, gross chemical-service allowance N(27+9m)/50, duration 12+4m.
The exact ledger is

```
net covalent synthesis = final I - initial I
                      + all-time effluent I + withdrawn I + lost I.
```

Internal exchange cancels; credited collection is only part of all-time effluent.
The lower bound N((m+1)/28-11/10) becomes positive at **m=30**. A ready start
without conditioning uses N((m+1)/28-161/160), positive at **m=28**. These indices
follow the paper's exact propositions; introductory prose saying 31st/29th is
one cycle conservative. No finite transient simulation proves indefinite output.

The worked demand (I>=1.5, X>=.2) on four nodes requires 11 cycles. Time 64,
food budgets 300 and 280, and service 12 fund 12. Eleven cycles plus conditioning
take 56 minutes under the calibration, guarantee 11/7 micromoles I and 11/40
micromoles free X, and allow 260.24 micromoles of each food and 10.08 of gross
service. Gross service counts forward plus reverse driven events, not their net.

For total continuous duration L, transport handling is bounded by
(22/5)L sum_over_edges(kappa). The four-node path/ring/star routine allowances
are 26.4/35.2/17.6. These count chemical amount moved; they are not pumping work.
Each directed edge carries liquid at V*kappa/t0. Degree and edge count determine
how this extra cost scales even though the production floor is graph-independent.

## Outputs and limits

`results.json` contains exact checks, mission ledgers, sizing, calibration and
four pilot summaries. `pilots.csv` saves the full one-cycle states; `mission.csv`
saves the configured pulsed history (duplicate times mark instantaneous pulses).
`exchange_sweep.csv` changes common path strength, with actual and upper-bound
handling. Figures compare recovery, phase availability, movement and the initial
inventory subtraction. The literal paper pilot is reproduced with nonuniform
retentions and species-specific pulse losses; the smallest uncoupled outputs are
about .2681556621 I and .1243312990 X. The four graphs are diagnostics, not an
optimization contest or equally costly transport designs.

Seven test groups check symbolic constants, conservation/minimum identities,
pulse accounting, literal pilot values, actual-history propagation, resource
sizing, and the lower-system versus selective-transport distinction. Main also
compares independent Radau/BDF integrations. No negative state clipping or frozen
food approximation is used. The exact two-node X-only witness has negative Y
drift at equal minimum Y; it refutes that minimum argument, **not** all selective
exchange theorems and **not** extinction. Selective transport is deliberately
outside `CommonExchange`'s certificate-bearing interface.

Global recovery and forward invariance are imported manuscript results; this
package does not rerun Lean. The guarantee assumes synchronized instantaneous
pulses, equal restored volumes, fixed admissible node kinetics, common symmetric
exchange and maintained reservoirs. It does not imply stochastic reliability,
asynchronous operation, finite-duration pulse robustness, finite-bath autonomy,
purified-product recovery or a full energy budget.

## Provenance and license

Manuscript SHA-256:
`c8b16eaf2abf49162495bbfb0ea0e69908a3a28d5e34968d60dcd399daf6518f`.
Equations, rational constants and the pilot setup were checked against the full
PDF, `main.tex`, `check_paper.py` and `figures/diagnostic.py` in the author's
Conservative_Exchange_Reactor_Networks_arxiv source. The scientific model and
checks are implemented locally; no stored success verdicts or traces are loaded.
Output hashes and runtime information are recorded in `run_metadata.json`.

MIT is proposed for this example code, pending the owner's license choice.
No license grant is made by this README; the manuscript retains its own terms.
