diff --git a/CHANGELOG.md b/CHANGELOG.md index e3b3ed0..bb4ce00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ Versions follow [semantic versioning](https://semver.org). While the version is 0.x the project is in early development: anything may change from one version to the next, configurations and results included. Each version says what changed in what a run does, so that a result can be tied to the version that produced it. +## Unreleased + +- **A fuller cell.** `examples/networks/fuller-cell.toml` fills in what the RAS/ERK network and the stress response leave out: EGFR, RAF and MEK before ERK; cyclin D, RB, E2F, cyclin E and the brake p27 between hypoxia and the arrest; MDM2, p21 and BAX around p53. Its rates are set so that a cell asks for the same size, stops dividing at the same oxygen, dies of anoxia at the same oxygen and of a stress at the same rate as in the simpler networks, which tests hold (chapter 28). `spheroid-fuller.toml` and `cord-stress-fuller.toml` run it. Under a stress the cord dies out where the simpler one holds, through p21. No other run changes. +- **A term that switches off.** `inhibited_by` joins the catalogue of terms, the mirror of `activated_by`: `- rate * source * self`. No run changes. +- **One cell opened.** In the viewer, a click on a cell opens a window that draws its network as it stands, what it reads, and what it decides; `--open`, `--open-at`, `--follow`, `--protein` and `--window` do the same from the command line, for recordings. The camera turns only while the window has the pointer and the focus. +- **Networks by name.** `cellweave_io::shipped_network` reads a network shipped under `examples/networks`, such as `fuller-cell`, with everything it extends, from copies compiled into the program, so that a program built on cellweave carries it without the repository beside it. No run changes. +- **The course.** Chapter 28 is the fuller cell and the window; what the model does not say is now chapter 29. + ## 0.2.0 (2026-11-01) A tissue that grows in a volume, and a spheroid in it that stops near the size measured spheroids reach, once its dead core breaks down and the medium of its well is still. Experimental. diff --git a/README.md b/README.md index eafe1fb..e3f128a 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,12 @@ cargo run --release -- --config ../examples/epithelium-mutating.toml --view clon Space pauses, N takes one step, R restarts, H flattens the relief, A turns the camera, the mouse turns and zooms it. The panel colours the cells by fate, protein, oxygen, stress, the call for vessels, clone or blood flow, and plots the population as it goes. +A click on a cell opens it. A window draws the cell's network as it stands, every protein at its level and every link as thick as it is pushing, says in words what the cell does with them and why, and colours the tissue by any protein clicked. `spheroid-fuller.toml` is the calibrated spheroid with a fuller cell: eighteen proteins, from the growth factor's receptor through RAF and MEK to the cell cycle, and from damage through p53, MDM2, p21 and BAX to apoptosis, tuned to decide where the simpler network does ([chapter 28](docs/28-inside-one-cell.md)). This opens the cell at its centre at step 300 and follows it as it is arrested and starved: + +```bash +cargo run --release -- --config ../examples/spheroid-fuller.toml --open 400,400 --open-at 300 --follow --zoom 3 +``` + `--record ` saves every step as an image, taken from what the viewer draws rather than from the screen, and `--until ` stops there; with `--no-panel`, `--spin` and `--batch `, that is how the animations above were made: ```bash @@ -92,11 +98,11 @@ ffmpeg -framerate 30 -pattern_type glob -i 'frames/*.png' run.mp4 ## Learn how it works -[The course](docs/README.md) explains the program from the biology up, in 28 chapters, each answering one question: what a thing is in the body, what cellweave makes of it, which choices were made and why, where in the code it lives, and what is still a placeholder. It is kept in step with the code, and its last chapter lists what the model does not say. +[The course](docs/README.md) explains the program from the biology up, in 29 chapters, each answering one question: what a thing is in the body, what cellweave makes of it, which choices were made and why, where in the code it lives, and what is still a placeholder. It is kept in step with the code, and its last chapter lists what the model does not say. ## Under the hood -Rust, in four crates whose dependency graph enforces the layering: `cellweave-core` (types, no I/O, no computation), `cellweave-engine` (the lattice, the networks, the fields, the loop), `cellweave-io` (configuration and output) and the command line; the viewer sits on top in a workspace of its own. The same seed gives the same run, byte for byte, on any machine and any number of threads, and the CI checks it on every push, with fmt, clippy, docs, 209 tests green on Linux, macOS and Windows, the oldest supported Rust, and `cargo-deny`. +Rust, in four crates whose dependency graph enforces the layering: `cellweave-core` (types, no I/O, no computation), `cellweave-engine` (the lattice, the networks, the fields, the loop), `cellweave-io` (configuration and output) and the command line; the viewer sits on top in a workspace of its own. The same seed gives the same run, byte for byte, on any machine and any number of threads, and the CI checks it on every push, with fmt, clippy, docs, 223 tests green on Linux, macOS and Windows, the oldest supported Rust, and `cargo-deny`. ```bash cargo fmt --all -- --check diff --git a/crates/core/src/network.rs b/crates/core/src/network.rs index d316cb6..834f84a 100644 --- a/crates/core/src/network.rs +++ b/crates/core/src/network.rs @@ -61,6 +61,20 @@ pub enum Term { #[serde(default)] hill: Option, }, + /// `- rate * source * self`, Hill in place of `source` when `hill` is set. + /// The source switches this node off, in proportion to how much there is + /// of each: MDM2 marking p53 for destruction, a cyclin-dependent kinase + /// phosphorylating RB. The mirror of `ActivatedBy`, and like it the usual + /// shape of one protein acting on another, here to undo it. + InhibitedBy { + /// Node or input that switches it off. + source: String, + /// How fast, per unit time. + rate: f64, + /// Cooperative response instead of a proportional one. + #[serde(default)] + hill: Option, + }, /// `rate * (1 - source) * (1 - self)`. The node accumulates when the source /// is scarce: HIF-1α as oxygen falls, whose destruction slows rather than /// whose production rises. @@ -125,6 +139,7 @@ impl Term { pub fn source(&self) -> Option<&str> { match self { Self::ActivatedBy { source, .. } + | Self::InhibitedBy { source, .. } | Self::ActivatedByAbsenceOf { source, .. } | Self::ProducedBy { source, .. } | Self::DamagedBelow { source, .. } diff --git a/crates/engine/src/coupling.rs b/crates/engine/src/coupling.rs index 6a9c4de..d078543 100644 --- a/crates/engine/src/coupling.rs +++ b/crates/engine/src/coupling.rs @@ -8,7 +8,7 @@ use crate::cpm::{CpmLattice, OBSTACLE}; use crate::pde::ScalarField; -use cellweave_core::{CellKind, DiffusionField}; +use cellweave_core::{CellId, CellKind, DiffusionField}; /// Whether a cell of this kind draws on the field at all. A dead cell does /// not, and neither does one breaking up in apoptosis. @@ -181,6 +181,25 @@ pub fn mean_per_cell(field: &ScalarField, lattice: &CpmLattice) -> Vec { .collect() } +/// The mean of `field` over the pixels of one cell, or zero for a cell that +/// holds none: [`mean_per_cell`] for a single cell, as a picture of one cell +/// asks for it. +pub fn mean_in(field: &ScalarField, lattice: &CpmLattice, id: CellId) -> f64 { + let (sum, count) = lattice + .grid + .iter() + .enumerate() + .filter(|&(_, &occupant)| occupant == id.0) + .fold((0.0, 0u32), |(sum, count), (i, _)| { + (sum + field.value_at(i), count + 1) + }); + if count == 0 { + 0.0 + } else { + sum / f64::from(count) + } +} + #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index d1d3ba7..ed7f394 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -20,7 +20,7 @@ pub mod vessels; pub use cpm::CpmLattice; pub use evolution::CloneRecord; pub use measure::{DEPTH_SHARE, Measurements}; -pub use network::{Mutation, Network}; +pub use network::{Influence, Mutation, Network}; pub use pde::ScalarField; pub use simulation::{Fate, Scenario, Simulation}; pub use sisters::SisterFates; diff --git a/crates/engine/src/network.rs b/crates/engine/src/network.rs index fe823d2..bdf1b04 100644 --- a/crates/engine/src/network.rs +++ b/crates/engine/src/network.rs @@ -7,7 +7,7 @@ use std::sync::Arc; -use cellweave_core::network::{INPUT_NAMES, Term}; +use cellweave_core::network::{Hill, INPUT_NAMES, Term}; use cellweave_core::{ CellInputs, CellMechanics, CellweaveError, Concentration, MechanicsSpec, NetworkSpec, ProteinState, SignalingNetwork, TimeStep, Volume, @@ -39,6 +39,30 @@ fn input_source(name: &str) -> Option { } } +/// A Hill response as the loop needs it, refused unless both its exponent +/// and its half-maximal level are positive. +fn hill_of(hill: Option<&Hill>, node: &str) -> Result, CellweaveError> { + match hill { + Some(h) if h.n <= 0.0 || h.k <= 0.0 => Err(CellweaveError::Config(format!( + "node `{node}` has a Hill term with n = {} and k = {}; both must be positive", + h.n, h.k + ))), + Some(h) => Ok(Some((h.n, h.k))), + None => Ok(None), + } +} + +/// What a term reading `s` responds to: `s` itself, or its Hill response. +fn driver(s: f64, hill: Option<(f64, f64)>) -> f64 { + match hill { + None => s, + Some((n, half)) => { + let sn = s.max(0.0).powf(n); + sn / (half.powf(n) + sn) + } + } +} + /// A term with its source resolved and its shape reduced to what the loop needs. #[derive(Debug, Clone, Copy)] enum Compiled { @@ -48,6 +72,12 @@ enum Compiled { rate: f64, hill: Option<(f64, f64)>, }, + /// `- rate * f(source) * self`, `f` being Hill when `hill` is set. + InhibitedBy { + source: Source, + rate: f64, + hill: Option<(f64, f64)>, + }, /// `rate * (1 - source) * (1 - self)`. ActivatedByAbsenceOf { source: Source, rate: f64 }, /// `rate * source`. @@ -75,6 +105,7 @@ impl Compiled { fn rate_mut(&mut self) -> &mut f64 { match self { Compiled::ActivatedBy { rate, .. } + | Compiled::InhibitedBy { rate, .. } | Compiled::ActivatedByAbsenceOf { rate, .. } | Compiled::ProducedBy { rate, .. } | Compiled::Decays { rate } @@ -84,10 +115,30 @@ impl Compiled { } } + /// The rate this term moves its node at. + fn rate(self) -> f64 { + let mut term = self; + *term.rate_mut() + } + + /// The source this term reads, if it reads one. + fn source(&self) -> Option { + match *self { + Compiled::ActivatedBy { source, .. } + | Compiled::InhibitedBy { source, .. } + | Compiled::ActivatedByAbsenceOf { source, .. } + | Compiled::ProducedBy { source, .. } + | Compiled::DamagedBelow { source, .. } + | Compiled::DamagedAbove { source, .. } => Some(source), + Compiled::Decays { .. } | Compiled::RelaxesTo { .. } => None, + } + } + /// The kind of term, as a network file names it. fn kind(&self) -> &'static str { match self { Compiled::ActivatedBy { .. } => "activated_by", + Compiled::InhibitedBy { .. } => "inhibited_by", Compiled::ActivatedByAbsenceOf { .. } => "activated_by_absence_of", Compiled::ProducedBy { .. } => "produced_by", Compiled::Decays { .. } => "decays", @@ -170,6 +221,24 @@ impl std::fmt::Display for Mutation { } } +/// One term of one node as it stands: an arrow in a picture of the network, +/// and how hard it is pushing. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Influence<'a> { + /// The node the term moves, by its index in [`Network::node_names`]. + pub node: usize, + /// The kind of term, as a network file names it. + pub kind: &'static str, + /// The node or input it reads, by the name a file gives it; `None` for a + /// term that reads nothing, turnover or a set point. + pub source: Option<&'a str>, + /// Its rate, as the file gave it or as mutations left it. + pub rate: f64, + /// What it adds to the node's rate of change now: positive when it + /// raises the node, negative when it lowers it. + pub now: f64, +} + /// A protein network, ready to run. /// /// Cheap to clone, which is what a dividing cell does: a daughter is a copy of @@ -265,29 +334,20 @@ impl Network { let mut compiled = Vec::with_capacity(node.terms.len()); for term in &node.terms { compiled.push(match term { - Term::ActivatedBy { source, rate, hill } => { - let hill = match hill { - Some(h) if h.n <= 0.0 || h.k <= 0.0 => { - return Err(CellweaveError::Config(format!( - "node `{}` has a Hill term with n = {} and k = {}; both must be positive", - node.name, h.n, h.k - ))); - } - Some(h) => Some((h.n, h.k)), - None => None, - }; - Compiled::ActivatedBy { - source: resolve(source, &node.name)?, - rate: *rate, - hill, - } - } - Term::ActivatedByAbsenceOf { source, rate } => { - Compiled::ActivatedByAbsenceOf { - source: resolve(source, &node.name)?, - rate: *rate, - } - } + Term::ActivatedBy { source, rate, hill } => Compiled::ActivatedBy { + source: resolve(source, &node.name)?, + rate: *rate, + hill: hill_of(hill.as_ref(), &node.name)?, + }, + Term::InhibitedBy { source, rate, hill } => Compiled::InhibitedBy { + source: resolve(source, &node.name)?, + rate: *rate, + hill: hill_of(hill.as_ref(), &node.name)?, + }, + Term::ActivatedByAbsenceOf { source, rate } => Compiled::ActivatedByAbsenceOf { + source: resolve(source, &node.name)?, + rate: *rate, + }, Term::ProducedBy { source, rate } => Compiled::ProducedBy { source: resolve(source, &node.name)?, rate: *rate, @@ -628,52 +688,87 @@ impl Network { let own = state[i]; let mut rate = 0.0; for term in node_terms { - rate += match *term { - Compiled::ActivatedBy { - source, - rate: k, - hill, - } => { - let s = Self::read(state, inputs, source); - let driver = match hill { - None => s, - Some((n, half)) => { - let sn = s.max(0.0).powf(n); - sn / (half.powf(n) + sn) - } - }; - k * driver * (1.0 - own) - } - Compiled::ActivatedByAbsenceOf { source, rate: k } => { - k * (1.0 - Self::read(state, inputs, source)) * (1.0 - own) - } - Compiled::ProducedBy { source, rate: k } => { - k * Self::read(state, inputs, source) - } - Compiled::Decays { rate: k } => -k * own, - Compiled::RelaxesTo { value, rate: k } => -k * (own - value), - Compiled::DamagedBelow { - source, - threshold, - rate: k, - } => { - let s = Self::read(state, inputs, source); - -k * ((threshold - s) / threshold).max(0.0) - } - Compiled::DamagedAbove { - source, - threshold, - rate: k, - } => { - let s = Self::read(state, inputs, source); - -k * ((s - threshold) / threshold).max(0.0) - } - }; + rate += Self::term_rate(*term, own, state, inputs); } out[i] = rate; } } + /// What one term adds to the rate of change of its node, `own` being the + /// node's value. + fn term_rate(term: Compiled, own: f64, state: &[f64], inputs: &CellInputs) -> f64 { + match term { + Compiled::ActivatedBy { + source, + rate: k, + hill, + } => k * driver(Self::read(state, inputs, source), hill) * (1.0 - own), + Compiled::InhibitedBy { + source, + rate: k, + hill, + } => -k * driver(Self::read(state, inputs, source), hill) * own, + Compiled::ActivatedByAbsenceOf { source, rate: k } => { + k * (1.0 - Self::read(state, inputs, source)) * (1.0 - own) + } + Compiled::ProducedBy { source, rate: k } => k * Self::read(state, inputs, source), + Compiled::Decays { rate: k } => -k * own, + Compiled::RelaxesTo { value, rate: k } => -k * (own - value), + Compiled::DamagedBelow { + source, + threshold, + rate: k, + } => { + let s = Self::read(state, inputs, source); + -k * ((threshold - s) / threshold).max(0.0) + } + Compiled::DamagedAbove { + source, + threshold, + rate: k, + } => { + let s = Self::read(state, inputs, source); + -k * ((s - threshold) / threshold).max(0.0) + } + } + } + + /// Every term of every node as it stands, under `inputs`: what a picture + /// of the network draws as its arrows, and how hard each is pushing. + /// + /// The terms are this network's own, as mutations left them, so a cell + /// that lost a link or gained one shows it. + pub fn influences(&self, inputs: &CellInputs) -> Vec> { + let state: Vec = self.state.values.iter().map(|c| c.0).collect(); + self.terms + .iter() + .enumerate() + .flat_map(|(node, terms)| { + let state = &state; + terms.iter().map(move |term| Influence { + node, + kind: term.kind(), + source: term.source().map(|s| self.source_name(s)), + rate: term.rate(), + now: Self::term_rate(*term, state[node], state, inputs), + }) + }) + .collect() + } + + /// The name a file gives a source. + fn source_name(&self, source: Source) -> &str { + match source { + Source::Oxygen => "oxygen", + Source::Egf => "egf", + Source::Crowding => "crowding", + Source::Stress => "stress", + Source::Waste => "waste", + Source::NecroticFactor => "necrotic_factor", + Source::Node(i) => &self.names[i], + } + } + /// Classic RK4 over `dt`. /// /// Four evaluations, the middle two at the half step, blended one, two, two, @@ -973,7 +1068,7 @@ mod tests { // second order error of the scheme is about the curvature times half the // step, and the curvature here is of order one. let dt = 1e-6; - let cases: [(&str, Term, f64, f64, f64); 7] = [ + let cases: [(&str, Term, f64, f64, f64); 8] = [ // rate * source * (1 - self), with source 0.5 and self 0.25 ( "activated_by", @@ -986,6 +1081,18 @@ mod tests { 0.5, 2.0 * 0.5 * 0.75, ), + // - rate * source * self, with source 0.5 and self 0.6 + ( + "inhibited_by", + Term::InhibitedBy { + source: "egf".into(), + rate: 2.0, + hill: None, + }, + 0.6, + 0.5, + -2.0 * 0.5 * 0.6, + ), // rate * (1 - source) * (1 - self) ( "activated_by_absence_of", @@ -1068,6 +1175,96 @@ mod tests { } } + #[test] + fn an_inhibition_switches_sharply_with_a_hill_response_and_never_below_zero() { + // Half way at a source of 0.4, steeply: well below it the node is + // barely touched, well above it switched off at nearly the full rate. + let hill = Some(Hill { n: 4.0, k: 0.4 }); + let slope = |egf: f64| { + let dt = 1e-6; + let mut spec = one_node(vec![Term::InhibitedBy { + source: "egf".into(), + rate: 1.0, + hill, + }]); + spec.nodes[0].initial = 0.5; + let mut net = Network::from_spec(&spec, 100).unwrap(); + net.step(TimeStep(dt), &at(0.0, egf)); + (net.state().values[0].0 - 0.5) / dt + }; + assert!(slope(0.1).abs() < 0.01, "below k: {}", slope(0.1)); + assert!( + (slope(0.4) + 0.25).abs() < 1e-5, + "at k, half: {}", + slope(0.4) + ); + assert!(slope(1.6) < -0.49, "above k: {}", slope(1.6)); + + // Proportional to the node itself, so it empties the node without + // ever taking it past zero. + let mut spec = one_node(vec![Term::InhibitedBy { + source: "egf".into(), + rate: 2.0, + hill: None, + }]); + spec.nodes[0].initial = 0.5; + let mut net = Network::from_spec(&spec, 100).unwrap(); + for _ in 0..50 { + net.step(TimeStep(1.0), &at(0.0, 1.0)); + let level = net.state().values[0].0; + assert!(level >= 0.0, "below zero: {level}"); + } + assert!(net.state().values[0].0 < 1e-12, "switched off"); + } + + #[test] + fn a_picture_of_the_network_reads_every_term_as_it_pushes_now() { + let net = ras_erk(); + let inputs = at(0.2, 0.2); + let influences = net.influences(&inputs); + let terms: usize = RAS_ERK.matches("kind =").count(); + assert_eq!(influences.len(), terms, "one per term of the file"); + + // ERK, switched on by RAS: 0.8 * ras * (1 - erk), at the start. + let erk = net.node_names().iter().position(|n| n == "erk").unwrap(); + let from_ras = influences + .iter() + .find(|i| i.node == erk && i.source == Some("ras")) + .unwrap(); + assert_eq!(from_ras.kind, "activated_by"); + assert_eq!(from_ras.rate, 0.8); + assert!((from_ras.now - 0.8 * 0.05 * 0.95).abs() < 1e-12); + + // HIF-1a reads an input by its name, and its turnover reads nothing. + let hif = net.node_names().iter().position(|n| n == "hif1").unwrap(); + assert!( + influences + .iter() + .any(|i| i.node == hif && i.source == Some("oxygen")) + ); + assert!( + influences + .iter() + .any(|i| i.node == hif && i.kind == "decays" && i.source.is_none() && i.now < 0.0) + ); + + // The terms, summed, are the network's rate of change. + let mut slopes = vec![0.0; net.node_names().len()]; + let state: Vec = net.state().values.iter().map(|c| c.0).collect(); + Network::derivatives(&net.terms, &state, &inputs, &mut slopes); + for (node, slope) in slopes.iter().enumerate() { + let sum: f64 = influences + .iter() + .filter(|i| i.node == node) + .map(|i| i.now) + .sum(); + assert!( + (sum - slope).abs() < 1e-12, + "node {node}: {sum} against {slope}" + ); + } + } + #[test] fn a_node_reads_the_waste_around_its_cell() { let dt = 1e-6; diff --git a/crates/engine/src/simulation.rs b/crates/engine/src/simulation.rs index 8989bf4..2f5ea43 100644 --- a/crates/engine/src/simulation.rs +++ b/crates/engine/src/simulation.rs @@ -23,7 +23,7 @@ use rand::{RngExt, SeedableRng}; use crate::coupling::{ apply_background_uptake, apply_production, apply_uptake, hold_medium_bath, hold_vessels_at, - hold_vessels_by, mean_per_cell, + hold_vessels_by, mean_in, mean_per_cell, }; use crate::cpm::{CpmLattice, OBSTACLE}; use crate::evolution::CloneRecord; @@ -39,8 +39,10 @@ use crate::vessels::{Capillary, Tip, Vessels}; /// attributed to what was changed. pub const DEFAULT_SEED: u64 = 42; -/// A cell divides once it reaches this multiple of its lineage's reference volume. -const DIVISION_RATIO: f64 = 1.4; +/// A cell divides once it reaches this multiple of its lineage's reference +/// volume. Public, as the two thresholds below, so that a picture of a cell +/// can say how far it is from each. +pub const DIVISION_RATIO: f64 = 1.4; /// Monte Carlo steps between two checks for cells ready to divide, in a tissue /// grown from one cell. @@ -109,10 +111,14 @@ const OXYGEN_WARMUP_MAX_STEPS: usize = 2_000_000; const NETWORK_TIME_PER_MCS: u32 = 8; /// Survival signal below which a cell is necrotic. -const DEATH_THRESHOLD: f64 = 0.25; +pub const DEATH_THRESHOLD: f64 = 0.25; /// Hypoxia response above which a cell stops dividing while staying alive. -const QUIESCENCE_THRESHOLD: f64 = 0.45; +pub const QUIESCENCE_THRESHOLD: f64 = 0.45; + +/// The growth factor every cell reads, wherever it sits: no field carries +/// it, so it is the same for all of them. +const EGF: f64 = 0.2; /// Pixels a necrotic cell gives up per lattice step until nothing is left. /// @@ -1178,15 +1184,13 @@ impl Simulation { ) { continue; } - let inputs = CellInputs { - o2: Concentration(local_o2[i + 1]), - egf: Concentration(0.2), - vegf: Concentration(0.0), - crowding: Concentration(crowding(&self.lattice, id, net)), - stress: Concentration(local_stress.as_ref().map_or(0.0, |s| s[i + 1])), - waste: Concentration(local_waste.as_ref().map_or(0.0, |w| w[i + 1])), - necrotic_factor: Concentration(local_factor.as_ref().map_or(0.0, |f| f[i + 1])), - }; + let inputs = cell_inputs( + local_o2[i + 1], + crowding(&self.lattice, id, net), + local_stress.as_ref().map_or(0.0, |s| s[i + 1]), + local_waste.as_ref().map_or(0.0, |w| w[i + 1]), + local_factor.as_ref().map_or(0.0, |f| f[i + 1]), + ); for _ in 0..NETWORK_TIME_PER_MCS { net.step(TimeStep(1.0), &inputs); } @@ -2281,6 +2285,27 @@ impl Simulation { self.networks.get(slot)?.as_ref() } + /// What cell `id` reads from where it sits: the oxygen, the stress, the + /// waste and the necrotic factor averaged over the pixels it holds now, + /// in the fields as the last step left them, how squeezed it is, and the + /// growth factor. `None` for the medium, an obstacle, or a cell that is + /// gone. + /// + /// What its network last read, give or take the pixels it has gained or + /// lost since. + pub fn inputs(&self, id: CellId) -> Option { + let net = self.network(id)?; + let mean = + |field: Option<&ScalarField>| field.map_or(0.0, |f| mean_in(f, &self.lattice, id)); + Some(cell_inputs( + mean(Some(&self.oxygen)), + crowding(&self.lattice, id, net), + mean(self.stress.as_ref()), + mean(self.waste.as_ref()), + mean(self.necrotic_factor.as_ref()), + )) + } + /// The clone a cell belongs to, or `None` for the medium or an obstacle. A /// cell that is gone keeps the clone it had. pub fn clone_of(&self, id: CellId) -> Option { @@ -2481,6 +2506,20 @@ fn vegf_decay(angiogenesis: &Angiogenesis) -> f64 { /// What a cell can sense of its neighbours' pressure is its own spread: a cell /// pressed small by the tissue around it has less room than it was born to, /// and that is the signal contact inhibition in an epithelium runs on. +/// What a network reads, from the local levels of the fields and how +/// squeezed its cell is. +fn cell_inputs(o2: f64, crowding: f64, stress: f64, waste: f64, factor: f64) -> CellInputs { + CellInputs { + o2: Concentration(o2), + egf: Concentration(EGF), + vegf: Concentration(0.0), + crowding: Concentration(crowding), + stress: Concentration(stress), + waste: Concentration(waste), + necrotic_factor: Concentration(factor), + } +} + fn crowding(lattice: &CpmLattice, id: CellId, net: &Network) -> f64 { let volume = lattice.volume(id).map_or(0, |v| v.0); let reference = f64::from(net.reference_volume().max(1)); diff --git a/crates/io/src/config.rs b/crates/io/src/config.rs index 069b239..ca4bda9 100644 --- a/crates/io/src/config.rs +++ b/crates/io/src/config.rs @@ -181,6 +181,112 @@ fn default_contact_order() -> u8 { /// write go through exactly the same path. pub const BUILT_IN_NETWORK: &str = include_str!("../../../examples/networks/ras-erk.toml"); +/// The networks shipped under `examples/networks`, compiled in by file name, +/// so that a program built on cellweave carries them without the repository +/// beside it. +const SHIPPED_NETWORKS: [(&str, &str); 13] = [ + ( + "epithelium-no-pressing.toml", + include_str!("../../../examples/networks/epithelium-no-pressing.toml"), + ), + ( + "epithelium.toml", + include_str!("../../../examples/networks/epithelium.toml"), + ), + ( + "fuller-cell.toml", + include_str!("../../../examples/networks/fuller-cell.toml"), + ), + ( + "lesion-strong.toml", + include_str!("../../../examples/networks/lesion-strong.toml"), + ), + ( + "lesion.toml", + include_str!("../../../examples/networks/lesion.toml"), + ), + ( + "ras-erk-mutant.toml", + include_str!("../../../examples/networks/ras-erk-mutant.toml"), + ), + ( + "ras-erk-necrotic.toml", + include_str!("../../../examples/networks/ras-erk-necrotic.toml"), + ), + ( + "ras-erk-pdl1.toml", + include_str!("../../../examples/networks/ras-erk-pdl1.toml"), + ), + ( + "ras-erk-silent.toml", + include_str!("../../../examples/networks/ras-erk-silent.toml"), + ), + ( + "ras-erk-soft.toml", + include_str!("../../../examples/networks/ras-erk-soft.toml"), + ), + ( + "ras-erk-waste.toml", + include_str!("../../../examples/networks/ras-erk-waste.toml"), + ), + ( + "ras-erk.toml", + include_str!("../../../examples/networks/ras-erk.toml"), + ), + ( + "stress-response.toml", + include_str!("../../../examples/networks/stress-response.toml"), + ), +]; + +/// A network shipped with cellweave, named by its file under +/// `examples/networks` without the extension, such as `fuller-cell`, read +/// with everything it extends from the copies compiled into the program. +/// +/// # Errors +/// +/// [`CellweaveError::Config`] when cellweave ships no network of that name, +/// or when one in its chain does not parse or extends itself round a loop. +/// +/// # Examples +/// +/// ``` +/// # fn main() -> Result<(), cellweave_core::CellweaveError> { +/// let fuller = cellweave_io::shipped_network("fuller-cell")?; +/// assert!(fuller.nodes.iter().any(|n| n.name == "rb")); +/// # Ok(()) +/// # } +/// ``` +pub fn shipped_network(name: &str) -> Result { + shipped_chain(&format!("{name}.toml"), &mut Vec::new()) +} + +/// A shipped network and everything it extends, youngest laid over oldest, +/// as [`load_network_chain`] reads files. +fn shipped_chain(file: &str, seen: &mut Vec) -> Result { + let looped = seen.iter().any(|f| f == file); + seen.push(file.to_owned()); + if looped { + return Err(CellweaveError::Config(format!( + "a network extends itself round a loop: {}", + seen.join(" -> ") + ))); + } + let text = SHIPPED_NETWORKS + .iter() + .find(|(f, _)| *f == file) + .map(|(_, text)| *text) + .ok_or_else(|| CellweaveError::Config(format!("cellweave ships no network {file}")))?; + let spec = parse_network(text, file)?; + match &spec.extends { + None => Ok(spec), + Some(parent) => { + let base = shipped_chain(parent, seen)?; + Ok(spec.merge_onto(base)) + } + } +} + /// The uptake fixed on measured melanoma spheroids (chapter 25). fn default_oxygen_uptake() -> f64 { 0.00002 @@ -381,6 +487,38 @@ impl Default for SimConfig { mod tests { use super::*; + fn networks_dir() -> std::path::PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples/networks") + } + + #[test] + fn every_network_in_the_examples_is_shipped() { + let mut on_disk: Vec = std::fs::read_dir(networks_dir()) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .filter(|f| f.ends_with(".toml")) + .collect(); + on_disk.sort(); + let shipped: Vec<&str> = SHIPPED_NETWORKS.iter().map(|(f, _)| *f).collect(); + assert_eq!(on_disk, shipped); + } + + #[test] + fn a_shipped_network_is_the_one_read_from_its_file() { + for (file, _) in SHIPPED_NETWORKS { + let name = file.trim_end_matches(".toml"); + let from_file = + load_network_chain(&networks_dir().join(file), &mut Vec::new()).unwrap(); + assert_eq!(shipped_network(name).unwrap(), from_file, "{name}"); + } + } + + #[test] + fn a_network_cellweave_does_not_ship_is_named_in_the_error() { + let e = shipped_network("no-such-cell").unwrap_err().to_string(); + assert!(e.contains("no-such-cell"), "{e}"); + } + #[test] fn a_calibrated_step_converts_to_days_and_an_uncalibrated_one_does_not() { let mut cfg = SimConfig::default(); diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index c4c2163..9f28947 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -6,5 +6,5 @@ pub mod config; pub mod output; pub use cellweave_core::{Exposure, OxygenSource, Schedule, Seeding}; -pub use config::{LesionConfig, SimConfig}; +pub use config::{LesionConfig, SimConfig, shipped_network}; pub use output::{JsonOutput, MeasurementLog, TraceLog, write_clones}; diff --git a/crates/io/tests/fuller_cell.rs b/crates/io/tests/fuller_cell.rs new file mode 100644 index 0000000..5b414b9 --- /dev/null +++ b/crates/io/tests/fuller_cell.rs @@ -0,0 +1,219 @@ +//! The fuller cell of chapter 28 against the networks it fills in: the same +//! decisions, at the same places, with more proteins between. + +#![allow(clippy::unwrap_used)] + +use cellweave_core::{CellInputs, Concentration, NetworkSpec, SignalingNetwork, TimeStep}; +use cellweave_engine::Network; +use cellweave_engine::simulation::QUIESCENCE_THRESHOLD; +use cellweave_io::SimConfig; + +fn spec(config: &str) -> NetworkSpec { + let path = format!("{}/../../examples/{config}", env!("CARGO_MANIFEST_DIR")); + let config = SimConfig::from_file(&path).unwrap(); + config.load_network(Some(&path)).unwrap() +} + +fn fuller() -> NetworkSpec { + spec("spheroid-fuller.toml") +} + +fn simpler() -> NetworkSpec { + spec("spheroid.toml") +} + +fn stress_response() -> NetworkSpec { + spec("cord-stress.toml") +} + +fn inputs(o2: f64, stress: f64) -> CellInputs { + CellInputs { + o2: Concentration(o2), + egf: Concentration(0.2), + vegf: Concentration(0.0), + crowding: Concentration(0.0), + stress: Concentration(stress), + waste: Concentration(0.0), + necrotic_factor: Concentration(0.0), + } +} + +/// The network of `spec`, settled under `o2` and `stress`. +fn settled(spec: &NetworkSpec, o2: f64, stress: f64) -> Network { + let mut net = Network::from_spec(spec, 100).unwrap(); + for _ in 0..600 { + net.step(TimeStep(1.0), &inputs(o2, stress)); + } + net +} + +fn level(net: &Network, name: &str) -> f64 { + let i = net.node_names().iter().position(|n| n == name).unwrap(); + net.state().values[i].0 +} + +/// The oxygen below which a settled cell of `spec` has stopped dividing. +fn arrest_oxygen(spec: &NetworkSpec) -> f64 { + let (mut lo, mut hi) = (0.0, 1.0); + for _ in 0..30 { + let mid = 0.5 * (lo + hi); + if settled(spec, mid, 0.0).hypoxia_response() >= QUIESCENCE_THRESHOLD { + lo = mid; + } else { + hi = mid; + } + } + 0.5 * (lo + hi) +} + +#[test] +fn the_fuller_cell_asks_for_the_size_the_simpler_one_does() { + let (a, b) = (settled(&fuller(), 1.0, 0.0), settled(&simpler(), 1.0, 0.0)); + assert!( + (level(&a, "erk") - level(&b, "erk")).abs() < 0.002, + "ERK {} against {}", + level(&a, "erk"), + level(&b, "erk") + ); + let (ta, tb) = (a.mechanics().target_volume.0, b.mechanics().target_volume.0); + assert!(ta.abs_diff(tb) <= 1, "target {ta} against {tb}"); +} + +#[test] +fn the_fuller_cell_stops_dividing_at_the_oxygen_the_simpler_one_does() { + let (a, b) = (arrest_oxygen(&fuller()), arrest_oxygen(&simpler())); + assert!((a - b).abs() < 0.005, "arrest below {a:.4} against {b:.4}"); + // And by RB, through p27: well fed, RB is off and p27 absent. + let fed = settled(&fuller(), 1.0, 0.0); + assert!(level(&fed, "rb") < 0.3, "RB {}", level(&fed, "rb")); + assert!(level(&fed, "p27") < 0.01); + let starved = settled(&fuller(), 0.1, 0.0); + assert!( + level(&starved, "p27") > 0.5, + "p27 {}", + level(&starved, "p27") + ); + assert!(level(&starved, "cyclin_e") < level(&fed, "cyclin_e") / 2.0); +} + +#[test] +fn the_fuller_cell_dies_of_anoxia_where_the_simpler_one_does() { + for o2 in [0.02, 0.05, 0.1, 0.2, 0.6] { + let (a, b) = (settled(&fuller(), o2, 0.0), settled(&simpler(), o2, 0.0)); + assert!( + (a.survival() - b.survival()).abs() < 0.002, + "at {o2}: BCL2 {} against {}", + a.survival(), + b.survival() + ); + } +} + +#[test] +fn the_fuller_cell_answers_a_stress_as_the_stress_response_did() { + for stress in [0.0, 0.2, 0.5, 1.0] { + let (a, b) = ( + settled(&fuller(), 1.0, stress), + settled(&stress_response(), 1.0, stress), + ); + let (pa, pb) = (a.apoptosis().unwrap(), b.apoptosis().unwrap()); + assert!( + (pa - pb).abs() < 0.015, + "at {stress}: caspase {pa:.4} against {pb:.4}" + ); + } + // Without a stress, nothing on the way to apoptosis is on at all. + let calm = settled(&fuller(), 1.0, 0.0); + for name in ["p53", "mdm2", "p21", "bax", "caspase"] { + assert_eq!(level(&calm, name), 0.0, "{name}"); + } + // MDM2 holds p53 below what the stress alone would raise it to. + let (a, b) = ( + settled(&fuller(), 1.0, 1.0), + settled(&stress_response(), 1.0, 1.0), + ); + assert!(level(&a, "p53") < level(&b, "p53")); +} + +#[test] +fn p21_alone_does_not_stop_the_cycle_but_adds_to_hypoxia() { + let stressed = settled(&fuller(), 1.0, 1.0); + assert!(stressed.hypoxia_response() < QUIESCENCE_THRESHOLD); + assert!(level(&stressed, "rb") > level(&settled(&fuller(), 1.0, 0.0), "rb")); + // Just above the oxygen that arrests a calm cell, a stressed one stops. + let o2 = arrest_oxygen(&fuller()) + 0.05; + assert!(settled(&fuller(), o2, 0.0).hypoxia_response() < QUIESCENCE_THRESHOLD); + assert!(settled(&fuller(), o2, 1.0).hypoxia_response() >= QUIESCENCE_THRESHOLD); +} + +#[test] +fn the_cycle_settles_to_one_state_however_it_starts() { + // Started arrested, RB fully on and E2F and cyclin E off, a cell ends + // where one started cycling does: the switch has no memory, as HIF-1a + // had none, so a cell that regains its oxygen divides again. + let mut arrested = fuller(); + for node in &mut arrested.nodes { + match node.name.as_str() { + "rb" => node.initial = 1.0, + "e2f" | "cyclin_e" => node.initial = 0.0, + _ => {} + } + } + for o2 in [1.0, 0.4, 0.32, 0.31, 0.0] { + let (a, b) = (settled(&fuller(), o2, 0.0), settled(&arrested, o2, 0.0)); + assert!( + (a.hypoxia_response() - b.hypoxia_response()).abs() < 1e-6, + "at {o2}: RB {} against {}", + a.hypoxia_response(), + b.hypoxia_response() + ); + } +} + +#[test] +fn a_fuller_cell_starts_where_it_settles() { + // The initial levels in the file are the well fed steady state, so the + // first cell does not spend its first steps catching up. + let spec = fuller(); + let net = settled(&spec, 1.0, 0.0); + for (node, settled) in spec.nodes.iter().zip(&net.state().values) { + if ["hif1", "vegf", "bcl2"].contains(&node.name.as_str()) { + continue; + } + assert!( + (node.initial - settled.0).abs() < 0.01, + "{} starts at {} and settles at {}", + node.name, + node.initial, + settled.0 + ); + } +} + +#[test] +fn ras_stuck_on_raises_erk_as_far_through_raf_and_mek() { + // The mutant RAS of chapter 2, laid over each network: switched on by + // nothing rather than by what lies above it. + let mutant: NetworkSpec = toml::from_str(include_str!( + "../../../examples/networks/ras-erk-mutant.toml" + )) + .unwrap(); + let ras = mutant + .nodes + .iter() + .find(|n| n.name == "ras") + .unwrap() + .clone(); + let stuck = |spec: NetworkSpec| { + let mut spec = spec; + for node in &mut spec.nodes { + if node.name == "ras" { + *node = ras.clone(); + } + } + level(&settled(&spec, 1.0, 0.0), "erk") + }; + let (a, b) = (stuck(fuller()), stuck(simpler())); + assert!((a - b).abs() < 0.01, "ERK {a:.4} against {b:.4}"); + assert!(a > 0.5, "well above the 0.33 of a normal RAS: {a}"); +} diff --git a/docs/02-what-happens-inside-a-cell.md b/docs/02-what-happens-inside-a-cell.md index 80f3b8f..076aeb8 100644 --- a/docs/02-what-happens-inside-a-cell.md +++ b/docs/02-what-happens-inside-a-cell.md @@ -62,6 +62,7 @@ Each line of the table above is a **term**, and terms come from a closed catalog | term | what it computes | what it means | |---|---|---| | `activated_by` | `rate * source * (1 - self)` | one relay switching on the next, saturating because a protein cannot be more than fully active | +| `inhibited_by` | `- rate * source * self` | one protein switching another off, the mirror of `activated_by` (chapter 28) | | `activated_by_absence_of` | `rate * (1 - source) * (1 - self)` | accumulating when something is scarce, which is HIF-1α as oxygen falls | | `produced_by` | `rate * source` | made in proportion, without saturating, for something secreted | | `decays` | `- rate * self` | first order turnover, which is what gives a node a steady state at all | @@ -69,7 +70,7 @@ Each line of the table above is a **term**, and terms come from a closed catalog | `damaged_below` | `- rate * max(0, (threshold - source) / threshold)` | energy failure, the one term nothing above cancels | | `damaged_above` | `- rate * max(0, (source - threshold) / threshold)` | what is toxic past some level, offset by nothing (chapter 27) | -`activated_by` also takes a **Hill** response, `source^n / (k^n + source^n)` in place of `source`, where `n` is how sharply it switches and `k` the level at which it is half way. With a large `n` a graded signal becomes a decision. +`activated_by` and `inhibited_by` also take a **Hill** response, `source^n / (k^n + source^n)` in place of `source`, where `n` is how sharply it switches and `k` the level at which it is half way. With a large `n` a graded signal becomes a decision. A closed catalogue rather than free-form expressions is a deliberate limit. An expression language would be more expressive and would let anyone write something that parses and means nothing; a catalogue says exactly which mechanisms the model knows about, and every one of them is documented above and pinned by a test. A paper whose network does not fit adds an entry, which is a change on the record rather than an open hole. @@ -109,7 +110,7 @@ The network settles in about fifteen units of its time. The binary gives it eigh **Concentrations, not molecules.** Each protein is one number, a fraction between 0 and 1, as if the cell were a well-stirred bag. A real cell has thousands of copies of each protein in specific places. Averaging is the standard first model and it keeps five equations rather than five million. -**A reduced chain.** RAF and MEK are skipped: RAS activates ERK directly. They relay without deciding, and two more equations would add constants without adding behaviour. If a question ever turns on one of them, they come back. +**A reduced chain.** RAF and MEK are skipped: RAS activates ERK directly. They relay without deciding, and two more equations would add constants without adding behaviour. If a question ever turns on one of them, they come back. Chapter 28 brings them back, with the receptor before them and the cell cycle and the way to apoptosis after, in a fuller network whose rates are set so that it decides what this one does. **ERK sets the target volume**, with the coefficient 1.5: `target = base (1 + 1.5 erk)`. It was 0.5 at first, and since ERK saturates near 0.55, no cell could ever reach the division threshold. The coefficient is chosen so a well stimulated cell aims at about twice its reference size. A model constant that silently makes a behaviour impossible is the kind of thing to state in a comment, not tune quietly. diff --git a/docs/10-many-histories-paired.md b/docs/10-many-histories-paired.md index 059eed3..019bda9 100644 --- a/docs/10-many-histories-paired.md +++ b/docs/10-many-histories-paired.md @@ -46,7 +46,7 @@ So, in this model, continuous stress controls the cord far better in about half **Resistance asked of the network, not read from the tissue.** Whether a cell survives depends on where it sits as much as on what it carries. Asking each network how it would respond, at one fixed level, separates the two, and the third route in the table above is exactly the case where they differ. -**All at once.** The Monte Carlo step of one run uses one core (chapter 28); a campaign puts one run on each, which is how forty runs of 3000 steps take about forty minutes on twenty threads. +**All at once.** The Monte Carlo step of one run uses one core (chapter 29); a campaign puts one run on each, which is how forty runs of 3000 steps take about forty minutes on twenty threads. ## Where in the code diff --git a/docs/28-inside-one-cell.md b/docs/28-inside-one-cell.md new file mode 100644 index 0000000..c6b8da7 --- /dev/null +++ b/docs/28-inside-one-cell.md @@ -0,0 +1,138 @@ +# 28. Inside one cell + +What lies between what a cell reads and what it decides, and how is one cell opened to watch it? + +## In the body + +Chapter 2 gave each cell five proteins, and said what it left out: between a growth factor outside the cell and the decision to divide there are a dozen proteins, and as many between a damaged cell and its death. This chapter puts them back. Each is named here before it is used. + +**The growth relay.** **EGF** (epidermal growth factor) is a small protein outside the cell. It binds **EGFR** (the EGF receptor), a protein that crosses the cell's membrane, and the part of the receptor inside the cell becomes a **kinase**: an enzyme that switches other proteins on by attaching a phosphate group to them, which is called **phosphorylation**. The receptor switches on **RAS** (first found in a rat sarcoma, hence the name), a switch held on the inside of the membrane. RAS switches on **RAF** (rapidly accelerated fibrosarcoma), a kinase; RAF phosphorylates **MEK** (MAPK/ERK kinase), and MEK phosphorylates **ERK** (extracellular signal-regulated kinase), which goes into the nucleus and changes which genes are read (Lemmon and Schlessinger, Cell, 2010). RAF, MEK and ERK together are the **MAPK cascade** (mitogen-activated protein kinase). MEK and ERK each need two phosphates to be active. A kinase that must add two before its target works has to find it twice, and the response of the target then rises more than in proportion to the kinase above it: Huang and Ferrell measured it in frog eggs, where ERK goes from nearly off to nearly on over a narrow range of the signal (PNAS, 1996). + +**The cell cycle.** Chapter 27 named its phases: a first gap (G1), the copying of the DNA (S), a second gap and mitosis. Whether a cell leaves G1 for S is the decision that matters, and it is held by **RB** (the retinoblastoma protein, named after the eye tumour its loss causes). RB binds **E2F** (E2 promoter binding factor), the transcription factor that reads the genes needed to copy DNA, and while bound E2F reads nothing. RB is released by being phosphorylated, by kinases that work only when bound to a **cyclin**, hence their name, **CDK** (cyclin-dependent kinase). ERK has the cell make **cyclin D** (Lavoie and colleagues, J Biol Chem, 1996), whose kinase puts a single phosphate on RB, which does not release it (Narasimha and colleagues, eLife, 2014); E2F, once some is free, has the cell make **cyclin E**, whose kinase phosphorylates RB fully and frees more E2F. That is a loop: the less RB holds, the more cyclin E, the less RB holds. Past a point the cell is committed and divides whatever the growth factor does next, which is called the **restriction point**, and the loop is what makes it a switch (Yao and colleagues, Nat Cell Biol, 2008). + +**The brakes.** Two proteins block the cyclin E kinase, and with it the loop. **p27** (p27Kip1, chapter 27) is made when HIF-1α (hypoxia-inducible factor 1α, chapter 2) rises: without oxygen, cells raise p27 and stop in G1, and cells unable to make HIF-1α do not stop (Gardner and colleagues, J Biol Chem, 2001; Goda and colleagues, Mol Cell Biol, 2003). **p21** (p21Cip1, also called WAF1) is made when **p53** rises (el-Deiry and colleagues, Cell, 1993), and blocks the same kinases (Harper and colleagues, Cell, 1993). This is the half of p53 that chapter 8 described and left out: low, it pauses the cell. + +**The way to apoptosis.** p53 is held down in a healthy cell by **MDM2** (mouse double minute 2), which marks it for destruction (Haupt and colleagues, Nature, 1997). p53 has the cell make MDM2, so a rise of p53 brings on what lowers it again (Wu and colleagues, Genes Dev, 1993). p53 also has the cell make **BAX** (BCL2-associated X protein; Miyashita and Reed, Cell, 1995), which opens the mitochondria and lets out what starts the **caspases** of chapter 8. **BCL2** (B-cell lymphoma 2, chapter 2) binds BAX and holds it back (Oltvai and colleagues, Cell, 1993): survival and apoptosis meet on that pair. + +## In cellweave + +`examples/networks/fuller-cell.toml` is that network: eighteen proteins where chapter 2 has five and chapter 8 seven. It extends `stress-response.toml`, which extends `ras-erk.toml`, and adds or replaces only what this chapter fills in. HIF-1α, VEGF (vascular endothelial growth factor) and BCL2 are inherited unchanged. + +```mermaid +flowchart LR + EGF(["EGF"]) --> EGFR --> RAS --> RAF --> MEK --> ERK + ERK --> CD["cyclin D"] + CD --x|"one phosphate"| RB + RB --x E2F + E2F --> CE["cyclin E"] + CE --x RB + O2(["oxygen"]) -.->|"less oxygen,
more HIF"| HIF["HIF-1α"] + HIF --> P27["p27"] + P27 --x CE + S(["stress"]) --> P53["p53"] + P53 --> MDM2 + MDM2 --x P53 + P53 --> P21["p21"] + P21 --x CE + P53 --> BAX + BCL2 --x BAX + BAX --> CASP["caspase"] + ERK ==>|"target volume"| G["the lattice"] + RB ==>|"at or above 0.45:
stops cycling"| F["fate"] + BCL2 ==>|"below 0.25: dead"| F + CASP ==>|"chance per step"| A["apoptosis"] +``` + +An arrow switches its target on, a cross switches it off. HIF-1α's arrows to VEGF and BCL2, and ERK's to BCL2, are chapter 2's and not drawn again. + +### A new term + +Switching off is what most of these proteins do to each other, and chapter 2's catalogue had no term for it. It has one now, `inhibited_by`: `- rate * source * self`, the mirror of `activated_by`. The node is lost in proportion to how much of it there is and how much of the source, which is what a kinase that inactivates its target does, or a protein that marks another for destruction. It takes a Hill response as `activated_by` does. In the code it is `Term::InhibitedBy`, and a test checks that its slope is what its documentation says and that it empties a node without taking it below zero. + +### Rates set by what was calibrated + +None of the rates is measured; no study measures them in the units of a model whose levels are fractions between 0 and 1. They are chosen instead so that the fuller cell decides what the simpler networks decide, at the same places, which chapters 25 and 27 fixed against measured spheroids. The tests in `crates/io/tests/fuller_cell.rs` hold them there: + +- **The same size.** ERK settles at 0.333 in both, so a cell asks for the same target volume. The relay has two more steps and each saturates, which would damp the signal; the Hill response of order two on MEK and on ERK, which is the double phosphorylation above, gives it back. With RAS stuck on, as in chapter 2's mutant, ERK reaches 0.553 through RAF and MEK against 0.556 without them. +- **The same arrest.** The cell stops dividing when RB is on: the network's `hypoxia_response` role, the node whose height stops the cycle (chapter 4), is RB, against the same threshold of 0.45. It is the role's old name; what turns RB on here is p27 or p21, and with neither RB settles at 0.23. p27's half way point, 0.549, is the one number set to place the arrest: a well-stimulated cell crosses 0.45 at 31.8% of the source's oxygen, where HIF-1α crosses it in the simpler network. +- **The same death.** BCL2 is inherited, so a cell dies of anoxia where it did. +- **The same apoptosis.** Caspase answers a stress within 0.015 of what it did in `stress-response.toml`: 0.028 a step against 0.017 at a fifth of the full stress, 0.287 against 0.299 at all of it. MDM2 holds p53 lower than the stress alone would, 0.39 against 0.50 at full stress, and BAX carries it the rest of the way. + +Another checks that the cycle has no memory: started arrested, RB fully on and E2F and cyclin E off, a cell settles where one started cycling does, at every oxygen. Another, that the file's initial levels are the well-fed steady state, so the first cell does not spend its first steps catching up. + +### What is new + +Two things the simpler networks could not do. + +**p21 adds to p27.** On its own, at the stresses the model knows, p21 pushes RB up without reaching the threshold: 0.448 at full stress in full oxygen. With some hypoxia as well, the two brakes on cyclin E add up and the cell stops: 5 points of oxygen above where a calm cell would stop, a stressed one already has. + +**BCL2 shields from apoptosis.** BAX is held back by BCL2, so a cell whose BCL2 is high, fed by ERK and by HIF-1α, resists the stress more, and a cell whose BCL2 the anoxia is breaking down resists it less. + +### Run against the simpler networks + +**The spheroid.** `spheroid-fuller.toml` is chapter 25's calibrated spheroid with the fuller cell. Its first cell starts at the well-fed steady state rather than with ERK at 0.05, so it grows a few steps sooner and the run stays about fourteen steps ahead. Measured by size rather than by step, the two are the same: the first cell stops dividing when the spheroid's radius is 167.9 pixels in both. The first cell dies at a radius of 197.4 pixels against 197.3, where chapter 25 placed the core. Grown to a radius of 320 pixels, its dead core reaches 166.7 pixels from the centre against 166.6, and its living rim is 153.3 pixels deep against 153.5. At the last step, 625, the fuller spheroid is still thirteen steps ahead, 345.5 pixels against 337.6. + +**The stressed cord.** `cord-stress-fuller.toml` is chapter 8's cord under a continuous stress from step 800, with the fuller cell. This was not predicted before it ran. With the simpler network the cord keeps dividing beside its vessel while the stress thins it: 153 births from step 800 to step 1500, 33 cells living at step 1500, and 24 at step 3000, all of them arrested. With the fuller cell, not one cell divides once the stress is on, and the cord dwindles to 4 cells at step 1500 and 1 at step 3000. The cord's cells already carry some p27, from the oxygen gradient around the vessel; p21 adds to it, and the cells the stress reaches stop dividing before it kills them, so nothing replaces the dead. Run again with p21's brake on cyclin E taken out of the file, the fuller cord divides again: 106 births by step 1500, 19 cells living. p21 accounts for most of the difference; the rest is BAX, which BCL2 holds back less in the cells the anoxia is breaking down. + +Whether that is what a tumour does depends on what the stress is. The lethal stress here kills a cell whether it divides or not. Many real agents kill dividing cells far more readily, and against them an arrest would shield a cell rather than doom the tissue: the model cannot tell the two apart until its stress says which it is. + +### Opening a cell + +The viewer opens any cell. A click on a cell, one that does not drag, opens a window beside the tissue, and the cell's outline turns white. The window draws the cell's own network as it stands at the last step shown. What the cell reads from outside is on the left: oxygen, EGF, the stress, each at the level around it. Each protein is a box in the colour the tissue takes when coloured by that protein, with its level. Each term that reads something is an arrow: green where it switches its target on, red where it switches it off, dashed where it acts by an absence or a shortage, and as thick as it is pushing now, its contribution to its target's rate of change. A loop is drawn back under the boxes. The proteins that answer the simulation's questions carry their answer underneath, lit while it is the one given: size, arrest, alive, apoptosis, vessels. + +Below the diagram the window says, in words, what the cell does with those levels: whether it divides and why, how large it asks to be, whether it is alive, its chance of apoptosis this step. A plot follows the proteins that decide over the steps since the cell was opened. Hovering over a protein lists every term that moves it with its rate and what it adds now; clicking it colours the whole tissue by that protein, so the cell can be set against its neighbours. The camera can follow the cell as it is pushed about. + +The diagram is laid out from the network rather than drawn by hand: what the cell reads goes in the first column, each protein one column past the furthest of what it reads, and a link that closes a loop is set aside for the purpose. Any network a configuration names is drawn, and so is a cell whose mutations gained or lost a link (chapter 9), since the window draws that cell's own terms. + +From the command line, `--open x,y` opens the cell under a pixel, at the first step or at `--open-at`; `--follow` keeps the camera on it; `--protein rb` colours the tissue by a protein from the start; and `--window 1920x1080` sets the size of the window and of every frame recorded. + +```sh +cd viewer +cargo run --release -- --config ../examples/spheroid-fuller.toml --open 400,400 --open-at 300 --follow --zoom 3 +``` + +That opens the cell at the centre of the spheroid at step 300. Its oxygen is already down to 0.42 of the bath's, its HIF-1α at 0.41 and its p27 at 0.59, and its RB at 0.443, just short of the threshold. A few steps later RB crosses it and the cell stops dividing, inside a ring of cells doing the same. Then the oxygen around it falls under the anoxia threshold, its BCL2 collapses past 0.25 around step 375, and it dies, among the first cells of the core. The first cell of all, opened at step 0 instead, is not a good one to follow in this run: it keeps its number at each division while its daughters take new ones, and by step 278 it is at the rim. + +## Choices, and why + +**Tuned to the simpler networks rather than to new data.** The decisions of the simpler networks are the part of the model that was measured against something. A fuller network that moved them would need calibrating again, against data that do not separate one protein from the next. Holding the decisions where they were lets the proteins be added without unsettling any result that rests on them, and the tests say so if a later change does. + +**RB, not p27, decides.** Chapter 27's `ras-erk-waste.toml` gives the arrest role to p27. Here p27 is one of two brakes, and what both act on is RB, which is where the cell's commitment is decided. + +**No switch with memory.** The real restriction point is bistable: once past it, the cell divides even if the signal goes. Making it so here would have needed rates past what RK4 at one unit of network time per step integrates stably, and a cell that had stopped for lack of oxygen would not start again when it regains some, which the calibrated networks do. The loop is there, and it steepens the response, but it holds no memory. + +**p21 alone does not stop the cycle.** How far p53 must rise before p21 alone stops a cell is not something these rates could be set by. Set at full stress just short of the threshold, p21 is visible in the window and acts with hypoxia, and stopping the cycle on stress alone is left to be measured. + +## Where in the code + +`crates/core/src/network.rs` has `Term::InhibitedBy`, and `crates/engine/src/network.rs` evaluates it in `term_rate`, the one place every term's contribution is worked out, both for `derivatives` and for `Network::influences`. `Influence` is one term as it stands: the node it moves, its kind, what it reads, its rate, and what it adds now. That is what the window draws as an arrow. + +`crates/engine/src/simulation.rs` has `Simulation::inputs`, what a cell reads from where it sits, the fields averaged over its pixels by `mean_in` in `crates/engine/src/coupling.rs`. `DEATH_THRESHOLD`, `QUIESCENCE_THRESHOLD` and `DIVISION_RATIO` are public, so that the window can say how far a cell is from each. + +`viewer/src/inspect.rs` is the window: `Inspected` is which cell is open and what was read of it, `pick` turns a click into a pixel by marching down the camera's ray to the relief, `read` reads the cell between two batches, `follow` moves the camera, and `window` draws it. `viewer/src/diagram.rs` lays the network out, `Layout`, and draws it. `viewer/src/paint.rs` outlines the open cell with `OPEN_MEMBRANE`. + +`examples/networks/fuller-cell.toml` is the network. `examples/spheroid-fuller.toml` and `examples/cord-stress-fuller.toml` are the spheroid of chapter 25 and the stressed cord of chapter 8 with it. + +## Still a placeholder + +Every rate. The links are the literature's; their strengths are set so that the decisions land where the simpler networks put them, and so they say nothing the simpler networks did not, except where the new links act together, as p21 with p27 and BCL2 with BAX. + +The levels are fractions of a protein's possible activity, not concentrations, and a protein is one number for the whole cell. + +Much is still missing between these proteins: the second loop that makes the restriction point remember, the pulses of p53 that MDM2 makes in single cells, the growth of a cell's mass that mTOR (mechanistic target of rapamycin) drives apart from its division, the PI3K and AKT pathway beside RAS, MYC. + +## References + +- Lemmon MA, Schlessinger J. [Cell signaling by receptor tyrosine kinases](https://doi.org/10.1016/j.cell.2010.06.011). *Cell* 141, 1117-1134 (2010). [Free full text](https://europepmc.org/article/PMC/PMC2914105). +- Huang CY, Ferrell JE. [Ultrasensitivity in the mitogen-activated protein kinase cascade](https://doi.org/10.1073/pnas.93.19.10078). *PNAS* 93, 10078-10083 (1996). [Free full text](https://europepmc.org/article/PMC/PMC38339). +- Lavoie JN, L'Allemain G, Brunet A, Müller R, Pouysségur J. [Cyclin D1 expression is regulated positively by the p42/p44MAPK and negatively by the p38/HOGMAPK pathway](https://doi.org/10.1074/jbc.271.34.20608). *J Biol Chem* 271, 20608-20616 (1996). +- Narasimha AM, Kaulich M, Shapiro GS, Choi YJ, Sicinski P, Dowdy SF. [Cyclin D activates the Rb tumor suppressor by mono-phosphorylation](https://doi.org/10.7554/eLife.02872). *eLife* 3, e02872 (2014). [Free full text](https://europepmc.org/article/PMC/PMC4076869). +- Yao G, Lee TJ, Mori S, Nevins JR, You L. [A bistable Rb-E2F switch underlies the restriction point](https://doi.org/10.1038/ncb1711). *Nat Cell Biol* 10, 476-482 (2008). +- Gardner LB, Li Q, Park MS, Flanagan WM, Semenza GL, Dang CV. [Hypoxia inhibits G1/S transition through regulation of p27 expression](https://doi.org/10.1074/jbc.M010189200). *J Biol Chem* 276, 7919-7926 (2001). +- Goda N, Ryan HE, Khadivi B, McNulty W, Rickert RC, Johnson RS. [Hypoxia-inducible factor 1alpha is essential for cell cycle arrest during hypoxia](https://doi.org/10.1128/MCB.23.1.359-369.2003). *Mol Cell Biol* 23, 359-369 (2003). [Free full text](https://europepmc.org/article/PMC/PMC140666). +- el-Deiry WS, Tokino T, Velculescu VE, et al. [WAF1, a potential mediator of p53 tumor suppression](https://doi.org/10.1016/0092-8674(93)90500-P). *Cell* 75, 817-825 (1993). +- Harper JW, Adami GR, Wei N, Keyomarsi K, Elledge SJ. [The p21 Cdk-interacting protein Cip1 is a potent inhibitor of G1 cyclin-dependent kinases](https://doi.org/10.1016/0092-8674(93)90499-G). *Cell* 75, 805-816 (1993). +- Wu X, Bayle JH, Olson D, Levine AJ. [The p53-mdm-2 autoregulatory feedback loop](https://doi.org/10.1101/gad.7.7a.1126). *Genes Dev* 7, 1126-1132 (1993). +- Haupt Y, Maya R, Kazaz A, Oren M. [Mdm2 promotes the rapid degradation of p53](https://doi.org/10.1038/387296a0). *Nature* 387, 296-299 (1997). +- Miyashita T, Reed JC. [Tumor suppressor p53 is a direct transcriptional activator of the human bax gene](https://doi.org/10.1016/0092-8674(95)90412-3). *Cell* 80, 293-299 (1995). +- Oltvai ZN, Milliman CL, Korsmeyer SJ. [Bcl-2 heterodimerizes in vivo with a conserved homolog, Bax, that accelerates programmed cell death](https://doi.org/10.1016/0092-8674(93)90509-O). *Cell* 74, 609-619 (1993). diff --git a/docs/28-what-the-model-does-not-say.md b/docs/29-what-the-model-does-not-say.md similarity index 96% rename from docs/28-what-the-model-does-not-say.md rename to docs/29-what-the-model-does-not-say.md index aae8958..9b65876 100644 --- a/docs/28-what-the-model-does-not-say.md +++ b/docs/29-what-the-model-does-not-say.md @@ -1,4 +1,4 @@ -# 28. What the model does not say +# 29. What the model does not say The placeholders, the missing units, and why emergence is the whole point. @@ -25,6 +25,7 @@ What is a placeholder today, gathered from the chapters: | lattice | contact energies 16, 2, 11, 6; λ = 50; T = 10 | cells stay compact and fluctuate visibly | | network | every rate constant | ERK saturates near 0.55; the network settles in 15 units; survival collapses near 5% oxygen | | network | growth coefficient 1.5 | a stimulated cell can reach the division threshold at all | +| a fuller cell | every rate of its eighteen proteins; a Hill response of order two on MEK and on ERK; p27 half way at HIF-1α of 0.549; p21 just short of stopping the cycle alone at full stress | ERK, the arrest, the death by anoxia and the apoptosis under a stress fall where the simpler networks put them (chapter 28) | | field | D = 0.2; uptake 0.00002 for every tumour | calibrated on measured melanoma spheroids (chapter 25): a disc forms its core where a sphere with their oxygen would; it was 0.0003, 0.00003 and 0.0001 by geometry before | | field | stroma consumes at the tumour's rate | the medium beyond a cord does not fill up from the vessel | | a volume | a voxel 2.975 µm; uptake 0.00017 with the medium stirred, divided by $1 + 2k$ with it still; a dead cell's debris losing 0.024 of its volume a step, paid at the edge of the dead tissue; four Monte Carlo sweeps a step; λ = 20; contact counted to the corners, each contact divided by 9, copies across faces; a cycle of 20 steps median, spread 0.3, a cell growing through it in a straight line | a ball forms its core where the measured spheroids do (chapter 27), fitted by Greenspan's relation; the loss Greenspan's model asks of the measured end against how fast the cells grow, $\gamma = 0.70$; sweeps enough for the tissue to carry what the core loses out to its surface; a surface that holds round; a tissue that does not divide all at once | diff --git a/docs/README.md b/docs/README.md index a117bb9..115fd81 100644 --- a/docs/README.md +++ b/docs/README.md @@ -42,7 +42,8 @@ Chapters build on each other and are meant to be read in order the first time. | 25 | [Measured against spheroids](25-measured-against-spheroids.md) | Set against hundreds of measured spheroids, where does the model put the core and the arrest, what does that make of a cord, and how long is a step? | | 26 | [A tissue with depth](26-a-tissue-with-depth.md) | What changes when the lattice has a third dimension, and how a plane is kept exactly as it was? | | 27 | [Spheroids in a volume](27-spheroids-in-a-volume.md) | Grown as balls, do the model's spheroids form their core and their arrest where measured ones do, and does a core that breaks down stop them where those stop? | -| 28 | [What the model does not say](28-what-the-model-does-not-say.md) | The placeholders, the missing units, and why emergence is the whole point. | +| 28 | [Inside one cell](28-inside-one-cell.md) | What lies between what a cell reads and what it decides, and how is one cell opened to watch it? | +| 29 | [What the model does not say](29-what-the-model-does-not-say.md) | The placeholders, the missing units, and why emergence is the whole point. | | | [Glossary](glossary.md) | Every word, in one place. | ## Where the code is diff --git a/docs/glossary.md b/docs/glossary.md index adb8994..935e290 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -20,11 +20,15 @@ Every word the course uses, in one place. Chapter numbers point to where each is **Bath** (3). A large stirred volume of liquid around a tissue whose oxygen never drops. Modelled by holding every medium pixel the bath can reach at 1.0. +**BAX** (28). BCL2-associated X protein. Made when p53 rises, it opens the mitochondria and starts the caspases; BCL2 binds it and holds it back. In the fuller cell, what caspase answers. + **BCL2** (2). B-cell lymphoma 2, a survival protein. When it falls below 0.25 the cell is necrotic. **Capillary** (3, 18). The finest blood vessel, where oxygen leaves the blood. No cell in the body is further than 100 to 200 micrometres from one. Here also a vessel lying across the box, which blood enters on one side and leaves on the other. -**Caspase** (8). The enzymes that carry out apoptosis, cutting the cell's own proteins apart. Here one node, switched on sharply by p53. +**Caspase** (8). The enzymes that carry out apoptosis, cutting the cell's own proteins apart. Here one node, switched on sharply by p53, or in the fuller cell of chapter 28 by BAX. + +**CDK, cyclin-dependent kinase** (28). A kinase that works only bound to a cyclin. CDKs phosphorylate RB and so let a cell leave G1. **Cell cycle** (27). What a cell goes through from its birth to its division: a first gap (G1), copying its DNA (S), a second gap (G2) and mitosis (M). With `[cycle]`, each cell draws at its birth how many steps its cycle lasts, log-normal around a median, and does not divide before they have passed. @@ -60,6 +64,8 @@ Every word the course uses, in one place. Chapter numbers point to where each is **Crowding** (7). How squeezed a cell is: how far below its reference size it sits, as a fraction of it. An input every network can read, like oxygen. +**Cyclin** (28). A protein whose level rises and falls through the cell cycle and switches on a CDK. Cyclin D is made on ERK's signal, cyclin E on E2F's. + **Debris loss** (27). The share of a dead cell's volume its debris loses each step, broken down into fluid that leaves the tissue; the tissue closes over what goes, and gives it up at its surface. What stops a spheroid growing, in Greenspan's model and here. **Depth** (26). The number of slices of the lattice. One is a plane, run exactly as it always was; more is a volume. @@ -76,10 +82,14 @@ Every word the course uses, in one place. Chapter numbers point to where each is **Driver** (9). A mutation that gave the cells carrying it an advantage the tumour grew from. Here, one whose suppression changes the history. +**E2F** (28). The transcription factor that reads the genes a cell needs to copy its DNA, held by RB until RB is phosphorylated. + **Early tumour, lesion** (13, 15). A microscopic patch of abnormal cells that has only just formed. Here a patch placed at one step, carrying a network of its own: in the sheet, where whether it survives depends on its fitness relative to the clones around it, within a window (13); or in a tumour, as a subclone placed by hand (16). **EGF** (2). Epidermal growth factor, the growth signal. A hardcoded input for every cell today. +**EGFR** (28). The EGF receptor: it crosses the membrane, binds EGF outside, and switches RAS on inside. + **Emergence** (6, 7, 12, 14, 20, 28). Behaviour that follows from the model without any rule naming it. The necrotic core, the compact cell, the cord's thickness. **Endothelial cell** (14). A cell of the thin layer that lines every blood vessel. The cells that sprout. @@ -132,8 +142,14 @@ Every word the course uses, in one place. Chapter numbers point to where each is **Loss of function** (11). A mutation that stops a gene's product from working, rather than turning it up or down. Here a lost term, through rewiring. +**MAPK cascade** (28). RAF, MEK and ERK, three kinases each switching on the next: the mitogen-activated protein kinase cascade. + +**MDM2** (28). Mouse double minute 2, the protein that marks p53 for destruction. p53 has the cell make it, so a rise of p53 brings on what lowers it. + **Medium** (1, 3). Empty pixels, identity 0. Liquid in a bath; stroma around a vessel. +**MEK** (28). MAPK/ERK kinase: switched on by RAF, it switches ERK on by attaching two phosphates. + **Monte Carlo step, MCS** (1). One attempt per pixel to change hands, 40,000 on the default grid. The lattice's unit of time. **Muller plot** (6). Every clone's share of the population over time, stacked, so a sweep is a band that widens. @@ -156,9 +172,11 @@ Every word the course uses, in one place. Chapter numbers point to where each is **ODE** (2). Ordinary differential equation: rates of change in time only. The network is five of them. -**p27** (27). p27Kip1, a cyclin-dependent kinase inhibitor: a protein that holds a cell in the first gap of its cycle (G1). Higher in the arrested inner cells of melanoma spheroids. Here the node that arrests a cell in `ras-erk-waste.toml`, raised by HIF-1α and by the waste. +**p21** (28). p21Cip1, or WAF1: a cyclin-dependent kinase inhibitor made when p53 rises, the way p53 pauses a cell. In the fuller cell, a second brake on cyclin E beside p27. + +**p27** (27). p27Kip1, a cyclin-dependent kinase inhibitor: a protein that holds a cell in the first gap of its cycle (G1). Higher in the arrested inner cells of melanoma spheroids. Here the node that arrests a cell in `ras-erk-waste.toml`, raised by HIF-1α and by the waste; in the fuller cell of chapter 28, the brake HIF-1α puts on cyclin E. -**p53** (8). The protein that rises when a cell is damaged and decides between repair and apoptosis. Here switched on by the stress. +**p53** (8). The protein that rises when a cell is damaged and decides between repair and apoptosis. Here switched on by the stress; in the fuller cell of chapter 28 it also raises MDM2, p21 and BAX. **Passenger** (9). A mutation carried along by a lineage that won for other reasons. Here, one whose suppression leaves the history identical to the last bit. @@ -168,6 +186,8 @@ Every word the course uses, in one place. Chapter numbers point to where each is **Perfusion** (14, 16, 19). Blood flowing through a vessel. Here a sprout carries blood, and oxygen, from its first pixel, or only once its tip has joined another vessel and closed a loop. +**Phosphorylation** (28). Attaching a phosphate group to a protein, which is how a kinase switches its target on or off. + **Pixel** (1). One square of the lattice, about a micrometre, carrying one identity and one oxygen value. **Poiseuille's law** (19). The flow through a tube is the difference of pressure across it times the fourth power of its radius, over its length and the blood's viscosity. A vessel twice as wide carries sixteen times as much. @@ -182,8 +202,12 @@ Every word the course uses, in one place. Chapter numbers point to where each is **Quiescent** (4). Alive, not dividing. Hypoxia response above 0.45. +**RAF** (28). Rapidly accelerated fibrosarcoma, the kinase RAS switches on, and which switches MEK on. + **RAS** (2). The switch at the start of the growth pathway. Stuck on in one cancer in three. +**RB** (28). The retinoblastoma protein, which holds E2F and so the cell in G1 until cyclin-dependent kinases phosphorylate it. In the fuller cell, the node whose height stops the cycle. + **Red-black** (3). An order for an SOR sweep: the grid coloured like a chessboard, every red pixel updated from its black neighbours, then every black one from the new reds. Each colour can be updated in parallel. **Refuge** (8, 10). Where a stress does not reach: here the hypoxic, quiescent edge of the cord, the cells it is used up before reaching. @@ -196,6 +220,8 @@ Every word the course uses, in one place. Chapter numbers point to where each is **Resorption** (4). Dead tissue being cleared. Two pixels per step here. +**Restriction point** (28). The point in G1 past which a cell divides whatever its growth signal does next, set by the loop between RB, E2F and cyclin E. + **Reversion** (13). Undoing a clone's mutation at one step, in every cell carrying it, as switching a gene back does in an experiment. The run is the real one until that step. **Rewiring** (6). A mutation that changes which terms a network has rather than how strong one is: a node loses a term, or gains a link to an input or another node. diff --git a/examples/cord-stress-fuller.toml b/examples/cord-stress-fuller.toml new file mode 100644 index 0000000..3360714 --- /dev/null +++ b/examples/cord-stress-fuller.toml @@ -0,0 +1,26 @@ +# The cord of cord-stress.toml under its lethal stress, its cells carrying +# the fuller network of chapter 28, so that opening a cell in the viewer shows +# p53, MDM2, p21 and BAX answering the stress, and RB the oxygen. +# +# Tuned to die of a stress as the stress response did, within a hundredth of +# the chance per step; the new thing is p21, which stops the cycle where the +# stress meets hypoxia. + +width = 300 +height = 300 +mcs = 3000 +temperature = 10.0 +snapshot_interval = 50 +output_dir = "output-cord-stress-fuller" +oxygen_uptake = 0.00002 # calibrated on measured melanoma spheroids (chapter 25) +network = "networks/fuller-cell.toml" + +[oxygen_source] +kind = "vessel" +radius = 6 + +[exposure] +intensity = 1.0 +uptake = 0.0001 +start = 800 +schedule = { kind = "continuous" } diff --git a/examples/networks/fuller-cell.toml b/examples/networks/fuller-cell.toml new file mode 100644 index 0000000..c3058d6 --- /dev/null +++ b/examples/networks/fuller-cell.toml @@ -0,0 +1,174 @@ +# A fuller cell: the RAS/ERK network with the stress response, and the +# proteins in between that the two leave out (chapter 28). +# +# What the simpler network shortcuts is filled in: EGFR, RAF and MEK between +# EGF and ERK; the cell cycle between hypoxia and the arrest, cyclin D, RB, +# E2F, cyclin E and the inhibitor p27; and between stress and death, MDM2, +# p21 and BAX around p53. HIF-1a, VEGF and BCL2 are inherited unchanged. +# +# Every link is one the literature describes; chapter 28 gives the source +# of each. The rates are not measured. They are chosen so that the decisions +# fall where the simpler network puts them, which tests pin: ERK settles at +# the same level, so cells ask for the same size; RB reaches the arrest +# threshold at the oxygen where HIF-1a does in the simpler network, so cells +# stop dividing at the same depth; and caspase answers a stress within a +# hundredth of what it did. + +extends = "stress-response.toml" + +# The growth relay. EGF binds its receptor; the receptor switches RAS on; +# RAS switches RAF on, RAF MEK, MEK ERK. +[[nodes]] +name = "egfr" +initial = 0.5 +terms = [ + { kind = "activated_by", source = "egf", rate = 2.0 }, + { kind = "decays", rate = 0.4 }, +] + +[[nodes]] +name = "ras" +initial = 0.25 +terms = [ + { kind = "activated_by", source = "egfr", rate = 0.2 }, + { kind = "decays", rate = 0.3 }, +] + +[[nodes]] +name = "raf" +initial = 0.24 +terms = [ + { kind = "activated_by", source = "ras", rate = 0.5 }, + { kind = "decays", rate = 0.4 }, +] + +# MEK and ERK each need two phosphates to be active, which makes each +# respond more than in proportion to the kinase above it: a Hill response +# of order two. Without it a chain of saturating relays damps a signal at +# every step, and RAS stuck on would barely move ERK. +[[nodes]] +name = "mek" +initial = 0.28 +terms = [ + { kind = "activated_by", source = "raf", rate = 1.0, hill = { n = 2.0, k = 0.55 } }, + { kind = "decays", rate = 0.4 }, +] + +[[nodes]] +name = "erk" +initial = 0.33 +terms = [ + { kind = "activated_by", source = "mek", rate = 1.8, hill = { n = 2.0, k = 0.8 } }, + { kind = "decays", rate = 0.4 }, +] + +# The cell cycle. RB holds E2F, the factor that starts DNA replication; the +# cycle runs once RB is switched off by the kinases its cyclins drive. +# Cyclin D, made on ERK's signal, does a little of it; cyclin E, made on +# E2F's, does most, which closes a loop: the less RB, the more E2F, the more +# cyclin E, the less RB. p27 and p21 block cyclin E's kinase, and RB comes +# back on. +[[nodes]] +name = "cyclin_d" +initial = 0.5 +terms = [ + { kind = "activated_by", source = "erk", rate = 1.5 }, + { kind = "decays", rate = 0.5 }, +] + +[[nodes]] +name = "rb" +initial = 0.23 +terms = [ + { kind = "relaxes_to", value = 1.0, rate = 0.2 }, + { kind = "inhibited_by", source = "cyclin_d", rate = 0.1 }, + { kind = "inhibited_by", source = "cyclin_e", rate = 1.2 }, +] + +[[nodes]] +name = "e2f" +initial = 0.43 +terms = [ + { kind = "relaxes_to", value = 1.0, rate = 0.2 }, + { kind = "inhibited_by", source = "rb", rate = 1.5, hill = { n = 2.0, k = 0.5 } }, +] + +[[nodes]] +name = "cyclin_e" +initial = 0.51 +terms = [ + { kind = "activated_by", source = "e2f", rate = 1.2 }, + { kind = "inhibited_by", source = "p27", rate = 1.5 }, + { kind = "inhibited_by", source = "p21", rate = 1.5 }, + { kind = "decays", rate = 0.5 }, +] + +# Hypoxia reaches the cycle through p27, which HIF-1a induces. Its half way +# point is what places the arrest: at 0.549, RB crosses 0.45 at the oxygen +# where HIF-1a does in the simpler network. +[[nodes]] +name = "p27" +initial = 0.0 +terms = [ + { kind = "activated_by", source = "hif1", rate = 2.0, hill = { n = 2.0, k = 0.549 } }, + { kind = "decays", rate = 0.5 }, +] + +# Stress reaches the cycle through p21, which p53 induces. On its own it +# pushes RB up without stopping the cycle at the stresses the model knows; +# with hypoxia, the two brakes on cyclin E add up. +[[nodes]] +name = "p21" +initial = 0.0 +terms = [ + { kind = "activated_by", source = "p53", rate = 2.0 }, + { kind = "decays", rate = 0.5 }, +] + +# p53, raised by stress as before, now also induces MDM2, which marks it for +# destruction: the loop that brings p53 back down once the stress is gone. +[[nodes]] +name = "p53" +initial = 0.0 +terms = [ + { kind = "activated_by", source = "stress", rate = 0.5 }, + { kind = "inhibited_by", source = "mdm2", rate = 1.0 }, + { kind = "decays", rate = 0.5 }, +] + +[[nodes]] +name = "mdm2" +initial = 0.0 +terms = [ + { kind = "activated_by", source = "p53", rate = 0.5 }, + { kind = "decays", rate = 0.5 }, +] + +# BAX, which p53 induces, opens the mitochondria and starts the caspases; +# BCL2 binds it and holds it back, which is where survival and apoptosis +# meet. Caspase now answers BAX rather than p53 directly. +[[nodes]] +name = "bax" +initial = 0.0 +terms = [ + { kind = "activated_by", source = "p53", rate = 0.5 }, + { kind = "inhibited_by", source = "bcl2", rate = 0.5 }, + { kind = "decays", rate = 0.5 }, +] + +[[nodes]] +name = "caspase" +initial = 0.0 +terms = [ + { kind = "activated_by", source = "bax", rate = 0.3, hill = { n = 4.0, k = 0.14 } }, + { kind = "decays", rate = 0.5 }, +] + +# The cell stops dividing when RB is on, whatever turned it on. The role +# keeps the name it was given when only hypoxia could stop the cycle. +[roles] +growth = "erk" +survival = "bcl2" +hypoxia_response = "rb" +apoptosis = "caspase" +angiogenic = "vegf" diff --git a/examples/spheroid-fuller.toml b/examples/spheroid-fuller.toml new file mode 100644 index 0000000..d4a1e0c --- /dev/null +++ b/examples/spheroid-fuller.toml @@ -0,0 +1,21 @@ +# The spheroid of spheroid.toml, its cells carrying the fuller network of +# chapter 28: the same box, the same oxygen, the same decisions, with the +# proteins in between drawn when a cell is opened in the viewer. +# +# The network is tuned so that its cells ask for the size, stop dividing at +# the oxygen and die of anoxia where those of the simpler network do; the run +# is not the same to the last bit, since RB answers a falling oxygen a step +# or two behind HIF-1a, and every living cell now draws its chance of +# apoptosis. Like spheroid.toml, expect tens of minutes. + +width = 800 +height = 800 +mcs = 626 +temperature = 10.0 +snapshot_interval = 25 +output_dir = "output-spheroid-fuller" +oxygen_uptake = 0.00002 +network = "networks/fuller-cell.toml" + +[oxygen_source] +kind = "bath" diff --git a/viewer/src/diagram.rs b/viewer/src/diagram.rs new file mode 100644 index 0000000..bbbc78c --- /dev/null +++ b/viewer/src/diagram.rs @@ -0,0 +1,437 @@ +//! A cell's network drawn as a diagram: what it reads on the left, each +//! protein in a column by how many relays it sits from what it reads, and +//! every term that reads something as an arrow, as thick as it pushes. +//! +//! The layout is worked out from the network itself, not drawn by hand, so +//! that any network a configuration names, and any cell whose mutations +//! rewired it, is drawn as it is. + +use bevy_egui::egui::{self, Color32, Pos2, Rect, Sense, Shape, Stroke, Vec2}; +use cellweave_core::network::INPUT_NAMES; + +use crate::inspect::Link; +use crate::paint; + +/// Room per column and per row, and the size of a protein's box. +const COLUMN: f32 = 90.0; +const ROW: f32 = 60.0; +const BOX: Vec2 = Vec2::new(76.0, 36.0); +/// Room around the whole, for the arrows that loop back under a row. +const MARGIN: f32 = 18.0; + +/// A rate of change, per unit of network time, at which an arrow is drawn +/// at its thickest. +const FULL_PUSH: f64 = 0.15; + +/// Activation, inhibition and damage: green, red, and a darker red. +const ACTIVATES: Color32 = Color32::from_rgb(90, 205, 150); +const INHIBITS: Color32 = Color32::from_rgb(240, 95, 90); +const DAMAGES: Color32 = Color32::from_rgb(190, 60, 120); + +/// Where everything goes, in the diagram's own coordinates. +pub struct Layout { + /// The inputs the network reads, by name, in the engine's order. + pub inputs: Vec<&'static str>, + /// The centre of each input, then of each node, in that order. + pub centres: Vec, + /// The column of each, the same order. + columns: Vec, + /// The size of the whole. + pub size: Vec2, +} + +impl Layout { + /// Lay out `nodes` proteins and what `links` say they read. + pub fn of(nodes: usize, names: &[String], links: &[Link]) -> Self { + let inputs: Vec<&'static str> = INPUT_NAMES + .iter() + .copied() + .filter(|input| links.iter().any(|l| l.source.as_deref() == Some(*input))) + .collect(); + let vertices = inputs.len() + nodes; + let index = |name: &str| { + inputs.iter().position(|i| *i == name).or_else(|| { + names + .iter() + .position(|n| n == name) + .map(|n| inputs.len() + n) + }) + }; + let mut edges: Vec<(usize, usize)> = links + .iter() + .filter_map(|l| Some((index(l.source.as_deref()?)?, inputs.len() + l.node))) + .filter(|(from, to)| from != to) + .collect(); + edges.sort_unstable(); + edges.dedup(); + + let columns = columns(vertices, inputs.len(), &edges); + let rows = rows(&columns, &edges); + let tallest = rows.iter().copied().fold(0, usize::max) + 1; + let mut per_column = vec![0usize; columns.iter().copied().max().unwrap_or(0) + 1]; + for &c in &columns { + per_column[c] += 1; + } + let centres = (0..vertices) + .map(|v| { + // Each column centred on the tallest one. + let offset = (tallest - per_column[columns[v]]) as f32 / 2.0; + Pos2::new( + MARGIN + BOX.x / 2.0 + columns[v] as f32 * COLUMN, + MARGIN + BOX.y / 2.0 + (rows[v] as f32 + offset) * ROW, + ) + }) + .collect(); + Self { + inputs, + centres, + columns, + size: Vec2::new( + 2.0 * MARGIN + BOX.x + (per_column.len() - 1) as f32 * COLUMN, + 2.0 * MARGIN + BOX.y + (tallest - 1) as f32 * ROW + 16.0, + ), + } + } + + /// The vertex a term's source is, if it reads one. + fn source_of(&self, link: &Link, names: &[String]) -> Option { + let name = link.source.as_deref()?; + self.inputs.iter().position(|i| *i == name).or_else(|| { + names + .iter() + .position(|n| n == name) + .map(|n| self.inputs.len() + n) + }) + } +} + +/// The column of every vertex: inputs in the first, and each node one past +/// the furthest of what it reads, once the links that close a loop back are +/// set aside. A node that reads nothing goes in the second. +fn columns(vertices: usize, inputs: usize, edges: &[(usize, usize)]) -> Vec { + let mut after: Vec> = vec![Vec::new(); vertices]; + for &(from, to) in edges { + after[from].push(to); + } + // A depth first walk from the inputs, then from whatever it missed: an + // edge to a vertex still on the walk's path is one that loops back. + let mut state = vec![0u8; vertices]; + let mut back = Vec::new(); + fn walk(v: usize, after: &[Vec], state: &mut [u8], back: &mut Vec<(usize, usize)>) { + state[v] = 1; + for &next in &after[v] { + match state[next] { + 0 => walk(next, after, state, back), + 1 => back.push((v, next)), + _ => {} + } + } + state[v] = 2; + } + for v in 0..vertices { + if state[v] == 0 { + walk(v, &after, &mut state, &mut back); + } + } + let forward: Vec<(usize, usize)> = edges + .iter() + .copied() + .filter(|e| !back.contains(e)) + .collect(); + let mut column: Vec = (0..vertices).map(|v| usize::from(v >= inputs)).collect(); + // The longest path, by relaxing every edge as many times as there are + // vertices: a graph this small needs no cleverer order. + for _ in 0..vertices { + for &(from, to) in &forward { + if to >= inputs { + column[to] = column[to].max(column[from] + 1); + } + } + } + column +} + +/// The row of every vertex within its column, ordered so that each sits +/// near what it is linked to: a few sweeps, each sorting a column by the +/// mean row of its neighbours. +fn rows(columns: &[usize], edges: &[(usize, usize)]) -> Vec { + let n = columns.len(); + let mut row = vec![0.0f32; n]; + let count = columns.iter().copied().max().unwrap_or(0) + 1; + let mut members: Vec> = vec![Vec::new(); count]; + for v in 0..n { + members[columns[v]].push(v); + } + for list in &members { + for (r, &v) in list.iter().enumerate() { + row[v] = r as f32; + } + } + for _ in 0..6 { + for list in &mut members { + let mean = |v: usize| { + let (sum, k) = edges + .iter() + .filter_map(|&(a, b)| match (a == v, b == v) { + (true, false) => Some(row[b]), + (false, true) => Some(row[a]), + _ => None, + }) + .fold((0.0, 0), |(s, k), r| (s + r, k + 1)); + if k == 0 { row[v] } else { sum / k as f32 } + }; + let mut keyed: Vec<(f32, usize)> = list.iter().map(|&v| (mean(v), v)).collect(); + keyed.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); + *list = keyed.into_iter().map(|(_, v)| v).collect(); + for (r, &v) in list.iter().enumerate() { + row[v] = r as f32; + } + } + } + row.into_iter().map(|r| r as usize).collect() +} + +/// What a click on the diagram asked for. +pub enum Clicked { + /// Nothing. + Nothing, + /// The protein with this index. + Node(usize), +} + +/// Draw the diagram, scaled to fit `width`, and say what was clicked. +/// +/// `levels` are the proteins' levels, `reads` the inputs' values by name, +/// `badges` a short role label per protein, and `chosen` the protein the +/// tissue is coloured by, if one is. +#[allow(clippy::too_many_arguments)] +pub fn draw( + ui: &mut egui::Ui, + layout: &Layout, + names: &[String], + levels: &[f64], + links: &[Link], + reads: &dyn Fn(&str) -> f64, + badges: &[Option<(String, bool)>], + chosen: Option, + explain: &dyn Fn(usize) -> String, +) -> Clicked { + let scale = (ui.available_width() / layout.size.x).min(1.0); + let (whole, _) = ui.allocate_exact_size(layout.size * scale, Sense::hover()); + let painter = ui.painter_at(whole); + let at = |p: Pos2| whole.min + (p.to_vec2() * scale); + let half = BOX * scale / 2.0; + let boxed = |v: usize| Rect::from_center_size(at(layout.centres[v]), BOX * scale); + let inputs = layout.inputs.len(); + + // Arrows first, under the boxes. + for link in links { + let Some(from) = layout.source_of(link, names) else { + continue; + }; + let to = inputs + link.node; + if from == to { + continue; + } + let strength = ((link.now.abs() / FULL_PUSH) as f32).min(1.0); + let (colour, dashed, bar) = match link.kind { + "activated_by" | "produced_by" => (ACTIVATES, false, false), + "activated_by_absence_of" => (ACTIVATES, true, false), + "inhibited_by" => (INHIBITS, false, true), + _ => (DAMAGES, true, true), + }; + let colour = colour.gamma_multiply(0.35 + 0.65 * strength); + let stroke = Stroke::new((1.0 + 3.5 * strength) * scale.max(0.6), colour); + let (a, b) = (at(layout.centres[from]), at(layout.centres[to])); + let forward = layout.columns[to] > layout.columns[from]; + let points = if forward { + let start = a + Vec2::new(half.x, 0.0); + let end = b - Vec2::new(half.x + 4.0 * scale, 0.0); + let bend = (end.x - start.x) / 2.0; + [ + start, + start + Vec2::new(bend, 0.0), + end - Vec2::new(bend, 0.0), + end, + ] + } else { + // A loop back, under both boxes. + let start = a + Vec2::new(0.0, half.y); + let end = b + Vec2::new(0.0, half.y + 4.0 * scale); + let drop = Vec2::new(0.0, 0.9 * ROW * scale); + [start, start + drop, end + drop, end] + }; + let curve = egui::epaint::CubicBezierShape::from_points_stroke( + points, + false, + Color32::TRANSPARENT, + stroke, + ) + .flatten(Some(0.5)); + if dashed { + painter.extend(Shape::dashed_line(&curve, stroke, 5.0 * scale, 4.0 * scale)); + } else { + painter.add(Shape::line(curve.clone(), stroke)); + } + let (Some(&tip), Some(&before)) = (curve.last(), curve.iter().rev().nth(2)) else { + continue; + }; + let along = (tip - before).normalized(); + let across = along.rot90(); + let size = (5.0 + 2.0 * strength) * scale.max(0.6); + if bar { + painter.line_segment([tip + across * size, tip - across * size], stroke); + } else { + painter.add(Shape::convex_polygon( + vec![ + tip + along * size, + tip + across * size * 0.7, + tip - across * size * 0.7, + ], + colour, + Stroke::NONE, + )); + } + } + + let font = |size: f32| egui::FontId::proportional(size * scale.max(0.7)); + let mut clicked = Clicked::Nothing; + for (i, input) in layout.inputs.iter().enumerate() { + let rect = boxed(i); + let value = reads(input); + painter.rect_filled(rect, rect.height() / 2.0, fill(value)); + painter.text( + rect.center(), + egui::Align2::CENTER_CENTER, + format!("{}\n{value:.2}", label(input)), + font(12.5), + ink(value), + ); + ui.interact(rect, ui.id().with(("input", i)), Sense::hover()) + .on_hover_text(format!( + "{}: read from outside the cell, {value:.2} where it sits now.", + label(input) + )); + } + for (n, name) in names.iter().enumerate() { + let rect = boxed(inputs + n); + let value = levels.get(n).copied().unwrap_or(0.0); + painter.rect_filled(rect, 5.0 * scale, fill(value)); + if chosen == Some(n) { + painter.rect_stroke( + rect.expand(2.0), + 6.0 * scale, + Stroke::new(2.0, Color32::WHITE), + egui::StrokeKind::Outside, + ); + } + painter.text( + rect.center(), + egui::Align2::CENTER_CENTER, + format!("{}\n{value:.2}", label(name)), + font(13.0), + ink(value), + ); + if let Some(Some((badge, on))) = badges.get(n) { + painter.text( + rect.center_bottom() + Vec2::new(0.0, 2.0), + egui::Align2::CENTER_TOP, + badge, + font(11.5), + if *on { + Color32::from_rgb(255, 210, 120) + } else { + Color32::from_gray(150) + }, + ); + } + let response = ui + .interact(rect, ui.id().with(("node", n)), Sense::click()) + .on_hover_text(explain(n)); + if response.clicked() { + clicked = Clicked::Node(n); + } + } + clicked +} + +/// The colour of a level, the ramp the tissue's protein view uses, so that +/// a box and the cells coloured by the same protein match. +fn fill(value: f64) -> Color32 { + let [r, g, b, _] = paint::bytes(paint::ramp(value as f32)); + Color32::from_rgb(r, g, b) +} + +/// Text that reads on that colour: dark on the bright end of the ramp. +fn ink(value: f64) -> Color32 { + if value > 0.72 { + Color32::from_gray(20) + } else { + Color32::from_gray(235) + } +} + +/// How a protein or an input is written for a reader rather than in a +/// file: the usual name where there is one, the file's name otherwise. +pub fn label(name: &str) -> String { + match name { + "oxygen" => "O₂", + "egf" => "EGF", + "crowding" => "crowding", + "stress" => "stress", + "waste" => "waste", + "necrotic_factor" => "necrotic f.", + "egfr" => "EGFR", + "ras" => "RAS", + "raf" => "RAF", + "mek" => "MEK", + "erk" => "ERK", + "hif1" => "HIF-1α", + "vegf" => "VEGF", + "bcl2" => "BCL2", + "bax" => "BAX", + "mdm2" => "MDM2", + "notch" => "NOTCH", + "rb" => "RB", + "e2f" => "E2F", + "cyclin_d" => "cyclin D", + "cyclin_e" => "cyclin E", + "pdl1" => "PD-L1", + other => other, + } + .to_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn link(node: usize, source: &str) -> Link { + Link { + node, + kind: "activated_by", + source: Some(source.to_owned()), + rate: 1.0, + now: 0.0, + } + } + + #[test] + fn a_relay_steps_one_column_further_and_a_loop_back_does_not_push_it() { + // egf -> a -> b -> c, and c back onto b. + let names: Vec = ["a", "b", "c"].iter().map(|s| (*s).to_owned()).collect(); + let links = vec![link(0, "egf"), link(1, "a"), link(2, "b"), link(1, "c")]; + let layout = Layout::of(3, &names, &links); + assert_eq!(layout.inputs, vec!["egf"]); + assert_eq!(layout.columns, vec![0, 1, 2, 3]); + } + + #[test] + fn a_node_that_reads_nothing_sits_beside_the_inputs() { + let names: Vec = ["a", "b"].iter().map(|s| (*s).to_owned()).collect(); + let links = vec![link(1, "a")]; + let layout = Layout::of(2, &names, &links); + assert!(layout.inputs.is_empty()); + assert_eq!(layout.columns, vec![1, 2]); + } +} diff --git a/viewer/src/inspect.rs b/viewer/src/inspect.rs new file mode 100644 index 0000000..3420a42 --- /dev/null +++ b/viewer/src/inspect.rs @@ -0,0 +1,846 @@ +//! One cell opened: click a cell, and a window beside the tissue shows its +//! network as it stands, every protein at its level and every link as hard +//! as it pushes, what the cell reads from where it sits, and what it does +//! with it. +//! +//! Nothing in the window is drawn for the picture's sake: every number is +//! read from the simulation, between two batches, as the census is. + +use bevy::prelude::*; +use bevy::window::PrimaryWindow; +use bevy_egui::{EguiContexts, egui}; +use cellweave_core::{CellId, CellInputs, Roles, SignalingNetwork}; +use cellweave_engine::Fate; +use cellweave_engine::cpm::OBSTACLE; +use cellweave_engine::simulation::{DEATH_THRESHOLD, DIVISION_RATIO, QUIESCENCE_THRESHOLD}; +use egui_plot::{Legend, Line, Plot, PlotPoints}; + +use crate::diagram::{self, Clicked, Layout}; +use crate::orbit::Orbit; +use crate::paint::{self, View}; +use crate::relief::Relief; +use crate::runner::Runner; + +/// Pixels the pointer may move between press and release for the two to +/// be a click on a cell rather than a turn of the camera. +const CLICK: f32 = 5.0; + +/// Readings kept at most; past this every other one is dropped, as the +/// panel's history is. +const HISTORY_LIMIT: usize = 1500; + +/// How quickly the camera catches up with the cell it follows, per second. +const FOLLOW: f32 = 4.0; + +/// How high above the tissue the halo around the open cell floats, in +/// pixels: over the tallest dome a living cell makes. +const HALO_HEIGHT: f32 = 6.5; + +/// How bright the halo is, in HDR units: enough to bloom. +const HALO_GLOW: f32 = 6.0; + +/// How wide the window opens: room at full size for a network of nine +/// columns, the fuller cell's. +const WIDTH: f32 = 860.0; + +/// One term of the cell's network, as it stood when last read. +#[derive(Debug, Clone)] +pub struct Link { + /// The node it moves, by index. + pub node: usize, + /// Its kind, as a network file names it. + pub kind: &'static str, + /// What it reads, by name, if anything. + pub source: Option, + /// Its rate. + pub rate: f64, + /// What it adds to the node's rate of change. + pub now: f64, +} + +/// The cell as it was last read. +#[derive(Debug, Clone)] +pub struct Reading { + /// The step it was read at. + pub mcs: u64, + /// Its proteins, by name, and their levels. + pub names: Vec, + pub levels: Vec, + /// Every term, as it pushes. + pub links: Vec, + /// What it reads from where it sits. + pub inputs: CellInputs, + /// What it is doing; `None` once it is gone. + pub fate: Option, + /// Its size, what it is trying to be, and the size its lineage divides + /// against. + pub volume: u32, + pub target: u32, + pub reference: u32, + /// Its clone. + pub clone: Option, + /// Its centre, in pixels. + pub centre: Option, +} + +/// Which cell is open, and what was read of it. +#[derive(Resource, Default)] +pub struct Inspected { + /// The run it belongs to, by its place on screen, and the cell. + pub cell: Option<(usize, CellId)>, + /// A pixel clicked, waiting for its run to be back from the pool to say + /// which cell holds it. + clicked: Option<(usize, u32, u32)>, + /// Keep the camera on the cell. + pub follow: bool, + /// The latest reading, kept once the cell is gone. + pub reading: Option, + /// Every reading's levels, oldest first. + pub history: Vec<(u64, Vec)>, + /// The generation last read. + seen: Option, + /// Where a press of the left button began. + pressed_at: Option, + /// A pixel of the first run to open once it reaches a step, asked for + /// on the command line. + opening: Option<(u32, u32, u64)>, + /// Where the window's left edge is, as a share of the screen's width, + /// so that a cell followed can be kept in what it leaves uncovered. + covered_from: Option, +} + +impl Inspected { + /// The cell open in the run at `index`, if there is one. + pub fn in_run(&self, index: usize) -> Option { + self.cell.filter(|(i, _)| *i == index).map(|(_, id)| id) + } + + /// Open the cell under pixel `(x, y)` of the first run once it reaches + /// `step`, following it with the camera if `follow`. + pub fn opening(self, x: u32, y: u32, step: u64, follow: bool) -> Self { + Self { + opening: Some((x, y, step)), + follow, + ..self + } + } + + fn close(&mut self) { + self.cell = None; + self.reading = None; + self.history.clear(); + self.seen = None; + self.follow = false; + } +} + +/// A click that does not drag picks the pixel under the pointer, on +/// whichever run it falls; the cell holding it is found once that run is +/// back from the pool. +#[allow(clippy::too_many_arguments)] +pub fn pick( + buttons: Res>, + windows: Query<&Window, With>, + cameras: Query<(&Camera, &GlobalTransform), With>, + sides: Query<(&Runner, &Relief, &GlobalTransform)>, + mut contexts: EguiContexts, + mut inspected: ResMut, +) -> Result { + let Ok(window) = windows.single() else { + return Ok(()); + }; + let Some(cursor) = window.cursor_position() else { + return Ok(()); + }; + let ctx = contexts.ctx_mut()?; + if ctx.is_pointer_over_egui() || ctx.egui_wants_pointer_input() { + inspected.pressed_at = None; + return Ok(()); + } + if buttons.just_pressed(MouseButton::Left) { + inspected.pressed_at = Some(cursor); + } + if !buttons.just_released(MouseButton::Left) { + return Ok(()); + } + let Some(start) = inspected.pressed_at.take() else { + return Ok(()); + }; + if start.distance(cursor) > CLICK { + return Ok(()); + } + let Ok((camera, eye)) = cameras.single() else { + return Ok(()); + }; + let Ok(ray) = camera.viewport_to_world(eye, cursor) else { + return Ok(()); + }; + match hit(ray, &sides) { + Some(pixel) => inspected.clicked = Some(pixel), + None => inspected.close(), + } + Ok(()) +} + +/// The first pixel of any run's surface the ray meets, and the run's +/// place: a march down the ray from above the tallest dome to the plane, +/// stopping where it passes under the surface. +fn hit( + ray: Ray3d, + sides: &Query<(&Runner, &Relief, &GlobalTransform)>, +) -> Option<(usize, u32, u32)> { + let (origin, direction) = (ray.origin, *ray.direction); + if direction.y >= 0.0 { + return None; + } + let top = 10.0; + let t0 = ((top - origin.y) / direction.y).max(0.0); + let t1 = -origin.y / direction.y; + let steps = 400; + for k in 0..=steps { + let point = origin + direction * (t0 + (t1 - t0) * k as f32 / steps as f32); + for (runner, relief, place) in sides { + let (w, h) = relief.size(); + let local = point - place.translation(); + let x = local.x + w as f32 / 2.0; + let y = local.z + h as f32 / 2.0; + if x < 0.0 || y < 0.0 || x >= w as f32 || y >= h as f32 { + continue; + } + let (x, y) = (x as usize, y as usize); + if point.y <= relief.height(x, y) + 0.05 { + return Some((runner.index, x as u32, y as u32)); + } + } + } + None +} + +/// Read the open cell, each time its run is back from the pool with a new +/// state, and find the cell a click asked for. +pub fn read(runners: Query<&Runner>, mut inspected: ResMut) { + if let Some((x, y, step)) = inspected.opening + && runners + .iter() + .find(|r| r.index == 0) + .and_then(Runner::latest) + .is_some_and(|m| m.mcs >= step) + { + inspected.opening = None; + inspected.clicked = Some((0, x, y)); + } + if let Some((index, x, y)) = inspected.clicked { + let Some(runner) = runners.iter().find(|r| r.index == index) else { + inspected.clicked = None; + return; + }; + let Some(sim) = runner.idle() else { + return; + }; + inspected.clicked = None; + let occupant = sim.lattice().occupant(x, y); + let id = CellId(occupant); + if occupant == 0 || occupant == OBSTACLE || sim.network(id).is_none() { + inspected.close(); + return; + } + let follow = inspected.follow; + inspected.close(); + inspected.cell = Some((index, id)); + inspected.follow = follow; + } + + let Some((index, id)) = inspected.cell else { + return; + }; + let Some(runner) = runners.iter().find(|r| r.index == index) else { + return; + }; + if inspected + .seen + .is_some_and(|seen| runner.restarted_since(seen)) + { + inspected.close(); + return; + } + let Some(sim) = runner.idle() else { + return; + }; + if inspected.seen == Some(runner.generation()) { + return; + } + inspected.seen = Some(runner.generation()); + let mcs = runner.latest().map_or(0, |m| m.mcs); + + let (Some(net), Some(inputs)) = (sim.network(id), sim.inputs(id)) else { + // Gone: the last reading stays, marked as such. + if let Some(reading) = inspected.reading.as_mut() { + reading.fate = None; + } + return; + }; + let lattice = sim.lattice(); + let (w, _) = lattice.dims(); + let pixels = lattice.pixels_of(&[id]).pop().unwrap_or_default(); + let centre = (!pixels.is_empty()).then(|| { + let sum = pixels.iter().fold(Vec2::ZERO, |sum, &i| { + sum + Vec2::new((i % w as usize) as f32, (i / w as usize) as f32) + }); + sum / pixels.len() as f32 + }); + let levels: Vec = net.state().values.iter().map(|c| c.0).collect(); + let reading = Reading { + mcs, + names: net.node_names().to_vec(), + levels: levels.clone(), + links: net + .influences(&inputs) + .into_iter() + .map(|i| Link { + node: i.node, + kind: i.kind, + source: i.source.map(str::to_owned), + rate: i.rate, + now: i.now, + }) + .collect(), + inputs, + fate: sim.fate(id), + volume: lattice.volume(id).map_or(0, |v| v.0), + target: lattice.target_volume(id).map_or(0, |v| v.0), + reference: net.reference_volume(), + clone: sim.clone_of(id).map(|c| c.0), + centre, + }; + inspected.reading = Some(reading); + inspected.history.push((mcs, levels)); + if inspected.history.len() > HISTORY_LIMIT { + let last = inspected.history.len() - 1; + let mut k = 0; + inspected.history.retain(|_| { + let keep = k % 2 == 0 || k == last; + k += 1; + keep + }); + } +} + +/// A ring of light over the open cell, so it can be found in the tissue at +/// any zoom: the white membrane alone is lost on a dome seen from afar. +#[derive(Component)] +pub struct Halo; + +/// Make the halo, hidden until a cell is opened. +pub fn spawn_halo( + mut commands: Commands, + mut meshes: ResMut>, + mut materials: ResMut>, +) { + commands.spawn(( + Halo, + Mesh3d(meshes.add(Annulus::new(0.82, 1.0))), + // Unlit, its colour is what it gives off: above one, it blooms. + MeshMaterial3d(materials.add(StandardMaterial { + base_color: Color::linear_rgb(HALO_GLOW, HALO_GLOW * 0.85, HALO_GLOW * 0.55), + unlit: true, + ..default() + })), + // An annulus lies in the plane facing +Z; the tissue faces +Y. + Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)), + Visibility::Hidden, + )); +} + +/// Put the halo over the open cell, as wide as the cell, easing towards +/// where the cell has moved since the last batch. +pub fn halo( + time: Res