nexosim 1.0.0

A high performance asynchronous compute framework for system simulation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! Example: espresso coffee machine.
//!
//! This example demonstrates in particular:
//!
//! * non-trivial state machines,
//! * cancellation of events,
//! * model initialization,
//!
//! ```text
//!                                                   flow rate
//!                                ┌─────────────────────────────────────────────┐
//!                                │                     (≥0)                    │
//!                                │    ┌────────────┐                           │
//!                                └───►│            │                           │
//!                   added volume      │ Water tank ├────┐                      │
//!     Water fill ●───────────────────►│            │    │                      │
//!                      (>0)           └────────────┘    │                      │
//!                                                       │                      │
//!                                      water sense      │                      │
//!                                ┌──────────────────────┘                      │
//!                                │  (empty|not empty)                          │
//!                                │                                             │
//!                                │    ┌────────────┐          ┌────────────┐   │
//!                    brew time   └───►│            │ command  │            │   │
//! Brew time dial ●───────────────────►│ Controller ├─────────►│ Water pump ├───┘
//!                      (>0)      ┌───►│            │ (on|off) │            │
//!                                │    └────────────┘          └────────────┘
//!                    trigger     │
//!   Brew command ●───────────────┘
//!                      (-)
//! ```

use std::time::Duration;

use serde::{Deserialize, Serialize};

use nexosim::Message;
use nexosim::model::{Context, Model, schedulable};
use nexosim::ports::{EventSinkReader, EventSource, Output, SinkState, event_slot};
use nexosim::simulation::{EventKey, Mailbox, SimInit, SimulationError};
use nexosim::time::MonotonicTime;

/// Water pump.
#[derive(Serialize, Deserialize)]
pub struct Pump {
    /// Actual volumetric flow rate [m³·s⁻¹] -- output port.
    pub flow_rate: Output<f64>,

    /// Nominal volumetric flow rate in operation [m³·s⁻¹]  -- constant.
    nominal_flow_rate: f64,
}
#[Model]
impl Pump {
    /// Creates a pump with the specified nominal flow rate [m³·s⁻¹].
    pub fn new(nominal_flow_rate: f64) -> Self {
        Self {
            nominal_flow_rate,
            flow_rate: Output::default(),
        }
    }

    /// Main ON/OFF command -- input port.
    pub async fn command(&mut self, cmd: PumpCommand) {
        let flow_rate = match cmd {
            PumpCommand::On => self.nominal_flow_rate,
            PumpCommand::Off => 0.0,
        };

        self.flow_rate.send(flow_rate).await;
    }
}

/// Espresso machine controller.
#[derive(Serialize, Deserialize)]
pub struct Controller {
    /// Pump command -- output port.
    pub pump_cmd: Output<PumpCommand>,

    /// Brew time setting [s] -- internal state.
    brew_time: Duration,
    /// Current water sense state.
    water_sense: WaterSenseState,
    /// Event key, which if present indicates that the machine is currently
    /// brewing -- internal state.
    stop_brew_key: Option<EventKey>,
}
#[Model]
impl Controller {
    /// Default brew time [s].
    pub const DEFAULT_BREW_TIME: Duration = Duration::new(25, 0);

    /// Creates an espresso machine controller.
    pub fn new() -> Self {
        Self {
            brew_time: Self::DEFAULT_BREW_TIME,
            pump_cmd: Output::default(),
            stop_brew_key: None,
            water_sense: WaterSenseState::Empty, // will be overridden during init
        }
    }

    /// Signals a change in the water sensing state -- input port.
    pub async fn water_sense(&mut self, state: WaterSenseState) {
        // Check if the tank just got empty.
        if state == WaterSenseState::Empty && self.water_sense == WaterSenseState::NotEmpty {
            // If a brew was ongoing, we must cancel it.
            if let Some(key) = self.stop_brew_key.take() {
                key.cancel();
                self.pump_cmd.send(PumpCommand::Off).await;
            }
        }

        self.water_sense = state;
    }

    /// Sets the timing for the next brews [s] -- input port.
    pub async fn brew_time(&mut self, brew_time: Duration) {
        // Panic if the duration is null.
        assert!(!brew_time.is_zero());

        self.brew_time = brew_time;
    }

    /// Starts brewing or cancels the current brew -- input port.
    pub async fn brew_cmd(&mut self, _: (), cx: &Context<Self>) {
        // If a brew was ongoing, sending the brew command is interpreted as a
        // request to cancel it.
        if let Some(key) = self.stop_brew_key.take() {
            self.pump_cmd.send(PumpCommand::Off).await;

            // Abort the scheduled call to `stop_brew()`.
            key.cancel();

            return;
        }

        // If there is no water, do nothing.
        if self.water_sense == WaterSenseState::Empty {
            return;
        }

        // Schedule the `stop_brew()` method and turn on the pump.
        self.stop_brew_key = Some(
            cx.schedule_keyed_event(self.brew_time, schedulable!(Self::stop_brew), ())
                .unwrap(),
        );
        self.pump_cmd.send(PumpCommand::On).await;
    }

    /// Stops brewing.
    #[nexosim(schedulable)]
    async fn stop_brew(&mut self) {
        if self.stop_brew_key.take().is_some() {
            self.pump_cmd.send(PumpCommand::Off).await;
        }
    }
}

/// ON/OFF pump command.
#[derive(Copy, Clone, Eq, Message, PartialEq, Serialize, Deserialize)]
pub enum PumpCommand {
    On,
    Off,
}

/// Water tank.
#[derive(Serialize, Deserialize)]
pub struct Tank {
    /// Water sensor -- output port.
    pub water_sense: Output<WaterSenseState>,

    /// Volume of water [m³] -- internal state.
    volume: f64,
    /// State that exists when the mass flow rate is non-zero -- internal state.
    dynamic_state: Option<TankDynamicState>,
}
#[Model]
impl Tank {
    /// Creates a new tank with the specified amount of water [m³].
    ///
    /// The initial flow rate is assumed to be zero.
    pub fn new(water_volume: f64) -> Self {
        assert!(water_volume >= 0.0);

        Self {
            volume: water_volume,
            dynamic_state: None,
            water_sense: Output::default(),
        }
    }

    /// Broadcasts the initial state of the water sense.
    #[nexosim(init)]
    async fn init(&mut self) {
        self.water_sense
            .send(if self.volume == 0.0 {
                WaterSenseState::Empty
            } else {
                WaterSenseState::NotEmpty
            })
            .await;
    }

    /// Water volume added [m³] -- input port.
    pub async fn fill(&mut self, added_volume: f64, cx: &Context<Self>) {
        // Ignore zero and negative values. We could also impose a maximum based
        // on tank capacity.
        if added_volume <= 0.0 {
            return;
        }
        let was_empty = self.volume == 0.0;

        // Account for the added water.
        self.volume += added_volume;

        // If the current flow rate is non-zero, compute the current volume and
        // schedule a new update.
        if let Some(state) = self.dynamic_state.take() {
            // Abort the scheduled call to `set_empty()`.
            state.set_empty_key.cancel();

            // Update the volume, saturating at 0 in case of rounding errors.
            let time = cx.time();
            let elapsed_time = time.duration_since(state.last_volume_update).as_secs_f64();
            self.volume = (self.volume - state.flow_rate * elapsed_time).max(0.0);

            self.schedule_empty(state.flow_rate, time, cx).await;

            // There is no need to broadcast the state of the water sense since
            // it could not be previously `Empty` (otherwise the dynamic state
            // would not exist).
            return;
        }

        if was_empty {
            self.water_sense.send(WaterSenseState::NotEmpty).await;
        }
    }

    /// Returns current volume [m³] -- replier.
    pub async fn volume(&mut self) -> f64 {
        self.volume
    }

    /// Flow rate [m³·s⁻¹] -- input port.
    ///
    /// # Panics
    ///
    /// This method will panic if the flow rate is negative.
    pub async fn set_flow_rate(&mut self, flow_rate: f64, cx: &Context<Self>) {
        assert!(flow_rate >= 0.0);

        let time = cx.time();

        // If the flow rate was non-zero up to now, update the volume.
        if let Some(state) = self.dynamic_state.take() {
            // Abort the scheduled call to `set_empty()`.
            state.set_empty_key.cancel();

            // Update the volume, saturating at 0 in case of rounding errors.
            let elapsed_time = time.duration_since(state.last_volume_update).as_secs_f64();
            self.volume = (self.volume - state.flow_rate * elapsed_time).max(0.0);
        }

        self.schedule_empty(flow_rate, time, cx).await;
    }

    /// Schedules a callback for when the tank becomes empty.
    ///
    /// Pre-conditions:
    /// - `flow_rate` cannot be negative.
    /// - `self.volume` should be up to date,
    /// - `self.dynamic_state` should be `None`.
    async fn schedule_empty(&mut self, flow_rate: f64, time: MonotonicTime, cx: &Context<Self>) {
        // Determine when the tank will be empty at the current flow rate.
        let duration_until_empty = if self.volume == 0.0 {
            0.0
        } else {
            self.volume / flow_rate
        };
        if duration_until_empty.is_infinite() {
            // The flow rate is zero or very close to zero, so there is not
            // need to plan an update since the tank will never become
            // empty.
            return;
        }
        let duration_until_empty = Duration::from_secs_f64(duration_until_empty);

        // Schedule the next update.
        match cx.schedule_keyed_event(duration_until_empty, schedulable!(Self::set_empty), ()) {
            Ok(set_empty_key) => {
                let state = TankDynamicState {
                    last_volume_update: time,
                    set_empty_key,
                    flow_rate,
                };
                self.dynamic_state = Some(state);
            }
            Err(_) => {
                // The duration was null so the tank is already empty.
                self.volume = 0.0;
                self.water_sense.send(WaterSenseState::Empty).await;
            }
        }
    }

    /// Updates the state of the tank to indicate that there is no more water.
    #[nexosim(schedulable)]
    async fn set_empty(&mut self) {
        self.volume = 0.0;
        self.dynamic_state = None;
        self.water_sense.send(WaterSenseState::Empty).await;
    }
}

/// Dynamic state of the tank that exists when and only when the mass flow rate
/// is non-zero.
#[derive(Serialize, Deserialize)]
struct TankDynamicState {
    last_volume_update: MonotonicTime,
    set_empty_key: EventKey,
    flow_rate: f64,
}

/// Water level in the tank.
#[derive(Copy, Clone, Eq, Message, PartialEq, Serialize, Deserialize)]
pub enum WaterSenseState {
    Empty,
    NotEmpty,
}

#[allow(dead_code)]
fn main() -> Result<(), SimulationError> {
    // ---------------
    // Bench assembly.
    // ---------------

    // Models.

    // The constant mass flow rate assumption is of course a gross
    // simplification, so the flow rate is set to an expected average over the
    // whole extraction [m³·s⁻¹].
    let pump_flow_rate = 4.5e-6;
    // Start with 1.5l in the tank [m³].
    let init_tank_volume = 1.5e-3;

    let mut pump = Pump::new(pump_flow_rate);
    let mut controller = Controller::new();
    let mut tank = Tank::new(init_tank_volume);

    let pump_mbox = Mailbox::new();
    let controller_mbox = Mailbox::new();
    let tank_mbox = Mailbox::new();

    // Connections.
    controller.pump_cmd.connect(Pump::command, &pump_mbox);
    tank.water_sense
        .connect(Controller::water_sense, &controller_mbox);
    pump.flow_rate.connect(Tank::set_flow_rate, &tank_mbox);

    // Endpoints.
    let mut bench = SimInit::new();

    let brew_cmd = EventSource::new()
        .connect(Controller::brew_cmd, &controller_mbox)
        .register(&mut bench);
    let brew_time = EventSource::new()
        .connect(Controller::brew_time, &controller_mbox)
        .register(&mut bench);
    let tank_fill = EventSource::new()
        .connect(Tank::fill, &tank_mbox)
        .register(&mut bench);

    let (sink, mut flow_rate) = event_slot(SinkState::Enabled);
    pump.flow_rate.connect_sink(sink);

    // Assembly and initialization.
    let t0 = MonotonicTime::EPOCH; // arbitrary since models do not depend on absolute time
    let mut simu = bench
        .add_model(controller, controller_mbox, "controller")
        .add_model(pump, pump_mbox, "pump")
        .add_model(tank, tank_mbox, "tank")
        .init(t0)?;

    let scheduler = simu.scheduler();

    // ----------
    // Simulation.
    // ----------

    // Check initial conditions.
    let mut t = t0;
    assert_eq!(simu.time(), t);

    // Brew one espresso shot with the default brew time.
    simu.process_event(&brew_cmd, ())?;
    assert_eq!(flow_rate.try_read(), Some(pump_flow_rate));

    simu.step()?;
    t += Controller::DEFAULT_BREW_TIME;
    assert_eq!(simu.time(), t);
    assert_eq!(flow_rate.try_read(), Some(0.0));

    // Drink too much coffee.
    let volume_per_shot = pump_flow_rate * Controller::DEFAULT_BREW_TIME.as_secs_f64();
    let shots_per_tank = (init_tank_volume / volume_per_shot) as u64; // YOLO--who cares about floating-point rounding errors?
    for _ in 0..(shots_per_tank - 1) {
        simu.process_event(&brew_cmd, ())?;
        assert_eq!(flow_rate.try_read(), Some(pump_flow_rate));
        simu.step()?;
        t += Controller::DEFAULT_BREW_TIME;
        assert_eq!(simu.time(), t);
        assert_eq!(flow_rate.try_read(), Some(0.0));
    }

    // Check that the tank becomes empty before the completion of the next shot.
    simu.process_event(&brew_cmd, ())?;
    simu.step()?;
    assert!(simu.time() < t + Controller::DEFAULT_BREW_TIME);
    t = simu.time();
    let last_flow_rate = flow_rate.try_read();
    assert_eq!(last_flow_rate, Some(0.0));

    // Try to brew another shot while the tank is still empty.
    simu.process_event(&brew_cmd, ())?;
    assert!(flow_rate.try_read().is_none());

    // Change the brew time and fill up the tank.
    let brew_duration = Duration::new(30, 0);
    simu.process_event(&brew_time, brew_duration)?;
    simu.process_event(&tank_fill, 1.0e-3)?;
    simu.process_event(&brew_cmd, ())?;
    assert_eq!(flow_rate.try_read(), Some(pump_flow_rate));

    simu.step()?;
    t += brew_duration;
    assert_eq!(simu.time(), t);
    assert_eq!(flow_rate.try_read(), Some(0.0));

    // Interrupt the brew after 15s by pressing again the brew button.
    scheduler
        .schedule_event(Duration::from_secs(15), &brew_cmd, ())
        .unwrap();
    simu.process_event(&brew_cmd, ())?;
    assert_eq!(flow_rate.try_read(), Some(pump_flow_rate));

    simu.step()?;
    t += Duration::from_secs(15);
    assert_eq!(simu.time(), t);
    assert_eq!(flow_rate.try_read(), Some(0.0));

    Ok(())
}