From 8b0bed3335d0d32246e9e393bdfba176b7857621 Mon Sep 17 00:00:00 2001 From: Nick Harder Date: Wed, 13 Nov 2024 09:31:12 +0100 Subject: [PATCH] -remove duplicated code into a function --- assume/common/utils.py | 16 ++++++++++++++++ assume/units/building.py | 29 ++++++++++++----------------- 2 files changed, 28 insertions(+), 17 deletions(-) diff --git a/assume/common/utils.py b/assume/common/utils.py index 0c224871..5b1eedf5 100644 --- a/assume/common/utils.py +++ b/assume/common/utils.py @@ -674,3 +674,19 @@ def suppress_output(): os.close(saved_stdout_fd) os.close(saved_stderr_fd) os.close(devnull) + + +def str_to_bool(val): + """Convert a string representation of truth to True or False. + + True values are 'y', 'yes', 't', 'true', 'on', and '1'; + false values are 'n', 'no', 'f', 'false', 'off', and '0'. + Raises ValueError if 'val' is anything else. + """ + val = val.lower() + if val in {"y", "yes", "t", "true", "on", "1"}: + return True + elif val in {"n", "no", "f", "false", "off", "0"}: + return False + else: + raise ValueError(f"Invalid truth value: {val!r}") diff --git a/assume/units/building.py b/assume/units/building.py index 988cf6bf..21a943d9 100644 --- a/assume/units/building.py +++ b/assume/units/building.py @@ -14,6 +14,7 @@ ) from assume.common.base import SupportsMinMax +from assume.common.utils import str_to_bool from assume.units.dsm_load_shift import DSMFlex SOLVERS = ["appsi_highs", "gurobi", "glpk", "cbc", "cplex"] @@ -134,28 +135,22 @@ def __init__( # Configuration for electric vehicles selling energy to the market if self.has_ev: - self.ev_sells_energy_to_market = self.components["electric_vehicle"].get( - "sells_energy_to_market", "true" - ).lower() in {"y", "yes", "t", "true", "on", "1"} - + self.ev_sells_energy_to_market = str_to_bool( + self.components["electric_vehicle"].get( + "sells_energy_to_market", "true" + ) + ) # Configuration for battery storage selling energy to the market if self.has_battery_storage: - self.battery_sells_energy_to_market = self.components[ - "generic_storage" - ].get("sells_energy_to_market", "true").lower() in { - "y", - "yes", - "t", - "true", - "on", - "1", - } + self.battery_sells_energy_to_market = str_to_bool( + self.components["generic_storage"].get("sells_energy_to_market", "true") + ) # Configure PV plant power profile based on availability if self.has_pv: - uses_power_profile = self.components["pv_plant"].get( - "uses_power_profile", "false" - ).lower() in {"y", "yes", "t", "true", "on", "1"} + uses_power_profile = str_to_bool( + self.components["pv_plant"].get("uses_power_profile", "false") + ) profile_key = ( f"{self.id}_pv_power_profile" if not uses_power_profile