### Install ACN-Sim Source: https://github.com/zach401/acnportal/blob/master/tutorials/lesson1_running_an_experiment.ipynb Install the acnportal library and its dependencies. This is typically run in environments like Google Colab. ```python # !git clone https://github.com/zach401/acnportal.git # !pip install acnportal/. ``` -------------------------------- ### Install ACN Portal Source: https://github.com/zach401/acnportal/blob/master/README.md Install the ACN Portal package using pip. This command should be run from the root directory of the cloned repository. ```bash pip install . ``` -------------------------------- ### Select Scheduling Algorithm Source: https://github.com/zach401/acnportal/blob/master/tutorials/lesson1_running_an_experiment.ipynb Instantiate a scheduling algorithm. This example uses the UncontrolledCharging algorithm, a built-in option. ```python sch = algorithms.UncontrolledCharging() ``` -------------------------------- ### Full Schedule Dictionary Example Source: https://github.com/zach401/acnportal/blob/master/tutorials/lesson2_implementing_a_custom_algorithm.ipynb This is an example of the expected output format for the schedule dictionary when an algorithm provides rates for multiple future time periods. ```python { 'CA-301': [32, 32, 32, 16, 16, ..., 8], 'CA-302': [8, 13, 13, 15, 6, ..., 0], ..., 'CA-408': [24, 24, 24, 24, 0, ..., 0] } ``` -------------------------------- ### Setup and Algorithm Initialization Source: https://github.com/zach401/acnportal/blob/master/tutorials/lesson2_implementing_a_custom_algorithm.ipynb Initializes experiment parameters, network, events, and two scheduling algorithms: a custom EarliestDeadlineFirstAlgo and a built-in SortedSchedulingAlgo. ```python from datetime import datetime import pytz import matplotlib.pyplot as plt import matplotlib.dates as mdates from copy import deepcopy from acnportal import algorithms from acnportal import acnsim # -- Experiment Parameters --------------------------------------------------------------------------------------------- timezone = pytz.timezone('America/Los_Angeles') start = timezone.localize(datetime(2018, 9, 5)) end = timezone.localize(datetime(2018, 9, 6)) period = 5 # minute voltage = 220 # volts default_battery_power = 32 * voltage / 1000 # kW site = 'caltech' # -- Network ----------------------------------------------------------------------------------------------------------- cn = acnsim.sites.caltech_acn(basic_evse=True, voltage=voltage) # -- Events ------------------------------------------------------------------------------------------------------------ API_KEY = 'DEMO_TOKEN' events = acnsim.acndata_events.generate_events(API_KEY, site, start, end, period, voltage, default_battery_power) # -- Scheduling Algorithm ---------------------------------------------------------------------------------------------- sch = EarliestDeadlineFirstAlgo(increment=1) sch2 = algorithms.SortedSchedulingAlgo(algorithms.least_laxity_first) ``` -------------------------------- ### Run Unit Tests Source: https://github.com/zach401/acnportal/blob/master/README.md Execute the project's unit tests after installation. Verbose output can be suppressed by removing the -v flag. ```bash python -m unittest discover -v ``` -------------------------------- ### Single Period Schedule Dictionary Example Source: https://github.com/zach401/acnportal/blob/master/tutorials/lesson2_implementing_a_custom_algorithm.ipynb This is an example of the expected output format for the schedule dictionary when an algorithm only calculates a target rate for the next time interval. Note that values are single-element lists. ```python { 'CA-301': [32], 'CA-302': [8], ..., 'CA-408': [24] } ``` -------------------------------- ### Configure Charging Network Source: https://github.com/zach401/acnportal/blob/master/tutorials/lesson1_running_an_experiment.ipynb Instantiate the ChargingNetwork object. This example uses the predefined CaltechACN network configuration. ```python # For this experiment we use the predefined CaltechACN network. cn = acnsim.sites.caltech_acn(basic_evse=True, voltage=voltage) ``` -------------------------------- ### get_prices Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/interface.md Retrieves a vector of electricity prices for a specified duration and start time. ```APIDOC ## get_prices(length: int, start: int | None = None) ### Description Get a vector of prices beginning at time start and continuing for length periods. ($/kWh) ### Parameters - **length** (int) - Required - Number of elements in the prices vector. One entry per period. - **start** (int) - Optional - Time step of the simulation where price vector should begin. If None, uses the current timestep of the simulation. ### Returns Array of floats where each entry is the price for the corresponding period. ($/kWh) ### Return Type np.ndarray[float] ``` -------------------------------- ### Initialize Simulator Source: https://github.com/zach401/acnportal/blob/master/tutorials/lesson1_running_an_experiment.ipynb Set up the simulation environment by combining the ChargingNetwork, Scheduling Algorithm, and EventQueue. Configure simulation parameters like period and max_recomp. ```python sim = acnsim.Simulator(cn, sch, events, start, period=period, verbose=False) ``` -------------------------------- ### Define Experiment Parameters Source: https://github.com/zach401/acnportal/blob/master/tutorials/lesson1_running_an_experiment.ipynb Set up key parameters for the simulation, including timezone, start/end times, time interval period, network voltage, default battery power, and site identifier. ```python # Timezone of the ACN we are using. timezone = pytz.timezone('America/Los_Angeles') # Start and End times are used when collecting data. start = timezone.localize(datetime(2018, 9, 5)) end = timezone.localize(datetime(2018, 9, 6)) # How long each time discrete time interval in the simulation should be. period = 5 # minutes # Voltage of the network. voltage = 220 # volts # Default maximum charging rate for each EV battery. default_battery_power = 32 * voltage / 1000 # kW # Identifier of the site where data will be gathered. site = 'caltech' ``` -------------------------------- ### index_of_evse(station_id) Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/simulator.md Gets the numerical index of an EVSE given its station ID. ```APIDOC ## index_of_evse(station_id) ### Description Return the numerical index of the EVSE given by station_id in the (ordered) dictionary of EVSEs. ``` -------------------------------- ### Earliest Deadline First Algorithm Implementation Source: https://github.com/zach401/acnportal/blob/master/tutorials/lesson2_implementing_a_custom_algorithm.ipynb This custom algorithm inherits from BaseAlgorithm and implements the schedule method to assign charging rates based on EV departure times. It sorts EVs by estimated departure and allocates charging capacity, respecting network constraints. ```python from acnportal.algorithms import BaseAlgorithm class EarliestDeadlineFirstAlgo(BaseAlgorithm): """ Algorithm which assigns charging rates to each EV in order of estimated departure time. Implements abstract class BaseAlgorithm. For this algorithm EVs will first be sorted by estimated departure time. We will then allocate as much current as possible to each EV in order until the EV is finished charging or an infrastructure limit is met. Args: increment (number): Minimum increment of charging rate. Default: 1. """ def __init__(self, increment=1): super().__init__() self._increment = increment self.max_recompute = 1 def schedule(self, active_evs): schedule = {ev.station_id: [0] for ev in active_evs} # Next, we sort the active_evs by their estimated departure time. sorted_evs = sorted(active_evs, key=lambda x: x.estimated_departure) # We now iterate over the sorted list of EVs. for ev in sorted_evs: # First try to charge the EV at its maximum rate. Remember that each schedule value # must be a list, even if it only has one element. schedule[ev.station_id] = [self.interface.max_pilot_signal(ev.station_id)] # If this is not feasible, we will reduce the rate. # interface.is_feasible() is one way to interact with the constraint set # of the network. We will explore another more direct method in lesson 3. while not self.interface.is_feasible(schedule, 0): # Since the maximum rate was not feasible, we should try a lower rate. schedule[ev.station_id][0] -= self._increment # EVs should never charge below 0 (i.e. discharge) so we will clip the value at 0. if schedule[ev.station_id][0] < 0: schedule[ev.station_id] = [0] break return schedule ``` -------------------------------- ### Run Simulation Source: https://github.com/zach401/acnportal/blob/master/tutorials/lesson1_running_an_experiment.ipynb Execute the simulation using the configured Simulator object. ```python sim.run() ``` -------------------------------- ### Run Built-in Algorithm Simulation for Comparison Source: https://github.com/zach401/acnportal/blob/master/tutorials/lesson2_implementing_a_custom_algorithm.ipynb Initializes and runs the ACN simulator with the built-in Earliest Deadline First algorithm for comparison. ```python # For comparison we will also run the builtin earliest deadline first algorithm sim2 = acnsim.Simulator(deepcopy(cn), sch2, deepcopy(events), start, period=period, verbose=False) sim2.run() ``` -------------------------------- ### run() Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/simulator.md Executes the simulation until the event queue is empty, processing events, scheduling, and network updates. ```APIDOC ## run() ### Description If scheduler is not None, run the simulation until the event queue is empty. The run function is the heart of the simulator. It triggers all actions and keeps the simulator moving forward. Its actions are (in order): > 1. Get current events from the event queue and execute them. > 2. If necessary run the scheduling algorithm. > 3. Send pilot signals to the network. > 4. Receive back actual charging rates from the network and store the results. ### Returns None ### Raises **TypeError** – If called when the scheduler attribute is None. The run() method requires a BaseAlgorithm-like scheduler to execute. ``` -------------------------------- ### Run Custom Algorithm Simulation Source: https://github.com/zach401/acnportal/blob/master/tutorials/lesson2_implementing_a_custom_algorithm.ipynb Initializes and runs the ACN simulator with the custom scheduling algorithm. ```python # -- Simulator --------------------------------------------------------------------------------------------------------- sim = acnsim.Simulator(deepcopy(cn), sch, deepcopy(events), start, period=period, verbose=False) sim.run() ``` -------------------------------- ### Import Necessary Libraries Source: https://github.com/zach401/acnportal/blob/master/tutorials/lesson1_running_an_experiment.ipynb Import core modules from acnportal and other libraries for simulation, algorithms, and plotting. ```python import pytz from datetime import datetime import matplotlib.pyplot as plt from acnportal import acnsim from acnportal import algorithms ``` -------------------------------- ### Change Directory to acnportal Source: https://github.com/zach401/acnportal/blob/master/CONTRIBUTING.md Navigate into the cloned acnportal project directory. ```bash cd acnportal ``` -------------------------------- ### get_constraints Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/interface.md Retrieves the constraint matrix, corresponding EVSE IDs, and limits for the network simulation. ```APIDOC ## get_constraints() ### Description Get the constraint matrix and corresponding EVSE ids for the network. ### Returns - **constraint_matrix** (np.ndarray) - Matrix representing the constraints of the network. Each row is a constraint and each column is an index. - **constraint_limits** (np.ndarray) - Vector of bounding limits for each constraint (1 for each constraint). - **constraint_ids** (List[str]) - Names of each constraint. - **station_ids** (List[str]) - Names of each station. ### Return Type Constraint ``` -------------------------------- ### ChargingNetwork Class Initialization Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/network/charging_network.md Initializes the ChargingNetwork with optional violation tolerances. ```APIDOC ## class acnportal.acnsim.network.ChargingNetwork(violation_tolerance: float = 1e-05, relative_tolerance: float = 1e-07) The ChargingNetwork class describes the infrastructure of the charging network with information about the types of the charging station_schedule. * **Parameters:** * **violation_tolerance** (*float*) – Absolute amount by which an input charging schedule may violate network constraints (A). * **relative_tolerance** (*float*) – Relative amount by which an input charging schedule may violate network constraints (A). ``` -------------------------------- ### Push Changes to Your Fork Source: https://github.com/zach401/acnportal/blob/master/CONTRIBUTING.md Upload your local commits to your personal fork on GitHub. ```bash git push origin is-feasible-speedups ``` -------------------------------- ### step(new_schedule) Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/simulator.md Advances the simulation by one iteration using a provided schedule, returning a flag indicating completion. ```APIDOC ## step(new_schedule) ### Description Step the simulation until the next schedule recompute is required. The step function executes a single iteration of the run() function. However, the step function updates the simulator with an input schedule rather than query the scheduler for a new schedule when one is required. Also, step will return a flag if the simulation is done. ### Parameters * **new_schedule** (*Dict[str, List[number]]*) – Dictionary mapping station ids to a schedule of pilot signals. ### Returns True if the simulation is complete. ### Return type bool ``` -------------------------------- ### Calculate Proportion of Energy Delivered Source: https://github.com/zach401/acnportal/blob/master/tutorials/lesson1_running_an_experiment.ipynb Use the `proportion_of_energy_delivered` method to find the fraction of total user energy demand that was met by the simulation. Requires a Simulator object. ```python total_energy_prop = acnsim.proportion_of_energy_delivered(sim) print('Proportion of requested energy delivered: {0}'.format(total_energy_prop)) ``` -------------------------------- ### infrastructure_info Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/interface.md Returns a copy of the InfrastructureInfo object, providing details about the charging infrastructure. ```APIDOC ## infrastructure_info() ### Description Returns a copy of the InfrastructureInfo object generated from interface. ### Returns A description of the charging infrastructure. ### Return Type InfrastructureInfo ``` -------------------------------- ### BaseEVSE Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/models.md Abstract base class for Electric Vehicle Supply Equipment (charging stations). Subclasses must implement specific methods for charging rates and pilot signals. ```APIDOC ## Class acnportal.acnsim.models.evse.BaseEVSE(station_id) ### Description Abstract base class to model Electric Vehicle Supply Equipment (charging station). This class is meant to be inherited from to implement new EVSEs. Subclasses must implement the max_rate, allowable_pilot_signals, and _valid_rate methods. ### Properties #### _station_id - **Type:** str - **Description:** Unique identifier of the EVSE. #### _ev - **Type:** [EV](#acnportal.acnsim.models.ev.EV) - **Description:** EV currently connected the the EVSE. #### _current_pilot - **Type:** float - **Description:** Pilot signal for the current time step. [acnsim units] #### is_continuous - **Type:** bool - **Description:** If True, this EVSE accepts a continuous range of pilot signals. If False, this EVSE accepts only a discrete set of pilot signals. #### allowable_pilot_signals - **Description:** Returns the allowable pilot signal levels for this EVSE. NOT IMPLEMENTED IN BaseEVSE. This method MUST be implemented in all subclasses. - **Returns:** List of acceptable pilot signal values or an interval of acceptable pilot signal values. - **Return type:** List[float] #### current_pilot - **Description:** Return pilot signal for the current time step. - **Return type:** float #### ev - **Description:** Return EV currently connected the the EVSE. - **Return type:** EV #### max_rate - **Description:** Return maximum charging current allowed by the EVSE. - **Return type:** float #### min_rate - **Description:** Return minimum charging current allowed by the EVSE. - **Return type:** float ### Methods #### plugin(ev) - **Description:** Method to attach an EV to the EVSE. - **Parameters:** - **ev** ([*EV*](#acnportal.acnsim.models.ev.EV)) – EV which should be attached to the EVSE. - **Returns:** None. - **Raises:** - [**StationOccupiedError**](#acnportal.acnsim.models.evse.StationOccupiedError) – Exception raised when plugin is called by an EV is already attached to the EVSE. #### set_pilot(pilot, voltage, period) - **Description:** Apply a new pilot signal to the EVSE. Before applying the new pilot, this method first checks if the pilot is allowed. If it is not, an InvalidRateError is raised. If the rate is valid, it is forwarded on to the attached EV if one is present. This method is also where EV charging is triggered. Thus it must be called in every time time period where the attached EV should receive charge. - **Parameters:** - **pilot** (float) – New pilot (control signal) to be sent to the attached EV. [A] - **voltage** (float) – AC voltage provided to the battery charger. [V] - **period** (float) – Length of the charging period. [minutes] - **Returns:** None. - **Raises:** - [**InvalidRateError**](#acnportal.acnsim.models.evse.InvalidRateError) – Exception raised when pilot is not allowed by the EVSE. #### station_id - **Description:** Return unique identifier of the EVSE. - **Return type:** str #### unplug() - **Description:** Method to remove an EV currently attached to the EVSE. Sets ev to None and current_pilot to 0. - **Returns:** None ``` -------------------------------- ### Plotting Aggregated Current for Two EDF Simulations Source: https://github.com/zach401/acnportal/blob/master/tutorials/lesson2_implementing_a_custom_algorithm.ipynb This snippet visualizes the aggregated current from two different EDF (Event-Driven Framework) simulations. It sets up date locators and formatters for the x-axis to display datetimes clearly. Use this to compare the performance of your custom algorithm against a baseline. ```python # Get list of datetimes over which the simulations were run. sim_dates = mdates.date2num(acnsim.datetimes_array(sim)) sim2_dates = mdates.date2num(acnsim.datetimes_array(sim2)) # Set locator and formatter for datetimes on x-axis. locator = mdates.AutoDateLocator(maxticks=6) formatter = mdates.ConciseDateFormatter(locator) fig, axs = plt.subplots(1, 2, sharey=True, sharex=True) axs[0].plot(sim_dates, acnsim.aggregate_current(sim), label='Our EDF') axs[1].plot(sim2_dates, acnsim.aggregate_current(sim2), label='Included EDF') axs[0].set_title('Our EDF') axs[1].set_title('Included EDF') for ax in axs: ax.set_ylabel('Current (A)') for label in ax.get_xticklabels(): label.set_rotation(40) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter) plt.show() ``` -------------------------------- ### Clone acnportal Repository Source: https://github.com/zach401/acnportal/blob/master/CONTRIBUTING.md Clone the acnportal project to your local computer after forking it on GitHub. ```bash git clone https://github.com/your-username/acnportal.git ``` -------------------------------- ### Generate Simulation Events Source: https://github.com/zach401/acnportal/blob/master/tutorials/lesson1_running_an_experiment.ipynb Generate events for the simulation using the acndata_events utility. Requires an API key and parameters like site, start/end times, period, and voltage. ```python API_KEY = 'DEMO_TOKEN' events = acnsim.acndata_events.generate_events(API_KEY, site, start, end, period, voltage, default_battery_power) ``` -------------------------------- ### EV Class Initialization Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/models.md Initializes an Electrical Vehicle (EV) object with its charging session details and battery information. ```APIDOC ## EV Class Initialization ### Description Initializes an Electrical Vehicle (EV) object with its charging session details and battery information. ### Parameters * **arrival** (*int*) – Arrival time of the ev. [periods] * **departure** (*int*) – Departure time of the ev. [periods] * **requested_energy** (*float*) – Energy requested by the ev on arrival. [kWh] * **station_id** (*str*) – Identifier of the station used by this ev. * **session_id** (*str*) – Identifier of the session belonging to this ev. * **battery** (*Battery-like*) – Battery object to be used by the EV. * **estimated_departure** (*int*) – Optional: Estimated departure time of the ev. [periods] ``` -------------------------------- ### Create a New Feature Branch Source: https://github.com/zach401/acnportal/blob/master/CONTRIBUTING.md Create a new branch for your feature development, using a descriptive name. ```bash git checkout -b is-feasible-speedups ``` -------------------------------- ### EventQueue Methods Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/events/index.md Provides methods for interacting with the event queue, including adding, retrieving, and checking the status of events. ```APIDOC ## EventQueue Methods ### Description Methods for managing and querying the event queue. ### Methods - `add_event(event)`: Adds a single event to the queue. - `add_events(events)`: Adds a list of events to the queue. - `empty()`: Returns `True` if the queue is empty, `False` otherwise. - `get_current_events()`: Returns a list of events scheduled for the current timestamp. - `get_event()`: Retrieves and removes the next event from the queue. - `get_last_timestamp()`: Returns the timestamp of the last event added to the queue. ### Parameters - `event` (Event): The event object to add. - `events` (list[Event]): A list of event objects to add. ### Returns - `add_event`, `add_events`: None - `empty`: bool - `get_current_events`: list[Event] - `get_event`: Event - `get_last_timestamp`: int ``` -------------------------------- ### is_feasible Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/interface.md Checks if a given set of load currents is feasible within the network constraints, with options for linearization and tolerance adjustments. ```APIDOC ## is_feasible(load_currents: Dict[str, List[float]], linear: bool = False, violation_tolerance: float | None = None, relative_tolerance: float | None = None) ### Description Return if a set of current magnitudes for each load are feasible. Wraps Network’s is_feasible method. For a given constraint, the larger of the violation_tolerance and relative_tolerance is used to evaluate feasibility. ### Parameters - **load_currents** (Dict[str, List[float]]) - Required - Dictionary mapping load_ids to schedules of charging rates. - **linear** (bool) - Optional - If True, linearize all constraints to a more conservative but easier to compute constraint by ignoring the phase angle and taking the absolute value of all load coefficients. Default False. - **violation_tolerance** (float) - Optional - Absolute amount by which schedule may violate network constraints. Default None, in which case the network’s violation_tolerance attribute is used. - **relative_tolerance** (float) - Optional - Relative amount by which schedule may violate network constraints. Default None, in which case the network’s relative_tolerance attribute is used. ### Returns If load_currents is feasible at time t according to this set of constraints. ### Return Type bool ``` -------------------------------- ### plugin Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/network/charging_network.md Attaches an Electric Vehicle (EV) to a specific EVSE. This method allows for managing EV connections to charging stations. ```APIDOC ## plugin(ev: EV, station_id: str = None) -> None ### Description Attach EV to a specific EVSE. ### Parameters * **ev** (EV) – EV object which will be attached to the EVSE. * **station_id** (*str*) – ID of the EVSE. ### Returns None ### Raises **KeyError** – Raised when the station id has not yet been registered. ``` -------------------------------- ### is_feasible Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/network/charging_network.md Checks if a given schedule of EVSE load currents is feasible with respect to network constraints. It allows for absolute and relative tolerances to define the violation limits. ```APIDOC ## is_feasible(schedule_matrix: ndarray, linear: bool = False, violation_tolerance: float | None = None, relative_tolerance: float | None = None) -> bool ### Description Return if a set of current magnitudes for each load are feasible. For a given constraint, the larger of the violation_tolerance and relative_tolerance is used to evaluate feasibility. ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters * **schedule_matrix** (*np.Array*) – 2-D matrix with each row corresponding to an EVSE and each column corresponding to a time index in the schedule. * **linear** (*bool*) – If True, linearize all constraints to a more conservative but easier to compute constraint by ignoring the phase angle and taking the absolute value of all load coefficients. Default False. * **violation_tolerance** (*float*) – Absolute amount by which schedule_matrix may violate network constraints. Default None, in which case the network’s violation_tolerance attribute is used. * **relative_tolerance** (*float*) – Relative amount by which schedule_matrix may violate network constraints. Default None, in which case the network’s relative_tolerance attribute is used. ### Returns If load_currents is feasible at time t according to this set of constraints. ### Return type bool ``` -------------------------------- ### unittest Main Execution Block Source: https://github.com/zach401/acnportal/blob/master/CONTRIBUTING.md End unittest files with this block to ensure proper execution when run directly. ```python if __name__ == '__main__': unittest.main() ``` -------------------------------- ### SessionInfo Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/interface.md Class to store information relevant to a charging session. ```APIDOC ## class SessionInfo(station_id: str, session_id: str, requested_energy: float, energy_delivered: float, arrival: int, departure: int, estimated_departure: int | None = None, current_time: int = 0, min_rates: float | List[float] = 0, max_rates: float | List[float] = inf) ### Description Class to store information relevant to a charging session. ### Parameters - **station_id** (str) - Unique identifier of the station (EVSE) where the session takes place. - **session_id** (str) - Unique identifier of the charging session. - **requested_energy** (float) - Energy requested by the user during the session. [kWh] - **energy_delivered** (float) - Energy delivered already during the session. [kWh] - **arrival** (int) - Time index when the session begins. - **departure** (int) - Time index when the session ends. - **estimated_departure** (int | None) - Optional - Time index when the user estimates the session will end. - **current_time** (int) - Time index of the current time. - **min_rates** (float | List[float]) - Lower bound for the charging rate of the session. If List (or np.array) length should be departure - arrival and each entry is a lower bound for the corresponding time period. - **max_rates** (float | List[float]) - Upper bound for the charging rate of the session. If List (or np.array) length should be departure - arrival and each entry is a upper bound for the corresponding time period. ### Properties #### arrival_offset - **return_value** (int) - Return the time (in periods) until the arrival of the EV represented by this Session, or 0 if the EV has already arrived. #### remaining_demand - **return_value** (float) - Return the Session’s remaining demand in kWh. #### remaining_time - **return_value** (int) - Return the time remaining until the EV represented by this Session departs, or the time between the EV’s departure and arrival if the EV has not arrived yet. If the EV has already departed, return 0. ``` -------------------------------- ### demand_charge Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/analysis.md Calculate the total demand charge of the simulation. ```APIDOC ## demand_charge(sim, tariff=None) ### Description Calculate the total demand charge of the simulation. This is only an accurate depiction of true demand charge if the simulation is exactly one billing period long. ### Parameters * **sim** (*Simulator*) – A Simulator object which has been run. * **tariff** (*TimeOfUseTariff*) – Tariff structure to use when calculating energy costs. ### Returns Total demand charge incurred by the simulation ($) ### Return type float ``` -------------------------------- ### Current Class Initialization Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/network/current.md Initializes a Current object, representing currents in the ACNSIM network. It can be initialized with loads, which map load IDs to their coefficients in the aggregate current. ```APIDOC ## class acnportal.acnsim.network.Current ### Description Initializes a Current object, representing currents in the ACNSIM network. It can be initialized with loads, which map load IDs to their coefficients in the aggregate current. ### Parameters #### loads - **loads** (Dict[str, number] | str | List[str] | pd.Series | None) - Required - Dictionary which maps a load_id to its coefficient in the aggregate current. If dict, a dictionary mapping load_ids to coefficients. If str a load_id. If list, a list of load_ids. Default None. If None, loads will begin as an empty dict. ``` -------------------------------- ### Add Upstream Repository Source: https://github.com/zach401/acnportal/blob/master/CONTRIBUTING.md Add the official acnportal repository as an upstream remote to track its changes. ```bash git remote add upstream https://github.com/zach401/acnportal.git ``` -------------------------------- ### charging_rates_as_df() Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/simulator.md Returns the charging rates for all EVs over the simulation as a pandas DataFrame. ```APIDOC ## charging_rates_as_df() ### Description Return the charging rates as a pandas DataFrame, with EVSE id as columns and iteration as index. ### Returns A DataFrame containing the charging rates of the simulation. Columns are EVSE id, and the index is the iteration. ### Return type pandas.DataFrame ``` -------------------------------- ### EV Methods Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/models.md Provides methods to interact with the EV object, such as charging the vehicle or resetting its state. ```APIDOC ## EV Methods ### Description Provides methods to interact with the EV object, such as charging the vehicle or resetting its state. ### Methods #### charge(pilot, voltage, period) Method to “charge” the ev. * **Parameters:** * **pilot** (*float*) – Pilot signal passed to the battery. [A] * **voltage** (*float*) – AC voltage provided to the battery charger. [V] * **period** (*float*) – Length of the charging period. [minutes] * **Returns:** Actual charging rate of the ev. [A] * **Return type:** float #### reset() Reset battery back to its initialization. Also reset energy delivered. * **Returns:** None. #### update_station_id(station_id) Method to update the station where EV will charge. * **Parameters:** * **station_id** (*str*) – The new station identifier. ``` -------------------------------- ### energy_cost Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/analysis.md Calculate the total energy cost of the simulation. ```APIDOC ## energy_cost(sim, tariff=None) ### Description Calculate the total energy cost of the simulation. ### Parameters * **sim** (*Simulator*) – A Simulator object which has been run. * **tariff** (*TimeOfUseTariff*) – Tariff structure to use when calculating energy costs. ### Returns Total energy cost of the simulation ($) ### Return type float ``` -------------------------------- ### constraints_as_df Method Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/network/charging_network.md Returns the network constraints formatted as a pandas DataFrame. ```APIDOC #### constraints_as_df() → DataFrame Returns the network constraints in a pandas DataFrame. The index is the constraint IDs, and the columns are station IDs. The magnitudes (constraint limits) must be accessed separately. * **Returns:** The network constraints as a DataFrame. * **Return type:** pd.DataFrame ``` -------------------------------- ### StationOccupiedError Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/network/index.md Custom exception raised when attempting to occupy an already occupied station. ```APIDOC ## StationOccupiedError ### Description Exception raised when an operation targets a charging station that is already occupied. ``` -------------------------------- ### ChargingNetwork Methods Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/network/index.md Provides methods for managing and querying the state of the charging network, including active EVs, station IDs, constraints, and charging rates. ```APIDOC ## ChargingNetwork Class ### Description Represents the charging network and provides methods to manage its state and constraints. ### Methods - **`active_evs()`** - Description: Returns a list of active Electric Vehicles in the network. - Returns: List of active EVs. - **`active_station_ids()`** - Description: Returns a list of IDs for active charging stations. - Returns: List of station IDs. - **`add_constraint(constraint)`** - Description: Adds a new constraint to the network. - Parameters: - `constraint`: The constraint object to add. - **`constraint_current()`** - Description: Returns the current constrained charging rates. - Returns: Current charging rates under constraints. - **`constraints_as_df()`** - Description: Returns all network constraints as a pandas DataFrame. - Returns: DataFrame of constraints. - **`current_charging_rates()`** - Description: Returns the current charging rates for all stations. - Returns: Dictionary of current charging rates. - **`get_ev(ev_id)`** - Description: Retrieves a specific Electric Vehicle by its ID. - Parameters: - `ev_id`: The ID of the Electric Vehicle. - Returns: The Electric Vehicle object. - **`is_feasible()`** - Description: Checks if the current network state is feasible. - Returns: Boolean indicating feasibility. - **`phase_angles()`** - Description: Returns the phase angles of the network voltages. - Returns: Dictionary of phase angles. - **`plugin(ev, station_id)`** - Description: Simulates an EV plugging into a charging station. - Parameters: - `ev`: The Electric Vehicle object. - `station_id`: The ID of the charging station. - **`post_charging_update()`** - Description: Updates the charging status after a charging event. - **`register_evse(evse_id, station_id)`** - Description: Registers an EVSE (Electric Vehicle Supply Equipment) with a station. - Parameters: - `evse_id`: The ID of the EVSE. - `station_id`: The ID of the station. - **`remove_constraint(constraint_id)`** - Description: Removes a constraint from the network by its ID. - Parameters: - `constraint_id`: The ID of the constraint to remove. - **`station_ids()`** - Description: Returns a list of all station IDs in the network. - Returns: List of station IDs. - **`unplug(ev_id)`** - Description: Simulates an EV unplugging from the network. - Parameters: - `ev_id`: The ID of the Electric Vehicle. - **`update_constraint(constraint_id, new_constraint_data)`** - Description: Updates an existing constraint. - Parameters: - `constraint_id`: The ID of the constraint to update. - `new_constraint_data`: The new data for the constraint. - **`update_pilots(ev_id, new_pilot_signal)`** - Description: Updates the pilot signal for a specific EV. - Parameters: - `ev_id`: The ID of the Electric Vehicle. - `new_pilot_signal`: The new pilot signal value. - **`voltages()`** - Description: Returns the voltages of the network. - Returns: Dictionary of voltages. ``` -------------------------------- ### current_unbalance Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/analysis.md Calculate the current unbalance for each time in simulation. ```APIDOC ## current_unbalance(sim, phase_ids, unbalance_type='NEMA', type=None) ### Description Calculate the current unbalance for each time in simulation. Supports two definitions of unbalance: NEMA definition. ### Parameters * **sim** (*Simulator*) – A Simulator object which has been run. * **phase_ids** (*List[str]*) – List of length 3 where each element is the identifier of phase A, B, and C respectively. * **unbalance_type** (*str*) – Method to use for calculating phase unbalance. Acceptable values are ‘NEMA’. ### Returns Time series of current unbalance as a list with one value per timestep. ### Return type List[float] ``` -------------------------------- ### total_energy_requested Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/analysis.md Calculates the total amount of energy requested in kilowatt-hours (kWh) during the simulation. ```APIDOC ## total_energy_requested(sim) ### Description Calculate total energy requested in kWh. ### Parameters #### Path Parameters * **sim** (*Simulator*) - A Simulator object which has been run. ### Returns Total energy requested during the simulation [kWh] ### Return type float ``` -------------------------------- ### proportion_of_demands_met Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/analysis.md Calculates the percentage of charging sessions where the energy request was fully met, considering a given threshold for session completion. ```APIDOC ## proportion_of_demands_met(sim, threshold=0.1) ### Description Calculate the percentage of charging sessions where the energy request was met. ### Parameters #### Path Parameters * **sim** (*Simulator*) - A Simulator object which has been run. * **threshold** (*float*) - Close to finished a session should be to be considered finished. Default: 0.1. [kW] ### Returns Proportion of sessions where the energy demand was fully met. ### Return type float ``` -------------------------------- ### EventQueue Class Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/events/event_queue.md The EventQueue class manages a collection of simulation events. It allows for adding single or multiple events, retrieving events based on time, and checking the queue's status. ```APIDOC ## class acnportal.acnsim.events.EventQueue(events=None) Queue which stores simulation events. * **Parameters:** **events** (*List* *[Event]* ) – A list of Event-like objects. ### add_event(event) Add an event to the queue. * **Parameters:** **event** (*Event like*) – An Event-like object. * **Returns:** None ### add_events(events) Add multiple events at a time to the queue. * **Parameters:** **events** (*List*[Event like]*) – A list of Event-like objects. * **Returns:** None ### empty() Return if the queue is empty. * **Returns:** True if the queue is empty. * **Return type:** bool ### get_current_events(timestep) Return all events occurring before or during timestep. * **Parameters:** **timestep** (*int*) – Time index in periods. * **Returns:** List of all events occurring before or during timestep. * **Return type:** List[Event] ### get_event() Return the next event in the queue. * **Returns:** The next event in the queue. * **Return type:** Event like ### get_last_timestamp() Return the timestamp of the last event (chronologically) in the event queue * **Returns:** Last timestamp in the event queue, or None if the event queue is empty. * **Return type:** int ### property queue Return the queue of events ``` -------------------------------- ### Access Peak Demand Source: https://github.com/zach401/acnportal/blob/master/tutorials/lesson1_running_an_experiment.ipynb Retrieve the peak aggregate current demand from the simulation using the `peak` property of the Simulator object. This value is crucial for system sizing and cost estimation. ```python print('Peak aggregate current: {0} A'.format(sim.peak)) ``` -------------------------------- ### count_sessions Source: https://github.com/zach401/acnportal/blob/master/docs/acndata/data_client.md Returns the number of sessions that match the specified site and optional conditions. ```APIDOC ## count_sessions ### Description Return the number of sessions which match the given query. ### Method Not applicable (Python method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **site** (str) - Required - ACN ID from which data should be gathered. * **cond** (str) - Optional - String of conditions. See API reference for the where parameter. ### Response #### Success Response * **Type:** int - Number of sessions which match the query. ### Raises * **ValueError** – Raised if the site name is not valid. ``` -------------------------------- ### update_scheduler(new_scheduler) Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/simulator.md Updates the simulator's current scheduling algorithm. ```APIDOC ## update_scheduler(new_scheduler) ### Description Updates a Simulator’s schedule. ``` -------------------------------- ### Simulator Class Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/simulator.md The central class for managing and running simulations. It holds the network, scheduler, and events, and handles timekeeping and simulation progression. ```APIDOC ## class acnportal.acnsim.simulator.Simulator ### Description Central class of the acnsim package. The Simulator class is the central place where everything about a particular simulation is stored including the network, scheduling algorithm, and events. It is also where timekeeping is done and orchestrates calling the scheduling algorithm, sending pilots to the network, and updating the energy delivered to each EV. ### Parameters * **network** (*ChargingNetwork*) – The charging network which the simulation will use. * **scheduler** (*BaseAlgorithm*) – The scheduling algorithm used in the simulation. If scheduler = None, Simulator.run() cannot be called. * **events** (*EventQueue*) – Queue of events which will occur in the simulation. * **start** (*datetime*) – Date and time of the first period of the simulation. * **period** (*float*) – Length of each time interval in the simulation in minutes. Default: 1 * **signals** (*Dict[str, ...]*) – * **store_schedule_history** (*bool*) – If True, store the scheduler output each time it is run. Note this can use lots of memory for long simulations. * **verbose** (*bool*) – * **interface_type** (*type*) – The class of interface to register with the scheduler. ``` -------------------------------- ### EVSE Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/models.md EVSE that allows for charging in a continuous range from min_rate to max_rate. ```APIDOC ## Class acnportal.acnsim.models.evse.EVSE(station_id, max_rate=inf, min_rate=0) ### Description This class of EVSE allows for charging in a continuous range from min_rate to max_rate. ### See BaseEVSE attributes. ### Properties #### _max_rate - **Type:** float - **Description:** Maximum charging current allowed by the EVSE. #### _min_rate - **Type:** float - **Description:** Minimum charging current allowed by the EVSE. #### allowable_pilot_signals - **Description:** Returns the allowable pilot signal levels for this EVSE. Implements abstract method allowable_pilot_signals from BaseEVSE. - **Returns:** List of 2 values: the min and max acceptable values. - **Return type:** list[float] #### max_rate - **Description:** Return maximum charging current allowed by the EVSE. - **Return type:** float #### min_rate - **Description:** Return minimum charging current allowed by the EVSE. - **Return type:** float ``` -------------------------------- ### get_sessions_by_time Source: https://github.com/zach401/acnportal/blob/master/docs/acndata/data_client.md Retrieves sessions based on time range and minimum energy delivered, with options for timeseries data and counting. ```APIDOC ## get_sessions_by_time ### Description Wrapper for get_sessions with condition based on start and end times and a minimum energy delivered. ### Method Not applicable (Python method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **site** (str) - Required - Site where data should be gathered. * **start** (datetime) - Optional - Only return sessions which began after start. * **end** (datetime) - Optional - Only return session which began before end. * **min_energy** (float) - Optional - Only return sessions where the kWhDelivered is greater than or equal to min_energy. * **timeseries** (bool) - Optional - If True return the time-series of charging rates and pilot signals. Default False. * **count** (bool) - Optional - If True return the number of sessions which would be returned by the function. Default False. ### Yields * If count is False see get_sessions else see count_sessions. ### Raises * **See get_sessions/count_sessions.** ``` -------------------------------- ### constraint_currents Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/analysis.md Calculate the time series of current for each constraint in the ChargingNetwork for a simulation. ```APIDOC ## constraint_currents(sim, return_magnitudes=False, constraint_ids=None) ### Description Calculate the time series of current for each constraint in the ChargingNetwork for a simulation. ### Parameters * **sim** (*Simulator*) – A Simulator object which has been run. * **return_magnitudes** (*bool*) – If true, return constraint currents as real magnitudes instead of complex numbers. * **constraint_ids** (*List[str]*) – List of constraint names for which the current should be returned. If None, return all constraint currents. ### Returns A dictionary mapping the name of a constraint to a numpy array of the current subject to that constraint at each time. ### Return type Dict (str, np.Array) ``` -------------------------------- ### min_pilot_signal Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/interface.md Returns the minimum allowable pilot signal level for the EVSE. A zero pilot signal is always assumed to be allowed; the minimum allowable pilot signal returned here is the minimum nonzero pilot signal allowed by the EVSE if said EVSE is non-continuous. ```APIDOC ## min_pilot_signal(station_id: str) ### Description Returns the minimum allowable pilot signal level for the EVSE. A zero pilot signal is always assumed to be allowed; the minimum allowable pilot signal returned here is the minimum nonzero pilot signal allowed by the EVSE if said EVSE is non-continuous. ### Parameters #### Path Parameters - **station_id** (str) - Required - The ID of the station. ### Response #### Success Response - **return_value** (float) - the minimum pilot signal supported by this EVSE. ``` -------------------------------- ### last_actual_charging_rate Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/interface.md Retrieves the actual charging rates for all active sessions in the last simulation period. ```APIDOC ## last_actual_charging_rate ### Description Return the actual charging rates in the last period for all active sessions. ### Returns A dictionary with the session ID as key and actual charging rate as value. ### Return Type Dict[str, float] ``` -------------------------------- ### post_charging_update Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/network/charging_network.md A hook method designed to define actions that should occur immediately after a charging update has been processed within the network. ```APIDOC ## post_charging_update() ### Description Hook to define actions to take after the charging update. ### Parameters * None ### Returns None ``` -------------------------------- ### pilot_signals_as_df() Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/simulator.md Returns the pilot signals sent to EVs over the simulation as a pandas DataFrame. ```APIDOC ## pilot_signals_as_df() ### Description Return the pilot signals as a pandas DataFrame ### Returns A DataFrame containing the pilot signals of the simulation. Columns are EVSE id, and the index is the iteration. ### Return type pandas.DataFrame ``` -------------------------------- ### voltages Source: https://github.com/zach401/acnportal/blob/master/docs/acnsim/network/charging_network.md Retrieves the input voltages for all Electric Vehicle Supply Equipment (EVSE) registered within the network. ```APIDOC ## property voltages: Dict[str, float] ### Description Return dictionary of voltages for all EVSEs in the network. ### Returns Dictionary mapping EVSE ids their input voltage. [V] ### Return type Dict[str, float] ```