# Finite-batch selection between inherited chemical states

This standalone example implements the effective count model and evaluates the bounds in *Finite-batch selection between inherited chemical states under a shared limiting resource* (14 September 2026). Original PDF SHA-256: `b93345aac9b134b314f9e6115f46585fd3e5fc60c2ece42f5da6eacab32199ed`.

A high-state compartment has about three times the resident concentration of growth-linked species z as a low-state compartment. Every compartment consumes z and one unit of a shared precursor to add one unit of size. At doubled newborn size it divides into complementary daughters. Faster size accumulation does not immediately imply more cells: a lineage can be nearer its next division while still having the same cell count. The paper controls chemical fidelity, ancestral size odds and the deadline under one stopped population law, then pays a factor of two to convert size odds into cell-count odds.

## Run

Use Python 3.11 or later:

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

The default run evaluates the analytic error budgets, reproduces the manuscript's numerical table, prepares integer founder counts inside rationally enclosed energy regions, and plots the bounds and a separately labelled division-phase diagnostic. It does not attempt to simulate an astronomical batch. Outputs contain exact founder counts and energy enclosures, source-root enclosures, matrix/scalar checks, high-precision bound values, sufficient-size estimates, CSV sweeps, PNG/SVG figures and hashed run metadata.

Inputs at the top specify newborn size N, founder numbers, growth coupling gamma, requested logarithmic odds gain s, scaled deadline gamma*T, error target, and simulation budget/seed. The manuscript's 13 resident reactions and their coefficients are fixed in `ResidentChemistry`; changing those requires a new chemical certificate. These are theoretical, dimensionless source parameters, not measured laboratory inputs. Size is assumed proportional to volume. Resident feeds and removals remain maintained; only the growth precursor is finite. The effective reaction table is not an atom-balanced autonomous chemical system.

The default `N=1.11e22`, `h=low=1`, `gamma=1e-11`, `s=0.1`, `gamma*T=8` gives a raw-formula success lower bound about **0.99688942456**, while the simpler chemical envelope still gives only the trivial zero lower bound. The original sufficient-size formula for total error 0.01 gives approximately **3.078875e22**; the double-exponent envelope reduces that sufficient value to approximately **1.574927e22**. These are conservative bounds on the stated model, not estimated actual failure probabilities or practical operating scales.

## Reusable count model

`Cell` stores four nonnegative integer counts `(A,B,z,H)`, integer size, and an ancestral tag. Its measured state is the sign of `10*n_z-n_B`; tags are bookkeeping, not an imposed fitness. `Channel` computes a literal falling-factorial propensity and applies its integer transition. No factorial divisor is added to the manuscript's propensity coefficients. `ResidentChemistry` supplies all 13 channels and a generator evaluator for observables.

`Population` stores live cells, precursor, division count and an absorbing terminal status. `BatchParameters` validates editable batch inputs and identifies the source theorem's parameter range. `PopulationKernel` composes chemistry, energy regions and a partition rule. It exposes initial preparation, exact rational event rates, individual event transitions, the success readout, and an optional direct jump simulator.

Growth has rate `gamma * Q/(4*N*M) * n_z` and changes `(Q,n_z,m)` by `(-1,-1,+1)`. The event that reaches `m=2N` also partitions the post-growth resident counts into two size-N daughters. The complementary allocation conserves every resident species across the pair and preserves ancestral size. The kernel retains both daughters even if that event also hits the nutrient endpoint or raises a chemical flag. Chemical inspection order is outer energy, post-growth parent division energy, daughter partition energy, then nutrient endpoint. Thus a simultaneous failure cannot be reported as nutrient success.

Every implemented transition checks precursor-plus-size conservation, the change in live-cell count versus division count, and the live size range. Starting from the supplied preparation, the identities are `Q+sum(m)=5*N*M` and `C=M+D`; at the endpoint `Q=N*M` and `sum(m)=4*N*M`. Both endpoint daughters are included. This is one batch: endpoint cells need not be admitted newborns for another batch.

`ChemicalRegions` bisects the two rational stationary-root brackets and constructs interval enclosures of their full compositions. It evaluates each rational energy matrix on interval deviations `n/m-center`. A comparison unresolved by the interval raises an explicit computational limit, not a chemical failure or a success. This avoids subtracting rounded double-precision centers at counts of order `1e22`. Newborn admission uses `E<=4a`; the outer continuing condition is `E<b`; predivision parent admission uses `E<=2a`; daughter admission uses `E<4a`, matching the paper's strictness conventions.

`ComplementaryPartition` draws one binomial allocation per species and gives the remainder to the other daughter. It also evaluates the exact allocation probability for small parent counts. The default sampler limits binomial input counts to `2**53`; it refuses larger draws rather than rounding the molecule number. A different vetted partition sampler can be passed into the kernel. In particular, independent draws for both daughters would violate the model.

## Exploring paths and observables

To attempt a direct count path:

```sh
python example.py --output exploratory_outputs --simulate
```

The event budget is a computational limit. A path that has not reached a physical terminal event or the deadline returns `success=None`, with its actual status and time; it is not counted as failure. At the certified counts and slow growth rate, feasible direct simulation advances through only a tiny part of the batch. Event choice and holding times use floating-point numerical random sampling, even though rate formulas and state updates are exact. No simulated frequency is used as evidence for the probability theorem.

For a smaller exploratory model, use the API rather than editing the fixed source constants:

```python
from example import BatchParameters, ChemicalRegions, PopulationKernel

parameters = BatchParameters(N=10**12)
regions = ChemicalRegions()
model = PopulationKernel(parameters, regions)
initial = model.initial()
print(model.events(initial)[:3])  # cell index, resident-channel index, exact rate
print(model.simulate(budget=100)) # often unfinished; source theorem does not apply at this N
```

`AncestralObservables` computes size odds versus cell-count odds, the logarithm of the paper's selection observable, its relative drift under supplied high/low z concentrations, and an interval for the logarithm of the size-position energy exponential. Division does not change ancestral size totals, so these observables remain meaningful when the number of cells changes. `ErrorBudget` is a separate component; using a different kernel, sampler or source chemistry does not transfer its theorem.

## Analytic bounds and the separate phase diagnostic

`ErrorBudget` evaluates the five raw chemical contributions, simplified/retained/double-exponent envelopes, the selection tail and deadline tail. The three failure categories are **added**, not multiplied; they need not be independent. Calculations use 80-digit mpmath arithmetic and logarithmic outputs to keep extremely small population tails visible without double-precision underflow. These are high-precision numerical evaluations of proved formulas, not directed interval or Lean certificates. The sufficient-size routine evaluates the closed-form bound and adds one integer to its numerical ceiling.

For a success-probability interpretation, the model must use admitted founders, `N>=1.4e20`, `0<gamma<=1e-11`, and the fixed resident table. Values outside the parameter scope return no claimed probability lower bound. Within scope a nonpositive selection/deadline margin or error at least one gives the trivial zero bound. The useful gain margin is `log(2)/5-s`; the deadline margin is `9*gamma*T/40-log(4)`. More time reduces the deadline tail while increasing the chemical error. `sufficient_size()` specifically requires `s=0.1` and `gamma*T=8`.

On the successful event the two-founder high-state frequency is at least **4/7**, stronger than the continuous odds-conversion value of about 0.525. The strengthening uses integer cell counts, positive counts of both tags, and at most eight endpoint cells. It is a consequence of success, not an additional independent event.

The phase figure is an **added deterministic diagnostic with resident z clamped at its stationary composition** and equal division. It uses integrated precursor exposure, not physical time. Ancestral sizes grow smoothly, cell numbers change at division thresholds, and precursor depletion obeys the same size accounting. This makes the phase mismatch visible but removes molecular noise, chemical recovery, and stochastic partition; it does not establish fidelity or the selection probability of the count model. The literal stochastic model remains available separately in `PopulationKernel`.

## Checks and scope

Seven scientific test groups check stationary-root and founder admission enclosures, exact energy-matrix sandwiches, literal falling-factorial propensities, the nonexplosion-weight generator identity, complementary probabilities, simultaneous endpoint division and chemical-flag priority, unfinished simulation semantics, the published bound table, envelope ordering, scope guards, the factor-two phase issue and the safe aggregate drift sign. Boundary-order tests use a labelled deterministic acceptance double to isolate the control flow; those synthetic cells are not claimed to be chemically admitted.

`scalar_certificates()` recomputes the displayed rational constant relations and exact positive-definiteness of both matrix sandwiches. It does not recheck the full nonlinear finite-count generator inequalities, rebuild the finite uniformized state space, or rerun the Lean proof. The probability result is the manuscript theorem; finite tests are implementation checks. No atom-balanced realization, repeated-transfer theorem, fixation probability or experimental validation is supplied.

## Reuse terms

MIT licensing is proposed pending the owner's decision. This example does not independently grant a new license; confirm repository terms before redistribution.
