Table of Contents

fastsim

Python API for fastsim

check_version_gte_311

def check_version_gte_311() -> bool

Return true if python version is greater than or equal to 3.11

package_root

def package_root() -> Path

Return the package root directory.

resources_root

def resources_root() -> Path

Return the resources root directory.

cyc_keys

def cyc_keys() -> list[str]

Return cycle keys

to_pydict

def to_pydict(self, data_fmt: str = "msg_pack", flatten: bool = False) -> dict

Return self converted to pure python dictionary with no nested Rust objects

Arguments

  • - flatten: if True, returns dict without any hierarchy
  • - data_fmt: data format for intermediate conversion step

get_hist_len

def get_hist_len(obj: dict) -> int | None

Find nested history and gets lenth of first element

get_flattened

def get_flattened(obj: dict | list,
                  hist_len: int,
                  prepend_str: str = "") -> dict

Flatten and return dictionary, separating keys and indices with a "."

Arguments

- obj: object to flatten

- hist_len: length of any lists storing history data

- prepend_str: prepend this to all keys in the returned flat dict

from_pydict

@classmethod
def from_pydict(cls,
                pydict: dict,
                data_fmt: str = "msg_pack",
                skip_init: bool = False) -> Self

Instantiate Self from pure python dictionary

Arguments

  • - pydict: dictionary to be converted to FASTSim object
  • - data_fmt: data format for intermediate conversion step
  • - skip_init: passed to SerdeAPI methods to control whether initialization is skipped

to_dataframe

def to_dataframe(self,
                 pandas: bool = False,
                 allow_partial: bool = False) -> pd.DataFrame | pl.DataFrame

Return time series results from fastsim object as a Polars or Pandas dataframe.

Arguments

  • - pandas: returns pandas dataframe if True; otherwise, returns polars dataframe by default
  • - allow_partial: tries to return dataframe of length equal to solved time steps if simulation fails early

fastsim.utils.utilities

copy_demo_files

def copy_demo_files(path_for_copies: Path = Path("demos"))

Copies demo files from demos folder into specified local directory Arguments

  • - path_for_copies: path to copy files into (relative or absolute in) Warning

Running this function will overwrite existing files with the same name in the specified directory, so make sure any files with changes you'd like to keep are renamed.

fastsim.utils

fastsim.copy_stub_docstrings

fastsim.pymoo_api

Module containing functions and classes for easy interaction with PyMOO

get_error_val

def get_error_val(model: npt.NDArray[np.float64],
                  test: npt.NDArray[np.float64],
                  time_steps: npt.NDArray[np.float64]) -> float

Returns time-averaged error for model and test signal.

Args:

  • model: array of values for signal from model
  • test: array of values for signal from test data
  • time_steps: array (or scalar for constant) of values for model time steps [s]

Returns:

  • error: integral of absolute value of difference between model and test per time

ModelObjectives Objects

@dataclass
class ModelObjectives()

Class for calculating eco-driving objectives

Attributes/Fields

  • models (Dict[str, Dict]): dictionary of model dicts to be simulated
  • dfs (Dict[str, pd.DataFrame]): dictionary of dataframes from test data corresponding to models
  • obj_fns (Tuple[Callable] | Tuple[Tuple[Callable, Callable]]): Tuple of functions for extracting objective signal values for either minimizing a scalar metric (e.g. fuel economy) or minimizing error relative to test data.
    • minimizing error in fuel consumption relative to test data
      obj_fns = (
          (
              # model -- note, `lambda` only works for single thread
              lambda sd_dict: sd_dict['veh']['pt_type']['Conventional']['fc']['history']['energy_fuel_joules'],
              # test data
              lambda df: df['fuel_flow_gps'] * ... (conversion factors to get to same unit),
          ), # note that this trailing comma ensures `obj_fns` is interpreted as a tuple
      )
      
    • minimizing fuel consumption
      obj_fns = (
          (
              # note that a trailing comma ensures `obj_fns` is interpreted as tuple
              lambda sd_dict: sd_dict['veh']['pt_type']['Conventional']['fc']['state']['energy_fuel_joules'],
          )
      )
      
  • param_fns_and_bounds Tuple[Tuple[Callable], Tuple[Tuple[float, float]]]: tuple containing functions to modify parameters and bounds for optimizer Example
    def new_peak_res_eff (sd_dict, new_peak_eff) -> Dict:
        sd_dict['veh']['pt_type']['HybridElectricVehicle']['res']['peak_eff'] = new_peak_eff
        return sd_dict
    ...
    param_fns_and_bounds = (
        (new_peak_res_eff, (100.0, 200.0)),
    )
    
  • verbose (bool): print more stuff or not

update_params

def update_params(xs: list[Any])

Updates model parameters based on x, which must match length of self.param_fns

get_errors

def get_errors(
    sim_drives: dict[str, fsim.SimDrive],
    return_mods: bool = False
) -> (tuple[dict[str, list[float]], dict[str, list[float]]]
      | tuple[
          dict[str, list[float]],
          dict[str, list[float]],
          dict[str, fsim.SimDrive | Any],
          dict[str, fsim.SimDrive | Any],
      ])

Calculate model errors w.r.t. test data for each element in dfs/models for each objective.

Args:

  • sim_drives: dictionary with user-defined keys and SimDrive instances
  • return_mods: if true, also returns dict of solved models. Defaults to False.

Returns:

Objectives and optionally solved models

get_parser

def get_parser(
        def_description: str = "Program for calibrating fastsim models.",
        def_p: int = 4,
        def_n_max_gen: int = 500,
        def_pop_size: int = 12) -> argparse.ArgumentParser

Generate parser for optimization hyper params and misc. other params

Args:

  • def_p: default number of processes
  • def_n_max_gen: max allowed generations
  • def_pop_size: default population size

Returns:

argparse.ArgumentParser: description

fastsim.tests.test_speedup

fastsim.tests.test_serde

fastsim.tests.test_utils

fastsim.tests.test_resources

Test getting resource lists via Rust API

test_list_resources_for_cycle

def test_list_resources_for_cycle()

Assert list_resources works for Cycle

test_list_resources_for_vehicle

def test_list_resources_for_vehicle()

Assert list_resources works for Vehicle

fastsim.demos.demo_hev

Hybrid electric vehicle demo showcasing FASTSim-3 simulation capabilities.

plot_road_loads_comparison

def plot_road_loads_comparison() -> tuple[Figure, Axes]

Plot comparison of fastsim-3 v. fastsim-2 road loads

plot_fc_pwr

def plot_fc_pwr() -> tuple[Figure, Axes]

Plot fuel converter powers

plot_fc_energy

def plot_fc_energy() -> tuple[Figure, Axes]

Plot fuel converter energies

plot_res_pwr

def plot_res_pwr() -> tuple[Figure, Axes]

Plot reversible energy storage powers

plot_res_energy

def plot_res_energy() -> tuple[Figure, Axes]

Plot reversible energy storage energies

fastsim.demos.test_demos

Test suite for FASTSim demo scripts to ensure they run without errors.

demo_paths

def demo_paths()

Get list of all demo script paths.

test_demo

@pytest.mark.parametrize("demo_path",
                         demo_paths(),
                         ids=[dp.name for dp in demo_paths()])
def test_demo(demo_path: Path)

Test that each demo script runs successfully without errors.

fastsim.demos.plot_utils

Plotting utilities for FASTSim demo scripts.

get_paired_cycler

def get_paired_cycler(pair_attr: str = DEF_PAIR_ATTR)

Return a cycler for setting style in paired plots

Arguments:

  • pair_attr: whether the paired lines should match in "color" or "linestyle"

get_uni_cycler

def get_uni_cycler(pair_attr: str = DEF_PAIR_ATTR)

Get a uniform cycler for plotting.

Arguments:

  • pair_attr: ensures consistent behavior with get_paired_cycler

plot_bev_temperatures

def plot_bev_temperatures(df: pd.DataFrame, save_figs: bool,
                          show_plots: bool) -> tuple[Figure, Axes]

Plot BEV component temperatures over time.

plot_bev_hvac_pwr

def plot_bev_hvac_pwr(df: pd.DataFrame, save_figs: bool,
                      show_plots: bool) -> tuple[Figure, Axes]

Plot BEV HVAC power consumption over time.

plot_bev_res_pwr

def plot_bev_res_pwr(df: pd.DataFrame, save_figs: bool,
                     show_plots: bool) -> tuple[Figure, Axes]

Plot BEV reversible energy storage power over time.

plot_bev_res_energy

def plot_bev_res_energy(df: pd.DataFrame, save_figs: bool,
                        show_plots: bool) -> tuple[Figure, Axes]

Plot BEV reversible energy storage energy over time.

plot_road_loads

def plot_road_loads(df: pd.DataFrame, veh: fsim.Vehicle, save_figs: bool,
                    show_plots: bool) -> tuple[Figure, Axes]

Plot vehicle road loads over time.

plot_hev_temperatures

def plot_hev_temperatures(df: pd.DataFrame, save_figs: bool,
                          show_plots: bool) -> tuple[Figure, Axes]

Plot HEV component temperatures including battery, engine, and cabin.

plot_hev_fc_pwr

def plot_hev_fc_pwr(df: pd.DataFrame, save_figs: bool,
                    show_plots: bool) -> tuple[Figure, Axes]

Plot HEV fuel converter powers

plot_hev_fc_energy

def plot_hev_fc_energy(df: pd.DataFrame, save_figs: bool,
                       show_plots: bool) -> tuple[Figure, Axes]

Plot HEV fuel converter energy consumption over time.

plot_hev_res_pwr

def plot_hev_res_pwr(df: pd.DataFrame, save_figs: bool,
                     show_plots: bool) -> tuple[Figure, Axes]

Plot HEV reversible energy storage power including electrical and thermal.

plot_hev_res_energy

def plot_hev_res_energy(df: pd.DataFrame, save_figs: bool,
                        show_plots: bool) -> tuple[Figure, Axes]

Plot HEV reversible energy storage energy including electrical and thermal.

fastsim.demos.demo_bev_thrml_sweep

BEV thermal demo with cold start and cold ambient conditions.

try_walk

def try_walk(sd: fsim.SimDrive, loc: str) -> None

Wrap walk in try to enable context

setup_sweep

def setup_sweep() -> pd.DataFrame

Set up sweep of ambient and initial conditions

sweep

def sweep(df: pd.DataFrame,
          n_proc: int | None) -> tuple[pd.DataFrame, pd.DataFrame]

Sweep ambient and initial conditions

Arguments:

- df: dataframe of DOE

- n_proc: number of parallel processes

solve_row

def solve_row(iterrow: tuple[Hashable, pd.Series]) -> dict[str, Any]

Solve row of dataframe and return result

plot_time_series

def plot_time_series(df: pd.DataFrame,
                     verbose: bool = False,
                     show_plots: bool = False,
                     save_figs: bool = False) -> None

Plot time series temperature data

plot_sweep

def plot_sweep(df: pd.DataFrame,
               cyc: str,
               x_var: str,
               par_var_sweep: list[float],
               show_plots: bool = False,
               save_figs: bool = False) -> tuple[plt.Figure, plt.Axes]

Plot sweep of ambient and initial temperatures, parameteric style

plot_sweep_cross_effects

def plot_sweep_cross_effects(
        df: pd.DataFrame,
        cyc: str,
        x_var: str,
        par_var_sweep: list[float],
        show_plots: bool = False,
        save_figs: bool = False) -> tuple[plt.Figure, plt.Axes]

Plot sweep of ambient and initial temperatures, parameteric style

def print_cross_delta(df: pd.DataFrame, cycle: str, fixed_var: str) -> None

Print percent increase in ECR for one variable when the other is fixed between 22C and 24C

fastsim.demos.demo_bev_thrml_ws_ca

BEV thermal demo with warm start and cold ambient conditions.

fastsim.demos.demo_trace_miss

A module that demonstrates trace-miss correction.

trace_miss_demo

def trace_miss_demo()

Run a vehicle over a cycle with a trace miss + correction

fastsim.demos.demo_bev

BEV demo showcasing FASTSim-3 vehicle simulation and plotting capabilities.

plot_res_pwr

def plot_res_pwr() -> tuple[Figure, Axes]

Plot reversible energy storage powers

plot_res_energy

def plot_res_energy() -> tuple[Figure, Axes]

Plot reversible energy storage energies

plot_road_loads_comparison

def plot_road_loads_comparison() -> tuple[Figure, Axes]

Plot comparison of fastsim-3 v. fastsim-2 road loads

test_this_file

def test_this_file()

To trigger automated testing

fastsim.demos.demo_hev_thrml_ws_ca

HEV thermal demo with warm start and cold ambient conditions.

fastsim.demos.demo_bev_thrml_ws_wa

BEV thermal demo with warm start and warm ambient conditions.

fastsim.demos.demo_hev_thrml_ws_wa

HEV thermal demo with warm start and warm ambient conditions.

fastsim.demos.demo_bev_thrml_cs_ca

BEV thermal demo with cold start and cold ambient conditions.

fastsim.demos.demo_cavs

Demonstration of Connected Automated Vehicle (CAV) Functionality in FASTSim

This module demonstrates:

  • cycle manipulation utilities
  • eco-approach: utilizing vehicle coasting to conserve fuel use
  • eco-cruise: use of trajectories to remove unnecessary accelerations

microtrip_demo

def microtrip_demo()

Run a demonstration of cycle manipulation utilities

plot_speed_by_time

def plot_speed_by_time(df,
                       c0,
                       is_coast=None,
                       save_interval=1,
                       title=None,
                       with_elevation=False)

Plot speed by time

plot_speed_by_dist

def plot_speed_by_dist(df,
                       c0,
                       is_coast=None,
                       save_interval=1,
                       title=None,
                       with_elevation=False)

Plot speed by distance

setup_models

def setup_models(cyc_file="udds.csv", veh_file="2012_Ford_Fusion.yaml")

Set up and return cycle and vehicle models

basic_coasting_demo

def basic_coasting_demo()

Demonstrate coasting starting from a given speed

advanced_coasting_demo

def advanced_coasting_demo()

Demonstrate coasting starting from a given speed

basic_cruise_demo

def basic_cruise_demo()

Demonstrate basic Eco-Cruise usage

cruise_and_coast_demo

def cruise_and_coast_demo()

Demonstrate both cruise and coast

coast_with_grade_demo

def coast_with_grade_demo()

Coasting in the presence of grade

fastsim.demos.demo_hev_thrml_cs_ca

HEV thermal demo with cold start and cold ambient conditions.

fastsim.demos.demo_conv

Conventional vehicle demo showcasing FASTSim-3 simulation capabilities.

plot_fc_pwr

def plot_fc_pwr() -> tuple[Figure, Axes]

Plot fuel converter powers

plot_fc_energy

def plot_fc_energy() -> tuple[Figure, Axes]

Plot fuel converter energies

plot_road_loads_comparison

def plot_road_loads_comparison() -> tuple[Figure, Axes]

Plot comparison of fastsim-3 v. fastsim-2 road loads

fastsim.demos