diff --git a/rust/fastsim-cli/src/bin/fastsim-cli.rs b/rust/fastsim-cli/src/bin/fastsim-cli.rs index 3d73845a..99b80705 100644 --- a/rust/fastsim-cli/src/bin/fastsim-cli.rs +++ b/rust/fastsim-cli/src/bin/fastsim-cli.rs @@ -240,9 +240,9 @@ pub fn main() -> anyhow::Result<()> { // TODO: put in logic here for loading vehicle for adopt-hd // with same file format as regular adopt and same outputs retured - let is_adopt: bool = fastsim_api.adopt.is_some() && fastsim_api.adopt.unwrap(); - let mut fc_pwr_out_perc: Option> = None; - let mut hd_h2_diesel_ice_h2share: Option> = None; + let is_adopt = fastsim_api.adopt.is_some() && fastsim_api.adopt.unwrap(); + let mut fc_pwr_out_perc = None; + let mut hd_h2_diesel_ice_h2share = None; let veh = if let Some(veh_string) = fastsim_api.veh { if is_adopt || is_adopt_hd { let (veh_string, pwr_out_perc, h2share) = json_rewrite(veh_string)?; @@ -401,8 +401,8 @@ impl SerdeAPI for ParsedValue {} fn json_rewrite(x: String) -> anyhow::Result<(String, Option>, Option>)> { let adoptstring = x; - let mut fc_pwr_out_perc: Option> = None; - let mut hd_h2_diesel_ice_h2share: Option> = None; + let mut fc_pwr_out_perc = None; + let mut hd_h2_diesel_ice_h2share = None; let mut parsed_data: Value = serde_json::from_str(&adoptstring)?; @@ -440,7 +440,7 @@ fn json_rewrite(x: String) -> anyhow::Result<(String, Option>, Option publish_path, false => build_path, }; diff --git a/rust/fastsim-core/fastsim-proc-macros/src/add_pyo3_api/mod.rs b/rust/fastsim-core/fastsim-proc-macros/src/add_pyo3_api/mod.rs index a7189e34..c899c52b 100644 --- a/rust/fastsim-core/fastsim-proc-macros/src/add_pyo3_api/mod.rs +++ b/rust/fastsim-core/fastsim-proc-macros/src/add_pyo3_api/mod.rs @@ -9,7 +9,7 @@ pub fn add_pyo3_api(attr: TokenStream, item: TokenStream) -> TokenStream { let mut ast = syn::parse_macro_input!(item as syn::ItemStruct); // println!("{}", ast.ident.to_string()); let ident = &ast.ident; - let _is_state_or_history: bool = + let _is_state_or_history = ident.to_string().contains("State") || ident.to_string().contains("HistoryVec"); let mut impl_block = TokenStream2::default(); @@ -344,7 +344,7 @@ pub fn add_pyo3_api(attr: TokenStream, item: TokenStream) -> TokenStream { final_output.extend::(quote! { #[cfg_attr(feature="pyo3", pyclass(module = "fastsimrust", subclass))] }); - let mut output: TokenStream2 = ast.to_token_stream(); + let mut output = ast.to_token_stream(); output.extend(impl_block); // if ast.ident.to_string() == "RustSimDrive" { // println!("{}", output.to_string()); diff --git a/rust/fastsim-core/fastsim-proc-macros/src/approx_eq_derive.rs b/rust/fastsim-core/fastsim-proc-macros/src/approx_eq_derive.rs index 5babdf0a..34c467e8 100644 --- a/rust/fastsim-core/fastsim-proc-macros/src/approx_eq_derive.rs +++ b/rust/fastsim-core/fastsim-proc-macros/src/approx_eq_derive.rs @@ -20,7 +20,7 @@ pub fn approx_eq_derive(input: TokenStream) -> TokenStream { generated.append_all(quote! { impl ApproxEq for #name { fn approx_eq(&self, other: &#name, tol: f64) -> bool { - let mut approx_eq_vals: Vec = Vec::new(); + let mut approx_eq_vals = Vec::new(); #(approx_eq_vals.push(self.#field_names.approx_eq(&other.#field_names, tol));)* approx_eq_vals.iter().all(|&x| x) } diff --git a/rust/fastsim-core/fastsim-proc-macros/src/doc_field.rs b/rust/fastsim-core/fastsim-proc-macros/src/doc_field.rs index 068f334c..ec3599f7 100644 --- a/rust/fastsim-core/fastsim-proc-macros/src/doc_field.rs +++ b/rust/fastsim-core/fastsim-proc-macros/src/doc_field.rs @@ -7,7 +7,7 @@ pub fn doc_field(_attr: TokenStream, item: TokenStream) -> TokenStream { let new_fields = if let syn::Fields::Named(FieldsNamed { named, .. }) = &mut item_struct.fields { - let mut new_doc_fields: Vec = Vec::new(); + let mut new_doc_fields = Vec::new(); for field in named.iter_mut() { let mut skip_doc = false; remove_handled_attrs(field, &mut skip_doc); @@ -57,7 +57,7 @@ pub fn doc_field(_attr: TokenStream, item: TokenStream) -> TokenStream { let struct_vis = item_struct.vis; let struct_attrs = item_struct.attrs; - let output: TokenStream2 = quote! { + let output = quote! { #(#struct_attrs)* #struct_vis struct #struct_ident { #new_fields diff --git a/rust/fastsim-core/src/cycle.rs b/rust/fastsim-core/src/cycle.rs index 101bf295..a4009fb5 100644 --- a/rust/fastsim-core/src/cycle.rs +++ b/rust/fastsim-core/src/cycle.rs @@ -111,7 +111,7 @@ pub fn accel_for_constant_jerk(n: usize, a0: f64, k: f64, dt: f64) -> f64 { /// Apply `accel_for_constant_jerk` to full pub fn accel_array_for_constant_jerk(nmax: usize, a0: f64, k: f64, dt: f64) -> Array1 { - let mut accels: Vec = Vec::new(); + let mut accels = Vec::new(); for n in 0..nmax { accels.push(accel_for_constant_jerk(n, a0, k, dt)); } @@ -120,7 +120,7 @@ pub fn accel_array_for_constant_jerk(nmax: usize, a0: f64, k: f64, dt: f64) -> A /// Calculate the average speed per each step in m/s pub fn average_step_speeds(cyc: &RustCycle) -> Array1 { - let mut result: Vec = Vec::with_capacity(cyc.len()); + let mut result = Vec::with_capacity(cyc.len()); result.push(0.0); for i in 1..cyc.len() { result.push(0.5 * (cyc.mps[i] + cyc.mps[i - 1])); @@ -141,7 +141,7 @@ pub fn trapz_step_distances(cyc: &RustCycle) -> Array1 { } pub fn trapz_step_distances_primitive(time_s: &Array1, mps: &Array1) -> Array1 { - let mut delta_dists_m: Vec = Vec::with_capacity(time_s.len()); + let mut delta_dists_m = Vec::with_capacity(time_s.len()); delta_dists_m.push(0.0); for i in 1..time_s.len() { delta_dists_m.push((time_s[i] - time_s[i - 1]) * 0.5 * (mps[i] + mps[i - 1])); @@ -153,7 +153,7 @@ pub fn trapz_step_distances_primitive(time_s: &Array1, mps: &Array1) - /// (i.e., distance traveled up to sample point i-1) /// Distance is in meters. pub fn trapz_step_start_distance(cyc: &RustCycle, i: usize) -> f64 { - let mut dist_m: f64 = 0.0; + let mut dist_m = 0.0; for i in 1..i { dist_m += (cyc.time_s[i] - cyc.time_s[i - 1]) * 0.5 * (cyc.mps[i] + cyc.mps[i - 1]); } @@ -199,7 +199,7 @@ pub fn time_spent_moving(cyc: &RustCycle, stopped_speed_m_per_s: Option) -> /// that name to all microtrips pub fn to_microtrips(cycle: &RustCycle, stop_speed_m_per_s: Option) -> Vec { let stop_speed_m_per_s = stop_speed_m_per_s.unwrap_or(1e-6); - let mut microtrips: Vec = Vec::new(); + let mut microtrips = Vec::new(); let ts = cycle.time_s.to_vec(); let vs = cycle.mps.to_vec(); let gs = cycle.grade.to_vec(); @@ -278,7 +278,7 @@ pub fn create_dist_and_target_speeds_by_microtrip( } else { blend_factor }; - let mut dist_and_tgt_speeds: Vec<(f64, f64)> = Vec::new(); + let mut dist_and_tgt_speeds = Vec::new(); // Split cycle into microtrips let microtrips = to_microtrips(cyc, None); let mut dist_at_start_of_microtrip_m = 0.0; @@ -421,9 +421,9 @@ impl RustCycleCache { ndarrcumsum(&xs) }; let stops = Array::from_iter(cyc.mps.iter().map(|v| v <= &tol)); - let mut interp_ds: Vec = Vec::with_capacity(num_items); - let mut interp_is: Vec = Vec::with_capacity(num_items); - let mut interp_hs: Vec = Vec::with_capacity(num_items); + let mut interp_ds = Vec::with_capacity(num_items); + let mut interp_is = Vec::with_capacity(num_items); + let mut interp_hs = Vec::with_capacity(num_items); for idx in 0..num_items { let d = trapz_distances_m[idx]; if interp_ds.is_empty() || d > *interp_ds.last().unwrap() { @@ -968,7 +968,7 @@ impl RustCycle { distance_m: f64, cache: Option<&RustCycleCache>, ) -> f64 { - let tol: f64 = 1e-6; + let tol = 1e-6; match cache { Some(rcc) => { for (&dist, &v) in rcc.trapz_distances_m.iter().zip(self.mps.iter()) { @@ -1071,8 +1071,8 @@ impl RustCycle { // time-to-stop (s) let tts_s = -v0 / brake_accel_m_per_s2; // number of steps to take - let n: usize = (tts_s / dt).round() as usize; - let n: usize = if n < 2 { 2 } else { n }; // need at least 2 steps + let n = (tts_s / dt).round() as usize; + let n = if n < 2 { 2 } else { n }; // need at least 2 steps let (jerk_m_per_s3, accel_m_per_s2) = calc_constant_jerk_trajectory(n, 0.0, v0, dts_m, 0.0, dt)?; Ok(( @@ -1154,16 +1154,16 @@ pub fn detect_passing( } let zero_speed_tol_m_per_s = 1e-6; let dist_tol_m = dist_tol_m.unwrap_or(0.1); - let mut v0: f64 = cyc.mps[i - 1]; - let d0: f64 = trapz_step_start_distance(cyc, i); - let mut v0_lv: f64 = cyc0.mps[i - 1]; - let d0_lv: f64 = trapz_step_start_distance(cyc0, i); + let mut v0 = cyc.mps[i - 1]; + let d0 = trapz_step_start_distance(cyc, i); + let mut v0_lv = cyc0.mps[i - 1]; + let d0_lv = trapz_step_start_distance(cyc0, i); let mut d = d0; let mut d_lv = d0_lv; - let mut rendezvous_idx: Option = None; - let mut rendezvous_num_steps: usize = 0; - let mut rendezvous_distance_m: f64 = 0.0; - let mut rendezvous_speed_m_per_s: f64 = 0.0; + let mut rendezvous_idx = None; + let mut rendezvous_num_steps = 0; + let mut rendezvous_distance_m = 0.0; + let mut rendezvous_speed_m_per_s = 0.0; for di in 0..(cyc.mps.len() - i) { let idx = i + di; let v = cyc.mps[idx]; @@ -1237,7 +1237,7 @@ mod tests { #[test] fn test_loading_a_cycle_from_the_filesystem() { let cyc_file_path = resources_path().join("cycles/udds.csv"); - let expected_udds_length: usize = 1370; + let expected_udds_length = 1370; let cyc = RustCycle::from_csv_file(cyc_file_path).unwrap(); let num_entries = cyc.len(); assert_eq!(cyc.name, String::from("udds")); diff --git a/rust/fastsim-core/src/imports.rs b/rust/fastsim-core/src/imports.rs index f054cb15..6216dd4c 100644 --- a/rust/fastsim-core/src/imports.rs +++ b/rust/fastsim-core/src/imports.rs @@ -13,4 +13,3 @@ pub(crate) use std::path::PathBuf; pub(crate) use crate::traits::*; pub(crate) use crate::utils::*; -pub(crate) use crate::vehicle_utils::*; diff --git a/rust/fastsim-core/src/params.rs b/rust/fastsim-core/src/params.rs index 20a3877c..db40d339 100644 --- a/rust/fastsim-core/src/params.rs +++ b/rust/fastsim-core/src/params.rs @@ -58,12 +58,12 @@ impl SerdeAPI for RustPhysicalProperties {} impl Default for RustPhysicalProperties { fn default() -> Self { - let air_density_kg_per_m3: f64 = 1.2; - let a_grav_mps2: f64 = 9.81; - let kwh_per_gge: f64 = 33.7; + let air_density_kg_per_m3 = 1.2; + let a_grav_mps2 = 9.81; + let kwh_per_gge = 33.7; #[allow(non_snake_case)] - let fuel_rho_kg__L: f64 = 0.75; - let fuel_afr_stoich: f64 = 14.7; + let fuel_rho_kg__L = 0.75; + let fuel_afr_stoich = 14.7; Self { air_density_kg_per_m3, a_grav_mps2, @@ -161,7 +161,7 @@ impl SerdeAPI for AdjCoef {} impl Default for RustLongParams { fn default() -> Self { - let long_params_str: &str = include_str!("../resources/longparams.json"); + let long_params_str = include_str!("../resources/longparams.json"); let long_params = Self::from_json(long_params_str).unwrap(); long_params } @@ -173,22 +173,22 @@ mod params_test { #[test] fn test_get_long_params() { - let long_params: RustLongParams = RustLongParams::default(); + let long_params = RustLongParams::default(); - let adj_coef_2008: AdjCoef = AdjCoef { + let adj_coef_2008 = AdjCoef { city_intercept: 0.003259, city_slope: 1.1805, hwy_intercept: 0.001376, hwy_slope: 1.3466, }; - let adj_coef_2017: AdjCoef = AdjCoef { + let adj_coef_2017 = AdjCoef { city_intercept: 0.004091, city_slope: 1.1601, hwy_intercept: 0.003191, hwy_slope: 1.2945, }; - let mut adj_coef_map: HashMap = HashMap::new(); + let mut adj_coef_map = HashMap::new(); adj_coef_map.insert(String::from("2008"), adj_coef_2008); adj_coef_map.insert(String::from("2017"), adj_coef_2017); diff --git a/rust/fastsim-core/src/simdrive.rs b/rust/fastsim-core/src/simdrive.rs index 3f79035a..ef7f11a7 100644 --- a/rust/fastsim-core/src/simdrive.rs +++ b/rust/fastsim-core/src/simdrive.rs @@ -67,19 +67,19 @@ impl Default for RustSimDriveParams { // if true, missed trace correction is active, default = false let missed_trace_correction = false; // maximum time dilation factor to "catch up" with trace -- e.g. 1.0 means 100% increase in step size - let max_time_dilation: f64 = 1.0; + let max_time_dilation = 1.0; // minimum time dilation margin to let trace "catch up" -- e.g. -0.5 means 50% reduction in step size - let min_time_dilation: f64 = -0.5; - let time_dilation_tol: f64 = 5e-4; // convergence criteria for time dilation - let max_trace_miss_iters: u32 = 5; // number of iterations to achieve time dilation correction - let trace_miss_speed_mps_tol: f64 = 1.0; // # threshold of error in speed [m/s] that triggers warning - let trace_miss_time_tol: f64 = 1e-3; // threshold for printing warning when time dilation is active - let trace_miss_dist_tol: f64 = 1e-3; // threshold of fractional eror in distance that triggers warning - let sim_count_max: usize = 30; // max allowable number of HEV SOC iterations - let newton_gain: f64 = 0.9; // newton solver gain - let newton_max_iter: u32 = 100; // newton solver max iterations - let newton_xtol: f64 = 1e-9; // newton solver tolerance - let energy_audit_error_tol: f64 = 0.002; // tolerance for energy audit error warning, i.e. 0.1% + let min_time_dilation = -0.5; + let time_dilation_tol = 5e-4; // convergence criteria for time dilation + let max_trace_miss_iters = 5; // number of iterations to achieve time dilation correction + let trace_miss_speed_mps_tol = 1.0; // # threshold of error in speed [m/s] that triggers warning + let trace_miss_time_tol = 1e-3; // threshold for printing warning when time dilation is active + let trace_miss_dist_tol = 1e-3; // threshold of fractional eror in distance that triggers warning + let sim_count_max = 30; // max allowable number of HEV SOC iterations + let newton_gain = 0.9; // newton solver gain + let newton_max_iter = 100; // newton solver max iterations + let newton_xtol = 1e-9; // newton solver tolerance + let energy_audit_error_tol = 0.002; // tolerance for energy audit error warning, i.e. 0.1% // Coasting let coast_allow = false; let coast_allow_passing = false; @@ -99,7 +99,7 @@ impl Default for RustSimDriveParams { let idm_decel_m_per_s2 = 1.5; let idm_v_desired_in_m_per_s_by_distance_m = None; // EPA fuel economy adjustment parameters - let max_epa_adj: f64 = 0.3; // maximum EPA adjustment factor + let max_epa_adj = 0.3; // maximum EPA adjustment factor Self { favor_grade_accuracy, missed_trace_correction, @@ -207,9 +207,9 @@ impl Default for RustSimDriveParams { blend_factor: Option, min_target_speed_m_per_s: Option, ) -> anyhow::Result<()> { - let by_microtrip: bool = by_microtrip.unwrap_or(false); - let extend_fraction: f64 = extend_fraction.unwrap_or(0.1); - let blend_factor: f64 = blend_factor.unwrap_or(0.0); + let by_microtrip = by_microtrip.unwrap_or(false); + let extend_fraction = extend_fraction.unwrap_or(0.1); + let blend_factor = blend_factor.unwrap_or(0.0); let min_target_speed_m_per_s = min_target_speed_m_per_s.unwrap_or(8.0); self.activate_eco_cruise_rust( by_microtrip, extend_fraction, blend_factor, min_target_speed_m_per_s) @@ -571,10 +571,10 @@ impl SerdeAPI for RustSimDrive { // // SIM DRIVE // let mut sd = RustSimDrive::__new__(cyc, veh); -// let init_soc: f64 = 0.5; +// let init_soc = 0.5; // sd.walk(init_soc); -// let expected_final_i: usize = cycle_length; +// let expected_final_i = cycle_length; // assert_eq!(sd.i, expected_final_i); // } // } diff --git a/rust/fastsim-core/src/simdrive/cyc_mods.rs b/rust/fastsim-core/src/simdrive/cyc_mods.rs index 91d9d62f..bd2a06b9 100644 --- a/rust/fastsim-core/src/simdrive/cyc_mods.rs +++ b/rust/fastsim-core/src/simdrive/cyc_mods.rs @@ -5,7 +5,7 @@ use super::*; use crate::cycle::{ accel_array_for_constant_jerk, accel_for_constant_jerk, calc_constant_jerk_trajectory, create_dist_and_target_speeds_by_microtrip, detect_passing, extend_cycle, - trapz_distance_for_step, trapz_step_distances, trapz_step_start_distance, PassingInfo, + trapz_distance_for_step, trapz_step_distances, trapz_step_start_distance, }; use crate::simdrive::RustSimDrive; use crate::utils::{add_from, max, min, ndarrcumsum, ndarrunique}; @@ -119,7 +119,7 @@ impl RustSimDrive { let v0_m_per_s = self.mps_ach[i - 1]; let v0_lead_m_per_s = self.cyc0.mps[i - 1]; let dv0_m_per_s = v0_m_per_s - v0_lead_m_per_s; - let d0_lead_m: f64 = self.cyc0_cache.trapz_distances_m[(i - 1).max(0)] + s0_m; + let d0_lead_m = self.cyc0_cache.trapz_distances_m[(i - 1).max(0)] + s0_m; let d0_m = trapz_step_start_distance(&self.cyc, i); let s_m = max(d0_lead_m - d0_m, 0.01); // IDM EQUATIONS @@ -237,8 +237,8 @@ impl RustSimDrive { < self.sim_params.time_dilation_tol || self.cyc.mps[i] == 0.0; - let mut d_short: Vec = vec![]; - let mut t_dilation: Vec = vec![0.0]; // no time dilation initially + let mut d_short = vec![]; + let mut t_dilation = vec![0.0]; // no time dilation initially if !trace_met { self.trace_miss_iters[i] += 1; @@ -375,8 +375,8 @@ impl RustSimDrive { assert![a_brake <= 0.0]; let ds = &self.cyc0_cache.trapz_distances_m; let d0 = trapz_step_start_distance(&self.cyc, i); - let mut distances_m: Vec = Vec::with_capacity(ds.len()); - let mut grade_by_distance: Vec = Vec::with_capacity(ds.len()); + let mut distances_m = Vec::with_capacity(ds.len()); + let mut grade_by_distance = Vec::with_capacity(ds.len()); for idx in 0..ds.len() { if ds[idx] >= d0 { distances_m.push(ds[idx] - d0); @@ -408,19 +408,19 @@ impl RustSimDrive { let mut d = 0.0; let d_max = distances_m.last().unwrap() - dtb; let unique_grades = ndarrunique(&grade_by_distance); - let unique_grade: Option = if unique_grades.len() == 1 { + let unique_grade = if unique_grades.len() == 1 { Some(unique_grades[0]) } else { None }; - let has_unique_grade: bool = unique_grade.is_some(); + let has_unique_grade = unique_grade.is_some(); let max_iter = 180; let iters_per_step = if self.sim_params.favor_grade_accuracy { 2 } else { 1 }; - let mut new_speeds_m_per_s: Vec = Vec::with_capacity(max_iter as usize); + let mut new_speeds_m_per_s = Vec::with_capacity(max_iter as usize); let mut v = v0; let mut iter = 0; let mut idx = i; @@ -521,7 +521,7 @@ impl RustSimDrive { gs.len() ); let d0 = trapz_step_start_distance(&self.cyc, i); - let mut grade_by_distance: Vec = Vec::with_capacity(ds.len()); + let mut grade_by_distance = Vec::with_capacity(ds.len()); for idx in 0..ds.len() { if ds[idx] >= d0 { grade_by_distance.push(gs[idx]); @@ -624,10 +624,10 @@ impl RustSimDrive { let brake_accel_m_per_s2 = self.sim_params.coast_brake_accel_m_per_s2; let time_horizon_s = max(self.sim_params.coast_time_horizon_for_adjustment_s, 1.0); // distance_horizon_m = 1000.0 - let not_found_n: usize = 0; - let not_found_jerk_m_per_s3: f64 = 0.0; - let not_found_accel_m_per_s2: f64 = 0.0; - let not_found: (bool, usize, f64, f64) = ( + let not_found_n = 0; + let not_found_jerk_m_per_s3 = 0.0; + let not_found_accel_m_per_s2 = 0.0; + let not_found = ( false, not_found_n, not_found_jerk_m_per_s3, @@ -707,9 +707,9 @@ impl RustSimDrive { r_bi_jerk_m_per_s3, dt, ); - let as_bi_min: f64 = + let as_bi_min = as_bi.to_vec().into_iter().reduce(f64::min).unwrap_or(0.0); - let as_bi_max: f64 = + let as_bi_max = as_bi.to_vec().into_iter().reduce(f64::max).unwrap_or(0.0); let accel_spread = (as_bi_max - as_bi_min).abs(); let flag = (as_bi_max < (max_accel_m_per_s2 + 1e-6) @@ -756,14 +756,14 @@ impl RustSimDrive { for idx in i..self.cyc.len() { self.coast_delay_index[idx] = 0; // clear all future coast-delays } - let mut coast_delay: Option = None; + let mut coast_delay = None; if !self.sim_params.idm_allow && self.cyc.mps[i] < speed_tol { let d0 = trapz_step_start_distance(&self.cyc, i); let d0_lv = self.cyc0_cache.trapz_distances_m[i - 1]; let dtlv0 = d0_lv - d0; if dtlv0.abs() > dist_tol { let mut d_lv = 0.0; - let mut min_dtlv: Option = None; + let mut min_dtlv = None; for (idx, (&dd, &v)) in trapz_step_distances(&self.cyc0) .iter() .zip(self.cyc0.mps.iter()) @@ -814,11 +814,11 @@ impl RustSimDrive { /// RETURN: Bool, True if cyc was modified fn prevent_collisions(&mut self, i: usize, passing_tol_m: Option) -> anyhow::Result { let passing_tol_m = passing_tol_m.unwrap_or(1.0); - let collision: PassingInfo = detect_passing(&self.cyc, &self.cyc0, i, Some(passing_tol_m)); + let collision = detect_passing(&self.cyc, &self.cyc0, i, Some(passing_tol_m)); if !collision.has_collision { return Ok(false); } - let mut best: RendezvousTrajectory = RendezvousTrajectory { + let mut best = RendezvousTrajectory { found_trajectory: false, idx: 0, n: 0, @@ -869,8 +869,8 @@ impl RustSimDrive { collision.speed_m_per_s, dt, )?; - let mut accels_m_per_s2: Vec = vec![]; - let mut trace_accels_m_per_s2: Vec = vec![]; + let mut accels_m_per_s2 = vec![]; + let mut trace_accels_m_per_s2 = vec![]; for ni in 0..n { if (ni + idx + full_brake_steps) >= self.cyc.len() { break; @@ -887,7 +887,7 @@ impl RustSimDrive { / self.cyc.dt_s()[ni + idx + full_brake_steps], ); } - let all_sub_coast: bool = trace_accels_m_per_s2 + let all_sub_coast = trace_accels_m_per_s2 .iter() .copied() .zip(accels_m_per_s2.iter().copied()) diff --git a/rust/fastsim-core/src/simdrive/simdrive_impl.rs b/rust/fastsim-core/src/simdrive/simdrive_impl.rs index d604966a..38186339 100644 --- a/rust/fastsim-core/src/simdrive/simdrive_impl.rs +++ b/rust/fastsim-core/src/simdrive/simdrive_impl.rs @@ -27,11 +27,11 @@ pub struct CoastTrajectory { impl RustSimDrive { pub fn new(cyc: RustCycle, veh: RustVehicle) -> Self { - let hev_sim_count: usize = 0; + let hev_sim_count = 0; 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() + let i = 1; // 1 # initialize step counter for possible use outside sim_drive_walk() let cyc_len = cyc.len(); let cur_max_fs_kw_out = Array::zeros(cyc_len); let fc_trans_lim_kw = Array::zeros(cyc_len); diff --git a/rust/fastsim-core/src/thermal.rs b/rust/fastsim-core/src/thermal.rs index 10d87749..59943523 100644 --- a/rust/fastsim-core/src/thermal.rs +++ b/rust/fastsim-core/src/thermal.rs @@ -481,13 +481,13 @@ impl SimDriveHot { if let CabinHvacModelTypes::Internal(hvac_model) = &mut self.vehthrm.cabin_hvac_model { // flat plate model for isothermal, mixed-flow from Incropera and deWitt, Fundamentals of Heat and Mass // Transfer, 7th Edition - let cab_te_film_ext_deg_c: f64 = + let cab_te_film_ext_deg_c = 0.5 * (self.state.cab_te_deg_c + self.state.amb_te_deg_c); - let re_l: f64 = self.air.get_rho(cab_te_film_ext_deg_c, None) + let re_l = self.air.get_rho(cab_te_film_ext_deg_c, None) * self.sd.mps_ach[i - 1] * self.vehthrm.cab_l_length / self.air.get_mu(cab_te_film_ext_deg_c); - let re_l_crit: f64 = 5.0e5; // critical Re for transition to turbulence + let re_l_crit = 5.0e5; // critical Re for transition to turbulence let nu_l_bar = if re_l < re_l_crit { // equation 7.30 @@ -720,7 +720,7 @@ impl SimDriveHot { // Constitutive equations for catalyst // catalyst film temperature for property calculation - let cat_te_ext_film_deg_c: f64 = 0.5 * (self.state.cat_te_deg_c + self.state.amb_te_deg_c); + let cat_te_ext_film_deg_c = 0.5 * (self.state.cat_te_deg_c + self.state.amb_te_deg_c); // density * speed * diameter / dynamic viscosity self.state.cat_re_ext = self.air.get_rho(cat_te_ext_film_deg_c, None) * self.sd.mps_ach[i - 1] @@ -1105,7 +1105,7 @@ impl ThermalState { cat_te_deg_c_init: Option, ) -> Self { // Note default temperature is defined twice, see default() - let default_te_deg_c: f64 = 22.0; + let default_te_deg_c = 22.0; let amb_te_deg_c = amb_te_deg_c.unwrap_or(default_te_deg_c); Self { amb_te_deg_c, @@ -1123,7 +1123,7 @@ impl ThermalState { impl Default for ThermalState { fn default() -> Self { // Note default temperature is defined twice, see new() - let default_te_deg_c: f64 = 22.0; + let default_te_deg_c = 22.0; Self { fc_te_deg_c: default_te_deg_c, // overridden by new() diff --git a/rust/fastsim-core/src/utils.rs b/rust/fastsim-core/src/utils.rs index c24710ac..7974bfef 100644 --- a/rust/fastsim-core/src/utils.rs +++ b/rust/fastsim-core/src/utils.rs @@ -106,8 +106,8 @@ pub fn ndarrcumsum(arr: &Array1) -> Array1 { /// return the unique values of the array pub fn ndarrunique(arr: &Array1) -> Array1 { - let mut set: HashSet = HashSet::new(); - let mut new_arr: Vec = Vec::new(); + let mut set = HashSet::new(); + let mut new_arr = Vec::new(); let x_min = arr.min().unwrap(); let x_max = arr.max().unwrap(); let dx = if x_max == x_min { 1.0 } else { x_max - x_min }; @@ -131,8 +131,8 @@ pub fn interpolate( extrapolate: bool, ) -> f64 { assert!(x_data_in.len() == y_data_in.len()); - let mut new_x_data: Vec = Vec::new(); - let mut new_y_data: Vec = Vec::new(); + let mut new_x_data = Vec::new(); + let mut new_y_data = Vec::new(); let mut last_x = x_data_in[0]; for idx in 0..x_data_in.len() { if idx == 0 || (idx > 0 && x_data_in[idx] > last_x) { @@ -179,8 +179,8 @@ pub fn interpolate_vectors( extrapolate: bool, ) -> f64 { assert!(x_data_in.len() == y_data_in.len()); - let mut new_x_data: Vec = Vec::new(); - let mut new_y_data: Vec = Vec::new(); + let mut new_x_data = Vec::new(); + let mut new_y_data = Vec::new(); let mut last_x = x_data_in[0]; for idx in 0..x_data_in.len() { if idx == 0 || (idx > 0 && x_data_in[idx] > last_x) { @@ -670,33 +670,33 @@ mod tests { #[test] fn test_that_first_eq_finds_the_right_index_when_one_exists() { - let xs: [f64; 5] = [0.0, 1.2, 3.3, 4.4, 6.6]; + let xs = [0.0, 1.2, 3.3, 4.4, 6.6]; let idx = first_eq(&xs, 3.3).unwrap(); - let expected_idx: usize = 2; + let expected_idx = 2; assert_eq!(idx, expected_idx) } #[test] fn test_that_first_eq_yields_last_index_when_nothing_found() { - let xs: [f64; 5] = [0.0, 1.2, 3.3, 4.4, 6.6]; + let xs = [0.0, 1.2, 3.3, 4.4, 6.6]; let idx = first_eq(&xs, 7.0).unwrap(); - let expected_idx: usize = xs.len() - 1; + let expected_idx = xs.len() - 1; assert_eq!(idx, expected_idx) } #[test] fn test_that_first_grtr_finds_the_right_index_when_one_exists() { - let xs: [f64; 5] = [0.0, 1.2, 3.3, 4.4, 6.6]; + let xs = [0.0, 1.2, 3.3, 4.4, 6.6]; let idx = first_grtr(&xs, 3.0).unwrap(); - let expected_idx: usize = 2; + let expected_idx = 2; assert_eq!(idx, expected_idx) } #[test] fn test_that_first_grtr_yields_last_index_when_nothing_found() { - let xs: [f64; 5] = [0.0, 1.2, 3.3, 4.4, 6.6]; + let xs = [0.0, 1.2, 3.3, 4.4, 6.6]; let idx = first_grtr(&xs, 7.0).unwrap(); - let expected_idx: usize = xs.len() - 1; + let expected_idx = xs.len() - 1; assert_eq!(idx, expected_idx) } @@ -735,7 +735,7 @@ mod tests { } // #[test] // fn test_that_argmax_does_the_right_thing_on_an_empty_array(){ - // let xs: Array1 = Array::from_vec(vec![]); + // let xs = Array::from_vec(vec![]); // let idx = first_grtr(&xs); // // unclear what should happen here; np.argmax throws a ValueError in the case of an empty vector // // ... possibly we should return an Option type? diff --git a/rust/fastsim-core/src/vehicle.rs b/rust/fastsim-core/src/vehicle.rs index f51e3546..780d6ab6 100644 --- a/rust/fastsim-core/src/vehicle.rs +++ b/rust/fastsim-core/src/vehicle.rs @@ -1160,89 +1160,89 @@ mod tests { fn test_input_validation() { // set up vehicle input parameters let scenario_name = String::from("2016 FORD Escape 4cyl 2WD"); - let selection: u32 = 5; - let veh_year: u32 = 2016; + let selection = 5; + let veh_year = 2016; let veh_pt_type = String::from("whoops"); // bad input - let drag_coef: f64 = 0.355; - let frontal_area_m2: f64 = 3.066; - let glider_kg: f64 = -50.0; // bad input - let veh_cg_m: f64 = 0.53; - let drive_axle_weight_frac: f64 = 0.59; - let wheel_base_m: f64 = 2.6; - let cargo_kg: f64 = 136.0; - let veh_override_kg: Option = None; - let comp_mass_multiplier: f64 = 1.4; - let fs_max_kw: f64 = 2000.0; - let fs_secs_to_peak_pwr: f64 = 1.0; - let fs_kwh: f64 = 504.0; - let fs_kwh_per_kg: f64 = 9.89; - let fc_max_kw: f64 = -60.0; // bad input - let fc_pwr_out_perc: Vec = vec![ + let drag_coef = 0.355; + let frontal_area_m2 = 3.066; + let glider_kg = -50.0; // bad input + let veh_cg_m = 0.53; + let drive_axle_weight_frac = 0.59; + let wheel_base_m = 2.6; + let cargo_kg = 136.0; + let veh_override_kg = None; + let comp_mass_multiplier = 1.4; + let fs_max_kw = 2000.0; + let fs_secs_to_peak_pwr = 1.0; + let fs_kwh = 504.0; + let fs_kwh_per_kg = 9.89; + let fc_max_kw = -60.0; // bad input + let fc_pwr_out_perc = vec![ 0.0, 0.005, 0.015, 0.04, 0.06, 0.1, 0.14, 0.2, 0.4, 0.6, 0.8, 1.0, ]; - let fc_eff_type: String = String::from("SI"); - let fc_sec_to_peak_pwr: f64 = 6.0; - let fc_base_kg: f64 = 61.0; - let fc_kw_per_kg: f64 = 2.13; - let min_fc_time_on: f64 = 30.0; - let idle_fc_kw: f64 = 2.5; - let mc_max_kw: f64 = 0.0; - let mc_sec_to_peak_pwr: f64 = 4.0; - let mc_pe_kg_per_kw: f64 = 0.833; - let mc_pe_base_kg: f64 = 21.6; - let ess_max_kw: f64 = 0.0; - let ess_max_kwh: f64 = 0.0; - let ess_kg_per_kwh: f64 = 8.0; - let ess_base_kg: f64 = 75.0; - let ess_round_trip_eff: f64 = 0.97; - let ess_life_coef_a: f64 = 110.0; - let ess_life_coef_b: f64 = -0.6811; - let min_soc: f64 = -0.5; // bad input - let max_soc: f64 = 1.5; // bad input - let ess_dischg_to_fc_max_eff_perc: f64 = 0.0; - let ess_chg_to_fc_max_eff_perc: f64 = 0.0; - let wheel_inertia_kg_m2: f64 = 0.815; - let num_wheels: f64 = 4.0; - let wheel_rr_coef: f64 = 0.006; - let wheel_radius_m: f64 = 0.336; - let wheel_coef_of_fric: f64 = 0.7; - let max_accel_buffer_mph: f64 = 60.0; - let max_accel_buffer_perc_of_useable_soc: f64 = 0.2; - let perc_high_acc_buf: f64 = 0.0; - let mph_fc_on: f64 = 30.0; - let kw_demand_fc_on: f64 = 100.0; - let max_regen: f64 = 0.98; - let stop_start: bool = false; - let force_aux_on_fc: bool = true; - let alt_eff: f64 = 1.0; - let chg_eff: f64 = 0.86; - let aux_kw: f64 = 0.7; - let trans_kg: f64 = 114.0; - let trans_eff: f64 = 0.92; - let ess_to_fuel_ok_error: f64 = 0.005; - let val_udds_mpgge: f64 = 23.0; - let val_hwy_mpgge: f64 = 32.0; - let val_comb_mpgge: f64 = 26.0; - let val_udds_kwh_per_mile: f64 = f64::NAN; - let val_hwy_kwh_per_mile: f64 = f64::NAN; - let val_comb_kwh_per_mile: f64 = f64::NAN; - let val_cd_range_mi: f64 = f64::NAN; - let val_const65_mph_kwh_per_mile: f64 = f64::NAN; - let val_const60_mph_kwh_per_mile: f64 = f64::NAN; - let val_const55_mph_kwh_per_mile: f64 = f64::NAN; - let val_const45_mph_kwh_per_mile: f64 = f64::NAN; - let val_unadj_udds_kwh_per_mile: f64 = f64::NAN; - let val_unadj_hwy_kwh_per_mile: f64 = f64::NAN; - let val0_to60_mph: f64 = 9.9; - let val_ess_life_miles: f64 = f64::NAN; - let val_range_miles: f64 = f64::NAN; - let val_veh_base_cost: f64 = f64::NAN; - let val_msrp: f64 = f64::NAN; + let fc_eff_type = String::from("SI"); + let fc_sec_to_peak_pwr = 6.0; + let fc_base_kg = 61.0; + let fc_kw_per_kg = 2.13; + let min_fc_time_on = 30.0; + let idle_fc_kw = 2.5; + let mc_max_kw = 0.0; + let mc_sec_to_peak_pwr = 4.0; + let mc_pe_kg_per_kw = 0.833; + let mc_pe_base_kg = 21.6; + let ess_max_kw = 0.0; + let ess_max_kwh = 0.0; + let ess_kg_per_kwh = 8.0; + let ess_base_kg = 75.0; + let ess_round_trip_eff = 0.97; + let ess_life_coef_a = 110.0; + let ess_life_coef_b = -0.6811; + let min_soc = -0.5; // bad input + let max_soc = 1.5; // bad input + let ess_dischg_to_fc_max_eff_perc = 0.0; + let ess_chg_to_fc_max_eff_perc = 0.0; + let wheel_inertia_kg_m2 = 0.815; + let num_wheels = 4.0; + let wheel_rr_coef = 0.006; + let wheel_radius_m = 0.336; + let wheel_coef_of_fric = 0.7; + let max_accel_buffer_mph = 60.0; + let max_accel_buffer_perc_of_useable_soc = 0.2; + let perc_high_acc_buf = 0.0; + let mph_fc_on = 30.0; + let kw_demand_fc_on = 100.0; + let max_regen = 0.98; + let stop_start = false; + let force_aux_on_fc = true; + let alt_eff = 1.0; + let chg_eff = 0.86; + let aux_kw = 0.7; + let trans_kg = 114.0; + let trans_eff = 0.92; + let ess_to_fuel_ok_error = 0.005; + let val_udds_mpgge = 23.0; + let val_hwy_mpgge = 32.0; + let val_comb_mpgge = 26.0; + let val_udds_kwh_per_mile = f64::NAN; + let val_hwy_kwh_per_mile = f64::NAN; + let val_comb_kwh_per_mile = f64::NAN; + let val_cd_range_mi = f64::NAN; + let val_const65_mph_kwh_per_mile = f64::NAN; + let val_const60_mph_kwh_per_mile = f64::NAN; + let val_const55_mph_kwh_per_mile = f64::NAN; + let val_const45_mph_kwh_per_mile = f64::NAN; + let val_unadj_udds_kwh_per_mile = f64::NAN; + let val_unadj_hwy_kwh_per_mile = f64::NAN; + let val0_to60_mph = 9.9; + let val_ess_life_miles = f64::NAN; + let val_range_miles = f64::NAN; + let val_veh_base_cost = f64::NAN; + let val_msrp = f64::NAN; let props = RustPhysicalProperties::default(); - let regen_a: f64 = 500.0; - let regen_b: f64 = 0.99; - let fc_peak_eff_override: Option = None; - let mc_peak_eff_override: Option = Some(-0.50); // bad input + let regen_a = 500.0; + let regen_b = 0.99; + let fc_peak_eff_override = None; + let mc_peak_eff_override = Some(-0.50); // bad input let small_motor_power_kw = 7.5; let large_motor_power_kw = 75.0; let fc_perc_out_array = FC_PERC_OUT_ARRAY.clone().to_vec(); diff --git a/rust/fastsim-core/src/vehicle_utils.rs b/rust/fastsim-core/src/vehicle_utils.rs index de53eeec..ea6692ac 100644 --- a/rust/fastsim-core/src/vehicle_utils.rs +++ b/rust/fastsim-core/src/vehicle_utils.rs @@ -1,7 +1,7 @@ //! Module for utility functions that support the vehicle struct. #[cfg(feature = "default")] -use argmin::core::{CostFunction, Executor, OptimizationResult, State}; +use argmin::core::{CostFunction, Executor, State}; #[cfg(feature = "default")] use argmin::solver::neldermead::NelderMead; use ndarray::{array, Array1}; @@ -48,25 +48,25 @@ pub fn abc_to_drag_coeffs( // otherwise, directly use target A, B, C to calculate the results // show_plots: if True, plots are shown - let air_props: AirProperties = AirProperties::default(); + let air_props = AirProperties::default(); let props = RustPhysicalProperties::default(); - let cur_ambient_air_density_kg__m3: f64 = if custom_rho.unwrap_or(false) { + let cur_ambient_air_density_kg__m3 = if custom_rho.unwrap_or(false) { air_props.get_rho(custom_rho_temp_degC.unwrap_or(20.0), custom_rho_elevation_m) } else { props.air_density_kg_per_m3 }; - let vmax_mph: f64 = 70.0; - let a_newton: f64 = a_lbf * super::params::N_PER_LBF; - let _b_newton__mps: f64 = b_lbf__mph * super::params::N_PER_LBF * super::params::MPH_PER_MPS; - let c_newton__mps2: f64 = c_lbf__mph2 + let vmax_mph = 70.0; + let a_newton = a_lbf * super::params::N_PER_LBF; + let _b_newton__mps = b_lbf__mph * super::params::N_PER_LBF * super::params::MPH_PER_MPS; + let c_newton__mps2 = c_lbf__mph2 * super::params::N_PER_LBF * super::params::MPH_PER_MPS * super::params::MPH_PER_MPS; - let cd_len: usize = 300; + let cd_len = 300; - let cyc: RustCycle = RustCycle { + let cyc = RustCycle { time_s: (0..cd_len as i32).map(f64::from).collect(), mps: Array::linspace(vmax_mph / super::params::MPH_PER_MPS, 0.0, cd_len), grade: Array::zeros(cd_len), @@ -87,13 +87,13 @@ pub fn abc_to_drag_coeffs( vehicle: veh, dyno_func_lb: &dyno_func_lb, }; - let solver: NelderMead, f64> = + let solver = NelderMead::new(vec![array![0.0, 0.0], array![0.5, 0.0], array![0.5, 0.1]]); - let res: OptimizationResult<_, _, _> = Executor::new(cost, solver) + let res = Executor::new(cost, solver) .configure(|state| state.max_iters(100)) .run() .unwrap(); - let best_param: &Array1 = res.state().get_best_param().unwrap(); + let best_param = res.state().get_best_param().unwrap(); drag_coef = best_param[0]; wheel_rr_coef = best_param[1]; } else { @@ -129,8 +129,8 @@ pub fn get_error_val(model: Array1, test: Array1, time_steps: Array1 = (model - test).mapv(f64::abs); + let mut err = 0.0; + let y = (model - test).mapv(f64::abs); for index in 0..time_steps.len() - 1 { err += 0.5 * (time_steps[index + 1] - time_steps[index]) * (y[index] + y[index + 1]); @@ -158,22 +158,22 @@ where type Output = f64; fn cost(&self, x: &Self::Param) -> anyhow::Result { - let mut veh: RustVehicle = self.vehicle.clone(); - let cyc: RustCycle = self.cycle.clone(); + let mut veh = self.vehicle.clone(); + let cyc = self.cycle.clone(); veh.drag_coef = x[0]; veh.wheel_rr_coef = x[1]; - let mut sd_coast: RustSimDrive = RustSimDrive::new(self.cycle.clone(), veh); + let mut sd_coast = RustSimDrive::new(self.cycle.clone(), veh); sd_coast.impose_coast = Array::from_vec(vec![true; sd_coast.impose_coast.len()]); - let _sim_drive_result: Result<_, _> = sd_coast.sim_drive(None, None); + let _sim_drive_result = sd_coast.sim_drive(None, None); let cutoff_vec: Vec = sd_coast .mps_ach .indexed_iter() .filter_map(|(index, &item)| (item < 0.1).then_some(index)) .collect(); - let cutoff: usize = if cutoff_vec.is_empty() { + let cutoff = if cutoff_vec.is_empty() { sd_coast.mps_ach.len() } else { cutoff_vec[0] @@ -275,7 +275,7 @@ pub fn fetch_github_list(repo_url: Option) -> anyhow::Result let response = get_response(repo_url)?.into_reader(); let github_list: Vec = serde_json::from_reader(response).with_context(|| "Cannot parse github vehicle list.")?; - let mut vehicle_name_list: Vec = Vec::new(); + let mut vehicle_name_list = Vec::new(); for object in github_list.iter() { if object.url_type == "dir" { let url = &object.url; @@ -310,11 +310,11 @@ mod tests { #[test] fn test_get_error_val() { - let time_steps: Array1 = array![0.0, 1.0, 2.0, 3.0, 4.0]; - let model: Array1 = array![1.1, 4.6, 2.5, 3.7, 5.0]; - let test: Array1 = array![2.1, 4.5, 3.4, 4.8, 6.3]; + let time_steps = array![0.0, 1.0, 2.0, 3.0, 4.0]; + let model = array![1.1, 4.6, 2.5, 3.7, 5.0]; + let test = array![2.1, 4.5, 3.4, 4.8, 6.3]; - let error_val: f64 = get_error_val(model, test, time_steps); + let error_val = get_error_val(model, test, time_steps); println!("Error Value: {}", error_val); assert!(error_val.approx_eq(&0.8124999999999998, 1e-10)); @@ -323,12 +323,12 @@ mod tests { #[cfg(feature = "default")] #[test] fn test_abc_to_drag_coeffs() { - let mut veh: RustVehicle = RustVehicle::mock_vehicle(); - let a: f64 = 25.91; - let b: f64 = 0.1943; - let c: f64 = 0.01796; + let mut veh = RustVehicle::mock_vehicle(); + let a = 25.91; + let b = 0.1943; + let c = 0.01796; - let (drag_coef, wheel_rr_coef): (f64, f64) = abc_to_drag_coeffs( + let (drag_coef, wheel_rr_coef) = abc_to_drag_coeffs( &mut veh, a, b,