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

Feature/log level input checking #119

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
14 changes: 10 additions & 4 deletions python/fastsim/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import sys
import logging
import traceback
from typing import Dict

from fastsim import parameters as params
from fastsim import utils
Expand All @@ -21,11 +22,16 @@ def package_root() -> Path:
return Path(__file__).parent


def default_logging_config() -> Dict[str, str]:
return dict(
format = "%(asctime)s.%(msecs)03d | %(filename)s:%(lineno)s | %(levelname)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)



# Set up logging
logging.basicConfig(
format="%(asctime)s.%(msecs)03d | %(filename)s:%(lineno)s | %(levelname)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logging.basicConfig(**default_logging_config())
logger = logging.getLogger(__name__)

from pkg_resources import get_distribution
Expand Down
173 changes: 88 additions & 85 deletions python/fastsim/demos/demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -482,92 +482,94 @@ def get_sim_drive_vec(
# Includes example of how to load cycle from dict

# %%
veh = fsim.vehicle.Vehicle.from_vehdb(1) # load vehicle model
output = {}

results_df = pd.DataFrame()
t_start = time.perf_counter()
for trp in list(drive_cycs_df.nrel_trip_id.unique()):
pnts = drive_cycs_df[drive_cycs_df['nrel_trip_id'] == trp].copy()
pnts['time_local'] = pd.to_datetime(pnts['timestamp'])

cyc = {}
cyc['cycGrade'] = np.zeros(len(pnts))
cyc['mps'] = np.array(
pnts['speed_mph'] / fsim.params.MPH_PER_MPS) # MPH to MPS conversion
cyc['time_s'] = np.array(
np.cumsum(
(pnts['time_local'] -
pnts['time_local'].shift()).fillna(pd.Timedelta(seconds=0)).astype('timedelta64[s]')
with fsim.utils.suppress_logging():
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we change instances of fsim.utils.suppress_logging(): to a single fsim.utils.disable_logging() at the top of the file?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kylecarow, I prefer the latter because I'd like it to be really obvious that we're suppressing logging so that we remember to fix the cause of the logging at some point in the future. Does this seem ok?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm fine with either way really. Do you mean keeping it as is?

veh = fsim.vehicle.Vehicle.from_vehdb(1) # load vehicle model
output = {}

results_df = pd.DataFrame()
t_start = time.perf_counter()
for trp in list(drive_cycs_df.nrel_trip_id.unique()):
pnts = drive_cycs_df[drive_cycs_df['nrel_trip_id'] == trp].copy()
pnts['time_local'] = pd.to_datetime(pnts['timestamp'])

cyc = {}
cyc['cycGrade'] = np.zeros(len(pnts))
cyc['mps'] = np.array(
pnts['speed_mph'] / fsim.params.MPH_PER_MPS) # MPH to MPS conversion
cyc['time_s'] = np.array(
np.cumsum(
(pnts['time_local'] -
pnts['time_local'].shift()).fillna(pd.Timedelta(seconds=0)).astype('timedelta64[s]')
)
)
)
cyc['road_type'] = np.zeros(len(pnts))
# example of loading cycle from dict
cyc = fsim.cycle.Cycle.from_dict(cyc)

sim_drive = fsim.simdrive.SimDrive(cyc, veh)
sim_drive.sim_drive()

output['nrel_trip_id'] = trp
output['distance_mi'] = sum(sim_drive.dist_mi)
duration_sec = sim_drive.cyc.time_s[-1] - sim_drive.cyc.time_s[0]
output['avg_speed_mph'] = sum(
sim_drive.dist_mi) / (duration_sec / 3600.0)
#results_df = results_df.append(output, ignore_index=True)
results_df = pd.concat([results_df,pd.DataFrame(output,index=[0])],ignore_index=True)
output['mpgge'] = sim_drive.mpgge

t_end = time.perf_counter()
cyc['road_type'] = np.zeros(len(pnts))
# example of loading cycle from dict
cyc = fsim.cycle.Cycle.from_dict(cyc)

sim_drive = fsim.simdrive.SimDrive(cyc, veh)
sim_drive.sim_drive()

output['nrel_trip_id'] = trp
output['distance_mi'] = sum(sim_drive.dist_mi)
duration_sec = sim_drive.cyc.time_s[-1] - sim_drive.cyc.time_s[0]
output['avg_speed_mph'] = sum(
sim_drive.dist_mi) / (duration_sec / 3600.0)
#results_df = results_df.append(output, ignore_index=True)
results_df = pd.concat([results_df,pd.DataFrame(output,index=[0])],ignore_index=True)
output['mpgge'] = sim_drive.mpgge

t_end = time.perf_counter()

# results_df = results_df.astype(float)
# results_df = results_df.astype(float)

print(f'Simulations Complete. Total runtime = {t_end - t_start:.2f} s')
print(' Average time per cycle = {:.2f} s'.format((
t_end - t_start) / len(drive_cycs_df.nrel_trip_id.unique())))
print(f'Simulations Complete. Total runtime = {t_end - t_start:.2f} s')
print(' Average time per cycle = {:.2f} s'.format((
t_end - t_start) / len(drive_cycs_df.nrel_trip_id.unique())))

# %% ... and the Rust version
veh = fsim.vehicle.Vehicle.from_vehdb(1).to_rust() # load vehicle model
output = {}

rust_results_df = pd.DataFrame()
t_start = time.perf_counter()
for trp in list(drive_cycs_df.nrel_trip_id.unique()):
pnts = drive_cycs_df[drive_cycs_df['nrel_trip_id'] == trp].copy()
pnts['time_local'] = pd.to_datetime(pnts['timestamp'])

cyc = {}
cyc['cycGrade'] = np.zeros(len(pnts))
cyc['mps'] = np.array(
pnts['speed_mph'] / fsim.params.MPH_PER_MPS) # MPH to MPS conversion
cyc['time_s'] = np.array(
np.cumsum(
(pnts['time_local'] -
pnts['time_local'].shift()).fillna(pd.Timedelta(seconds=0)).astype('timedelta64[s]')
with fsim.utils.suppress_logging():
veh = fsim.vehicle.Vehicle.from_vehdb(1).to_rust() # load vehicle model
output = {}

rust_results_df = pd.DataFrame()
t_start = time.perf_counter()
for trp in list(drive_cycs_df.nrel_trip_id.unique()):
pnts = drive_cycs_df[drive_cycs_df['nrel_trip_id'] == trp].copy()
pnts['time_local'] = pd.to_datetime(pnts['timestamp'])

cyc = {}
cyc['cycGrade'] = np.zeros(len(pnts))
cyc['mps'] = np.array(
pnts['speed_mph'] / fsim.params.MPH_PER_MPS) # MPH to MPS conversion
cyc['time_s'] = np.array(
np.cumsum(
(pnts['time_local'] -
pnts['time_local'].shift()).fillna(pd.Timedelta(seconds=0)).astype('timedelta64[s]')
)
)
)
cyc['road_type'] = np.zeros(len(pnts))
# example of loading cycle from dict
cyc = fsim.cycle.Cycle.from_dict(cyc).to_rust()

sim_drive = fsim.simdrive.RustSimDrive(cyc, veh)
sim_drive.sim_drive()

output['nrel_trip_id'] = trp
output['distance_mi'] = sum(sim_drive.dist_mi)
duration_sec = sim_drive.cyc.time_s[-1] - sim_drive.cyc.time_s[0]
output['avg_speed_mph'] = sum(
sim_drive.dist_mi) / (duration_sec / 3600.0)
rust_results_df = pd.concat([results_df, pd.DataFrame(output,index=[0])], ignore_index=True)
#rust_results_df = results_df.append(output, ignore_index=True)
output['mpgge'] = sim_drive.mpgge

t_end = time.perf_counter()
cyc['road_type'] = np.zeros(len(pnts))
# example of loading cycle from dict
cyc = fsim.cycle.Cycle.from_dict(cyc).to_rust()

sim_drive = fsim.simdrive.RustSimDrive(cyc, veh)
sim_drive.sim_drive()

output['nrel_trip_id'] = trp
output['distance_mi'] = sum(sim_drive.dist_mi)
duration_sec = sim_drive.cyc.time_s[-1] - sim_drive.cyc.time_s[0]
output['avg_speed_mph'] = sum(
sim_drive.dist_mi) / (duration_sec / 3600.0)
rust_results_df = pd.concat([results_df, pd.DataFrame(output,index=[0])], ignore_index=True)
#rust_results_df = results_df.append(output, ignore_index=True)
output['mpgge'] = sim_drive.mpgge

t_end = time.perf_counter()

# results_df = results_df.astype(float)
# results_df = results_df.astype(float)

print(f'Simulations Complete. Total runtime = {t_end - t_start:.2f} s')
print(' Average time per cycle = {:.2f} s'.format((
t_end - t_start) / len(drive_cycs_df.nrel_trip_id.unique())))
print(f'Simulations Complete. Total runtime = {t_end - t_start:.2f} s')
print(' Average time per cycle = {:.2f} s'.format((
t_end - t_start) / len(drive_cycs_df.nrel_trip_id.unique())))

# %% [markdown]
# ### Results
Expand Down Expand Up @@ -889,12 +891,13 @@ def get_sim_drive_vec(
# values.

# %%
if "default" in fsim.fastsimrust.enabled_features():
from fastsim.fastsimrust import abc_to_drag_coeffs
test_veh = fsim.vehicle.Vehicle.from_vehdb(5, to_rust=True).to_rust()
(drag_coef, wheel_rr_coef) = abc_to_drag_coeffs(test_veh, 25.91, 0.1943, 0.01796, simdrive_optimize=True)

print(f'Drag Coefficient: {drag_coef:.3g}')
print(f'Wheel Rolling Resistance Coefficient: {wheel_rr_coef:.3g}')
with fsim.utils.suppress_logging():
if "default" in fsim.fastsimrust.enabled_features():
from fastsim.fastsimrust import abc_to_drag_coeffs
test_veh = fsim.vehicle.Vehicle.from_vehdb(5, to_rust=True).to_rust()
(drag_coef, wheel_rr_coef) = abc_to_drag_coeffs(test_veh, 25.91, 0.1943, 0.01796, simdrive_optimize=True)

print(f'Drag Coefficient: {drag_coef:.3g}')
print(f'Wheel Rolling Resistance Coefficient: {wheel_rr_coef:.3g}')

# %%
22 changes: 22 additions & 0 deletions python/fastsim/utils/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,28 @@ def set_log_level(level: str | int) -> int:
Previous log level
"""
# Map string name to logging level

allowed_args = [
"CRITICAL",
50,
"ERROR",
40,
"WARNING",
30,
"INFO",
20,
"DEBUG",
10,
"NOTSET",
0,
# no logging of anything ever!
logging.CRITICAL + 1,
]

err_str = f"Invalid arg: '{level}'. See doc string:\n{set_log_level.__doc__}"

assert level in allowed_args, err_str

if isinstance(level, str):
level = logging._nameToLevel[level]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@calbaker optionally:

Suggested change
level = logging._nameToLevel[level]
level = logging._nameToLevel[level.upper()]

This would allow lowercase log level strings "warning", "info", etc., but we would need to add those to the allowable inputs.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kylecarow , yea that sounds good. Could you make that change?

# Extract previous log level and set new log level
Expand Down
Loading