Derive a phenotype from the genome without touching it

M3.2 adds derive_phenotype and plan_development as pure integer
functions of a genome, a growth state and an environment. Nothing is
stored: a phenotype is recomputed from retained inputs rather than
cached, so a cached copy can always be checked against a recomputation.

The risk this increment was scoped against is confusing the genome with
runtime damage. Growth and damage live in a separate state that no
function may write back, and no entry point takes a mutable genome.
Damage changes the phenotype and leaves the encoded bytes and content
digest identical, so heredity cannot carry acquired condition.

The genome's development version selects a rule set, which is what makes
that field worth carrying; an unknown version fails closed rather than
deriving under the wrong rules. Version 1 declares every constant. The
shape model is explicit rather than implied: the body is a cube of
uniform declared density, so extent is an exact integer cube root and
surface is six extents squared. Membrane mass follows surface and the
genome's thickness, maintenance follows total mass plus a membrane
upkeep term, and uptake scales with surface, so size trades uptake
against maintenance. A capability the genome does not carry yields zero.

A plan advances growth by at most the rule step, reduced to the largest
step the available material funds exactly, never a partial one and never
a grant. It reserves nothing and pays for nothing: the matching transfer
does not exist until M3.3, and an apply that moved no inventory would
look like a committed operation while conserving nothing.

The fixture genome is an exact 20 micrometre cube, so every derived value
is asserted as a hand-calculated literal, as are the half-built, damaged,
maximum and cube-root-boundary cases. Determinism is checked over 45
growth and temperature combinations. The declared flooring is pinned
rather than hidden: a body whose mass floors to zero advances its counter
for no material, granting no structure because none exists either way.

Omitted physics is a documented model limitation, not a modifier. Nothing
here is balance, and no organism yet develops. Native Release, clang-tidy
analysis, ASan and format checks pass 18/18; every existing golden and
fingerprint is unchanged. Linux CI has not run yet.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-09-22 21:48:24 -04:00
co-authored by Claude Opus 5
parent 64a12c4dfc
commit 3f86dada0e
11 changed files with 703 additions and 6 deletions
+6 -1
View File
@@ -40,7 +40,7 @@ target_include_directories(evo_accounting PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/in
target_compile_features(evo_accounting PUBLIC cxx_std_23)
evo_owned_target(evo_accounting)
add_library(evo_biology STATIC src/biology/genome.cpp)
add_library(evo_biology STATIC src/biology/genome.cpp src/biology/development.cpp)
add_library(evo::biology ALIAS evo_biology)
target_include_directories(evo_biology PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include")
target_compile_features(evo_biology PUBLIC cxx_std_23)
@@ -72,6 +72,11 @@ if(BUILD_TESTING)
evo_owned_target(evo-genome-tests)
add_test(NAME genome-contracts COMMAND evo-genome-tests)
set_tests_properties(genome-contracts PROPERTIES TIMEOUT 60)
add_executable(evo-development-tests tests/development_tests.cpp)
target_link_libraries(evo-development-tests PRIVATE evo::biology)
evo_owned_target(evo-development-tests)
add_test(NAME development-contracts COMMAND evo-development-tests)
set_tests_properties(development-contracts PROPERTIES TIMEOUT 60)
add_executable(evo-producer-tests tests/producer_tests.cpp)
target_link_libraries(evo-producer-tests PRIVATE evo::processes)
evo_owned_target(evo-producer-tests)
+2 -1
View File
@@ -94,7 +94,8 @@ codec. `src/accounting` provides the independent finite-inventory ledger;
it is not yet part of particle snapshots. `src/processes` holds the synthetic
producer, feeding, reproduction and episode fixtures built on that ledger; they
are bounded experiments, not organism biology. `src/biology` holds the immutable
genome record; nothing reads it yet. `apps/evo-sim` owns CLI/file I/O
genome record and the deterministic development that derives a phenotype from it;
nothing reads either yet. `apps/evo-sim` owns CLI/file I/O
and reporting. `tests` holds contract,
fuzz and measurement programs. Future biology, world, networking and persistence
modules are documented boundaries; they are added when they have real behavior.
+5 -1
View File
@@ -74,7 +74,11 @@ million ticks conserve exactly, which demonstrates arithmetic, not ecology.
M3.1 now supplies that record (ADR-0030): seven versioned capability kinds with
units, ranges, declared and mandated developmental edges, immutable ancestry and
a canonical bounded encoding. It is validated once at the boundary and coupled to
nothing; development, phenotype derivation and mutation remain M3.2 to M3.4.
nothing. M3.2 now derives a phenotype from it (ADR-0031): mass, a declared cube
geometry, maintenance and enabled components, as pure integer functions of genome,
growth and environment, with a bounded plan reporting what further growth would
require. Growth and damage are runtime state that never reach the genome. Nothing
is spent yet; M3.3 attaches these parameters to the M2 budgets.
## M3 — Genome v0.1
+20 -3
View File
@@ -7,7 +7,7 @@ persistent simulation server. The founding vision remains unchanged.
## Completed implementation
- Vision, architectural pillars, risks, open-question register, architecture
diagrams, biological contracts, engineering constitution and 30 ADRs.
diagrams, biological contracts, engineering constitution and 31 ADRs.
Proposed/deferred choices remain distinct from accepted proof decisions.
- M0–M4 task breakdowns with dependencies, acceptance evidence and risks,
plus M5–M14 gates in [ROADMAP.md](ROADMAP.md).
@@ -61,8 +61,8 @@ for the bounded proof; the general production ECS remains a later measured choic
| Priority | Work | Completion evidence |
|---|---|---|
| 1 | M3.2 development pipeline | Same genome and environment yield the same explicit phenotype parameters, with material and capability prerequisites |
| 2 | M3.3 derive energetic components | Size, membrane and movement tradeoffs affect several budgets; connects the genome to the M2 fixtures |
| 1 | M3.3 derive energetic components | Size, membrane and movement tradeoffs affect several budgets; the first increment where a genome reaches the M2 ledger |
| 2 | M3.4 seeded mutation candidates | Bounded reproducible candidates conditioned by recorded context, with prerequisite and cost tests |
| Delivery gate | Add/update the dev workload when a deployable increment needs it; Argo is ready | Observe Job/pod completion separately from image publication; no World0 changes |
M1.6 now implements [the sequential scheduler contract](architecture/SCHEDULER_CONTRACT.md):
@@ -174,6 +174,23 @@ affects any simulation; the M2 fixtures still duplicate founder strategies.
Development, phenotype, mutation and heredity remain M3.2 to M3.5. Native
Release, analysis, ASan and formatting passed; Linux CI has not run yet.
M3.2 derives a phenotype from that record (ADR-0031). `derive_phenotype` and
`plan_development` are pure integer functions of genome, growth and environment,
so a phenotype is recomputed from retained inputs rather than cached. Growth and
damage are runtime state that never reach the genome: damage changes the
phenotype and leaves the content digest identical, which is the risk this
increment was scoped against. The genome's development version selects a rule
set and an unknown version fails closed. Version 1 declares every constant:
the body is a cube of uniform declared density, membrane mass follows surface and
thickness, maintenance follows mass plus a membrane upkeep term, and uptake scales
with surface, so size trades uptake against maintenance. A capability the genome
does not carry yields zero. A plan advances growth by at most the rule step,
reduced to the largest step the available material funds exactly, and reserves
nothing: no inventory moves until M3.3. Omitted physics is a documented model
limitation, not a modifier, and the constants must not become tuning by having
been written down. Native Release, analysis, ASan and formatting passed 18/18;
Linux CI has not run yet.
Before biology, resolve the relevant heredity and energetic contracts rather
than treating proof particles as organisms. Exact game tick rate, NPC mutation,
logout treatment, species/extinction rules and multicellular transition remain
+115
View File
@@ -0,0 +1,115 @@
# ADR-0031: Deterministic development and derived phenotype
## Status
Adopted for M3.2. The transfer half of ApplyDevelopment, energetic budgets and
any coupling to the M2 process fixtures are M3.3. Mutation is M3.4. No gameplay
balance, mortality rule or fitness score is selected.
## Context
M3.1 produced a validated genome that nothing reads. GENOME_MODEL requires two
things before capability can reach a budget: DerivePhenotype, producing dimensioned
mass, geometry, maintenance and enabled component descriptions, and
PlanDevelopment, returning a bounded construction plan and its resource
requirements from genome, growth and environment.
The named risk is confusing the genome with runtime damage. A genome is immutable
and shared by a lineage; what an organism has actually built, and what it has
lost, are per-organism runtime state. If development wrote either back into the
genome, heredity would silently carry acquired condition.
## Decision
Add `evo::biology` free functions over the existing record. Nothing is stored:
`derive_phenotype` and `plan_development` are pure functions of a genome, a
`GrowthState` and an `EnvironmentState`, so a phenotype is recomputed from
retained inputs rather than cached, and a cached copy can always be checked
against a recomputation.
`GrowthState` holds what the organism has built and lost, both in thousandths:
realized fraction of target size, and damage. `EnvironmentState` holds the
ambient temperature and the material available for building. Neither is ever
written to the genome, and no function takes a mutable genome. Damage reduces
realized structure and therefore the phenotype; it changes no genome field and
leaves the content digest untouched.
The genome's development version selects a rule set. Version 1 declares every
constant the derivation uses: densities, a maintenance rate, a membrane upkeep
factor, a construction energy cost, a reference surface for uptake scaling, a
reference temperature, and a maximum growth step per plan. An unknown version
fails closed rather than silently deriving under the wrong rules, which is what
makes that field worth carrying.
Derivation is exact integer arithmetic with declared flooring, no floating point,
no clock and no randomness, so the same inputs always produce the same phenotype.
Every step is checked for overflow and reports an error rather than wrapping.
The shape model is explicit: the body is a cube of uniform declared density, so
extent is the exact integer cube root of volume and surface is six extents
squared. Membrane mass is surface times the genome's thickness times membrane
density. Maintenance is proportional to total mass plus a membrane upkeep term,
so a thicker membrane costs more to hold. Uptake scales with surface against a
declared reference, so size is a real tradeoff rather than a free gain. A
capability the genome does not carry yields zero for its component: permitted
capability still requires the record to carry it, and later the material to build
it. Thermal shortfall is the amount by which the ambient temperature exceeds the
genome's tolerance around the reference, reported as a physical quantity and not
as a mortality, penalty or damage rule.
`plan_development` advances realized growth toward the target by at most the rule
step, computes the mass difference between the current and proposed phenotype, and
reports the material and construction energy that difference requires. When the
available material cannot fund the whole step it returns the largest step the
material does fund, exactly, rather than a partially funded one or a grant. The
plan carries the growth state it would produce, so committing is storing that
state; no function applies a plan on its own, because the matching transfer does
not exist until M3.3 and an apply that moved nothing would invite exactly the
unpaid commit this project keeps rejecting.
## Alternatives Considered
Caching a phenotype on the organism would need invalidation on every input change
and would let a stale cache outlive the record it came from. Writing realized
growth back into the genome would make heredity carry acquired condition, the
explicit risk here. Floating point would end determinism across platforms for no
gain at these magnitudes. A geometry solver or a real surface-to-volume physics
model is unjustified before any of it reaches a budget. An `apply` that returned
a new growth state without moving inventory would look like a committed operation
while conserving nothing.
## Benefits
Capability becomes dimensioned physical parameters without touching the genome or
any ledger. Development is reproducible from retained inputs, so a phenotype can
be recomputed and compared rather than trusted. Material shortfall reduces what is
built instead of granting it. M3.3 can attach budgets to a phenotype that is
already deterministic and already tested.
## Costs
The rule constants are chosen, not derived, and the cube shape model is a
deliberate simplification. Flooring at each step biases small organisms slightly
downward. Recomputing instead of caching costs a cube root and a few
multiplications per query. Repair is not modelled: a plan advances growth and
never reduces damage, which leaves damaged structure permanent for now.
## Risks
Omitted physics is a documented model limitation, not an unrelated modifier: do
not read extent, maintenance or uptake as balance, stats or a power score, and do
not let the constants become tuning by having been written down. A derived
phenotype is not a viability claim, and thermal shortfall is a reported quantity,
not a death rule. Nothing here decides repair, ageing, starvation, morphology or
how any of this is spent; a plan reserves nothing and pays for nothing.
## Consequences
Test that identical inputs give identical phenotypes and that the genome and its
digest are unchanged by every call, that damage changes the phenotype while
leaving the genome identical, that absent capabilities yield zero components,
that every rule constant is exercised, that the cube root is exact at boundaries,
that unknown rule versions and out-of-range growth fail closed, that overflow is
reported rather than wrapped, and that an underfunded plan returns the exact
largest affordable step. No genome, snapshot, ledger, process fixture, renderer or
deployment changes, and no organism yet develops.
+1
View File
@@ -23,6 +23,7 @@ Each record has the eight required sections.
0028 adopts funded reproduction, bounded slot capacity and retained lineage IDs.
0029 scopes the deterministic ecosystem driver and bounded measured episodes.
0030 adopts the immutable genome v1 record, validation and canonical encoding.
0031 adopts deterministic development, derived phenotype and bounded plans.
Every dependency adoption records exact version/commit and integrity hash,
transitive license obligations, maintenance/security review, owner and removal
+39
View File
@@ -115,3 +115,42 @@ expression, NPC divergence or recombination. A parameter within range is not a
viable organism: validation proves neither developmental feasibility nor
biological plausibility, and the schema ranges are expressible bounds rather than
balance. Fitness remains an outcome, not a score held in the record.
## Implemented M3.2 development and phenotype
[ADR-0031](../adr/0031-development-and-phenotype.md) adds `derive_phenotype` and
`plan_development` as pure functions over the M3.1 record. Nothing is stored: a
phenotype is recomputed from retained inputs rather than cached, so a cached copy
can always be checked against a recomputation.
`GrowthState` holds what an organism has built and what it has lost, in
thousandths. `EnvironmentState` holds ambient temperature and the material a plan
may draw on. Neither is written to the genome, and no function takes a mutable
genome: damage changes the phenotype and leaves the content digest untouched, so
heredity cannot carry acquired condition.
The genome's development version selects the rule set, and an unknown version
fails closed. Version 1 declares every constant the derivation uses. The shape
model is explicit: the body is a cube of uniform declared density, so extent is
the exact integer cube root of volume and surface is six extents squared. Membrane
mass is surface times the genome's thickness times membrane density. Maintenance
is proportional to total mass plus a membrane upkeep term, so a thicker membrane
costs more to hold. Uptake scales with surface against a declared reference, so
size trades uptake against maintenance. A capability the genome does not carry
yields zero for its component.
| Contract | Status after M3.2 |
|---|---|
| ValidateGenome | Implemented for schema 1, at construction and at decode |
| PlanDevelopment | Implemented: bounded step, exact largest affordable, reserves nothing |
| ApplyDevelopment | Half: a plan carries the growth state it would produce, but no transfer exists until M3.3 |
| DerivePhenotype | Implemented for rule version 1 |
| GenerateMutationCandidates | Not started; M3.4 |
| SelectMutation | Not started; M3.4 |
Omitted physics is a documented model limitation. Extent, maintenance and uptake
are derived quantities, not balance, stats or a power score, and the constants
must not become tuning by having been written down. Thermal shortfall is reported
as a quantity; it is not a mortality, penalty or damage rule. A derived phenotype
is not a viability claim. Repair is not modelled: a plan advances growth and never
reduces damage. Nothing is spent or reserved, and no organism yet develops.
+48
View File
@@ -434,3 +434,51 @@ network protocol or durable storage, and neither the digest nor the checksum is
an authenticity claim. Golden `d61ad5bf0c928c76` and the ecosystem fingerprint
`2cd4a15f9fbe9949` are unchanged. No deployment manifest or image pin changed.
Linux validation is pending its first pushed run; no Gitea result is claimed yet.
## M3.2 development and phenotype (2026-09-22)
Native Release, analysis and MSVC ASan each passed 18/18 CTests; formatting
passed. Commands: `tools/windows-check.ps1 -Preset <release|analysis|asan>
-Action check` and debug `-Action format`. `development-contracts` is the one new
CTest case, in the existing `evo::biology` library, which still nothing else
links. No existing suite changed.
The fixture genome uses a target size of 8,000,000 fg, which is an exact 20
micrometre cube at the declared density, so every derived value is hand-calculable
and is asserted as a literal: structural mass 8,000,000, extent 20, surface 2,400,
membrane mass 28,800,000, total 36,800,000 and maintenance 160,000 picojoules per
tick. Half-built, damaged and maximum-size cases are hand-calculated the same way,
including the 1e9 fg body that is an exact 100 micrometre cube with an uptake rate
of exactly the reference surface, and the 999,999,999 fg body one cubic micrometre
short of it, whose extent is 99.
Determinism is checked over 45 growth and temperature combinations, each derived
twice and compared, with more growth never yielding less structure. Damage is
checked to change the phenotype while leaving the genome's encoded bytes and
content digest identical, which is the M3.2 risk stated in the roadmap. Capability
prerequisites are checked both ways: without the capability a component is zero at
any size, and with it uptake scales with surface while movement speed does not.
Thermal shortfall is checked inside tolerance, symmetrically outside it, and
without the capability, and is confirmed to change no other derived value.
Unsupported rule versions and out-of-range growth fail closed through both entry
points.
Plans are checked for the full funded step, for the exact largest affordable step
one femtogram short of it, for no growth with no material, for a finished organism,
for clamping the last step to the target rather than overshooting, and for never
repairing damage. The declared flooring is pinned rather than hidden: a body whose
mass floors to zero advances its growth counter for no material, which grants no
structure because none exists at that size either way.
Coverage limitation: the overflow guards are unreachable through the public API at
schema 1 ranges, because the largest admissible genome produces a total mass of
about 7.2e11 femtograms, eleven orders of magnitude below the u64 limit. They are
kept as guards for later schema ranges and are recorded here rather than covered
by a test that could not fail.
No organism develops, nothing links the library except its own tests, and no
inventory moves: a plan reserves nothing and pays for nothing. The transfer half
of ApplyDevelopment, energetic budgets, repair, ageing, starvation, mutation and
morphology are not implemented. Golden `d61ad5bf0c928c76`, ecosystem fingerprint
`2cd4a15f9fbe9949` and the frozen genome fixture are unchanged. No deployment
manifest or image pin changed. Linux validation is pending its first pushed run.
+67
View File
@@ -0,0 +1,67 @@
#pragma once
#include "evo/biology/genome.hpp"
namespace evo::biology {
// What an organism has actually built and lost. Runtime state, never written
// back into the genome: heredity must not carry acquired condition.
struct GrowthState {
std::uint32_t realized_per_thousand{};
std::uint32_t damage_per_thousand{};
auto operator<=>(const GrowthState&) const = default;
};
struct EnvironmentState {
std::uint32_t temperature_millikelvin{};
// Bounds what a plan can fund. Nothing here is spent or reserved.
std::uint64_t available_material{};
auto operator<=>(const EnvironmentState&) const = default;
};
// Chosen constants, reviewable as a unit and selected by the genome's
// development version. Declared model parameters, not balance.
struct DevelopmentRules {
std::uint64_t structure_density; // femtograms per cubic micrometre
std::uint64_t membrane_density; // femtograms per cubic micrometre
std::uint64_t maintenance_per_kilogram; // picojoules per tick per 1000 fg
std::uint64_t membrane_upkeep_per_kilo; // picojoules per tick per 1000 fg
std::uint64_t construction_per_kilogram; // picojoules per 1000 fg built
std::uint64_t reference_surface; // square micrometres
std::uint32_t reference_temperature; // millikelvin
std::uint32_t growth_step_per_thousand; // most one plan may advance
};
// Dimensioned parameters derived from a genome and its runtime state. A derived
// phenotype is not a viability claim and holds no fitness score.
struct Phenotype {
std::uint64_t structural_mass{}; // femtograms
std::uint64_t membrane_mass{}; // femtograms
std::uint64_t total_mass{}; // femtograms
std::uint32_t extent{}; // micrometres, the cube-model side length
std::uint64_t surface{}; // square micrometres
std::uint64_t maintenance{}; // picojoules per tick
std::uint32_t movement_speed{}; // micrometres per tick; zero without the capability
std::uint64_t ingestion_rate{}; // femtograms per tick; zero without the capability
std::uint32_t conversion_per_thousand{};
// Millikelvin beyond the genome's tolerance. A reported quantity, not a rule.
std::uint32_t thermal_shortfall{};
auto operator<=>(const Phenotype&) const = default;
};
// A proposal. It reserves nothing, pays for nothing and commits nothing; the
// matching transfer does not exist until M3.3.
struct DevelopmentPlan {
GrowthState after{};
std::uint64_t material_required{};
std::uint64_t energy_required{};
auto operator<=>(const DevelopmentPlan&) const = default;
};
enum class DevelopmentError : std::uint8_t { unsupported_rules, invalid_growth, overflow };
[[nodiscard]] std::expected<DevelopmentRules, DevelopmentError>
rules_for(std::uint32_t development_version);
// Pure: a phenotype is recomputed from retained inputs rather than cached, so a
// cached copy can always be checked against a recomputation.
[[nodiscard]] std::expected<Phenotype, DevelopmentError>
derive_phenotype(const Genome& genome, GrowthState growth, EnvironmentState environment);
// Advances realized growth toward the target by at most the rule step, reduced to
// the largest step the available material funds exactly. Never repairs damage.
[[nodiscard]] std::expected<DevelopmentPlan, DevelopmentError>
plan_development(const Genome& genome, GrowthState growth, EnvironmentState environment);
} // namespace evo::biology
+146
View File
@@ -0,0 +1,146 @@
#include "evo/biology/development.hpp"
#include <algorithm>
#include <limits>
namespace evo::biology {
namespace {
constexpr std::uint32_t thousand = 1000;
bool multiply(std::uint64_t& result, std::uint64_t left, std::uint64_t right) noexcept {
if (left != 0 && right > std::numeric_limits<std::uint64_t>::max() / left) {
return false;
}
result = left * right;
return true;
}
bool add(std::uint64_t& result, std::uint64_t left, std::uint64_t right) noexcept {
if (right > std::numeric_limits<std::uint64_t>::max() - left) {
return false;
}
result = left + right;
return true;
}
// Exact: the largest r with r*r*r <= value. No floating point is involved.
std::uint64_t integer_cube_root(std::uint64_t value) noexcept {
std::uint64_t root = 0;
// 2^21 cubed already exceeds u64, so 21 bits are enough.
for (std::uint64_t bit = 1ULL << 21U; bit != 0; bit >>= 1U) {
const auto candidate = root | bit;
std::uint64_t cube{};
if (multiply(cube, candidate, candidate) && multiply(cube, cube, candidate) &&
cube <= value) {
root = candidate;
}
}
return root;
}
std::uint64_t scaled(std::uint64_t value, std::uint64_t numerator) noexcept {
// Declared flooring; the remainder is discarded rather than carried.
return value / thousand * numerator + value % thousand * numerator / thousand;
}
} // namespace
std::expected<DevelopmentRules, DevelopmentError> rules_for(std::uint32_t development_version) {
if (development_version != 1) {
return std::unexpected{DevelopmentError::unsupported_rules};
}
return DevelopmentRules{1000, 1200, 2, 3, 40, 60'000, 293'150, 50};
}
std::expected<Phenotype, DevelopmentError>
derive_phenotype(const Genome& genome, GrowthState growth, EnvironmentState environment) {
if (growth.realized_per_thousand > thousand || growth.damage_per_thousand > thousand) {
return std::unexpected{DevelopmentError::invalid_growth};
}
const auto rules = rules_for(genome.development_version());
if (!rules) {
return std::unexpected{rules.error()};
}
Phenotype phenotype;
// target_size, membrane and energy_conversion are required by schema 1.
const auto target = *genome.parameter(Capability::target_size);
const auto built = scaled(target, growth.realized_per_thousand);
phenotype.structural_mass = scaled(built, thousand - growth.damage_per_thousand);
phenotype.extent = static_cast<std::uint32_t>(
integer_cube_root(phenotype.structural_mass / rules->structure_density));
std::uint64_t face{};
if (!multiply(face, phenotype.extent, phenotype.extent) ||
!multiply(phenotype.surface, face, 6)) {
return std::unexpected{DevelopmentError::overflow};
}
std::uint64_t shell{};
if (!multiply(shell, phenotype.surface, *genome.parameter(Capability::membrane)) ||
!multiply(phenotype.membrane_mass, shell, rules->membrane_density)) {
return std::unexpected{DevelopmentError::overflow};
}
if (!add(phenotype.total_mass, phenotype.structural_mass, phenotype.membrane_mass)) {
return std::unexpected{DevelopmentError::overflow};
}
// A thicker membrane is held as well as built, so upkeep is charged twice over.
if (!add(phenotype.maintenance, scaled(phenotype.total_mass, rules->maintenance_per_kilogram),
scaled(phenotype.membrane_mass, rules->membrane_upkeep_per_kilo))) {
return std::unexpected{DevelopmentError::overflow};
}
phenotype.conversion_per_thousand =
static_cast<std::uint32_t>(*genome.parameter(Capability::energy_conversion));
// A capability the genome does not carry yields nothing, whatever the size.
if (genome.carries(Capability::movement)) {
phenotype.movement_speed =
static_cast<std::uint32_t>(*genome.parameter(Capability::movement));
}
if (genome.carries(Capability::ingestion)) {
std::uint64_t uptake{};
if (!multiply(uptake, *genome.parameter(Capability::ingestion), phenotype.surface)) {
return std::unexpected{DevelopmentError::overflow};
}
phenotype.ingestion_rate = uptake / rules->reference_surface;
}
const auto tolerance = genome.carries(Capability::thermal_tolerance)
? *genome.parameter(Capability::thermal_tolerance)
: 0;
const auto deviation = environment.temperature_millikelvin > rules->reference_temperature
? environment.temperature_millikelvin - rules->reference_temperature
: rules->reference_temperature - environment.temperature_millikelvin;
phenotype.thermal_shortfall = deviation > tolerance ? deviation - tolerance : 0;
return phenotype;
}
std::expected<DevelopmentPlan, DevelopmentError>
plan_development(const Genome& genome, GrowthState growth, EnvironmentState environment) {
const auto current = derive_phenotype(genome, growth, environment);
if (!current) {
return std::unexpected{current.error()};
}
const auto rules = rules_for(genome.development_version());
if (!rules) {
return std::unexpected{rules.error()};
}
DevelopmentPlan plan;
plan.after = growth;
const auto remaining = thousand - growth.realized_per_thousand;
const auto step = std::min(remaining, rules->growth_step_per_thousand);
// Take the largest step the available material funds exactly, never a
// partially funded one and never a grant.
for (std::uint32_t attempt = step; attempt > 0; --attempt) {
auto proposed = growth;
proposed.realized_per_thousand += attempt;
const auto grown = derive_phenotype(genome, proposed, environment);
if (!grown) {
return std::unexpected{grown.error()};
}
if (grown->total_mass < current->total_mass) {
return std::unexpected{DevelopmentError::overflow};
}
const auto material = grown->total_mass - current->total_mass;
if (material > environment.available_material) {
continue;
}
plan.after = proposed;
plan.material_required = material;
plan.energy_required = scaled(material, rules->construction_per_kilogram);
break;
}
return plan;
}
} // namespace evo::biology
+254
View File
@@ -0,0 +1,254 @@
#include "evo/biology/development.hpp"
#include <iostream>
#include <source_location>
#include <stdexcept>
#include <string>
#include <vector>
namespace {
using namespace evo::biology;
void check(bool condition, std::source_location location = std::source_location::current()) {
if (!condition) {
throw std::runtime_error("development line " + std::to_string(location.line()));
}
}
#define CHECK(expression) check(static_cast<bool>(expression))
// Target size 8e6 fg gives an exact cube root at full growth, so every derived
// value below is hand-calculable against ADR-0031's declared rules.
GenomeDraft draft() {
return {7,
1,
1,
{},
{{Capability::energy_conversion, 400, 0},
{Capability::membrane, 10, 0},
{Capability::target_size, 8'000'000, 0}}};
}
Genome build(const GenomeDraft& source) {
const auto genome = Genome::create(source);
check(genome.has_value());
return *genome;
}
constexpr EnvironmentState temperate{293'150, 1'000'000'000};
void hand_calculated_phenotype() {
const auto genome = build(draft());
const auto grown = derive_phenotype(genome, {1000, 0}, temperate);
CHECK(grown);
// 8e6 fg at density 1000 is 8000 um^3, an exact 20 um cube.
CHECK(grown->structural_mass == 8'000'000 && grown->extent == 20);
CHECK(grown->surface == 2400); // six 20x20 faces
CHECK(grown->membrane_mass == 28'800'000); // 2400 * 10 um * 1200
CHECK(grown->total_mass == 36'800'000);
CHECK(grown->maintenance == 73'600 + 86'400); // mass * 2 plus membrane * 3
CHECK(grown->conversion_per_thousand == 400);
CHECK(grown->movement_speed == 0 && grown->ingestion_rate == 0);
CHECK(grown->thermal_shortfall == 0);
// Half-built: 4e6 fg is 4000 um^3, and 15^3 = 3375 <= 4000 < 16^3.
const auto half = derive_phenotype(genome, {500, 0}, temperate);
CHECK(half && half->structural_mass == 4'000'000 && half->extent == 15);
CHECK(half->surface == 1350 && half->membrane_mass == 16'200'000);
CHECK(half->total_mass == 20'200'000);
}
void damage_is_not_genome() {
const auto genome = build(draft());
const auto before = genome.encode();
const auto intact = derive_phenotype(genome, {1000, 0}, temperate);
// A quarter lost: 6e6 fg is 6000 um^3, and 18^3 = 5832 <= 6000 < 19^3.
const auto hurt = derive_phenotype(genome, {1000, 250}, temperate);
CHECK(intact && hurt);
CHECK(hurt->structural_mass == 6'000'000 && hurt->extent == 18);
CHECK(hurt->surface == 1944 && hurt->membrane_mass == 23'328'000);
CHECK(hurt->total_mass == 29'328'000 && hurt->maintenance == 58'656 + 69'984);
CHECK(*hurt != *intact);
// The record a lineage inherits is untouched by what one organism lost.
CHECK(genome.encode() == before);
CHECK(genome.content_digest() == build(draft()).content_digest());
const auto repeated = derive_phenotype(genome, {1000, 250}, temperate);
CHECK(repeated && *repeated == *hurt);
}
void identical_inputs_give_identical_phenotypes() {
const auto genome = build(draft());
for (std::uint32_t realized = 0; realized <= 1000; realized += 125) {
for (std::uint32_t damage = 0; damage <= 1000; damage += 250) {
for (const auto temperature : {0U, 293'150U, 400'000U}) {
const EnvironmentState environment{temperature, 1'000'000};
const auto first = derive_phenotype(genome, {realized, damage}, environment);
const auto second = derive_phenotype(genome, {realized, damage}, environment);
CHECK(first && second && *first == *second);
// More growth never yields less structure at equal damage.
if (realized >= 125) {
const auto smaller =
derive_phenotype(genome, {realized - 125, damage}, environment);
CHECK(smaller && smaller->structural_mass <= first->structural_mass);
}
}
}
}
}
void capability_prerequisites() {
const auto bare = build(draft());
const auto without = derive_phenotype(bare, {1000, 0}, temperate);
CHECK(without && without->movement_speed == 0 && without->ingestion_rate == 0);
auto source = draft();
source.capabilities.push_back({Capability::movement, 250, 0});
source.capabilities.push_back({Capability::ingestion, 120'000, 0});
const auto capable = build(source);
const auto with = derive_phenotype(capable, {1000, 0}, temperate);
CHECK(with && with->movement_speed == 250);
CHECK(with->ingestion_rate == 4800); // 120000 * 2400 / 60000 reference surface
// Size is a real tradeoff: uptake scales with surface, maintenance with mass.
const auto smaller = derive_phenotype(capable, {500, 0}, temperate);
CHECK(smaller && smaller->ingestion_rate < with->ingestion_rate);
CHECK(smaller->maintenance < with->maintenance);
CHECK(smaller->movement_speed == with->movement_speed); // Speed is not size-scaled.
// Everything else about the two genomes is identical.
CHECK(with->structural_mass == without->structural_mass);
CHECK(with->maintenance == without->maintenance);
}
void thermal_shortfall_is_reported_not_enforced() {
auto source = draft();
source.capabilities.push_back({Capability::thermal_tolerance, 5'000, 0});
const auto tolerant = build(source);
const auto bare = build(draft());
for (const auto offset : {0U, 5'000U}) {
const EnvironmentState warm{293'150 + offset, 0};
const auto inside = derive_phenotype(tolerant, {1000, 0}, warm);
CHECK(inside && inside->thermal_shortfall == 0);
}
const EnvironmentState hot{293'150 + 8'000, 0};
const auto stressed = derive_phenotype(tolerant, {1000, 0}, hot);
CHECK(stressed && stressed->thermal_shortfall == 3'000);
const EnvironmentState cold{293'150 - 8'000, 0};
const auto chilled = derive_phenotype(tolerant, {1000, 0}, cold);
CHECK(chilled && chilled->thermal_shortfall == 3'000); // Symmetric about the reference.
// Without the capability every deviation is reported in full.
const auto exposed = derive_phenotype(bare, {1000, 0}, hot);
CHECK(exposed && exposed->thermal_shortfall == 8'000);
// Shortfall is a reported quantity: nothing else about the body changes.
CHECK(stressed->total_mass == exposed->total_mass);
CHECK(stressed->maintenance == exposed->maintenance);
}
void rule_versions_and_invalid_growth() {
CHECK(rules_for(1));
for (const auto version : {0U, 2U, 99U}) {
const auto missing = rules_for(version);
CHECK(!missing && missing.error() == DevelopmentError::unsupported_rules);
}
auto source = draft();
source.development_version = 2;
const auto future = build(source);
const auto derived = derive_phenotype(future, {1000, 0}, temperate);
CHECK(!derived && derived.error() == DevelopmentError::unsupported_rules);
const auto planned = plan_development(future, {0, 0}, temperate);
CHECK(!planned && planned.error() == DevelopmentError::unsupported_rules);
const auto genome = build(draft());
for (const auto growth : {GrowthState{1001, 0}, GrowthState{0, 1001}}) {
const auto rejected = derive_phenotype(genome, growth, temperate);
CHECK(!rejected && rejected.error() == DevelopmentError::invalid_growth);
const auto refused = plan_development(genome, growth, temperate);
CHECK(!refused && refused.error() == DevelopmentError::invalid_growth);
}
}
void plans_are_bounded_and_funded() {
const auto genome = build(draft());
// From half built, one step of 50 reaches 550: 4.4e6 fg is 4400 um^3 and
// 16^3 = 4096 <= 4400, so the extent grows from 15 to 16.
const auto funded = plan_development(genome, {500, 0}, temperate);
CHECK(funded);
CHECK(funded->after == (GrowthState{550, 0}));
CHECK(funded->material_required == 2'632'000); // 22832000 - 20200000
CHECK(funded->energy_required == 105'280); // material * 40 per 1000 fg
// One femtogram short of the full step buys exactly the largest step that fits.
const EnvironmentState tight{293'150, 2'631'999};
const auto reduced = plan_development(genome, {500, 0}, tight);
CHECK(reduced);
CHECK(reduced->after == (GrowthState{549, 0}));
CHECK(reduced->material_required == 2'624'000);
CHECK(reduced->material_required <= tight.available_material);
// No material funds no growth, and nothing is granted.
const EnvironmentState barren{293'150, 0};
const auto refused = plan_development(genome, {500, 0}, barren);
CHECK(refused && refused->after == (GrowthState{500, 0}));
CHECK(refused->material_required == 0 && refused->energy_required == 0);
// A finished organism plans nothing further.
const auto complete = plan_development(genome, {1000, 0}, temperate);
CHECK(complete && complete->after == (GrowthState{1000, 0}));
CHECK(complete->material_required == 0);
// The last step is clamped to the target rather than overshooting it.
const auto final_step = plan_development(genome, {980, 0}, temperate);
CHECK(final_step && final_step->after == (GrowthState{1000, 0}));
// A plan never repairs damage.
const auto damaged = plan_development(genome, {500, 300}, temperate);
CHECK(damaged && damaged->after.damage_per_thousand == 300);
}
void flooring_consequences() {
// A body whose mass floors to nothing advances its counter for no material.
// This is the declared flooring, not a grant: no structure exists either way.
auto source = draft();
source.capabilities = {{Capability::energy_conversion, 1, 0},
{Capability::membrane, 1, 0},
{Capability::target_size, 1, 0}};
const auto tiny = build(source);
const EnvironmentState barren{293'150, 0};
const auto plan = plan_development(tiny, {500, 0}, barren);
CHECK(plan && plan->after == (GrowthState{550, 0}));
CHECK(plan->material_required == 0 && plan->energy_required == 0);
const auto derived = derive_phenotype(tiny, {550, 0}, barren);
CHECK(derived && derived->structural_mass == 0 && derived->total_mass == 0);
CHECK(derived->extent == 0 && derived->surface == 0 && derived->maintenance == 0);
// The smallest body that rounds to a whole cubic micrometre is still tiny.
source.capabilities = {{Capability::energy_conversion, 1, 0},
{Capability::membrane, 1, 0},
{Capability::target_size, 1000, 0}};
const auto unit = build(source);
const auto whole = derive_phenotype(unit, {1000, 0}, barren);
CHECK(whole && whole->structural_mass == 1000 && whole->extent == 1);
CHECK(whole->surface == 6 && whole->membrane_mass == 7200);
}
void extreme_sizes_are_exact() {
auto source = draft();
source.capabilities = {{Capability::energy_conversion, 1000, 0},
{Capability::membrane, 10'000, 0},
{Capability::target_size, 1'000'000'000, 0},
{Capability::ingestion, 1'000'000, 0}};
const auto largest = build(source);
const auto derived = derive_phenotype(largest, {1000, 0}, temperate);
CHECK(derived);
// 1e9 fg at density 1000 is 1e6 um^3, an exact 100 um cube.
CHECK(derived->structural_mass == 1'000'000'000 && derived->extent == 100);
CHECK(derived->surface == 60'000);
CHECK(derived->membrane_mass == 720'000'000'000); // 60000 * 10000 * 1200
CHECK(derived->total_mass == 721'000'000'000);
CHECK(derived->ingestion_rate == 1'000'000); // Exactly the reference surface.
CHECK(derived->maintenance == 1'442'000'000 + 2'160'000'000);
// Cube roots are exact on both sides of a boundary.
source.capabilities[2] = {Capability::target_size, 999'999'999, 0};
const auto under = derive_phenotype(build(source), {1000, 0}, temperate);
CHECK(under && under->extent == 99); // 999999 um^3 is one short of 100^3
}
} // namespace
int main() try {
hand_calculated_phenotype();
damage_is_not_genome();
identical_inputs_give_identical_phenotypes();
capability_prerequisites();
thermal_shortfall_is_reported_not_enforced();
rule_versions_and_invalid_growth();
plans_are_bounded_and_funded();
flooring_consequences();
extreme_sizes_are_exact();
std::cout << "PASS development rules, phenotype derivation and bounded plans\n";
return 0;
} catch (...) {
return 1;
}