diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..4b5a294 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "python-envs.defaultEnvManager": "ms-python.python:conda", + "python-envs.defaultPackageManager": "ms-python.python:conda" +} \ No newline at end of file diff --git a/README.md b/README.md index 2fb1246..d84fd2d 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,8 @@ The problem that **opti_market** solves is to optimize the charge and discharge opti_market ├── base_configuration │ ├── blue_print.yml +│ ├── double_market_min_charge.yml +│ ├── double_market_unconstrained.yml # │ ├── double_market.yml │ ├── single_market_a.yml │ └── single_market_b.yml @@ -193,7 +195,6 @@ simulation: packaged_data: output: path_to_save: - basic_plot: default_location: clean_option: ``` @@ -243,7 +244,6 @@ One block per market (`market1`, `market2`, …; at most 6). The names are free; | `default_location` | no | True | If True, the results are saved in `/results/`. | | `path_to_save` | no | null | Folder where the results are saved (`/results/`). Use it with `default_location: False`. | | `clean_option` | no | True | If the output folder already exists, True deletes it and writes the new results; False stops the program. | -| `basic_plot` | no | False | Reserved for plotting. Not used in the current version. | ### Example @@ -275,7 +275,6 @@ simulation: packaged_data: True output: path_to_save: null - basic_plot: True default_location: True clean_option: True ``` diff --git a/base_configuration/blue_print.yml b/base_configuration/blue_print.yml index 8a6a640..0ced336 100644 --- a/base_configuration/blue_print.yml +++ b/base_configuration/blue_print.yml @@ -23,6 +23,5 @@ simulation: packaged_data: output: path_to_save: - basic_plot: default_location: clean_option: diff --git a/base_configuration/double_market.yml b/base_configuration/double_market.yml index 0d73357..8f75a20 100644 --- a/base_configuration/double_market.yml +++ b/base_configuration/double_market.yml @@ -29,6 +29,5 @@ simulation: output: path_to_save: null - basic_plot: True default_location: True clean_option: True \ No newline at end of file diff --git a/base_configuration/double_market_min_charge.yml b/base_configuration/double_market_min_charge.yml index c27eb44..625766c 100644 --- a/base_configuration/double_market_min_charge.yml +++ b/base_configuration/double_market_min_charge.yml @@ -29,6 +29,5 @@ simulation: output: path_to_save: null - basic_plot: True default_location: True clean_option: True \ No newline at end of file diff --git a/base_configuration/double_market_unconstrained.yml b/base_configuration/double_market_unconstrained.yml index 66c8573..8ad2026 100644 --- a/base_configuration/double_market_unconstrained.yml +++ b/base_configuration/double_market_unconstrained.yml @@ -29,6 +29,5 @@ simulation: output: path_to_save: null - basic_plot: True default_location: True clean_option: True \ No newline at end of file diff --git a/base_configuration/single_market_a.yml b/base_configuration/single_market_a.yml index d550a1c..f25b3c3 100644 --- a/base_configuration/single_market_a.yml +++ b/base_configuration/single_market_a.yml @@ -26,6 +26,5 @@ simulation: output: path_to_save: null - basic_plot: True default_location: True clean_option: True \ No newline at end of file diff --git a/base_configuration/single_market_b.yml b/base_configuration/single_market_b.yml index 69a78ba..ff53540 100644 --- a/base_configuration/single_market_b.yml +++ b/base_configuration/single_market_b.yml @@ -26,6 +26,5 @@ simulation: output: path_to_save: null - basic_plot: True default_location: True clean_option: True \ No newline at end of file diff --git a/src/opti_market/__init__.py b/src/opti_market/__init__.py index e69de29..c60b502 100644 --- a/src/opti_market/__init__.py +++ b/src/opti_market/__init__.py @@ -0,0 +1 @@ +"""Battery dispatch optimisation across electricity markets.""" diff --git a/src/opti_market/__main__.py b/src/opti_market/__main__.py index 84169be..265ef3a 100644 --- a/src/opti_market/__main__.py +++ b/src/opti_market/__main__.py @@ -1,3 +1,5 @@ +"""Run the package with ``python -m opti_market``.""" + from opti_market.opti_market import run_opti_market run_opti_market() diff --git a/src/opti_market/config_module/__init__.py b/src/opti_market/config_module/__init__.py index d228598..87863a3 100644 --- a/src/opti_market/config_module/__init__.py +++ b/src/opti_market/config_module/__init__.py @@ -1,3 +1,5 @@ +"""Configuration of the battery, markets, simulation options and output.""" + from .configuration_read import read_configuration, read_configurations_files from .configure_battery import BATTERY, BATTERY_SPEC from .configure_market import Markets, read_market diff --git a/src/opti_market/config_module/configuration_read.py b/src/opti_market/config_module/configuration_read.py index 46290da..d5f2ed5 100644 --- a/src/opti_market/config_module/configuration_read.py +++ b/src/opti_market/config_module/configuration_read.py @@ -1,8 +1,8 @@ """ Definition of options for the input configuration file. -'man':'mandatory', => If it is not defined, the program is preventevely blocked -'opt': 'fully optional, if anything is defined, the default value are applied' +'man':'mandatory', => If it is not defined, the program is preventively blocked +'opt': 'fully optional, if nothing is defined, the default values are applied' """ from importlib.resources import files @@ -58,7 +58,6 @@ } _OUTPUT_INPUT_: dict[str, tuple[OptionKind, OptionValue]] = { "path_to_save": ("opt", None), - "basic_plot": ("opt", False), "default_location": ("opt", True), "clean_option": ("opt", True), } @@ -67,6 +66,17 @@ # --- # --- def read_simulation_config(inp_dict: dict[str, Any]) -> dict[str, Any]: + """Read the optimization section of the configuration file. + + Check the input against _SIMULATION_INPUT_ and fill the missing + optional entries with their default values. + + Args: + inp_dict (dict): optimization data field from the yml file. + + Returns: + dict: complete set of simulation options, including defaults. + """ sim_config = check_input(inp_dict=inp_dict, par=_SIMULATION_INPUT_) @@ -75,6 +85,21 @@ def read_simulation_config(inp_dict: dict[str, Any]) -> dict[str, Any]: # --- def read_simulation_output(inp_dict: dict[str, Any]) -> dict[str, Any]: + """Read the output section of the configuration file. + + Check the input against _OUTPUT_INPUT_, fill the missing optional + entries with their default values and convert an empty path_to_save + into None. + + Args: + inp_dict (dict): output data field from the yml file. + + Raises: + ValueError: if path_to_save is specified and default_location is True. + + Returns: + dict: complete set of output options, including defaults. + """ output_configuration = check_input(inp_dict=inp_dict, par=_OUTPUT_INPUT_) # Safe Guard. @@ -94,13 +119,13 @@ def read_simulation_output(inp_dict: dict[str, Any]) -> dict[str, Any]: # --- def read_battery(inp_dict: dict[str, Any]) -> dict[str, Any]: - """Read the battery input data - Check the input, fill up the data with the default options + """Read the battery input data. + Check the input and fill in the data with the default options. Args: - inp_dict (dict): input battery data field from yml file + inp_dict (dict): input battery data field from the yml file. Returns: - dict: complete data set for battery with default. + dict: complete data set for the battery, with defaults. """ battery = check_input(inp_dict=inp_dict, par=_BATTERY_INPUT_) @@ -109,20 +134,20 @@ def read_battery(inp_dict: dict[str, Any]) -> dict[str, Any]: # --- def check_input(inp_dict: dict[str, Any], par: dict[str, Any]) -> dict[str, Any]: - """Check the input, and fill a new small dictionary - of input. - The function checks the data + """Check the input and fill a new small dictionary + of inputs. + The function checks the data. Args: inp_dict (dict): the data read from the configuration files - par (dict): the global parameter dictionary on top of this file + par (dict): the global parameter dictionary at the top of this file Raises: - ValueError: if the parameters is not defined (i.e., it is not specified), + ValueError: if the parameter is not defined (i.e., it is not specified) but it is mandatory, throw an error and highlight at least the name of the field Returns: - dict: completed dictionary with all the information for filling up the + dict: completed dictionary with all the information for filling in the real input configuration. """ new_dict = dict.fromkeys(par, None) @@ -145,7 +170,7 @@ def check_input(inp_dict: dict[str, Any], par: dict[str, Any]) -> dict[str, Any] # --- def read_markets(markt: dict[str, Any]) -> dict[str, Any]: - """Reads the market and convert path in case of flags. + """Read the market and convert the path in case of flags. Args: markets (dict): check the input data of the market and release @@ -203,16 +228,16 @@ def post_process_config_file( pre_config: dict[str, Any], config_fin: dict[str, Any] ) -> None: """Use the original configuration file and construct the - effective configuration of the simulation + effective configuration of the simulation. - Reason: Since the take-home assignment has two market, I wanted + Reason: Since the take-home assignment has two markets, I wanted to flag the presence of these markets within the package, such that the behaviour is deterministic for the example, and also - to inform directly the unit/integration/regression test. + to directly inform the unit/integration/regression tests. Args: pre_config (dict): data read from the configuration file - config_fin (dict): final data for configure, battery and market classes + config_fin (dict): final data to configure the battery and market classes """ config_fin["markets"] = read_markets(pre_config["simulation"]["markets"]) @@ -251,37 +276,43 @@ def read_configuration(config_file: str) -> dict[str, dict[str, Any]]: ) return configurations_sim + + # --- -def check_consistency(markt:Markets,opti_opt:Opti_Market_Options)->None: +def check_consistency(markt: Markets, opti_opt: Opti_Market_Options) -> None: """Check if the starting date of the simulation is consistent with the - common start/end of the markets + common start/end of the markets. Args: - markt (Markets): Markets class - opti_opt (Opti_Market_Options): optimization option + markt (Markets): Markets class + opti_opt (Opti_Market_Options): optimization options Raises: - ValueError: The starting date of the simulation predates the markets timeseries. - ValueError: The ending date of the simulation is after the final date of the markets timeseries. + ValueError: The starting date of the simulation predates the market timeseries. + ValueError: The ending date of the simulation is after the final date of the market timeseries. """ - - if opti_opt.start_date < markt.common_start: - raise ValueError(' The simulation starts before the initial common time frame of the markets') - elif opti_opt.end_date > markt.common_end: - raise ValueError(' The simulation ends after the final common time frame of the markets') - + if opti_opt.start_date < markt.common_start: + raise ValueError( + " The simulation starts before the initial common time frame of the markets" + ) + elif opti_opt.end_date > markt.common_end: + raise ValueError( + " The simulation ends after the final common time frame of the markets" + ) + + # --- def read_configurations_files( config_file: str, ) -> tuple[BATTERY, Markets, Opti_Market_Options, Output]: - """Configure the simulation using the configuration file + """Configure the simulation using the configuration file. Args: config_file (str): path to the configuration file Returns: - tuple[BATTERY, Markets, Opti_Market_Options, Output]: classes that handles the simulation behaviour + tuple[BATTERY, Markets, Opti_Market_Options, Output]: classes that handle the simulation behaviour """ configuration_sim = read_configuration(config_file=config_file) @@ -297,8 +328,8 @@ def read_configurations_files( dict_config=configuration_sim["output"], name_simulation=str(configuration_sim["name"]), ) - - check_consistency(markt=markt,opti_opt=opti_opt) + + check_consistency(markt=markt, opti_opt=opti_opt) return bat, markt, opti_opt, output diff --git a/src/opti_market/config_module/configure_battery.py b/src/opti_market/config_module/configure_battery.py index b8c37f6..6bfa819 100644 --- a/src/opti_market/config_module/configure_battery.py +++ b/src/opti_market/config_module/configure_battery.py @@ -1,3 +1,5 @@ +"""Battery specification and battery state during the simulation.""" + from dataclasses import InitVar, dataclass, field from pathlib import Path from typing import Literal @@ -5,23 +7,23 @@ import numpy as np import yaml -DegradationModel = Literal["linear", "compound","none"] +DegradationModel = Literal["linear", "compound", "none"] @dataclass(frozen=True) class BATTERY_SPEC: """Class containing the information of the battery: model_name:str :model name - max_discharge_rate:float32 :maximum volume that can be export (MW) - max_charge_rate:float32 :maximum volume that can be import (MW) - max_storage_vol:float32: maximum volume storage (MWh) - dicharge_eff: float32: efficiency of discharge + max_discharge_rate:float32 :maximum volume that can be exported (MW) + max_charge_rate:float32 :maximum volume that can be imported (MW) + max_storage_vol:float32: maximum storage volume (MWh) + discharge_eff: float32: efficiency of discharge charge_eff: float32: efficiency of charge max_cycle: int32: number of cycles of total charge/discharge of the battery - max_life: int32: maximum year in which the battery is guarantee to have its original specification - if not used- [?] - degradation: float32: given a number of cycle, the amount of total storage loss. + max_life: int32: maximum year in which the battery is guaranteed to have its original specification - if not used - [?] + degradation: float32: given a number of cycles, the amount of total storage loss. capex: float32: initial costs for installing the battery - fix_cost_yr: float32: fixed cost of the battery (maintainance...) + fix_cost_yr: float32: fixed cost of the battery (maintenance...) cur_cycle: int32: current cycle cur_age: int2: current age """ @@ -43,6 +45,26 @@ class BATTERY_SPEC: # --- @dataclass class BATTERY: + """Battery model and its state during the simulation. + + The specification is read from the battery database (battery_data_base.yaml) + using model_name. The state (number of cycles, effective storage volume and + cumulative discharged energy) is updated after each optimisation window. + + Attributes: + model_name (str): name of the battery model in the database (init only). + battery_spec (BATTERY_SPEC): specification of the battery model. + initial_charge (float): initial stored energy, as a fraction of the + effective maximum storage volume. + initial_cycles (float): number of cycles already performed by the battery. + initial_age (int): initial age of the battery. + effective_max_storage_vol (float): current maximum storage volume after + degradation (MWh). + total_number_cycle (float): current number of cycles. + cumulative_power_discharged (float): cumulative discharged energy (MWh). + degradation_model (str): "linear", "compound" or "none". + """ + model_name: InitVar[str] battery_spec: BATTERY_SPEC = field(init=False) # Initial state of the battery @@ -68,9 +90,9 @@ class BATTERY: # define the concept of cycles # --- def __post_init__(self, model_name: str) -> None: - """Update the battery_spec - Read the yml file containing the battery specification - Fill the battery_spec sub-class + """Update the battery_spec. + Read the yml file containing the battery specification. + Fill the battery_spec sub-class. Args: mname (str): _description_ @@ -89,7 +111,7 @@ def __post_init__(self, model_name: str) -> None: # --- def read_yml_battery(self, mname: str) -> None: - """Read the yaml file containing the batteries information + """Read the yaml file containing the battery information. Args: mname (str): model name. battery model name. @@ -126,9 +148,9 @@ def get_spec_battery(self, spec: str): # --- def _update_total_discharge(self, dE: float) -> None: - """Update the total discharge - dE: total discharge for a given amount of time (i.e., sold energy to the market) - Update the energy discharge + """Update the total discharge. + dE: total discharge for a given amount of time (i.e., energy sold to the market). + Update the energy discharge. """ if dE > 0: @@ -140,7 +162,7 @@ def _update_total_discharge(self, dE: float) -> None: def analytical_total_discharge(self) -> float: """Compute the analytical total discharge. The analytical expression for the total energy can be derived - by a simple integration of the total number of cycle. + by a simple integration of the total number of cycles. """ E0 = self.get_spec_battery("max_storage_vol") degradation = self.get_spec_battery("degradation") / 100 @@ -159,7 +181,7 @@ def analytical_total_discharge(self) -> float: # --- def _update_effective_max_storage_vol(self) -> None: """Update the effective max storage volume using - a compound forumation or a linear formulation. + a compound formulation or a linear formulation. TO DO: pyfile of global configuration to modify, or introducing directly the option in the class battery """ @@ -180,11 +202,11 @@ def _update_effective_max_storage_vol(self) -> None: # --- def _update_cycle(self, dE: float) -> None: - """Update the number of cycle using the current discharge + """Update the number of cycles using the current discharge and using the previous effective_max_volume. Args: - dE (float): currenty energy + dE (float): current energy """ self.total_number_cycle = ( @@ -193,6 +215,17 @@ def _update_cycle(self, dE: float) -> None: # --- def update_state_battery(self, dE: float) -> None: + """Update the battery state after a discharge. + + Update the number of cycles, the effective maximum storage volume and + the cumulative discharged energy, in this order. + + Args: + dE (float): discharged energy (MWh), as a non-positive value. + + Raises: + ValueError: if dE is positive. + """ if dE > 0: raise ValueError("The total discharge must be always negative") else: diff --git a/src/opti_market/config_module/configure_market.py b/src/opti_market/config_module/configure_market.py index 929efb0..0ea2985 100644 --- a/src/opti_market/config_module/configure_market.py +++ b/src/opti_market/config_module/configure_market.py @@ -1,3 +1,5 @@ +"""Market price timeseries and their common time step and time frame.""" + from dataclasses import InitVar, dataclass, field from math import gcd from pathlib import Path @@ -15,6 +17,22 @@ # --- @dataclass class Markets: + """Price timeseries of up to six markets and their common time grid. + + Attributes: + markets (dict): market configurations, each with "prices_file" and + "path_to_file" entries (init only). + n_market (int): number of markets. + market_n1 ... market_n6 (pd.DataFrame): price timeseries of each market; + unused slots are None. + common_start (pd.Timestamp): latest first timestamp among the markets. + common_end (pd.Timestamp): earliest last timestamp among the markets. + dt (float): common time step (minutes), the greatest common divisor of + the market time steps. + dt_steps (list[int]): number of common time steps in one period of each + market. + """ + markets: InitVar[dict[str, Any]] n_market: int = field(init=False) market_n1: pd.DataFrame = field(init=False) @@ -27,10 +45,18 @@ class Markets: common_end: pd.Timestamp = field(init=False) dt: float = 0.0 dt_steps: list[int] = field(init=False) - # --- def __post_init__(self, markets: dict[str, Any]): + """Read the price file of each market and set the common time grid. + + Args: + markets (dict): market configurations, each with "prices_file" and + "path_to_file" entries. + + Raises: + ValueError: if more than six markets are given. + """ self.n_market = len(markets) if self.n_market > 6: raise ValueError("The maximum market per battery is 6. Reduce the markets") @@ -47,28 +73,37 @@ def __post_init__(self, markets: dict[str, Any]): self._extract_dt() self._check_initial_final_date_markets() - + # Find the common time interval - def _check_initial_final_date_markets(self)->None: - - start :list[pd.Timestamp] = [] - end :list[pd.Timestamp] = [] + def _check_initial_final_date_markets(self) -> None: + """Find the common time frame of the markets. + + Set common_start to the latest first timestamp and common_end to the + earliest last timestamp among the markets. + + Raises: + ValueError: if the markets do not overlap in time. + """ + + start: list[pd.Timestamp] = [] + end: list[pd.Timestamp] = [] for k in range(self.n_market): - a = getattr(self,f'market_n{k+1}') - start.append(a['timestamp'].min()) - end.append(a['timestamp'].max()) - + a = getattr(self, f"market_n{k + 1}") + start.append(a["timestamp"].min()) + end.append(a["timestamp"].max()) + self.common_start = max(start) self.common_end = min(end) - + if self.common_start >= self.common_end: raise ValueError("The markets do not overlap in time") + # --- def _extract_dt(self) -> None: - """Collect all the market, compute the dt per each market + """Collect all the markets, compute the dt for each market and choose the minimum denominator. - Before it, checks if the price are in any fraction of hours, - the accepted fraction of hours are 15/30/45/60 min. + Before that, check if the prices are in any fraction of an hour; + the accepted fractions of an hour are 15/30/45/60 min. total minutes day: 1440 % (_FRACTION_) = 64,48,32,24 """ dt_buf: float = 0.0 @@ -99,7 +134,7 @@ def _extract_dt(self) -> None: # --- # --- def read_market(name: str, path: str) -> pd.DataFrame: - """Read the market csv file + """Read the market csv file. Args: name (str): name of the csv file diff --git a/src/opti_market/config_module/configure_output.py b/src/opti_market/config_module/configure_output.py index e5402d7..5100cb9 100644 --- a/src/opti_market/config_module/configure_output.py +++ b/src/opti_market/config_module/configure_output.py @@ -1,3 +1,5 @@ +"""Output settings: results folder and output options.""" + from dataclasses import dataclass from importlib.resources import files from pathlib import Path @@ -8,8 +10,15 @@ # --- @dataclass(frozen=True) class Output: + """Output settings of the simulation. + + Attributes: + path_to_save (Path): folder where the results are written. + clean_option (bool): if True, an existing results folder is removed + before the run. + """ + path_to_save: Path - basic_plot: bool clean_option: bool # --- @@ -34,6 +43,5 @@ def read_output_configuration( return cls( path_to_save=path, - basic_plot=dict_config["basic_plot"], clean_option=dict_config["clean_option"], ) diff --git a/src/opti_market/config_module/configure_simulation.py b/src/opti_market/config_module/configure_simulation.py index 8e73608..b47f3b7 100644 --- a/src/opti_market/config_module/configure_simulation.py +++ b/src/opti_market/config_module/configure_simulation.py @@ -1,3 +1,5 @@ +"""Simulation options: window, start and end dates, cycle limit, minimum charge.""" + from dataclasses import dataclass from typing import Any @@ -8,6 +10,17 @@ # --- @dataclass(frozen=True) class Opti_Market_Options: + """Options of the optimization. + + Attributes: + window_day (pd.Timedelta): length of each optimization window. + start_date (pd.Timestamp): start of the simulation. + end_date (pd.Timestamp): end of the simulation (excluded). + max_cycles (float): maximum number of full cycles per day. + charge_min (float): minimum stored energy, as a fraction of the + effective maximum storage volume. + """ + window_day: pd.Timedelta start_date: pd.Timestamp end_date: pd.Timestamp @@ -16,6 +29,18 @@ class Opti_Market_Options: @classmethod def read_optimisation_options(cls, dict_config: dict[str, Any]): + """Build the options from the 'optimization' section of the configuration. + + Args: + dict_config (dict): simulation options from read_simulation_config. + + Raises: + ValueError: if the simulation interval is not a multiple of the + window (raised by _parse_dates). + + Returns: + Opti_Market_Options: the optimization options. + """ window_day = pd.Timedelta(days=dict_config["window_days"]) start_date, end_date = _parse_dates( @@ -37,7 +62,7 @@ def read_optimisation_options(cls, dict_config: dict[str, Any]): def _parse_dates( sd: str, ed: str | None, window: pd.Timedelta ) -> tuple[pd.Timestamp, pd.Timestamp]: - """Parse the date and compute the number of intervals + """Parse the dates and compute the number of intervals. Args: sd (str): starting date diff --git a/src/opti_market/opti_market.py b/src/opti_market/opti_market.py index b4d5bdf..64585c8 100644 --- a/src/opti_market/opti_market.py +++ b/src/opti_market/opti_market.py @@ -1,3 +1,5 @@ +"""Command-line entry point of the opti_market package.""" + import argparse import shutil from pathlib import Path @@ -10,6 +12,19 @@ # function to run the function def run_opti_market(args: list[str] | None = None): + """Run the battery dispatch optimisation from the command line. + + Parse the arguments, read the configuration file, prepare the output + folder and solve the optimisation problem. + + Args: + args (list[str] | None): command-line arguments; if None, sys.argv + is used. + + Raises: + ValueError: if the configuration file does not exist, or if the + output folder already exists and clean_option is False. + """ # Parse the arguments parser = argparse.ArgumentParser( prog="python -m opti_market", diff --git a/src/opti_market/optimisation_module/__init__.py b/src/opti_market/optimisation_module/__init__.py index dd1ed6a..c4e2cab 100644 --- a/src/opti_market/optimisation_module/__init__.py +++ b/src/opti_market/optimisation_module/__init__.py @@ -1,3 +1,5 @@ +"""Optimisation of the battery dispatch.""" + from .optimization_routines import solve_problem __all__ = ["solve_problem"] diff --git a/src/opti_market/optimisation_module/optimization_routines.py b/src/opti_market/optimisation_module/optimization_routines.py index 24b226a..ac8f06b 100644 --- a/src/opti_market/optimisation_module/optimization_routines.py +++ b/src/opti_market/optimisation_module/optimization_routines.py @@ -1,3 +1,5 @@ +"""Battery dispatch problem, built with PuLP and solved with HiGHS window by window.""" + from typing import Any, TypedDict import numpy as np @@ -18,6 +20,15 @@ # Useful class for handling multimarket class MarketProblem(TypedDict): + """Variables and data of one market in the optimisation problem. + + Attributes: + charge (VarDict): power bought from the market in each period (MW). + discharge (VarDict): power sold to the market in each period (MW). + res (int): number of model time steps in one market period. + prices (NDArray[np.float64]): market price in each period (£/MWh). + """ + charge: VarDict discharge: VarDict res: int @@ -29,8 +40,8 @@ class MarketProblem(TypedDict): def select_range_prices( tar_markt: pd.DataFrame, date: pd.Timestamp, window: pd.Timedelta ) -> NDArray[np.float64]: - """From the actual date, extract the price - from the given market using the specified window + """From the current date, extract the prices + from the given market using the specified window. Args: tar_markt (pd.DataFrame): target market @@ -38,7 +49,7 @@ def select_range_prices( window (pd.Timedelta):how many days Returns: - NDArray[np.float64]: price lists + NDArray[np.float64]: list of prices """ end = date + window @@ -54,6 +65,18 @@ def select_range_prices( def add_market( prob: pulp.LpProblem, prices: NDArray[np.float64], res: int, market_number: int ) -> MarketProblem: + """Add the charge and discharge variables of one market to the problem. + + Args: + prob (pulp.LpProblem): optimisation problem. + prices (NDArray[np.float64]): market prices in the window (£/MWh). + res (int): number of model time steps in one market period. + market_number (int): index of the market, used in the variable names. + + Returns: + MarketProblem: variables and data of the market, with one non-negative + charge and one non-negative discharge variable per price period. + """ periods = range(len(prices)) return MarketProblem( charge=prob.add_variable_dicts( @@ -69,8 +92,23 @@ def add_market( # --- def battery_confg( - prob: pulp.LpProblem, bat: BATTERY, time_vec_len: int, -min_charge:float) -> dict[str, dict[int, pulp.LpVariable]]: + prob: pulp.LpProblem, bat: BATTERY, time_vec_len: int, min_charge: float +) -> dict[str, dict[int, pulp.LpVariable]]: + """Add the battery variables to the problem. + + Args: + prob (pulp.LpProblem): optimisation problem. + bat (BATTERY): battery model. + time_vec_len (int): number of model time steps in the window. + min_charge (float): minimum stored energy, as a fraction of the + effective maximum storage volume. + + Returns: + dict: "charge_binary", one binary variable per time step (1 = charging), + and "energy_bat", the stored energy at each step boundary + (time_vec_len + 1 values, MWh), bounded between + min_charge * effective_max_storage_vol and effective_max_storage_vol. + """ # Defining output data charge_binary = prob.add_variable_dicts( @@ -100,6 +138,28 @@ def configure_problem( opti_interval: int, energy_start: float, ) -> tuple[pulp.LpProblem, dict[str, MarketProblem], dict[str, VarDict]]: + """Build the dispatch optimisation problem for one window. + + The objective is the total profit over all markets. The constraints are + the cycle limit of the window, the initial stored energy, the energy + balance of the battery at each time step, the charge and discharge rate + limits, and no simultaneous charge and discharge. + + Args: + name_problem (str): name of the PuLP problem. + bat (BATTERY): battery model. + mar (Markets): markets. + opti_mar (Opti_Market_Options): optimisation options. + sim_cycle_sd (pd.Timestamp): start date of the window. + opti_interval (int): index of the window; for the first window (0) + the initial energy is initial_charge * effective_max_storage_vol. + energy_start (float): stored energy at the start of the window (MWh), + used when opti_interval > 0. + + Returns: + tuple: the problem, the variables of each market (keyed by + "market_n{i}") and the battery variables. + """ # Temporary variable mkrt_prb: dict[str, MarketProblem] = {} # update battery @@ -108,8 +168,9 @@ def configure_problem( prob = pulp.LpProblem(name_problem, pulp.LpMaximize) t_vc = int((_MIN_DAY_ * opti_mar.window_day.days) / mar.dt) dt_hr = mar.dt / _MIN_HR_ - bat_prb = battery_confg(prob=prob, bat=bat, time_vec_len=t_vc - ,min_charge=opti_mar.charge_min) + bat_prb = battery_confg( + prob=prob, bat=bat, time_vec_len=t_vc, min_charge=opti_mar.charge_min + ) time_step = range(t_vc) # Set the market variables for i in range(1, mar.n_market + 1): @@ -146,7 +207,11 @@ def configure_problem( max_dch = bat.get_spec_battery("max_discharge_rate") max_cha = bat.get_spec_battery("max_charge_rate") - prob += total_energy_uncharged <= opti_mar.max_cycles * opti_mar.window_day.days * max_pow, "cycle_day_limit" + prob += ( + total_energy_uncharged + <= opti_mar.max_cycles * opti_mar.window_day.days * max_pow, + "cycle_day_limit", + ) if opti_interval == 0: prob += ( bat_prb["energy_bat"][0] == bat.initial_charge * max_pow, @@ -175,6 +240,22 @@ def configure_problem( def solve_problem( opti_opt: Opti_Market_Options, bat: BATTERY, markt: Markets, output: Output ) -> None: + """Solve the dispatch problem window by window and save the results. + + For each window, build and solve the problem with HiGHS, write the + results, update the battery state with the discharged energy and carry + the final stored energy over to the next window. At the end, print and + save the summary. + + Args: + opti_opt (Opti_Market_Options): optimisation options. + bat (BATTERY): battery model; its state is updated in place. + markt (Markets): markets. + output (Output): output settings. + + Raises: + AssertionError: if a window is not solved to optimality. + """ interval = opti_opt.end_date - opti_opt.start_date n_opt_max = int(interval / opti_opt.window_day) @@ -227,8 +308,8 @@ def solve_problem( ) final_energy = energy[-1] # state at the end -> next window steps = np.diff(energy) - discharged = -steps[steps < 0].sum() - bat.update_state_battery(dE=-discharged) + discharged = -steps[steps < 0].sum() + bat.update_state_battery(dE=-discharged) start_energy = min(max(final_energy, 0.0), bat.effective_max_storage_vol) total_profit = total_profit + float(pulp.value(prob.objective)) start = start + opti_opt.window_day diff --git a/src/opti_market/output_module/__init__.py b/src/opti_market/output_module/__init__.py index 315e5dc..a7720a4 100644 --- a/src/opti_market/output_module/__init__.py +++ b/src/opti_market/output_module/__init__.py @@ -1,3 +1,5 @@ +"""Writing of the optimisation results and of the run summary.""" + from .write_csv_data import output_results_opti, print_summary, save_summary __all__ = [ diff --git a/src/opti_market/output_module/write_csv_data.py b/src/opti_market/output_module/write_csv_data.py index dafe2fb..70702ab 100644 --- a/src/opti_market/output_module/write_csv_data.py +++ b/src/opti_market/output_module/write_csv_data.py @@ -1,3 +1,5 @@ +"""Writing of the results (raw data, window totals, summary) to CSV files.""" + from __future__ import annotations import numbers @@ -41,6 +43,14 @@ # --- # --- def create_path(path: Path) -> Path: + """Create the folder if it does not exist and return it. + + Args: + path (Path): folder to create. + + Returns: + Path: the same path. + """ path.mkdir(parents=True, exist_ok=True) return path @@ -55,6 +65,24 @@ def save_data_raw( time_information: tuple[pd.Timestamp, float, pd.Timedelta], summary: dict[str, Any], ) -> list[float]: + """Append the results of one window to one CSV file per market. + + Each row holds the timestamp, the price (£/MWh), the charge and discharge + power (MW) and the revenue (£) of one market period. The revenue of each + market is also added to summary["market_revenues"]. + + Args: + output (Output): output settings. + bat_cfg (dict): battery variables (not used). + markt (dict): variables and data of each market. + prob (pulp.LpProblem): solved problem (not used). + time_information (tuple): start of the window, model time step + (minutes) and window length. + summary (dict): run summary, updated in place. + + Returns: + list[float]: total revenue of each market in the window (£). + """ path = create_path(Path(output.path_to_save / "Data_Raw")) # save markets data dt_min = time_information[1] # model step, minutes @@ -102,6 +130,21 @@ def save_window( time_information: tuple[pd.Timestamp, float, pd.Timedelta], total_revenue: list[float], ) -> None: + """Append the totals of one window to window_optimisation_results.csv. + + The row holds the start and end of the window, the total revenue (£), + the stored energy at the end (MWh) and the energy discharged from the + battery (MWh), computed from the decreases of the stored energy. + + Args: + output (Output): output settings. + bat_prb (dict): battery variables. + markt (dict): variables and data of each market (not used). + prob (pulp.LpProblem): solved problem (not used). + time_information (tuple): start of the window, model time step + (minutes) and window length. + total_revenue (list[float]): revenue of each market in the window (£). + """ path = create_path(Path(output.path_to_save / "Data_Window")) start = time_information[0] @@ -139,16 +182,31 @@ def output_results_opti( time_information: tuple[pd.Timestamp, float, pd.Timedelta], summary: dict[str, Any], ) -> None: + """Save the raw data and the window totals of one optimisation window. + + Args: + output (Output): output settings. + bat_cfg (dict): battery variables. + markt (dict): variables and data of each market. + prob (pulp.LpProblem): solved problem. + time_information (tuple): start of the window, model time step + (minutes) and window length. + summary (dict): run summary, updated in place. + """ revenue = save_data_raw(output, bat_cfg, markt, prob, time_information, summary) save_window(output, bat_cfg, markt, prob, time_information, revenue) + def _rounded(value: Any, decimals: int = 2) -> Any: """Round floats; leave text, dates, integers and booleans unchanged.""" - if isinstance(value, numbers.Number) and not isinstance(value, (bool, numbers.Integral)): + if isinstance(value, numbers.Number) and not isinstance( + value, (bool, numbers.Integral) + ): return round(float(value), decimals) return value + # --- def summary_table(summary: dict[str, Any]) -> pd.DataFrame: """Turn the run summary into a table with one row per value: metric, value, unit.""" @@ -157,11 +215,11 @@ def summary_table(summary: dict[str, Any]) -> pd.DataFrame: unit = _SUMMARY_UNIT.get(key, "") if isinstance(value, dict): # market_revenues -> one row per market for name, sub_value in value.items(): - sub_value = _rounded(sub_value,2) - + sub_value = _rounded(sub_value, 2) + rows.append((f"{key}:{name}", sub_value, unit)) else: - value = _rounded(value,2) + value = _rounded(value, 2) rows.append((key, value, unit)) return pd.DataFrame(rows, columns=["metric", "value", "unit"]) diff --git a/tests/configuration_folder_tests/double_market.yml b/tests/configuration_folder_tests/double_market.yml index 6e37798..71ee531 100644 --- a/tests/configuration_folder_tests/double_market.yml +++ b/tests/configuration_folder_tests/double_market.yml @@ -29,6 +29,5 @@ simulation: output: path_to_save: null - basic_plot: False default_location: True clean_option: True \ No newline at end of file diff --git a/tests/configuration_folder_tests/single_market_a.yml b/tests/configuration_folder_tests/single_market_a.yml index a4208dc..a2c54b5 100644 --- a/tests/configuration_folder_tests/single_market_a.yml +++ b/tests/configuration_folder_tests/single_market_a.yml @@ -26,6 +26,5 @@ simulation: output: path_to_save: null - basic_plot: False default_location: True clean_option: True \ No newline at end of file diff --git a/tests/configuration_folder_tests/single_market_b.yml b/tests/configuration_folder_tests/single_market_b.yml index 5c6da7a..485abee 100644 --- a/tests/configuration_folder_tests/single_market_b.yml +++ b/tests/configuration_folder_tests/single_market_b.yml @@ -26,6 +26,5 @@ simulation: output: path_to_save: null - basic_plot: False default_location: True clean_option: True \ No newline at end of file diff --git a/tests/test_config_battery.py b/tests/test_config_battery.py index bd692db..5e23e69 100644 --- a/tests/test_config_battery.py +++ b/tests/test_config_battery.py @@ -2,7 +2,6 @@ from pathlib import Path import numpy as np - from opti_market.config_module import BATTERY, read_configuration @@ -14,6 +13,7 @@ def test_specification_battery(mname: str = "bt001"): assert np.isclose(bat.get_spec_battery("max_charge_rate"), 2.0, rtol=1e-2) assert np.isclose(bat.get_spec_battery("capex"), 500000, rtol=1e-2) + # --- def test_configure_battery(): # Read the battery and check wheter or not the name, and the other data are there. @@ -36,6 +36,8 @@ def test_configure_battery(): passed = False assert passed + + # --- def test_used_battery_cumulative_discharge(): """Test the analytical formulation for the total discharge.""" diff --git a/tests/test_config_read_market.py b/tests/test_config_read_market.py index 9099a77..73deab2 100644 --- a/tests/test_config_read_market.py +++ b/tests/test_config_read_market.py @@ -6,28 +6,33 @@ import opti_market.config_module -# --- +# --- def test_market_class(): - - pathtoconfig = str(Path(str(files("opti_market"))).resolve().parents[1] \ - / 'base_configuration' / 'double_market.yml') - + + pathtoconfig = str( + Path(str(files("opti_market"))).resolve().parents[1] + / "base_configuration" + / "double_market.yml" + ) + config_sim = opti_market.config_module.read_configuration(pathtoconfig) - markets = opti_market.config_module.Markets(config_sim['markets']) - + markets = opti_market.config_module.Markets(config_sim["markets"]) + assert len(markets.market_n1) == 52608 - assert len(markets.market_n2) == 26304 - -# --- + assert len(markets.market_n2) == 26304 + + +# --- def test_read_market(): - path = Path(str(files("opti_market"))).resolve().parents[1] / 'study_case' - - market1 = opti_market.config_module.read_market('market1.csv',str(path)) - - assert isinstance(market1,pd.DataFrame) -# --- - -if __name__ == '__main__': - - test_market_class() \ No newline at end of file + path = Path(str(files("opti_market"))).resolve().parents[1] / "study_case" + + market1 = opti_market.config_module.read_market("market1.csv", str(path)) + + assert isinstance(market1, pd.DataFrame) + + +# --- + +if __name__ == "__main__": + test_market_class() diff --git a/tests/test_configuration.py b/tests/test_configuration.py index efea0b4..ce930fe 100644 --- a/tests/test_configuration.py +++ b/tests/test_configuration.py @@ -5,8 +5,8 @@ def test_configuration(): - """Read the configuration files - Do basic checks. + """Read the configuration files + Do basic checks. """ pathtoconfig = str( diff --git a/tests/test_optimization.py b/tests/test_optimization.py index 2768031..786e902 100644 --- a/tests/test_optimization.py +++ b/tests/test_optimization.py @@ -16,20 +16,18 @@ from opti_market.optimisation_module import solve_problem -# --- -# --- +# --- +# --- @pytest.fixture(scope="session", autouse=True) def cleanup_output(): yield - pt = str( - Path(str(files("opti_market"))).resolve().parents[1] - / "results") - + pt = str(Path(str(files("opti_market"))).resolve().parents[1] / "results") shutil.rmtree(f"{pt}", ignore_errors=True) + +# --- # --- -# --- def read_summary(output: Output) -> tuple[float, float]: """Read the run summary and return (total revenue in GBP, battery cycles).""" file = Path(output.path_to_save) / "summary.csv" @@ -38,12 +36,15 @@ def read_summary(output: Output) -> tuple[float, float]: revenue = float(table["total_revenue"]) cycles = float(table["battery_cyles"]) return revenue, cycles + + # --- def test_integration_test_double(): - pathtoconfig = str( + pathtoconfig = str( Path(str(files("opti_market"))).resolve().parents[1] - / "tests" / "configuration_folder_tests" + / "tests" + / "configuration_folder_tests" / "double_market.yml" ) @@ -54,22 +55,24 @@ def test_integration_test_double(): markt = Markets(config_sim["markets"]) # Solution options: {To Do: seeing the other options} opti_opt = Opti_Market_Options.read_optimisation_options(config_sim["sim_options"]) - output = Output.read_output_configuration(dict_config=config_sim["output"] - , name_simulation=str(config_sim["name"])) - - - solve_problem(opti_opt=opti_opt, markt=markt, bat=bat,output=output) + output = Output.read_output_configuration( + dict_config=config_sim["output"], name_simulation=str(config_sim["name"]) + ) + + solve_problem(opti_opt=opti_opt, markt=markt, bat=bat, output=output) # See if the total revenue and total cycles are the correct one - rv,mc = read_summary(output=output) - assert np.isclose(rv,1182.95,rtol=1e-2) - assert np.isclose(mc,9.59,rtol=1e-2) -# --- -def test_integration_single_market_a(): + rv, mc = read_summary(output=output) + assert np.isclose(rv, 1182.95, rtol=1e-2) + assert np.isclose(mc, 9.59, rtol=1e-2) +# --- +def test_integration_single_market_a(): + pathtoconfig = str( Path(str(files("opti_market"))).resolve().parents[1] - / "tests" / "configuration_folder_tests" + / "tests" + / "configuration_folder_tests" / "single_market_a.yml" ) @@ -80,22 +83,24 @@ def test_integration_single_market_a(): markt = Markets(config_sim["markets"]) # Solution options: {To Do: seeing the other options} opti_opt = Opti_Market_Options.read_optimisation_options(config_sim["sim_options"]) - output = Output.read_output_configuration(dict_config=config_sim["output"] - , name_simulation=str(config_sim["name"])) - - - solve_problem(opti_opt=opti_opt, markt=markt, bat=bat,output=output) + output = Output.read_output_configuration( + dict_config=config_sim["output"], name_simulation=str(config_sim["name"]) + ) + + solve_problem(opti_opt=opti_opt, markt=markt, bat=bat, output=output) # See if the total revenue and total cycles are the correct one - rv,mc = read_summary(output=output) - assert np.isclose(rv,937.06,rtol=1e-2) - assert np.isclose(mc,9.48,rtol=1e-2) -# --- -def test_integration_single_market_b(): + rv, mc = read_summary(output=output) + assert np.isclose(rv, 937.06, rtol=1e-2) + assert np.isclose(mc, 9.48, rtol=1e-2) - pathtoconfig = str( +# --- +def test_integration_single_market_b(): + + pathtoconfig = str( Path(str(files("opti_market"))).resolve().parents[1] - / "tests" / "configuration_folder_tests" + / "tests" + / "configuration_folder_tests" / "single_market_b.yml" ) @@ -106,14 +111,16 @@ def test_integration_single_market_b(): markt = Markets(config_sim["markets"]) # Solution options: {To Do: seeing the other options} opti_opt = Opti_Market_Options.read_optimisation_options(config_sim["sim_options"]) - output = Output.read_output_configuration(dict_config=config_sim["output"] - , name_simulation=str(config_sim["name"])) - - - solve_problem(opti_opt=opti_opt, markt=markt, bat=bat,output=output) + output = Output.read_output_configuration( + dict_config=config_sim["output"], name_simulation=str(config_sim["name"]) + ) + + solve_problem(opti_opt=opti_opt, markt=markt, bat=bat, output=output) # See if the total revenue and total cycles are the correct one - rv,mc = read_summary(output=output) - assert np.isclose(rv,1092.28,rtol=1e-2) - assert np.isclose(mc,9.59,rtol=1e-2) + rv, mc = read_summary(output=output) + assert np.isclose(rv, 1092.28, rtol=1e-2) + assert np.isclose(mc, 9.59, rtol=1e-2) + + +# --- # --- -# --- \ No newline at end of file