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

209 pyo3 simdrivelabel #25

Merged
merged 33 commits into from
Jul 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
758a660
dropped in a TODO for Asmaa
calbaker May 31, 2023
aa0a886
add _py version
Romia87 Jun 12, 2023
a793392
Merge branch 'fastsim-2' of https://github.com/NREL/fastsim into 209-…
Romia87 Jun 12, 2023
916c0c0
refactored to separate pyo3 getter and setter functions from core fun…
calbaker Jun 13, 2023
0971c9f
renamed function to remove warning
calbaker Jun 13, 2023
aeaa810
Merge branch 'fastsim-2' of https://github.com/NREL/fastsim into 209-…
Romia87 Jun 13, 2023
905890d
Merge branch 'fastsim-2' of https://github.com/NREL/fastsim into 209-…
Romia87 Jun 20, 2023
0f92ee5
modify with add pyo3
Romia87 Jun 20, 2023
a7ff1f3
Merge branch '209-pyo3-simdrivelabel' of https://github.com/NREL/fast…
Romia87 Jun 20, 2023
bc41ca2
Merge branch 'fastsim-2' into 209-pyo3-simdrivelabel
Romia87 Jun 20, 2023
150ed85
add pyo3
Romia87 Jun 20, 2023
0609b9a
Merge branch '209-pyo3-simdrivelabel' of https://github.com/NREL/fast…
Romia87 Jun 20, 2023
519f9bc
add pyo3
Romia87 Jun 20, 2023
4aa3d9e
changes to add_pyo3_api
Romia87 Jun 21, 2023
df03345
add pyo3
Romia87 Jun 23, 2023
12f0a6a
add pyo3_api
Romia87 Jun 27, 2023
9896406
modify Cargo.toml
Romia87 Jun 27, 2023
f75d197
update add_pyo3_api
Romia87 Jun 30, 2023
feb5593
update ad_pyo3_api
Romia87 Jun 30, 2023
9184913
return to origin
Romia87 Jun 30, 2023
14a8395
add pyo3_api
Romia87 Jun 30, 2023
0a5122e
add pyo3_api
Romia87 Jun 30, 2023
87d68d9
modify add pyo3
Romia87 Jul 5, 2023
1bfe9c8
add pyo3
Romia87 Jul 6, 2023
db419fd
fixed several warnings and errors
calbaker Jul 10, 2023
d7e9fe8
update lib.rs
Romia87 Jul 12, 2023
4f86fb3
ready for handoff to Asmaa
calbaker Jul 14, 2023
da442fc
update add pyo3
Romia87 Jul 17, 2023
0c19191
removed blank line
calbaker Jul 18, 2023
320f990
autoformatting
calbaker Jul 18, 2023
2979c46
removed unneeded reference
calbaker Jul 18, 2023
bf435af
fixed numerous clippy recommendations
calbaker Jul 18, 2023
e3dfdce
fixed failing test
calbaker Jul 18, 2023
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
1 change: 1 addition & 0 deletions python/fastsim/fastsimrust.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,7 @@ class RustSimDrive:
i: int
impose_coast: Pyo3ArrayBool
ke_kj: float
long_params: RustLongParams
max_ess_accell_buff_dischg_kw: Pyo3ArrayF64
max_ess_regen_buff_chg_kw: Pyo3ArrayF64
max_trac_mps: Pyo3ArrayF64
Expand Down
4 changes: 3 additions & 1 deletion python/fastsim/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
from pathlib import Path
import copy
from copy import deepcopy
import json

import fastsim.fastsimrust as fsr

from . import inspect_utils
Expand Down Expand Up @@ -100,7 +102,7 @@ def copy_physical_properties(p: PhysicalProperties, return_type: str = None, dee
elif return_type == 'python':
return PhysicalProperties.from_dict(p_dict)
elif return_type == 'rust':
return fsr.RustPhysicalProperties(**p_dict)
return fsr.RustPhysicalProperties.from_json(json.dumps(p_dict))
else:
raise ValueError(f"Invalid return_type: '{return_type}'")

Expand Down
4 changes: 2 additions & 2 deletions rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ codegen-units = 1 # optimize connection between modules

[workspace.dependencies]
anyhow = "1.0.57"
pyo3 = "0.17.2"
pyo3 = "0.19"
pyo3-log = "*"
serde = "1.0.143"
serde_json = "1.0.83"
serde_yaml = "0.8.24"
serde_yaml = "0.9.22"
51 changes: 28 additions & 23 deletions rust/fastsim-cli/src/bin/fastsim-cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ pub fn main() {
let adopt_hd_str_lc = adopt_hd_string.to_lowercase();
let true_string = String::from("true");
let false_string = String::from("false");
let adopt_hd_has_cycle = adopt_hd_str_lc.len() > 0
let adopt_hd_has_cycle = !adopt_hd_str_lc.is_empty()
&& adopt_hd_str_lc != true_string
&& adopt_hd_str_lc != false_string;
(true, adopt_hd_string.clone(), adopt_hd_has_cycle)
Expand Down Expand Up @@ -246,17 +246,17 @@ pub fn main() {
let (veh_string, pwr_out_perc, h2share) = json_rewrite(veh_string);
hd_h2_diesel_ice_h2share = h2share;
fc_pwr_out_perc = pwr_out_perc;
RustVehicle::from_str(&veh_string)
RustVehicle::from_json_str(&veh_string)
} else {
RustVehicle::from_str(&veh_string)
RustVehicle::from_json_str(&veh_string)
}
} else if let Some(veh_file_path) = fastsim_api.veh_file {
if is_adopt || is_adopt_hd {
let vehstring = fs::read_to_string(veh_file_path).unwrap();
let (vehstring, pwr_out_perc, h2share) = json_rewrite(vehstring);
hd_h2_diesel_ice_h2share = h2share;
fc_pwr_out_perc = pwr_out_perc;
RustVehicle::from_str(&vehstring)
RustVehicle::from_json_str(&vehstring)
} else {
RustVehicle::from_file(&veh_file_path)
}
Expand Down Expand Up @@ -312,31 +312,37 @@ pub fn main() {
"HHDDTCruiseSmooth.csv"
));
let cyc = if adopt_hd_has_cycle {
cyc.clone()
cyc
} else {
RustCycle::from_csv_string(hd_cyc_filestring, "HHDDTCruiseSmooth".to_string()).unwrap()
};
let mut sim_drive = RustSimDrive::new(cyc.clone(), veh.clone());
let mut sim_drive = RustSimDrive::new(cyc, veh.clone());
sim_drive.sim_drive(None, None).unwrap();
let mut sim_drive_accel = RustSimDrive::new(make_accel_trace(), veh.clone());
let net_accel = get_net_accel(&mut sim_drive_accel, &veh.scenario_name).unwrap();
let mut mpgge = sim_drive.mpgge;
let h2_diesel_results = if hd_h2_diesel_ice_h2share.is_some() && fc_pwr_out_perc.is_some() {
let dist_mi = sim_drive.dist_mi.sum();
let r = calculate_mpgge_for_h2_diesel_ice(
dist_mi,
sim_drive.veh.fc_max_kw,
sim_drive.props.kwh_per_gge,
&sim_drive.fc_kw_out_ach.to_vec(),
&sim_drive.fs_kwh_out_ach.to_vec(),
&fc_pwr_out_perc.unwrap(),
&hd_h2_diesel_ice_h2share.unwrap(),
);
mpgge = dist_mi / (r.diesel_gge + r.h2_gge);
Some(r)

let h2_diesel_results = if let Some(hd_h2_diesel_ice_h2share) = hd_h2_diesel_ice_h2share {
if let Some(fc_pwr_out_perc) = fc_pwr_out_perc {
let dist_mi = sim_drive.dist_mi.sum();
let r = calculate_mpgge_for_h2_diesel_ice(
dist_mi,
sim_drive.veh.fc_max_kw,
sim_drive.props.kwh_per_gge,
&sim_drive.fc_kw_out_ach.to_vec(),
&sim_drive.fs_kwh_out_ach.to_vec(),
&fc_pwr_out_perc,
&hd_h2_diesel_ice_h2share,
);
mpgge = dist_mi / (r.diesel_gge + r.h2_gge);
Some(r)
} else {
None
}
} else {
None
};

let res = AdoptResults {
adjCombMpgge: mpgge,
rangeMiles: if mpgge > 0.0 {
Expand Down Expand Up @@ -397,8 +403,7 @@ fn array_to_object_representation(xs: &Vec<f64>) -> ArrayObject {

fn transform_array_of_value_to_vec_of_f64(array_of_values: &Vec<Value>) -> Vec<f64> {
let mut vec_of_f64 = Vec::<f64>::new();
for idx in 0..array_of_values.len() {
let item_raw = &array_of_values[idx];
for item_raw in array_of_values {
if item_raw.is_number() {
let item = item_raw.as_f64().unwrap();
vec_of_f64.push(item);
Expand Down Expand Up @@ -437,7 +442,7 @@ fn json_rewrite(x: String) -> (String, Option<Vec<f64>>, Option<Vec<f64>>) {
let fc_eff_type_value = fc_eff_type_raw.as_str().unwrap();
let fc_eff_type = String::from(fc_eff_type_value);
parsed_data["fcEffType"] = Value::String(fc_eff_type.clone());
if fc_eff_type == String::from("HDH2DieselIce") {
if fc_eff_type == *"HDH2DieselIce" {
let fc_pwr_out_perc_raw = &parsed_data["fuelConverter"]["fcPwrOutPerc"];
if fc_pwr_out_perc_raw.is_array() {
fc_pwr_out_perc = Some(transform_array_of_value_to_vec_of_f64(
Expand Down Expand Up @@ -517,5 +522,5 @@ fn json_rewrite(x: String) -> (String, Option<Vec<f64>>, Option<Vec<f64>>) {

let adoptstring = ParsedValue(parsed_data).to_json();

return (adoptstring, fc_pwr_out_perc, hd_h2_diesel_ice_h2share);
(adoptstring, fc_pwr_out_perc, hd_h2_diesel_ice_h2share)
}
2 changes: 1 addition & 1 deletion rust/fastsim-core/proc-macros/src/add_pyo3_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub fn add_pyo3_api(attr: TokenStream, item: TokenStream) -> TokenStream {
let mut impl_block = TokenStream2::default();
let mut py_impl_block = TokenStream2::default();
py_impl_block.extend::<TokenStream2>(crate::utilities::parse_ts_as_fn_defs(
attr.into(),
attr,
vec![],
false,
vec![],
Expand Down
25 changes: 11 additions & 14 deletions rust/fastsim-core/proc-macros/src/utilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,26 +265,23 @@ pub fn parse_ts_as_fn_defs(
let sig_str = &item_meth.sig.ident.to_token_stream().to_string();
fn_from_attr.extend(item_meth.clone().to_token_stream());
// check signature
if expected_exclusive {
if forbidden_fn_names.contains(sig_str) || !expected_fn_names.contains(sig_str)
{
emit_error!(
&item_meth.sig.ident.span(),
format!("Function name `{}` is forbidden", sig_str)
)
}
if expected_exclusive
&& (forbidden_fn_names.contains(sig_str)
|| !expected_fn_names.contains(sig_str))
{
emit_error!(
&item_meth.sig.ident.span(),
format!("Function name `{}` is forbidden", sig_str)
)
}

let index = expected_fn_names.iter().position(|x| x == sig_str);

match index {
Some(i) => {
expected_fn_names.remove(i);
}
_ => {}
}
// remove the matching name from the vec to avoid checking again
// at the end of iteration, this vec should be empty
if let Some(i) = index {
expected_fn_names.remove(i);
}
}
_ => abort_call_site!(ONLY_FN_MSG),
}
Expand Down
1 change: 1 addition & 0 deletions rust/fastsim-core/src/fastsim
Submodule fastsim added at 26edd8
12 changes: 10 additions & 2 deletions rust/fastsim-core/src/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@ pub const SMALL_BASELINE_EFF: [f64; 11] = [

pub const CHG_EFF: f64 = 0.86; // charger efficiency for PEVs, this should probably not be hard coded long term

#[derive(Debug, Serialize, Deserialize, PartialEq, ApproxEq)]
#[add_pyo3_api]
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, ApproxEq)]
pub struct RustLongParams {
#[serde(rename = "rechgFreqMiles")]
pub rechg_freq_miles: Vec<f64>,
Expand All @@ -131,12 +132,18 @@ pub struct RustLongParams {
pub ld_fe_adj_coef: AdjCoefMap,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, ApproxEq)]
impl SerdeAPI for RustLongParams {}

#[add_pyo3_api]
#[derive(Default, Debug, Serialize, Deserialize, PartialEq, Clone, ApproxEq)]
pub struct AdjCoefMap {
#[serde(flatten)]
pub adj_coef_map: HashMap<String, AdjCoef>,
}

impl SerdeAPI for AdjCoefMap {}

#[add_pyo3_api]
#[derive(Default, Debug, Serialize, Deserialize, PartialEq, Clone, ApproxEq)]
pub struct AdjCoef {
#[serde(rename = "City Intercept")]
Expand All @@ -148,6 +155,7 @@ pub struct AdjCoef {
#[serde(rename = "Highway Slope")]
pub hwy_slope: f64,
}
impl SerdeAPI for AdjCoef {}

impl Default for RustLongParams {
fn default() -> Self {
Expand Down
Loading