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
use super::{hev::HEVPowertrainControls, *};
use crate::prelude::*;
pub mod fastsim2_interface;

/// Possible aux load power sources
#[derive(
    Clone, Debug, Serialize, Deserialize, PartialEq, IsVariant, derive_more::From, TryInto,
)]
pub enum AuxSource {
    /// Aux load power provided by ReversibleEnergyStorage with help from FuelConverter, if present
    /// and needed
    ReversibleEnergyStorage,
    /// Aux load power provided by FuelConverter with help from ReversibleEnergyStorage, if present
    /// and needed
    FuelConverter,
}

impl SerdeAPI for AuxSource {}
impl Init for AuxSource {}

#[serde_api]
#[cfg_attr(feature = "pyo3", pyclass(module = "fastsim", subclass, eq))]
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize, StateMethods)]
#[non_exhaustive]
#[serde(deny_unknown_fields)]
/// Struct for simulating vehicle
pub struct Vehicle {
    /// Vehicle name
    pub name: String,
    /// Documentation (e.g. how this file was generated, calibration details)]
    pub doc: Option<String>,
    /// Year manufactured
    pub year: u32,
    #[has_state]
    /// type of vehicle powertrain including contained type-specific parameters and variables
    pub pt_type: PowertrainType,

    /// Chassis model with various chassis-related parameters
    pub chassis: Chassis,

    /// Cabin thermal model
    #[has_state]
    #[serde(default)]
    pub cabin: CabinOption,

    /// HVAC model
    #[has_state]
    #[serde(default)]
    pub hvac: HVACOption,

    /// Total vehicle mass
    pub(crate) mass: Option<si::Mass>,

    /// Baseline power required by auxilliary systems
    pub pwr_aux_base: si::Power,

    /// time step interval at which `state` is saved into `history`
    save_interval: Option<usize>,
    /// current state of vehicle
    #[serde(default)]
    pub state: VehicleState,
    /// Vector-like history of [Self::state]
    #[serde(default)]
    pub history: VehicleStateHistoryVec,
}

#[pyo3_api]
impl Vehicle {
    #[staticmethod]
    fn try_from_fastsim2(veh: fastsim_2::vehicle::RustVehicle) -> PyResult<Vehicle> {
        Ok(Self::try_from(veh.clone())?)
    }

    #[pyo3(name = "set_save_interval")]
    #[pyo3(signature = (save_interval=None))]
    /// Set save interval and cascade to nested components.
    fn set_save_interval_py(&mut self, save_interval: Option<usize>) -> PyResult<()> {
        self.set_save_interval(save_interval)
            .map_err(|e| PyAttributeError::new_err(e.to_string()))
    }

    // despite having `getter` here, this seems to work as a function
    #[getter("save_interval")]
    /// Set save interval and cascade to nested components.
    fn get_save_interval_py(&self) -> anyhow::Result<Option<usize>> {
        self.save_interval()
    }

    #[getter]
    fn get_fc(&self) -> Option<FuelConverter> {
        self.fc().cloned()
    }

    #[getter]
    fn get_res(&self) -> Option<ReversibleEnergyStorage> {
        self.res().cloned()
    }

    #[getter]
    fn get_em(&self) -> Option<ElectricMachine> {
        self.em().cloned()
    }

    fn veh_type(&self) -> String {
        self.pt_type.to_string()
    }

    // #[getter]
    // fn get_pwr_rated_kilowatts(&self) -> f64 {
    //     self.get_pwr_rated().get::<si::kilowatt>()
    // }

    // #[getter]
    // fn get_mass_kg(&self) -> PyResult<Option<f64>> {
    //     Ok(self.mass()?.map(|m| m))
    // }

    /// Load vehicle from file saved in fastsim-2 format
    #[pyo3(name = "from_f2_file")]
    #[staticmethod]
    fn from_f2_file_py(file: PathBuf) -> anyhow::Result<Self> {
        Self::from_f2_file(file)
    }

    #[pyo3(name = "to_fastsim2")]
    fn to_fastsim2_py(&self) -> anyhow::Result<fastsim_2::vehicle::RustVehicle> {
        self.to_fastsim2()
    }

    #[pyo3(name = "reset_py")]
    /// Compines [Self::reset_cumulative], [Self::reset_step], [Self::clear]
    fn reset_py(&mut self) -> anyhow::Result<()> {
        self.reset_cumulative(|| format_dbg!())?;
        self.reset_step(|| format_dbg!())?;
        self.clear();
        Ok(())
    }

    #[pyo3(name = "clear")]
    fn clear_py(&mut self) {
        self.clear()
    }

    #[pyo3(name = "reset_step")]
    fn reset_step_py(&mut self) -> anyhow::Result<()> {
        self.reset_step(|| format_dbg!())
    }

    #[pyo3(name = "reset_cumulative")]
    fn reset_cumulative_py(&mut self) -> anyhow::Result<()> {
        self.reset_cumulative(|| format_dbg!())
    }
}

impl Mass for Vehicle {
    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))
            }
            (None, None) => bail!(
                "Not all mass fields in `{}` are set and no mass was previously set.",
                stringify!(Vehicle)
            ),
            _ => 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 vehicle 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!(Vehicle)
                )
            })?),
        };
        Ok(())
    }

    fn derived_mass(&self) -> anyhow::Result<Option<si::Mass>> {
        let chassis_mass = self
            .chassis
            .mass()
            .with_context(|| anyhow!(format_dbg!()))?;
        let pt_mass = match &self.pt_type {
            PowertrainType::ConventionalVehicle(conv) => conv.mass()?,
            PowertrainType::HybridElectricVehicle(hev) => hev.mass()?,
            PowertrainType::PlugInHybridElectricVehicle(phev) => phev.mass()?,
            PowertrainType::BatteryElectricVehicle(bev) => bev.mass()?,
        };
        if let (Some(pt_mass), Some(chassis_mass)) = (pt_mass, chassis_mass) {
            Ok(Some(pt_mass + chassis_mass))
        } else {
            Ok(None)
        }
    }

    fn expunge_mass_fields(&mut self) {
        self.chassis.expunge_mass_fields();
        match &mut self.pt_type {
            PowertrainType::ConventionalVehicle(conv) => conv.expunge_mass_fields(),
            PowertrainType::HybridElectricVehicle(hev) => hev.expunge_mass_fields(),
            PowertrainType::PlugInHybridElectricVehicle(phev) => phev.expunge_mass_fields(),
            PowertrainType::BatteryElectricVehicle(bev) => bev.expunge_mass_fields(),
        };
    }
}

impl SerdeAPI for Vehicle {
    #[cfg(feature = "resources")]
    const RESOURCES_SUBDIR: &'static str = "vehicles";
}
impl Init for Vehicle {
    fn init(&mut self) -> Result<(), Error> {
        let _mass = self
            .mass()
            .map_err(|err| Error::InitError(format_dbg!(err)))?;
        self.calculate_wheel_radius()
            .map_err(|err| Error::InitError(format_dbg!(err)))?;
        self.pt_type
            .init()
            .map_err(|err| Error::InitError(format_dbg!(err)))?;
        let mass = self
            .mass()
            .unwrap_or(Some(0.0 * uc::KG))
            .unwrap_or(0.0 * uc::KG);
        let _ = match &self.pt_type {
            PowertrainType::HybridElectricVehicle(hev) => hev.check_buffers(mass),
            PowertrainType::PlugInHybridElectricVehicle(hev) => hev.check_buffers(mass),
            _ => Ok(()),
        };
        Ok(())
    }
}

impl HistoryMethods for Vehicle {
    fn save_interval(&self) -> anyhow::Result<Option<usize>> {
        Ok(self.save_interval)
    }
    fn set_save_interval(&mut self, save_interval: Option<usize>) -> anyhow::Result<()> {
        self.save_interval = save_interval;
        self.pt_type.set_save_interval(save_interval)?;
        self.cabin.set_save_interval(save_interval)?;
        self.hvac.set_save_interval(save_interval)?;
        Ok(())
    }
    fn clear(&mut self) {
        self.history.clear();
        self.pt_type.clear();
        self.cabin.clear();
        self.hvac.clear();
    }
}

/// TODO: update this constant to match fastsim-2 for gasoline
pub(super) const FUEL_LHV_MJ_PER_KG: f64 = 43.2;
const CONV: &str = "Conv";
const HEV: &str = "HEV";
const PHEV: &str = "PHEV";
const BEV: &str = "BEV";

impl SetCumulative for Vehicle {
    fn set_cumulative<F: Fn() -> String>(&mut self, dt: si::Time, loc: F) -> anyhow::Result<()> {
        self.state
            .set_cumulative(dt, || format!("{}\n{}", loc(), format_dbg!()))?;
        self.pt_type
            .set_cumulative(dt, || format!("{}\n{}", loc(), format_dbg!()))?;
        self.cabin
            .set_cumulative(dt, || format!("{}\n{}", loc(), format_dbg!()))?;
        self.hvac
            .set_cumulative(dt, || format!("{}\n{}", loc(), format_dbg!()))?;
        // this does not get handled by the `SetCumulative` derive macro
        self.state.dist.increment(
            *self.state.speed_ach.get_fresh(|| format_dbg!())? * dt,
            || format_dbg!(),
        )?;
        Ok(())
    }

    fn reset_cumulative<F: Fn() -> String>(&mut self, loc: F) -> anyhow::Result<()> {
        self.state
            .reset_cumulative(|| format!("{}\n{}", loc(), format_dbg!()))?;
        self.pt_type
            .reset_cumulative(|| format!("{}\n{}", loc(), format_dbg!()))?;
        self.cabin
            .reset_cumulative(|| format!("{}\n{}", loc(), format_dbg!()))?;
        self.hvac
            .reset_cumulative(|| format!("{}\n{}", loc(), format_dbg!()))?;
        // this does not get handled by the `SetCumulative` derive macro
        self.state.dist.mark_stale();
        self.state.dist.update(si::Length::ZERO, || format_dbg!())?;
        self.state.time.mark_stale();
        self.state.time.update(si::Time::ZERO, || format_dbg!())?;
        self.state.speed_ach.mark_stale();
        self.state
            .speed_ach
            .update(si::Velocity::ZERO, || format_dbg!())?;
        Ok(())
    }
}

impl Vehicle {
    /// # Assumptions
    /// - peak power of all components can be produced concurrently.
    pub fn get_pwr_rated(&self) -> si::Power {
        match (self.fc(), self.res()) {
            (Some(fc), Some(res)) => fc.pwr_out_max + res.pwr_out_max,
            (Some(fc), None) => fc.pwr_out_max,
            (None, Some(res)) => res.pwr_out_max,
            (None, None) => unreachable!(),
        }
    }

    pub fn conv(&self) -> Option<&ConventionalVehicle> {
        self.pt_type.conv()
    }

    pub fn hev(&self) -> Option<&HybridElectricVehicle> {
        self.pt_type.hev()
    }

    // pub fn phev(&self) -> Option<&HybridElectricVehicle> {
    //     self.pt_type.phev()
    // }

    pub fn bev(&self) -> Option<&BatteryElectricVehicle> {
        self.pt_type.bev()
    }

    pub fn conv_mut(&mut self) -> Option<&mut ConventionalVehicle> {
        self.pt_type.conv_mut()
    }

    pub fn hev_mut(&mut self) -> Option<&mut HybridElectricVehicle> {
        self.pt_type.hev_mut()
    }

    // pub fn phev_mut(&mut self) -> Option<&mut HybridElectricVehicle> {
    //     self.pt_type.phev_mut()
    // }

    pub fn bev_mut(&mut self) -> Option<&mut BatteryElectricVehicle> {
        self.pt_type.bev_mut()
    }

    pub fn fc(&self) -> Option<&FuelConverter> {
        self.pt_type.fc()
    }

    pub fn fc_mut(&mut self) -> Option<&mut FuelConverter> {
        self.pt_type.fc_mut()
    }

    pub fn set_fc(&mut self, fc: FuelConverter) -> anyhow::Result<()> {
        self.pt_type.set_fc(fc)
    }

    pub fn fs(&self) -> Option<&FuelStorage> {
        self.pt_type.fs()
    }

    pub fn fs_mut(&mut self) -> Option<&mut FuelStorage> {
        self.pt_type.fs_mut()
    }

    pub fn set_fs(&mut self, fs: FuelStorage) -> anyhow::Result<()> {
        self.pt_type.set_fs(fs)
    }

    pub fn res(&self) -> Option<&ReversibleEnergyStorage> {
        self.pt_type.res()
    }

    pub fn res_mut(&mut self) -> Option<&mut ReversibleEnergyStorage> {
        self.pt_type.res_mut()
    }

    pub fn set_res(&mut self, res: ReversibleEnergyStorage) -> anyhow::Result<()> {
        self.pt_type.set_res(res)
    }

    pub fn em(&self) -> Option<&ElectricMachine> {
        self.pt_type.em()
    }

    pub fn em_mut(&mut self) -> Option<&mut ElectricMachine> {
        self.pt_type.em_mut()
    }

    pub fn set_em(&mut self, em: ElectricMachine) -> anyhow::Result<()> {
        self.pt_type.set_em(em)
    }

    pub fn trans(&self) -> Option<&Transmission> {
        self.pt_type.trans()
    }

    pub fn trans_mut(&mut self) -> Option<&mut Transmission> {
        self.pt_type.trans_mut()
    }

    pub fn set_trans(&mut self, trans: Transmission) -> anyhow::Result<()> {
        self.pt_type.set_trans(trans)
    }

    /// Calculate wheel radius from tire code, if applicable
    fn calculate_wheel_radius(&mut self) -> anyhow::Result<()> {
        ensure!(
            self.chassis.wheel_radius.is_some() || self.chassis.tire_code.is_some(),
            "Either `wheel_radius` or `tire_code` must be supplied"
        );
        if self.chassis.wheel_radius.is_none() {
            self.chassis.wheel_radius =
                Some(utils::tire_code_to_radius(self.chassis.tire_code.as_ref().unwrap())? * uc::M)
        }
        Ok(())
    }

    /// Solves for energy consumption
    pub fn solve_powertrain(&mut self, dt: si::Time) -> anyhow::Result<()> {
        self.pt_type
            .solve(
                *self.state.pwr_tractive.get_fresh(|| format_dbg!())?,
                true, // `enabled` should always be true at the powertrain level
                dt,
            )
            .with_context(|| anyhow!(format_dbg!()))?;
        self.state.pwr_brake.update(
            -self
                .state
                .pwr_tractive
                .get_fresh(|| format_dbg!())?
                .max(si::Power::ZERO)
                - self.pt_type.pwr_regen().with_context(|| format_dbg!())?,
            || format_dbg!(),
        )?;
        Ok(())
    }

    pub fn set_curr_pwr_out_max(&mut self, dt: si::Time) -> anyhow::Result<()> {
        // Calculate traction limits
        let mass = self
            .mass
            .with_context(|| format!("{}\nMass should have been set before now", format_dbg!()))?;
        let max_trac_accel = self.chassis.wheel_fric_coef
            * self.chassis.drive_axle_weight_frac
            * uc::ACC_GRAV
            / (1.0 * uc::R
                + self.chassis.cg_height * self.chassis.wheel_fric_coef / self.chassis.wheel_base);
        let prev_speed = *self.state.speed_ach.get_stale(|| format_dbg!())?;
        let max_trac_speed = prev_speed + (max_trac_accel * dt);
        let max_trac_power = self.chassis.wheel_fric_coef
            * self.chassis.drive_axle_weight_frac
            * mass
            * uc::ACC_GRAV
            / (1.0 * uc::R
                + self.chassis.cg_height * self.chassis.wheel_fric_coef / self.chassis.wheel_base)
            * max_trac_speed;
        // Calculate powertrain limits
        self.pt_type
            .set_curr_pwr_prop_out_max(
                (si::Power::ZERO, si::Power::ZERO),
                *self.state.pwr_aux.get_fresh(|| format_dbg!())?,
                dt,
                &self.state,
            )
            .with_context(|| anyhow!(format_dbg!()))?;
        let pwr_prop_maxes = self
            .pt_type
            .get_curr_pwr_prop_out_max()
            .with_context(|| anyhow!(format_dbg!()))?;
        self.state.pwr_prop_fwd_max.update(
            if pwr_prop_maxes.0 > max_trac_power {
                max_trac_power
            } else {
                pwr_prop_maxes.0
            },
            || format_dbg!(),
        )?;
        self.state
            .pwr_prop_bwd_max
            .update(pwr_prop_maxes.1, || format_dbg!())?;

        Ok(())
    }

    pub fn solve_thermal(
        &mut self,
        te_amb_air: si::Temperature,
        dt: si::Time,
    ) -> anyhow::Result<()> {
        let te_fc: Option<si::Temperature> = self
            .fc()
            .and_then(|fc| fc.temperature().map(|fct| fct.get_stale(|| format_dbg!())))
            .transpose()
            .with_context(|| {
                format!(
                    "{}\nfuel converter temperature has not been properly set",
                    format_dbg!()
                )
            })?
            .copied();
        let pwr_thrml_cab_to_res: si::Power = match self.res() {
            Some(res) => match &res.thrml {
                RESThermalOption::RESLumpedThermal(rlt) => {
                    *rlt.state.pwr_thrml_from_cabin.get_stale(|| format_dbg!())?
                }
                RESThermalOption::None => si::Power::ZERO,
            },
            None => si::Power::ZERO,
        };

        let (pwr_thrml_fc_to_cabin, pwr_thrml_hvac_to_res, te_cab) = self
            .solve_hvac_cab_res(te_amb_air, dt, te_fc, pwr_thrml_cab_to_res)
            .with_context(|| format_dbg!())?;

        self.pt_type
            .solve_thermal(
                te_amb_air,
                pwr_thrml_fc_to_cabin,
                &mut self.state,
                pwr_thrml_hvac_to_res,
                te_cab,
                dt,
            )
            .with_context(|| format_dbg!())?;
        Ok(())
    }

    fn solve_hvac_cab_res(
        &mut self,
        te_amb_air: si::Temperature,
        dt: si::Time,
        te_fc: Option<si::Temperature>,
        pwr_thrml_cab_to_res: si::Power,
    ) -> anyhow::Result<(
        Option<si::Power>,
        Option<si::Power>,
        Option<si::Temperature>,
    )> {
        let res_thrml_state = self.pt_type.res_mut().and_then(|rm| rm.res_thrml_state());
        let (pwr_thrml_fc_to_cabin, pwr_thrml_hvac_to_res, te_cab): (
            Option<si::Power>,
            Option<si::Power>,
            Option<si::Temperature>,
        ) = match (&mut self.cabin, &mut self.hvac, res_thrml_state) {
            (CabinOption::None, HVACOption::None, None) => {
                self.state
                    .pwr_aux
                    .update(self.pwr_aux_base, || format_dbg!())?;
                (None, None, None)
            }
            (CabinOption::LumpedCabin(cab), HVACOption::LumpedCabin(hvac), None) => {
                let (pwr_thrml_hvac_to_cabin, pwr_thrml_fc_to_cab) = hvac
                    .solve(te_amb_air, te_fc, &cab.state, cab.heat_capacitance, dt)
                    .with_context(|| format_dbg!())?;
                let te_cab = cab
                    .solve(
                        te_amb_air,
                        &self.state,
                        pwr_thrml_hvac_to_cabin,
                        Default::default(),
                        dt,
                    )
                    .with_context(|| format_dbg!())?;
                self.state.pwr_aux.update(
                    self.pwr_aux_base
                        + *hvac
                            .state
                            .pwr_aux_for_hvac
                            .get_fresh(|| format_dbg!("hvac.state.pwr_aux_for_hvac"))?,
                    || format_dbg!(),
                )?;
                (Some(pwr_thrml_fc_to_cab), None, Some(te_cab))
            }
            (
                CabinOption::LumpedCabin(cab),
                HVACOption::LumpedCabinAndRES(hvac),
                Some(res_thrml_state),
            ) => {
                let (pwr_thrml_hvac_to_cabin, pwr_thrml_fc_to_cab, pwr_thrml_hvac_to_res) = hvac
                    .solve(
                        te_amb_air,
                        te_fc,
                        &cab.state,
                        cab.heat_capacitance,
                        res_thrml_state,
                        dt,
                    )
                    .with_context(|| format_dbg!())?;
                let te_cab = cab
                    .solve(
                        te_amb_air,
                        &self.state,
                        pwr_thrml_hvac_to_cabin,
                        pwr_thrml_cab_to_res,
                        dt,
                    )
                    .with_context(|| format_dbg!())?;
                self.state.pwr_aux.update(
                    self.pwr_aux_base
                        + *hvac
                            .state
                            .pwr_aux_for_cab_hvac
                            .get_fresh(|| format_dbg!())?
                        + *hvac
                            .state
                            .pwr_aux_for_res_hvac
                            .get_fresh(|| format_dbg!())?,
                    || format_dbg!(),
                )?;
                ensure!(
                    *self.state.pwr_aux.get_fresh(|| format_dbg!())? > si::Power::ZERO,
                    format!(
                        "{}\n{}\n{}",
                        format_dbg!(self.state.pwr_aux),
                        format_dbg!(hvac.state.pwr_aux_for_res_hvac),
                        format_dbg!(hvac.state.pwr_aux_for_cab_hvac)
                    )
                );
                (
                    Some(pwr_thrml_fc_to_cab),
                    Some(pwr_thrml_hvac_to_res),
                    Some(te_cab),
                )
            }
            (CabinOption::LumpedCabin(cab), HVACOption::LumpedCabin(hvac), Some(_)) => {
                let (pwr_thrml_hvac_to_cabin, pwr_thrml_fc_to_cab) = hvac
                    .solve(te_amb_air, te_fc, &cab.state, cab.heat_capacitance, dt)
                    .with_context(|| format_dbg!())?;
                let te_cab = cab
                    .solve(
                        te_amb_air,
                        &self.state,
                        pwr_thrml_hvac_to_cabin,
                        Default::default(),
                        dt,
                    )
                    .with_context(|| format_dbg!())?;
                self.state.pwr_aux.update(
                    self.pwr_aux_base
                        + *hvac
                            .state
                            .pwr_aux_for_hvac
                            .get_fresh(|| format_dbg!("hvac.state.pwr_aux_for_hvac"))?,
                    || format_dbg!(),
                )?;
                (Some(pwr_thrml_fc_to_cab), None, Some(te_cab))
            }
            (CabinOption::LumpedCabin(cab), HVACOption::None, Some(_)) => {
                let te_cab = cab
                    .solve(
                        te_amb_air,
                        &self.state,
                        si::Power::ZERO,
                        si::Power::ZERO,
                        dt,
                    )
                    .with_context(|| format_dbg!())?;
                self.state
                    .pwr_aux
                    .update(self.pwr_aux_base, || format_dbg!())?;
                (None, None, Some(te_cab))
            }
            (_, _, _) => {
                bail!(
                    "{}\nCabin, HVAC, and RESThermal configuration is either invalid or not yet implemented.\n{} - {} - {}",
                    format_dbg!(),
                    format!("{}", self.hvac),
                    format!("{}", self.cabin),
                    format!(
                        "`res.res_thrml_state().is_some()`: {}",
                        self.pt_type.res().and_then(|res| res.res_thrml_state()).is_some()
                    ),
                );
            }
        };
        Ok((pwr_thrml_fc_to_cabin, pwr_thrml_hvac_to_res, te_cab))
    }

    #[allow(dead_code)]
    fn from_f2_file(file: PathBuf) -> anyhow::Result<Self> {
        use fastsim_2::traits::SerdeAPI;
        let f2veh = fastsim_2::vehicle::RustVehicle::from_file(file, false)
            .with_context(|| format_dbg!())?;
        Self::try_from(f2veh)
    }

    pub(crate) fn mark_non_thermal_fresh(&mut self) -> Result<(), anyhow::Error> {
        self.state.i.mark_stale();
        self.state.time.mark_stale();
        self.state.pwr_aux.mark_stale();
        self.state.mass.mark_stale();
        self.state.mark_fresh(|| format_dbg!())?;
        self.state.energy_tractive.mark_stale();
        self.state.energy_aux.mark_stale();
        self.state.energy_drag.mark_stale();
        self.state.energy_accel.mark_stale();
        self.state.energy_ascent.mark_stale();
        self.state.energy_rr.mark_stale();
        self.state.energy_whl_inertia.mark_stale();
        self.state.energy_brake.mark_stale();
        self.state.dist.mark_stale();
        if let Some(fc) = self.fc_mut() {
            fc.state.i.mark_stale();
            fc.state.mark_fresh(|| format_dbg!())?;
            fc.state.energy_prop.mark_stale();
            fc.state.energy_aux.mark_stale();
            fc.state.energy_fuel.mark_stale();
            fc.state.energy_loss.mark_stale();
        }
        if let Some(res) = self.res_mut() {
            res.state.i.mark_stale();
            res.state.soh.mark_stale();
            res.state.mark_fresh(|| format_dbg!())?;
            res.state.energy_out_electrical.mark_stale();
            res.state.energy_out_prop.mark_stale();
            res.state.energy_aux.mark_stale();
            res.state.energy_loss.mark_stale();
            res.state.energy_out_chemical.mark_stale();
        }

        if let Some(em) = self.em_mut() {
            em.state.i.mark_stale();
            em.state.mark_fresh(|| format_dbg!())?;
            em.state.energy_out_req.mark_stale();
            em.state.energy_elec_prop_in.mark_stale();
            em.state.energy_mech_prop_out.mark_stale();
            em.state.energy_mech_dyn_brake.mark_stale();
            em.state.energy_elec_dyn_brake.mark_stale();
            em.state.energy_loss.mark_stale();
        }
        if let Some(trans) = self.trans_mut() {
            trans.state.i.mark_stale();
            trans.state.mark_fresh(|| format_dbg!())?;
            trans.state.energy_out.mark_stale();
            trans.state.energy_in.mark_stale();
            trans.state.energy_loss.mark_stale();
        }
        if let PowertrainType::HybridElectricVehicle(hev) = &mut self.pt_type {
            match &mut hev.pt_cntrl {
                HEVPowertrainControls::RGWDB(rgwdb) => rgwdb.state.i.mark_stale(),
            }
            hev.pt_cntrl.mark_fresh(|| format_dbg!())?
        }
        Ok(())
    }
}

/// Vehicle state for current time step
#[serde_api]
#[derive(
    Clone, Debug, Deserialize, Serialize, PartialEq, HistoryVec, StateMethods, SetCumulative,
)]
#[non_exhaustive]
#[serde(default)]
#[serde(deny_unknown_fields)]
pub struct VehicleState {
    /// time step index
    pub i: TrackedState<usize>,

    /// elapsed simulation time since start
    pub time: TrackedState<si::Time>,

    // power and energy fields
    /// maximum forward propulsive power vehicle can produce
    pub pwr_prop_fwd_max: TrackedState<si::Power>,
    /// pwr exerted on wheels by powertrain
    /// maximum backward propulsive power (e.g. regenerative braking) vehicle can produce
    pub pwr_prop_bwd_max: TrackedState<si::Power>,
    /// Tractive power for achieved speed
    pub pwr_tractive: TrackedState<si::Power>,
    /// Tractive power required for prescribed speed
    pub pwr_tractive_for_cyc: TrackedState<si::Power>,
    /// integral of [Self::pwr_tractive]
    pub energy_tractive: TrackedState<si::Energy>,
    /// time varying aux load
    pub pwr_aux: TrackedState<si::Power>,
    /// integral of [Self::pwr_aux]
    pub energy_aux: TrackedState<si::Energy>,
    /// Power applied to aero drag
    pub pwr_drag: TrackedState<si::Power>,
    /// integral of [Self::pwr_drag]
    pub energy_drag: TrackedState<si::Energy>,
    /// Power applied to acceleration (includes deceleration)
    pub pwr_accel: TrackedState<si::Power>,
    /// integral of [Self::pwr_accel]
    pub energy_accel: TrackedState<si::Energy>,
    /// Power applied to grade ascent
    pub pwr_ascent: TrackedState<si::Power>,
    /// integral of [Self::pwr_ascent]
    pub energy_ascent: TrackedState<si::Energy>,
    /// Power applied to rolling resistance
    pub pwr_rr: TrackedState<si::Power>,
    /// integral of [Self::pwr_rr]
    pub energy_rr: TrackedState<si::Energy>,
    /// Power applied to wheel and tire inertia
    pub pwr_whl_inertia: TrackedState<si::Power>,
    /// integral of [Self::pwr_whl_inertia]
    pub energy_whl_inertia: TrackedState<si::Energy>,
    /// Total braking power including regen
    pub pwr_brake: TrackedState<si::Power>,
    /// integral of [Self::pwr_brake]
    pub energy_brake: TrackedState<si::Energy>,
    /// whether powertrain can achieve power demand to achieve prescribed speed
    /// in current time step
    // because it should be assumed true in the first time step
    pub cyc_met: TrackedState<bool>,
    /// whether powertrain can achieve power demand to achieve prescribed speed
    /// in entire cycle
    pub cyc_met_overall: TrackedState<bool>,
    /// actual achieved speed
    pub speed_ach: TrackedState<si::Velocity>,
    /// cumulative distance traveled, integral of [Self::speed_ach]
    pub dist: TrackedState<si::Length>,
    /// current grade
    pub grade_curr: TrackedState<si::Ratio>,
    /// current grade
    // will be overridden during simulation anyway
    pub elev_curr: TrackedState<si::Length>,
    /// current air density
    pub air_density: TrackedState<si::MassDensity>,
    /// current mass
    // TODO: make sure this gets updated appropriately
    pub mass: TrackedState<si::Mass>,
}

impl SerdeAPI for VehicleState {}
impl Init for VehicleState {}
impl Default for VehicleState {
    fn default() -> Self {
        Self {
            i: TrackedState::new(Default::default()),
            time: Default::default(),
            pwr_prop_fwd_max: Default::default(),
            pwr_prop_bwd_max: Default::default(),
            pwr_tractive: Default::default(),
            pwr_tractive_for_cyc: Default::default(),
            energy_tractive: Default::default(),
            pwr_aux: Default::default(),
            energy_aux: Default::default(),
            pwr_drag: Default::default(),
            energy_drag: Default::default(),
            pwr_accel: Default::default(),
            energy_accel: Default::default(),
            pwr_ascent: Default::default(),
            energy_ascent: Default::default(),
            pwr_rr: Default::default(),
            energy_rr: Default::default(),
            pwr_whl_inertia: Default::default(),
            energy_whl_inertia: Default::default(),
            pwr_brake: Default::default(),
            energy_brake: Default::default(),
            cyc_met: TrackedState::new(true),
            cyc_met_overall: TrackedState::new(true),
            speed_ach: Default::default(),
            dist: Default::default(),
            // note that this value will be overwritten
            grade_curr: Default::default(),
            // note that this value will be overwritten
            elev_curr: Default::default(),
            air_density: Default::default(),
            mass: TrackedState::new(uc::KG * f64::NAN),
        }
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;

    #[allow(dead_code)]
    fn vehicles_dir() -> PathBuf {
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/vehicles")
    }

    #[cfg(feature = "yaml")]
    /// Load representative conv from fastsim-2, convert to fastsim-3 format, and
    /// save to file in the resources folder
    pub(crate) fn mock_conv_veh() -> Vehicle {
        let file_contents = include_str!("fastsim-2_2012_Ford_Fusion.yaml");
        use fastsim_2::traits::SerdeAPI;
        let veh = {
            let f2veh = fastsim_2::vehicle::RustVehicle::from_yaml(file_contents, false).unwrap();
            let veh = Vehicle::try_from(f2veh);
            veh.unwrap()
        };

        veh.to_file(vehicles_dir().join("2012_Ford_Fusion.yaml"))
            .unwrap();
        assert!(veh.pt_type.is_conventional_vehicle());
        veh
    }

    #[cfg(feature = "yaml")]
    /// Load representative HEV from fastsim-2, convert to fastsim-3 format, and
    /// save to file in the resources folder
    pub(crate) fn mock_hev() -> Vehicle {
        let file_contents = include_str!("fastsim-2_2016_TOYOTA_Prius_Two.yaml");
        use fastsim_2::traits::SerdeAPI;
        let veh = {
            let f2veh = fastsim_2::vehicle::RustVehicle::from_yaml(file_contents, false).unwrap();
            let veh = Vehicle::try_from(f2veh);
            veh.unwrap()
        };

        veh.to_file(vehicles_dir().join("2016_TOYOTA_Prius_Two.yaml"))
            .unwrap();
        assert!(veh.pt_type.is_hybrid_electric_vehicle());
        veh
    }

    #[cfg(feature = "yaml")]
    /// Load representative BEV from fastsim-2, convert to fastsim-3 format, and
    /// save to file in the resources folder
    pub(crate) fn mock_bev() -> Vehicle {
        let file_contents = include_str!("fastsim-2_2022_Renault_Zoe_ZE50_R135.yaml");
        use fastsim_2::traits::SerdeAPI;
        let veh = {
            let f2veh = fastsim_2::vehicle::RustVehicle::from_yaml(file_contents, false).unwrap();
            let veh = Vehicle::try_from(f2veh);
            veh.unwrap()
        };

        veh.to_file(vehicles_dir().join("2022_Renault_Zoe_ZE50_R135.yaml"))
            .unwrap();
        assert!(veh.pt_type.is_battery_electric_vehicle());
        veh
    }

    #[test]
    #[cfg(feature = "yaml")]
    pub(crate) fn test_conv_veh_init() {
        use pretty_assertions::assert_eq;
        let veh = mock_conv_veh();
        let mut veh1 = veh.clone();
        // NOTE: eventually figure out why the following assertions fail if
        // `.to_yaml().uwrap()` is removed.  It's probably related to f64::NAN
        assert_eq!(veh.to_yaml().unwrap(), veh1.to_yaml().unwrap());
        veh1.init().unwrap();
        assert_eq!(veh.to_yaml().unwrap(), veh1.to_yaml().unwrap());
    }

    #[test]
    #[cfg(all(feature = "csv", feature = "resources"))]
    fn test_to_fastsim2_conv() {
        let veh = mock_conv_veh();
        let cyc = crate::drive_cycle::Cycle::from_resource("udds.csv", false).unwrap();
        let sd = crate::simdrive::SimDrive::new(veh, cyc, Default::default());
        let mut sd2 = sd.to_fastsim2().unwrap();
        sd2.sim_drive(None, None).unwrap();
    }

    #[test]
    #[cfg(all(feature = "csv", feature = "resources"))]
    fn test_to_fastsim2_hev() {
        let veh = mock_hev();
        let cyc = crate::drive_cycle::Cycle::from_resource("udds.csv", false).unwrap();
        let sd = crate::simdrive::SimDrive::new(veh, cyc, Default::default());
        let mut sd2 = sd.to_fastsim2().unwrap();
        sd2.sim_drive(None, None).unwrap();
    }

    #[test]
    #[cfg(all(feature = "csv", feature = "resources"))]
    fn test_to_fastsim2_bev() {
        let veh = mock_bev();
        let cyc = crate::drive_cycle::Cycle::from_resource("udds.csv", false).unwrap();
        let sd = crate::simdrive::SimDrive::new(veh, cyc, Default::default());
        let mut sd2 = sd.to_fastsim2().unwrap();
        sd2.sim_drive(None, None).unwrap();
    }

    type StructWithResources = Vehicle;

    #[test]
    fn test_resources() {
        let mut time_to_panic = false;

        let resource_list = StructWithResources::list_resources().unwrap();
        assert!(!resource_list.is_empty());

        // verify that resources can all load
        for resource in resource_list {
            if let Err(e) = StructWithResources::from_resource(resource.clone(), false) {
                time_to_panic = true;
                eprintln!("Error loading {resource:?}: {e}\n");
            }
        }
        if time_to_panic {
            panic!()
        }
    }

    #[test]
    fn test_calibrated_vehicles() {
        let mut time_to_panic = false;

        // check that calibrated vehicles can load
        let paths: Vec<_> = std::fs::read_dir("../cal_and_val/f3-vehicles")
            .unwrap()
            .collect();
        assert!(!paths.is_empty());
        for path in paths {
            let p = path.unwrap().path();
            if let Err(e) = StructWithResources::from_file(p.clone(), false) {
                time_to_panic = true;
                eprintln!("Error loading {p:?}: {e}\n");
            }
        }

        // check that calibrated thermal-equipped vehicles can load
        let paths: Vec<_> = std::fs::read_dir("../cal_and_val/thermal/f3-vehicles")
            .unwrap()
            .collect();
        assert!(!paths.is_empty());
        for path in paths {
            let p = path.unwrap().path();
            if let Err(e) = StructWithResources::from_file(p.clone(), false) {
                time_to_panic = true;
                eprintln!("Error loading {p:?}: {e}\n");
            }
        }

        if time_to_panic {
            panic!()
        }
    }
}