API Reference#

Warning

This page is under development. Some modules may not be fully documented yet.

Core Modules#

The Fleet Electrification BC framework consists of three main modules that work together to simulate EV fleet electrification and power system impacts.

Fleet Simulator#

models.fleet_simulator.main.run_fleet_simulation(start_date: str, end_date: str, samples: int, force_update=True, show_log: bool = False)[source]

_summary_

Parameters:
  • start_date (str) – “yyyy-mm-dd”

  • days (int) – Number of days to simulate

  • samples (int) – Number of samples to get from the vehicle population

EV Load Simulator#

models.fleet_EV_load_simulator.scripts.main.get_pypsa_ev_components(start_date: str, end_date: str, ev_charging: str, ev_population: float)[source]

PyPSA-BC Integration#

Note

If the above documentation doesn’t render properly, these modules provide the core functionality for fleet simulation, EV load generation, and power system modeling.

Utility Functions#

Visualization Tools#

models.pypsa_ev_vis.calculate_net_load(network: Network, coord_type: str) list[source]
models.pypsa_ev_vis.get_annotation_text(resample_freq: str, aggregation_method: str = None)[source]
models.pypsa_ev_vis.get_combo_elbow_plot(new_capacity_df: DataFrame, font_family: str = 'serif', strategy_scenario_colors: dict = None)[source]

Generate a combo plot of elbow curves comparing EV charging strategies, with shared y-axis scaled to show all curves clearly.

models.pypsa_ev_vis.get_elbow_curve(df: DataFrame, scenario: str, ax=None, strategy_scenario_colors: dict = None)[source]

Plot elbow curve for a given scenario on the specified matplotlib axis.

models.pypsa_ev_vis.get_generators_curtailment(n: Network, generators_df: DataFrame, show: bool = True, font_family: str = 'serif')[source]
models.pypsa_ev_vis.get_investment_comparison_plot(filtered_gens: DataFrame, gen_tag: str = '', save_to: str = 'vis', font_family: str = 'serif')[source]
models.pypsa_ev_vis.get_net_load_curves(network_dict: dict, scenario_keyword: str, run_tag: str, font_family: str = 'serif')[source]

_summary_

Parameters:

scenario_keyword (str) – ‘hybrid_coord_uncoord’,’coordinated’,’uncoordinated’,’v2g’

models.pypsa_ev_vis.get_network_optimized_installed_capacity_comparison_plot(run_tag: str, ev_scenario_tag: str, ev_penetration: int, network_features: dict, font_family: str = 'serif')[source]

Dictionary of snapshots of different generator profiles.

models.pypsa_ev_vis.get_resampled_data(data: DataFrame, resample_freq: str = 'h', aggregation_method: str = 'mean') DataFrame[source]

Resample the data based on the specified frequency and aggregation method.

Parameters:
  • data (pd.DataFrame) – The input data to be resampled.

  • resample_freq (str) – The frequency string for resampling (e.g., ‘H’, ‘D’, ‘W’, ‘M’, ‘Q’).

  • aggregation_method (str) – The aggregation method to apply (mean, median, sum, max, min).

models.pypsa_ev_vis.plot_curtailment_profile(curtailment_profile: DataFrame, show: bool = True, font_family: str = 'serif')[source]
models.pypsa_ev_vis.plot_ev_loads_interactive(ev_population: int, ev_load_results: dict, resample_freq: str, aggregation_method: str = 'mean')[source]

Plots interactive EV load profiles for different scenarios using Plotly.

Parameters: - scale (int): The penetration scale of EVs (e.g., 50, 100). - ev_load_results (dict): Dictionary containing EV load time series data for different networks. - resample_freq (str, optional): Frequency string to resample the time series data (e.g., ‘h’ for hourly, ‘D’ for daily, ‘M’ for Monthly, ‘Q’ for Quarterly).

If None, no resampling is applied.

  • aggregation_method (str, optional): Aggregation method (mean, median, sum, max, min). Default is ‘median’.

The function creates an interactive plot with different colors for each coordination type (uncoordinated, coordinated, v2g).

models.pypsa_ev_vis.plot_generators(unique_tag: str, network_names: list, network_dict: Dict[str, Network], resample_freq: str = 'D', save_to: str = 'vis', font_family: str = 'serif')[source]

Plot generator power output for different networks. Networks provided are ideally with same runtag.

Parameters:
  • unique_tag (str) – Unique tag to filter generators.

  • network_names (list) – List of network names. Ideally with same runtag

  • network_dict (dict) – Dictionary of networks.

  • resample_freq (str) – Resampling frequency for the data. “D” for daily, “h” for hourly, “W” for weekly, “M” for monthly, “Qe” for quarterly.

models.pypsa_ev_vis.plot_load_profiles(network_names: list, network_dict: Dict[str, Network], resample_freq: str, aggregation_method: str = 'mean', save_to='vis', font_family='serif')[source]

Plot load profiles for multiple networks on the same figure. Ideally give a list of network with same runtag.

Parameters:
  • network_names (list) – List of network names. Ideally give a list of network with same runtag.

  • network_dict (dict) – Dictionary containing PyPSA network objects.

  • resample_freq (str) – Resampling frequency (e.g., ‘H’, ‘D’, ‘W’).

  • Aggregation_method (str) – Aggregation method (mean, median, sum, max, min).

  • save_to (str) – Directory to save the plots.

models.pypsa_ev_vis.plot_selected_generators_power_output(search_keyword: str, network_name: str, network_dict: Dict[str, Network], save_to: str = 'vis', font_family: str = 'serif')[source]

Plots the power output of ‘New’ generators for a given network.

Parameters: - network_dict (dict): Dictionary containing PyPSA networks. - run_tag (int): The run tag to identify the network. - network_key (str): The key of the network to analyze (e.g., ‘pypsa_n_2021_uncoordinated_100_{run_tag}’).

General Utilities#

models.utils.load_config(config_file)[source]

This function loads the configuration file for PyPSA_BC config_file: Path + filename of the configuration file. (i.e. ../config/config.yaml)

models.utils.print_banner(message: str)[source]
models.utils.print_update(level: int = None, message: str = '--', alert: bool | None = False)[source]
models.utils.save_pickle(data, file_path)[source]

Configuration Parameters#

Fleet Simulation Parameters#

Parameter

Type

Description

Default

start_date

str

Simulation start date (YYYY-MM-DD)

“2021-01-01”

end_date

str

Simulation end date (YYYY-MM-DD)

“2021-01-02”

samples

int

Number of vehicles to simulate

10000

show_log

bool

Display simulation logs

False

EV Load Simulation Parameters#

Parameter

Type

Description

Default

ev_charging

str

Charging strategy

“coordinated”

ev_population

float

EV penetration rate (0.0-1.0)

0.8

optimization_horizon

int

Planning horizon in hours

24

min_soc

float

Minimum state of charge

0.2

Charging Strategy Options#

  • "coordinated" - Optimized charging timing

  • "uncoordinated" - User-driven charging patterns

  • "v2g" - Vehicle-to-grid capabilities

  • "hybrid" - Mixed coordination levels

PyPSA Model Parameters#

Parameter

Type

Description

Default

copperplate

bool

Single region simulation

True

update_data

bool

Update base network data

False

update_load

bool

Update demand data

False

resource_options

str

Resource capacity options

“full_potential”

total_load_scaling_factor

float

Load scaling multiplier

1.4

run_tag

str/int

Simulation identifier

Current date (YYYYMMDD)

Resource Options#

  • "full_potential" - Use maximum resource potential

  • "investment" - Use BCNexus investment scenarios

Data Structures#

Timespan Configuration#

timespan = {
    'start_date': str,  # Format: "YYYY-MM-DD"
    'end_date': str,    # Format: "YYYY-MM-DD"
}

Fleet Pattern Arguments#

commercial_pattern_args = {
    'start_date': str,
    'end_date': str,
    'samples': int,
    'vehicle_types': list,  # Optional
    'region': str,          # Optional
}

EV Load Arguments#

fleet_EV_args = {
    'start_date': str,
    'end_date': str,
    'ev_charging': str,
    'ev_population': float,
    'charging_power': float,     # Optional, kW
    'battery_capacity': float,   # Optional, kWh
    'efficiency': float,         # Optional
}

PyPSA Model Arguments#

pypsa_model_build_args = {
    'copperplate': bool,
    'update_data': bool,
    'update_load': bool,
    'resource_options': str,
    'total_load_scaling_factor': float,
    'run_tag': str or int,
    'solver': str,              # Optional
    'solver_options': dict,     # Optional
}

Input Data Requirements#

Vehicle Population Data#

Required input files and data sources:

  • ICBC Commercial Population: Commercial vehicle registration data

  • ICBC Passenger Population: Passenger vehicle registration data

  • Battery Specifications: Vehicle-specific capacity and range data

  • Travel Patterns: Regional driving behavior data

Network Data#

  • Load Profiles: Historical electricity demand data

  • Generation Resources: Renewable energy resource data

  • Network Topology: Transmission system configuration

  • Cost Parameters: Generation and transmission costs

Geospatial Data#

  • Regional Boundaries: Administrative and electrical regions

  • Population Distribution: Spatial population data

  • Infrastructure Locations: Charging station locations

Output Data Formats#

Fleet Simulation Outputs#

  • Vehicle Populations: Processed vehicle registration data

  • Travel Patterns: Simulated vehicle movement patterns

  • Charging Demand: Temporal charging requirements

EV Load Outputs#

  • Load Profiles: Hourly EV electricity demand

  • Spatial Distribution: Geographic load allocation

  • Charging Station Requirements: Infrastructure needs

PyPSA Model Outputs#

  • Optimal Capacity: Generation capacity expansion results

  • Operational Results: Unit commitment and dispatch

  • System Costs: Investment and operational cost breakdown

  • Grid Metrics: Reliability and performance indicators

Error Handling#

Common Exceptions#

class FleetSimulationError(Exception):
    """Raised when fleet simulation encounters an error"""
    pass

class EVLoadError(Exception):
    """Raised when EV load calculation fails"""
    pass

class PyPSAModelError(Exception):
    """Raised when PyPSA model execution fails"""
    pass

Error Codes#

Code

Description

Solution

FS001

Invalid date range

Check start_date < end_date

EV001

Invalid charging strategy

Use supported charging options

PS001

Solver convergence failure

Check model feasibility

IO001

Missing input data

Verify data file paths

Performance Considerations#

Computational Requirements#

  • Memory: Minimum 8GB RAM recommended

  • Storage: ~10GB for full simulation data

  • CPU: Multi-core processor recommended for large scenarios

  • Time: Runtime varies from minutes to hours depending on scenario complexity

Optimization Tips#

# For faster development iterations
quick_test_args = {
    'samples': 1000,           # Reduced sample size
    'copperplate': True,       # Single region
    'solver': 'highs',         # Fast solver
    'update_data': False,      # Skip data updates
}

# For production runs
production_args = {
    'samples': 100000,         # Full sample size
    'copperplate': False,      # Multi-region
    'solver': 'gurobi',        # Commercial solver
    'update_data': True,       # Fresh data
}

Extensions and Customization#

Adding New Charging Strategies#

def custom_charging_strategy(ev_fleet, grid_signals):
    """
    Custom charging strategy implementation
    
    Args:
        ev_fleet: EV fleet data
        grid_signals: Grid condition signals
        
    Returns:
        charging_schedule: Optimized charging schedule
    """
    # Implementation here
    pass

Custom Visualization#

import models.pypsa_ev_vis as vis

# Create custom plots
vis.plot_capacity_scenarios(scenario_results)
vis.plot_load_duration_curves(load_data)
vis.plot_generation_profiles(gen_data)

Integration Examples#

Basic Workflow#

import models.fleet_simulator.main as fleet
import models.fleet_EV_load_simulator.scripts.main as fleet_EV
from models.PyPSA_BC import run_pypsa_bc as pypsa_bc

# Define simulation period
timespan = {
    'start_date': "2021-01-01",
    'end_date': "2021-01-07"
}

# Step 1: Fleet simulation
commercial_pattern_args = {**timespan, 'samples': 50000}
fleet.run_fleet_simulation(**commercial_pattern_args, show_log=True)

# Step 2: EV load simulation  
fleet_EV_args = {
    **timespan,
    'ev_charging': "coordinated",
    'ev_population': 0.8,
}
fleet_EV.get_pypsa_ev_components(**fleet_EV_args)

# Step 3: PyPSA model execution
pypsa_model_build_args = {
    'copperplate': True,
    'update_data': True,
    'resource_options': 'full_potential',
    'total_load_scaling_factor': 1.2,
    'run_tag': 'example_run'
}
pypsa_bc.run(**fleet_EV_args, **pypsa_model_build_args)

Scenario Analysis#

# Multi-scenario analysis
scenarios = [
    {'ev_charging': 'uncoordinated', 'ev_population': 0.5},
    {'ev_charging': 'coordinated', 'ev_population': 0.5},
    {'ev_charging': 'v2g', 'ev_population': 0.5},
]

results = {}
for i, scenario in enumerate(scenarios):
    scenario_args = {**timespan, **scenario, 'run_tag': f'scenario_{i}'}
    results[f'scenario_{i}'] = pypsa_bc.run(**scenario_args, **pypsa_model_build_args)