fastsim-core 1.0.4

Core FASTSim models for vehicle energy usage 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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
use super::{vehicle_model::VehicleState, *};
use crate::prelude::ElectricMachineState;

#[serde_api]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, StateMethods, SetCumulative)]
#[non_exhaustive]
#[serde(deny_unknown_fields)]
#[cfg_attr(feature = "pyo3", pyclass(module = "fastsim", subclass, eq))]
/// Hybrid vehicle with both engine and reversible energy storage (aka battery)
/// This type of vehicle is not likely to be widely prevalent due to modularity of consists.
pub struct HybridElectricVehicle {
    #[has_state]
    pub res: ReversibleEnergyStorage,
    pub fs: FuelStorage,
    #[has_state]
    pub fc: FuelConverter,
    #[has_state]
    pub em: ElectricMachine,
    #[has_state]
    pub transmission: Transmission,
    /// control strategy for distributing power demand between `fc` and `res`
    #[has_state]
    #[serde(default)]
    pub pt_cntrl: HEVPowertrainControls,
    /// control strategy for distributing aux power demand between `fc` and `res`
    #[serde(default)]
    pub aux_cntrl: HEVAuxControls,
    /// hybrid powertrain mass
    pub(crate) mass: Option<si::Mass>,
    #[serde(default)]
    pub sim_params: HEVSimulationParams,
    /// vector of SOC balance iterations
    #[serde(default)]
    pub soc_bal_iter_history: Vec<Self>,
    /// Number of `walk` iterations required to achieve SOC balance (i.e. SOC
    /// ends at same starting value, ensuring no net [ReversibleEnergyStorage] usage)
    #[serde(default)]
    pub soc_bal_iters: TrackedState<u32>,
}

impl HybridElectricVehicle {
    /// This method should be called after initialization but prior to
    /// simulation start. It checks that the buffer parameters are reasonable as
    /// compared to RES capacity and the like. Note: currently, this routine
    /// doesn't panic -- only writes to stderr if it detects an issue.
    pub fn check_buffers(&self, veh_mass: si::Mass) -> anyhow::Result<()> {
        // CHECK BUFFER PARAMETERS ARE REALISTIC
        let (disch_buffer, chrg_buffer, fc_on_soc) = match &self.pt_cntrl {
            HEVPowertrainControls::RGWDB(rgwdb) => {
                let disch_buffer = (0.5
                    * veh_mass
                    * rgwdb
                        .speed_soc_disch_buffer
                        .with_context(|| format_dbg!())?
                        .powi(P2::new()))
                .max(si::Energy::ZERO)
                    * rgwdb
                        .speed_soc_disch_buffer_coeff
                        .with_context(|| format_dbg!())?;

                let chrg_buffer = (0.5
                    * veh_mass
                    * ((70.0 * uc::MPH).powi(P2::new())
                        - rgwdb
                            .speed_soc_regen_buffer
                            .with_context(|| format_dbg!())?
                            .powi(P2::new())))
                .max(si::Energy::ZERO)
                    * rgwdb
                        .speed_soc_regen_buffer_coeff
                        .with_context(|| format_dbg!())?;

                let fc_on_soc = {
                    let energy_delta_to_buffer_speed: si::Energy = 0.5
                        * veh_mass
                        * rgwdb
                            .speed_soc_fc_on_buffer
                            .with_context(|| format_dbg!())?
                            .powi(P2::new());
                    energy_delta_to_buffer_speed.max(si::Energy::ZERO)
                        * rgwdb
                            .speed_soc_fc_on_buffer_coeff
                            .with_context(|| format_dbg!())?
                } / self.res.energy_capacity_usable()
                    + self.res.min_soc;

                (disch_buffer, chrg_buffer, fc_on_soc)
            }
        };
        if fc_on_soc > self.res.max_soc {
            eprintln!("fc_on_soc > self.res.max_soc");
            eprintln!("fc_on_soc: {:?}", fc_on_soc);
        }
        if fc_on_soc < self.res.min_soc {
            eprintln!("fc_on_soc < self.res.min_soc");
            eprintln!("fc_on_soc: {:?}", fc_on_soc);
        }
        if disch_buffer > self.res.energy_capacity_usable() {
            eprintln!("disch_buffer < self.res.energy_capacity_usable()");
            eprintln!(
                "disch_buffer: {:?} kWh",
                disch_buffer.get::<si::kilowatt_hour>()
            );
            eprintln!(
                "RES usable energy capacity: {:?} kWh",
                self.res.energy_capacity_usable().get::<si::kilowatt_hour>()
            );
        }
        if chrg_buffer > self.res.energy_capacity_usable() {
            eprintln!("disch_buffer < self.res.energy_capacity_usable()");
            eprintln!(
                "chrg_buffer: {:?} kWh",
                chrg_buffer.get::<si::kilowatt_hour>()
            );
            eprintln!(
                "RES usable energy capacity: {:?} kWh",
                self.res.energy_capacity_usable().get::<si::kilowatt_hour>()
            );
        }
        Ok(())
    }
}

#[pyo3_api]
impl HybridElectricVehicle {}

impl HistoryMethods for HybridElectricVehicle {
    fn save_interval(&self) -> anyhow::Result<Option<usize>> {
        bail!("`save_interval` is not implemented in HybridElectricVehicle")
    }
    fn set_save_interval(&mut self, save_interval: Option<usize>) -> anyhow::Result<()> {
        self.res.set_save_interval(save_interval)?;
        // self.fs.set_save_interval(save_interval)?;
        self.fc.set_save_interval(save_interval)?;
        self.em.set_save_interval(save_interval)?;
        self.transmission.set_save_interval(save_interval)?;
        self.pt_cntrl.set_save_interval(save_interval)?;
        Ok(())
    }
    fn clear(&mut self) {
        self.res.clear();
        // self.fs.clear();
        self.fc.clear();
        self.em.clear();
        self.transmission.clear();
        self.pt_cntrl.clear();
    }
}

impl Init for HybridElectricVehicle {
    fn init(&mut self) -> Result<(), Error> {
        self.fc
            .init()
            .map_err(|err| Error::InitError(format_dbg!(err)))?;
        self.res
            .init()
            .map_err(|err| Error::InitError(format_dbg!(err)))?;
        self.em
            .init()
            .map_err(|err| Error::InitError(format_dbg!(err)))?;
        self.transmission
            .init()
            .map_err(|err| Error::InitError(format_dbg!(err)))?;
        self.pt_cntrl
            .init()
            .map_err(|err| Error::InitError(format_dbg!(err)))?;
        Ok(())
    }
}

impl SerdeAPI for HybridElectricVehicle {}

impl Powertrain for Box<HybridElectricVehicle> {
    fn set_curr_pwr_prop_out_max(
        &mut self,
        _pwr_upstream: (si::Power, si::Power),
        pwr_aux: si::Power,
        dt: si::Time,
        veh_state: &VehicleState,
    ) -> anyhow::Result<()> {
        // TODO: account for transmission efficiency in here
        let (disch_buffer, chrg_buffer) = match &mut self.pt_cntrl {
            HEVPowertrainControls::RGWDB(rgwdb) => {
                rgwdb.handle_fc_on_causes(&self.fc, veh_state, &self.res, &self.em.state)?;

                let disch_buffer = (0.5
                    * *veh_state.mass.get_fresh(|| format_dbg!())?
                    * (rgwdb
                        .speed_soc_disch_buffer
                        .with_context(|| format_dbg!())?
                        .powi(P2::new())
                        - veh_state
                            .speed_ach
                            .get_stale(|| format_dbg!())?
                            .powi(P2::new())))
                .max(si::Energy::ZERO)
                    * rgwdb
                        .speed_soc_disch_buffer_coeff
                        .with_context(|| format_dbg!())?;

                let chrg_buffer = (0.5
                    * *veh_state.mass.get_fresh(|| format_dbg!())?
                    * (veh_state
                        .speed_ach
                        .get_stale(|| format_dbg!())?
                        .powi(P2::new())
                        - rgwdb
                            .speed_soc_regen_buffer
                            .with_context(|| format_dbg!())?
                            .powi(P2::new())))
                .max(si::Energy::ZERO)
                    * rgwdb
                        .speed_soc_regen_buffer_coeff
                        .with_context(|| format_dbg!())?;

                (disch_buffer, chrg_buffer)
            }
        };
        // set total max powers, including aux power
        self.fc
            .set_curr_pwr_out_max(dt)
            .with_context(|| anyhow!(format_dbg!()))?;
        self.res
            .set_curr_pwr_out_max(dt, disch_buffer, chrg_buffer)
            .with_context(|| anyhow!(format_dbg!()))?;

        // determine distribution of aux power between engine and battery
        let (pwr_aux_res, pwr_aux_fc) = {
            match self.aux_cntrl {
                HEVAuxControls::AuxOnResPriority => {
                    if pwr_aux <= *self.res.state.pwr_disch_max.get_fresh(|| format_dbg!())? {
                        (pwr_aux, si::Power::ZERO)
                    } else {
                        (si::Power::ZERO, pwr_aux)
                    }
                }
                HEVAuxControls::AuxOnFcPriority => (si::Power::ZERO, pwr_aux),
            }
        };

        match &mut self.pt_cntrl {
            HEVPowertrainControls::RGWDB(rgwdb) => {
                rgwdb
                    .state
                    .aux_power_demand
                    .update(pwr_aux_fc > si::Power::ZERO, || format_dbg!())?;
            }
        }

        // set max propulsion powers
        self.fc
            .set_curr_pwr_prop_max(pwr_aux_fc)
            .with_context(|| anyhow!(format_dbg!()))?;
        self.res
            .set_curr_pwr_prop_max(pwr_aux_res)
            .with_context(|| anyhow!(format_dbg!()))?;
        self.em
            .set_curr_pwr_prop_out_max(
                // TODO: add means of controlling whether fc can provide power to em and also how much
                // Try out a 'power out type' enum field on the fuel converter with variants for mechanical and electrical
                self.res
                    .get_curr_pwr_prop_out_max()
                    .with_context(|| format_dbg!())?,
                pwr_aux,
                dt,
                veh_state,
            )
            .with_context(|| anyhow!(format_dbg!()))?;
        let em_pwr_prop_out_maxes = self
            .em
            .get_curr_pwr_prop_out_max()
            .with_context(|| format_dbg!())?;
        let fc_max = self.fc.state.pwr_prop_max.get_fresh(|| format_dbg!())?;
        self.transmission
            .set_curr_pwr_prop_out_max(
                (em_pwr_prop_out_maxes.0 + *fc_max, em_pwr_prop_out_maxes.1),
                f64::NAN * uc::W,
                dt,
                veh_state,
            )
            .with_context(|| format_dbg!())?;
        Ok(())
    }

    fn get_curr_pwr_prop_out_max(&self) -> anyhow::Result<(si::Power, si::Power)> {
        self.transmission
            .get_curr_pwr_prop_out_max()
            .with_context(|| format_dbg!())
    }

    fn solve(
        &mut self,
        pwr_out_req: si::Power,
        _enabled: bool,
        dt: si::Time,
    ) -> anyhow::Result<Option<si::Power>> {
        // TODO: address these concerns
        // - what happens when the fc is on and producing more power than the
        //   transmission requires? It seems like the excess goes straight to the battery,
        //   but it should probably go thourgh the em somehow.
        let pwr_in_transmission = self
            .transmission
            .solve(pwr_out_req, true, dt)
            .with_context(|| format_dbg!())?
            .with_context(|| format!("{}\nExpected `Some`", format_dbg!()))?;

        // TODO: use an enum with a match here to determine whether power is shared by
        // - fc and em (e.g. for ICE HEV)
        //   or
        // - fc and res (e.g. for H2FC HEV)

        let (fc_pwr_out_req, em_pwr_out_req) = self
            .pt_cntrl
            .get_pwr_fc_and_em(pwr_in_transmission, &self.fc, &self.em.state, &self.res)
            .with_context(|| format_dbg!())?;
        let fc_on: bool = self.pt_cntrl.engine_on()?;

        self.fc
            .solve(fc_pwr_out_req, fc_on, dt)
            .with_context(|| format_dbg!())?;
        let res_pwr_out_req = self
            .em
            .solve(em_pwr_out_req, true, dt)
            .with_context(|| format_dbg!())?
            .with_context(|| format!("{}\nExpected `Some`", format_dbg!()))?;
        // TODO: `res_pwr_out_req` probably does not include charging from the engine
        self.res
            .solve(res_pwr_out_req, dt)
            .with_context(|| format_dbg!())?;
        Ok(None)
    }

    /// Regen braking power, positive means braking is happening
    fn pwr_regen(&self) -> anyhow::Result<si::Power> {
        // When `pwr_mech_prop_out` is negative, regen is happening.  First, clip it at 0, and then negate it.
        // see https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=e8f7af5a6e436dd1163fa3c70931d18d
        // for example
        self.transmission.pwr_regen().with_context(|| format_dbg!())
    }
}

impl HybridElectricVehicle {
    /// # Arguments
    /// - `te_amb`: ambient temperature
    /// - `pwr_thrml_fc_to_cab`: thermal power flow from [FuelConverter::thrml]
    ///   to [Vehicle::cabin], if cabin is equipped
    /// - `veh_state`: current [VehicleState]
    /// - `pwr_thrml_hvac_to_res`: thermal power flow from [Vehicle::hvac] --
    ///   zero if `None` is passed
    /// - `te_cab`: cabin temperature, required if [ReversibleEnergyStorage::thrml] is `Some`
    /// - `dt`: simulation time step size
    pub fn solve_thermal(
        &mut self,
        te_amb: si::Temperature,
        pwr_thrml_fc_to_cab: Option<si::Power>,
        veh_state: &mut VehicleState,
        pwr_thrml_hvac_to_res: Option<si::Power>,
        te_cab: Option<si::Temperature>,
        dt: si::Time,
    ) -> anyhow::Result<()> {
        self.fc
            .solve_thermal(te_amb, pwr_thrml_fc_to_cab, veh_state, dt)
            .with_context(|| format_dbg!())?;
        self.res
            .solve_thermal(
                te_amb,
                pwr_thrml_hvac_to_res.unwrap_or_default(),
                te_cab,
                dt,
            )
            .with_context(|| format_dbg!())?;
        Ok(())
    }
}

impl TryFrom<&fastsim_2::vehicle::RustVehicle> for HybridElectricVehicle {
    type Error = anyhow::Error;
    fn try_from(f2veh: &fastsim_2::vehicle::RustVehicle) -> anyhow::Result<HybridElectricVehicle> {
        let pt_cntrl = HEVPowertrainControls::RGWDB(Box::new(hev::RESGreedyWithDynamicBuffers {
            speed_soc_fc_on_buffer: None,
            speed_soc_fc_on_buffer_coeff: None,
            speed_soc_disch_buffer: None,
            speed_soc_disch_buffer_coeff: None,
            speed_soc_regen_buffer: None,
            speed_soc_regen_buffer_coeff: None,
            // note that this exists in `fastsim-2` but has no apparent effect!
            fc_min_time_on: None,
            speed_fc_forced_on: Some(f2veh.mph_fc_on * uc::MPH),
            frac_pwr_demand_fc_forced_on: Some(
                f2veh.kw_demand_fc_on / (f2veh.fc_max_kw + f2veh.ess_max_kw.min(f2veh.mc_max_kw))
                    * uc::R,
            ),
            frac_of_most_eff_pwr_to_run_fc: None,
            temp_fc_forced_on: None,
            temp_fc_allowed_off: None,
            save_interval: Some(1),
            state: Default::default(),
            history: Default::default(),
        }));
        let mut hev = HybridElectricVehicle {
            fs: {
                let mut fs = FuelStorage {
                    pwr_out_max: f2veh.fs_max_kw * uc::KW,
                    pwr_ramp_lag: f2veh.fs_secs_to_peak_pwr * uc::S,
                    energy_capacity: f2veh.fs_kwh * 3.6 * uc::MJ,
                    specific_energy: None,
                    mass: None,
                };
                fs.set_mass(None, MassSideEffect::None)
                    .with_context(|| anyhow!(format_dbg!()))?;
                fs
            },
            fc: FuelConverter::try_from(f2veh.clone())?,
            res: ReversibleEnergyStorage::try_from(f2veh.clone()).with_context(|| format_dbg!())?,
            em: ElectricMachine::try_from(f2veh.clone())?,
            transmission: Transmission::try_from(f2veh.clone())?,
            pt_cntrl,
            mass: None,
            sim_params: Default::default(),
            aux_cntrl: Default::default(),
            soc_bal_iter_history: Default::default(),
            soc_bal_iters: Default::default(),
        };
        hev.init()?;
        Ok(hev)
    }
}
impl Mass for HybridElectricVehicle {
    fn mass(&self) -> anyhow::Result<Option<si::Mass>> {
        let derived_mass = self
            .derived_mass()
            .with_context(|| anyhow!(format_dbg!()))?;
        match (derived_mass, self.mass) {
            (Some(derived_mass), Some(set_mass)) => {
                ensure!(
                    utils::almost_eq_uom(&set_mass, &derived_mass, None),
                    format!(
                        "{}",
                        format_dbg!(utils::almost_eq_uom(&set_mass, &derived_mass, None)),
                    )
                );
                Ok(Some(set_mass))
            }
            _ => Ok(self.mass.or(derived_mass)),
        }
    }

    fn set_mass(
        &mut self,
        new_mass: Option<si::Mass>,
        side_effect: MassSideEffect,
    ) -> anyhow::Result<()> {
        ensure!(
            side_effect == MassSideEffect::None,
            "At the powertrain level, only `MassSideEffect::None` is allowed"
        );
        let derived_mass = self
            .derived_mass()
            .with_context(|| anyhow!(format_dbg!()))?;
        self.mass = match new_mass {
            // Set using provided `new_mass`, setting constituent mass fields to `None` to match if inconsistent
            Some(new_mass) => {
                if let Some(dm) = derived_mass {
                    if dm != new_mass {
                        self.expunge_mass_fields();
                    }
                }
                Some(new_mass)
            }
            // Set using `derived_mass()`, failing if it returns `None`
            None => Some(derived_mass.with_context(|| {
                format!(
                    "Not all mass fields in `{}` are set and no mass was provided.",
                    stringify!(HybridElectricVehicle)
                )
            })?),
        };
        Ok(())
    }

    fn derived_mass(&self) -> anyhow::Result<Option<si::Mass>> {
        let fc_mass = self.fc.mass().with_context(|| anyhow!(format_dbg!()))?;
        let fs_mass = self.fs.mass().with_context(|| anyhow!(format_dbg!()))?;
        let res_mass = self.res.mass().with_context(|| anyhow!(format_dbg!()))?;
        let em_mass = self.em.mass().with_context(|| anyhow!(format_dbg!()))?;
        let transmission_mass = self
            .transmission
            .mass()
            .with_context(|| anyhow!(format_dbg!()))?;
        match (fc_mass, fs_mass, res_mass, em_mass, transmission_mass) {
            (
                Some(fc_mass),
                Some(fs_mass),
                Some(res_mass),
                Some(em_mass),
                Some(transmission_mass),
            ) => Ok(Some(
                fc_mass + fs_mass + res_mass + em_mass + transmission_mass,
            )),
            (None, None, None, None, None) => Ok(None),
            _ => bail!(
                "`{}` field masses are not consistently set to `Some` or `None`",
                stringify!(HybridElectricVehicle)
            ),
        }
    }

    fn expunge_mass_fields(&mut self) {
        self.fc.expunge_mass_fields();
        self.fs.expunge_mass_fields();
        self.res.expunge_mass_fields();
        self.em.expunge_mass_fields();
        self.transmission.expunge_mass_fields();
        self.mass = None;
    }
}

#[serde_api]
#[derive(
    Clone,
    Debug,
    Default,
    Deserialize,
    Serialize,
    PartialEq,
    HistoryVec,
    StateMethods,
    SetCumulative,
)]
#[non_exhaustive]
#[serde(deny_unknown_fields)]
pub struct RGWDBState {
    /// time step index
    pub i: TrackedState<usize>,
    /// Engine must be on to self heat if thermal model is enabled
    pub fc_temperature_too_low: TrackedState<bool>,
    /// Engine must be on for high vehicle speed to ensure powertrain can meet
    /// any spikes in power demand
    pub vehicle_speed_too_high: TrackedState<bool>,
    /// Engine has not been on long enough (usually 30 s)
    pub on_time_too_short: TrackedState<bool>,
    /// Powertrain power demand exceeds motor and/or battery capabilities
    pub propulsion_power_demand: TrackedState<bool>,
    /// Powertrain power demand exceeds optimal motor and/or battery output
    pub propulsion_power_demand_soft: TrackedState<bool>,
    /// Aux power demand exceeds battery capability
    pub aux_power_demand: TrackedState<bool>,
    /// SOC is below min buffer so FC is charging RES
    pub charging_for_low_soc: TrackedState<bool>,
    /// buffer at which FC is forced on
    pub soc_fc_on_buffer: TrackedState<si::Ratio>,
}
impl SerdeAPI for RGWDBState {}
impl Init for RGWDBState {}

impl RGWDBState {
    /// If any of the causes are true, engine must be on
    fn engine_on(&self) -> anyhow::Result<bool> {
        Ok(*self.fc_temperature_too_low.get_fresh(|| format_dbg!())?
            || *self.vehicle_speed_too_high.get_fresh(|| format_dbg!())?
            || *self.on_time_too_short.get_fresh(|| format_dbg!())?
            || *self.propulsion_power_demand.get_fresh(|| format_dbg!())?
            || *self
                .propulsion_power_demand_soft
                .get_fresh(|| format_dbg!())?
            || *self.aux_power_demand.get_fresh(|| format_dbg!())?
            || *self.charging_for_low_soc.get_fresh(|| format_dbg!())?)
    }
}

/// Options for controlling simulation behavior
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
#[non_exhaustive]
#[serde(deny_unknown_fields)]
pub struct HEVSimulationParams {
    /// [ReversibleEnergyStorage] per [FuelConverter]
    pub res_per_fuel_lim: si::Ratio,
    /// Threshold of SOC balancing iteration for triggering error
    pub soc_balance_iter_err: u32,
    /// Whether to allow iteration to achieve SOC balance
    pub balance_soc: bool,
    /// Whether to save each SOC balance iteration    
    pub save_soc_bal_iters: bool,
}

impl Default for HEVSimulationParams {
    fn default() -> Self {
        Self {
            res_per_fuel_lim: uc::R * 0.005,
            soc_balance_iter_err: 5,
            balance_soc: true,
            save_soc_bal_iters: false,
        }
    }
}

#[derive(
    Clone, Debug, PartialEq, Deserialize, Serialize, Default, IsVariant, derive_more::From, TryInto,
)]
pub enum HEVAuxControls {
    /// If feasible, use [ReversibleEnergyStorage] to handle aux power demand
    #[default]
    AuxOnResPriority,
    /// If feasible, use [FuelConverter] to handle aux power demand
    AuxOnFcPriority,
}

#[derive(
    Clone, Debug, PartialEq, Deserialize, Serialize, IsVariant, derive_more::From, TryInto,
)]
pub enum HEVPowertrainControls {
    /// Greedily uses [ReversibleEnergyStorage] with buffers that derate charge
    /// and discharge power inside of static min and max SOC range.  Also, includes
    /// buffer for forcing [FuelConverter] to be active/on.
    RGWDB(Box<RESGreedyWithDynamicBuffers>),
}

impl Default for HEVPowertrainControls {
    fn default() -> Self {
        Self::RGWDB(Default::default())
    }
}

impl SetCumulative for HEVPowertrainControls {
    fn set_cumulative<F: Fn() -> String>(&mut self, dt: si::Time, loc: F) -> anyhow::Result<()> {
        match self {
            Self::RGWDB(rgwdb) => {
                rgwdb.set_cumulative(dt, || format!("{}\n{}", loc(), format_dbg!()))?
            }
        }
        Ok(())
    }

    fn reset_cumulative<F: Fn() -> String>(&mut self, loc: F) -> anyhow::Result<()> {
        match self {
            Self::RGWDB(rgwdb) => {
                rgwdb.reset_cumulative(|| format!("{}\n{}", loc(), format_dbg!()))?
            }
        }
        Ok(())
    }
}
impl Step for HEVPowertrainControls {
    fn step<F: Fn() -> String>(&mut self, loc: F) -> anyhow::Result<()> {
        match self {
            HEVPowertrainControls::RGWDB(rgwdb) => rgwdb.step(loc)?,
        }
        Ok(())
    }

    fn reset_step<F: Fn() -> String>(&mut self, loc: F) -> anyhow::Result<()> {
        match self {
            HEVPowertrainControls::RGWDB(rgwdb) => rgwdb.reset_step(loc)?,
        }
        Ok(())
    }
}

impl StateMethods for HEVPowertrainControls {}

impl SaveState for HEVPowertrainControls {
    fn save_state<F: Fn() -> String>(&mut self, loc: F) -> anyhow::Result<()> {
        match self {
            HEVPowertrainControls::RGWDB(rgwdb) => rgwdb.save_state(loc)?,
        }
        Ok(())
    }
}
impl TrackedStateMethods for HEVPowertrainControls {
    fn check_and_reset<F: Fn() -> String>(&mut self, loc: F) -> anyhow::Result<()> {
        match self {
            HEVPowertrainControls::RGWDB(rgwdb) => rgwdb.check_and_reset(loc)?,
        }
        Ok(())
    }

    fn mark_fresh<F: Fn() -> String>(&mut self, loc: F) -> anyhow::Result<()> {
        match self {
            HEVPowertrainControls::RGWDB(rgwdb) => rgwdb.mark_fresh(loc)?,
        }
        Ok(())
    }
}
impl HistoryMethods for HEVPowertrainControls {
    fn set_save_interval(&mut self, save_interval: Option<usize>) -> anyhow::Result<()> {
        match self {
            HEVPowertrainControls::RGWDB(rgwdb) => Ok(rgwdb.set_save_interval(save_interval)?),
        }
    }

    fn save_interval(&self) -> anyhow::Result<Option<usize>> {
        match self {
            HEVPowertrainControls::RGWDB(rgwdb) => rgwdb.save_interval(),
        }
    }
    fn clear(&mut self) {
        match self {
            HEVPowertrainControls::RGWDB(rgwdb) => rgwdb.clear(),
        }
    }
}

impl Init for HEVPowertrainControls {
    fn init(&mut self) -> Result<(), Error> {
        match self {
            Self::RGWDB(rgwb) => rgwb.init()?,
        }
        Ok(())
    }
}

impl HEVPowertrainControls {
    /// Determines power split between engine and electric machine
    ///
    /// # Arguments
    /// - `pwr_prop_req`: tractive power required
    /// - `veh_state`: vehicle state
    /// - `hev_state`: HEV powertrain state
    /// - `fc`: fuel converter
    /// - `em_state`: electric machine state
    /// - `res`: reversible energy storage (e.g. high voltage battery)
    fn get_pwr_fc_and_em(
        &mut self,
        pwr_prop_req: si::Power,
        fc: &FuelConverter,
        em_state: &ElectricMachineState,
        res: &ReversibleEnergyStorage,
    ) -> anyhow::Result<(si::Power, si::Power)> {
        let fc_state = &fc.state;
        ensure!(
            // `almost` is in case of negligible numerical precision discrepancies
            almost_le_uom(
                &pwr_prop_req,
                &(*em_state.pwr_mech_fwd_out_max.get_fresh(|| format_dbg!())?
                    + *fc_state.pwr_prop_max.get_fresh(|| format_dbg!())?),
                None
            ),
            "{}
`pwr_out_req`: {} kW
`em_state.pwr_mech_fwd_out_max`: {} kW
`fc_state.pwr_prop_max`: {} kW
`res.state.soc`: {}",
            format_dbg!(),
            pwr_prop_req.get::<si::kilowatt>(),
            em_state
                .pwr_mech_fwd_out_max
                .get_fresh(|| format_dbg!())?
                .get::<si::kilowatt>(),
            fc_state
                .pwr_prop_max
                .get_fresh(|| format_dbg!())?
                .get::<si::kilowatt>(),
            res.state
                .soc
                .get_fresh(|| format_dbg!())?
                .get::<si::ratio>()
        );

        // # Brain dump for thermal stuff
        // TODO: engine on/off w.r.t. thermal stuff should not come into play
        // if there is no component (e.g. cabin) demanding heat from the engine.  My 2019
        // Hyundai Ioniq will turn the engine off if there is no heat demand regardless of
        // the coolant temperature
        // TODO: make sure idle fuel gets converted to heat correctly

        match self {
            Self::RGWDB(rgwdb) => rgwdb.get_pwr_fc_and_em(fc, pwr_prop_req, em_state),
        }
    }

    pub fn engine_on(&self) -> anyhow::Result<bool> {
        match self {
            Self::RGWDB(rgwdb) => rgwdb.state.engine_on(),
        }
    }
}

/// Greedily uses [ReversibleEnergyStorage] with buffers that derate charge
/// and discharge power inside of static min and max SOC range.  Also, includes
/// buffer for forcing [FuelConverter] to be active/on. See [Self::init] for
/// default values.
#[serde_api]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, Default, StateMethods, SetCumulative)]
#[cfg_attr(feature = "pyo3", pyclass(module = "fastsim", subclass, eq))]
#[non_exhaustive]
#[serde(deny_unknown_fields)]
pub struct RESGreedyWithDynamicBuffers {
    /// RES energy delta from minimum SOC corresponding to kinetic energy of
    /// vehicle at this speed that triggers ramp down in RES discharge.
    pub speed_soc_disch_buffer: Option<si::Velocity>,
    /// Coefficient for modifying amount of accel buffer
    pub speed_soc_disch_buffer_coeff: Option<si::Ratio>,
    /// RES energy delta from minimum SOC corresponding to kinetic energy of
    /// vehicle at this speed that triggers FC to be forced on.
    pub speed_soc_fc_on_buffer: Option<si::Velocity>,
    /// Coefficient for modifying amount of [Self::speed_soc_fc_on_buffer]
    pub speed_soc_fc_on_buffer_coeff: Option<si::Ratio>,
    /// RES energy delta from maximum SOC corresponding to kinetic energy of
    /// vehicle at current speed minus kinetic energy of vehicle at this speed
    /// triggers ramp down in RES discharge
    pub speed_soc_regen_buffer: Option<si::Velocity>,
    /// Coefficient for modifying amount of regen buffer
    pub speed_soc_regen_buffer_coeff: Option<si::Ratio>,
    /// Minimum time engine must remain on if it was on during the previous
    /// simulation time step.
    pub fc_min_time_on: Option<si::Time>,
    /// Speed at which [FuelConverter] is forced on.
    pub speed_fc_forced_on: Option<si::Velocity>,
    /// Fraction of total aux and powertrain rated power at which
    /// [FuelConverter] is forced on.
    pub frac_pwr_demand_fc_forced_on: Option<si::Ratio>,
    /// Force engine, if on, to run at this fraction of power at which peak
    /// efficiency occurs or the required power, whichever is greater. If SOC is
    /// below min buffer or engine is otherwise forced on and battery has room
    /// to receive charge, engine will run at this level and charge.
    pub frac_of_most_eff_pwr_to_run_fc: Option<si::Ratio>,
    /// Fraction of available charging capacity to use toward running the engine
    /// efficiently.
    /// Time step interval between saves. 1 is a good option. If None, no saving occurs.
    pub save_interval: Option<usize>,
    /// temperature at which engine is forced on to warm up
    #[serde(default)]
    pub temp_fc_forced_on: Option<si::Temperature>,
    /// temperature at which engine is allowed to turn off due to being sufficiently warm
    #[serde(default)]
    pub temp_fc_allowed_off: Option<si::Temperature>,
    /// current state of control variables
    #[serde(default)]
    pub state: RGWDBState,
    #[serde(default)]
    /// history of current state
    pub history: RGWDBStateHistoryVec,
}

#[pyo3_api]
impl RESGreedyWithDynamicBuffers {}

impl HistoryMethods for RESGreedyWithDynamicBuffers {
    fn set_save_interval(&mut self, save_interval: Option<usize>) -> anyhow::Result<()> {
        self.save_interval = save_interval;
        Ok(())
    }

    fn save_interval(&self) -> anyhow::Result<Option<usize>> {
        Ok(self.save_interval)
    }

    fn clear(&mut self) {
        self.history.clear();
    }
}

impl Init for RESGreedyWithDynamicBuffers {
    fn init(&mut self) -> Result<(), Error> {
        // TODO: make sure these values propagate to the documented defaults above
        init_opt_default!(self, speed_soc_disch_buffer, 50.0 * uc::MPH);
        init_opt_default!(self, speed_soc_disch_buffer_coeff, 1.0 * uc::R);
        init_opt_default!(
            self,
            speed_soc_fc_on_buffer,
            self.speed_soc_disch_buffer.unwrap() * 1.2
        );
        init_opt_default!(self, speed_soc_fc_on_buffer_coeff, 1.0 * uc::R);
        init_opt_default!(self, speed_soc_regen_buffer, 30. * uc::MPH);
        init_opt_default!(self, speed_soc_regen_buffer_coeff, 1.0 * uc::R);
        init_opt_default!(self, fc_min_time_on, uc::S * 5.0);
        init_opt_default!(self, speed_fc_forced_on, uc::MPH * 75.);
        init_opt_default!(self, frac_pwr_demand_fc_forced_on, uc::R * 0.75);
        init_opt_default!(self, frac_of_most_eff_pwr_to_run_fc, 1.0 * uc::R);
        Ok(())
    }
}
impl SerdeAPI for RESGreedyWithDynamicBuffers {}

impl RESGreedyWithDynamicBuffers {
    fn get_pwr_fc_and_em(
        &mut self,
        fc: &FuelConverter,
        pwr_prop_req: si::Power,
        em_state: &ElectricMachineState,
    ) -> anyhow::Result<(si::Power, si::Power)> {
        // Tractive power `em` must provide before deciding power
        // split, cannot exceed ElectricMachine max output power.
        // Excess demand will be handled by `fc`.  Favors drawing power from
        // `em` before engine
        let em_pwr = pwr_prop_req
            .min(*em_state.pwr_mech_fwd_out_max.get_fresh(|| format_dbg!())?)
            .max(-*em_state.pwr_mech_regen_max.get_fresh(|| format_dbg!())?);
        // tractive power handled by fc
        let (fc_pwr, em_pwr) = if !self.state.engine_on()? {
            // engine is off, and `em_pwr` has already been limited within bounds
            (si::Power::ZERO, em_pwr)
        } else {
            // engine has been forced on
            let frac_of_pwr_for_peak_eff: si::Ratio = self
                .frac_of_most_eff_pwr_to_run_fc
                .with_context(|| format_dbg!())?;
            let fc_pwr = if pwr_prop_req < si::Power::ZERO {
                // negative tractive power
                // max power system can receive from engine during negative traction
                (*em_state.pwr_mech_regen_max.get_fresh(|| format_dbg!())? + pwr_prop_req)
                    // or peak efficiency power if it's lower than above
                    .min(fc.pwr_for_peak_eff * frac_of_pwr_for_peak_eff)
                    // but not negative
                    .max(si::Power::ZERO)
            } else {
                // positive tractive power
                if pwr_prop_req - em_pwr > fc.pwr_for_peak_eff * frac_of_pwr_for_peak_eff {
                    // engine needs to run higher than peak efficiency point
                    pwr_prop_req - em_pwr
                } else {
                    // engine does not need to run higher than peak
                    // efficiency point to make tractive demand

                    // fc handles all power not covered by em
                    (pwr_prop_req - em_pwr)
                        // and if that's less than the
                        // efficiency-focused value, then operate at
                        // that value
                        .max(fc.pwr_for_peak_eff * frac_of_pwr_for_peak_eff)
                        // but don't exceed what what the battery can
                        // absorb + tractive demand
                        .min(
                            pwr_prop_req
                                + *em_state.pwr_mech_regen_max.get_fresh(|| format_dbg!())?,
                        )
                }
            }
            // and don't exceed what the fc can do
            .min(*fc.state.pwr_prop_max.get_fresh(|| format_dbg!())?);

            // recalculate `em_pwr` based on `fc_pwr`
            let em_pwr_corrected = (pwr_prop_req - fc_pwr)
                .max(-*em_state.pwr_mech_regen_max.get_fresh(|| format_dbg!())?);
            (fc_pwr, em_pwr_corrected)
        };
        Ok((fc_pwr, em_pwr))
    }

    fn handle_fc_on_causes(
        &mut self,
        fc: &FuelConverter,
        veh_state: &VehicleState,
        res: &ReversibleEnergyStorage,
        em_state: &ElectricMachineState,
    ) -> Result<(), anyhow::Error> {
        self.handle_fc_on_causes_for_temp(fc)?;
        self.handle_fc_on_causes_for_speed(veh_state)?;
        self.handle_fc_on_causes_for_low_soc(res, veh_state)?;
        self.handle_fc_on_causes_for_pwr_demand(
            *veh_state
                .pwr_tractive
                .get_stale(|| format_dbg!(veh_state.pwr_tractive))?,
            em_state,
            &fc.state,
        )
        .with_context(|| format_dbg!())?;
        self.handle_fc_on_causes_for_on_time(fc)?;
        Ok(())
    }

    fn handle_fc_on_causes_for_on_time(&mut self, fc: &FuelConverter) -> Result<(), anyhow::Error> {
        self.state.on_time_too_short.update(*fc.state.fc_on.get_stale(|| format_dbg!())? && *fc.state.time_on.get_stale(|| format_dbg!())?
                    < self.fc_min_time_on.with_context(|| {
                    anyhow!(
                        "{}\n Expected `ResGreedyWithBuffers::init` to have been called beforehand.",
                        format_dbg!()
                    )
                })?, || format_dbg!())?;
        Ok(())
    }

    /// Determines whether power demand requires engine to be on.  Not needed during
    /// negative traction.
    fn handle_fc_on_causes_for_pwr_demand(
        &mut self,
        pwr_out_req_for_cyc: si::Power,
        em_state: &ElectricMachineState,
        fc_state: &FuelConverterState,
    ) -> Result<(), anyhow::Error> {
        let frac_pwr_demand_fc_forced_on: si::Ratio = self
            .frac_pwr_demand_fc_forced_on
            .with_context(|| format_dbg!())?;
        self.state.propulsion_power_demand_soft.update(
            pwr_out_req_for_cyc
                > frac_pwr_demand_fc_forced_on
                    * (*em_state.pwr_mech_fwd_out_max.get_stale(|| format_dbg!())?
                        + *fc_state.pwr_out_max.get_stale(|| format_dbg!())?),
            || format_dbg!(),
        )?;
        self.state.propulsion_power_demand.update(
            pwr_out_req_for_cyc - *em_state.pwr_mech_fwd_out_max.get_stale(|| format_dbg!())?
                >= si::Power::ZERO,
            || format_dbg!(),
        )?;
        Ok(())
    }

    /// Detemrines whether engine must be on to charge battery
    fn handle_fc_on_causes_for_low_soc(
        &mut self,
        res: &ReversibleEnergyStorage,
        veh_state: &VehicleState,
    ) -> anyhow::Result<()> {
        self.state.soc_fc_on_buffer.update(
            {
                let energy_delta_to_buffer_speed: si::Energy = 0.5
                    * *veh_state.mass.get_fresh(|| format_dbg!())?
                    * (self
                        .speed_soc_fc_on_buffer
                        .with_context(|| format_dbg!())?
                        .powi(P2::new())
                        - veh_state
                            .speed_ach
                            .get_stale(|| format_dbg!())?
                            .powi(P2::new()));
                energy_delta_to_buffer_speed.max(si::Energy::ZERO)
                    * self
                        .speed_soc_fc_on_buffer_coeff
                        .with_context(|| format_dbg!())?
            } / res.energy_capacity_usable()
                + res.min_soc,
            || format_dbg!(),
        )?;
        self.state.charging_for_low_soc.update(
            *res.state.soc.get_stale(|| format_dbg!())?
                < *self.state.soc_fc_on_buffer.get_fresh(|| format_dbg!())?,
            || format_dbg!(),
        )?;
        Ok(())
    }

    /// Determines whether enigne must be on for high speed
    fn handle_fc_on_causes_for_speed(&mut self, veh_state: &VehicleState) -> anyhow::Result<()> {
        self.state.vehicle_speed_too_high.update(
            *veh_state.speed_ach.get_stale(|| format_dbg!())?
                > self.speed_fc_forced_on.with_context(|| format_dbg!())?,
            || format_dbg!(),
        )?;
        Ok(())
    }

    /// Determines whether engine needs to be on due to low temperature and pushes
    /// appropriate variant to `fc_on_causes`
    fn handle_fc_on_causes_for_temp(&mut self, fc: &FuelConverter) -> anyhow::Result<()> {
        match (
            match fc.temperature() {
                Some(fct) => Some(*fct.get_fresh(|| format_dbg!())?),
                None => None,
            },
            match fc.temperature() {
                Some(fct) => Some(*fct.get_fresh(|| format_dbg!())?),
                None => None,
            },
            self.temp_fc_forced_on,
            self.temp_fc_allowed_off,
        ) {
            (None, None, None, None) => {
                self.state
                    .fc_temperature_too_low
                    .update(false, || format_dbg!())?;
            }
            (
                Some(temperature),
                Some(temp_prev),
                Some(temp_fc_forced_on),
                Some(temp_fc_allowed_off),
            ) => {
                self.state.fc_temperature_too_low.update(
                    // temperature is currently below forced on threshold
                    temperature < temp_fc_forced_on ||
            // temperature was below forced on threshold and still has not exceeded allowed off threshold
            (temp_prev < temp_fc_forced_on && temperature < temp_fc_allowed_off),
                    || format_dbg!(),
                )?;
            }
            _ => {
                bail!(
                    "{}\n`fc.temperature()`, `fc.temp_prev()`, `self.temp_fc_forced_on`, and 
`self.temp_fc_allowed_off` must all be `None` or `Some` because these controls are necessary
for an HEV equipped with thermal models or superfluous otherwise",
                    format_dbg!((
                        fc.temperature(),
                        self.temp_fc_forced_on,
                        self.temp_fc_allowed_off
                    ))
                );
            }
        }
        Ok(())
    }
}