Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added a single vehicle to the from_resources #156

Merged
merged 3 commits into from
Sep 20, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions python/fastsim/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ def package_root() -> Path:
"""Returns the package root directory."""
return Path(__file__).parent

def resources_root() -> Path:
"""Returns the resources root directory."""
return Path(__file__).parent / "resources"


DEFAULT_LOGGING_CONFIG = dict(
format = "%(asctime)s.%(msecs)03d | %(filename)s:%(lineno)s | %(levelname)s: %(message)s",
Expand Down
6 changes: 3 additions & 3 deletions rust/fastsim-cli/src/bin/fastsim-cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,8 @@ pub fn calculate_mpgge_for_h2_diesel_ice(
dist_mi: f64,
max_fc_power_kw: f64,
kwh_per_gge: f64,
fc_kw_out_ach: &Vec<f64>,
fs_kwh_out_ach: &Vec<f64>,
fc_kw_out_ach: &[f64],
fs_kwh_out_ach: &[f64],
fc_pwr_out_perc: &Vec<f64>,
h2share: &Vec<f64>,
) -> anyhow::Result<H2AndDieselResults> {
Expand Down Expand Up @@ -168,7 +168,7 @@ pub fn calculate_mpgge_for_h2_diesel_ice(
})
}

pub fn integrate_power_to_kwh(dts_s: &Vec<f64>, ps_kw: &Vec<f64>) -> anyhow::Result<Vec<f64>> {
pub fn integrate_power_to_kwh(dts_s: &[f64], ps_kw: &[f64]) -> anyhow::Result<Vec<f64>> {
anyhow::ensure!(dts_s.len() == ps_kw.len());
let mut energy_kwh = Vec::<f64>::with_capacity(dts_s.len());
for idx in 0..dts_s.len() {
Expand Down
20 changes: 20 additions & 0 deletions rust/fastsim-core/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,26 @@ fn main() {
return;
}

check_files_consistent(&prepath);

// make sure at least one vehicle is available in the `from_resources`
let veh_path_in_python = PathBuf::from(format!(
// "{}/{}/vehdb/2017_Toyota_Highlander_3.5_L.yaml",
"{}/{}/vehdb/2017_Toyota_Highlander_3.5_L.yaml",
env::current_dir().unwrap().as_os_str().to_str().unwrap(),
prepath
));
assert!(veh_path_in_python.exists());
let veh_path_in_rust = PathBuf::from(format!(
"{}/resources/vehicles/2017_Toyota_Highlander_3.5_L.yaml",
env::current_dir().unwrap().as_os_str().to_str().unwrap()
));
println!("{:?}", &veh_path_in_rust);
std::fs::copy(veh_path_in_python, veh_path_in_rust).unwrap();
}

/// Checks if rust and python resource files are consistent
fn check_files_consistent(prepath: &String) {
let truth_files = [
format!(
"{}/{}/longparams.json",
Expand Down
1 change: 0 additions & 1 deletion rust/fastsim-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ pub mod params;
pub mod pyo3imports;
pub mod simdrive;
pub use simdrive::simdrive_impl;
pub mod resources;
pub mod simdrivelabel;
pub mod thermal;
pub mod traits;
Expand Down
41 changes: 0 additions & 41 deletions rust/fastsim-core/src/resources.rs

This file was deleted.

1 change: 0 additions & 1 deletion rust/fastsim-core/src/simdrive/simdrive_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1856,7 +1856,6 @@ impl RustSimDrive {
(self.dist_m.sum() - dist_m).abs() / dist_m
} else {
bail!("Vehicle did not move forward.");
0.0
};
self.trace_miss_time_frac = (self
.cyc
Expand Down
46 changes: 42 additions & 4 deletions rust/fastsim-core/src/traits.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
use crate::{imports::*, resources};
use crate::imports::*;
use include_dir::{include_dir, Dir};
use std::collections::HashMap;
calbaker marked this conversation as resolved.
Show resolved Hide resolved
use std::path::PathBuf;
use ureq;

pub const RESOURCES_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/resources");

calbaker marked this conversation as resolved.
Show resolved Hide resolved
pub trait SerdeAPI: Serialize + for<'a> Deserialize<'a> {
const ACCEPTED_BYTE_FORMATS: &'static [&'static str] = &["yaml", "json", "toml", "bin"];
const ACCEPTED_STR_FORMATS: &'static [&'static str] = &["yaml", "json", "toml"];
Expand All @@ -14,11 +18,25 @@ pub trait SerdeAPI: Serialize + for<'a> Deserialize<'a> {
}

/// List available (compiled) resources (stored in the rust binary)
/// RESULT:
/// # RESULT
/// vector of string of resource names that can be loaded
#[cfg(feature = "resources")]
fn list_resources() -> Vec<String> {
resources::list_resources(Self::RESOURCE_PREFIX)
if Self::RESOURCE_PREFIX.is_empty() {
Vec::<String>::new()
} else if let Some(resources_path) = RESOURCES_DIR.get_dir(Self::RESOURCE_PREFIX) {
let mut file_names: Vec<String> = resources_path
.files()
.filter_map(|entry| entry.path().file_name()?.to_str().map(String::from))
.collect();
file_names.retain(|f| {
Self::ACCEPTED_STR_FORMATS.contains(&f.split(".").last().unwrap_or_default())
});
file_names.sort();
file_names
} else {
Vec::<String>::new()
}
}

/// Read (deserialize) an object from a resource file packaged with the `fastsim-core` crate
Expand All @@ -33,7 +51,7 @@ pub trait SerdeAPI: Serialize + for<'a> Deserialize<'a> {
.extension()
.and_then(OsStr::to_str)
.with_context(|| format!("File extension could not be parsed: {filepath:?}"))?;
let file = crate::resources::RESOURCES_DIR
let file = RESOURCES_DIR
.get_file(&filepath)
.with_context(|| format!("File not found in resources: {filepath:?}"))?;
Self::from_reader(file.contents(), extension, skip_init)
Expand Down Expand Up @@ -434,3 +452,23 @@ impl IterMaxMin<f64> for Array1<f64> {
})
}
}

#[cfg(test)]
mod tests {
use crate::imports::SerdeAPI;

#[test]
fn test_list_resources() {
calbaker marked this conversation as resolved.
Show resolved Hide resolved
let cyc_resource_list = crate::cycle::RustCycle::list_resources();
assert!(cyc_resource_list.len() == 3);
assert!(cyc_resource_list[0] == "HHDDTCruiseSmooth.csv");
// NOTE: at the time of writing this test, there is no
// vehicles subdirectory. The agreed-upon behavior in
// that case is that list_resources should return an
// empty vector of string.
let veh_resource_list = crate::vehicle::RustVehicle::list_resources();
println!("{:?}", veh_resource_list);
assert!(veh_resource_list.len() == 1);
assert!(veh_resource_list[0] == "2017_Toyota_Highlander_3.5_L.yaml")
}
}
Loading