Skip to content

Commit

Permalink
Merge branch 'fastsim-2' into multilinear
Browse files Browse the repository at this point in the history
  • Loading branch information
kylecarow authored Nov 30, 2023
2 parents d0279f6 + 42268bf commit 0e525e9
Show file tree
Hide file tree
Showing 14 changed files with 88 additions and 120 deletions.
4 changes: 2 additions & 2 deletions rust/fastsim-cli/src/bin/fastsim-cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ pub fn main() -> anyhow::Result<()> {
&& adopt_hd_str_lc != false_string;
(true, adopt_hd_string.clone(), adopt_hd_has_cycle)
} else {
(false, String::from(""), false)
(false, String::default(), false)
};
let cyc = if let Some(cyc_file_path) = fastsim_api.cyc_file {
if cyc_file_path == *"coastdown" {
Expand Down Expand Up @@ -231,7 +231,7 @@ pub fn main() -> anyhow::Result<()> {
vec![0.0],
vec![0.0],
vec![0.0],
String::from(""),
"",
))
}?;

Expand Down
1 change: 1 addition & 0 deletions rust/fastsim-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ regex = "1.7.1"
rayon = "1.7.0"
include_dir = "0.7.3"
itertools = "0.12.0"
ndarray-stats = "0.5.1"

[package.metadata]
include = [
Expand Down
6 changes: 3 additions & 3 deletions rust/fastsim-core/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ fn main() {
// path when building using build_and_test.sh
let build_path = "../../python/fastsim/resources".to_string();

let prepath: String = match PathBuf::from(publish_path.clone()).exists() {
let prepath: String = match PathBuf::from(&publish_path).exists() {
true => publish_path,
false => build_path,
};

if !PathBuf::from(prepath.clone()).exists() {
if !PathBuf::from(&prepath).exists() {
// no need for further checks since this indicates that it's
// likely that python fastsim is not available and thus
// fastsim-core is likely being compiled as a dependency
Expand Down Expand Up @@ -59,7 +59,7 @@ fn main() {
for (tf, cf) in truth_files.iter().zip(compare_files) {
let tfc = fs::read_to_string(tf).unwrap_or_else(|_| panic!("{tf} does not exist."));

let cfc = fs::read_to_string(cf.clone()).unwrap_or_else(|_| panic!("{cf} does not exist."));
let cfc = fs::read_to_string(&cf).unwrap_or_else(|_| panic!("{cf} does not exist."));

if tfc != cfc {
panic!("Reference file {tf} does not match file being compared: {cf}. Copy {tf} to {cf} to fix this.")
Expand Down
2 changes: 1 addition & 1 deletion rust/fastsim-core/src/air.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ impl Default for AirProperties {
.into(),
);

let pr_array = mu_array.clone() * c_p_array.clone() / k_array.clone();
let pr_array = &mu_array * &c_p_array / &k_array;

Self {
te_array_degc,
Expand Down
21 changes: 8 additions & 13 deletions rust/fastsim-core/src/cycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ pub fn to_microtrips(cycle: &RustCycle, stop_speed_m_per_s: Option<f64>) -> Vec<
mt_vs.clone(),
mt_gs.clone(),
mt_rs.clone(),
cycle.name.clone(),
&cycle.name,
));
mt_ts = vec![last_t];
mt_vs = vec![last_v];
Expand All @@ -244,13 +244,7 @@ pub fn to_microtrips(cycle: &RustCycle, stop_speed_m_per_s: Option<f64>) -> Vec<
}
if !mt_ts.is_empty() {
mt_ts = mt_ts.iter().map(|t| -> f64 { t - mt_ts[0] }).collect();
microtrips.push(RustCycle::new(
mt_ts,
mt_vs,
mt_gs,
mt_rs,
cycle.name.clone(),
));
microtrips.push(RustCycle::new(mt_ts, mt_vs, mt_gs, mt_rs, &cycle.name));
}
microtrips
}
Expand Down Expand Up @@ -344,7 +338,7 @@ pub fn extend_cycle(
rs.push(0.0);
idx += 1;
}
RustCycle::new(ts, vs, gs, rs, cyc.name.clone())
RustCycle::new(ts, vs, gs, rs, &cyc.name)
}

#[cfg(feature = "pyo3")]
Expand Down Expand Up @@ -686,17 +680,18 @@ impl SerdeAPI for RustCycle {

/// pure Rust methods that need to be separate due to pymethods incompatibility
impl RustCycle {
pub fn new(
pub fn new<S: AsRef<str>>(
time_s: Vec<f64>,
mps: Vec<f64>,
grade: Vec<f64>,
road_type: Vec<f64>,
name: String,
name: S,
) -> Self {
let time_s = Array::from_vec(time_s);
let mps = Array::from_vec(mps);
let grade = Array::from_vec(grade);
let road_type = Array::from_vec(road_type);
let name = name.as_ref().to_string();
Self {
time_s,
mps,
Expand Down Expand Up @@ -1014,7 +1009,7 @@ impl RustCycle {

/// elevation change w.r.t. to initial
pub fn delta_elev_m(&self) -> Array1<f64> {
ndarrcumsum(&(self.dist_m() * self.grade.clone()))
ndarrcumsum(&(self.dist_m() * &self.grade))
}
}

Expand Down Expand Up @@ -1127,7 +1122,7 @@ mod tests {
let speed_mps = vec![0.0, 10.0, 10.0, 0.0, 0.0];
let grade = Array::zeros(5).to_vec();
let road_type = Array::zeros(5).to_vec();
let name = String::from("test");
let name = "test";
let cyc = RustCycle::new(time_s, speed_mps, grade, road_type, name);
let avg_mps = average_step_speeds(&cyc);
let expected_avg_mps = Array::from_vec(vec![0.0, 5.0, 10.0, 5.0, 0.0]);
Expand Down
1 change: 1 addition & 0 deletions rust/fastsim-core/src/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ pub(crate) use anyhow::{anyhow, bail, ensure, Context};
pub(crate) use bincode;
pub(crate) use log;
pub(crate) use ndarray::{array, s, Array, Array1, Axis};
pub(crate) use ndarray_stats::QuantileExt;
pub(crate) use serde::{Deserialize, Serialize};
pub(crate) use std::cmp;
pub(crate) use std::ffi::OsStr;
Expand Down
4 changes: 2 additions & 2 deletions rust/fastsim-core/src/simdrive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -345,11 +345,11 @@ impl Default for RustSimDriveParams {
#[getter]
pub fn get_fs_cumu_mj_out_ach(&self) -> Pyo3ArrayF64 {
Pyo3ArrayF64::new(ndarrcumsum(&(self.fs_kw_out_ach.clone() * self.cyc.dt_s() * 1e-3)))
Pyo3ArrayF64::new(ndarrcumsum(&(&self.fs_kw_out_ach * self.cyc.dt_s() * 1e-3)))
}
#[getter]
pub fn get_fc_cumu_mj_out_ach(&self) -> Pyo3ArrayF64 {
Pyo3ArrayF64::new(ndarrcumsum(&(self.fc_kw_out_ach.clone() * self.cyc.dt_s() * 1e-3)))
Pyo3ArrayF64::new(ndarrcumsum(&(&self.fc_kw_out_ach * self.cyc.dt_s() * 1e-3)))
}
)]
pub struct RustSimDrive {
Expand Down
17 changes: 8 additions & 9 deletions rust/fastsim-core/src/simdrive/cyc_mods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::cycle::{
trapz_distance_for_step, trapz_step_distances, trapz_step_start_distance, PassingInfo,
};
use crate::simdrive::RustSimDrive;
use crate::utils::{add_from, max, min, ndarrcumsum, ndarrmax, ndarrmin, ndarrunique};
use crate::utils::{add_from, max, min, ndarrcumsum, ndarrunique};

impl RustSimDrive {
/// Provides the gap-with lead vehicle from start to finish
Expand Down Expand Up @@ -159,7 +159,7 @@ impl RustSimDrive {
let v_desired_m_per_s = if self.idm_target_speed_m_per_s[i] > 0.0 {
self.idm_target_speed_m_per_s[i]
} else {
ndarrmax(&self.cyc0.mps)
*self.cyc0.mps.max().unwrap()
};
// DERIVED VALUES
self.cyc.mps[i] = self.next_speed_by_idm(
Expand Down Expand Up @@ -374,14 +374,13 @@ impl RustSimDrive {
let a_brake = self.sim_params.coast_brake_accel_m_per_s2;
assert![a_brake <= 0.0];
let ds = &self.cyc0_cache.trapz_distances_m;
let gs = self.cyc0.grade.clone();
let d0 = trapz_step_start_distance(&self.cyc, i);
let mut distances_m: Vec<f64> = Vec::with_capacity(ds.len());
let mut grade_by_distance: Vec<f64> = Vec::with_capacity(ds.len());
for idx in 0..ds.len() {
if ds[idx] >= d0 {
distances_m.push(ds[idx] - d0);
grade_by_distance.push(gs[idx])
grade_by_distance.push(self.cyc0.grade[idx])
}
}
if distances_m.is_empty() {
Expand Down Expand Up @@ -889,9 +888,9 @@ impl RustSimDrive {
);
}
let all_sub_coast: bool = trace_accels_m_per_s2
.clone()
.into_iter()
.zip(accels_m_per_s2.clone().into_iter())
.iter()
.copied()
.zip(accels_m_per_s2.iter().copied())
.fold(
true,
|all_sc_flag: bool, (trace_accel, accel): (f64, f64)| {
Expand All @@ -902,8 +901,8 @@ impl RustSimDrive {
},
);
let accels_ndarr = Array1::from(accels_m_per_s2.clone());
let min_accel_m_per_s2 = ndarrmin(&accels_ndarr);
let max_accel_m_per_s2 = ndarrmax(&accels_ndarr);
let min_accel_m_per_s2 = accels_ndarr.min()?;
let max_accel_m_per_s2 = accels_ndarr.max()?;
let accept = all_sub_coast;
let accel_spread = (max_accel_m_per_s2 - min_accel_m_per_s2).abs();
if accept && (!best.found_trajectory || accel_spread < best.accel_spread) {
Expand Down
88 changes: 41 additions & 47 deletions rust/fastsim-core/src/simdrive/simdrive_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::cycle::{RustCycle, RustCycleCache};
use crate::imports::*;
use crate::params;
use crate::simdrive::{RustSimDrive, RustSimDriveParams};
use crate::utils::{arrmax, first_grtr, max, min, ndarrmax, ndarrmin};
use crate::utils::{arrmax, first_grtr, max, min};
use crate::vehicle::*;

pub struct RendezvousTrajectory {
Expand All @@ -28,7 +28,7 @@ pub struct CoastTrajectory {
impl RustSimDrive {
pub fn new(cyc: RustCycle, veh: RustVehicle) -> Self {
let hev_sim_count: usize = 0;
let cyc0: RustCycle = cyc.clone();
let cyc0 = cyc.clone();
let sim_params = RustSimDriveParams::default();
let props = params::RustPhysicalProperties::default();
let i: usize = 1; // 1 # initialize step counter for possible use outside sim_drive_walk()
Expand Down Expand Up @@ -123,29 +123,29 @@ impl RustSimDrive {
let cur_max_roadway_chg_kw = Array::zeros(cyc_len);
let trace_miss_iters = Array::zeros(cyc_len);
let newton_iters = Array::zeros(cyc_len);
let fuel_kj: f64 = 0.0;
let ess_dischg_kj: f64 = 0.0;
let energy_audit_error: f64 = 0.0;
let mpgge: f64 = 0.0;
let roadway_chg_kj: f64 = 0.0;
let battery_kwh_per_mi: f64 = 0.0;
let electric_kwh_per_mi: f64 = 0.0;
let ess2fuel_kwh: f64 = 0.0;
let drag_kj: f64 = 0.0;
let ascent_kj: f64 = 0.0;
let rr_kj: f64 = 0.0;
let brake_kj: f64 = 0.0;
let trans_kj: f64 = 0.0;
let mc_kj: f64 = 0.0;
let ess_eff_kj: f64 = 0.0;
let aux_kj: f64 = 0.0;
let fc_kj: f64 = 0.0;
let net_kj: f64 = 0.0;
let ke_kj: f64 = 0.0;
let fuel_kj = 0.0;
let ess_dischg_kj = 0.0;
let energy_audit_error = 0.0;
let mpgge = 0.0;
let roadway_chg_kj = 0.0;
let battery_kwh_per_mi = 0.0;
let electric_kwh_per_mi = 0.0;
let ess2fuel_kwh = 0.0;
let drag_kj = 0.0;
let ascent_kj = 0.0;
let rr_kj = 0.0;
let brake_kj = 0.0;
let trans_kj = 0.0;
let mc_kj = 0.0;
let ess_eff_kj = 0.0;
let aux_kj = 0.0;
let fc_kj = 0.0;
let net_kj = 0.0;
let ke_kj = 0.0;
let trace_miss = false;
let trace_miss_dist_frac: f64 = 0.0;
let trace_miss_time_frac: f64 = 0.0;
let trace_miss_speed_mps: f64 = 0.0;
let trace_miss_dist_frac = 0.0;
let trace_miss_time_frac = 0.0;
let trace_miss_speed_mps = 0.0;
let coast_delay_index = Array::zeros(cyc_len);
let idm_target_speed_m_per_s = Array::zeros(cyc_len);
let cyc0_cache = RustCycleCache::new(&cyc0);
Expand Down Expand Up @@ -474,7 +474,7 @@ impl RustSimDrive {
aux_in_kw_override: Option<Array1<f64>>,
) -> anyhow::Result<()> {
// Initialize and run sim_drive_walk as appropriate for vehicle attribute vehPtType.
let init_soc_auto: f64 = match self.veh.veh_pt_type.as_str() {
let init_soc_auto = match self.veh.veh_pt_type.as_str() {
// If no EV / Hybrid components, no SOC considerations.
CONV => (self.veh.max_soc + self.veh.min_soc) / 2.0,
HEV => (self.veh.max_soc + self.veh.min_soc) / 2.0,
Expand Down Expand Up @@ -511,12 +511,12 @@ impl RustSimDrive {
if self.sim_params.missed_trace_correction {
log::info!(
"Max time dilation factor = {:.3}",
ndarrmax(&(self.cyc.dt_s() / self.cyc0.dt_s()))
(self.cyc.dt_s() / self.cyc0.dt_s()).max()?
);
}
log::warn!(
"Large time steps affect accuracy significantly (max time step = {:.3})",
ndarrmax(&self.cyc.dt_s())
self.cyc.dt_s().max()?
);
}
Ok(())
Expand Down Expand Up @@ -1085,8 +1085,8 @@ impl RustSimDrive {
self.mps_ach[i] = max(
speed_guesses[_ys
.iter()
.position(|&x| x == ndarrmin(&_ys))
.ok_or_else(|| anyhow!(format_dbg!(ndarrmin(&_ys))))?],
.position(|x| x == _ys.min().unwrap())
.ok_or_else(|| anyhow!(format_dbg!(_ys.min().unwrap())))?],
0.0,
);
grade_estimate = self.lookup_grade_for_step(i, Some(self.mps_ach[i]));
Expand Down Expand Up @@ -1780,7 +1780,7 @@ impl RustSimDrive {
self.mpgge = self.dist_mi.sum() / (self.fs_kwh_out_ach.sum() / self.props.kwh_per_gge);
}

self.roadway_chg_kj = (self.roadway_chg_kw_out_ach.clone() * self.cyc.dt_s()).sum();
self.roadway_chg_kj = (&self.roadway_chg_kw_out_ach * self.cyc.dt_s()).sum();
self.ess_dischg_kj = -1.0
* (self
.soc
Expand All @@ -1800,7 +1800,7 @@ impl RustSimDrive {
} else {
0.0
};
self.fuel_kj = (self.fs_kw_out_ach.clone() * self.cyc.dt_s()).sum();
self.fuel_kj = (&self.fs_kw_out_ach * self.cyc.dt_s()).sum();

if (self.fuel_kj + self.roadway_chg_kj) == 0.0 {
self.ess2fuel_kwh = 1.0
Expand All @@ -1809,9 +1809,9 @@ impl RustSimDrive {
}

// energy audit calcs
self.drag_kj = (self.drag_kw.clone() * self.cyc.dt_s()).sum();
self.ascent_kj = (self.ascent_kw.clone() * self.cyc.dt_s()).sum();
self.rr_kj = (self.rr_kw.clone() * self.cyc.dt_s()).sum();
self.drag_kj = (&self.drag_kw * self.cyc.dt_s()).sum();
self.ascent_kj = (&self.ascent_kw * self.cyc.dt_s()).sum();
self.rr_kj = (&self.rr_kw * self.cyc.dt_s()).sum();

for i in 1..self.cyc.len() {
if self.veh.ess_max_kw == 0.0 || self.veh.ess_max_kwh == 0.0 {
Expand All @@ -1826,17 +1826,12 @@ impl RustSimDrive {
}
}

self.brake_kj = (self.cyc_fric_brake_kw.clone() * self.cyc.dt_s()).sum();
self.trans_kj = ((self.trans_kw_in_ach.clone() - self.trans_kw_out_ach.clone())
* self.cyc.dt_s())
.sum();
self.mc_kj = ((self.mc_elec_kw_in_ach.clone() - self.mc_mech_kw_out_ach.clone())
* self.cyc.dt_s())
.sum();
self.ess_eff_kj = (self.ess_loss_kw.clone() * self.cyc.dt_s()).sum();
self.aux_kj = (self.aux_in_kw.clone() * self.cyc.dt_s()).sum();
self.fc_kj =
((self.fc_kw_in_ach.clone() - self.fc_kw_out_ach.clone()) * self.cyc.dt_s()).sum();
self.brake_kj = (&self.cyc_fric_brake_kw * self.cyc.dt_s()).sum();
self.trans_kj = ((&self.trans_kw_in_ach - &self.trans_kw_out_ach) * self.cyc.dt_s()).sum();
self.mc_kj = ((&self.mc_elec_kw_in_ach - &self.mc_mech_kw_out_ach) * self.cyc.dt_s()).sum();
self.ess_eff_kj = (&self.ess_loss_kw * self.cyc.dt_s()).sum();
self.aux_kj = (&self.aux_in_kw * self.cyc.dt_s()).sum();
self.fc_kj = ((&self.fc_kw_in_ach - &self.fc_kw_out_ach) * self.cyc.dt_s()).sum();

self.net_kj = self.drag_kj
+ self.ascent_kj
Expand Down Expand Up @@ -1914,8 +1909,7 @@ impl RustSimDrive {
);
}

self.trace_miss_speed_mps =
ndarrmax(&(self.mps_ach.clone() - self.cyc.mps.clone()).map(|x| x.abs()));
self.trace_miss_speed_mps = *(&self.mps_ach - &self.cyc.mps).map(|x| x.abs()).max()?;
if self.trace_miss_speed_mps > self.sim_params.trace_miss_speed_mps_tol {
self.trace_miss = true;
log::warn!(
Expand Down
Loading

0 comments on commit 0e525e9

Please sign in to comment.