Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add sanitize_locations function and apply it #913

Merged
merged 3 commits into from
Feb 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion config/test/config.perfect.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ scenario:
clusters:
- 5
sector_opts:
- 8760H-T-H-B-I-A-dist1
- 8760h-T-H-B-I-A-dist1
planning_horizons:
- 2030
- 2040
Expand Down
9 changes: 9 additions & 0 deletions scripts/add_electricity.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,15 @@ def sanitize_carriers(n, config):
n.carriers["color"] = n.carriers.color.where(n.carriers.color != "", colors)


def sanitize_locations(n):
n.buses["x"] = n.buses.x.where(n.buses.x != 0, n.buses.location.map(n.buses.x))
n.buses["y"] = n.buses.y.where(n.buses.y != 0, n.buses.location.map(n.buses.y))
n.buses["country"] = n.buses.country.where(
n.buses.country.ne("") & n.buses.country.notnull(),
n.buses.location.map(n.buses.country),
)


def add_co2_emissions(n, costs, carriers):
"""
Add CO2 emissions to the network's carriers attribute.
Expand Down
8 changes: 4 additions & 4 deletions scripts/add_extra_components.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@
import pandas as pd
import pypsa
from _helpers import configure_logging
from add_electricity import load_costs, sanitize_carriers
from add_electricity import load_costs, sanitize_carriers, sanitize_locations

idx = pd.IndexSlice

Expand Down Expand Up @@ -100,10 +100,9 @@ def attach_stores(n, costs, extendable_carriers):
n.madd("Carrier", carriers)

buses_i = n.buses.index
bus_sub_dict = {k: n.buses[k].values for k in ["x", "y", "country"]}

if "H2" in carriers:
h2_buses_i = n.madd("Bus", buses_i + " H2", carrier="H2", **bus_sub_dict)
h2_buses_i = n.madd("Bus", buses_i + " H2", carrier="H2", location=buses_i)

n.madd(
"Store",
Expand Down Expand Up @@ -143,7 +142,7 @@ def attach_stores(n, costs, extendable_carriers):

if "battery" in carriers:
b_buses_i = n.madd(
"Bus", buses_i + " battery", carrier="battery", **bus_sub_dict
"Bus", buses_i + " battery", carrier="battery", location=buses_i
)

n.madd(
Expand Down Expand Up @@ -246,6 +245,7 @@ def attach_hydrogen_pipelines(n, costs, extendable_carriers):
attach_hydrogen_pipelines(n, costs, extendable_carriers)

sanitize_carriers(n, snakemake.config)
sanitize_locations(n)

n.meta = dict(snakemake.config, **dict(wildcards=dict(snakemake.wildcards)))
n.export_to_netcdf(snakemake.output[0])
12 changes: 9 additions & 3 deletions scripts/make_summary.py
Original file line number Diff line number Diff line change
Expand Up @@ -507,7 +507,7 @@ def calculate_weighted_prices(n, label, weighted_prices):
if carrier in ["H2", "gas"]:
load = pd.DataFrame(index=n.snapshots, columns=buses, data=0.0)
else:
load = n.loads_t.p_set[buses]
load = n.loads_t.p_set[buses.intersection(n.loads.index)]

for tech in value:
names = n.links.index[n.links.index.to_series().str[-len(tech) :] == tech]
Expand Down Expand Up @@ -560,7 +560,10 @@ def calculate_market_values(n, label, market_values):
)
revenue = dispatch * n.buses_t.marginal_price[buses]

market_values.at[tech, label] = revenue.sum().sum() / dispatch.sum().sum()
if total_dispatch := dispatch.sum().sum():
market_values.at[tech, label] = revenue.sum().sum() / total_dispatch
else:
market_values.at[tech, label] = np.nan

## Now do market value of links ##

Expand All @@ -583,7 +586,10 @@ def calculate_market_values(n, label, market_values):

revenue = dispatch * n.buses_t.marginal_price[buses]

market_values.at[tech, label] = revenue.sum().sum() / dispatch.sum().sum()
if total_dispatch := dispatch.sum().sum():
market_values.at[tech, label] = revenue.sum().sum() / total_dispatch
else:
market_values.at[tech, label] = np.nan

return market_values

Expand Down
24 changes: 16 additions & 8 deletions scripts/make_summary_perfect.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ def calculate_energy(n, label, energy):
totals[no_bus] = float(
n.component_attrs[c.name].loc["p" + port, "default"]
)
c_energies -= totals.groupby(c.df.carrier, axis=1).sum()
c_energies -= totals.T.groupby(c.df.carrier).sum().T

c_energies = pd.concat([c_energies.T], keys=[c.list_name])

Expand Down Expand Up @@ -376,9 +376,8 @@ def calculate_supply_energy(n, label, supply_energy):
.groupby(level=0)
.sum()
.multiply(c.df.loc[items, "sign"])
.groupby(c.df.loc[items, "carrier"], axis=1)
.T.groupby(c.df.loc[items, "carrier"])
.sum()
.T
)
s = pd.concat([s], keys=[c.list_name])
s = pd.concat([s], keys=[i])
Expand Down Expand Up @@ -525,9 +524,12 @@ def calculate_weighted_prices(n, label, weighted_prices):
# stores[stores > 0.] = 0.
# load += -stores

weighted_prices.loc[carrier, label] = (
load * n.buses_t.marginal_price[buses]
).sum().sum() / load.sum().sum()
if total_load := load.sum().sum():
weighted_prices.loc[carrier, label] = (
load * n.buses_t.marginal_price[buses]
).sum().sum() / total_load
else:
weighted_prices.loc[carrier, label] = np.nan

if carrier[:5] == "space":
print(load * n.buses_t.marginal_price[buses])
Expand Down Expand Up @@ -562,7 +564,10 @@ def calculate_market_values(n, label, market_values):

revenue = dispatch * n.buses_t.marginal_price[buses]

market_values.at[tech, label] = revenue.sum().sum() / dispatch.sum().sum()
if total_dispatch := dispatch.sum().sum():
market_values.at[tech, label] = revenue.sum().sum() / total_dispatch
else:
market_values.at[tech, label] = np.nan

## Now do market value of links ##

Expand All @@ -585,7 +590,10 @@ def calculate_market_values(n, label, market_values):

revenue = dispatch * n.buses_t.marginal_price[buses]

market_values.at[tech, label] = revenue.sum().sum() / dispatch.sum().sum()
if total_dispatch := dispatch.sum().sum():
market_values.at[tech, label] = revenue.sum().sum() / total_dispatch
else:
market_values.at[tech, label] = np.nan

return market_values

Expand Down
4 changes: 3 additions & 1 deletion scripts/plot_hydrogen_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ def group_pipes(df, drop_direction=False):
lambda x: f"H2 pipeline {x.bus0.replace(' H2', '')} -> {x.bus1.replace(' H2', '')}",
axis=1,
)
return df.groupby(level=0).agg({"p_nom_opt": sum, "bus0": "first", "bus1": "first"})
return df.groupby(level=0).agg(
{"p_nom_opt": "sum", "bus0": "first", "bus1": "first"}
)


def plot_h2_map(n, regions):
Expand Down
2 changes: 1 addition & 1 deletion scripts/prepare_perfect_foresight.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ def concat_networks(years):
# set investment periods
n.investment_periods = n.snapshots.levels[0]
# weighting of the investment period -> assuming last period same weighting as the period before
time_w = n.investment_periods.to_series().diff().shift(-1).fillna(method="ffill")
time_w = n.investment_periods.to_series().diff().shift(-1).ffill()
n.investment_period_weightings["years"] = time_w
# set objective weightings
objective_w = get_investment_weighting(
Expand Down
17 changes: 16 additions & 1 deletion scripts/prepare_sector_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import pypsa
import xarray as xr
from _helpers import update_config_with_sector_opts
from add_electricity import calculate_annuity, sanitize_carriers
from add_electricity import calculate_annuity, sanitize_carriers, sanitize_locations
from build_energy_totals import build_co2_totals, build_eea_co2, build_eurostat_co2
from networkx.algorithms import complement
from networkx.algorithms.connectivity.edge_augmentation import k_edge_augmentation
Expand Down Expand Up @@ -546,6 +546,17 @@ def patch_electricity_network(n):
n.loads_t.p_set.rename(lambda x: x.strip(), axis=1, inplace=True)


def add_eu_bus(n, x=-5.5, y=46):
"""
Add EU bus to the network.

This cosmetic bus serves as a reference point for the location of
the EU buses in the plots and summaries.
"""
n.add("Bus", "EU", location="EU", x=x, y=y, carrier="none")
n.add("Carrier", "none")


def add_co2_tracking(n, costs, options):
# minus sign because opposite to how fossil fuels used:
# CH4 burning puts CH4 down, atmosphere up
Expand Down Expand Up @@ -1005,6 +1016,7 @@ def insert_electricity_distribution_grid(n, costs):
"Store",
nodes + " home battery",
bus=nodes + " home battery",
location=nodes,
e_cyclic=True,
e_nom_extendable=True,
carrier="home battery",
Expand Down Expand Up @@ -3594,6 +3606,8 @@ def lossy_bidirectional_links(n, carrier, efficiencies={}):
for carrier in conventional:
add_carrier_buses(n, carrier)

add_eu_bus(n)

add_co2_tracking(n, costs, options)

add_generation(n, costs)
Expand Down Expand Up @@ -3733,5 +3747,6 @@ def lossy_bidirectional_links(n, carrier, efficiencies={}):
n.meta = dict(snakemake.config, **dict(wildcards=dict(snakemake.wildcards)))

sanitize_carriers(n, snakemake.config)
sanitize_locations(n)

n.export_to_netcdf(snakemake.output[0])
Loading