Skip to main content

dualis_core/
sim.rs

1//! Running several domains at once.
2//!
3//! A domain is a piece of physics that can be stepped: heat in a block of glass,
4//! a rigid body under contact, light through a train of surfaces. Each one knows
5//! its own equations and nothing about the others. This module is how they share
6//! a clock and a budget without knowing about each other.
7//!
8//! # The timescale problem, which is the real one
9//!
10//! Domains do not agree on how big a step is. An explicit FDTD electromagnetic
11//! solver on a nanometre grid is stable to about 10⁻¹⁷ s; heat conduction to about
12//! 10⁻⁹ s; rigid contact to 10⁻⁴ s; and a thermal drift that defocuses an
13//! instrument plays out over seconds. Stepping all of them at the smallest limit
14//! integrates the slow ones ten billion times for nothing.
15//!
16//! Two mechanisms deal with that, and they are the reason this module is not just
17//! a `for` loop over domains:
18//!
19//! - **[`Kind::QuasiStatic`]** — a domain with no state to roll forward, which is
20//!   re-solved on demand instead of stepped. Light crosses an instrument in
21//!   nanoseconds; against a thermal timescale that is zero, so optics is not
22//!   integrated at all. This is the largest single saving available, and it is
23//!   what the closed-form [`Motion`](crate::motion::Motion) and the instantaneous
24//!   `SurfaceOptics` were already doing before there was a scheduler to notice.
25//! - **[`Schedule::Multirate`]** — each evolving domain takes as many equal
26//!   substeps of the shared window as its own stability limit requires, so the
27//!   slow domain is not dragged down to the fast one's step.
28//!
29//! # Coupling, and why it goes through a bus
30//!
31//! Domains never touch each other. They publish to and consume from an
32//! [`Exchange`], which is a set of named channels carrying SI amounts. That is not
33//! only a borrow-checker convenience: it is what makes the transfer *auditable*.
34//! Each domain conserves energy internally, but the interface between two
35//! discretisations of the same surface — ray hits on one side, mesh nodes on the
36//! other — is exactly where interpolation quietly loses or invents some. The bus
37//! compares what was published against what was consumed and refuses to let the
38//! difference pass silently.
39//!
40//! # What the schedules cost
41//!
42//! [`Schedule::OneWay`] is unconditionally stable and embarrassingly parallel,
43//! because nothing feeds back. [`Schedule::Staggered`] costs one exchange per
44//! step and is stable only while the coupling is weak — and *not* fixable by
45//! shrinking `dt`, since some strongly coupled systems (the standard example is
46//! fluid-structure interaction at comparable densities, the added-mass effect)
47//! become more unstable as the step shrinks. That is what
48//! [`Schedule::Iterative`] is for, and why it is worth its cost.
49
50use std::any::Any;
51use std::collections::BTreeMap;
52
53use dualis_units::Time;
54
55use crate::bodies::Bodies;
56use crate::conserved::{audit_with, Ledger, Tolerances, Violation};
57use crate::field::ScalarField;
58use crate::integrator::substeps_for;
59use crate::scene::{mismatch, Flux, Interface};
60
61/// Whether a domain has state to roll forward.
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub enum Kind {
64    /// Has state, and a stability limit on how far it can be stepped at once.
65    Evolving,
66    /// Has no state: solved from its inputs whenever asked, in zero time. Optics,
67    /// a static load, an equilibrium reaction. Never subcycled — a solve is a
68    /// solve.
69    QuasiStatic,
70}
71
72/// One piece of physics.
73///
74/// The only required methods are the name and the step; the rest have defaults
75/// that describe a well-behaved evolving domain with no stability limit and no
76/// books to keep.
77pub trait Domain {
78    /// What this domain is called. Used to look it up and to name it in a violation.
79    ///
80    /// Borrowed rather than `&'static str`, so a name can come from a scene file. That was
81    /// the first thing the workspace's own application could not do: every constructor
82    /// wanted a compile-time name and the name it had was a `String` read off disk, so it
83    /// leaked one per domain to get past the signature.
84    fn name(&self) -> &str;
85
86    /// Whether it has state to roll forward. Defaults to [`Kind::Evolving`].
87    fn kind(&self) -> Kind {
88        Kind::Evolving
89    }
90
91    /// The largest step this domain can take from `now` and stay stable — a CFL
92    /// condition, a diffusion limit, a contact penetration budget.
93    ///
94    /// Infinite means "no limit", which is the honest answer for a quasi-static
95    /// domain and for a linear one being solved implicitly.
96    fn max_stable_dt(&self, now: Time) -> Time {
97        let _ = now;
98        Time::from_si(f64::INFINITY)
99    }
100
101    /// Advance by `dt` from `t`, reading inputs from `bus` and publishing outputs
102    /// to it. A quasi-static domain ignores `dt`.
103    ///
104    /// Must be a pure function of its state and its inputs: no wall clock, no
105    /// unordered reduction, no shared generator. [`Rng::for_index`](crate::Rng::for_index)
106    /// is how a domain gets randomness without giving that up.
107    fn step(&mut self, t: Time, dt: Time, bus: &mut Exchange) -> Result<(), Violation>;
108
109    /// How far this domain still is from agreeing with its neighbours, for
110    /// [`Schedule::Iterative`]. Zero means converged.
111    fn residual(&self) -> f64 {
112        0.0
113    }
114
115    /// What this domain is holding, for the conservation audit.
116    fn ledger(&self) -> Ledger {
117        Ledger::new()
118    }
119
120    /// Save state so an iterative sweep can be re-run from the same starting
121    /// point. A domain that does not implement this cannot take part in
122    /// [`Schedule::Iterative`], and [`Simulation::advance`] says so rather than
123    /// silently iterating from the wrong state.
124    fn checkpoint(&mut self) {}
125
126    /// Restore the last [`Domain::checkpoint`].
127    fn restore(&mut self) {}
128
129    /// Whether this domain's books are **exact**: its ledger changes by precisely what it takes
130    /// from the bus minus what it publishes, every step.
131    ///
132    /// # Why this is opt-in, and what it buys
133    ///
134    /// The whole-simulation audit sums every domain's ledger before comparing, so it can only see
135    /// a leak that moves the *total*. A molecular fluid holding a kilojoule and an acoustic room
136    /// holding a microjoule are checked together, and the room could lose everything it has
137    /// without the sum noticing. That is the limit `ARCHITECTURE.md` records against rule 4, and
138    /// it is not a tolerance problem — no tolerance separates them, because the scale is wrong.
139    ///
140    /// A domain that says `true` here is checked **on its own**, against its own holdings, every
141    /// step. The scheduler visits domains one at a time, so the traffic on the bus between the
142    /// call before and the call after is attributable to exactly that domain.
143    ///
144    /// # Why it is not the default
145    ///
146    /// Not every honest ledger is an exact one. A domain that loses heat to an environment which
147    /// is not on the bus is not leaking — it is modelling a boundary — but its books do not
148    /// balance against bus traffic alone, and saying `true` would make a correct domain fail.
149    /// `LumpedMass` with a convective loss is exactly that case.
150    ///
151    /// So it is a claim a domain makes about itself, and the ones that make it are held to it.
152    fn books_balance(&self) -> bool {
153        false
154    }
155
156    /// Whether [`Domain::checkpoint`] and [`Domain::restore`] actually do something.
157    ///
158    /// [`Schedule::Iterative`] refuses to run a domain that says no, rather than iterating
159    /// from the wrong state and reporting a residual that means nothing.
160    fn supports_restore(&self) -> bool {
161        false
162    }
163
164    /// This domain as [`Any`], so a caller can get the concrete type back out of a
165    /// [`Simulation`] — see [`Simulation::domain_as`].
166    ///
167    /// Opt-in, and returning `None` by default, because it cannot be automatic. Deriving it
168    /// from the trait would need `Domain: Any` plus upcasting `dyn Domain` to `dyn Any`,
169    /// which is a newer Rust than this crate promises. A domain that wants to be inspected
170    /// writes `fn as_any(&self) -> Option<&dyn Any> { Some(self) }` and is done.
171    ///
172    /// The coupling never needs this: domains meet through [`Exchange`] and nothing else,
173    /// which is the property the whole design rests on. What needs it is everything *around*
174    /// the simulation — a test asserting a temperature profile, a visualiser drawing one —
175    /// and that is a reader, not a participant.
176    fn as_any(&self) -> Option<&dyn Any> {
177        None
178    }
179
180    /// The same, mutably, so a caller can *write* to a domain between steps.
181    ///
182    /// **This does not weaken "domains never read each other."** That rule is about what happens
183    /// inside [`Domain::step`], where the only channel is [`Exchange`]. This is the owner of the
184    /// simulation, outside the step loop, holding `&mut Simulation` already — it could drop the
185    /// domain and rebuild it, so denying it a write was never protecting anything.
186    ///
187    /// What needs it is a feedback loop the bus cannot carry. A copper winding's resistance rises
188    /// with its temperature, and that temperature lives in a thermal domain: neither can see the
189    /// other's state, and neither should. A caller between frames can see both, and until this
190    /// existed it could read one and not write the other, which made the loop unclosable from
191    /// anywhere at all.
192    ///
193    /// Opt-in and `None` by default, like [`Domain::as_any`] — and that default is a hazard this
194    /// workspace has been bitten by twice, in `FRICTION.md` findings 7 and 12: a domain that
195    /// forgets it is not broken, it is silently absent from whatever asks. If you implement
196    /// `as_any`, implement this beside it.
197    fn as_any_mut(&mut self) -> Option<&mut dyn Any> {
198        None
199    }
200
201    /// This domain as a [`ScalarField`], if it has one to show.
202    ///
203    /// Opt-in and `None` by default, in the same style as [`Domain::as_any`] and for a
204    /// sharper reason than that one. `ScalarField` was written as the interface a visualiser
205    /// would read a simulation through, and then a visualiser found it unreachable: it holds
206    /// `&dyn Domain`, and there was no way to ask that for a field. So it downcast to
207    /// concrete types instead and knew every domain by name — precisely what the interface
208    /// existed to avoid.
209    ///
210    /// A domain with a field writes `fn as_field(&self) -> Option<&dyn ScalarField>
211    /// { Some(self) }`. See [`Simulation::field`].
212    fn as_field(&self) -> Option<&dyn ScalarField> {
213        None
214    }
215
216    /// The named scalars this domain reports, for a table, a chart or a caption.
217    ///
218    /// **The number a domain has when it has no picture.** A source has a remaining tank, a
219    /// winding has a dissipation, a thermal network has a temperature per node — and for several
220    /// of those the scalar *is* the result. `as_field` covers the domains that are continua and
221    /// there was no counterpart for the rest, so a caller wanting them had to know every domain
222    /// by name and downcast to each.
223    ///
224    /// That is what makes this a trait method rather than a function somewhere above: a layer
225    /// that collects readings by matching on domain types has to be edited every time a physics
226    /// is added, which is the one thing this workspace's structure exists to avoid.
227    ///
228    /// Return what the domain is *for* rather than a uniform summary. A mean over a pressure
229    /// field is zero by symmetry and would be a column of noise; the peak is the number a reader
230    /// wants. Nobody but the domain knows which.
231    ///
232    /// Empty by default, and opt-in like [`as_any`](Domain::as_any) and
233    /// [`as_field`](Domain::as_field) — with the hazard `as_any` has already taught once: four
234    /// mechanics domains never opted into it, and an orbit scene ran, conserved, and drew nothing
235    /// at all. A domain that forgets this one is silently absent from every table, not broken.
236    fn readings(&self) -> Vec<Reading> {
237        Vec::new()
238    }
239
240    /// This domain as a countable set of bodies, if that is what it is.
241    ///
242    /// The counterpart to [`as_field`](Domain::as_field), and between them they cover both kinds
243    /// of thing a domain can be. A caller wanting to draw, measure or export no longer has to
244    /// name `NBody`, `ContactSystem` or `Fluid` — which it did for months, recorded as
245    /// `FRICTION.md` finding 11, until splitting the layers made it unpayable.
246    ///
247    /// Opt-in and `None` by default, with the hazard that default has now taught three times: a
248    /// domain that forgets is silently absent rather than broken.
249    fn as_bodies(&self) -> Option<&dyn Bodies> {
250        None
251    }
252}
253
254/// Delegation, so a domain chosen at run time can be added like any other.
255///
256/// Without this a caller holding `Box<dyn Domain>` — which is what building from data
257/// produces — could not hand it to [`Simulation::with`], even though the simulation stores
258/// exactly that internally. Prefer [`Simulation::with_boxed`], which avoids boxing the box;
259/// this impl is here so that generic code over `impl Domain` works on a boxed one too.
260impl Domain for Box<dyn Domain> {
261    fn name(&self) -> &str {
262        (**self).name()
263    }
264    fn kind(&self) -> Kind {
265        (**self).kind()
266    }
267    fn max_stable_dt(&self, now: Time) -> Time {
268        (**self).max_stable_dt(now)
269    }
270    fn step(&mut self, t: Time, dt: Time, bus: &mut Exchange) -> Result<(), Violation> {
271        (**self).step(t, dt, bus)
272    }
273    fn residual(&self) -> f64 {
274        (**self).residual()
275    }
276    fn ledger(&self) -> Ledger {
277        (**self).ledger()
278    }
279    fn checkpoint(&mut self) {
280        (**self).checkpoint()
281    }
282    fn restore(&mut self) {
283        (**self).restore()
284    }
285    fn supports_restore(&self) -> bool {
286        (**self).supports_restore()
287    }
288    fn as_any_mut(&mut self) -> Option<&mut dyn Any> {
289        (**self).as_any_mut()
290    }
291    fn readings(&self) -> Vec<Reading> {
292        (**self).readings()
293    }
294    fn books_balance(&self) -> bool {
295        (**self).books_balance()
296    }
297    fn as_bodies(&self) -> Option<&dyn Bodies> {
298        (**self).as_bodies()
299    }
300    fn as_any(&self) -> Option<&dyn Any> {
301        (**self).as_any()
302    }
303    fn as_field(&self) -> Option<&dyn ScalarField> {
304        (**self).as_field()
305    }
306}
307
308/// The channel between domains: named quantities, in SI base units.
309///
310/// A domain publishes what it produced and consumes what it needs. Nothing else
311/// crosses between domains, which means every transfer is in one place and can be
312/// checked in one place.
313#[derive(Clone, Debug, Default)]
314pub struct Exchange {
315    published: BTreeMap<&'static str, f64>,
316    consumed: BTreeMap<&'static str, f64>,
317    /// Channels that carry a place as well as an amount, keyed by
318    /// `(interface name, channel)` so the audit reports them in a fixed order.
319    spatial: BTreeMap<(String, &'static str), Flux>,
320    spatial_consumed: BTreeMap<(String, &'static str), f64>,
321    /// The outer step the current sweep is covering, in seconds. Zero when nobody has said —
322    /// a bare `Exchange` in a test — and [`Exchange::take_share`] falls back to taking
323    /// everything, which is the honest answer when the interval is unknown.
324    interval: f64,
325    /// How much of `interval` is still unclaimed, per channel. See `take_share`.
326    unclaimed_time: BTreeMap<&'static str, f64>,
327    /// How many separate `take` calls each channel saw this step.
328    ///
329    /// Counted because the conservation audit structurally cannot see the failure it detects.
330    /// [`Exchange::take`] empties a channel, so a *second* consumer of the same channel gets
331    /// zero — and the books balance perfectly, because everything published was taken. Two
332    /// plates under one lamp warm at the rate of one plate, and the audit reports it clean.
333    ///
334    /// Every scene and every integration test in this workspace had at most one consumer per
335    /// channel, which is why this went unnoticed until a world with six domains was attempted.
336    takers: BTreeMap<&'static str, u32>,
337    /// Everything ever published on each channel, spatial and plain together.
338    ///
339    /// `published` is the *current offer* and is emptied every sweep; this is the running total
340    /// and is not. It exists so [`Simulation`] can attribute a step's traffic to the domain that
341    /// made it — snapshot before, snapshot after, and the difference is that domain's, because
342    /// only that domain ran in between.
343    published_total: BTreeMap<&'static str, f64>,
344}
345
346impl Exchange {
347    /// An empty bus.
348    pub fn new() -> Exchange {
349        Exchange::default()
350    }
351
352    /// Offer an amount on a channel. Repeated publishes accumulate, so several
353    /// surfaces can each contribute to one heat load.
354    pub fn publish(&mut self, channel: &'static str, si_amount: f64) {
355        *self.published.entry(channel).or_insert(0.0) += si_amount;
356        *self.published_total.entry(channel).or_insert(0.0) += si_amount;
357    }
358
359    /// Take everything on a channel, recording that it was taken. The channel is
360    /// left empty: an amount consumed twice would be an amount doubled.
361    pub fn take(&mut self, channel: &'static str) -> f64 {
362        let amount = self.published.insert(channel, 0.0).unwrap_or(0.0);
363        *self.consumed.entry(channel).or_insert(0.0) += amount;
364        *self.takers.entry(channel).or_insert(0) += 1;
365        amount
366    }
367
368    /// Look without taking.
369    pub fn peek(&self, channel: &'static str) -> f64 {
370        self.published.get(channel).copied().unwrap_or(0.0)
371    }
372
373    /// Take the share of a channel that belongs to a substep of length `dt`.
374    ///
375    /// For a domain that subcycles. [`Exchange::take`] empties the channel, which is right for
376    /// a domain stepping once per interval and wrong for one stepping many times: a publisher
377    /// offers a whole outer step's worth at once, so the first substep would take all of it and
378    /// the rest would find the channel dark. Every joule of the interval then lands at its
379    /// beginning, and **refining the substep stops improving the answer** — see
380    /// [`Schedule::Multirate`], where the measured error is 26% at a 300 s outer step whatever
381    /// the substep count.
382    ///
383    /// The share is taken against the time *remaining*, not against the whole interval. That is
384    /// what makes it exact: after handing out `A·dt/T` and reducing both, `A/T` is unchanged, so
385    /// the last substep — which asks for at least what is left — receives the remainder and the
386    /// channel ends empty to the last bit. Apportioning against the whole interval instead
387    /// leaves `O(n·ε·A)` stranded, and [`Exchange::audit_transfers`] uses an absolute tolerance
388    /// that would eventually refuse it.
389    ///
390    /// Falls back to [`Exchange::take`] when the interval is unknown, so a domain written
391    /// against this works unchanged under a bare `Exchange` and under
392    /// [`Schedule::Staggered`], where it steps once and the share is the whole.
393    pub fn take_share(&mut self, channel: &'static str, dt: Time) -> f64 {
394        let h = dt.to_si();
395        if self.interval <= 0.0 || !h.is_finite() || h <= 0.0 {
396            return self.take(channel);
397        }
398        let left = *self.unclaimed_time.entry(channel).or_insert(self.interval);
399        // The last substep asks for everything that is left, and gets it. Compared with a
400        // slack of `1e-12` of the interval rather than exactly, because `n` substeps of `dt/n`
401        // do not sum to `dt` in binary: three of a third leave a residue one ulp wide, and an
402        // exact comparison misses the final share and strands it on the channel.
403        if h >= left || left - h <= self.interval * 1e-12 {
404            self.unclaimed_time.insert(channel, 0.0);
405            return self.take(channel);
406        }
407        let amount = self.published.get(channel).copied().unwrap_or(0.0);
408        let share = amount * h / left;
409        self.unclaimed_time.insert(channel, left - h);
410        *self.published.entry(channel).or_insert(0.0) -= share;
411        *self.consumed.entry(channel).or_insert(0.0) += share;
412        share
413    }
414
415    /// Tell the bus what interval the current sweep covers, so [`Exchange::take_share`] can
416    /// apportion. Called by [`Simulation::advance`]; a standalone `Exchange` need not.
417    pub fn covering(&mut self, dt: Time) {
418        self.interval = dt.to_si().max(0.0);
419        self.unclaimed_time.clear();
420        self.takers.clear();
421    }
422
423    /// Offer an amount that knows where on a boundary it landed.
424    ///
425    /// The spatial counterpart of [`publish`](Exchange::publish), and the reason
426    /// [`scene`](crate::scene) exists: a coating absorbs where the beam is, and a lumped
427    /// number cannot say that. Repeated publishes accumulate face by face, so two
428    /// mechanisms heating the same surface add up in place.
429    ///
430    /// Refuses a [`Flux`] whose face count does not match the interface. Silently padding
431    /// or truncating would put energy on the wrong part of the boundary, which is worse
432    /// than losing it — losing it the audit would catch.
433    pub fn publish_on(
434        &mut self,
435        interface: &Interface,
436        channel: &'static str,
437        flux: &Flux,
438    ) -> Result<(), Violation> {
439        if flux.faces() != interface.faces() {
440            return Err(mismatch(
441                &format!("publish on {}/{channel}", interface.name()),
442                interface.faces(),
443                flux.faces(),
444            ));
445        }
446        let key = (interface.name().to_string(), channel);
447        // Counted on the same running total as a plain publish. A spatial amount is still an
448        // amount; where it landed is the interface's business and not the ledger's.
449        *self.published_total.entry(channel).or_insert(0.0) += flux.total();
450        match self.spatial.get_mut(&key) {
451            Some(existing) => existing.add(flux),
452            None => {
453                self.spatial.insert(key, flux.clone());
454                Ok(())
455            }
456        }
457    }
458
459    /// Take everything offered on an interface's channel, leaving it empty.
460    ///
461    /// Returns zeros rather than an error when nothing was published, because a consumer
462    /// stepping a boundary that happens to be dark this step is not a fault. A face-count
463    /// disagreement *is*, and is reported: the two sides do not share a discretisation, and
464    /// the fix is [`Flux::resample`] at whichever side owns the decision.
465    pub fn take_on(
466        &mut self,
467        interface: &Interface,
468        channel: &'static str,
469    ) -> Result<Flux, Violation> {
470        let key = (interface.name().to_string(), channel);
471        // Removed rather than zeroed. A drained channel is empty, and an empty channel
472        // should not go on pinning a face count for the rest of the step — the next
473        // publisher on that boundary is entitled to its own discretisation.
474        let Some(offered) = self.spatial.remove(&key) else {
475            return Ok(Flux::zeros(interface.faces()));
476        };
477        if offered.faces() != interface.faces() {
478            // Put it back: a consumer that could not read it has not consumed it, and the
479            // audit should still see the energy sitting there unclaimed.
480            let found = offered.faces();
481            self.spatial.insert(key, offered);
482            return Err(mismatch(
483                &format!("take from {}/{channel}", interface.name()),
484                interface.faces(),
485                found,
486            ));
487        }
488        *self.spatial_consumed.entry(key).or_insert(0.0) += offered.total();
489        // And on the plain running total, so a domain that takes spatially is attributed the
490        // same way as one that takes a lump. `spatial_consumed` keeps the per-interface detail
491        // the face-by-face audit needs; this is the per-channel sum attribution wants.
492        *self.consumed.entry(channel).or_insert(0.0) += offered.total();
493        Ok(offered)
494    }
495
496    /// Look at a spatial channel without taking it.
497    pub fn peek_on(&self, interface: &Interface, channel: &'static str) -> Option<&Flux> {
498        self.spatial.get(&(interface.name().to_string(), channel))
499    }
500
501    /// Channels that were published to but never taken from, with what is left on
502    /// them. Energy sitting here at the end of a step is energy that left one
503    /// domain and arrived nowhere.
504    ///
505    /// Spatial channels appear as `"interface/channel"`, with the total left on them.
506    pub fn unclaimed(&self) -> impl Iterator<Item = (String, f64)> + '_ {
507        self.published
508            .iter()
509            .filter(|(_, v)| v.abs() > 0.0)
510            .map(|(k, v)| ((*k).to_string(), *v))
511            .chain(
512                self.spatial
513                    .iter()
514                    .filter(|(_, f)| f.total().abs() > 0.0)
515                    .map(|((i, c), f)| (format!("{i}/{c}"), f.total())),
516            )
517    }
518
519    /// Fail if anything published was not consumed.
520    ///
521    /// This is the check that catches a coupling whose two sides disagree — a
522    /// surface that absorbed 3.7 mW handing it to a mesh that received 3.4 mW
523    /// because the interpolation between their discretisations lost the rest.
524    ///
525    /// The original design said that, and then could not check it: with one number per
526    /// channel there was no discretisation to disagree about. Spatial channels close that
527    /// gap, and they are audited **face by face** rather than on their total — a
528    /// redistribution that moves heat from one side of a mirror to the other keeps the sum
529    /// exactly right, so a total-only check would pass the one bug the spatial coupling
530    /// exists to prevent. The failure names the face.
531    pub fn audit_transfers(&self, site: &str, abs_tol: f64) -> Result<(), Violation> {
532        for (channel, left) in self.published.iter() {
533            if left.abs() > abs_tol {
534                return Err(Violation {
535                    quantity: (*channel).to_string(),
536                    site: format!("{site} (published but not consumed)"),
537                    before: *left,
538                    after: 0.0,
539                    // An absolute check: the amount left on the channel *is* the
540                    // scale, because all of it went missing.
541                    scale: left.abs(),
542                    tolerance: abs_tol,
543                });
544            }
545        }
546        for ((interface, channel), flux) in self.spatial.iter() {
547            for (face, left) in flux.per_face().iter().enumerate() {
548                if left.abs() > abs_tol {
549                    return Err(Violation {
550                        quantity: format!("{interface}/{channel} face {face}"),
551                        site: format!("{site} (published but not consumed)"),
552                        before: *left,
553                        after: 0.0,
554                        scale: left.abs(),
555                        tolerance: abs_tol,
556                    });
557                }
558            }
559        }
560        Ok(())
561    }
562
563    /// Total published on a channel over the run, plain and spatial together.
564    ///
565    /// Cumulative, unlike [`Exchange::peek`], which reports what is on offer right now.
566    pub fn total_published(&self, channel: &str) -> f64 {
567        self.published_total.get(channel).copied().unwrap_or(0.0)
568    }
569
570    /// Everything each channel has carried over the run, as `(channel, published, taken)`.
571    ///
572    /// In name order, so a caller comparing two snapshots gets a stable sequence.
573    pub fn traffic(&self) -> Vec<(&'static str, f64, f64)> {
574        let mut names: Vec<&'static str> = self.published_total.keys().copied().collect();
575        for name in self.consumed.keys() {
576            if !self.published_total.contains_key(name) {
577                names.push(name);
578            }
579        }
580        names.sort_unstable();
581        names
582            .into_iter()
583            .map(|n| (n, self.total_published(n), self.total_consumed(n)))
584            .collect()
585    }
586
587    /// Total taken from a channel over the run, for reporting.
588    pub fn total_consumed(&self, channel: &str) -> f64 {
589        self.consumed.get(channel).copied().unwrap_or(0.0)
590    }
591
592    /// Total taken from a spatial channel over the run, summed over its faces.
593    pub fn total_consumed_on(&self, interface: &Interface, channel: &'static str) -> f64 {
594        self.spatial_consumed
595            .get(&(interface.name().to_string(), channel))
596            .copied()
597            .unwrap_or(0.0)
598    }
599
600    /// Empty the offers, keeping the running consumption totals.
601    pub fn clear_offers(&mut self) {
602        self.published.clear();
603        self.spatial.clear();
604        self.unclaimed_time.clear();
605        self.takers.clear();
606    }
607
608    /// How many times each channel has been taken from this sweep.
609    ///
610    /// Raw counts, because the bus cannot interpret them: a domain subcycling ten times takes
611    /// ten times, and ten domains taking once each also takes ten times. Only
612    /// [`Simulation`] knows whose turn it was, and it compares this between turns — see
613    /// `Simulation::sweep`, where the check that a channel had at most one *consumer* lives.
614    pub fn takes_per_channel(&self) -> impl Iterator<Item = (&'static str, u32)> + '_ {
615        self.takers.iter().map(|(c, n)| (*c, *n))
616    }
617}
618
619/// One named scalar from one domain at one instant.
620///
621/// Deliberately flat and owned: it crosses a layer boundary, gets written to a CSV column and a
622/// chart legend, and neither of those wants a borrow into a running simulation.
623#[derive(Clone, Debug, PartialEq)]
624pub struct Reading {
625    /// Which domain it came from. Filled in by the domain, because only it knows its own name.
626    pub domain: String,
627    /// What it is — `"mean"`, `"peak"`, `"reserve"`, a node's name.
628    pub label: String,
629    /// The value, in SI, with one exception this workspace has already made everywhere else:
630    /// temperatures are celsius, because that is the unit a column of them is read in.
631    pub value: f64,
632    /// The unit, for a header row or an axis. `&'static str` because a unit is a compile-time
633    /// fact about the quantity, not data — unlike a domain's name, which comes from a file.
634    pub unit: &'static str,
635}
636
637impl Reading {
638    /// A reading, named.
639    pub fn new(
640        domain: impl Into<String>,
641        label: impl Into<String>,
642        value: f64,
643        unit: &'static str,
644    ) -> Reading {
645        Reading {
646            domain: domain.into(),
647            label: label.into(),
648            value,
649            unit,
650        }
651    }
652}
653
654/// How the domains are interleaved.
655#[derive(Clone, Copy, Debug, PartialEq)]
656pub enum Schedule {
657    /// One pass in declared order, no feedback expected. Unconditionally stable;
658    /// the only schedule whose domains could safely run concurrently.
659    OneWay,
660    /// One pass in declared order, with each domain seeing the previous ones'
661    /// output from this step and the later ones' from the last. Cheap, and stable
662    /// only while the coupling is weak.
663    Staggered,
664    /// Repeat the pass until every domain's residual is under `tol`, or fail.
665    ///
666    /// The cost is `max_iter` passes; the benefit is stability where a staggered
667    /// scheme diverges no matter how small the step. Failing to converge is
668    /// reported as a [`Violation`] rather than accepted, because an unconverged
669    /// coupling that is allowed through is the most expensive kind of wrong
670    /// answer: it looks like physics.
671    Iterative {
672        /// Give up after this many sweeps. Reaching it is a [`Violation`], not a result.
673        max_iter: u32,
674        /// The residual every domain must fall under for the step to be accepted.
675        tol: f64,
676    },
677    /// As [`Schedule::Staggered`], but each evolving domain takes as many equal
678    /// substeps as its own stability limit needs.
679    ///
680    /// # It does not refine a coupled quantity, and the audit cannot tell you
681    ///
682    /// Read this before choosing it for accuracy, because that is the obvious reason to and it
683    /// is the wrong one.
684    ///
685    /// One domain is stepped to completion before the next. A quasi-static publisher is never
686    /// subcycled, so it puts a whole outer step's worth on the bus once; a subcycling consumer
687    /// then calls [`Exchange::take`] on its **first** substep and takes all of it. So every
688    /// joule of the interval is deposited at its beginning and decays for the rest of it, and
689    /// refining the substep does not move the answer toward the truth. Taking the limit of
690    /// `u ← u·gⁿ + (P·dt/C)·g^(n−1)` with `g = 1 − h/τ` as `n → ∞` gives
691    /// `u·e^(−dt/τ) + (P·dt/C)·e^(−dt/τ)`, which is not the solution: the error is first order
692    /// in the **outer** step and independent of the substep entirely.
693    ///
694    /// Measured on a lumped plate under a steady lamp, against the closed form: 26.2% low at a
695    /// 300 s outer step, 13.8% at 150 s, 7.1% at 75 s — *whatever* the substep count. At the
696    /// same outer step it is not reliably better than [`Schedule::Staggered`] and at a coarse
697    /// one it is worse, with the errors on opposite sides.
698    ///
699    /// **Every one of those runs passes the conservation audit at around 1e-12.** The total
700    /// that crossed is exactly right; only its distribution in time is wrong, and a [`Ledger`]
701    /// has no representation for *when*. This is the time-domain twin of the reason
702    /// [`Exchange::audit_transfers`] had to become a per-face check in space — a quantity moved
703    /// to the wrong part of an interval keeps its total, and conservation is blind to it.
704    ///
705    /// So: choose this for **stability**, which is what it delivers — a domain whose limit is a
706    /// hundredth of the frame no longer forces the frame to shrink. Choose the outer step for
707    /// **accuracy**, because that is what sets it. `crates/dualis/tests/multirate_timing.rs`
708    /// pins the consequence.
709    Multirate,
710}
711
712/// What one [`Simulation::advance`] actually did.
713#[derive(Clone, Debug, Default, PartialEq)]
714pub struct Report {
715    /// Substeps taken, per domain, in declared order.
716    ///
717    /// Owned names, because [`Domain::name`] is borrowed from the domain and this report
718    /// outlives the borrow — the same consequence of names being data rather than
719    /// constants that shows up everywhere else in this module.
720    pub substeps: Vec<(String, u32)>,
721    /// Coupling iterations used. One for every schedule but `Iterative`.
722    pub iterations: u32,
723    /// Largest residual left at the end.
724    pub residual: f64,
725}
726
727/// A set of domains sharing a clock.
728pub struct Simulation {
729    domains: Vec<Box<dyn Domain>>,
730    schedule: Schedule,
731    bus: Exchange,
732    t: Time,
733    transfer_tol: f64,
734    conservation_tol: Tolerances,
735}
736
737impl Simulation {
738    /// Domains are stepped in the order they are added. That order is part of the
739    /// physics under a staggered schedule — put the quasi-static producers before
740    /// the evolving consumers — and it is fixed rather than discovered, so two
741    /// runs take the same path.
742    pub fn new(schedule: Schedule) -> Simulation {
743        Simulation {
744            domains: Vec::new(),
745            schedule,
746            bus: Exchange::new(),
747            t: Time::ZERO,
748            transfer_tol: 1e-12,
749            conservation_tol: Tolerances::default(),
750        }
751    }
752
753    /// Add a domain whose type was chosen at run time.
754    ///
755    /// What [`Simulation::with`] cannot do: building a domain from a scene file produces a
756    /// `Box<dyn Domain>`, and `with` wants a concrete type. The simulation has always stored
757    /// boxes internally, so this is the shorter path and not a wider one.
758    pub fn with_boxed(mut self, domain: Box<dyn Domain>) -> Simulation {
759        self.domains.push(domain);
760        self
761    }
762
763    /// Add a domain. Order matters for [`Schedule::Staggered`] and its relatives: a domain
764    /// sees the output of those declared before it from this step, and of those after it from
765    /// the last one.
766    pub fn with(mut self, domain: impl Domain + 'static) -> Simulation {
767        self.domains.push(Box::new(domain));
768        self
769    }
770
771    /// Absolute tolerance on the bus audit, in SI units of whatever is on the
772    /// channel. Default 1e-12.
773    pub fn transfer_tolerance(mut self, tol: f64) -> Simulation {
774        self.transfer_tol = tol;
775        self
776    }
777
778    /// Relative tolerance on the whole-simulation conservation audit across a
779    /// step, for every quantity that has no override. Default 1e-9.
780    pub fn conservation_tolerance(mut self, tol: f64) -> Simulation {
781        let overrides: Vec<(&'static str, f64)> = self.conservation_tol.overrides().collect();
782        self.conservation_tol = overrides
783            .into_iter()
784            .fold(Tolerances::uniform(tol), |t, (q, v)| t.with(q, v));
785        self
786    }
787
788    /// Relative tolerance for **one** quantity, overriding the default.
789    ///
790    /// The reason this exists: a Barnes-Hut N-body gives up exact momentum by construction, and
791    /// energy in a rigid room is exact to `1e-15`. Under one number either the momentum check
792    /// refuses a correct run or the energy check stops being able to see anything. A quantity's
793    /// achievable accuracy is a property of the scheme carrying it.
794    ///
795    /// ```
796    /// # use dualis_core::{Schedule, Simulation};
797    /// # use dualis_core::conserved::quantity;
798    /// let sim = Simulation::new(Schedule::Staggered)
799    ///     .conservation_tolerance(1e-12)
800    ///     .conservation_tolerance_for(quantity::MOMENTUM, 1e-6);
801    /// assert_eq!(sim.tolerances().for_quantity(quantity::ENERGY), 1e-12);
802    /// assert_eq!(sim.tolerances().for_quantity(quantity::MOMENTUM), 1e-6);
803    /// ```
804    pub fn conservation_tolerance_for(mut self, quantity: &'static str, tol: f64) -> Simulation {
805        self.conservation_tol = std::mem::take(&mut self.conservation_tol).with(quantity, tol);
806        self
807    }
808
809    /// What this simulation checks each quantity against.
810    pub fn tolerances(&self) -> &Tolerances {
811        &self.conservation_tol
812    }
813
814    /// How far the simulation has been advanced.
815    pub fn time(&self) -> Time {
816        self.t
817    }
818
819    /// The coupling bus, for reading what crossed between domains.
820    pub fn bus(&self) -> &Exchange {
821        &self.bus
822    }
823
824    /// Every domain, in the order they were added.
825    ///
826    /// `domain` answers by name, which is right for a caller that knows what it is looking for
827    /// and useless for one that must visit them all. A layer capturing a run has to enumerate,
828    /// and without this it had to be handed the list by whoever built the simulation — which
829    /// means the layer above knows the composition rather than asking.
830    ///
831    /// Order is declaration order, which is also execution order under the staggered schedules,
832    /// so a caller iterating this sees domains in the order they act.
833    pub fn domains(&self) -> impl Iterator<Item = &dyn Domain> + '_ {
834        self.domains.iter().map(|d| &**d as &dyn Domain)
835    }
836
837    /// A domain by name, through the trait. For the concrete type, see
838    /// [`Simulation::domain_as`].
839    pub fn domain(&self, name: &str) -> Option<&dyn Domain> {
840        self.domains
841            .iter()
842            .find(|d| d.name() == name)
843            .map(|d| d.as_ref())
844    }
845
846    /// A domain's [`ScalarField`], if it has one and opted in.
847    ///
848    /// The domain-agnostic counterpart of [`Simulation::domain_as`]: a renderer can sample
849    /// every field in a simulation without knowing what any of them are. That was the whole
850    /// point of `ScalarField` and it was not reachable until [`Domain::as_field`] existed.
851    pub fn field(&self, name: &str) -> Option<&dyn ScalarField> {
852        self.domain(name)?.as_field()
853    }
854
855    /// A domain by name and concrete type, for a caller that needs more than the
856    /// [`Domain`] trait exposes — a temperature profile, a body's position.
857    ///
858    /// Returns `None` if the name is not here, if the type is wrong, or if that domain did
859    /// not implement [`Domain::as_any`]. Prefer [`Simulation::field`] when what is wanted is
860    /// a field to sample: that one does not need the concrete type at all.
861    pub fn domain_as<T: Any>(&self, name: &str) -> Option<&T> {
862        self.domain(name)?.as_any()?.downcast_ref::<T>()
863    }
864
865    /// The same, mutably, for a caller closing a feedback loop between steps.
866    ///
867    /// `None` if there is no such domain, if it is not a `T`, or if it does not implement
868    /// [`Domain::as_any_mut`] — three different reasons that look alike from here, which is why
869    /// that method's documentation asks for it to be implemented beside `as_any`.
870    pub fn domain_as_mut<T: Any>(&mut self, name: &str) -> Option<&mut T> {
871        self.domains
872            .iter_mut()
873            .find(|d| d.name() == name)?
874            .as_any_mut()?
875            .downcast_mut::<T>()
876    }
877
878    /// Every domain's books, summed.
879    pub fn ledger(&self) -> Ledger {
880        self.domains
881            .iter()
882            .fold(Ledger::new(), |total, d| total.merged(&d.ledger()))
883    }
884
885    /// Advance every domain by `dt`.
886    ///
887    /// Fails without advancing the clock if a domain fails, if the bus does not
888    /// balance, if an iterative coupling does not converge, or if the totalled
889    /// ledgers moved by more than the conservation tolerance.
890    pub fn advance(&mut self, dt: Time) -> Result<Report, Violation> {
891        let before = self.ledger();
892        // What a substep's share is measured against. Set here rather than in `sweep`, because
893        // `iterate` sweeps repeatedly over the same interval.
894        self.bus.covering(dt);
895        let report = match self.schedule {
896            Schedule::OneWay | Schedule::Staggered => self.sweep(dt, false)?,
897            Schedule::Multirate => self.sweep(dt, true)?,
898            Schedule::Iterative { max_iter, tol } => self.iterate(dt, max_iter, tol)?,
899        };
900
901        self.bus.audit_transfers("bus", self.transfer_tol)?;
902        let after = self.ledger();
903        if !before.is_empty() || !after.is_empty() {
904            audit_with("simulation", &before, &after, &self.conservation_tol)?;
905        }
906        self.t += dt;
907        Ok(report)
908    }
909
910    /// One pass over the domains in declared order.
911    fn sweep(&mut self, dt: Time, multirate: bool) -> Result<Report, Violation> {
912        let now = self.t;
913        let mut substeps = Vec::with_capacity(self.domains.len());
914        for domain in self.domains.iter_mut() {
915            // A quasi-static domain has no state to march, so subdividing its
916            // step would just solve the same problem several times.
917            let n = if multirate && domain.kind() == Kind::Evolving {
918                substeps_for(dt, domain.max_stable_dt(now))
919            } else {
920                1
921            };
922            let h = dt / n as f64;
923            let mut t = now;
924            // Which channels had already been drawn on before this domain's turn.
925            let before: Vec<(&'static str, u32)> = self.bus.takes_per_channel().collect();
926            // And, for a domain that claims exact books, what it was holding and what the bus
927            // had carried — snapshotted here because only this domain runs before the
928            // corresponding snapshot below, which is what makes the difference attributable.
929            let audited = domain.books_balance();
930            let books_before = audited.then(|| domain.ledger());
931            let traffic_before = audited.then(|| self.bus.traffic());
932            for _ in 0..n {
933                domain.step(t, h, &mut self.bus)?;
934                t += h;
935            }
936            if let (Some(before), Some(traffic)) = (books_before, traffic_before) {
937                attribute(
938                    domain.name(),
939                    &before,
940                    &domain.ledger(),
941                    &traffic,
942                    &self.bus.traffic(),
943                    &self.conservation_tol,
944                )?;
945            }
946
947            // A channel this domain took from that an *earlier* domain had already emptied.
948            //
949            // `Exchange::take` empties a channel, so the second consumer gets zero — and every
950            // total agrees, because everything published was consumed. Two plates under one lamp
951            // warm at the rate of one plate and the books balance to the bit. The conservation
952            // audit structurally cannot see it.
953            //
954            // Counted per *turn* rather than per call, because a subcycling domain takes once
955            // per substep and that is one consumer collecting its own interval in pieces.
956            //
957            // Refused rather than apportioned: splitting needs a rule the kernel has no way to
958            // choose — equally, by heat capacity, by area? — and any rule it picked would be
959            // silently wrong for someone, which is the failure being fixed rather than a fresh
960            // one. A caller who knows the answer can publish on channels of their own.
961            for (channel, now_taken) in self.bus.takes_per_channel() {
962                let was = before
963                    .iter()
964                    .find(|(c, _)| *c == channel)
965                    .map_or(0, |(_, n)| *n);
966                if was > 0 && now_taken > was {
967                    return Err(Violation {
968                        quantity: channel.to_string(),
969                        site: format!(
970                            "{} (a second domain took from a channel already emptied)",
971                            domain.name()
972                        ),
973                        before: was as f64,
974                        after: now_taken as f64,
975                        scale: now_taken as f64,
976                        tolerance: 0.0,
977                    });
978                }
979            }
980            substeps.push((domain.name().to_string(), n));
981        }
982        let residual = self
983            .domains
984            .iter()
985            .map(|d| d.residual())
986            .fold(0.0f64, f64::max);
987        Ok(Report {
988            substeps,
989            iterations: 1,
990            residual,
991        })
992    }
993
994    /// Repeat the pass from the same starting state until the residuals settle.
995    fn iterate(&mut self, dt: Time, max_iter: u32, tol: f64) -> Result<Report, Violation> {
996        if let Some(bad) = self.domains.iter().find(|d| !d.supports_restore()) {
997            return Err(Violation::at(
998                bad.name(),
999                "iterative coupling needs a restorable domain",
1000                0.0,
1001            ));
1002        }
1003        for domain in self.domains.iter_mut() {
1004            domain.checkpoint();
1005        }
1006
1007        let mut last = Report::default();
1008        for iteration in 1..=max_iter {
1009            if iteration > 1 {
1010                for domain in self.domains.iter_mut() {
1011                    domain.restore();
1012                }
1013                self.bus.clear_offers();
1014            }
1015            let mut report = self.sweep(dt, true)?;
1016            report.iterations = iteration;
1017            last = report;
1018            if last.residual <= tol {
1019                return Ok(last);
1020            }
1021        }
1022
1023        // Not converged. Reporting this rather than proceeding is the whole point:
1024        // an unconverged coupling produces plausible numbers, which is worse than
1025        // producing none.
1026        Err(Violation {
1027            quantity: "coupling residual".to_string(),
1028            site: format!("simulation (after {max_iter} iterations)"),
1029            before: 0.0,
1030            after: last.residual,
1031            scale: last.residual.abs(),
1032            tolerance: tol,
1033        })
1034    }
1035}
1036
1037/// Check one domain's books against its own traffic on the bus.
1038///
1039/// **What the whole-simulation audit structurally cannot see.** That audit sums every ledger
1040/// before comparing, so the scale it measures against is the total — and a domain holding a
1041/// microjoule beside one holding a kilojoule can lose everything it has without moving the sum.
1042/// No tolerance fixes that, because the problem is the scale rather than the number.
1043///
1044/// Here the scale is the domain's own: what it held, what it holds, and what it moved. A leak of
1045/// a per cent of a small domain is a per cent here, whatever else is in the simulation.
1046///
1047/// Only for domains that opt in through [`Domain::books_balance`], because an exact book is a
1048/// claim not every honest domain can make — one losing heat to an environment that is not on the
1049/// bus is modelling a boundary, not leaking.
1050fn attribute(
1051    name: &str,
1052    before: &Ledger,
1053    after: &Ledger,
1054    traffic_before: &[(&'static str, f64, f64)],
1055    traffic_after: &[(&'static str, f64, f64)],
1056    tolerances: &Tolerances,
1057) -> Result<(), Violation> {
1058    let moved = |channel: &str| -> f64 {
1059        let find = |t: &[(&'static str, f64, f64)]| {
1060            t.iter()
1061                .find(|(c, _, _)| *c == channel)
1062                .map(|(_, p, k)| (*p, *k))
1063                .unwrap_or((0.0, 0.0))
1064        };
1065        let (pub_before, took_before) = find(traffic_before);
1066        let (pub_after, took_after) = find(traffic_after);
1067        // Taken minus published: what the domain gained from the bus.
1068        (took_after - took_before) - (pub_after - pub_before)
1069    };
1070
1071    let mut names: Vec<&'static str> = before.quantities().map(|(n, _)| n).collect();
1072    for (n, _) in after.quantities() {
1073        if !names.contains(&n) {
1074            names.push(n);
1075        }
1076    }
1077    names.sort_unstable();
1078
1079    for quantity in names {
1080        let held_before = before.get(quantity).unwrap_or(0.0);
1081        let held_after = after.get(quantity).unwrap_or(0.0);
1082        let expected = moved(quantity);
1083        let discrepancy = (held_after - held_before) - expected;
1084
1085        // The domain's own scale, which is the whole point: its holdings, its declared scale, and
1086        // the amount it moved. Not the simulation's total.
1087        let scale = held_before
1088            .abs()
1089            .max(held_after.abs())
1090            .max(before.scale_of(quantity).unwrap_or(0.0))
1091            .max(after.scale_of(quantity).unwrap_or(0.0))
1092            .max(expected.abs());
1093        if scale < 1e-300 {
1094            continue;
1095        }
1096        let tol = tolerances.for_quantity(quantity);
1097        if discrepancy.abs() / scale > tol {
1098            return Err(Violation {
1099                quantity: quantity.to_string(),
1100                site: format!("{name} (its own books, against what it moved on the bus)"),
1101                before: held_before + expected,
1102                after: held_after,
1103                scale,
1104                tolerance: tol,
1105            });
1106        }
1107    }
1108    Ok(())
1109}
1110
1111#[cfg(test)]
1112mod tests {
1113    use super::*;
1114    use crate::conserved::quantity;
1115    use dualis_units::Area;
1116
1117    /// A quasi-static source: converts an input into watts on the bus without any
1118    /// state of its own. This is the shape optics has — solved, never stepped.
1119    struct Lamp {
1120        watts: f64,
1121        delivered: f64,
1122    }
1123
1124    impl Domain for Lamp {
1125        fn name(&self) -> &str {
1126            "lamp"
1127        }
1128        fn kind(&self) -> Kind {
1129            Kind::QuasiStatic
1130        }
1131        fn step(&mut self, _t: Time, dt: Time, bus: &mut Exchange) -> Result<(), Violation> {
1132            let joules = self.watts * dt.to_si();
1133            bus.publish(quantity::ENERGY, joules);
1134            self.delivered += joules;
1135            Ok(())
1136        }
1137        fn ledger(&self) -> Ledger {
1138            // Energy that has left the lamp is still in the system's books until
1139            // something else takes it, so the lamp reports what it has paid out.
1140            Ledger::new().with(quantity::ENERGY, -self.delivered)
1141        }
1142        fn checkpoint(&mut self) {}
1143        fn restore(&mut self) {}
1144        fn supports_restore(&self) -> bool {
1145            true
1146        }
1147    }
1148
1149    /// An evolving sink with a stability limit: a lumped thermal mass that must
1150    /// not be stepped past a fraction of its time constant.
1151    struct Block {
1152        joules: f64,
1153        limit: Time,
1154        saved: f64,
1155    }
1156
1157    impl Domain for Block {
1158        fn name(&self) -> &str {
1159            "block"
1160        }
1161        fn max_stable_dt(&self, _now: Time) -> Time {
1162            self.limit
1163        }
1164        fn step(&mut self, _t: Time, _dt: Time, bus: &mut Exchange) -> Result<(), Violation> {
1165            self.joules += bus.take(quantity::ENERGY);
1166            Ok(())
1167        }
1168        fn ledger(&self) -> Ledger {
1169            Ledger::new().with(quantity::ENERGY, self.joules)
1170        }
1171        fn checkpoint(&mut self) {
1172            self.saved = self.joules;
1173        }
1174        fn restore(&mut self) {
1175            self.joules = self.saved;
1176        }
1177        fn supports_restore(&self) -> bool {
1178            true
1179        }
1180    }
1181
1182    fn lamp_and_block(schedule: Schedule, limit: Time) -> Simulation {
1183        Simulation::new(schedule)
1184            .with(Lamp {
1185                watts: 0.01,
1186                delivered: 0.0,
1187            })
1188            .with(Block {
1189                joules: 0.0,
1190                limit,
1191                saved: 0.0,
1192            })
1193    }
1194
1195    /// The chain works end to end: a quasi-static producer hands energy across
1196    /// the bus to an evolving consumer, the books balance, and the clock moves.
1197    #[test]
1198    fn energy_crosses_the_bus_and_the_books_balance() {
1199        let mut sim = lamp_and_block(Schedule::Staggered, Time::s(1.0));
1200        let report = sim.advance(Time::s(2.0)).expect("a balanced step");
1201        assert_eq!(report.iterations, 1);
1202        assert!((sim.time().to_si() - 2.0).abs() < 1e-15);
1203        // 10 mW for 2 s is 20 mJ, and all of it arrived.
1204        assert!((sim.bus().total_consumed(quantity::ENERGY) - 0.02).abs() < 1e-15);
1205        // The system as a whole is where it started: the lamp is down what the
1206        // block is up.
1207        assert_eq!(sim.ledger().get(quantity::ENERGY), Some(0.0));
1208    }
1209
1210    /// Energy published and not consumed is caught. This is the interpolation bug
1211    /// at a coupling interface, in its simplest possible form: a producer with no
1212    /// consumer.
1213    #[test]
1214    fn energy_that_arrives_nowhere_is_a_violation() {
1215        let mut sim = Simulation::new(Schedule::Staggered).with(Lamp {
1216            watts: 0.01,
1217            delivered: 0.0,
1218        });
1219        let err = sim.advance(Time::s(1.0)).expect_err("nothing consumed it");
1220        assert_eq!(err.quantity, "energy");
1221        assert!(err.site.contains("not consumed"), "{err}");
1222        // And the clock did not move, so the failure is not half-applied.
1223        assert_eq!(sim.time(), Time::ZERO);
1224    }
1225
1226    /// Multirate: the domain with the tight limit subcycles, and the quasi-static
1227    /// one does not, because there is nothing to subdivide.
1228    #[test]
1229    fn only_evolving_domains_subcycle() {
1230        let mut sim = lamp_and_block(Schedule::Multirate, Time::s(0.3));
1231        let report = sim.advance(Time::s(1.0)).unwrap();
1232        assert_eq!(
1233            report.substeps,
1234            vec![("lamp".to_string(), 1), ("block".to_string(), 4)],
1235            "the block needs ceil(1.0/0.3) = 4 substeps; the lamp needs none"
1236        );
1237        // Subcycling must not change the total that crossed.
1238        assert!((sim.bus().total_consumed(quantity::ENERGY) - 0.01).abs() < 1e-15);
1239    }
1240
1241    /// A domain with no stability limit is not subcycled at all, however long the
1242    /// step.
1243    #[test]
1244    fn an_unlimited_domain_takes_one_step() {
1245        let mut sim = lamp_and_block(Schedule::Multirate, Time::from_si(f64::INFINITY));
1246        let report = sim.advance(Time::s(1e6)).unwrap();
1247        assert_eq!(
1248            report.substeps,
1249            vec![("lamp".to_string(), 1), ("block".to_string(), 1)]
1250        );
1251    }
1252
1253    /// Iterative coupling converges and reports how many passes it took.
1254    struct Settling {
1255        residual: f64,
1256        saved: f64,
1257    }
1258
1259    impl Domain for Settling {
1260        fn name(&self) -> &str {
1261            "settling"
1262        }
1263        fn step(&mut self, _t: Time, _dt: Time, _bus: &mut Exchange) -> Result<(), Violation> {
1264            // Each pass halves the disagreement with the neighbour.
1265            self.residual /= 2.0;
1266            Ok(())
1267        }
1268        fn residual(&self) -> f64 {
1269            self.residual
1270        }
1271        fn checkpoint(&mut self) {
1272            self.saved = self.residual;
1273        }
1274        fn restore(&mut self) {
1275            // The restore puts the state back but keeps the improved coupling
1276            // guess, which is what makes the iteration converge rather than loop.
1277            let improved = self.residual;
1278            self.residual = self.saved.min(improved);
1279        }
1280        fn supports_restore(&self) -> bool {
1281            true
1282        }
1283    }
1284
1285    #[test]
1286    fn an_iterative_coupling_converges_and_says_how_long_it_took() {
1287        let mut sim = Simulation::new(Schedule::Iterative {
1288            max_iter: 20,
1289            tol: 1e-3,
1290        })
1291        .with(Settling {
1292            residual: 1.0,
1293            saved: 0.0,
1294        });
1295        let report = sim.advance(Time::s(1.0)).unwrap();
1296        // 1.0 halved ten times is 9.8e-4, the first value under 1e-3.
1297        assert_eq!(report.iterations, 10);
1298        assert!(report.residual <= 1e-3);
1299    }
1300
1301    /// Not converging is a failure, not a result. An unconverged coupling gives
1302    /// numbers that look like physics, which is the worst thing it could do.
1303    #[test]
1304    fn failing_to_converge_is_reported_not_accepted() {
1305        let mut sim = Simulation::new(Schedule::Iterative {
1306            max_iter: 3,
1307            tol: 1e-9,
1308        })
1309        .with(Settling {
1310            residual: 1.0,
1311            saved: 0.0,
1312        });
1313        let err = sim
1314            .advance(Time::s(1.0))
1315            .expect_err("three halvings is not 1e-9");
1316        assert_eq!(err.quantity, "coupling residual");
1317        assert!(err.site.contains("after 3 iterations"), "{err}");
1318        assert_eq!(sim.time(), Time::ZERO);
1319    }
1320
1321    /// A domain that cannot put itself back cannot be iterated, and is told so by
1322    /// name rather than being iterated from the wrong state.
1323    #[test]
1324    fn iteration_refuses_a_domain_that_cannot_rewind() {
1325        struct NoRewind;
1326        impl Domain for NoRewind {
1327            fn name(&self) -> &str {
1328                "no-rewind"
1329            }
1330            fn step(&mut self, _t: Time, _dt: Time, _b: &mut Exchange) -> Result<(), Violation> {
1331                Ok(())
1332            }
1333        }
1334        let mut sim = Simulation::new(Schedule::Iterative {
1335            max_iter: 5,
1336            tol: 1e-6,
1337        })
1338        .with(NoRewind);
1339        let err = sim.advance(Time::s(1.0)).unwrap_err();
1340        assert_eq!(err.site, "no-rewind");
1341        assert!(err.quantity.contains("restorable"), "{err}");
1342    }
1343
1344    /// The whole scheduler is deterministic: same domains, same schedule, same
1345    /// numbers, down to the substep counts.
1346    #[test]
1347    fn advancing_is_reproducible() {
1348        let run = || {
1349            let mut sim = lamp_and_block(Schedule::Multirate, Time::s(0.07));
1350            let mut reports = Vec::new();
1351            for _ in 0..5 {
1352                reports.push(sim.advance(Time::s(0.25)).unwrap());
1353            }
1354            (reports, sim.bus().total_consumed(quantity::ENERGY))
1355        };
1356        let (a, ea) = run();
1357        let (b, eb) = run();
1358        assert_eq!(a, b);
1359        assert_eq!(ea.to_bits(), eb.to_bits(), "not bit-identical");
1360        assert_eq!(
1361            a[0].substeps,
1362            vec![("lamp".to_string(), 1), ("block".to_string(), 4)]
1363        );
1364    }
1365
1366    /// Taking from a channel empties it, so an amount cannot be consumed twice.
1367    #[test]
1368    fn a_channel_cannot_be_drained_twice() {
1369        let mut bus = Exchange::new();
1370        bus.publish(quantity::ENERGY, 5.0);
1371        bus.publish(quantity::ENERGY, 3.0);
1372        assert_eq!(bus.peek(quantity::ENERGY), 8.0);
1373        assert_eq!(bus.take(quantity::ENERGY), 8.0);
1374        assert_eq!(bus.take(quantity::ENERGY), 0.0);
1375        assert_eq!(bus.total_consumed(quantity::ENERGY), 8.0);
1376        assert!(bus.unclaimed().next().is_none());
1377    }
1378
1379    /// A spatial channel behaves like a lumped one — accumulate, drain once — but face by
1380    /// face, so two mechanisms heating the same mirror add up *where* each of them did.
1381    #[test]
1382    fn a_spatial_channel_accumulates_and_drains_in_place() {
1383        let mirror = Interface::uniform("mirror", 4, Area::from_si(1e-4));
1384        let mut bus = Exchange::new();
1385
1386        // Absorption in the coating, on the two faces the beam covers.
1387        bus.publish_on(
1388            &mirror,
1389            quantity::ENERGY,
1390            &Flux::from_faces(vec![0.0, 2.0, 3.0, 0.0]),
1391        )
1392        .unwrap();
1393        // And a mount conducting into one edge, which is a different mechanism on the same
1394        // boundary. It must land on face 0, not be averaged in.
1395        bus.publish_on(
1396            &mirror,
1397            quantity::ENERGY,
1398            &Flux::from_faces(vec![1.0, 0.0, 0.0, 0.0]),
1399        )
1400        .unwrap();
1401
1402        assert_eq!(
1403            bus.peek_on(&mirror, quantity::ENERGY).unwrap().per_face(),
1404            &[1.0, 2.0, 3.0, 0.0]
1405        );
1406
1407        let taken = bus.take_on(&mirror, quantity::ENERGY).unwrap();
1408        assert_eq!(taken.per_face(), &[1.0, 2.0, 3.0, 0.0]);
1409        assert!((bus.total_consumed_on(&mirror, quantity::ENERGY) - 6.0).abs() < 1e-15);
1410        // Emptied, so it cannot be consumed twice.
1411        assert_eq!(bus.take_on(&mirror, quantity::ENERGY).unwrap().total(), 0.0);
1412        assert!(bus.unclaimed().next().is_none());
1413
1414        // A channel nobody published to reads as zeros over the right boundary, not an
1415        // error: a mirror that happens to be dark this step is not a fault.
1416        let dark = bus.take_on(&mirror, "photons").unwrap();
1417        assert_eq!(dark.faces(), 4);
1418        assert_eq!(dark.total(), 0.0);
1419    }
1420
1421    /// **The bug the spatial audit exists to catch.** A consumer that keeps the total but
1422    /// moves it to the wrong part of the boundary is invisible to a total-only check, and
1423    /// is exactly the failure a shared discretisation is supposed to prevent.
1424    #[test]
1425    fn the_audit_names_the_face_that_was_left_holding_something() {
1426        let mirror = Interface::uniform("mirror", 8, Area::from_si(1e-4));
1427        let mut bus = Exchange::new();
1428
1429        // Ten joules on face 6.
1430        let mut absorbed = vec![0.0; 8];
1431        absorbed[6] = 10.0;
1432        bus.publish_on(&mirror, quantity::ENERGY, &Flux::from_faces(absorbed))
1433            .unwrap();
1434
1435        // A consumer takes it and puts back the same total in the wrong place. The sum is
1436        // exactly right, and the sum is not what is being checked.
1437        let taken = bus.take_on(&mirror, quantity::ENERGY).unwrap();
1438        let mut misplaced = vec![0.0; 8];
1439        misplaced[1] = -taken.total();
1440        misplaced[2] = taken.total();
1441        bus.publish_on(&mirror, quantity::ENERGY, &Flux::from_faces(misplaced))
1442            .unwrap();
1443
1444        assert!(
1445            bus.peek_on(&mirror, quantity::ENERGY)
1446                .unwrap()
1447                .total()
1448                .abs()
1449                < 1e-12,
1450            "the total balances, which is the whole point of the example"
1451        );
1452        let err = bus
1453            .audit_transfers("mirror coupling", 1e-9)
1454            .expect_err("a redistribution that keeps the total must still be caught");
1455        assert!(err.quantity.contains("face 1"), "{err}");
1456        assert!(err.quantity.contains("mirror/energy"), "{err}");
1457    }
1458
1459    /// Two sides that do not share a discretisation are refused rather than resampled
1460    /// behind the caller's back, on both the publishing and the consuming side.
1461    #[test]
1462    fn a_discretisation_disagreement_is_refused_at_the_bus() {
1463        let coarse = Interface::uniform("mirror", 4, Area::from_si(1e-4));
1464        let fine = Interface::uniform("mirror", 16, Area::from_si(0.25e-4));
1465        let mut bus = Exchange::new();
1466
1467        // Publishing 16 faces onto a 4-face boundary.
1468        let err = bus
1469            .publish_on(&coarse, quantity::ENERGY, &Flux::zeros(16))
1470            .expect_err("16 faces is not 4 faces");
1471        assert!(err.quantity.contains("expected 4"), "{err}");
1472        assert!(err.site.contains("mirror/energy"), "{err}");
1473
1474        // And a consumer whose own boundary is finer than what was published. Note both
1475        // interfaces are named "mirror": the channel matches, the discretisation does not,
1476        // and it is the face count that decides.
1477        bus.publish_on(&coarse, quantity::ENERGY, &Flux::from_faces(vec![1.0; 4]))
1478            .unwrap();
1479        let err = bus
1480            .take_on(&fine, quantity::ENERGY)
1481            .expect_err("a 16-cell mesh must not read a 4-face flux");
1482        assert!(err.quantity.contains("expected 16"), "{err}");
1483        assert!(err.quantity.contains("found 4"), "{err}");
1484
1485        // A refused take consumed nothing, so the energy is still there to be found.
1486        assert!((bus.peek_on(&coarse, quantity::ENERGY).unwrap().total() - 4.0).abs() < 1e-15);
1487        assert_eq!(bus.total_consumed_on(&coarse, quantity::ENERGY), 0.0);
1488        assert!(bus.audit_transfers("mirror", 1e-9).is_err());
1489
1490        // Saying it explicitly is what works, and it conserves.
1491        let crossed = bus
1492            .take_on(&coarse, quantity::ENERGY)
1493            .unwrap()
1494            .resample(&coarse, &fine)
1495            .unwrap();
1496        assert_eq!(crossed.faces(), 16);
1497        assert!((crossed.total() - 4.0).abs() < 1e-12);
1498    }
1499}