altrios-core 0.2.0

ALTRIOS Core model for train 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
454
455
//! Module for standalone simulation of locomotive powertrains

use rayon::prelude::*;

use crate::consist::locomotive::Locomotive;
use crate::consist::LocoTrait;
use crate::imports::*;

#[altrios_api(
    #[new]
    fn __new__(
        time_seconds: Vec<f64>,
        pwr_watts: Vec<f64>,
        engine_on: Vec<Option<bool>>,
    ) -> anyhow::Result<Self> {
        Ok(Self::new(time_seconds, pwr_watts, engine_on))
    }

    #[staticmethod]
    #[pyo3(name = "from_csv_file")]
    fn from_csv_file_py(pathstr: String) -> anyhow::Result<Self> {
        Self::from_csv_file(&pathstr)
    }

    fn __len__(&self) -> usize {
        self.len()
    }
)]
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, SerdeAPI)]
/// Container
pub struct PowerTrace {
    /// simulation time
    #[serde(rename = "time_seconds")]
    pub time: Vec<si::Time>,
    /// simulation power
    #[serde(rename = "pwr_watts")]
    pub pwr: Vec<si::Power>,
    /// Whether engine is on
    pub engine_on: Vec<Option<bool>>,
}

impl PowerTrace {
    pub fn new(time_s: Vec<f64>, pwr_watts: Vec<f64>, engine_on: Vec<Option<bool>>) -> Self {
        Self {
            time: time_s.iter().map(|x| uc::S * (*x)).collect(),
            pwr: pwr_watts.iter().map(|x| uc::W * (*x)).collect(),
            engine_on,
        }
    }

    pub fn empty() -> Self {
        Self {
            time: Vec::new(),
            pwr: Vec::new(),
            engine_on: Vec::new(),
        }
    }

    pub fn dt(&self, i: usize) -> si::Time {
        self.time[i] - self.time[i - 1]
    }

    pub fn len(&self) -> usize {
        self.time.len()
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn push(&mut self, pt_element: PowerTraceElement) {
        self.time.push(pt_element.time);
        self.pwr.push(pt_element.pwr);
        self.engine_on.push(pt_element.engine_on);
    }

    pub fn trim(&mut self, start_idx: Option<usize>, end_idx: Option<usize>) -> anyhow::Result<()> {
        let start_idx = start_idx.unwrap_or(0);
        let end_idx = end_idx.unwrap_or(self.len());
        ensure!(end_idx <= self.len(), format_dbg!(end_idx <= self.len()));

        self.time = self.time[start_idx..end_idx].to_vec();
        self.pwr = self.pwr[start_idx..end_idx].to_vec();
        self.engine_on = self.engine_on[start_idx..end_idx].to_vec();
        Ok(())
    }

    /// Load cycle from csv file
    pub fn from_csv_file(pathstr: &str) -> Result<Self, anyhow::Error> {
        let pathbuf = PathBuf::from(&pathstr);

        // create empty cycle to be populated
        let mut pt = Self::empty();

        let file = File::open(pathbuf)?;
        let mut rdr = csv::ReaderBuilder::new()
            .has_headers(true)
            .from_reader(file);
        for result in rdr.deserialize() {
            let pt_elem: PowerTraceElement = result?;
            pt.push(pt_elem);
        }
        if pt.is_empty() {
            bail!("Invalid PowerTrace file; PowerTrace is empty")
        } else {
            Ok(pt)
        }
    }
}

impl Default for PowerTrace {
    fn default() -> Self {
        let pwr_max_watts = 1.5e6;
        let pwr_watts_ramp: Vec<f64> = Vec::linspace(0., pwr_max_watts, 300);
        let mut pwr_watts = pwr_watts_ramp.clone();
        pwr_watts.append(&mut vec![pwr_max_watts; 100]);
        pwr_watts.append(&mut pwr_watts_ramp.iter().rev().copied().collect());
        let time_s: Vec<f64> = (0..pwr_watts.len()).map(|x| x as f64).collect();
        let time_len = time_s.len();
        Self::new(time_s, pwr_watts, vec![Some(true); time_len])
    }
}

/// Element of [PowerTrace].  Used for vec-like operations.
#[derive(Default, Debug, Serialize, Deserialize, PartialEq, SerdeAPI)]
pub struct PowerTraceElement {
    /// simulation time
    #[serde(rename = "time_seconds")]
    time: si::Time,
    /// simulation power
    #[serde(rename = "pwr_watts")]
    pwr: si::Power,
    /// Whether engine is on
    engine_on: Option<bool>,
}

#[altrios_api(
    #[new]
    fn __new__(
        loco_unit: Locomotive,
        power_trace: PowerTrace,
        save_interval: Option<usize>,
    ) -> Self {
        Self::new(loco_unit, power_trace, save_interval)
    }

    #[pyo3(name = "walk")]
    /// Exposes `walk` to Python.
    fn walk_py(&mut self) -> anyhow::Result<()> {
        self.walk()
    }

    #[pyo3(name = "step")]
    fn step_py(&mut self) -> anyhow::Result<()> {
        self.step()
    }

    #[pyo3(name = "set_save_interval")]
    /// Set save interval and cascade to nested components.
    fn set_save_interval_py(&mut self, save_interval: Option<usize>) -> anyhow::Result<()> {
        self.set_save_interval(save_interval);
        Ok(())
    }

    #[pyo3(name = "get_save_interval")]
    fn get_save_interval_py(&self) -> anyhow::Result<Option<usize>> {
        Ok(self.loco_unit.get_save_interval())
    }

    #[pyo3(name = "trim_failed_steps")]
    fn trim_failed_steps_py(&mut self) -> anyhow::Result<()> {
        self.trim_failed_steps()?;
        Ok(())
    }
)]
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, SerdeAPI)]
/// Struct for simulating operation of a standalone locomotive.  
pub struct LocomotiveSimulation {
    pub loco_unit: Locomotive,
    pub power_trace: PowerTrace,
    pub i: usize,
}

impl LocomotiveSimulation {
    pub fn new(
        loco_unit: Locomotive,
        power_trace: PowerTrace,
        save_interval: Option<usize>,
    ) -> Self {
        let mut loco_sim = Self {
            loco_unit,
            power_trace,
            i: 1,
        };
        loco_sim.loco_unit.set_save_interval(save_interval);
        loco_sim
    }

    /// Trims off any portion of the trip that failed to run
    pub fn trim_failed_steps(&mut self) -> anyhow::Result<()> {
        if self.i <= 1 {
            bail!("`walk` method has not proceeded past first time step.")
        }
        self.power_trace.trim(None, Some(self.i))?;

        Ok(())
    }

    pub fn set_save_interval(&mut self, save_interval: Option<usize>) {
        self.loco_unit.set_save_interval(save_interval);
    }

    pub fn get_save_interval(&self) -> Option<usize> {
        self.loco_unit.get_save_interval()
    }

    pub fn step(&mut self) -> anyhow::Result<()> {
        self.solve_step()
            .map_err(|err| err.context(format!("time step: {}", self.i)))?;
        self.save_state();
        self.i += 1;
        self.loco_unit.step();
        Ok(())
    }

    pub fn solve_step(&mut self) -> anyhow::Result<()> {
        // linear aux model
        let engine_on = self.power_trace.engine_on[self.i];
        self.loco_unit.set_pwr_aux(engine_on);
        self.loco_unit
            .set_cur_pwr_max_out(None, self.power_trace.dt(self.i))?;
        self.solve_energy_consumption(
            self.power_trace.pwr[self.i],
            self.power_trace.dt(self.i),
            engine_on,
        )?;
        ensure!(
            utils::almost_eq_uom(
                &self.power_trace.pwr[self.i],
                &self.loco_unit.state.pwr_out,
                None
            ),
            format_dbg!(
                (utils::almost_eq_uom(
                    &self.power_trace.pwr[self.i],
                    &self.loco_unit.state.pwr_out,
                    None
                ))
            )
        );
        Ok(())
    }

    fn save_state(&mut self) {
        self.loco_unit.save_state();
    }

    /// Iterates `save_state` and `step` through all time steps.
    pub fn walk(&mut self) -> anyhow::Result<()> {
        self.save_state();
        while self.i < self.power_trace.len() {
            self.step()?
        }
        ensure!(self.i == self.power_trace.len());
        Ok(())
    }

    /// Solves for fuel and RES consumption
    /// Arguments:
    /// ----------
    /// pwr_out_req: float, output brake power required from fuel converter.
    /// dt: current time step size
    /// engine_on: whether or not locomotive is active
    pub fn solve_energy_consumption(
        &mut self,
        pwr_out_req: si::Power,
        dt: si::Time,
        engine_on: Option<bool>,
    ) -> anyhow::Result<()> {
        self.loco_unit
            .solve_energy_consumption(pwr_out_req, dt, engine_on)?;
        Ok(())
    }
}

impl Default for LocomotiveSimulation {
    fn default() -> Self {
        let power_trace = PowerTrace::default();
        let loco_unit = Locomotive::default();
        Self::new(loco_unit, power_trace, None)
    }
}

#[altrios_api(
    #[pyo3(name="walk")]
    /// Exposes `walk` to Python.
    fn walk_py(&mut self, b_parallelize: Option<bool>) -> anyhow::Result<()> {
        let b_par = b_parallelize.unwrap_or(false);
        self.walk(b_par)
    }
)]
#[derive(Clone, Debug, Serialize, Deserialize, SerdeAPI)]
pub struct LocomotiveSimulationVec(pub Vec<LocomotiveSimulation>);

impl Default for LocomotiveSimulationVec {
    fn default() -> Self {
        Self(vec![LocomotiveSimulation::default(); 3])
    }
}

impl LocomotiveSimulationVec {
    /// Calls `walk` for each locomotive in vec.
    pub fn walk(&mut self, parallelize: bool) -> anyhow::Result<()> {
        if parallelize {
            self.0
                .par_iter_mut()
                .enumerate()
                .try_for_each(|(i, loco_sim)| {
                    loco_sim
                        .walk()
                        .map_err(|err| err.context(format!("loco_sim idx:{}", i)))
                })?;
        } else {
            self.0
                .iter_mut()
                .enumerate()
                .try_for_each(|(i, loco_sim)| {
                    loco_sim
                        .walk()
                        .map_err(|err| err.context(format!("loco_sim idx:{}", i)))
                })?;
        }
        Ok(())
    }
}
#[cfg(test)]
mod tests {
    use super::{Locomotive, LocomotiveSimulation, LocomotiveSimulationVec, PowerTrace};
    use crate::consist::locomotive::PowertrainType;

    #[test]
    fn test_loco_sim_vec_par() {
        let mut loco_sim_vec = LocomotiveSimulationVec::default();
        loco_sim_vec.walk(true).unwrap();
    }

    #[test]
    fn test_loco_sim_vec_ser() {
        let mut loco_sim_vec = LocomotiveSimulationVec::default();
        loco_sim_vec.walk(false).unwrap();
    }

    #[test]
    fn test_power_trace_serialize() {
        let pt = PowerTrace::default();
        let json = serde_json::to_string(&pt).unwrap();
        println!("{json}");
        let new_pt: PowerTrace = serde_json::from_str(json.as_str()).unwrap();
        println!("{new_pt:?}");
    }

    #[test]
    fn test_power_trace_serialize_yaml() {
        let pt = PowerTrace::default();
        let yaml = serde_yaml::to_string(&pt).unwrap();
        println!("{yaml}");
        let new_pt: PowerTrace = serde_yaml::from_str(yaml.as_str()).unwrap();
        println!("{new_pt:?}");
    }

    #[test]
    fn test_conventional_locomotive_sim() {
        let cl = Locomotive::default();
        let pt = PowerTrace::default();
        let mut loco_sim = LocomotiveSimulation::new(cl, pt, None);
        loco_sim.walk().unwrap();
    }

    #[test]
    fn test_hybrid_locomotive_sim() {
        // let hel = Locomotive::new(
        //     PowertrainType::HybridLoco(Box::default()),

        // );

        // let pt = PowerTrace::default();
        // let mut loco_sim = LocomotiveSimulation::new(hel, pt, None);
        // loco_sim.walk().unwrap();
    }

    #[test]
    fn test_battery_locomotive_sim() {
        let bel = Locomotive::default_battery_electric_loco();
        let pt = PowerTrace::default();
        let mut loco_sim = LocomotiveSimulation::new(bel, pt, None);
        loco_sim.walk().unwrap();
    }

    #[test]
    fn test_set_save_interval() {
        let mut ls = LocomotiveSimulation::default();

        assert!(ls.get_save_interval().is_none());
        assert!(ls.loco_unit.get_save_interval().is_none());
        assert!(match &ls.loco_unit.loco_type {
            PowertrainType::ConventionalLoco(loco) => {
                loco.fc.save_interval
            }
            _ => None,
        }
        .is_none());

        ls.set_save_interval(Some(1));

        assert_eq!(ls.get_save_interval(), Some(1));
        assert_eq!(ls.loco_unit.get_save_interval(), Some(1));
        assert_eq!(
            match &ls.loco_unit.loco_type {
                PowertrainType::ConventionalLoco(loco) => {
                    loco.fc.save_interval
                }
                _ => None,
            },
            Some(1)
        );

        ls.walk().unwrap();

        assert_eq!(ls.get_save_interval(), Some(1));
        assert_eq!(ls.loco_unit.get_save_interval(), Some(1));
        assert_eq!(
            match &ls.loco_unit.loco_type {
                PowertrainType::ConventionalLoco(loco) => {
                    loco.fc.save_interval
                }
                _ => None,
            },
            Some(1)
        );
    }

    #[test]
    fn test_power_trace_trim() {
        let pt = PowerTrace::default();
        let mut pt_test = pt.clone();

        assert!(pt == pt_test);
        pt_test.trim(None, None).unwrap();
        assert!(pt == pt_test);

        pt_test.trim(None, Some(10)).unwrap();
        assert!(pt_test != pt);
        assert!(pt_test.len() == 10);
    }
}