API
This page provides the API Reference for the classes of EV-PV Simulator.
Each subsection below corresponds to a specific category of classes. All classes are documented using their docstrings and include constructor details, attributes, and available methods.
Vehicle definition
Classes related to the properties of the EV fleet.
Vehicle
- class evpv.vehicle.Vehicle(name, battery_capacity_kWh, consumption_kWh_per_km, max_charging_power_kW=inf)[source]
Bases:
objectA class to represent an Electric Vehicle (EV) with configurable attributes.
- __init__(name, battery_capacity_kWh, consumption_kWh_per_km, max_charging_power_kW=inf)[source]
Initializes the Vehicle class.
- Parameters:
name (str) – The name of the vehicle.
battery_capacity_kWh (float) – Battery capacity in kWh.
consumption_kWh_per_km (float) – Energy consumption in kWh/km.
max_charging_power_kW (float, optional) – [Default: float(“inf”)] Maximum charging power in kW.
- property battery_capacity_kWh: float
The battery capacity of the vehicle in kWh.
- Type:
float
- property consumption_kWh_per_km: float
The energy consumption of the vehicle per kilometer in kWh/km.
- Type:
float
- property max_charging_power_kW: float
The maximum charging power of the vehicle in kW.
- Type:
float
- property name: str
The name of the vehicle.
- Type:
str
VehicleFleet
- class evpv.vehiclefleet.VehicleFleet(total_vehicles, vehicle_types)[source]
Bases:
objectA class to represent a fleet of electric vehicles (EVs) with specified types and their shares.
- __init__(total_vehicles, vehicle_types)[source]
Initializes the VehicleFleet class.
- Parameters:
total_vehicles (int) – The total number of vehicles in the fleet.
vehicle_types (list) – A list of pairs [Vehicle, share], where each share is a value between 0 and 1.
- average_battery_capacity()[source]
Calculates the average battery capacity based on vehicle shares.
- Returns:
The average battery capacity in kWh.
- Return type:
float
- average_consumption()[source]
Calculates the average consumption based on vehicle shares.
- Returns:
The average consumption in kWh/km.
- Return type:
float
- property total_vehicles: int
The total number of vehicles in the fleet.
- Type:
int
- property vehicle_types: list
The list of vehicle types and their shares in the fleet.
- Type:
list
Region of interest
Classes related to region of interest, and how it is subdivided into traffic zones and populated with aggregated geospatial data.
Region
- class evpv.region.Region(region_geojson, population_raster, workplaces_csv, pois_csv, traffic_zone_properties)[source]
Bases:
objectA class to represent the region of interest, subdivided into traffic zones populated with aggregated geospatial data.
This class enables geospatial data input validation, subdivision into traffic zones, and the aggregation of data across these zones. Specifically, it facilitates the processing of population data from raster files, workplace and POI data from CSVs, and the generation of traffic zones based on configurable properties. The class also supports the export of traffic zone data for further analysis and visualization through CSV files and Folium maps.
Key Features:
Input Data Validation: Validates input data and recalculates/repopulates traffic zones on-the-fly when key properties are modified.
Traffic Zone Creation: Defines the traffic zones based of zone target size and shape, and provides the option to crop zones to the boundaries of the defined region.
Data Aggregation: Aggregates population, workplace, and POI data within each traffic zone.
Export and Visualizatio: Offers traffic zone export to CSV and visualization via Folium maps
Note: The region of interest is converted to a bounding box for zoning purposes. Set the crop_to_region parameter to True to retain only zones within the region’s boundaries.
- __init__(region_geojson, population_raster, workplaces_csv, pois_csv, traffic_zone_properties)[source]
Initializes the Region class with region data and properties for traffic zoning.
- Parameters:
region_geojson (str) – Path to the region geojson file.
population_raster (str) – Path to the population density raster file.
workplaces_csv (str) – Path to the CSV file containing workplace locations.
pois_csv (str) – Path to the CSV file containing points of interest (POI) locations.
traffic_zone_properties (dict) – A dictionary of traffic zone properties with keys: ‘target_size_km’ (float): Desired zone size in kilometers. ‘shape’ (str): Shape of zones (e.g., “rectangle”, “triangle”). ‘crop_to_region’ (bool): Whether to crop zones to the region of interest.
- average_zone_area_km2()[source]
Calculates the average area of the traffic zones in square kilometers.
- Returns:
The area in square kilometers.
- Return type:
float
- calculate_area_km2()[source]
Calculates the area of the region in square kilometers.
- Returns:
The area in square kilometers.
- Return type:
float
- centroid_coords()[source]
Get the coordinates of the centroid of the target area.
- Returns:
The (latitude, longitude) coordinates of the centroid.
- Return type:
tuple
- property pois: list
A list of tuples representing points of interest (longitude, latitude)
- Type:
list
- property population_density: str
The population density data from the raster file.
- Type:
str
- property region_geometry: Polygon
The shapely polygon representing the region of interest.
- Type:
Polygon
- to_map(filepath)[source]
Saves a folium map with simulation setup properties, including region geometry, zone geometry, population, workplaces, and POIs.
- Return type:
None
- property traffic_zone_properties: dict
A dictionary of traffic zone properties.
- Type:
dict
- property traffic_zones
Data representing the traffic zones in the region.
- Type:
pd.DataFrame
- property workplaces: list
A list of tuples representing workplaces (longitude, latitude)
- Type:
list
Mobility Demand
Classes related to mobility demand simulation for a the given region.
MobilitySimulator
- class evpv.mobilitysimulator.MobilitySimulator(vehicle_fleet, region, vehicle_allocation_params, trip_distribution_params)[source]
Bases:
objectA class to perform a mobility demand simulation for a given region.
This class simulates the demand of commuting demand based on a given vehicle fleet and region, supporting various methods for allocating vehicles spatially and performing trip distribution using spatial interaction modelling.
Key Features: - Vehicle allocation: Allocates vehicles across zones of a region based on user-defined methods, supporting the addition of randomness. - Trip distribution: Supports various spatial interaction models for trip distribution, such as the gravity and radiation models, allowing for customization of attraction and cost features to generate realistic commuting demand. - Self-calibrated gravity model: Integrates a self-calibrated gravity model that can be used without calibration, following the work of Lenormand et. al. 2016 - Routing and time/distance calculation: Enables flexible distance computation through both euclidean and road-based distances, with optional integration of OpenRouteService (ORS) API for advanced routing. - Distance offset: Allows for adding a distance offset added to the distance calculated for commuting.
Note: This class assumes the region is pre-defined and vehicle allocation parameters are specified in a dictionary. The use of the ors_key parameter enables routing with real road network data, while omitting it defaults to basic distance calculations.
- __init__(vehicle_fleet, region, vehicle_allocation_params, trip_distribution_params)[source]
Initializes the MobilitySimulator class.
- Parameters:
vehicle_fleet (VehicleFleet) – An instance of the VehicleFleet class.
region (Region) – An instance of the Region class.
vehicle_allocation_params (dict) – Method for vehicle spatial allocation generation. Keys: ‘method’ (str): The method used for trip generation (e.g., ‘population’). ‘randomness’ (float): A value between 0 and 1 to introduce randomness.
trip_distribution_params (dict) – Parameters specific to trip distribution. Keys: ‘road_to_euclidian_ratio’ (float): Ratio of road distance to Euclidean distance. ‘ors_key’ (str or None): Optional ORS (OpenRouteService) API key for routing. ‘model_type’ (str): Type of spatial interaction model (‘gravity’ or ‘radiation’). ‘attraction_feature’ (str): Feature to attract trips (e.g., ‘workplaces’). ‘cost_feature’ (str): Feature representing the cost of travel (e.g., ‘distance_road’). ‘distance_offset_km’ (float): Distance added to the distance calculated through trip distribution.
- property aggregated_zone_metrics: DataFrame
The aggregated_zone_metrics of the trip distribution model.
- Type:
pd.DataFrame
- property flows: DataFrame
The flows of the trip distribution model.
- Type:
pd.DataFrame
- is_valid_ors_connection(ors_key)[source]
Check if the ORS key is valid by creating a client.
- Parameters:
ors_key (str) – The ORS API key to validate.
- Returns:
True if the key is valid, False otherwise.
- Return type:
bool
- prod_constrained_gravity_exp(origin_n_trips, dest_attractivity_list, cost_list, beta)[source]
Estimates flows from origin to destinations using a production-constrained gravity model with exponential cost.
This is a special case of a spatial interaction model, where the cost function$f(d_{ij})$ follows an exponential law.
\[f(d_{ij})=e^{-d_{ij} \beta}\]See prod_constrained_gravity_power() for more details on spatial interaction models for trip distribution.
- Parameters:
origin_n_trips (float) – The total number of trips originating from the origin.
dest_attractivity_list (list[float]) – A list of attractivity values for each destination.
cost_list (list[float]) – A list of cost values corresponding to each destination.
beta (float, optional) – The exponent applied to the cost in the calculation.
- Returns:
An array of estimated flows to each destination.
- Return type:
np.ndarray
- prod_constrained_radiation(origin_n_trips, origin_attractivity, dest_attractivity_list, cost_list)[source]
Estimates flows from origin to destinations using a production-constrained radiation model.
This is a special case of an intervening opportunity spatial interaction model. In this case, the algorithm is more complex than gravity laws, as the cost function $f(d_{ij})$ includes the intervening opportunities located at a distance smaller than $d_{ij}$
\[f(d_{ij}) = ((A_i+s_{ij}).(A_i+A_j+s_{ij}))^{-1}\]\[s_{ij} = \sum_{k \neq i,j} A_k, ~ if ~ d_{ik}<d_{ij}\]with $s_{ij}$ being the intervening opportunities. Refer to prod_constrained_gravity_power() for other symbols.
To our knowledge, this model has been initially described in the following publication: Simini, F., González, M., Maritan, A. et al. A universal model for mobility and migration patterns. Nature 484, 96–100 (2012). https://doi.org/10.1038/nature10856.
While this model has the advantage of being parameter-free, it seems to not perform well at smaller scales.
- Parameters:
origin_n_trips (float) – The total number of trips originating from the origin.
origin_attractivity (float) – The attractivity of the origin.
dest_attractivity_list (list[float]) – A list of attractivity values for each destination.
cost_list (list[float]) – A list of cost values corresponding to each destination.
- Returns:
An array of estimated flows to each destination.
- Return type:
np.ndarray
- prod_constrained_radius(origin_n_trips, dest_attractivity_list, cost_list, radius=10)[source]
Estimates flows from origin to destinations using a production-constrained model based on distance radius.
This is a simplified example of a spatial interaction model. In this case, the product of attractiveness and cost is set to 1 if the destination falls within a specified radius, and 0 otherwise. This function is purely hypothetical and has no practical application justification. It can serve as a test function since it directs all flows to destinations within the given radius.
See prod_constrained_gravity_power() for more details on spatial interaction models for trip distribution.
- Parameters:
origin_n_trips (float) – The total number of trips originating from the origin.
dest_attractivity_list (list[float]) – A list of attractivity values for each destination.
cost_list (list[float]) – A list of cost values corresponding to each destination.
radius (float, optional) – The maximum distance for attractivity.
- Returns:
An array of estimated flows to each destination.
- Return type:
np.ndarray
- to_csv(filepath)[source]
Saves two CSV files with the main output data for flows and aggregated zone metrics.
- Parameters:
filepath (str) – Base path for the output files. Automatically appends suffixes “_flows” and “_aggregated_zone_metrics” before “.csv”.
- Return type:
None
- trip_distribution(batch_size=49)[source]
Distributes trips between traffic zones based on a spatial interaction model.
- Return type:
None
- property trip_distribution_params: dict
Parameters used for trip distribution.
- Type:
dict
- vehicle_allocation()[source]
Allocates vehicle (number of outflows) to traffic zones.
This method returns a new DataFrame containing the id of each zone and the allocated number of outflows (n_outflows).
- Returns:
A DataFrame with zone metrics, including id and n_outflows.
- Return type:
pd.DataFrame
- property vehicle_allocation_params: str
The method used for trip generation (e.g., ‘population’).
- Type:
str
- property vehicle_fleet: VehicleFleet
The vehicle fleet used in the simulation.
- Type:
Charging Demand
Classes related to charging demand simulation.
ChargingSimulator
- class evpv.chargingsimulator.ChargingSimulator(region, vehicle_fleet, mobility_demand, scenario, charging_efficiency)[source]
Bases:
objectA class to simulate the spatio-temporal daily charging demand of an electric vehicle fleet within a specified region.
This class models charging demand by integrating data from mobility simulations, region-specific characteristics, and vehicle fleet details, along with user-defined charging scenarios that include charging efficiency and behavior settings.
Key Features:
Spatial Charging Demand: Computes the charging demand per traffic zone within the specified region, enabling geographically detailed assessments of charging needs.
Temporal Charging Demand: Generates a load profile for each electric vehicle across all traffic zones using stochastic allocation. The number of vehicles charging and charging times are based on a state-of-charge (SOC) decision model, with a “dumb charging” strategy by default (where vehicles charge at full charger power upon arrival).
Scenario-Based Modeling: Allows flexible scenario configuration, including charging locations (with varying charger power levels), and custom arrival times at home and work, to reflect realistic charging patterns.
Smart Charging Compatibility: Enables the application of smart charging strategies in a secondary processing step, with pre-implemented strategies such as peak shaving to manage grid impact.
Note: This class assumes the use of a predefined region, vehicle fleet, and mobility demand simulator. Charging scenario parameters are provided as a dictionary, allowing flexible configuration of different charging behaviors.
- __init__(region, vehicle_fleet, mobility_demand, scenario, charging_efficiency)[source]
Initializes the ChargingSimulator class.
- Parameters:
region (Region) – An instance representing the geographic area for the simulation.
vehicle_fleet (VehicleFleet) – The electric vehicle fleet to be simulated.
mobility_demand (MobilitySimulator) – An instance of MobilitySimulator providing mobility demand data.
scenario (dict) – Configuration parameters for the charging scenario. Keys: ‘charging_power’ (float): The average power used for charging (in kW). ‘max_charging_sessions’ (int): Maximum number of charging sessions per day. ‘charging_schedule’ (str): Type of schedule for charging (e.g., ‘daytime’, ‘nighttime’).
charging_efficiency (float) – The efficiency factor for charging, ranging between 0 and 1.
- Prints:
Initialization details, including the chosen region, vehicle fleet characteristics, and scenario configuration.
- apply_smart_charging(location, charging_strategy, share, **kwargs)[source]
Apply a smart charging strategy to a subset of vehicles at specific locations.
- Parameters:
location (list) – List of location types (‘home’, ‘work’, ‘poi’).
charging_strategy (str) – The name of the charging strategy to apply.
share (float) – Proportion of vehicles participating (between 0 and 1).
kwargs – Additional parameters for specific charging strategies.
- property charging_efficiency: float
The charging efficiency (between 0 and 1).
- Type:
float
- chargingdemand_nvehicles_to_map(filepath)[source]
Creates a Folium map visualizing the number of vehicles charging at home, work, and POI locations.
- chargingdemand_pervehicle_to_map(filepath)[source]
Creates a Folium map visualizing the charging demand per vehicle at home, work, and POI.
- chargingdemand_total_to_map(filepath)[source]
Creates a Folium map visualizing the total charging demand at origin and destination points.S
- compute_spatial_demand()[source]
Compute the spatial charging demand and store results in the _spatial_demand DataFrame.
This method calculates the total and per-vehicle daily charging demand at each traffic zone based on the scenario configuration and zone-specific properties. It updates the spatial_demand attribute with the computed results.
- Returns:
This method does not return a value; it updates the internal _spatial_demand DataFrame.
- Return type:
None
- compute_temporal_demand(time_step, travel_time_home_work=0.5, soc_threshold_mean=0.6, soc_threshold_std_dev=0.2)[source]
Computes the temporal charging demand for vehicles, assigning their properties and calculating the charging profile based on specified parameters.
- Parameters:
time_step (float) – The time interval (in hours) for the charging profile computation.
travel_time_home_work (float) – Average travel time from home to work (in hours).
soc_threshold_mean (float) – Mean state of charge (SoC) threshold for vehicle charging.
soc_threshold_std_dev (float) – Standard deviation for the SoC threshold.
- Returns:
None
- property mobility_demand: MobilitySimulator
The mobility demand (i.e. flows between traffic zones) aggregated over all simulations provided.
- Type:
- property scenario: dict
The charging scenario.
- Type:
dict
- property spatial_demand: DataFrame
The spatial charging demand.
- Type:
pd.DataFrame
- property temporal_demand_profile: DataFrame
The temporal charging demand for each vehicle.
- Type:
pd.DataFrame
- property temporal_demand_profile_aggregated: DataFrame
The total temporal charging demand (aggregated over each vehicle).
- Type:
pd.DataFrame
- property temporal_demand_vehicle_properties: DataFrame
The properties of the vehicles that are charging today.
- Type:
pd.DataFrame
- to_csv(filepath)[source]
Saves two CSV files with the main output data for flows and aggregated zone metrics.
- Parameters:
filepath (str) – Base path for the output files. Automatically appends suffixes “_flows” and “_aggregated_zone_metrics” before “.csv”.
- property vehicle_fleet: VehicleFleet
The vehicle fleet used in the simulation.
- Type:
PV Simulation and EV-PV Complementarity
Classes related to PV Production and EV-PV Complementarity indicators.
PVSimulator
- class evpv.pvsimulator.PVSimulator(environment, pv_module, installation)[source]
Bases:
object- __init__(environment, pv_module, installation)[source]
Initializes the PVSimulator with validated environmental data, PV module parameters, and installation settings.
- Parameters:
environment (dict) – A dictionary containing environmental parameters with the following keys: - latitude (float): Latitude of the location (must be between -90 and 90). - longitude (float): Longitude of the location (must be between -180 and 180). - year (int): Year for the simulation.
pv_module (dict) – A dictionary containing PV module parameters with the following keys: - efficiency (float): Efficiency of the PV module (must be a positive decimal less than or equal to 1). - temperature_coefficient (float): Temperature coefficient of the module.
installation (dict) – A dictionary containing installation parameters with the following keys: - type (str): Type of installation (e.g., ‘groundmounted_fixed’). - system_losses (float): System losses as a decimal (must be between 0 and 1).
- calculate_angular_losses(lat_tilt_diff)[source]
Calculate the angular losses for a standard m-Si module based on the difference between latitude and tilt angle.
Martin, J.M. Ruiz, Calculation of the PV modules angular losses under field conditions by means of an analytical model, Solar Energy Materials and Solar Cells, Volume 70, Issue 1, 2001, Pages 25-38, ISSN 0927-0248, https://doi.org/10.1016/S0927-0248(00)00408-6.
Parameters: - lat_tilt_diff (float): The difference between latitude and tilt angle in degrees.
Returns: - float: Angular losses as a percentage.
- Return type:
float
- compute_pv_production()[source]
Compute the PV production and main KPIs using POA weather data.
- Returns:
- A DataFrame containing PV production, performance ratio, capacity factor,
operating temperature, and POA irradiance.
- Return type:
pd.DataFrame
- property environment: dict
- get_timezone(lat, lon)[source]
Get timezone string based on latitude and longitude.
- Parameters:
lat (float) – Latitude of the location.
lon (float) – Longitude of the location.
- Returns:
The timezone string if found, otherwise None.
- Return type:
str
- property installation: dict
- property pv_module: dict
- property results: DataFrame
EVPVSynergies
- class evpv.evpvsynergies.EVPVSynergies(pv, ev, pv_capacity_MW)[source]
Bases:
objectA class to analyze energy synergies between electric vehicle (EV) charging demand and photovoltaic (PV) production. The main metrics calculated include energy coverage, self-sufficiency, self-consumption, and excess PV ratios, as well as the Spearman correlation between EV and PV profiles over specific days.
This class requires:
A PVSimulator object, which holds the capacity factor time series data for PV production.
A ChargingSimulator object, which stores EV charging demand profiles.
The installed PV capacity (in megawatts, MW) as a float value.
- __init__(pv, ev, pv_capacity_MW)[source]
Initialize the EVPVSynergies object.
- Parameters:
pv (
PVSimulator) – Object containing PV production calculations.ev (
ChargingSimulator) – Object containing EV charging demand calculations.pv_capacity_MW (
float) – PV capacity in megawatts (MW).
- calculate_fully_solar_charging_vehicles(day, recompute_probability=0.0)[source]
Calculate the number of vehicles that can be fully charged using only solar power on a given day.
- Parameters:
day (str) – The day for which to perform the calculation, in ‘MM-DD’ format.
recompute_probability (float) – Probability (between 0 and 1) of recomputing EV demand to introduce randomness. Defaults to 0.0.
- Returns:
The number of vehicles fully charged using solar power.
- Return type:
int
- daily_metrics(start_date, end_date, n_points=100, recompute_probability=0.0)[source]
Compute all energy and synergy metrics over a given period.
- Parameters:
start_date (str) – Start date in ‘MM-DD’ format.
end_date (str) – End date in ‘MM-DD’ format.
n_points (int) – The number of points to sample for each day. Defaults to 100.
recompute_probability (float) – Probability (between 0 and 1) of recomputing EV demand for each day.
- Returns:
DataFrame containing all metrics for each day within the specified range.
- Return type:
pd.DataFrame
- energy_coverage_ratio(day='01-01')[source]
Calculate the ratio of PV production to EV charging demand for a given day.
- Parameters:
day (str) – The day in ‘MM-DD’ format to calculate the energy coverage ratio for. Defaults to ‘01-01’.
- Returns:
Energy coverage ratio for the specified day.
- Return type:
float
- property ev_charging_demand_MW: interp1d
Interpolation function for EV charging demand.
- Type:
interp1d
- ev_demand()[source]
Calculate the total EV charging demand by integrating over 24 hours.
- Returns:
Total EV charging demand (MWh) for the day.
- Return type:
float
- excess_pv_ratio(day='01-01', coincident_power=None)[source]
Calculate the excess PV ratio for a given day.
The excess PV ratio is the fraction of PV production that exceeds the EV demand.
- Parameters:
day (str) – The day in ‘MM-DD’ format to calculate the excess PV ratio for. Defaults to ‘01-01’.
coincident_power (float) – The coincident power if already calculated. Default is None.
- Returns:
Excess PV ratio for the specified day.
- Return type:
float
- property pv_capacity_MW: float
PV capacity in megawatts (MW).
- Type:
float
- property pv_capacity_factor: dict
Dictionary of interpolation functions for PV capacity factors by day.
- Type:
dict
- pv_power_MW(day='01-01')[source]
Return the PV power in megawatts for a given day as a function of time.
- Parameters:
day (str) – The day in ‘MM-DD’ format to calculate PV power for. Defaults to ‘01-01’.
- Returns:
A lambda function that calculates PV power (MW) at any given time.
- Return type:
callable
- pv_production(day='01-01')[source]
Calculate the total PV production for a given day by integrating over 24 hours.
- Parameters:
day (str) – The day in ‘MM-DD’ format to calculate PV production for. Defaults to ‘01-01’.
- Returns:
Total PV production (MWh) for the specified day.
- Return type:
float
- self_consumption_ratio(day='01-01', coincident_power=None)[source]
Calculate the self-consumption ratio for a given day.
The self-consumption ratio is the ratio of coincident power to total PV production.
- Parameters:
day (str) – The day in ‘MM-DD’ format to calculate the self-consumption ratio for. Defaults to ‘01-01’.
coincident_power (float) – The coincident power if already calculated. Default is None.
- Returns:
Self-consumption ratio for the specified day.
- Return type:
float
- self_sufficiency_ratio(day='01-01', coincident_power=None)[source]
Calculate the self-sufficiency ratio for a given day.
The self-sufficiency ratio is the ratio of coincident power (minimum of PV and EV demand) to EV demand.
- Parameters:
day (str) – The day in ‘MM-DD’ format to calculate the self-sufficiency ratio for. Defaults to ‘01-01’.
coincident_power (float) – The coincident power if already calculated. Default is None.
- Returns:
Self-sufficiency ratio for the specified day.
- Return type:
float
- spearman_correlation(day='01-01', n_points=100)[source]
Calculate the Spearman correlation between PV production and EV charging demand.
- Parameters:
day (str) – The day in ‘MM-DD’ format to calculate the Spearman correlation for. Defaults to ‘01-01’.
n_points (int) – The number of points to sample across the 24-hour period. Defaults to 100.
- Returns:
Spearman correlation coefficient and p-value.
- Return type:
tuple