# Inherited chemical-state selection across serial transfers

This package connects the paper's literal resident count chemistry to shared-resource growth, complementary division, unbiased intact-cell transfer, actual-state recovery and refill. It separately evaluates the two-cycle probability theorem. It follows manuscript entry 44, SHA-256 `d4d09105a0cfd39230861a7911081421a89f536afc2caf28d9297d00cab282ca`.

## Run and edit

Use Python 3.11 or newer:

```sh
python -m venv .venv
# Activate the environment for your shell.
python -m pip install -r requirements.txt
python example.py --output outputs
python -m unittest -v test_example
# Optional literal small-population stochastic diagnostic:
python example.py --simulate --output diagnostic_outputs
```

Inputs at the top of `example.py` separate the theorem witness from the small stochastic diagnostic. The witness uses newborn size N=65,536*10^18, M=4 billion retained cells, growth coupling 10^-11, a batch deadline 8/gamma and recovery duration 5376. These are a sufficient existence construction, not plausible laboratory specifications. The default run does not allocate M cells: two exactly enclosed founder prototypes carry multiplicities M/2.

The optional diagnostic instead uses N=10, M=4, gamma=2 and recovery 0.05 so individual events can be inspected. Its chemistry and event rules are literal, but its size, growth and recovery settings are outside the probability theorem. With the default seed and 100,000-event budget it completes two cycles in 44,093 events. No theorem-success verdict is inferred. A smaller 20,000-event budget leaves the second batch unfinished and preserves that partial population. The physical simulator does not apply the proof's energy/odds failure quotient and does not classify theorem success even when both physical cycles finish.

## Resident chemistry and preparation

Each cell has integer size m and counts (A,B,z,H), with concentrations counts/m. The thirteen resident channels are:

| Reversible pair | Maintained forward / reverse propensities |
|---|---|
| A <-> B+z | nA / (nB*nz/m) |
| z+F <-> H | 16*nz / nH |
| H <-> 2z | nH / (2*nz*(nz-1)/m) |
| RA <-> A | 6*m / nA |
| RB <-> B | 27*m / nB |
| B+G <-> 2A | 10^-5*nB / (10^-5*nA*(nA-1)/m) |

The final channel H->WH has propensity 10^-4*nH. In this table the slash separates directions; it is not an additional rate division. F,G,RA,RB are maintained at unit activity, and WH collects sink material. Identical-reactant propensities use falling factorials without an extra factorial divisor.

`resident.py` contains exact rational intervals, stationary reconstruction, quadratic energy enclosures, immutable cells and the thirteen channel definitions. These are adapted from this repository's entry-21 example; `provenance.json` records the source hash. The entry-44 changes are substantive: readiness is E<=a, a=1/512,000,000, and the measured type is **high exactly when nz/m>2**, otherwise low. The earlier batch paper's different readout is not reused. The package is self-contained and imports no other example folder.

`ChemicalRegions` brackets stationary z values in [0.99579401232,0.99579401233] and [2.97636724376,2.97636724377], refines the sign brackets rationally, and reconstructs the other coordinates. To prepare a founder, it requires both endpoints of each scaled coordinate enclosure to have the same integer floor, then verifies the resulting energy enclosure lies in E<=a. Unresolved floors or readiness comparisons raise an error rather than silently accepting a floating-point approximation. The exact symmetric matrices obey I/200<P<42I by fresh Sylvester checks.

`ChemicalModel.certificates()` also checks the full nine-species material assignment (2,1,1,2,1,3,2,1,2), the compatible Boltzmann weights, every reservoir projection and the stationary-curve identities. It checks the sink's material balance, without asserting a reversible detailed-balance ratio for that irreversible sink. The source-specific stochastic exponential-dissipation inequality is imported from the paper; the energy-matrix tests alone do not prove it.

## Physical population source

`PopulationSource` composes `ChemicalModel` with a replaceable complementary-division component. A batch starts at total size W0, with shared precursor Q=Omega=4W0. Cell j grows at rate gamma*(Q/Omega)*nz_j. A growth event consumes one precursor and one internal z and adds one size unit. At size 2N, the same event divides the parent into two daughters of size N. One daughter receives a binomial half-allocation of each internal species; the second receives its complement. Molecules cannot be independently assigned to both daughters.

Q+W=5W0 is conserved through growth and division. The batch stops at Q=W0, where W=4W0, or at its deadline. If the endpoint-triggering event also causes division, the division is processed first and both daughters remain in the actual endpoint. The source supports arbitrary live sizes N<=m<2N on later starts. It does not impose the invalid newborn-only 4M cell cap; the proof uses 8M for arbitrary division phases. A test constructs a small actual growth path that exceeds 4M.

Analytical ancestry labels appear in reporting and energy checks only. They enter no propensity, division draw, transfer draw or refill amount. `Cell.readout` independently reads the actual z concentration, so outside certified regions an inherited ancestry tag need not equal the measured chemical state.

`PopulationSource.run()` uses direct exponential-waiting-time simulation. An event budget preserves the partial population and reports `event_budget`, not failure or success. The numerical division sampler requires counts below 2^53; do not use it to pretend to simulate the astronomical theorem witness. The exact event kernel and count-based state representation remain reusable for smaller models or alternative numerical solvers.

## Transfer, recovery and refill

`UniformTransfer.sample()` chooses M distinct indices uniformly, without reading tags, sizes or concentrations. The selected and discarded tuples retain intact cells. Their material totals sum exactly to the endpoint total. Sampling favors neither type; selection arises in the preceding growth competition.

For analytical weights w_j in [0,1], the inclusion probability is M/n and the distinct-pair inclusion probability is M(M-1)/(n(n-1)). Nonpositive covariances imply Var(sum w_j I_j)<=E(sum w_j I_j). `weighted_moments()` evaluates the exact rational mean, variance and pair covariance. `enumerate()` checks every M-subset when at most 100,000 subsets are required.

The saved eight-cell diagnostic has four cells of each ancestry and retains four. At tolerance 1/50, the exact failure probability for retained ancestral size totals is 17/35 for equal sizes, high-larger sizes or low-larger sizes, and 27/35 for mixed sizes within each type. At tolerance 1/2 these become 1/35 and 13/35. The paper's general Chebyshev bound is uninformative at this tiny M. This diagnostic is an exact conditional sub-law, not a full population experiment.

`SerialProtocol` takes the actual selected cells into recovery at Q=0. Resident chemistry continues, while sizes, ancestry and cell counts remain fixed. After the configured duration, refill supplies 4*sum(actual retained sizes). The next batch therefore starts from actual recovered counts and sizes. It does not replace cells with stationary samples or reinitialize newborns. Partial recovery remains a partial physical population.

The plotted recovery experiment starts from a **constructed** admissible endpoint: stationary founder counts are perturbed upward in z by approximately 2e-5 in concentration. Their energies exceed a but stay below 8a. Four of eight cells are selected intact, and the actual count/size vectors initialize the full resident density ODE for 5376 units. It is not claimed that these endpoint cells came from a simulated batch. Radau and BDF agree within about 1.3e-10 in the configured illustration. Fixed-size density relaxation illustrates the recovery mechanism; the finite-count return probability is a separate theorem.

## Service counters and material accounts

The event source optionally carries a counter that saturates at quota J while physical chemistry continues. The counter increments on every actual source event; virtual holds are absent from the direct simulator. Tests couple identical random streams with and without a saturating counter and verify exactly the same physical endpoints and exchange ledgers.

A separate `hard_limit` option stops before a resident event would exceed a per-reservoir gross expenditure budget. This models external maintenance until cutoff. It is not gradual depletion that changes reaction rates. Before a cutoff, rates and transitions agree with the maintained source. Gross counts include both supply and collection, separately for F,G,RA,RB,WH. They are not net depletion, dissipation or a total free-energy bill.

For the certificate, sufficient clocks are qR=34000N per recovering cell and qB=280000NM for the batch. `TwoCycleCertificate` chooses integer quotas

```text
JB = ceil(T*qB/service_allowance)+1
JR = ceil(M*5376*qR/service_allowance)+1
```

so both service error terms are strictly below the requested allowance. At the smaller witness with allowance 1/1000:

```text
JB = 5.8720256e52 + 1
JR = 4.7915728896e43 + 1
```

Resident exchange, growth precursor, discarded cells and removed medium are distinct accounts. Each successful batch supplies 4W0 precursor, consumes 3W0 and removes residual W0. The two batches consume fresh supply at most 12NM. The post-second-cycle refill is preparation for a possible next batch; it is not included in that two-batch supply bound. Gross exchange per reservoir is strictly below 2*(JB+M*JR) on the quota event. Elapsed source and recovery time is at most 2*(8/gamma+5376), excluding external handling and preparation. The theorem assigns no physical calibration to the size or time unit. M counts cells and must not be divided by Avogadro's constant as though it counted molecules.

## Probability, count selection and evidence

`TwoCycleCertificate` requires N>=1.4e20, even M>=2 and 0<gamma<=1e-11. The theorem also requires balanced ready newborn founders, unbiased transfer, maintained resident reservoirs and the prescribed recovery. The complete error sum includes batch outer/parent/partition errors, deadline and size-odds errors, both service terms, uniform-transfer error and selected-population recovery. It is evaluated for the actual first- and second-cycle count floors 1/2 and 1/100. Outward intervals check a downward-rounded nine-decimal success claim; negative lower bounds become zero.

The paper's original exact rational envelopes are also freshly evaluated using e>=2, exp(-128)<=10^-38 and exp(-64)<=2^-64. These reproduce at least 495999/500000=0.991998 for the smaller witness and 497999/500000=0.995998 for the original larger witness. The sharper numerical evaluation with distinct count floors gives **0.993959999** as a certified downward-rounded lower bound for the smaller witness. The tiny difference from a displayed approximation of 0.99396 is preserved rather than rounded into a stronger claim.

For positive high/low counts, let C be log count odds, S log total-size odds and phi the log ratio of mean cell sizes. `OddsAccounting` uses the exact identity C=S-phi. Since each cell size lies in [N,2N), |phi|<=log(2); newborn founders have phi=0. Summing across cycles cancels all intermediate phases. The two-cycle newborn count gain is strictly above

```text
G2 = (7/5)*log(2) - 19/250 - 2*log(51/49).
```

This gives a measured high fraction above the exact logistic value exp(G2)/(1+exp(G2)); the code verifies the safe decimal consequence **fraction>0.6930453** by interval arithmetic. It does not claim that count odds increase at every intermediate census. A separate phase test shows that total size can increase for one type while counts remain unchanged.

The eligibility floors are 1/2, 49/1600 and 2401/1280000. The first returned floor exceeds 1/100 and permits the second cycle; the next is below 1/100, so this certificate does not authorize a third cycle at the same floors. No indefinite coexistence, fixation probability, autonomous reservoir operation or food-only establishment is asserted.

## Reuse and verification

```python
from example import TwoCycleCertificate, UniformTransfer, PopulationSource, SerialProtocol

certificate = TwoCycleCertificate(N=65536*10**18, M=4*10**9)
print(certificate.evaluate())
print(certificate.rational_witness())

# Existing Cell objects can carry arbitrary actual division phases.
source = PopulationSource(N=10, gamma='2')  # outside the probability theorem
protocol = SerialProtocol(source, M=4, recovery_duration=.05)
# result = protocol.run(your_four_cells, cycles=2, seed=7, event_budget=100000)

print(UniformTransfer.weighted_moments(['1','1/2','3/4','1/4'], M=2))
```

Outputs include exact prototype/energy data, both paper witnesses and rational envelopes, configured quotas and separate accounts, all eight exact transfer diagnostics, phase/threshold information, selected/discarded cells, density recovery CSV, error sweeps, figures and reproducibility hashes. The optional stochastic result records every completed stage plus any unfinished physical state.

Seven test groups check completed chemistry and source rates, exact ready preparation and the correct readout, complementary endpoint division and arbitrary-phase caps, exact transfer/covariance and type neutrality, capped-counter marginal preservation and hard cutoffs, witness/scope/rounding, phase conversion, and actual selected-state recovery/protocol continuation. Exact arithmetic and finite diagnostics are fresh computations. Probability, local stochastic dissipation and finite-law composition remain imported manuscript theorems. Lean is not rerun. The conventional continuous-time interpretation is kept separate from the formal finite stopped laws, as in the paper.

MIT is proposed for the example code, pending owner approval; this README grants no license and does not change manuscript rights.
