# Reliable chemical state copying

Companion to paper 17, *Reliable copying of chemical states: finite-molecule
guarantees and molecular redundancy*. Manuscript SHA-256:
`50450e40c8f43be86391b39a88460038b1d3d931ce7d2bba0be788916d1af07e`.

The central object is a complete copying cycle: a parent reaches division,
its molecules are allocated, and **both** daughters return to the region
from which the same guarantee applies again. A threshold decoder alone is
insufficient. This example supplies exact complementary-allocation calculations,
a literal stochastic constructed source, state-dependent joint offspring
kernels, the four-species redundancy model, and nominal eight-species recovery.
The three chemistries remain separate, as they are in the paper.

## Run

Python 3.11 or newer:

```sh
python -m venv .venv
# PowerShell: .venv\Scripts\Activate.ps1
# macOS/Linux: source .venv/bin/activate
python -m pip install -r requirements.txt
python example.py --output outputs
python -m unittest -v
```

The four constructed-source paths can take tens of seconds. NumPy and SciPy
provide random sampling and BDF integration, mpmath evaluates redundancy
bounds at high precision, and Matplotlib draws the figures. Exact allocation,
region membership and scalar budget calculations use Python fractions.
Inputs are grouped at the very top by model, with their units and roles.

## A. Constructed two-module source

`ConstructedSource` implements the five reversible resident pairs per module,
consuming shared growth, reverse growth, cross-catalysis, and the counted
rate-one self-event: 29 directed events in total. Repeated reactants use
falling factorials, not squared counts. Marker m determines the externally
prescribed volume; local food and waste activities remain controlled.
The default birth marker is 53, division occurs at 106, and the deadline is
20 seconds. Epsilon=0.05 and rho=10^-7 lie inside the paper's parameter window.

The low birth box is X in [6,106], Y in [0,8]; the high box is X in [371,742],
Y in [6,132]. The fixed preparations are (53,0) and (530,53). The decoder
X>212 distinguishes their labels but also accepts nonadmitted high states
such as (300,10). These are concentration labels at a controlled volume:
(10,1) in the low box and (400,40) in the high box have identical proportions.

`run(word, seed, initial=...)` uses the direct continuous-time jump method.
Domain exit, reverse growth, deadline and the physical 10^8-event quota are
distinct monitored failures. The lower computational event limit returns
`unfinished` and no copying verdict. After a first division, every resident
is allocated fairly, the second daughter gets the exact complement, and both
markers reset to 53. The controller's pool reset is assumed and charged in
the scalar resource budget; there is no claim of autonomous volume control.

The four saved trajectories, one per label word, all divide within 3.47 s
and return both daughters. They are illustrations, not an estimate or proof
of 0.9901 uniform fidelity. For each observed parent, the package additionally
computes the exact joint partition-return probability. Saved traces are
decimated; every event is checked against the monitors.

`paper_budget()` reproduces the arithmetic leading from the manuscript's
generator inequalities to 0.9901518 > 0.9901 and the per-pool capacity
100100212000 molecules. **It assumes the paper's checked generator rows; it
does not regenerate or recheck the approximately 22 million rows.** The
874 figure counts newborn residents per module, not external inventories.
Changing the model inputs does not automatically recertify the bound.

## Complementary daughters and repeated copying

`ComplementaryAllocation.coordinate_return(n,l,u)` sums Bin(n,1/2) over
max(l,n-u) <= D <= min(u,n-l), also intersected with [0,n]. This enforces both
daughters' bounds simultaneously. Independent species allow multiplication
across coordinates; the two siblings do not. For parent count 4 and accepted
counts 1 through 3, both-return probability is 7/8, not (7/8)^2. Exact sums
are guarded at 20000 parent molecules per coordinate.

`OffspringKernel` accepts exact substochastic rows indexed by **pairs** of
admitted daughter states. Missing row mass is failure. It propagates a
designated lineage or the complete binary family by dynamic programming,
retaining dependence between sibling states. The included two-state kernel
is an explicitly illustrative example, not fitted chemical data.

A uniform one-cycle lower bound p gives p^G for a designated lineage of G
inspected divisions and p^(2^G-1) for all divisions through family depth G.
Every successful daughter must be an admitted restart state. This reasoning
does not assume independent generations. A small family lower bound does
not imply that most descendants actually fail.

```python
from fractions import Fraction as Q
from example import ComplementaryAllocation, CountBox, OffspringKernel

print(ComplementaryAllocation.joint_return((100,8), CountBox((6,0),(106,8))))
kernel = OffspringKernel(('a','b'), {
    'a': {('a','a'): Q(9,10), ('b','b'): Q(9,100)},
    'b': {('a','b'): Q(1,2), ('b','a'): Q(12,25)},
})
print(kernel.success(5), kernel.success(5, family=True))
```

## B. Four-species redundancy model

`FourSpeciesModule` supplies all thirteen resident channels and their fluid
field on (A,B,z,H), plus the exact scalar stationary-state reduction.
`CoupledModules` adds consuming growth and symmetric z exchange and returns
the literal rates and count jumps at any finite state. The physical rate for
an order-r resident reaction is c*k^(r-2)*m^(1-r) times its falling-factorial
reactant counts. Physical concentration is u/k, not u, where u=k*n/m.
The rate rescaling with module count is part of the theorem.

Exchange must have bounded total incident weight. A ring with edge weight
5e-12 meets the 1e-11 row-sum allowance for any size; a complete graph with
that fixed weight eventually fails it. `interaction_within_paper_allowance`
checks only that allowance and growth rate, not every local-quality premise.
Count arrays use 64-bit integers; the astronomical sufficient copy numbers
are evaluated analytically rather than passed to this finite-count kernel.

`RedundancyBounds.required` evaluates the sufficient integer copy number
and the separate necessary real lower bound for immediate return. It uses
the fixed N>=1.4e20 floor, c=1/(1.024e21), C(gamma)=2703+11/(5 gamma), and
replaces G by 2^G-1 for a family. At k=1, gamma=1e-11 and target error 0.01,
even one division requires about 3.1e22 under the sufficient bound. The
necessary inequality has vastly smaller constants and can lie below one
molecule; matching asymptotic orders do not mean matching numerical costs.
The bounds are not calibrated laboratory requirements. They do not apply
to the other two chemistries or to post-birth repair without a new argument.

```python
from example import RedundancyBounds
bound = RedundancyBounds(k=10)
print(bound.required(20))
print(bound.required(20, family=True))
```

## C. Nominal eight-species recovery

`SemenovModel` tracks (S,C,P,E,D,U,V,I), corresponding to AlaSEt, cysteamine,
thiol-bearing ligation product, ethanethiol, cystamine, two mixed disulfides,
and maleimide. It implements the eleven chemical channels, eight feeds and
eight outflows. The reusable `jump_rates` method keeps all 27 channels,
including zero-feed channels; no deterministic invariant plane constrains
fluctuations. `recovery` integrates the nominal concentration model from
the mean split-and-refill state (center+feed)/2 for 500 s with BDF.

`terminal_regions.json` is copied byte-for-byte from the supplied manuscript
sources, SHA-256
`e214ee720185c3e078d4880be7bfa247a473c4084165182477be5f7fae379e5a`.
It contains exact rational terminal centres and matrices, not rounded paper
table values. `ReturnEllipsoid` checks integer preparation membership exactly
and evaluates numerical trajectory endpoint energy separately. Admission
requires energy <=1; the thiol decoder alone is weaker. The nominal endpoints
return well inside both regions. Sufficient simultaneous preparation cube
tolerances are about 16.3665 nM (low) and 1.78818 nM (high).

The certified scale is Omega=2.4e19 molecules per molar, corresponding to
39.853 microlitres. The stochastic protocol splits complementarily, refills
each daughter with independent Poisson feed, then allows 500 s of recovery
with feed quota and coordinate caps. This example provides its count kernel
and exact scalar allocation/inventory budget; it does **not** attempt an
SSA over roughly 10^18 molecules or substitute a Gaussian allocation as exact.

`semenov_scalar_budget` recomputes each term of the rational failure budget,
including inherited parent energy, second/fourth moments, refill variance
and recovery drift. Doubling the per-daughter bound is a union bound, not
an independence assumption. The resulting joint failures are below 0.008.
This calculation assumes the manuscript's polynomial tube inequalities:
the 38 degree-16 time-piece certificates are not included or rechecked here.
The supplied exact terminal regions alone do not certify a stochastic tube.

Sensitivity outputs change one rate group by +/-0.1% while retaining the
nominal acceptance region. Several high-state endpoints leave that narrow
region while the thiol decoder stays correct. Those numerical diagnostics
do not prove loss of bistability or failure of a newly recentered protocol.
The nominal model's known discrepancy with experimental high-state thiol
also remains; the copying theorem is not an experimental fidelity claim.

## Outputs and checks

`copy_00.csv` through `copy_11.csv` save the constructed paths;
`recovery_low.csv` and `recovery_high.csv` save all eight concentrations.
`results.json` records exact partition payoffs, daughter states, scalar
budgets, region membership, stationary brackets, sensitivity and redundancy
calculations. Figures are supplied as PNG and SVG. Source/output hashes are
in `run_metadata.json`.

Seven scientific test groups exhaust small complementary allocations,
check literal propensities and monitors, verify rational budget arithmetic,
iterate a state-dependent joint kernel, check the four-species count/fluid
correction and graph allowance, compare horizon bounds, and verify exact
region-data hashes, integer preparations and nominal recovery. These checks
support the implementation; they do not claim a new Lean proof audit.

License: MIT is proposed, pending the owner's choice. No license grant is
asserted by this package. The return-region data retain their source provenance.
