Skip to content

Commit

Permalink
fix: ZeroDivision Error (#288)
Browse files Browse the repository at this point in the history
* fix: ZeroDivision Error

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* feat: safe division via helpers

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix ValueError

* fix: value error

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update scripts/helpers.py

Co-authored-by: Davide Fioriti <[email protected]>

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Davide Fioriti <[email protected]>
  • Loading branch information
3 people authored Feb 28, 2024
1 parent e26df4c commit 0fcefa8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
13 changes: 13 additions & 0 deletions scripts/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -746,3 +746,16 @@ def read_csv_nafix(file, **kwargs):
return pd.read_csv(file, **kwargs)
else:
return pd.DataFrame()


def safe_divide(numerator, denominator, default_value=np.nan):
"""
Safe division function that returns NaN when the denominator is zero
"""
if denominator != 0.0:
return numerator / denominator
else:
logging.warning(
f"Division by zero: {numerator} / {denominator}, returning NaN."
)
return np.nan
15 changes: 8 additions & 7 deletions scripts/prepare_sector_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
mock_snakemake,
override_component_attrs,
prepare_costs,
safe_divide,
three_2_two_digits_country,
two_2_three_digits_country,
)
Expand Down Expand Up @@ -2229,13 +2230,13 @@ def add_residential(n, costs):
)

heat_buses = (n.loads_t.p_set.filter(regex="heat").filter(like=country)).columns
n.loads_t.p_set.loc[:, heat_buses] = (
(
n.loads_t.p_set.filter(like=country)[heat_buses]
/ n.loads_t.p_set.filter(like=country)[heat_buses].sum().sum()
)
* rem_heat_demand
* 1e6

safe_division = safe_divide(
n.loads_t.p_set.filter(like=country)[heat_buses],
n.loads_t.p_set.filter(like=country)[heat_buses].sum().sum(),
)
n.loads_t.p_set.loc[:, heat_buses] = np.where(
~np.isnan(safe_division), safe_division * rem_heat_demand * 1e6, 0.0
)

# if snakemake.config["custom_data"]["elec_demand"]:
Expand Down

0 comments on commit 0fcefa8

Please sign in to comment.