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

Refactor RustCycle constructors #75

Merged
merged 8 commits into from
Dec 4, 2023
Merged
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
22 changes: 11 additions & 11 deletions python/fastsim/cycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def __init__(self, cyc: Cycle):
self.trapz_step_distances_m = trapz_step_distances(cyc)
self.trapz_distances_m = self.trapz_step_distances_m.cumsum()
if (self.grade_all_zero):
self.trapz_elevations_m = np.zeros(len(cyc.time_s))
self.trapz_elevations_m = np.zeros(len(cyc))
else:
self.trapz_elevations_m = np.cumsum(np.cos(np.arctan(cyc.grade)) * self.trapz_step_distances_m * np.array(cyc.grade))
self.stops = np.array(cyc.mps) <= tol
Expand Down Expand Up @@ -219,12 +219,12 @@ def delta_elev_m(self) -> np.ndarray:
"""
return (self.dist_m * self.grade).cumsum()

@property
def len(self) -> int:

def __len__(self) -> int:
"return cycle length"
return len(self.time_s)

def get_cyc_dict(self) -> Dict[str, np.ndarray]:
def to_dict(self) -> Dict[str, np.ndarray]:
"""Returns cycle as dict rather than class instance."""
keys = STANDARD_CYCLE_KEYS

Expand Down Expand Up @@ -396,7 +396,7 @@ def to_microtrips(cycle, stop_speed_m__s=1e-6, keep_name=False):

Arguments:
----------
cycle: drive cycle converted to dictionary by cycle.get_cyc_dict()
cycle: drive cycle converted to dictionary by cycle.to_dict()
stop_speed_m__s: speed at which vehicle is considered stopped for trip
separation
keep_name: (optional) bool, if True and cycle contains "name", adds
Expand Down Expand Up @@ -469,8 +469,8 @@ def equals(c1, c2) -> bool:
Returns true if the two cycles are equal, false otherwise
Arguments:
----------
c1: cycle as dictionary from get_cyc_dict()
c2: cycle as dictionary from get_cyc_dict()
c1: cycle as dictionary from to_dict()
c2: cycle as dictionary from to_dict()
"""
if c1.keys() != c2.keys():
c2missing = set(c1.keys()) - set(c2.keys())
Expand Down Expand Up @@ -914,7 +914,7 @@ def extend_cycle(
RETURNS: fastsim.cycle.Cycle (or fastsimrust.RustCycle), the new cycle with stopped time appended
NOTE: additional time is rounded to the nearest second
"""
cyc0 = cyc.get_cyc_dict()
cyc0 = cyc.to_dict()
extra_time_s = absolute_time_s + float(int(round(time_fraction * cyc.time_s[-1])))
# Zero-velocity cycle segment so simulation doesn't end while moving
cyc_stop = resample(
Expand Down Expand Up @@ -952,13 +952,13 @@ def time_spent_moving(cycle):
blend_factor = max(0.0, min(1.0, blend_factor))
dist_and_tgt_speeds = []
# Split cycle into microtrips
microtrips = to_microtrips(cyc.get_cyc_dict())
microtrips = to_microtrips(cyc.to_dict())
dist_at_start_of_microtrip_m = 0.0
for mt in microtrips:
mt_cyc = Cycle.from_dict(mt)
mt_dist_m = sum(mt_cyc.dist_m)
mt_time_s = mt_cyc.time_s[-1] - mt_cyc.time_s[0]
mt_moving_time_s = time_spent_moving(mt_cyc.get_cyc_dict())
mt_moving_time_s = time_spent_moving(mt_cyc.to_dict())
mt_avg_spd_m_per_s = mt_dist_m / mt_time_s if mt_time_s > 0.0 else 0.0
mt_moving_avg_spd_m_per_s = mt_dist_m / mt_moving_time_s if mt_moving_time_s > 0.0 else 0.0
mt_target_spd_m_per_s = max(
Expand Down Expand Up @@ -1021,7 +1021,7 @@ def copy_cycle(cyc: Cycle, return_type: str = None, deep: bool = True) -> Dict[s
elif return_type == 'legacy':
return LegacyCycle(cyc_dict)
elif return_type == 'rust':
return RustCycle(**cyc_dict)
return RustCycle.from_dict(cyc_dict)
else:
raise ValueError(f"Invalid return_type: '{return_type}'")

8 changes: 4 additions & 4 deletions python/fastsim/demos/cav_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def maybe_str_to_bool(x, default=True):
#
# Here we set up an "automated cruise control" for a system
# that drives the average speed of the cycle.
cyc_udds = fsim.cycle.Cycle.from_file('udds').get_cyc_dict()
cyc_udds = fsim.cycle.Cycle.from_file('udds').to_dict()
cyc_stop = fsim.cycle.resample(
fsim.cycle.make_cycle([0.0, 200.0], [0.0, 0.0]),
new_dt=1.0,
Expand Down Expand Up @@ -116,7 +116,7 @@ def maybe_str_to_bool(x, default=True):
# the average speed of the microtrip assuming the vehicle
# is able to get the average speed per microtrip from some
# external source.
cyc_udds = fsim.cycle.Cycle.from_file('udds').get_cyc_dict()
cyc_udds = fsim.cycle.Cycle.from_file('udds').to_dict()
cyc_stop = fsim.cycle.resample(
fsim.cycle.make_cycle([0.0, 200.0], [0.0, 0.0]),
new_dt=1.0,
Expand All @@ -127,7 +127,7 @@ def maybe_str_to_bool(x, default=True):
veh = fsim.vehicle.Vehicle.from_vehdb(1).to_rust()
sd = fsim.simdrive.RustSimDrive(cyc, veh)
dist_and_avg_speeds = []
microtrips = fsim.cycle.to_microtrips(cyc.get_cyc_dict())
microtrips = fsim.cycle.to_microtrips(cyc.to_dict())
dist_at_start_of_microtrip_m = 0.0
for mt in microtrips:
mt_cyc = fsim.cycle.Cycle.from_dict(mt)
Expand Down Expand Up @@ -184,7 +184,7 @@ def maybe_str_to_bool(x, default=True):
# # Eco-Cruise and Eco-Approach running at the same time
#
# Here, we run an Eco-Cruise and Eco-Approach at the same time.
cyc_udds = fsim.cycle.Cycle.from_file('udds').get_cyc_dict()
cyc_udds = fsim.cycle.Cycle.from_file('udds').to_dict()
cyc_stop = fsim.cycle.resample(
fsim.cycle.make_cycle([0.0, 400.0], [0.0, 0.0]),
new_dt=1.0,
Expand Down
2 changes: 1 addition & 1 deletion python/fastsim/demos/cav_sweep.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def load_cycle(cyc_name: str, use_rust: bool=False) -> fastsim.cycle.Cycle:
if RESAMPLE_TO_1HZ:
raw_cycle = fastsim.cycle.Cycle.from_dict(
fastsim.cycle.resample(
raw_cycle.get_cyc_dict(),
raw_cycle.to_dict(),
new_dt=1.0,
hold_keys_next={'grade'},
)
Expand Down
22 changes: 11 additions & 11 deletions python/fastsim/demos/demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -624,7 +624,7 @@ def get_sim_drive_vec(
# %% generate micro-trip
t0 = time.perf_counter()
cyc = fsim.cycle.Cycle.from_file("udds")
microtrips = fsim.cycle.to_microtrips(cyc.get_cyc_dict())
microtrips = fsim.cycle.to_microtrips(cyc.to_dict())
cyc = fsim.cycle.Cycle.from_dict(microtrips[1])
print(f'Time to load cycle: {time.perf_counter() - t0:.2e} s')

Expand Down Expand Up @@ -681,7 +681,7 @@ def get_sim_drive_vec(
cyc1 = fsim.cycle.Cycle.from_file(
str(Path(fsim.simdrive.__file__).parent / 'resources/cycles/udds.csv'))
cyc2 = fsim.cycle.Cycle.from_file("us06")
cyc_combo = fsim.cycle.concat([cyc1.get_cyc_dict(), cyc2.get_cyc_dict()])
cyc_combo = fsim.cycle.concat([cyc1.to_dict(), cyc2.to_dict()])
cyc_combo = fsim.cycle.Cycle.from_dict(cyc_combo)
print(f'Time to load cycles: {time.perf_counter() - t0:.2e} s')

Expand Down Expand Up @@ -727,15 +727,15 @@ def get_sim_drive_vec(
cyc1 = fsim.cycle.Cycle.from_file("udds")
cyc2 = fsim.cycle.Cycle.from_file("us06")
print('Cycle 1 and 2 equal?')
print(fsim.cycle.equals(cyc1.get_cyc_dict(), cyc2.get_cyc_dict()))
print(fsim.cycle.equals(cyc1.to_dict(), cyc2.to_dict()))
cyc1 = fsim.cycle.Cycle.from_file("udds")
cyc2 = fsim.cycle.Cycle.from_file("udds")
print('Cycle 1 and 2 equal?')
print(fsim.cycle.equals(cyc1.get_cyc_dict(), cyc2.get_cyc_dict()))
cyc2dict = cyc2.get_cyc_dict()
print(fsim.cycle.equals(cyc1.to_dict(), cyc2.to_dict()))
cyc2dict = cyc2.to_dict()
cyc2dict['extra key'] = None
print('Cycle 1 and 2 equal?')
print(fsim.cycle.equals(cyc1.get_cyc_dict(), cyc2dict))
print(fsim.cycle.equals(cyc1.to_dict(), cyc2dict))
print(f'Time to load and compare cycles: {time.perf_counter() - t0:.2e} s')

# %% [markdown]
Expand All @@ -744,8 +744,8 @@ def get_sim_drive_vec(
# %%
t0 = time.perf_counter()
cyc = fsim.cycle.Cycle.from_file("udds")
cyc10Hz = fsim.cycle.Cycle.from_dict(fsim.cycle.resample(cyc.get_cyc_dict(), new_dt=0.1))
cyc10s = fsim.cycle.Cycle.from_dict(fsim.cycle.resample(cyc.get_cyc_dict(), new_dt=10))
cyc10Hz = fsim.cycle.Cycle.from_dict(fsim.cycle.resample(cyc.to_dict(), new_dt=0.1))
cyc10s = fsim.cycle.Cycle.from_dict(fsim.cycle.resample(cyc.to_dict(), new_dt=10))

plt.plot(cyc10Hz.time_s, cyc10Hz.mph, marker=',')
plt.plot(cyc10s.time_s, cyc10s.mph, marker=',')
Expand All @@ -772,9 +772,9 @@ def get_sim_drive_vec(
cyc_udds = fsim.cycle.Cycle.from_file("udds")
# Generate cycle with 0.1 s time steps
cyc_udds_10Hz = fsim.cycle.Cycle.from_dict(
fsim.cycle.resample(cyc_udds.get_cyc_dict(), new_dt=0.1))
fsim.cycle.resample(cyc_udds.to_dict(), new_dt=0.1))
cyc_us06 = fsim.cycle.Cycle.from_file("us06")
cyc_combo = fsim.cycle.concat([cyc_udds_10Hz.get_cyc_dict(), cyc_us06.get_cyc_dict()])
cyc_combo = fsim.cycle.concat([cyc_udds_10Hz.to_dict(), cyc_us06.to_dict()])
cyc_combo = fsim.cycle.resample(cyc_combo, new_dt=1)
cyc_combo = fsim.cycle.Cycle.from_dict(cyc_combo)
print(f'Time to load and concatenate cycles: {time.perf_counter() - t0:.2e} s')
Expand Down Expand Up @@ -826,7 +826,7 @@ def get_sim_drive_vec(
# %% generate micro-trip
t0 = time.perf_counter()
cyc = fsim.cycle.Cycle.from_file("udds")
cyc = fsim.cycle.clip_by_times(cyc.get_cyc_dict(), t_end=300)
cyc = fsim.cycle.clip_by_times(cyc.to_dict(), t_end=300)
cyc = fsim.cycle.Cycle.from_dict(cyc)
print(f'Time to load and clip cycle: {time.perf_counter() - t0:.2e} s')

Expand Down
16 changes: 8 additions & 8 deletions python/fastsim/demos/demo_eu_vehicle_wltp.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ def convention_eu_veh_wltp_fe_test():
wltp_med_cyc_3b = fsim.cycle.Cycle.from_file('wltc_class3_med3b.csv').to_rust()
wltp_high_cyc_3b = fsim.cycle.Cycle.from_file('wltc_class3_high3b.csv').to_rust()
wltp_extrahigh_cyc_3 = fsim.cycle.Cycle.from_file('wltc_class3_extra_high3.csv').to_rust()
cyc_wltp_combo = fsim.cycle.concat([wltp_low_cyc_3.get_cyc_dict(),
wltp_med_cyc_3b.get_cyc_dict(),
wltp_high_cyc_3b.get_cyc_dict(),
wltp_extrahigh_cyc_3.get_cyc_dict()]
cyc_wltp_combo = fsim.cycle.concat([wltp_low_cyc_3.to_dict(),
wltp_med_cyc_3b.to_dict(),
wltp_high_cyc_3b.to_dict(),
wltp_extrahigh_cyc_3.to_dict()]
)
cyc_wltp_combo = fsim.cycle.Cycle.from_dict(cyc_wltp_combo).to_rust()

Expand Down Expand Up @@ -60,10 +60,10 @@ def hybrid_eu_veh_wltp_fe_test():
wltp_high_cyc_3b_rust = wltp_high_cyc_3b.to_rust()
wltp_extrahigh_cyc_3 = fsim.cycle.Cycle.from_file('wltc_class3_extra_high3.csv')
wltp_extrahigh_cyc_3_rust = wltp_extrahigh_cyc_3.to_rust()
cyc_wltp_combined = fsim.cycle.concat([wltp_low_cyc_3.get_cyc_dict(),
wltp_med_cyc_3b.get_cyc_dict(),
wltp_high_cyc_3b.get_cyc_dict(),
wltp_extrahigh_cyc_3.get_cyc_dict()
cyc_wltp_combined = fsim.cycle.concat([wltp_low_cyc_3.to_dict(),
wltp_med_cyc_3b.to_dict(),
wltp_high_cyc_3b.to_dict(),
wltp_extrahigh_cyc_3.to_dict()
]
)
cyc_wltp_combined = fsim.cycle.Cycle.from_dict(cyc_wltp_combined)
Expand Down
4 changes: 2 additions & 2 deletions python/fastsim/demos/stop_start_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@
# %%
t0 = time.time()
# cyc = cycle.Cycle.from_dict(cyc_dict=
# cycle.clip_by_times(cycle.Cycle.from_file("udds").get_cyc_dict(), 130))
cyc = cycle.Cycle.from_file('udds').get_cyc_dict()
# cycle.clip_by_times(cycle.Cycle.from_file("udds").to_dict(), 130))
cyc = cycle.Cycle.from_file('udds').to_dict()
cyc = cycle.Cycle.from_dict(cycle.clip_by_times(cyc, 130))
print(f"Elapsed time: {time.time() - t0:.3e} s")

Expand Down
2 changes: 1 addition & 1 deletion python/fastsim/demos/time_dilation_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

t0 = time.time()
cyc = cycle.Cycle.from_dict(cyc_dict=cycle.clip_by_times(
cycle.Cycle.from_file('longHaulDriveCycle').get_cyc_dict(),
cycle.Cycle.from_file('longHaulDriveCycle').to_dict(),
t_end=18_000, t_start=1_800))
print('Time to load cycle file: {:.3f} s'.format(time.time() - t0))

Expand Down
8 changes: 4 additions & 4 deletions python/fastsim/demos/wltc_calibration.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,10 @@ def mpgge_to_litersPer100km(mpgge):
# Generate combined cycle
cyc_combined_dict = fastsim.cycle.concat(
[
cyc_low.get_cyc_dict(),
cyc_med.get_cyc_dict(),
cyc_high.get_cyc_dict(),
cyc_extrahigh.get_cyc_dict(),
cyc_low.to_dict(),
cyc_med.to_dict(),
cyc_high.to_dict(),
cyc_extrahigh.to_dict(),
]
)
cyc = fastsim.cycle.Cycle.from_dict(cyc_combined_dict)
Expand Down
2 changes: 1 addition & 1 deletion python/fastsim/fastsimrust.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ class RustCycle(SerdeAPI):
def calc_distance_to_next_stop_from(self, distance_m: float) -> float:
...

def get_cyc_dict(self) -> Dict[str, List[float]]:
def to_dict(self) -> Dict[str, List[float]]:
"""Return a HashMap representing the cycle"""
...

Expand Down
4 changes: 2 additions & 2 deletions python/fastsim/simdrive.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ def __init_objects__(self, cyc: cycle.Cycle, veh: vehicle.Vehicle):

def init_arrays(self):
self.i = 1 # initialize step counter for possible use outside sim_drive_walk()
cyc_len = self.cyc.len
cyc_len = len(self.cyc)

# Component Limits -- calculated dynamically
self.cur_max_fs_kw_out = np.zeros(cyc_len, dtype=np.float64)
Expand Down Expand Up @@ -487,7 +487,7 @@ def activate_eco_cruise(
params = self.sim_params
params.idm_allow = True
if not by_microtrip:
if self.cyc0.len > 0 and self.cyc0.time_s[-1] > 0.0:
if len(self.cyc0) > 0 and self.cyc0.time_s[-1] > 0.0:
params.idm_v_desired_m_per_s = self.cyc0.dist_m.sum() / self.cyc0.time_s[-1]
else:
params.idm_v_desired_m_per_s = 0.0
Expand Down
Loading