#include "evo/biology/lineage.hpp" #include namespace evo::biology { namespace { constexpr auto by_organism = [](const auto& entry) { return entry.id; }; constexpr auto by_genome = [](const Genome& record) { return record.id(); }; template auto locate(Records& records, std::uint64_t identity, Identify identify) { return std::ranges::lower_bound(records, identity, {}, identify); } template bool holds(const Records& records, std::uint64_t identity, Identify identify) { const auto found = locate(records, identity, identify); return found != records.end() && identify(*found) == identity; } } // namespace std::expected LineageArchive::admit(const Genome& genome) { if (genomes_.size() >= max_archived_genomes) { // Refusing to record is not deleting; a silent drop would be. return std::unexpected{HistoryError::archive_full}; } const auto slot = locate(genomes_, genome.id(), by_genome); // Overwriting an existing record is deletion wearing another name. if (slot != genomes_.end() && slot->id() == genome.id()) { return std::unexpected{HistoryError::duplicate_genome}; } for (const auto parent : genome.parents()) { if (!holds(genomes_, parent, by_genome)) { return std::unexpected{HistoryError::unknown_parent}; } } genomes_.insert(slot, genome); return {}; } std::expected LineageArchive::record_birth(std::uint64_t organism, std::uint64_t genome, Tick when) { if (organism == 0) { return std::unexpected{HistoryError::invalid_identity}; } if (organisms_.size() >= max_archived_organisms) { return std::unexpected{HistoryError::archive_full}; } if (!holds(genomes_, genome, by_genome)) { return std::unexpected{HistoryError::unknown_genome}; } const auto slot = locate(organisms_, organism, by_organism); // An identity is never reused, alive or dead, so this is not a search for a // free slot: a repeat is a mistake and is reported as one. if (slot != organisms_.end() && slot->id == organism) { return std::unexpected{HistoryError::duplicate_organism}; } organisms_.insert(slot, ArchivedOrganism{organism, OrganismRecord{genome, when, {}, true}}); return {}; } std::expected LineageArchive::record_death(std::uint64_t organism, Tick when) { const auto found = locate(organisms_, organism, by_organism); if (found == organisms_.end() || found->id != organism) { return std::unexpected{HistoryError::unknown_organism}; } if (!found->record.alive) { return std::unexpected{HistoryError::already_dead}; } if (when < found->record.born) { return std::unexpected{HistoryError::invalid_tick}; } found->record.alive = false; found->record.died = when; // The organism is gone. Its genome, ancestry and origin are untouched. return {}; } std::expected LineageArchive::find(std::uint64_t genome) const { const auto found = locate(genomes_, genome, by_genome); if (found == genomes_.end() || found->id() != genome) { return std::unexpected{HistoryError::unknown_genome}; } return *found; } std::expected LineageArchive::organism(std::uint64_t identity) const { const auto found = locate(organisms_, identity, by_organism); if (found == organisms_.end() || found->id != identity) { return std::unexpected{HistoryError::unknown_organism}; } return found->record; } std::expected, HistoryError> LineageArchive::ancestry(std::uint64_t genome) const { if (!holds(genomes_, genome, by_genome)) { return std::unexpected{HistoryError::unknown_genome}; } // Admission order makes the parent graph acyclic, so this terminates. std::vector line; auto current = genome; while (true) { line.push_back(current); const auto& record = *locate(genomes_, current, by_genome); if (record.parents().empty()) { break; } current = record.parents()[0]; } std::ranges::reverse(line); // Founder first. return line; } std::expected, HistoryError> LineageArchive::children(std::uint64_t genome) const { if (!holds(genomes_, genome, by_genome)) { return std::unexpected{HistoryError::unknown_genome}; } std::vector descendants; for (const auto& record : genomes_) { if (!record.parents().empty() && record.parents()[0] == genome) { descendants.push_back(record.id()); } } return descendants; } std::expected LineageArchive::common_ancestor(std::uint64_t left, std::uint64_t right) const { const auto one = ancestry(left); if (!one) { return std::unexpected{one.error()}; } const auto other = ancestry(right); if (!other) { return std::unexpected{other.error()}; } // Both lines start at their founder, so the last shared prefix entry is the // most recent common ancestor. Zero when the founders differ. std::uint64_t shared = 0; for (std::size_t index = 0; index < one->size() && index < other->size(); ++index) { if ((*one)[index] != (*other)[index]) { break; } shared = (*one)[index]; } return shared; } std::expected LineageArchive::living_carriers(std::uint64_t genome) const { if (!holds(genomes_, genome, by_genome)) { return std::unexpected{HistoryError::unknown_genome}; } std::uint64_t carrying = 0; for (const auto& entry : organisms_) { if (entry.record.alive && entry.record.genome == genome) { ++carrying; } } return carrying; } std::vector LineageArchive::living_organisms() const { std::vector living; for (const auto& entry : organisms_) if (entry.record.alive) living.push_back(entry.id); return living; } std::uint64_t LineageArchive::highest_genome() const noexcept { return genomes_.empty() ? 0 : genomes_.back().id(); } std::uint64_t LineageArchive::highest_organism() const noexcept { return organisms_.empty() ? 0 : organisms_.back().id; } namespace { constexpr std::uint64_t archive_magic = 0x3152414C4F564541ULL; // "AEVOLAR1" constexpr std::size_t archive_header_bytes = 32; std::uint64_t fnv(std::span bytes) noexcept { std::uint64_t value = 14695981039346656037ULL; for (const auto byte : bytes) value = (value ^ byte) * 1099511628211ULL; return value; } void put(std::vector& out, std::uint64_t value, unsigned width) { for (unsigned i = 0; i < width; ++i) { out.push_back(static_cast(value & 0xFFU)); value >>= 8U; } } std::uint64_t get(std::span in, std::size_t at, unsigned width) { std::uint64_t value{}; for (unsigned i = 0; i < width; ++i) value |= static_cast(in[at + i]) << (8U * i); return value; } } // namespace std::vector LineageArchive::encode() const { // Depth from the founder, memoized; the parent graph is acyclic by admission. std::vector depth(genomes_.size(), 0); std::vector known(genomes_.size(), false); const auto index = [&](std::uint64_t id) { return static_cast(locate(genomes_, id, by_genome) - genomes_.begin()); }; for (std::size_t i = 0; i < genomes_.size(); ++i) { std::vector chain; auto at = i; while (!known[at]) { chain.push_back(at); if (genomes_[at].parents().empty()) break; at = index(genomes_[at].parents()[0]); } std::uint32_t d = known[at] ? depth[at] + 1 : 0; for (auto it = chain.rbegin(); it != chain.rend(); ++it) { if (known[*it]) continue; depth[*it] = genomes_[*it].parents().empty() ? 0 : d; known[*it] = true; d = depth[*it] + 1; } } std::vector order(genomes_.size()); for (std::size_t i = 0; i < order.size(); ++i) order[i] = i; // Genomes are id-sorted already, so a stable sort by depth yields (depth, id). std::ranges::stable_sort(order, {}, [&](std::size_t i) { return depth[i]; }); std::vector out; out.reserve(archive_header_bytes + (genomes_.size() * (2 + max_genome_bytes)) + (organisms_.size() * archived_organism_bytes) + 8); put(out, archive_magic, 8); put(out, lineage_archive_format, 4); put(out, genome_schema_version, 4); put(out, genomes_.size(), 4); put(out, organisms_.size(), 4); put(out, 0, 8); // Total length, patched below. for (const auto i : order) { const auto record = genomes_[i].encode(); put(out, record.size(), 2); out.insert(out.end(), record.begin(), record.end()); } for (const auto& entry : organisms_) { put(out, entry.id, 8); put(out, entry.record.genome, 8); put(out, entry.record.born.value, 8); put(out, entry.record.alive ? 0 : entry.record.died.value, 8); put(out, entry.record.alive ? 1 : 0, 1); } const auto total = out.size() + 8; for (unsigned b = 0; b < 8; ++b) out[24 + b] = static_cast((total >> (8U * b)) & 0xFFU); put(out, fnv(out), 8); return out; } std::expected LineageArchive::decode(std::span bytes) { if (bytes.size() < archive_header_bytes + 8 || get(bytes, 0, 8) != archive_magic) return std::unexpected{ArchiveCodecError::format}; if (get(bytes, 8, 4) != lineage_archive_format || get(bytes, 12, 4) != genome_schema_version) return std::unexpected{ArchiveCodecError::version}; const auto genomes = get(bytes, 16, 4); const auto organisms = get(bytes, 20, 4); if (bytes.size() > max_archive_bytes || genomes > max_archived_genomes || organisms > max_archived_organisms) return std::unexpected{ArchiveCodecError::bounds}; if (get(bytes, 24, 8) != bytes.size()) return std::unexpected{ArchiveCodecError::format}; const auto body = bytes.first(bytes.size() - 8); if (get(bytes, bytes.size() - 8, 8) != fnv(body)) return std::unexpected{ArchiveCodecError::checksum}; LineageArchive archive; std::size_t at = archive_header_bytes; for (std::uint64_t g = 0; g < genomes; ++g) { if (at + 2 > body.size()) return std::unexpected{ArchiveCodecError::format}; const auto length = static_cast(get(body, at, 2)); at += 2; if (length == 0 || length > max_genome_bytes || at + length > body.size()) return std::unexpected{ArchiveCodecError::format}; const auto genome = Genome::decode(body.subspan(at, length)); if (!genome) return std::unexpected{ArchiveCodecError::genome}; if (!archive.admit(*genome)) return std::unexpected{ArchiveCodecError::history}; at += length; } if (body.size() - at != organisms * archived_organism_bytes) return std::unexpected{ArchiveCodecError::format}; for (std::uint64_t o = 0; o < organisms; ++o, at += archived_organism_bytes) { const auto id = get(body, at, 8); const Tick born{get(body, at + 16, 8)}; const Tick died{get(body, at + 24, 8)}; const auto alive = get(body, at + 32, 1); if (alive > 1 || (alive == 1 && died.value != 0)) return std::unexpected{ArchiveCodecError::format}; if (!archive.record_birth(id, get(body, at + 8, 8), born) || (alive == 0 && !archive.record_death(id, died))) return std::unexpected{ArchiveCodecError::history}; } if (!std::ranges::equal(archive.encode(), bytes)) return std::unexpected{ArchiveCodecError::noncanonical}; return archive; } std::expected LineageArchive::status(std::uint64_t genome) const { const auto carrying = living_carriers(genome); if (!carrying) { return std::unexpected{carrying.error()}; } // Absent, never extinct: this type cannot see the world watermark that a // claim of terminal extinction would require. return *carrying == 0 ? LineageStatus::absent : LineageStatus::living; } } // namespace evo::biology