Give capability a cost without giving it a multiplier

M3.3 turns a phenotype into the budgets a ledger can hold: body
composition, maintenance, movement, the next construction step, the
per-tick intake limit and the reproduction investment. metabolism is the
single place the genome's description of capability becomes accounting
quantities, so the record itself stays free of those types and M3.1's
boundary is crossed once, explicitly.

The named risk is reintroducing RPG modifiers, where a capability
parameter becomes a flat percentage over every budget. Each budget is
therefore derived from a different phenotype quantity: maintenance from
mass plus membrane upkeep, movement from mass and speed, intake from
surface, construction from the mass a growth step adds, investment from
the body a parent already has. One parameter moves some budgets and not
others, by different amounts. Doubling membrane thickness costs more
matter to build, more energy to hold and more to haul, while leaving
uptake, speed, assimilation and structural mass identical, and the mass
and maintenance ratios differ, so no single multiplier could produce it.
The test asserts that non-uniformity rather than describing it.

Composition is declared per compartment, and membrane is the carbon-rich
one, so a thicker membrane changes what a body is made of and not only
how much. A split assigns the first three channels by share and gives the
remainder to the last, so parts always sum back to the whole and a
derived body can be spent through the ledger without a rounding leak.
That is checked at four awkward masses where every share floors.

processes::consumer_for is the first path from a genome into the M2
fixtures. Opening inventory stays the caller's: a genome says what an
organism can do, never what it holds, and a derived config that invented
an opening balance would create matter. A derived consumer is shown
driving a real feeding tick with the ledger conserving exactly, and a
bite one femtogram past the derived cap refused by the M2.3 contract.

Every budget is asserted as a hand-calculated literal. The constants are
chosen so budgets are of comparable magnitude, which is legibility for
tests and not tuning. No existing fixture reads genomes, and no organism
spends any budget: there is still no starvation, death or repair rule.

Native Release, clang-tidy analysis, ASan and format checks pass 19/19;
every existing golden and fingerprint is unchanged. Linux CI has not run.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-09-23 11:31:01 -04:00
co-authored by Claude Opus 5
parent 3f86dada0e
commit be71d4f441
13 changed files with 729 additions and 10 deletions
+9 -3
View File
@@ -40,15 +40,16 @@ 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 src/biology/development.cpp)
add_library(evo_biology STATIC src/biology/genome.cpp src/biology/development.cpp src/biology/metabolism.cpp)
add_library(evo::biology ALIAS evo_biology)
target_include_directories(evo_biology PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include")
target_link_libraries(evo_biology PUBLIC evo::accounting)
target_compile_features(evo_biology PUBLIC cxx_std_23)
evo_owned_target(evo_biology)
add_library(evo_processes STATIC src/processes/producer.cpp src/processes/feeding.cpp src/processes/ecosystem.cpp)
add_library(evo_processes STATIC src/processes/producer.cpp src/processes/feeding.cpp src/processes/ecosystem.cpp src/processes/genome_strategy.cpp)
add_library(evo::processes ALIAS evo_processes)
target_link_libraries(evo_processes PUBLIC evo::accounting)
target_link_libraries(evo_processes PUBLIC evo::accounting evo::biology)
evo_owned_target(evo_processes)
add_executable(evo-sim apps/evo-sim/main.cpp)
@@ -77,6 +78,11 @@ if(BUILD_TESTING)
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-metabolism-tests tests/metabolism_tests.cpp)
target_link_libraries(evo-metabolism-tests PRIVATE evo::processes)
evo_owned_target(evo-metabolism-tests)
add_test(NAME metabolism-contracts COMMAND evo-metabolism-tests)
set_tests_properties(metabolism-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)
+3 -2
View File
@@ -94,8 +94,9 @@ 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 and the deterministic development that derives a phenotype from it;
nothing reads either yet. `apps/evo-sim` owns CLI/file I/O
genome record, the deterministic development that derives a phenotype from it and
the metabolic budgets that give capability a cost. No fixture reads a genome 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.
+6 -1
View File
@@ -78,7 +78,12 @@ 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.
is spent yet. M3.3 now attaches those parameters to budgets (ADR-0032): body
composition, maintenance, movement, construction, intake and reproduction
investment, each derived from a different phenotype quantity so one parameter
moves some budgets and not others. `consumer_for` is the first path from a genome
into the M2 fixtures, and mass splits conserve exactly so a derived body can be
spent through the ledger. No existing fixture reads genomes yet; that is M3.6.
## M3 — Genome v0.1
+21 -4
View File
@@ -1,13 +1,13 @@
# Project status and next steps
Updated 2026-09-22. The repository contains an engineering foundation and a
Updated 2026-09-23. The repository contains an engineering foundation and a
deterministic headless proof. It does not yet contain cellular gameplay or a
persistent simulation server. The founding vision remains unchanged.
## Completed implementation
- Vision, architectural pillars, risks, open-question register, architecture
diagrams, biological contracts, engineering constitution and 31 ADRs.
diagrams, biological contracts, engineering constitution and 32 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.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 |
| 1 | M3.4 seeded mutation candidates | Bounded reproducible candidates conditioned by recorded context, with prerequisite, cost and fixed-seed tests |
| 2 | M3.5 heredity and divergence history | Reproduction persists parent/child links and genome identity survives death |
| 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):
@@ -191,6 +191,23 @@ 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.
M3.3 gives capability a cost (ADR-0032). `metabolic_budget` returns body
composition, maintenance, movement, construction, the per-tick intake limit and
the reproduction investment, in accounting types; `metabolism` is the single
translation layer and the genome record stays free of those types. Each budget
comes from a different phenotype quantity, so one parameter moves some and not
others: a thicker membrane costs more matter to build, more energy to hold and
more to haul, while leaving uptake, speed and assimilation identical. That
non-uniformity is asserted directly, because a capability that became a flat
multiplier is the failure this increment was scoped against. Composition is
declared per compartment, and splits give the remainder to the last channel so
parts sum back to the whole and a derived body can be spent without a rounding
leak. `processes::consumer_for` is the first path from a genome into the M2
fixtures, with opening inventory left to the caller so no matter is invented; a
derived consumer is shown driving a real feeding tick with the ledger conserving.
No existing fixture reads genomes yet and no organism spends any budget. Native
Release, analysis, ASan and formatting passed 19/19; 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
@@ -0,0 +1,106 @@
# ADR-0032: Metabolic budgets derived from a phenotype
## Status
Adopted for M3.3. Running seeded ensembles on genome-derived strategies is M3.6.
Mutation is M3.4. No gameplay balance, mortality rule or fitness score is selected,
and no existing M2 fixture behaviour changes.
## Context
M3.2 derives dimensioned physical parameters but nothing spends them. The M2
fixtures still run on hand-written constants, so capability and cost are still
unrelated. This is the increment where a genome first reaches the ledger, and the
roadmap names its risk precisely: reintroducing RPG modifiers, where a capability
parameter becomes a flat percentage applied uniformly to every budget.
M3.1 deliberately kept the genome free of accounting types so its units could not
imply ledger semantics. That boundary now has to be crossed somewhere explicit
rather than everywhere implicitly.
## Decision
Add `evo::biology::metabolic_budget`, one entry point returning every budget a
phenotype implies, in accounting types. The genome record itself stays free of
those types: `metabolism` is the single translation layer, and the genome remains
a description of capability rather than of resources.
The budgets are body composition, maintenance per tick, movement per tick at full
speed, total demand, the next construction step, the per-tick intake limit and the
reproduction investment. They are derived from different phenotype quantities on
purpose: maintenance from total mass plus a membrane upkeep term, movement from
total mass and speed, intake from surface, construction from the mass difference a
growth step implies, and investment from the body a parent would divide. A change
to one genome parameter therefore moves some budgets and not others, by different
amounts. That is the whole point: a thicker membrane costs more matter to build
and more energy to hold, while changing neither uptake nor speed. Nothing here is
a multiplier applied to a total.
Composition is declared per compartment in thousandths. Structure and membrane
have different compositions, so a thicker membrane changes what the body is made
of and not only how much. A split assigns the first three channels by share and
gives the remainder to the last, so mass is conserved exactly and a body can be
spent through the ledger without a rounding leak.
Reproduction investment is the body scaled by the genome's reproduction fraction,
with its energy priced at the same construction rate as the organism's own tissue:
building offspring tissue costs what building your own does. A genome without the
reproduction capability invests nothing, rather than investing a default.
The rule constants are selected by the same development version as M3.2 and fail
closed on an unknown one. They are chosen so the budgets are of comparable
magnitude, because budgets that differ by orders of magnitude make every tradeoff
invisible. That is a legibility choice for tests, not tuning, and it must be
re-derived before any of it is balanced.
`processes::consumer_for` converts a budget into the existing `ConsumerConfig`.
Opening inventory stays the caller's: a genome describes what an organism can do,
never the resources it happens to hold, and a derived config that also invented an
opening balance would be creating matter. Nothing else in the M2 fixtures changes,
and no existing fixture starts reading genomes.
## Alternatives Considered
A single efficiency multiplier over one budget would be exactly the modifier this
increment exists to avoid. Putting accounting types into the genome record would
undo the M3.1 boundary and let a stored parameter imply a ledger channel. Deriving
composition from the phenotype rather than declaring it per compartment would hide
the one place the membrane's different chemistry is stated. Giving the rounding
remainder to the largest channel instead of a fixed one would make a split depend
on the mass being split. Having `consumer_for` supply an opening inventory would
create matter from a description.
## Benefits
Capability now has cost, and the cost is not uniform. Size, membrane thickness and
movement each move a different subset of budgets, so the tradeoffs are visible and
testable rather than asserted. Mass splits conserve exactly, so a derived body can
be spent through the ledger. The M2 fixtures gain a genome-driven path without any
of them changing behaviour.
## Costs
Every constant is chosen, including two compositions, a movement coefficient and
an intake energy density. Intake is distributed by the structure composition, which
assumes an organism takes up what it builds from. Movement is priced at full speed
whether or not an organism moves, so it is a capacity rather than an expenditure.
The small integer helpers are duplicated rather than shared through an internal
header.
## Risks
Do not read any budget as balance or a power score, and do not let the constants
become tuning by having been measured. Comparable magnitudes were chosen for
legibility and say nothing about what an organism should be able to afford. A
budget is a derived quantity, not a rule: nothing here decides starvation, death,
repair or whether demand is ever met. No organism spends any of this yet.
## Consequences
Test that each budget is hand-calculable, that mass splits conserve exactly on
both compartments and at the remainder boundary, that a thicker membrane raises
matter cost and maintenance while leaving uptake and speed untouched, that a
larger body raises maintenance and uptake together, that an absent capability
yields a zero budget rather than a default, that unknown rule versions fail closed,
and that a derived consumer drives a real feeding tick with the ledger conserving.
No genome, snapshot, ledger, existing fixture, renderer or deployment changes.
+1
View File
@@ -24,6 +24,7 @@ Each record has the eight required sections.
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.
0032 derives non-uniform metabolic budgets and the first genome/ledger path.
Every dependency adoption records exact version/commit and integrity hash,
transitive license obligations, maintenance/security review, owner and removal
+34
View File
@@ -154,3 +154,37 @@ must not become tuning by having been written down. Thermal shortfall is reporte
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.
## Implemented M3.3 metabolic budgets
[ADR-0032](../adr/0032-metabolic-budgets-from-genome.md) turns a phenotype into
the budgets a ledger can hold: body composition, maintenance, movement, the next
construction step, the per-tick intake limit and the reproduction investment.
`metabolism` is the single place the genome's description of capability becomes
accounting quantities; the record itself stays free of those types.
Each budget is derived from a different phenotype quantity on purpose. Maintenance
follows total mass plus a membrane upkeep term, movement follows mass and speed,
intake follows surface, construction follows the mass a growth step adds, and
investment divides the body a parent already has. One genome parameter therefore
moves some budgets and not others, by different amounts: a thicker membrane costs
more matter to build, more energy to hold and more energy to haul, while changing
neither uptake nor speed. Nothing here is a multiplier applied to a total, which
is the capability-as-percentage-modifier failure this increment was scoped against.
Composition is declared per compartment, and membrane is the more carbon-rich one,
so a thicker membrane changes what a body is made of and not only how much. A
split assigns the first three channels by share and gives the remainder to the
last, so parts always sum back to the whole and a derived body can be spent
through the ledger without a rounding leak.
`processes::consumer_for` is the first path from a genome into the M2 fixtures.
Opening inventory stays the caller's: a genome describes what an organism can do,
never the resources it holds, and a derived config that invented an opening
balance would create matter. No existing fixture reads genomes; that is M3.6.
The rule constants are chosen so budgets are of comparable magnitude, because
budgets differing by orders of magnitude make every tradeoff invisible. That is a
legibility choice for tests, not tuning, and must be re-derived before balancing.
A budget is a derived quantity, not a rule: nothing here decides starvation,
death or repair, and no organism spends any of it yet.
+48
View File
@@ -482,3 +482,51 @@ 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.
## M3.3 metabolic budgets (2026-09-23)
Native Release, analysis and MSVC ASan each passed 19/19 CTests; formatting
passed. Commands: `tools/windows-check.ps1 -Preset <release|analysis|asan>
-Action check` and debug `-Action format`. `metabolism-contracts` is the one new
CTest case. `evo_biology` now links `evo::accounting` and `evo_processes` links
`evo::biology`; no existing suite changed and no existing fixture reads genomes.
Every budget is asserted as a hand-calculated literal against the same 20
micrometre cube fixture as M3.2: body 24,160,000 / 2,640,000 / 3,280,000 /
6,720,000 femtograms across C/N/P/other, maintenance 160,000 and movement 184,000
picojoules per tick, intake 240,000 picojoules and 2400/720/240/1440 femtograms,
and a reproduction investment of 11,040,000 femtograms priced at 441,600
picojoules. Construction is checked to compose each compartment separately rather
than by one blended ratio, and to agree exactly with what `plan_development`
reports as material and energy.
The non-uniformity the increment exists to demonstrate is tested directly.
Doubling membrane thickness raises body matter to 65,600,000 femtograms,
maintenance to 304,000 picojoules and the movement cost, shifts the carbon share
upward because membrane is the carbon-rich compartment, and leaves intake limit,
speed, assimilation and structural mass identical; the mass and maintenance ratios
are asserted to differ, so no single multiplier could produce this. Growth is
tested the same way: uptake follows surface while maintenance follows mass, and
their ratios differ.
Mass splits are checked to conserve at four awkward target sizes and four growth
fractions, where every share floors and the last channel absorbs the remainder.
An absent capability is checked to yield a zero budget rather than a default, and
unknown rule versions and out-of-range growth fail closed.
The genome-to-ledger path is exercised end to end: a derived `ConsumerConfig`
drives a real `FeedingCommunity` tick, the ledger totals are identical before and
after, and a bite one femtogram past the derived cap is refused by the existing
M2.3 contract. The opening inventory is checked to be exactly the caller's.
Coverage limitation: as in M3.2, the overflow guards are unreachable through the
public API at schema 1 ranges and are recorded rather than covered by a test that
could not fail. The small integer helpers are duplicated between `development.cpp`
and `metabolism.cpp` rather than shared through an internal header.
No organism spends any budget: nothing consumes maintenance, movement or
construction, and no starvation, death or repair rule exists. The constants are
chosen for legible magnitudes, not balance. 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; no Gitea result is claimed for any increment since `b01a824`.
+42
View File
@@ -0,0 +1,42 @@
#pragma once
#include "evo/accounting/ledger.hpp"
#include "evo/biology/development.hpp"
namespace evo::biology {
// Shares in thousandths over the ledger's C/N/P/other channels, summing to 1000.
// The last channel absorbs the rounding remainder, so a split conserves mass.
using Composition = std::array<std::uint16_t, 4>;
// Chosen constants, selected by the same development version as ADR-0031 and
// reviewable as a unit. Declared model parameters, not balance.
struct MetabolicRules {
Composition structure;
Composition membrane;
// Picojoules per tick per 1000 femtograms at 1000 micrometres per tick.
std::uint64_t movement_per_kilogram;
// Picojoules of intake capacity per 1000 femtograms of it.
std::uint64_t intake_energy_per_kilogram;
};
// Every budget a phenotype implies. Each is derived from a different phenotype
// quantity, so one genome parameter moves some and not others: none of this is a
// multiplier applied to a total.
struct MetabolicBudget {
Phenotype phenotype;
accounting::Inventory body; // matter only; a body is not energy
accounting::Picojoules maintenance; // per tick
accounting::Picojoules movement; // per tick at full speed, a capacity
accounting::Picojoules demand; // maintenance plus movement
accounting::Inventory construction; // what the next growth step would take
accounting::Inventory intake_limit; // per tick
// Zero without the reproduction capability, rather than a default.
accounting::Inventory reproduction_investment;
std::uint16_t assimilation_per_thousand{};
auto operator<=>(const MetabolicBudget&) const = default;
};
[[nodiscard]] std::expected<MetabolicRules, DevelopmentError>
metabolic_rules_for(std::uint32_t development_version);
// The single place the genome's description of capability becomes ledger
// quantities. The genome record itself stays free of accounting types.
[[nodiscard]] std::expected<MetabolicBudget, DevelopmentError>
metabolic_budget(const Genome& genome, GrowthState growth, EnvironmentState environment);
} // namespace evo::biology
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include "evo/biology/metabolism.hpp"
#include "evo/processes/feeding.hpp"
namespace evo::processes {
// The first place a genome reaches the M2 fixtures. Opening inventory stays the
// caller's: a genome describes what an organism can do, never the resources it
// happens to hold, and inventing an opening balance would create matter.
[[nodiscard]] std::expected<ConsumerConfig, biology::DevelopmentError>
consumer_for(const biology::Genome& genome, biology::GrowthState growth,
biology::EnvironmentState environment, accounting::Inventory opening);
} // namespace evo::processes
+161
View File
@@ -0,0 +1,161 @@
#include "evo/biology/metabolism.hpp"
#include <limits>
namespace evo::biology {
namespace {
constexpr std::uint64_t thousand = 1000;
// Membrane is the more carbon-rich compartment, so a thicker one changes what a
// body is made of and not only how much of it there is.
constexpr Composition structure_shares{500, 150, 50, 300};
constexpr Composition membrane_shares{700, 50, 100, 150};
constexpr std::uint32_t total_share(const Composition& shares) noexcept {
std::uint32_t sum = 0;
for (const auto share : shares) {
sum += share;
}
return sum;
}
static_assert(total_share(structure_shares) == thousand);
static_assert(total_share(membrane_shares) == thousand);
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;
}
// Declared flooring, matching ADR-0031's derivation.
std::uint64_t scaled(std::uint64_t value, std::uint64_t numerator) noexcept {
return value / thousand * numerator + value % thousand * numerator / thousand;
}
// Splits a mass across the ledger's channels. The last channel takes whatever the
// first three left, so the parts always sum back to the whole.
accounting::Inventory compose(std::uint64_t mass, const Composition& shares) noexcept {
accounting::Inventory parts{};
std::uint64_t assigned = 0;
for (std::size_t index = 0; index + 1 < shares.size(); ++index) {
const auto part = scaled(mass, shares[index]);
parts.matter[index].value = part;
assigned += part;
}
parts.matter[shares.size() - 1].value = mass - assigned;
return parts;
}
bool combine(accounting::Inventory& total, const accounting::Inventory& amount) noexcept {
if (!add(total.energy.value, total.energy.value, amount.energy.value)) {
return false;
}
for (std::size_t index = 0; index < total.matter.size(); ++index) {
if (!add(total.matter[index].value, total.matter[index].value,
amount.matter[index].value)) {
return false;
}
}
return true;
}
std::uint64_t matter_total(const accounting::Inventory& inventory) noexcept {
std::uint64_t sum = 0;
for (const auto& mass : inventory.matter) {
sum += mass.value;
}
return sum;
}
// Scales an inventory's matter while keeping its composition. The last channel
// again takes the remainder, so the parts sum to the scaled whole exactly.
accounting::Inventory fraction_of(const accounting::Inventory& source,
std::uint64_t numerator) noexcept {
accounting::Inventory parts{};
const auto whole = scaled(matter_total(source), numerator);
std::uint64_t assigned = 0;
for (std::size_t index = 0; index + 1 < source.matter.size(); ++index) {
const auto part = scaled(source.matter[index].value, numerator);
parts.matter[index].value = part;
assigned += part;
}
parts.matter[source.matter.size() - 1].value = whole - assigned;
return parts;
}
} // namespace
std::expected<MetabolicRules, DevelopmentError>
metabolic_rules_for(std::uint32_t development_version) {
if (development_version != 1) {
return std::unexpected{DevelopmentError::unsupported_rules};
}
return MetabolicRules{structure_shares, membrane_shares, 20, 50'000};
}
std::expected<MetabolicBudget, DevelopmentError>
metabolic_budget(const Genome& genome, GrowthState growth, EnvironmentState environment) {
const auto phenotype = derive_phenotype(genome, growth, environment);
if (!phenotype) {
return std::unexpected{phenotype.error()};
}
const auto rules = metabolic_rules_for(genome.development_version());
if (!rules) {
return std::unexpected{rules.error()};
}
const auto shape = rules_for(genome.development_version());
if (!shape) {
return std::unexpected{shape.error()};
}
MetabolicBudget budget;
budget.phenotype = *phenotype;
budget.assimilation_per_thousand =
static_cast<std::uint16_t>(phenotype->conversion_per_thousand);
budget.body = compose(phenotype->structural_mass, rules->structure);
if (!combine(budget.body, compose(phenotype->membrane_mass, rules->membrane))) {
return std::unexpected{DevelopmentError::overflow};
}
budget.maintenance.value = phenotype->maintenance;
// Moving a larger body costs more, so a thicker membrane is paid for twice.
std::uint64_t haulage{};
if (!multiply(haulage, scaled(phenotype->total_mass, rules->movement_per_kilogram),
phenotype->movement_speed)) {
return std::unexpected{DevelopmentError::overflow};
}
budget.movement.value = haulage / thousand;
if (!add(budget.demand.value, budget.maintenance.value, budget.movement.value)) {
return std::unexpected{DevelopmentError::overflow};
}
// Intake funds structure, so it arrives in the proportions structure needs.
budget.intake_limit = compose(phenotype->ingestion_rate, rules->structure);
budget.intake_limit.energy.value =
scaled(phenotype->ingestion_rate, rules->intake_energy_per_kilogram);
const auto plan = plan_development(genome, growth, environment);
if (!plan) {
return std::unexpected{plan.error()};
}
const auto grown = derive_phenotype(genome, plan->after, environment);
if (!grown) {
return std::unexpected{grown.error()};
}
// Each compartment is composed separately: the two differ in what they cost.
budget.construction =
compose(grown->structural_mass - phenotype->structural_mass, rules->structure);
if (!combine(budget.construction,
compose(grown->membrane_mass - phenotype->membrane_mass, rules->membrane))) {
return std::unexpected{DevelopmentError::overflow};
}
budget.construction.energy.value = plan->energy_required;
if (genome.carries(Capability::reproduction)) {
const auto fraction = *genome.parameter(Capability::reproduction);
// A parent divides the body it has, so the investment keeps its composition.
budget.reproduction_investment = fraction_of(budget.body, fraction);
// Offspring tissue is priced at what the parent's own tissue costs.
budget.reproduction_investment.energy.value =
scaled(matter_total(budget.reproduction_investment), shape->construction_per_kilogram);
}
return budget;
}
} // namespace evo::biology
+13
View File
@@ -0,0 +1,13 @@
#include "evo/processes/genome_strategy.hpp"
namespace evo::processes {
std::expected<ConsumerConfig, biology::DevelopmentError>
consumer_for(const biology::Genome& genome, biology::GrowthState growth,
biology::EnvironmentState environment, accounting::Inventory opening) {
const auto budget = biology::metabolic_budget(genome, growth, environment);
if (!budget) {
return std::unexpected{budget.error()};
}
return ConsumerConfig{opening, budget->intake_limit, budget->assimilation_per_thousand};
}
} // namespace evo::processes
+272
View File
@@ -0,0 +1,272 @@
#include "evo/processes/genome_strategy.hpp"
#include <iostream>
#include <source_location>
#include <stdexcept>
#include <string>
#include <vector>
namespace {
using namespace evo::biology;
using namespace evo::accounting;
void check(bool condition, std::source_location location = std::source_location::current()) {
if (!condition) {
throw std::runtime_error("metabolism line " + std::to_string(location.line()));
}
}
#define CHECK(expression) check(static_cast<bool>(expression))
// The ADR-0031 fixture: an exact 20 micrometre cube at full growth, so every
// budget below is hand-calculable against the declared compositions.
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;
}
GenomeDraft capable() {
auto source = draft();
source.capabilities.push_back({Capability::movement, 250, 0});
source.capabilities.push_back({Capability::ingestion, 120'000, 0});
source.capabilities.push_back({Capability::reproduction, 300, 0});
return source;
}
constexpr EnvironmentState temperate{293'150, 1'000'000'000};
std::uint64_t matter_total(const Inventory& inventory) {
std::uint64_t sum = 0;
for (const auto& mass : inventory.matter) {
sum += mass.value;
}
return sum;
}
void hand_calculated_budget() {
const auto genome = build(capable());
const auto budget = metabolic_budget(genome, {1000, 0}, temperate);
CHECK(budget);
// Structure 8e6 fg at 500/150/50/300, membrane 28.8e6 fg at 700/50/100/150.
CHECK(budget->body.matter[0].value == 24'160'000); // 4.0e6 + 20.16e6 carbon
CHECK(budget->body.matter[1].value == 2'640'000); // 1.2e6 + 1.44e6 nitrogen
CHECK(budget->body.matter[2].value == 3'280'000); // 0.4e6 + 2.88e6 phosphorus
CHECK(budget->body.matter[3].value == 6'720'000); // 2.4e6 + 4.32e6 other
CHECK(budget->body.energy.value == 0); // A body is matter, not energy.
// A split conserves the whole mass exactly, with nothing lost to rounding.
CHECK(matter_total(budget->body) == budget->phenotype.total_mass);
CHECK(budget->maintenance.value == 160'000);
CHECK(budget->movement.value == 184'000); // 36800 * 20 * 250 / 1000
CHECK(budget->demand.value == 344'000);
CHECK(budget->intake_limit.energy.value == 240'000); // 4800 fg at 50000 per 1000
CHECK(budget->intake_limit.matter[0].value == 2400); // 4800 fg by structure shares
CHECK(budget->intake_limit.matter[1].value == 720);
CHECK(budget->intake_limit.matter[2].value == 240);
CHECK(budget->intake_limit.matter[3].value == 1440);
CHECK(matter_total(budget->intake_limit) == budget->phenotype.ingestion_rate);
CHECK(budget->assimilation_per_thousand == 400);
// A parent divides the body it has, so the investment keeps its composition.
CHECK(budget->reproduction_investment.matter[0].value == 7'248'000);
CHECK(budget->reproduction_investment.matter[1].value == 792'000);
CHECK(budget->reproduction_investment.matter[2].value == 984'000);
CHECK(budget->reproduction_investment.matter[3].value == 2'016'000);
CHECK(matter_total(budget->reproduction_investment) == 11'040'000); // 30% of the body
CHECK(budget->reproduction_investment.energy.value == 441'600); // priced at 40 per 1000
// A finished organism has nothing left to build.
CHECK(matter_total(budget->construction) == 0 && budget->construction.energy.value == 0);
}
void construction_composes_each_compartment() {
const auto genome = build(capable());
const auto budget = metabolic_budget(genome, {500, 0}, temperate);
CHECK(budget);
// The step adds 400,000 fg of structure and 2,232,000 fg of membrane, each
// composed by its own shares rather than by one blended ratio.
CHECK(budget->construction.matter[0].value == 200'000 + 1'562'400);
CHECK(budget->construction.matter[1].value == 60'000 + 111'600);
CHECK(budget->construction.matter[2].value == 20'000 + 223'200);
CHECK(budget->construction.matter[3].value == 120'000 + 334'800);
CHECK(matter_total(budget->construction) == 2'632'000);
CHECK(budget->construction.energy.value == 105'280);
// What a plan reports as material is exactly what the composition sums to.
const auto plan = plan_development(genome, {500, 0}, temperate);
CHECK(plan && plan->material_required == matter_total(budget->construction));
CHECK(plan->energy_required == budget->construction.energy.value);
// Unaffordable growth leaves nothing to compose.
const EnvironmentState barren{293'150, 0};
const auto starved = metabolic_budget(genome, {500, 0}, barren);
CHECK(starved && matter_total(starved->construction) == 0);
CHECK(starved->construction.energy.value == 0);
}
void thicker_membrane_costs_matter_and_maintenance() {
auto source = capable();
const auto thin = metabolic_budget(build(source), {1000, 0}, temperate);
source.capabilities[1].parameter = 20; // membrane, twice as thick
const auto thick = metabolic_budget(build(source), {1000, 0}, temperate);
CHECK(thin && thick);
// Costs more matter to build and more energy to hold.
CHECK(matter_total(thick->body) == 65'600'000);
CHECK(matter_total(thick->body) > matter_total(thin->body));
CHECK(thick->maintenance.value == 304'000); // 65600*2 + 57600*3
CHECK(thick->maintenance.value > thin->maintenance.value);
// Membrane is the carbon-rich compartment, so composition shifts, not just mass.
CHECK(thick->body.matter[0].value == 44'320'000);
const auto thin_carbon_share = thin->body.matter[0].value * 1000 / matter_total(thin->body);
const auto thick_carbon_share = thick->body.matter[0].value * 1000 / matter_total(thick->body);
CHECK(thick_carbon_share > thin_carbon_share);
// Hauling the heavier body costs more, so a thick membrane is paid for twice.
CHECK(thick->movement.value > thin->movement.value);
// These budgets are untouched: nothing here is a multiplier over a total.
CHECK(thick->intake_limit == thin->intake_limit);
CHECK(thick->phenotype.movement_speed == thin->phenotype.movement_speed);
CHECK(thick->assimilation_per_thousand == thin->assimilation_per_thousand);
CHECK(thick->phenotype.structural_mass == thin->phenotype.structural_mass);
// Doubling one parameter moves the affected budgets by different ratios.
const auto mass_ratio = matter_total(thick->body) * 1000 / matter_total(thin->body);
const auto maintenance_ratio = thick->maintenance.value * 1000 / thin->maintenance.value;
CHECK(mass_ratio != maintenance_ratio);
}
void size_moves_several_budgets_together() {
const auto genome = build(capable());
const auto small = metabolic_budget(genome, {500, 0}, temperate);
const auto large = metabolic_budget(genome, {1000, 0}, temperate);
CHECK(small && large);
CHECK(matter_total(large->body) > matter_total(small->body));
CHECK(large->maintenance.value > small->maintenance.value);
CHECK(large->movement.value > small->movement.value);
CHECK(matter_total(large->intake_limit) > matter_total(small->intake_limit));
CHECK(matter_total(large->reproduction_investment) >
matter_total(small->reproduction_investment));
// Uptake rises with surface while maintenance rises with mass, so the two do
// not move together: size is a genuine tradeoff, not a uniform gain.
const auto uptake_ratio =
matter_total(large->intake_limit) * 1000 / matter_total(small->intake_limit);
const auto maintenance_ratio = large->maintenance.value * 1000 / small->maintenance.value;
CHECK(uptake_ratio != maintenance_ratio);
}
void absent_capabilities_cost_nothing() {
const auto bare = build(draft());
const auto budget = metabolic_budget(bare, {1000, 0}, temperate);
CHECK(budget);
CHECK(budget->movement.value == 0); // No movement capability.
CHECK(budget->demand.value == budget->maintenance.value);
CHECK(matter_total(budget->intake_limit) == 0); // No ingestion capability.
CHECK(budget->intake_limit.energy.value == 0);
CHECK(matter_total(budget->reproduction_investment) == 0); // No reproduction capability.
CHECK(budget->reproduction_investment.energy.value == 0);
// A body still costs maintenance whatever it cannot do.
CHECK(budget->maintenance.value == 160'000);
CHECK(matter_total(budget->body) == 36'800'000);
}
void rules_fail_closed() {
CHECK(metabolic_rules_for(1));
for (const auto version : {0U, 2U, 99U}) {
const auto missing = metabolic_rules_for(version);
CHECK(!missing && missing.error() == DevelopmentError::unsupported_rules);
}
auto source = draft();
source.development_version = 3;
const auto future = build(source);
const auto refused = metabolic_budget(future, {1000, 0}, temperate);
CHECK(!refused && refused.error() == DevelopmentError::unsupported_rules);
const auto genome = build(draft());
const auto invalid = metabolic_budget(genome, {1001, 0}, temperate);
CHECK(!invalid && invalid.error() == DevelopmentError::invalid_growth);
// Both compositions are declared, and both sum to the whole.
const auto rules = metabolic_rules_for(1);
std::uint32_t structure_total{}, membrane_total{};
for (std::size_t index = 0; index < 4; ++index) {
structure_total += rules->structure[index];
membrane_total += rules->membrane[index];
}
CHECK(structure_total == 1000 && membrane_total == 1000);
}
void splits_conserve_at_awkward_masses() {
// Masses chosen so every share floors, forcing the last channel to absorb it.
auto source = draft();
for (const std::uint32_t target : {1001U, 9'999U, 123'457U, 999'999'999U}) {
source.capabilities[2].parameter = target;
const auto genome = build(source);
for (const std::uint32_t realized : {1U, 333U, 999U, 1000U}) {
const auto budget = metabolic_budget(genome, {realized, 0}, temperate);
CHECK(budget);
// Whatever the rounding, the parts always sum back to the whole.
CHECK(matter_total(budget->body) == budget->phenotype.total_mass);
CHECK(matter_total(budget->intake_limit) == budget->phenotype.ingestion_rate);
}
}
}
void a_genome_drives_a_feeding_tick() {
using namespace evo::processes;
const auto genome = build(capable());
const auto opening =
Inventory{{0}, {Femtograms{0}, Femtograms{0}, Femtograms{0}, Femtograms{0}}};
const auto consumer = consumer_for(genome, {1000, 0}, temperate, opening);
CHECK(consumer);
const auto budget = metabolic_budget(genome, {1000, 0}, temperate);
CHECK(budget && consumer->intake_limit == budget->intake_limit);
CHECK(consumer->assimilation_per_thousand == 400);
CHECK(consumer->opening == opening); // The caller's, never invented.
// The derived cap drives a real community tick and the ledger still balances.
const ProducerConfig plants{
{{1'000'000}, 1},
{2, 1},
1000,
{1},
{Femtograms{4000}, Femtograms{4000}, Femtograms{4000}, Femtograms{4000}}};
const std::array configs{*consumer};
auto community = FeedingCommunity::create(
plants, {10'000'000},
{Femtograms{100'000}, Femtograms{100'000}, Femtograms{100'000}, Femtograms{100'000}},
configs);
CHECK(community);
Inventory total{};
for (const auto& balance : community->balances()) {
total.energy.value += balance.energy.value;
for (std::size_t index = 0; index < 4; ++index) {
total.matter[index].value += balance.matter[index].value;
}
}
const std::array meal{FeedIntent{
1, 2, 1, {{100}, {Femtograms{2000}, Femtograms{720}, Femtograms{240}, Femtograms{1440}}}}};
const auto receipts = community->advance(evo::Tick{1}, meal);
CHECK(receipts && receipts->size() == 1);
Inventory after{};
for (const auto& balance : community->balances()) {
after.energy.value += balance.energy.value;
for (std::size_t index = 0; index < 4; ++index) {
after.matter[index].value += balance.matter[index].value;
}
}
CHECK(after == total); // Conserved exactly, as every M2 tick must be.
// A bite past the genome's derived cap is refused by the existing contract.
const std::array excessive{FeedIntent{
1, 2, 1, {{100}, {Femtograms{2401}, Femtograms{0}, Femtograms{0}, Femtograms{0}}}}};
const auto denied = community->advance(evo::Tick{2}, excessive);
CHECK(!denied && denied.error() == FeedingError::intake_limit);
}
} // namespace
int main() try {
hand_calculated_budget();
construction_composes_each_compartment();
thicker_membrane_costs_matter_and_maintenance();
size_moves_several_budgets_together();
absent_capabilities_cost_nothing();
rules_fail_closed();
splits_conserve_at_awkward_masses();
a_genome_drives_a_feeding_tick();
std::cout << "PASS metabolic budgets, composition splits and genome-driven feeding\n";
return 0;
} catch (...) {
return 1;
}