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
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
pub mod roadload;
use roadload::StepInfo;
use super::drive_cycle::Cycle;
use super::vehicle::Vehicle;
use crate::drive_cycle::manipulation_utils::calc_best_rendezvous;
use crate::imports::*;
use crate::prelude::*;
#[serde_api]
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
#[serde(deny_unknown_fields)]
#[cfg_attr(feature = "pyo3", pyclass(module = "fastsim", subclass, eq))]
/// Solver parameters
pub struct SimParams {
#[serde(default = "SimParams::def_ach_speed_max_iter")]
/// max number of iterations allowed in setting achieved speed when trace
/// cannot be achieved
pub ach_speed_max_iter: u32,
#[serde(default = "SimParams::def_ach_speed_tol")]
/// tolerance in change in speed guess in setting achieved speed when trace
/// cannot be achieved
pub ach_speed_tol: si::Ratio,
#[serde(default = "SimParams::def_ach_speed_solver_gain")]
/// Newton method gain for setting achieved speed
pub ach_speed_solver_gain: f64,
// TODO: plumb this up to actually do something
/// When implemented, this will set the tolerance on how much trace miss
/// is allowed
#[serde(default = "SimParams::def_trace_miss_tol")]
pub trace_miss_tol: TraceMissTolerance,
#[serde(default = "SimParams::def_trace_miss_opts")]
pub trace_miss_opts: TraceMissOptions,
#[serde(default = "SimParams::def_trace_miss_correct_max_steps")]
/// the maximum number of steps in which to re-rendezvous with reference
/// trace after a trace miss. Note: this field only applies when
/// trace_miss_opts is set to TraceMissOptions::Correct. Note: must
/// be 2 or greater. Defaults to 6.
pub trace_miss_correct_max_steps: u32,
/// whether to use FASTSim-2 style air density
#[serde(default = "SimParams::def_f2_const_air_density")]
pub f2_const_air_density: bool,
/// if true, vehicle is totally inactive except for thermal models
pub ambient_thermal_soak: bool,
}
#[pyo3_api]
impl SimParams {
#[staticmethod]
#[pyo3(name = "default")]
fn default_py() -> Self {
Self::default()
}
}
impl SimParams {
fn def_ach_speed_max_iter() -> u32 {
Self::default().ach_speed_max_iter
}
fn def_ach_speed_tol() -> si::Ratio {
Self::default().ach_speed_tol
}
fn def_ach_speed_solver_gain() -> f64 {
Self::default().ach_speed_solver_gain
}
fn def_trace_miss_tol() -> TraceMissTolerance {
Self::default().trace_miss_tol
}
fn def_trace_miss_opts() -> TraceMissOptions {
Self::default().trace_miss_opts
}
fn def_trace_miss_correct_max_steps() -> u32 {
Self::default().trace_miss_correct_max_steps
}
fn def_f2_const_air_density() -> bool {
Self::default().f2_const_air_density
}
}
impl SerdeAPI for SimParams {}
impl Init for SimParams {}
impl Default for SimParams {
fn default() -> Self {
Self {
ach_speed_max_iter: 3,
ach_speed_tol: 1.0e-3 * uc::R,
ach_speed_solver_gain: 0.9,
trace_miss_tol: Default::default(),
trace_miss_opts: Default::default(),
trace_miss_correct_max_steps: 6,
f2_const_air_density: true,
ambient_thermal_soak: false,
}
}
}
#[serde_api]
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, StateMethods)]
#[non_exhaustive]
#[serde(deny_unknown_fields)]
#[cfg_attr(feature = "pyo3", pyclass(module = "fastsim", subclass, eq))]
pub struct SimDrive {
#[has_state]
pub veh: Vehicle,
pub cyc: Cycle,
pub sim_params: SimParams,
}
#[pyo3_api]
impl SimDrive {
#[new]
#[pyo3(signature = (veh, cyc, sim_params=None))]
fn __new__(veh: Vehicle, cyc: Cycle, sim_params: Option<SimParams>) -> anyhow::Result<Self> {
Ok(SimDrive::new(veh, cyc, sim_params))
}
/// Run vehicle simulation once
#[pyo3(name = "walk_once")]
fn walk_once_py(&mut self) -> anyhow::Result<()> {
self.walk_once()
}
/// Run vehicle simulation, and, if applicable, apply powertrain-specific
/// corrections (e.g. iterate `walk` until SOC balance is achieved -- i.e. initial
/// and final SOC are nearly identical)
#[pyo3(name = "walk")]
fn walk_py(&mut self) -> anyhow::Result<()> {
self.walk()
}
#[pyo3(name = "to_fastsim2")]
fn to_fastsim2_py(&self) -> anyhow::Result<fastsim_2::simdrive::RustSimDrive> {
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 SerdeAPI for SimDrive {}
impl Init for SimDrive {
fn init(&mut self) -> Result<(), Error> {
self.veh
.init()
.map_err(|err| Error::InitError(format_dbg!(err)))?;
self.cyc
.init()
.map_err(|err| Error::InitError(format_dbg!(err)))?;
self.sim_params
.init()
.map_err(|err| Error::InitError(format_dbg!(err)))?;
Ok(())
}
}
impl SimDrive {
pub fn new(veh: Vehicle, cyc: Cycle, sim_params: Option<SimParams>) -> Self {
Self {
veh,
cyc,
sim_params: sim_params.unwrap_or_default(),
}
}
// # TODO:
// ## Features
// - [ ] regen limiting curve during speeds approaching zero per f2 -- less urgent
// - [ ] ability to manipulate friction/regen brake split based on required braking
// power -- new feature -- move this to enum
// - [x] make enum `EngineOnCause::{AlreadyOn, TooCold,
// PowerDemand}` and save it in a vec or some such for when there are
// multiple causes -- new feature
/// Run vehicle simulation, and, if applicable, apply powertrain-specific
/// corrections:
/// - for HEV, set initial SOC to mean of min and max SOC, and then iterate
/// `walk` until SOC balance is achieved -- i.e. initial and final SOC are
/// nearly identical
/// - for PHEV, set initial SOC to max SOC, and then simulate once
/// - for BEV, set initial SOC to max SOC, and then simulate once
/// - for Conv, simulate once
///
/// # Important Considerations
/// If you need to run a [ReversibleEnergyStorage]-equipped vehicle for
/// only one iteration without modifying the initial SOC, then run the
/// [Self::walk_once] method directly
pub fn walk(&mut self) -> anyhow::Result<()> {
match self.veh.pt_type {
PowertrainType::HybridElectricVehicle(_) => {
// Net battery energy used per amount of fuel used
// clone initial vehicle to preserve starting state (TODO: figure out if this is a huge CPU burden)
let veh_init = self.veh.clone();
let res_mut = self.veh.res_mut().with_context(|| format_dbg!())?;
res_mut.state.soc.mark_stale();
res_mut
.state
.soc
.update(0.5 * (res_mut.min_soc + res_mut.max_soc), || format_dbg!())?;
loop {
self.veh
.hev_mut()
.with_context(|| format_dbg!())?
.soc_bal_iters
.mark_stale();
self.veh
.hev_mut()
.with_context(|| format_dbg!())?
.soc_bal_iters
.increment(1, || format_dbg!())?;
self.walk_once().with_context(|| format_dbg!())?;
let soc_final = self
.veh
.res()
.with_context(|| format_dbg!())?
.state
.soc
.clone();
let res_per_fuel = *self
.veh
.res()
.with_context(|| format_dbg!())?
.state
.energy_out_chemical
.get_fresh(|| format_dbg!())?
/ *self
.veh
.fc()
.with_context(|| format_dbg!())?
.state
.energy_fuel
.get_fresh(|| format_dbg!())?;
if self
.veh
.hev()
.with_context(|| format_dbg!())?
.soc_bal_iters
.get_fresh(|| format_dbg!())?
> &self
.veh
.hev()
.with_context(|| format_dbg!())?
.sim_params
.soc_balance_iter_err
{
bail!(
"{}",
format_dbg!((
self.veh
.hev()
.with_context(|| format_dbg!())?
.soc_bal_iters
.clone(),
self.veh
.hev()
.with_context(|| format_dbg!())?
.sim_params
.soc_balance_iter_err
))
);
}
if res_per_fuel.abs()
< self
.veh
.hev()
.with_context(|| format_dbg!())?
.sim_params
.res_per_fuel_lim
|| !self
.veh
.hev()
.with_context(|| format_dbg!())?
.sim_params
.balance_soc
|| self.sim_params.ambient_thermal_soak
{
break;
} else {
// prep for another iteration
if let Some(&mut ref mut hev) = self.veh.hev_mut() {
if hev.sim_params.save_soc_bal_iters {
hev.soc_bal_iter_history.push(hev.clone());
hev.soc_bal_iters.mark_stale();
}
}
// reset vehicle to initial state
self.veh = veh_init.clone();
// start SOC at previous final value
self.veh.res_mut().with_context(|| format_dbg!())?.state.soc = soc_final;
}
}
}
PowertrainType::PlugInHybridElectricVehicle(_) => {
let res_mut = self.veh.res_mut().with_context(|| format_dbg!())?;
res_mut.state.soc.mark_stale();
res_mut
.state
.soc
.update(res_mut.max_soc, || format_dbg!())?;
self.walk_once()?
}
PowertrainType::BatteryElectricVehicle(_) => {
let res_mut = self.veh.res_mut().with_context(|| format_dbg!())?;
res_mut.state.soc.mark_stale();
res_mut
.state
.soc
.update(res_mut.max_soc, || format_dbg!())?;
self.walk_once()?
}
PowertrainType::ConventionalVehicle(_) => self.walk_once()?,
}
Ok(())
}
/// Run vehicle simulation once
pub fn walk_once(&mut self) -> anyhow::Result<()> {
let len = &self.cyc.len_checked().with_context(|| format_dbg!())?;
ensure!(len >= &2, format_dbg!(len < &2));
self.save_state(|| format_dbg!())?;
self.veh.state.mass.mark_stale();
self.veh.state.mass.update(
self.veh
.mass()
.with_context(|| format_dbg!())?
.with_context(|| format_dbg!("Expected mass to have been set."))?,
|| format_dbg!(),
)?;
let hvac: Option<HVACOption> = if self.sim_params.ambient_thermal_soak {
ensure!(
self.cyc.speed.iter().all(|s| *s == si::Velocity::ZERO),
format!(
"{}\nDuring thermal soak, cycle speed should always be zero",
format_dbg!()
)
);
if !self.veh.hvac.is_none() {
// turn off HVAC if vehicle is not active
let hvac_some = Some(self.veh.hvac.clone());
self.veh.hvac = HVACOption::None;
hvac_some
} else {
None
}
} else {
None
};
loop {
self.check_and_reset(|| format_dbg!())?;
self.veh.state.mass.mark_fresh(|| format_dbg!())?;
if let Some(res) = self.veh.res_mut() {
res.state.soh.mark_fresh(|| format_dbg!())?;
}
self.step(|| format_dbg!())?;
self.solve_step()
.with_context(|| format!("{}\ntime step: {:?}", format_dbg!(), self.veh.state.i))?;
self.save_state(|| format_dbg!())?;
if *self.veh.state.i.get_fresh(|| format_dbg!())? == len - 1 {
break;
}
}
if let Some(hvac) = hvac {
// reset original hvac
self.veh.hvac = hvac;
}
Ok(())
}
/// Calculates the derivative dv/dd (change in speed by change in distance)
/// - speed_m_per_s: the speed at which to evaluate dv/dd (m/s)
/// - grade: the road grade as a decimal fraction
///
/// RETURN: number, the dv/dd for these conditions
pub fn calc_dvdd(&self, speed_m_per_s: f64, grade: f64) -> anyhow::Result<f64> {
let v = speed_m_per_s;
if v <= 0.0 {
Ok(0.0)
} else {
let (atan_grade_sin, atan_grade_cos) = if grade == 0.0 {
(0.0, 1.0)
} else {
let atan_grade = grade.atan();
(atan_grade.sin(), atan_grade.cos())
};
let g = uc::ACC_GRAV.get::<si::meter_per_second_squared>();
let m = self
.veh
.mass
.with_context(|| {
format!(
"{}\nVehicle mass should have been set already.",
format_dbg!()
)
})?
.get::<si::kilogram>();
let rho_cdfa = self
.veh
.state
.air_density
.get_stale(|| format_dbg!())?
.get::<si::kilogram_per_cubic_meter>()
* self.veh.chassis.drag_coef.get::<si::ratio>()
* self.veh.chassis.frontal_area.get::<si::square_meter>();
let rrc = self.veh.chassis.wheel_rr_coef.get::<si::ratio>();
Ok(-((g / v) * (atan_grade_sin + rrc * atan_grade_cos)
+ (0.5 * rho_cdfa * (1.0 / m) * v)))
}
}
/// Solves current time step
pub fn solve_step(&mut self) -> anyhow::Result<()> {
let i = *self.veh.state.i.get_fresh(|| format_dbg!())?;
let time_prev = *self.veh.state.time.get_stale(|| format_dbg!())?;
ensure!(self.cyc.time.len() > i);
self.veh.state.time.update(
*self.cyc.time.get(i).with_context(|| format_dbg!())?,
|| format_dbg!(),
)?;
let dt = *self.veh.state.time.get_fresh(|| format_dbg!())? - time_prev;
// maybe make controls like:
// ```
// pub enum HVACAuxPriority {
// /// Prioritize [ReversibleEnergyStorage] thermal management
// ReversibleEnergyStorage
// /// Prioritize [Cabin] and [ReversibleEnergyStorage] proportionally to their requests
// Proportional
// }
// ```
// `solve_thermal` must happen before the other methods because it impacts aux power demand
self.veh
.solve_thermal(self.cyc.temp_amb_air[i], dt)
.with_context(|| format!("{}\n`self.veh.state.i`: {}", format_dbg!(), i))?;
match self.sim_params.ambient_thermal_soak {
false => {
self.veh
.set_curr_pwr_out_max(dt)
.with_context(|| anyhow!(format_dbg!()))?;
self.set_pwr_prop_for_speed(
self.cyc.speed[i],
*self.veh.state.speed_ach.get_stale(|| format_dbg!())?,
dt,
)
.with_context(|| anyhow!(format_dbg!()))?;
self.veh.state.pwr_tractive_for_cyc.update(
*self.veh.state.pwr_tractive.get_fresh(|| format_dbg!())?,
|| format_dbg!(),
)?;
self.set_ach_speed(self.cyc.speed[i], dt)
.with_context(|| anyhow!(format_dbg!()))?;
if self.sim_params.trace_miss_opts.is_allow_checked() {
self.sim_params.trace_miss_tol.check_trace_miss(
self.cyc.speed[i],
*self.veh.state.speed_ach.get_fresh(|| format_dbg!())?,
self.cyc.dist[i],
*self.veh.state.dist.get_fresh(|| format_dbg!())?,
)?;
}
self.veh
.solve_powertrain(dt)
.with_context(|| anyhow!(format_dbg!()))?;
}
true => {
self.veh.mark_non_thermal_fresh()?;
}
}
self.set_cumulative(dt, || format_dbg!())?;
Ok(())
}
/// Sets power required for given prescribed speed
/// # Arguments
/// - `speed`: prescribed or achieved speed
/// - `dt`: simulation time step size
pub fn set_pwr_prop_for_speed(
&mut self,
speed: si::Velocity,
speed_prev: si::Velocity,
dt: si::Time,
) -> anyhow::Result<()> {
let i = *self.veh.state.i.get_fresh(|| format_dbg!())?;
let vs = &mut self.veh.state;
// TODO: get @mokeefe to give this a serious look and think about grade alignment issues that may arise
// TODO: memo-ize this
// - if we get back on trace or nearly back on trace, revert to just using the index
// - we can also shorten the x and y values by removing stuff that's already happened
let interp_pt_dist: &[f64] = match self.cyc.grade_interp {
Some(InterpolatorEnum::Interp0D(_)) => &[],
Some(InterpolatorEnum::Interp1D(_)) => {
&[vs.dist.get_fresh(|| format_dbg!())?.get::<si::meter>()]
}
_ => unreachable!(),
};
vs.grade_curr.update(
if *vs.cyc_met_overall.get_stale(|| format_dbg!())? {
*self
.cyc
.grade
.get(i)
.with_context(|| format_dbg!(self.cyc.grade.len()))?
} else {
uc::R
* self
.cyc
.grade_interp
.as_ref()
.with_context(|| format_dbg!("You might have somehow bypassed `init()`"))?
.interpolate(interp_pt_dist)
.with_context(|| format_dbg!())?
},
|| format_dbg!(),
)?;
vs.elev_curr.update(
if *vs.cyc_met_overall.get_stale(|| format_dbg!())? {
*self.cyc.elev.get(i).with_context(|| format_dbg!())?
} else {
uc::M
* self
.cyc
.elev_interp
.as_ref()
.with_context(|| format_dbg!("You might have somehow bypassed `init()`"))?
.interpolate(interp_pt_dist)
.with_context(|| format_dbg!())?
},
|| format_dbg!(),
)?;
vs.air_density.update(
if self.sim_params.f2_const_air_density {
1.2 * uc::KGPM3
} else {
let te_amb_air = {
let te_amb_air = self
.cyc
.temp_amb_air
.get(i)
.with_context(|| format_dbg!())?;
if *te_amb_air == *TE_STD_AIR {
None
} else {
Some(te_amb_air)
}
};
Air::get_density(
te_amb_air.copied(),
Some(*vs.elev_curr.get_fresh(|| format_dbg!())?),
)
},
|| format_dbg!(),
)?;
let mass = self.veh.mass.with_context(|| {
format!(
"{}\nVehicle mass should have been set already.",
format_dbg!()
)
})?;
vs.pwr_accel.update(
mass / (2.0 * dt) * (speed.powi(P2::new()) - speed_prev.powi(P2::new())),
|| format_dbg!(),
)?;
vs.pwr_ascent.update(
uc::ACC_GRAV
* *vs.grade_curr.get_fresh(|| format_dbg!())?
* mass
* (speed_prev + speed)
/ 2.0,
|| format_dbg!(),
)?;
vs.pwr_drag.update(
0.5
// TODO: feed in elevation
* Air::get_density(None, None)
* self.veh.chassis.drag_coef
* self.veh.chassis.frontal_area
* ((speed + speed_prev) / 2.0).powi(P3::new()),
|| format_dbg!(),
)?;
vs.pwr_rr.update(
mass * uc::ACC_GRAV
* self.veh.chassis.wheel_rr_coef
* vs.grade_curr.get_fresh(|| format_dbg!())?.atan().cos()
* (speed_prev + speed)
/ 2.,
|| format_dbg!(),
)?;
vs.pwr_whl_inertia.update(
0.5 * self.veh.chassis.wheel_inertia
* self.veh.chassis.num_wheels as f64
* ((speed
/ self
.veh
.chassis
.wheel_radius
.with_context(|| format_dbg!())?)
.powi(P2::new())
- (speed_prev
/ self
.veh
.chassis
.wheel_radius
.with_context(|| format_dbg!())?)
.powi(P2::new()))
/ self.cyc.dt_at_i(i).with_context(|| format_dbg!())?,
|| format_dbg!(),
)?;
vs.pwr_tractive.update(
*vs.pwr_rr.get_fresh(|| format_dbg!())?
+ *vs.pwr_whl_inertia.get_fresh(|| format_dbg!())?
+ *vs.pwr_accel.get_fresh(|| format_dbg!())?
+ *vs.pwr_ascent.get_fresh(|| format_dbg!())?
+ *vs.pwr_drag.get_fresh(|| format_dbg!())?,
|| format_dbg!(),
)?;
Ok(())
}
/// Sets achieved speed based on known current max power
/// # Arguments
/// - `cyc_speed`: prescribed speed
/// - `dt`: simulation time step size
pub fn set_ach_speed(&mut self, cyc_speed: si::Velocity, dt: si::Time) -> anyhow::Result<()> {
let vs = &mut self.veh.state;
vs.cyc_met.update(
vs.pwr_tractive.get_fresh(|| format_dbg!())?
<= vs.pwr_prop_fwd_max.get_fresh(|| format_dbg!())?,
|| format_dbg!(),
)?;
vs.cyc_met_overall.update(
if !*vs.cyc_met.get_fresh(|| format_dbg!())? {
// if current power demand is not met, then this becomes false for
// the rest of the cycle and should not be manipulated anywhere else
false
} else {
*vs.cyc_met_overall.get_stale(|| format_dbg!())?
},
|| format_dbg!(),
)?;
let veh = &mut self.veh;
let speed_prev = *veh.state.speed_ach.get_stale(|| format_dbg!())?;
if *veh.state.cyc_met.get_fresh(|| format_dbg!())? {
veh.state.speed_ach.update(cyc_speed, || format_dbg!())?;
return Ok(());
} else {
match self.sim_params.trace_miss_opts {
TraceMissOptions::Allow => {
// do nothing because `set_ach_speed` should be allowed to proceed to handle this
}
TraceMissOptions::AllowChecked => {
// this will be handled later
}
TraceMissOptions::Error => bail!(
"{}\nFailed to meet speed trace.
prescribed speed: {} mph
prev speed_ach: {} mph
pwr_tractive_for_cyc: {} kW
pwr_tractive: {} kW
pwr_prop_fwd_max: {} kW,
pwr deficit: {} kW
",
format_dbg!(),
cyc_speed.get::<si::mile_per_hour>(),
veh.state
.speed_ach
.get_stale(|| format_dbg!())?
.get::<si::mile_per_hour>(),
veh.state
.pwr_tractive_for_cyc
.get_fresh(|| format_dbg!())?
.get::<si::kilowatt>(),
veh.state
.pwr_tractive
.get_fresh(|| format_dbg!())?
.get::<si::kilowatt>(),
veh.state
.pwr_prop_fwd_max
.get_fresh(|| format_dbg!())?
.get::<si::kilowatt>(),
(*veh.state.pwr_tractive.get_fresh(|| format_dbg!())?
- *veh.state.pwr_prop_fwd_max.get_fresh(|| format_dbg!())?)
.get::<si::kilowatt>()
.format_eng(None)
),
TraceMissOptions::Correct => {
// We will correct the deviation from trace by modifying the cycle to re-rendezvous with a later time/distance.
// In so doing, we will use a less agressive roadload.
// NOTE: actual correction occurs later but we need to calculate
// the achieved speed first.
}
}
}
let vs = &mut self.veh.state;
let step_info = StepInfo {
dt,
speed_prev,
cyc_speed,
grade_curr: *vs.grade_curr.get_fresh(|| format_dbg!())?,
air_density: *vs.air_density.get_fresh(|| format_dbg!())?,
mass: self.veh.mass.with_context(|| {
format!("{}\nMass should have been set before now", format_dbg!())
})?,
drag_coef: self.veh.chassis.drag_coef,
frontal_area: self.veh.chassis.frontal_area,
wheel_inertia: self.veh.chassis.wheel_inertia,
num_wheels: self.veh.chassis.num_wheels,
wheel_radius: self
.veh
.chassis
.wheel_radius
.with_context(|| format_dbg!())?,
wheel_rr_coef: self.veh.chassis.wheel_rr_coef,
pwr_prop_fwd_max: *vs.pwr_prop_fwd_max.get_fresh(|| format_dbg!())?,
};
let speed_ach = step_info.solve_for_speed(
self.sim_params.ach_speed_max_iter * 10,
self.sim_params.ach_speed_tol,
self.sim_params.ach_speed_solver_gain,
);
let speed_ach_floored = {
// NOTE: what we are doing here is "flooring" the speed to the nearest tenth of a m/s.
// The purpose is to slightly reduce the target speed below the max power threshold
// to prevent float precision issues from sending us right back into trace miss.
let v = ((speed_ach.get::<si::meter_per_second>() * 10.0).floor() / 10.0) * uc::MPS;
// NOTE: if after "flooring" we happen to exactly be the same as
// previous, we subtract off a tenth of a m/s but prevent going below 0 m/s.
if v == speed_ach {
(v - 0.1 * uc::MPS).max(si::Velocity::ZERO)
} else {
v
}
};
vs.speed_ach.update(speed_ach_floored, || format_dbg!())?;
// NOTE: need to reset tracked state to allow
// for calling set_pwr_prop_for_speed(.) again this step.
// set_pwr_prop_for_speed has already been called so the
// following variables have already been set fresh but need
// to be re-iterated.
vs.air_density.mark_stale();
vs.cyc_met.mark_stale();
vs.cyc_met_overall.mark_stale();
vs.elev_curr.mark_stale();
vs.grade_curr.mark_stale();
vs.pwr_accel.mark_stale();
vs.pwr_ascent.mark_stale();
vs.pwr_drag.mark_stale();
vs.pwr_rr.mark_stale();
vs.pwr_tractive.mark_stale();
vs.pwr_whl_inertia.mark_stale();
vs.speed_ach.mark_stale();
// Rerun again to ensure we have updated achieved speed and state
self.set_pwr_prop_for_speed(speed_ach_floored, speed_prev, dt)
.with_context(|| format_dbg!())?;
self.set_ach_speed(speed_ach, dt)
.with_context(|| anyhow!(format_dbg!()))?;
if self.sim_params.trace_miss_opts == TraceMissOptions::Correct {
let i = *self.veh.state.i.get_fresh(|| format_dbg!())?;
let max_steps = self.sim_params.trace_miss_correct_max_steps.max(2) as usize;
let correction = calc_best_rendezvous(i, max_steps, &self.cyc, speed_ach_floored);
if correction.steps >= 2 {
// NOTE: in theory, grade could be slightly
// off with this deviation from trace. However, since we
// rendezvous in a small number of time steps, it should be
// close. The call again to init() should correct distance
// and elevation calculations.
self.cyc.speed[i] = speed_ach_floored;
self.cyc.modify_by_const_jerk_trajectory(
i + 1,
correction.steps,
correction.jerk_m_per_s3 * uc::MPS3,
correction.acceleration_m_per_s2 * uc::MPS2,
);
self.cyc.dist.clear();
self.cyc.elev.clear();
self.cyc.init().unwrap();
}
}
Ok(())
}
pub fn to_fastsim2(&self) -> anyhow::Result<fastsim_2::simdrive::RustSimDrive> {
let veh2 = self
.veh
.to_fastsim2()
.with_context(|| anyhow!(format_dbg!()))?;
let cyc2 = self
.cyc
.to_fastsim2()
.with_context(|| anyhow!(format_dbg!()))?;
Ok(fastsim_2::simdrive::RustSimDrive::new(cyc2, veh2))
}
pub fn clear(&mut self) {
self.veh.clear();
}
}
impl SetCumulative for SimDrive {
fn set_cumulative<F: Fn() -> String>(&mut self, dt: si::Time, loc: F) -> anyhow::Result<()> {
self.veh
.set_cumulative(dt, || format!("{}\n{}", loc(), format_dbg!()))?;
Ok(())
}
fn reset_cumulative<F: Fn() -> String>(&mut self, loc: F) -> anyhow::Result<()> {
self.veh
.reset_cumulative(|| format!("{}\n{}", loc(), format_dbg!()))?;
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
// NOTE: consider embedding this in TraceMissOptions::AllowChecked
pub struct TraceMissTolerance {
/// if the vehicle falls this far behind trace in terms of absolute
/// difference and [TraceMissOptions::is_allow_checked], fail
tol_dist: si::Length,
/// if the vehicle falls this far behind trace in terms of fractional
/// difference and [TraceMissOptions::is_allow_checked], fail
tol_dist_frac: si::Ratio,
/// if the vehicle falls this far behind instantaneous speed and
/// [TraceMissOptions::is_allow_checked], fail
tol_speed: si::Velocity,
/// if the vehicle falls this far behind instantaneous speed in terms of
/// fractional difference and [TraceMissOptions::is_allow_checked], fail
tol_speed_frac: si::Ratio,
}
impl TraceMissTolerance {
fn check_trace_miss(
&self,
cyc_speed: si::Velocity,
ach_speed: si::Velocity,
cyc_dist: si::Length,
ach_dist: si::Length,
) -> anyhow::Result<()> {
ensure!(
cyc_speed - ach_speed < self.tol_speed,
"{}\n{}\n{}",
format_dbg!(cyc_speed),
format_dbg!(ach_speed),
format_dbg!(self.tol_speed)
);
// if condition to prevent divide-by-zero errors
if cyc_speed > self.tol_speed {
ensure!(
(cyc_speed - ach_speed) / cyc_speed < self.tol_speed_frac,
"{}\n{}\n{}",
format_dbg!(cyc_speed),
format_dbg!(ach_speed),
format_dbg!(self.tol_speed_frac)
)
}
ensure!(
(cyc_dist - ach_dist) < self.tol_dist,
"{}\n{}\n{}",
format_dbg!(cyc_dist),
format_dbg!(ach_dist),
format_dbg!(self.tol_dist)
);
// if condition to prevent checking early in cycle
if cyc_dist > self.tol_dist * 5.0 {
ensure!(
(cyc_dist - ach_dist) / cyc_dist < self.tol_dist_frac,
"{}\n{}\n{}",
format_dbg!(cyc_dist),
format_dbg!(ach_dist),
format_dbg!(self.tol_dist_frac)
)
}
Ok(())
}
}
impl SerdeAPI for TraceMissTolerance {}
impl Init for TraceMissTolerance {}
impl Default for TraceMissTolerance {
fn default() -> Self {
Self {
tol_dist: 100. * uc::M,
tol_dist_frac: 0.05 * uc::R,
tol_speed: 10. * uc::MPS,
tol_speed_frac: 0.5 * uc::R,
}
}
}
#[derive(
Clone, Default, Debug, Deserialize, Serialize, PartialEq, IsVariant, derive_more::From, TryInto,
)]
pub enum TraceMissOptions {
/// Allow trace miss without any fanfare
Allow,
/// Allow trace miss within error tolerance
AllowChecked,
#[default]
/// Error out when trace miss happens
Error,
/// Correct trace miss with driver model that catches up
Correct,
}
impl SerdeAPI for TraceMissOptions {}
impl Init for TraceMissOptions {}
#[cfg(test)]
mod tests {
use super::*;
use crate::vehicle::vehicle_model::tests::*;
#[test]
#[cfg(feature = "resources")]
fn test_sim_drive_conv() {
let _veh = mock_conv_veh();
let _cyc = Cycle::from_resource("udds.csv", false).unwrap();
let mut sd = SimDrive::new(_veh, _cyc, Default::default());
sd.walk().unwrap();
assert!(
*sd.veh.state.i.get_fresh(String::new).unwrap() == sd.cyc.len_checked().unwrap() - 1
);
assert!(
*sd.veh
.fc()
.unwrap()
.state
.energy_fuel
.get_fresh(String::new)
.unwrap()
> si::Energy::ZERO
);
assert!(sd.veh.res().is_none());
}
#[test]
#[cfg(feature = "resources")]
fn test_sim_drive_hev() {
let _veh = mock_hev();
let _cyc = Cycle::from_resource("udds.csv", false).unwrap();
let mut sd = SimDrive::new(_veh, _cyc, Default::default());
sd.walk().unwrap();
assert!(
*sd.veh.state.i.get_fresh(String::new).unwrap() == sd.cyc.len_checked().unwrap() - 1
);
assert!(
*sd.veh
.fc()
.unwrap()
.state
.energy_fuel
.get_fresh(String::new)
.unwrap()
> si::Energy::ZERO
);
assert!(
*sd.veh
.res()
.unwrap()
.state
.energy_out_chemical
.get_fresh(String::new)
.unwrap()
!= si::Energy::ZERO
);
}
#[test]
#[cfg(feature = "resources")]
fn test_sim_drive_hev_thrml() {
let _veh =
Vehicle::from_resource("2021_Hyundai_Sonata_Hybrid_Blue_thrml.yaml", false).unwrap();
let _cyc = Cycle::from_resource("udds.csv", false).unwrap();
let te_amb_and_cab_and_batt_init_deg_c: Vec<(f64, f64)> = vec![
(-6.7, -6.7),
(5.0, 18.0),
(22.0, 22.0),
(25.0, 35.0),
(45.0, 45.0),
];
let te_amb: Vec<si::Temperature> = te_amb_and_cab_and_batt_init_deg_c
.iter()
.map(|t| (t.0 + uc::CELSIUS_TO_KELVIN) * uc::KELVIN)
.collect();
let te_batt_and_cab_init: Vec<si::Temperature> = te_amb_and_cab_and_batt_init_deg_c
.iter()
.map(|t| (t.1 + uc::CELSIUS_TO_KELVIN) * uc::KELVIN)
.collect();
let te_fc_init: Vec<si::Temperature> = [-6.7, 70.0, 90.0]
.iter()
.map(|t| (*t + uc::CELSIUS_TO_KELVIN) * uc::KELVIN)
.collect();
for ((te_amb, te_init), te_fc_init) in
te_amb.iter().zip(te_batt_and_cab_init).zip(te_fc_init)
{
let mut veh = _veh.clone();
veh.res_mut()
.unwrap()
.res_thrml_state_mut()
.unwrap()
.temperature
.mark_stale();
veh.res_mut()
.unwrap()
.res_thrml_state_mut()
.unwrap()
.temperature
.update(te_init, || format_dbg!())
.unwrap();
veh.res_mut()
.unwrap()
.res_thrml_state_mut()
.unwrap()
.temp_prev
.mark_stale();
veh.res_mut()
.unwrap()
.res_thrml_state_mut()
.unwrap()
.temp_prev
.update(te_init, || format_dbg!())
.unwrap();
if let CabinOption::LumpedCabin(lc) = &mut veh.cabin {
lc.state.temperature.mark_stale();
lc.state
.temperature
.update(te_init, || format_dbg!())
.unwrap();
lc.state.temp_prev.mark_stale();
lc.state
.temp_prev
.update(te_init, || format_dbg!())
.unwrap();
}
veh.fc_mut()
.unwrap()
.fc_thrml_state_mut()
.unwrap()
.temperature
.mark_stale();
veh.fc_mut()
.unwrap()
.fc_thrml_state_mut()
.unwrap()
.temperature
.update(te_fc_init, || format_dbg!())
.unwrap();
let mut cyc = _cyc.clone();
cyc.temp_amb_air = vec![*te_amb; cyc.len_checked().unwrap()];
let mut sd = SimDrive::new(veh, cyc, Default::default());
sd.walk()
.with_context(|| {
format!(
"ambient temperature: {}*C\ninit temperature: {}",
te_amb.get::<si::degree_celsius>(),
te_init.get::<si::degree_celsius>()
)
})
.unwrap();
assert!(
*sd.veh.state.i.get_fresh(String::new).unwrap()
== sd.cyc.len_checked().unwrap() - 1
);
assert!(
*sd.veh
.fc()
.unwrap()
.state
.energy_fuel
.get_fresh(String::new)
.unwrap()
> si::Energy::ZERO
);
assert!(
*sd.veh
.res()
.unwrap()
.state
.energy_out_chemical
.get_fresh(String::new)
.unwrap()
!= si::Energy::ZERO
);
}
}
#[test]
#[cfg(feature = "resources")]
/// Simulate prep cycle, soak cycle, and test cycle with thermal effects
fn test_sim_drive_hev_thrml_soak() {
let _veh =
Vehicle::from_resource("2021_Hyundai_Sonata_Hybrid_Blue_thrml.yaml", false).unwrap();
let mut cyc = Cycle::from_resource("udds.csv", false).unwrap();
// zero out speed in soak cyc
let mut soak_cyc_no_temp = cyc.clone();
soak_cyc_no_temp
.speed
.iter_mut()
.for_each(|v| *v = si::Velocity::ZERO);
let te_amb: Vec<si::Temperature> = [-6.7, -6.7, 38.0]
.iter()
.map(|t| (*t + uc::CELSIUS_TO_KELVIN) * uc::KELVIN)
.collect();
let te_batt_and_cab_init: Vec<si::Temperature> = [-6.7, 22.0, 45.0]
.iter()
.map(|t| (*t + uc::CELSIUS_TO_KELVIN) * uc::KELVIN)
.collect();
let te_fc_init: Vec<si::Temperature> = [-6.7, 70.0, 90.0]
.iter()
.map(|t| (*t + uc::CELSIUS_TO_KELVIN) * uc::KELVIN)
.collect();
for ((te_amb, te_init), te_fc_init) in
te_amb.iter().zip(te_batt_and_cab_init).zip(te_fc_init)
{
let prep_cyc = cyc
.with_temp_amb_air(vec![*te_amb; cyc.len_checked().unwrap()])
.unwrap();
let soak_cyc = soak_cyc_no_temp
.with_temp_amb_air(vec![*te_amb; cyc.len_checked().unwrap()])
.unwrap();
let test_cyc = cyc
.with_temp_amb_air(vec![*te_amb; cyc.len_checked().unwrap()])
.unwrap();
let mut veh = _veh.clone();
veh.res_mut()
.unwrap()
.res_thrml_state_mut()
.unwrap()
.temperature
.mark_stale();
veh.res_mut()
.unwrap()
.res_thrml_state_mut()
.unwrap()
.temperature
.update(te_init, || format_dbg!())
.unwrap();
veh.res_mut()
.unwrap()
.res_thrml_state_mut()
.unwrap()
.temp_prev
.mark_stale();
veh.res_mut()
.unwrap()
.res_thrml_state_mut()
.unwrap()
.temp_prev
.update(te_init, || format_dbg!())
.unwrap();
if let CabinOption::LumpedCabin(lc) = &mut veh.cabin {
lc.state.temperature.mark_stale();
lc.state
.temperature
.update(te_init, || format_dbg!())
.unwrap();
lc.state.temp_prev.mark_stale();
lc.state
.temp_prev
.update(te_init, || format_dbg!())
.unwrap();
}
veh.fc_mut()
.unwrap()
.fc_thrml_state_mut()
.unwrap()
.temperature
.mark_stale();
veh.fc_mut()
.unwrap()
.fc_thrml_state_mut()
.unwrap()
.temperature
.update(te_fc_init, || format_dbg!())
.unwrap();
// simulate prep cycle
dbg!("Running `sd_prep`");
let mut sd_prep = SimDrive::new(veh, prep_cyc, None);
sd_prep
.walk()
.with_context(|| {
format!(
"\nprep cycle:\nambient temperature: {}*C\ninit temperature: {}",
te_amb.get::<si::degree_celsius>(),
te_init.get::<si::degree_celsius>()
)
})
.unwrap();
assert!(
*sd_prep.veh.state.i.get_fresh(String::new).unwrap()
== sd_prep.cyc.len_checked().unwrap() - 1
);
sd_prep.reset_step(|| format_dbg!()).unwrap();
sd_prep.veh.clear();
sd_prep.reset_cumulative(|| format_dbg!()).unwrap();
// simulate soak cycle
dbg!("Running `sd_soak`");
let mut sd_soak = SimDrive::new(
sd_prep.veh.clone(),
soak_cyc,
Some(SimParams {
ambient_thermal_soak: true,
..Default::default()
}),
);
sd_soak
.walk()
.with_context(|| {
format!(
"\nsoak cycle:\nambient temperature: {}*C\ninit temperature: {}",
te_amb.get::<si::degree_celsius>(),
te_init.get::<si::degree_celsius>()
)
})
.unwrap();
assert!(
*sd_soak.veh.state.i.get_fresh(String::new).unwrap()
== sd_soak.cyc.len_checked().unwrap() - 1
);
sd_soak.reset_step(|| format_dbg!()).unwrap();
sd_soak.veh.clear();
sd_soak.reset_cumulative(|| format_dbg!()).unwrap();
// simulate test cycle
dbg!("Running `sd_test`");
let mut sd_test = SimDrive::new(sd_soak.veh.clone(), test_cyc, None);
sd_test
.walk()
.with_context(|| {
format!(
"\ntest cycle:\nambient temperature: {}*C\ninit temperature: {}",
te_amb.get::<si::degree_celsius>(),
te_init.get::<si::degree_celsius>()
)
})
.unwrap();
assert!(
*sd_test.veh.state.i.get_fresh(String::new).unwrap()
== sd_test.cyc.len_checked().unwrap() - 1
);
sd_test.reset_step(|| format_dbg!()).unwrap();
sd_test.veh.clear();
sd_test.reset_cumulative(|| format_dbg!()).unwrap();
}
}
#[test]
#[cfg(feature = "resources")]
/// Simulate prep cycle, soak cycle, and test cycle with thermal effects
fn test_sim_drive_bev_thrml_soak() {
let _veh = Vehicle::from_resource("2020 Chevrolet Bolt EV thrml.yaml", false).unwrap();
let mut cyc = Cycle::from_resource("udds.csv", false).unwrap();
// zero out speed in soak cyc
let mut soak_cyc_no_temp = cyc.clone();
soak_cyc_no_temp
.speed
.iter_mut()
.for_each(|v| *v = si::Velocity::ZERO);
let te_amb: Vec<si::Temperature> = [-6.7, -6.7, 38.0]
.iter()
.map(|t| (*t + uc::CELSIUS_TO_KELVIN) * uc::KELVIN)
.collect();
let te_batt_and_cab_init: Vec<si::Temperature> = [-6.7, 22.0, 45.0]
.iter()
.map(|t| (*t + uc::CELSIUS_TO_KELVIN) * uc::KELVIN)
.collect();
// sweep ambient and initial conditions
for (te_amb, te_init) in te_amb.iter().zip(te_batt_and_cab_init) {
let prep_cyc = cyc
.with_temp_amb_air(vec![*te_amb; cyc.len_checked().unwrap()])
.unwrap();
let soak_cyc = soak_cyc_no_temp
.with_temp_amb_air(vec![*te_amb; cyc.len_checked().unwrap()])
.unwrap();
let test_cyc = cyc
.with_temp_amb_air(vec![*te_amb; cyc.len_checked().unwrap()])
.unwrap();
let mut veh = _veh.clone();
veh.res_mut()
.unwrap()
.res_thrml_state_mut()
.unwrap()
.temperature
.mark_stale();
veh.res_mut()
.unwrap()
.res_thrml_state_mut()
.unwrap()
.temperature
.update(te_init, || format_dbg!())
.unwrap();
veh.res_mut()
.unwrap()
.res_thrml_state_mut()
.unwrap()
.temp_prev
.mark_stale();
veh.res_mut()
.unwrap()
.res_thrml_state_mut()
.unwrap()
.temp_prev
.update(te_init, || format_dbg!())
.unwrap();
// setup initial conditions
if let CabinOption::LumpedCabin(lc) = &mut veh.cabin {
lc.state.temperature.mark_stale();
lc.state
.temperature
.update(te_init, || format_dbg!())
.unwrap();
lc.state.temp_prev.mark_stale();
lc.state
.temp_prev
.update(te_init, || format_dbg!())
.unwrap();
}
// simulate prep cycle
dbg!("Running `sd_prep`");
let mut sd_prep = SimDrive::new(veh, prep_cyc, None);
sd_prep
.walk()
.with_context(|| {
format!(
"\nprep cycle:\nambient temperature: {}*C\ninit temperature: {}",
te_amb.get::<si::degree_celsius>(),
te_init.get::<si::degree_celsius>()
)
})
.unwrap();
assert!(
*sd_prep.veh.state.i.get_fresh(String::new).unwrap()
== sd_prep.cyc.len_checked().unwrap() - 1
);
sd_prep.reset_step(|| format_dbg!()).unwrap();
sd_prep.veh.clear();
sd_prep.reset_cumulative(|| format_dbg!()).unwrap();
// simulate soak cycle
dbg!("Running `sd_soak`");
let mut sd_soak = SimDrive::new(
sd_prep.veh.clone(),
soak_cyc,
Some(SimParams {
ambient_thermal_soak: true,
..Default::default()
}),
);
sd_soak
.walk()
.with_context(|| {
format!(
"\nsoak cycle:\nambient temperature: {}*C\ninit temperature: {}",
te_amb.get::<si::degree_celsius>(),
te_init.get::<si::degree_celsius>()
)
})
.unwrap();
assert!(
*sd_soak.veh.state.i.get_fresh(String::new).unwrap()
== sd_soak.cyc.len_checked().unwrap() - 1
);
sd_soak.reset_step(|| format_dbg!()).unwrap();
sd_soak.veh.clear();
sd_soak.reset_cumulative(|| format_dbg!()).unwrap();
// simulate test cycle
dbg!("Running `sd_test`");
let mut sd_test = SimDrive::new(sd_soak.veh.clone(), test_cyc, None);
sd_test
.walk()
.with_context(|| {
format!(
"\ntest cycle:\nambient temperature: {}*C\ninit temperature: {}",
te_amb.get::<si::degree_celsius>(),
te_init.get::<si::degree_celsius>()
)
})
.unwrap();
assert!(
*sd_test.veh.state.i.get_fresh(String::new).unwrap()
== sd_test.cyc.len_checked().unwrap() - 1
);
sd_test.reset_step(|| format_dbg!()).unwrap();
sd_test.veh.clear();
sd_test.reset_cumulative(|| format_dbg!()).unwrap();
}
}
#[test]
#[cfg(feature = "resources")]
fn test_sim_drive_bev() {
let _veh = mock_bev();
let _cyc = Cycle::from_resource("udds.csv", false).unwrap();
let mut sd = SimDrive {
veh: _veh,
cyc: _cyc,
sim_params: Default::default(),
};
sd.walk().unwrap();
assert!(
*sd.veh.state.i.get_fresh(String::new).unwrap() == sd.cyc.len_checked().unwrap() - 1
);
assert!(sd.veh.fc().is_none());
assert!(
*sd.veh
.res()
.unwrap()
.state
.energy_out_chemical
.get_fresh(String::new)
.unwrap()
!= si::Energy::ZERO
);
}
#[test]
#[cfg(feature = "resources")]
fn test_sim_drive_bev_thrml() {
let _veh = Vehicle::from_resource("2020 Chevrolet Bolt EV thrml.yaml", false).unwrap();
let _cyc = Cycle::from_resource("udds.csv", false).unwrap();
let te_amb_and_cab_and_batt_init_deg_c: Vec<(f64, f64)> = vec![
(-6.7, -6.7),
(5.0, 18.0),
(22.0, 22.0),
(25.0, 35.0),
(45.0, 45.0),
];
let te_amb: Vec<si::Temperature> = te_amb_and_cab_and_batt_init_deg_c
.iter()
.map(|t| (t.0 + uc::CELSIUS_TO_KELVIN) * uc::KELVIN)
.collect();
let te_batt_and_cab_init: Vec<si::Temperature> = te_amb_and_cab_and_batt_init_deg_c
.iter()
.map(|t| (t.1 + uc::CELSIUS_TO_KELVIN) * uc::KELVIN)
.collect();
for (te_amb, te_init) in te_amb.iter().zip(te_batt_and_cab_init) {
let mut veh = _veh.clone();
veh.res_mut()
.unwrap()
.res_thrml_state_mut()
.unwrap()
.temperature
.mark_stale();
veh.res_mut()
.unwrap()
.res_thrml_state_mut()
.unwrap()
.temperature
.update(te_init, || format_dbg!())
.unwrap();
veh.res_mut()
.unwrap()
.res_thrml_state_mut()
.unwrap()
.temp_prev
.mark_stale();
veh.res_mut()
.unwrap()
.res_thrml_state_mut()
.unwrap()
.temp_prev
.update(te_init, || format_dbg!())
.unwrap();
if let CabinOption::LumpedCabin(lc) = &mut veh.cabin {
lc.state.temperature.mark_stale();
lc.state
.temperature
.update(te_init, || format_dbg!())
.unwrap();
lc.state.temp_prev.mark_stale();
lc.state
.temp_prev
.update(te_init, || format_dbg!())
.unwrap();
} else {
panic!("cabin should have been configured");
}
let mut cyc = _cyc.clone();
cyc.temp_amb_air = vec![*te_amb; cyc.len_checked().unwrap()];
let mut sd = SimDrive::new(veh, cyc, Default::default());
if let CabinOption::LumpedCabin(lc) = sd.veh.cabin.clone() {
assert_eq!(
*lc.state.temperature.get_fresh(|| format_dbg!()).unwrap(),
te_init
);
} else {
panic!();
};
sd.walk()
.with_context(|| {
format!(
"ambient temperature: {}*C\ninit temperature: {}",
te_amb.get::<si::degree_celsius>(),
te_init.get::<si::degree_celsius>()
)
})
.unwrap();
assert!(
*sd.veh.state.i.get_fresh(String::new).unwrap()
== sd.cyc.len_checked().unwrap() - 1
);
assert!(sd.veh.fc().is_none());
assert!(
*sd.veh
.res()
.unwrap()
.state
.energy_out_chemical
.get_fresh(String::new)
.unwrap()
!= si::Energy::ZERO
);
sd.veh.reset_step(|| format_dbg!()).unwrap();
sd.veh.state.time.mark_stale();
sd.veh
.state
.time
.update(si::Time::ZERO, || format_dbg!())
.unwrap();
assert!(*sd.veh.state.i.get_fresh(|| format_dbg!()).unwrap() == 0);
sd.walk()
.with_context(|| {
format!(
"ambient temperature: {}*C\ninit temperature: {}",
te_amb.get::<si::degree_celsius>(),
te_init.get::<si::degree_celsius>()
)
})
.unwrap();
sd.reset_cumulative(|| format_dbg!()).unwrap();
assert_eq!(*sd.veh.state.i.get_fresh(|| format_dbg!()).unwrap(), 1369);
}
}
}