├── scripts ├── plotting │ ├── __init__.py │ ├── collection.py │ ├── convergence.py │ ├── single_pf.py │ ├── single_lopf.py │ ├── space.py │ ├── single_lopf_pf.py │ ├── utils.py │ ├── multiple_lopf.py │ ├── stats.py │ └── map.py ├── power_flow.py ├── _loss_models.py ├── solve_network.py └── plotting.ipynb ├── .gitmodules ├── .gitignore ├── config.yaml ├── Snakefile ├── README.md ├── config.pypsaeur.yaml └── LICENSE /scripts/plotting/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "pypsa-eur"] 2 | path = pypsa-eur 3 | url = https://github.com/PyPSA/pypsa-eur.git 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *__pycache__ 2 | .snakemake 3 | .vscode 4 | dconf 5 | results 6 | *.ipynb_checkpoints 7 | *.ipynb 8 | summary 9 | *.nc 10 | *.log 11 | *.pdf 12 | *.png 13 | 14 | -------------------------------------------------------------------------------- /scripts/plotting/collection.py: -------------------------------------------------------------------------------- 1 | """ 2 | Collection of plotting functions. 3 | """ 4 | 5 | __author__ = "Fabian Neumann (KIT)" 6 | __copyright__ = "Copyright 2019-2020 Fabian Neumann (KIT), GNU GPL 3" 7 | 8 | from .map import plot_network 9 | from .stats import ( 10 | check_capacities, 11 | check_costs, 12 | check_curtailment, 13 | check_energy_balance, 14 | check_energy_generated, 15 | check_energy_transmitted, 16 | check_flow_errors, 17 | check_slack, 18 | ) 19 | from .single_lopf import plot_flow_vs_loss, plot_negative_marginal_prices 20 | from .single_pf import plot_network_losses, plot_v_ang_diff 21 | from .single_lopf_pf import ( 22 | plot_duration_curve, 23 | plot_flow_comparison, 24 | plot_loss_comparison, 25 | ) 26 | from .multiple_lopf import plot_performance, plot_cost_bar, plot_capacity_correlation, plot_price_duration_curve 27 | from .convergence import plot_nonconverged, convergence_share 28 | from .space import plot_feasible_space 29 | -------------------------------------------------------------------------------- /config.yaml: -------------------------------------------------------------------------------- 1 | logging_level: INFO 2 | 3 | scenario: 4 | clusters: [150] 5 | opts: [2H] 6 | model: 7 | [ 8 | transport, 9 | lossytransport, 10 | lossless-0, 11 | lossless-3, 12 | lossy-3-0, 13 | lossy-5-0, 14 | lossy-3-3, 15 | lossy-5-3, 16 | ] 17 | slack: [distributed] 18 | 19 | lines: 20 | s_nom_add: 5000 21 | s_nom_factor: 2 22 | s_max_pu: 0.7 23 | loss_per_length: 5.e-5 # only applies to lossy transport model 24 | 25 | links: 26 | p_nom_max: 16000 27 | loss_per_length: 3.e-5 28 | 29 | solving: 30 | options: 31 | min_iterations: 3 32 | max_iterations: 3 33 | formulation: kirchhoff 34 | load_shedding: true 35 | noisy_costs: false 36 | clip_p_max_pu: 0.01 37 | solver: 38 | name: gurobi 39 | threads: 4 40 | method: 2 # barrier 41 | crossover: 0 42 | BarConvTol: 1.e-4 43 | FeasibilityTol: 1.e-4 44 | AggFill: 0 45 | PreDual: 0 46 | BarHomogeneous: 1 47 | GURO_PAR_BARDENSETHRESH: 200 48 | # ResultFile: "model.ilp" 49 | # ScaleFlag: 2 50 | # NumericFocus: 2 51 | -------------------------------------------------------------------------------- /scripts/plotting/convergence.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plotting functions regarding the NR power flow convergence rate of subnetworks. 3 | """ 4 | 5 | __author__ = "Fabian Neumann (KIT)" 6 | __copyright__ = "Copyright 2019-2020 Fabian Neumann (KIT), GNU GPL 3" 7 | 8 | import matplotlib.pyplot as plt 9 | 10 | 11 | # careful, this is a bit hard-coded! 12 | def convergence_share(log, fm): 13 | conv = log.converged.astype(int) 14 | conv.columns = [ 15 | "Continental Europe", 16 | "Nordic", 17 | "Baltic", 18 | "Mallorca", 19 | "Ireland", 20 | "Great Britain", 21 | "Sicily", 22 | ] 23 | conv = conv.drop(columns=["Mallorca", "Sicily"]) 24 | conv_share = (1 - conv.sum() / len(conv)) * 100 # % 25 | conv_share.name = fm 26 | return conv_share 27 | 28 | 29 | def plot_nonconverged(conv_share, model_names, fn=None): 30 | 31 | fig, ax = plt.subplots(figsize=(6, 2.5)) 32 | conv_share.rename(columns=model_names, inplace=True) 33 | conv_share.T.plot.bar(ax=ax) 34 | 35 | plt.legend(title="Synchronous Zone") 36 | plt.ylabel("Snapshots not\nconverged [%]") 37 | 38 | if fn is not None: 39 | plt.savefig(fn, bbox_inches="tight") 40 | -------------------------------------------------------------------------------- /scripts/plotting/single_pf.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plotting functions regarding a single PF network (checked power flow). 3 | """ 4 | 5 | __author__ = "Fabian Neumann (KIT)" 6 | __copyright__ = "Copyright 2019-2020 Fabian Neumann (KIT), GNU GPL 3" 7 | 8 | import matplotlib.pyplot as plt 9 | import cartopy.crs as ccrs 10 | import numpy as np 11 | 12 | from .utils import line_loading 13 | 14 | 15 | def plot_network_losses(n, fn=None): 16 | 17 | lc = n.lines_t.loss.mean() 18 | lw = line_loading(n, apparent=False, relative=False).mean() / 700 19 | 20 | fig, ax = plt.subplots( 21 | figsize=(7, 7), subplot_kw={"projection": ccrs.PlateCarree()} 22 | ) 23 | 24 | n.plot( 25 | ax=ax, 26 | color_geomap=True, 27 | line_widths=lw, 28 | line_colors=lc, 29 | bus_sizes=5e-3, 30 | bus_colors="darkgray", 31 | bus_alpha=0.8, 32 | link_widths=0, 33 | ) 34 | 35 | if fn is not None: 36 | plt.savefig(fn, bbox_inches="tight") 37 | 38 | 39 | def plot_v_ang_diff(n_pf, fn=None): 40 | 41 | v_ang_1 = n_pf.buses_t.v_ang.loc[:, n_pf.lines.bus1] 42 | v_ang_1.columns = n_pf.lines.index 43 | 44 | v_ang_0 = n_pf.buses_t.v_ang.loc[:, n_pf.lines.bus0] 45 | v_ang_0.columns = n_pf.lines.index 46 | 47 | v_ang_diff = (v_ang_1 - v_ang_0).applymap(lambda x: x * 180 / np.pi) 48 | 49 | fig, ax = plt.subplots(figsize=(5, 3)) 50 | 51 | v_ang_diff.stack().plot.hist(bins=np.arange(-90, 90, 5), density=True) 52 | 53 | plt.xticks(np.arange(-90, 90, 10), rotation=90) 54 | 55 | plt.xlabel("Voltage Angle Difference [Degrees]") 56 | 57 | if fn is not None: 58 | plt.savefig(fn, bbox_inches="tight") 59 | 60 | -------------------------------------------------------------------------------- /scripts/power_flow.py: -------------------------------------------------------------------------------- 1 | """ 2 | Run power flow on solved networks. 3 | """ 4 | 5 | __author__ = "Fabian Neumann (KIT), Anika Bitsch (KIT)" 6 | __copyright__ = ( 7 | "Copyright 2019-2020 Fabian Neumann (KIT), Anika Bitsch (KIT), GNU GPL 3" 8 | ) 9 | 10 | import pypsa 11 | import pandas as pd 12 | 13 | import logging 14 | 15 | logger = logging.getLogger(__name__) 16 | 17 | 18 | if __name__ == "__main__": 19 | 20 | logging.basicConfig( 21 | filename=snakemake.log.python, level=snakemake.config["logging_level"] 22 | ) 23 | 24 | slack = True if snakemake.wildcards.slack == "distributed" else False 25 | 26 | n = pypsa.Network(snakemake.input[0]) 27 | 28 | # remove load shedding generators (for distribution of slack) 29 | n.mremove("Generator", n.generators.loc[n.generators.carrier == "load"].index) 30 | 31 | set_components = n.controllable_one_port_components.union( 32 | n.controllable_branch_components 33 | ) - {"Load"} 34 | for c in n.iterate_components(set_components): 35 | if not c.df.empty: 36 | attr = "p0" if c.name == "Link" else "p" 37 | c.pnl.p_set = c.pnl.p_set.reindex(columns=c.df.index) 38 | c.pnl.p_set = c.pnl[attr] 39 | 40 | # set all buses to PV, since we don't know what Q set points are 41 | n.generators.control = "PV" 42 | 43 | # Need some PQ buses so that Jacobian doesn't break 44 | init_bus = n.buses.index[0] 45 | pq_gen_selection = n.generators[n.generators.bus == init_bus] 46 | n.generators.loc[pq_gen_selection.index, "control"] = "PQ" 47 | 48 | log = n.pf(distribute_slack=slack) 49 | 50 | pd.concat(log, axis=1).to_csv(snakemake.output.pf_log) 51 | 52 | n.export_to_netcdf(snakemake.output.network) 53 | -------------------------------------------------------------------------------- /scripts/plotting/single_lopf.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plotting functions regarding a single LOPF network. 3 | """ 4 | 5 | __author__ = "Fabian Neumann (KIT)" 6 | __copyright__ = "Copyright 2019-2020 Fabian Neumann (KIT), GNU GPL 3" 7 | 8 | import matplotlib.pyplot as plt 9 | import pandas as pd 10 | 11 | from .utils import reference, plot_hist_helper 12 | 13 | 14 | def plot_flow_vs_loss(n, norm="max", style="hist2d", vmax=100, title="", fn=None): 15 | 16 | fig, ax = plt.subplots(figsize=(6, 5)) 17 | 18 | loading = (n.lines_t.p0 / n.lines[f"s_nom_{norm}"] / n.lines.s_max_pu).stack() 19 | max_loss = n.lines.r_pu_eff * (n.lines.s_max_pu * n.lines[f"s_nom_{norm}"]) ** 2 20 | relative_loss = (n.lines_t.loss / max_loss).stack() 21 | 22 | xlim = [-1, 1] 23 | ylim = [0, 1.1] 24 | 25 | plot_hist_helper(ax, loading, relative_loss, xlim, ylim, vmax=vmax, style=style) 26 | 27 | reference(ax, *xlim, f=lambda x: x ** 2) 28 | 29 | if style in ["hexbin", "hist2d"]: 30 | cb = plt.colorbar(ax=ax, shrink=0.95) 31 | cb.set_label("Count") 32 | 33 | ax.set_ylim(ylim) 34 | ax.set_xlim(xlim) 35 | 36 | plt.ylabel("Rel. Losses (LOPF)") 37 | plt.xlabel("Rel. Line Flows (LOPF)") 38 | 39 | plt.title(title) 40 | 41 | if fn is not None: 42 | plt.savefig(fn, bbox_inches="tight") 43 | 44 | 45 | def plot_negative_marginal_prices(n, fn=None, max_mp=-0.5): 46 | 47 | mp = n.buses_t.marginal_price.stack() 48 | 49 | neg_mp = pd.Series(mp.loc[mp < max_mp].sort_values().values) 50 | 51 | if neg_mp.empty: 52 | return 53 | 54 | fig, ax = plt.subplots(figsize=(4, 3)) 55 | neg_mp.plot(ax=ax) 56 | 57 | plt.ylabel("EUR/MWh") 58 | plt.xlabel("Count") 59 | plt.title(f"Frequency: {len(neg_mp) / len(mp) * 100:f} %") 60 | 61 | if fn is not None: 62 | plt.savefig(fn, bbox_inches="tight") 63 | -------------------------------------------------------------------------------- /scripts/plotting/space.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plotting functions to portray feasible space in loss/flow domain. 3 | """ 4 | 5 | __author__ = "Fabian Neumann (KIT)" 6 | __copyright__ = "Copyright 2019-2020 Fabian Neumann (KIT), GNU GPL 3" 7 | 8 | import matplotlib.pyplot as plt 9 | import numpy as np 10 | 11 | from matplotlib.lines import Line2D 12 | 13 | 14 | def plot_feasible_space(line, fn=None): 15 | 16 | print(line[["s_nom", "s_max_pu", "r_pu_eff", "s_nom_max"]]) 17 | 18 | fig, ax = plt.subplots(figsize=(5, 4.5)) 19 | 20 | x = np.linspace(-line.s_nom, line.s_nom, 100) 21 | 22 | plt.plot(x, line.r_pu_eff * x ** 2, c="k", label=r"$\psi=rp^2$") 23 | 24 | plt.axhline(0, c="firebrick", label=r"$\psi\geq 0$") 25 | 26 | max_loss = line.r_pu_eff * (line.s_max_pu * line.s_nom) ** 2 27 | ax.axhline(max_loss, c="darkseagreen", label=r"$\psi\leq r(\bar{p}P)^2$") 28 | 29 | flow_upper = -x + line.s_max_pu * line.s_nom 30 | flow_lower = x + line.s_max_pu * line.s_nom 31 | plt.plot(x, flow_upper, c="navy", linestyle="--", label=r"$\psi+|p| \leq \bar{p}P$") 32 | plt.plot(x, flow_lower, c="navy", linestyle="--") 33 | 34 | tangents = [] 35 | for k in [1, 2]: 36 | p_k = k / 2 * line.s_max_pu * line.s_nom 37 | loss_k = line.r_pu_eff * p_k ** 2 38 | slope_k = 2 * line.r_pu_eff * p_k 39 | offset_k = loss_k - slope_k * p_k 40 | for sign in [-1, 1]: 41 | tangent = sign * slope_k * x + offset_k 42 | tangents.append(tangent) 43 | plt.plot(x, tangent, c="k", linestyle=":") 44 | min_loss = [min(max_loss, max(0, max(i))) for i in zip(*tangents)] 45 | plt.fill_between( 46 | x, max_loss, min_loss, alpha=0.2, color="firebrick", label="Feasible Space" 47 | ) 48 | 49 | handles, labels = ax.get_legend_handles_labels() 50 | handles.append(Line2D([0], [0], color="k", linestyle=":", label="Tangents")) 51 | 52 | plt.xlabel("Line Flow [MW]") 53 | plt.ylabel("Line Losses [MW]") 54 | plt.ylim([-5, max_loss / line.s_max_pu ** 2 * 0.8]) 55 | plt.legend(handles=handles) 56 | 57 | if fn is not None: 58 | plt.savefig(fn, bbox_inches="tight") 59 | -------------------------------------------------------------------------------- /Snakefile: -------------------------------------------------------------------------------- 1 | configfile: "config.yaml" 2 | 3 | subworkflow pypsaeur: 4 | workdir: "pypsa-eur" 5 | configfile: "config.pypsaeur.yaml" 6 | 7 | wildcard_constraints: 8 | clusters="[0-9]+m?|all", 9 | opts="[-+a-zA-Z0-9\.]*", 10 | model="(transport|lossytransport|lossless-[0-9]+|lossy-[0-9]+-[0-9]+)", 11 | slack="(distributed|regular)" 12 | 13 | 14 | # adapted from https://github.com/PyPSA/pypsa-eur/blob/master/Snakefile 15 | def memory(w): 16 | factor = 3. 17 | for o in w.opts.split('-'): 18 | m = re.match(r'^(\d+)h$', o, re.IGNORECASE) 19 | if m is not None: 20 | factor /= int(m.group(1)) 21 | break 22 | if "lossy-" in w.model: 23 | factor *= 0.45 * int(w.model.split("-")[-2]) 24 | return min(245000, int(factor * (10000 + 195 * int(w.clusters)))) 25 | 26 | 27 | # SOLVING RULES 28 | 29 | rule solve_network: 30 | input: pypsaeur("networks/elec_s_{clusters}_ec_lcopt_{opts}.nc") 31 | output: "results/networks/elec_s_{clusters}_ec_lcopt_{opts}_M{model}.nc" 32 | log: 33 | solver="logs/elec_s_{clusters}_lcopt_{opts}_M{model}_solver.log", 34 | python="logs/elec_s_{clusters}_lcopt_{opts}_M{model}_python.log", 35 | memory="logs/elec_s_{clusters}_lcopt_{opts}_M{model}_memory.log" 36 | threads: 4 37 | resources: mem=memory 38 | script: "scripts/solve_network.py" 39 | 40 | rule solve_all_networks: 41 | input: 42 | expand("results/networks/elec_s_{clusters}_ec_lcopt_{opts}_M{model}.nc", 43 | **config["scenario"]) 44 | 45 | 46 | # POWER FLOW RULES 47 | 48 | rule check_powerflow: 49 | input: "results/networks/elec_s_{clusters}_ec_lcopt_{opts}_M{model}.nc" 50 | log: 51 | python="logs/elec_s_{clusters}_lcopt_{opts}_M{model}_S{slack}_python.log" 52 | output: 53 | network="results/pf/elec_s_{clusters}_ec_lcopt_{opts}_M{model}_S{slack}.nc", 54 | pf_log="results/pf/log_elec_s_{clusters}_ec_lcopt_{opts}_M{model}_S{slack}.csv" 55 | script: "scripts/power_flow.py" 56 | 57 | rule check_all_powerflows: 58 | input: 59 | expand("results/pf/elec_s_{clusters}_ec_lcopt_{opts}_M{model}_S{slack}.nc", 60 | **config["scenario"]), 61 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Comparison of Power Flow and Loss Models in PyPSA-Eur 2 | 3 | With rising shares of renewables and the need to properly 4 | assess trade-offs between transmission, storage and sectoral integration as balancing options, 5 | building a bridge between energy system models and detailed power flow 6 | studies becomes increasingly important, but is computationally challenging. 7 | 8 | In this paper, we compare both common and improved 9 | approximations for two nonlinear phenomena, 10 | power flow and transmission losses, in linear capacity expansion problems 11 | that co-optimise investments in generation, storage and transmission infrastructure. 12 | 13 | We evaluate different flow representations discussing differences in investment decisions, 14 | nodal prices, the deviation of optimised flows and losses 15 | from simulated AC power flows, and the computational performance. 16 | 17 | By using the open European power system model \mbox{PyPSA-Eur}, 18 | that combines high spatial and temporal resolution, 19 | we obtain detailed and reproducible benchmarks aiming at 20 | facilitating the selection of a suitable power flow model. 21 | 22 | Given the differences in complexity, the optimal choice 23 | depends on the application, the access to computational 24 | resources, and the level of spatial detail considered. 25 | 26 | Although the commonly used transport model can already identify key features 27 | of a cost-efficient system while being computationally performant, 28 | deficiencies under high loading conditions are revealed 29 | due to the lack of a physical grid representation. 30 | Moreover, disregarding transmission losses overestimates optimal grid expansion by 20\%. 31 | 32 | Adding a convex relaxation of quadratic losses with two or three tangents to the linearised 33 | power flow equations and accounting for changing line impedances as the network is reinforced 34 | suffices to accurately represent active power flows and losses in design studies. 35 | These outputs are then sufficiently physical to be used in more detailed nonlinear simulations, 36 | for instance to determine reactive power flows and voltages or dynamic analyses. 37 | 38 | ## Usage 39 | 40 | Install common `pypsa-eur` environment and execute snakemake workflow. 41 | 42 | ```sh 43 | conda activate pypsa-eur 44 | cd power-flow-models 45 | snakemake -j 99 check_all_powerflows 46 | ``` 47 | -------------------------------------------------------------------------------- /scripts/plotting/single_lopf_pf.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plotting functions regarding a single network using both LOPF and PF outputs. 3 | """ 4 | 5 | __author__ = "Fabian Neumann (KIT)" 6 | __copyright__ = "Copyright 2019-2020 Fabian Neumann (KIT), GNU GPL 3" 7 | 8 | import matplotlib.pyplot as plt 9 | import numpy as np 10 | import pandas as pd 11 | 12 | from .utils import reference, plot_hist_helper, line_loading 13 | 14 | 15 | def plot_loss_comparison( 16 | n, n_pf, style="hist2d", vmax=100, title="", fn=None, norm="max" 17 | ): 18 | 19 | fig, ax = plt.subplots(figsize=(6, 5)) 20 | 21 | max_loss = n.lines.r_pu_eff * (n.lines.s_max_pu * n.lines[f"s_nom_{norm}"]) ** 2 22 | 23 | pf_loss = ((n_pf.lines_t.p0 + n_pf.lines_t.p1) / max_loss).stack() 24 | lopf_loss = (n.lines_t.loss / max_loss).stack() 25 | 26 | xlim = [0, 1] 27 | ylim = [0, 1.2] 28 | 29 | plot_hist_helper(ax, lopf_loss, pf_loss, xlim, ylim, style=style, vmax=vmax) 30 | 31 | reference(ax, *xlim, f=lambda x: x) 32 | 33 | if style in ["hexbin", "hist2d"]: 34 | cb = plt.colorbar(ax=ax, shrink=0.95) 35 | cb.set_label("Count") 36 | 37 | ax.set_ylim(ylim) 38 | ax.set_xlim(xlim) 39 | 40 | plt.xlabel("Rel. Losses (LOPF)") 41 | plt.ylabel("Rel. Losses (PF)") 42 | 43 | plt.title(title) 44 | 45 | if fn is not None: 46 | plt.savefig(fn, bbox_inches="tight") 47 | 48 | 49 | def plot_flow_comparison(n, n_pf, style="hist2d", vmax=600, title="", fn=None): 50 | 51 | pf = n_pf.lines_t.relative_loading.stack() 52 | lopf = n.lines_t.relative_loading.stack() 53 | 54 | fig, ax = plt.subplots(figsize=(6, 5)) 55 | 56 | xlim = [-1.2, 1.2] 57 | ylim = [-0.8, 0.8] 58 | 59 | plot_hist_helper(ax, pf, lopf, xlim, ylim, style=style, vmax=vmax) 60 | 61 | if style in ["hexbin", "hist2d"]: 62 | cb = plt.colorbar(ax=ax, shrink=0.65) 63 | cb.set_label("Count") 64 | 65 | reference(ax, -1, 1) 66 | 67 | ax.set_ylim(ylim) 68 | ax.set_xlim(xlim) 69 | 70 | ax.set_yticks(np.arange(ylim[0], ylim[1] + 0.1, 0.2)) 71 | ax.set_xticks(np.arange(xlim[0], xlim[1] + 0.1, 0.2)) 72 | plt.xticks(rotation=90) 73 | 74 | ax.set_aspect(1) 75 | 76 | plt.xlabel("Rel. Line Flows (PF)") 77 | plt.ylabel("Rel. Line Flows (LOPF)") 78 | 79 | plt.title(title) 80 | 81 | if fn is not None: 82 | plt.savefig(fn, bbox_inches="tight") 83 | 84 | 85 | def plot_duration_curve(n, n_pf, apparent=True, fn=None): 86 | 87 | fig, ax = plt.subplots(figsize=(4, 3)) 88 | 89 | def duration_curve(nc, s=True, label=""): 90 | series = pd.Series( 91 | line_loading(nc, apparent=s).stack().sort_values(ascending=False).values 92 | ) 93 | series.index = [i / len(series) * 100 for i in series.index] 94 | series.plot(ax=ax, label=label) 95 | 96 | duration_curve(n, s=False, label="LOPF (Approx. power flow)") 97 | duration_curve(n_pf, s=apparent, label="PF (AC power flow)") 98 | 99 | plt.ylim([-0.1, 1.4]) 100 | plt.legend(loc="upper right") 101 | plt.ylabel("Relative Line Loading [-]") 102 | plt.xlabel("Share of Snapshots [%]") 103 | 104 | if fn is not None: 105 | plt.savefig(fn, bbox_inches="tight") 106 | -------------------------------------------------------------------------------- /scripts/plotting/utils.py: -------------------------------------------------------------------------------- 1 | """ 2 | Utility functions for plotting functionality. 3 | """ 4 | 5 | __author__ = "Fabian Neumann (KIT)" 6 | __copyright__ = "Copyright 2019-2020 Fabian Neumann (KIT), GNU GPL 3" 7 | 8 | import pandas as pd 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | 12 | 13 | def load_memory(fn): 14 | memlog = pd.read_csv( 15 | fn, sep=" ", index_col=1, usecols=[1, 2], header=None 16 | ).squeeze() 17 | memlog.index = [t - memlog.index[0] for t in memlog.index] 18 | return memlog 19 | 20 | 21 | def aggregate_costs(n, existing_only=False, by_carrier=True): 22 | 23 | components = dict( 24 | Link=("p_nom", "p0"), 25 | Generator=("p_nom", "p"), 26 | StorageUnit=("p_nom", "p"), 27 | Store=("e_nom", "p"), 28 | Line=("s_nom", None), 29 | ) 30 | 31 | costs = {} 32 | for c in n.iterate_components(components.keys()): 33 | p_nom, p_attr = components[c.name] 34 | if c.df.empty: 35 | continue 36 | if not existing_only: 37 | p_nom += "_opt" 38 | costs[(c.list_name, "capital")] = ( 39 | (c.df[p_nom] * c.df.capital_cost).groupby(c.df.carrier).sum() 40 | ) 41 | if p_attr is not None: 42 | p = c.pnl[p_attr].multiply(n.snapshot_weightings, axis=0).sum() 43 | if c.name == "StorageUnit": 44 | p = p.loc[p > 0] 45 | costs[(c.list_name, "marginal")] = ( 46 | (p * c.df.marginal_cost).groupby(c.df.carrier).sum() 47 | ) 48 | costs = pd.concat(costs) / 1e9 # bn EUR/a 49 | 50 | if by_carrier: 51 | costs = costs.groupby(level=2).sum() 52 | 53 | return costs 54 | 55 | 56 | def assign_carriers(n): 57 | 58 | if "Load" in n.carriers.index: 59 | n.carriers = n.carriers.drop("Load") 60 | 61 | if "carrier" not in n.lines: 62 | n.lines["carrier"] = "AC" 63 | 64 | if n.links.empty: 65 | n.links["carrier"] = pd.Series(dtype=str) 66 | 67 | config = { 68 | "AC": {"color": "rosybrown", "nice_name": "HVAC Line"}, 69 | "DC": {"color": "darkseagreen", "nice_name": "HVDC Link"}, 70 | } 71 | 72 | for c in ["AC", "DC"]: 73 | if c in n.carriers.index: 74 | continue 75 | n.carriers = n.carriers.append(pd.Series(config[c], name=c)) 76 | 77 | 78 | def line_loading(n, apparent=True, relative=True): 79 | p = np.maximum(n.lines_t.p0.abs(), n.lines_t.p1.abs()) 80 | 81 | if apparent: 82 | q = np.maximum(n.lines_t.q0.abs(), n.lines_t.q1.abs()) 83 | else: 84 | q = 0 85 | 86 | s = np.sqrt(p ** 2 + q ** 2) 87 | 88 | if relative: 89 | return s / n.lines.s_nom_opt 90 | else: 91 | return s 92 | 93 | 94 | def plot_hist_helper(ax, x, y, xlim, ylim, style="hexbin", vmin=0, vmax=400): 95 | 96 | if style == "scatter": 97 | ax.scatter(x, y, alpha=0.2, marker=".") 98 | elif style == "hexbin": 99 | scope = xlim + ylim 100 | plt.hexbin( 101 | x, 102 | y, 103 | gridsize=100, 104 | cmap=plt.cm.viridis, 105 | vmin=vmin, 106 | vmax=vmax, 107 | extent=xlim + ylim, 108 | ) 109 | elif style == "hist2d": 110 | scope = np.array([xlim, ylim]) 111 | plt.hist2d( 112 | x, 113 | y, 114 | bins=100, 115 | cmap=plt.cm.viridis, 116 | vmin=vmin, 117 | vmax=vmax, 118 | linewidths=0, 119 | range=scope, 120 | ) 121 | 122 | 123 | def reference(ax, low, high, res=100, lw=1, c="k", f=lambda x: x): 124 | x = np.linspace(low, high, res) 125 | ax.plot(x, f(x), c="k", linewidth=lw) 126 | -------------------------------------------------------------------------------- /scripts/plotting/multiple_lopf.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plotting functions regarding multiple LOPF networks at once. 3 | """ 4 | 5 | __author__ = "Fabian Neumann (KIT)" 6 | __copyright__ = "Copyright 2019-2020 Fabian Neumann (KIT), GNU GPL 3" 7 | 8 | import pandas as pd 9 | import matplotlib.pyplot as plt 10 | import numpy as np 11 | import seaborn as sns 12 | 13 | from .utils import aggregate_costs, assign_carriers 14 | 15 | 16 | def process_logs(logs): 17 | attrs = ["time", "peak_mem"] 18 | df = pd.DataFrame(columns=logs.keys(), index=attrs) 19 | for fm, mem in logs.items(): 20 | df.at["time", fm] = mem.index[-1] / 3600 # h 21 | df.at["peak_mem", fm] = mem.max() / 1e3 # GB 22 | return df 23 | 24 | 25 | def plot_performance(logs, attr, model_names=None, colors="forestgreen", fn=None): 26 | 27 | df = process_logs(logs) 28 | 29 | if model_names is not None: 30 | df.rename(columns=model_names, inplace=True) 31 | 32 | fig, ax = plt.subplots(figsize=(4.5, 2.5)) 33 | 34 | df.T[attr].plot.bar(ax=ax, color=colors) 35 | 36 | if attr == "peak_mem": 37 | plt.ylabel("Peak Memory [GB]") 38 | else: 39 | plt.ylabel("Solving Time [h]") 40 | 41 | if fn is not None: 42 | plt.savefig(fn, bbox_inches="tight") 43 | 44 | 45 | def plot_cost_bar(networks, model_names, fn=None): 46 | 47 | for n in networks.values(): 48 | assign_carriers(n) 49 | 50 | costs = pd.concat({k: aggregate_costs(v) for k, v in networks.items()}, axis=1).T 51 | 52 | if "load" in costs.columns: 53 | costs.drop(columns=["load"], inplace=True) 54 | 55 | colors = n.carriers.color.reindex(index=costs.columns).values 56 | 57 | costs.rename(columns=n.carriers.nice_name, index=model_names, inplace=True) 58 | costs.columns.name = "Technology" 59 | 60 | fig, ax = plt.subplots(figsize=(8, 4)) 61 | 62 | costs.plot.bar(ax=ax, stacked=True, color=colors) 63 | 64 | handles, labels = ax.get_legend_handles_labels() 65 | ax.legend(handles[::-1], labels[::-1], ncol=1, bbox_to_anchor=(1, 1.2)) 66 | 67 | plt.xticks(rotation=0) 68 | plt.ylabel("Total System Costs [bn Euro / a]") 69 | 70 | if fn is not None: 71 | plt.savefig(fn, bbox_inches="tight") 72 | 73 | 74 | def optimised_capacities(n, c, regex="()"): 75 | attr = "s" if c == "Line" else "p" 76 | return n.df(c)[f"{attr}_nom_opt"].filter(regex=regex) 77 | 78 | 79 | def plot_capacity_correlation( 80 | networks, c, model_names, regex="", triangle=False, fn=None 81 | ): 82 | 83 | regexb = "(" + regex + ")" 84 | 85 | df = pd.DataFrame( 86 | {fm: optimised_capacities(n, c, regexb) for fm, n in networks.items()} 87 | ) 88 | df.rename(columns=model_names, inplace=True) 89 | 90 | corr = df.corr() 91 | 92 | mask = None 93 | if triangle: 94 | mask = np.triu(np.ones_like(corr, dtype=np.bool)) 95 | 96 | fig, ax = plt.subplots(figsize=(4, 4)) 97 | 98 | sns.heatmap( 99 | df.corr(), 100 | vmin=0.5, 101 | mask=mask, 102 | cmap="viridis", 103 | square=True, 104 | annot=True, 105 | fmt=".2", 106 | ax=ax, 107 | cbar=False, 108 | ) 109 | 110 | auxn = next(iter(networks.values())) 111 | 112 | if regex != "": 113 | plt.title(getattr(auxn.carriers.nice_name, regex, regex)) 114 | else: 115 | plt.title(c) 116 | 117 | if fn is not None: 118 | plt.savefig(fn, bbox_inches="tight") 119 | 120 | 121 | def plot_price_duration_curve(networks, model_names, ignore=[], fn=None): 122 | 123 | fig, axs = plt.subplots( 124 | 1, 2, sharey=True, figsize=(10, 3), gridspec_kw={"width_ratios": [1, 5]} 125 | ) 126 | 127 | for k, v in networks.items(): 128 | if k in ignore: 129 | continue 130 | y = v.buses_t.marginal_price.stack().sort_values().reset_index(drop=True) 131 | y.index = [100 * i / len(y) for i in y.index] 132 | for ax in axs: 133 | y.plot(label=model_names[k], ax=ax) 134 | 135 | axs[0].set_xlim([-0.01, 0.2]) 136 | axs[1].set_xlim([80, 100]) 137 | 138 | axs[0].set_ylabel("Nodal price [EUR/MWh]") 139 | axs[1].set_xlabel("Share of Snapshots and Nodes [%]") 140 | 141 | plt.tight_layout() 142 | plt.legend(loc="upper left", ncol=2) 143 | plt.ylim([-100, 1000]) 144 | 145 | if fn is not None: 146 | plt.savefig(fn, bbox_inches="tight") 147 | -------------------------------------------------------------------------------- /scripts/plotting/stats.py: -------------------------------------------------------------------------------- 1 | """ 2 | Functions yielding statistics about solved networks. 3 | """ 4 | 5 | __author__ = "Fabian Neumann (KIT)" 6 | __copyright__ = "Copyright 2019-2020 Fabian Neumann (KIT), GNU GPL 3" 7 | 8 | import pandas as pd 9 | 10 | from .utils import aggregate_costs 11 | 12 | 13 | def check_curtailment(n): 14 | possible = ( 15 | (n.generators_t.p_max_pu * n.generators.p_nom_opt) 16 | .filter(regex="(ror|solar|wind)", axis=1) 17 | .sum() 18 | .sum() 19 | ) 20 | generated = n.generators_t.p.filter(regex="(ror|solar|wind)", axis=1).sum().sum() 21 | return (1 - generated / possible) * 100 # % 22 | 23 | 24 | def check_energy_balance(n): 25 | gen = n.generators_t.p.multiply(n.snapshot_weightings, axis=0).sum().sum() 26 | sto = n.storage_units_t.p.multiply(n.snapshot_weightings, axis=0).sum().sum() 27 | load = n.loads_t.p_set.multiply(n.snapshot_weightings, axis=0).sum().sum() 28 | if "loss" in n.lines_t.keys(): 29 | line_loss = n.lines_t.loss.multiply(n.snapshot_weightings, axis=0).sum().sum() 30 | else: 31 | line_loss = 0 32 | link_loss = ( 33 | (n.links_t.p0 + n.links_t.p1) 34 | .multiply(n.snapshot_weightings, axis=0) 35 | .sum() 36 | .sum() 37 | ) 38 | loss = link_loss + line_loss 39 | loss_share = loss / (gen + sto) * 100 # % 40 | balance = (gen + sto - loss - load) / 1e6 # TWh 41 | return balance, loss_share, link_loss / 1e6, line_loss / 1e6 42 | 43 | 44 | def check_energy_transmitted(n, branch="lines"): 45 | branches_t = getattr(n, branch + "_t") 46 | branches = getattr(n, branch) 47 | return ( 48 | branches_t.p0.abs() 49 | .multiply(n.snapshot_weightings, axis=0) 50 | .multiply(branches.length) 51 | .sum() 52 | .sum() 53 | / 1e12 54 | ) # EWhkm 55 | 56 | 57 | def check_energy_generated(n): 58 | n.generators["energy"] = n.generators_t.p.multiply( 59 | n.snapshot_weightings, axis=0 60 | ).sum() 61 | generated = n.generators.groupby("carrier").energy.sum() / 1e6 # TWh 62 | generated["inflow"] = ( 63 | n.storage_units_t.inflow.multiply(n.snapshot_weightings, axis=0).sum().sum() 64 | / 1e6 65 | ) # TWh 66 | return generated 67 | 68 | 69 | def check_costs(n): 70 | 71 | abs_c = aggregate_costs(n).sum() # bn EUR/a 72 | rel_c = ( 73 | abs_c 74 | / n.loads_t.p_set.multiply(n.snapshot_weightings, axis=0).sum().sum() 75 | * 1e9 76 | ) # EUR/MWh 77 | 78 | return abs_c, rel_c 79 | 80 | 81 | def check_capacities(n): 82 | 83 | capacities = pd.concat( 84 | [ 85 | n.generators.groupby("carrier").p_nom_opt.sum() / 1e3, # GW 86 | n.storage_units.groupby("carrier").p_nom_opt.sum() / 1e3, # GW 87 | pd.Series( 88 | {"links": n.links.eval("length * (p_nom_opt - p_nom) / 1e6 / 2").sum()} 89 | ), # TWkm # links are split and p_nom_opt thus counted double 90 | pd.Series( 91 | {"lines": n.lines.eval("length * (s_nom_opt - s_nom) / 1e6").sum()} 92 | ), # TWkm 93 | ] 94 | ) 95 | 96 | if "load" in capacities.index: 97 | capacities.drop("load", inplace=True) 98 | 99 | return capacities 100 | 101 | 102 | def check_flow_errors(n, n_pf): 103 | 104 | pf = n_pf.lines_t.p0.stack() 105 | 106 | lopf = n.lines_t.p0.stack() 107 | 108 | mse = pf.sub(lopf).pow(2).mean() 109 | rmse = mse ** 0.5 110 | mape = pf.sub(lopf).div(pf).abs().mean() 111 | mae = pf.sub(lopf).abs().mean() 112 | corr = pf.corr(lopf) 113 | r2 = corr ** 2 114 | return (rmse, mae, mape, corr, r2) 115 | 116 | 117 | def check_slack(n_pf, logs): 118 | converged = logs.converged.all(axis=1) 119 | 120 | valley_q = n_pf.generators_t.q.loc[converged].sum(axis=1).min() / 1e3 # GW 121 | peak_q = n_pf.generators_t.q.loc[converged].sum(axis=1).max() / 1e3 # GW 122 | tvarh = ( 123 | n_pf.generators_t.q.loc[converged] 124 | .multiply(n_pf.snapshot_weightings, axis=0) 125 | .sum() 126 | .sum() 127 | / 1e6 128 | ) # Tvarh 129 | 130 | slack = (n_pf.generators_t.p - n_pf.generators_t.p_set).loc[converged] 131 | twh = slack.multiply(n_pf.snapshot_weightings, axis=0).sum().sum() / 1e6 # TWh 132 | peak_p = slack.sum(axis=1).max() / 1e3 # GW 133 | valley_p = slack.sum(axis=1).min() / 1e3 # GW 134 | 135 | return (twh, peak_p, valley_p, tvarh, peak_q, valley_q) 136 | -------------------------------------------------------------------------------- /scripts/plotting/map.py: -------------------------------------------------------------------------------- 1 | """ 2 | Network expansion plotting functions. 3 | """ 4 | 5 | __author__ = "Fabian Neumann (KIT)" 6 | __copyright__ = "Copyright 2019-2020 Fabian Neumann (KIT), GNU GPL 3" 7 | 8 | import pandas as pd 9 | import numpy as np 10 | 11 | import cartopy.crs as ccrs 12 | import matplotlib.pyplot as plt 13 | 14 | from matplotlib.patches import Circle, Ellipse 15 | from matplotlib.legend_handler import HandlerPatch 16 | 17 | 18 | def make_handler_map_to_scale_circles_as_in(ax, dont_resize_actively=False): 19 | fig = ax.get_figure() 20 | 21 | def axes2pt(): 22 | return np.diff(ax.transData.transform([(0, 0), (1, 1)]), axis=0)[0] * ( 23 | 300.0 / fig.dpi 24 | ) 25 | 26 | ellipses = [] 27 | if not dont_resize_actively: 28 | 29 | def update_width_height(event): 30 | dist = axes2pt() 31 | for e, radius in ellipses: 32 | e.width, e.height = 2.0 * radius * dist 33 | 34 | fig.canvas.mpl_connect("resize_event", update_width_height) 35 | ax.callbacks.connect("xlim_changed", update_width_height) 36 | ax.callbacks.connect("ylim_changed", update_width_height) 37 | 38 | def legend_circle_handler( 39 | legend, orig_handle, xdescent, ydescent, width, height, fontsize 40 | ): 41 | w, h = 2.0 * orig_handle.get_radius() * axes2pt() 42 | e = Ellipse( 43 | xy=(0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent), 44 | width=w, 45 | height=w, 46 | ) 47 | ellipses.append((e, orig_handle.get_radius())) 48 | return e 49 | 50 | return {Circle: HandlerPatch(patch_func=legend_circle_handler)} 51 | 52 | 53 | def make_legend_circles_for(sizes, scale=1.0, **kw): 54 | return [Circle((0, 0), radius=(s / scale) ** 0.5, **kw) for s in sizes] 55 | 56 | 57 | def add_legend(n, ax, bus_factor, branch_factor): 58 | 59 | handles = [] 60 | labels = [] 61 | for s in (2, 5, 10): 62 | handles.append( 63 | plt.Line2D([0], [0], color="rosybrown", linewidth=s * 1e3 / branch_factor) 64 | ) 65 | labels.append(f"{s} GW") 66 | l1 = ax.legend( 67 | handles, 68 | labels, 69 | loc="upper left", 70 | bbox_to_anchor=(0, 0), 71 | frameon=False, 72 | labelspacing=0.8, 73 | handletextpad=1.5, 74 | title="HVAC Line Capacity", 75 | ) 76 | ax.add_artist(l1) 77 | 78 | handles = [] 79 | labels = [] 80 | for s in (2, 5, 10): 81 | handles.append( 82 | plt.Line2D( 83 | [0], [0], color="darkseagreen", linewidth=s * 1e3 / branch_factor 84 | ) 85 | ) 86 | labels.append(f"{s} GW") 87 | l2 = ax.legend( 88 | handles, 89 | labels, 90 | loc="upper left", 91 | bbox_to_anchor=(0.2, -0.0), 92 | frameon=False, 93 | labelspacing=0.8, 94 | handletextpad=1.5, 95 | title="HVDC Link Capacity", 96 | ) 97 | ax.add_artist(l2) 98 | 99 | handles = [] 100 | labels = [] 101 | if "Load" in n.carriers.index: 102 | n.carriers = n.carriers.drop("Load") 103 | for name, carrier in n.carriers.iterrows(): 104 | handles.append( 105 | plt.Line2D( 106 | [0], [0], color=carrier.color, marker="o", markersize=8, linewidth=0 107 | ) 108 | ) 109 | labels.append(carrier.nice_name) 110 | l3 = ax.legend( 111 | handles, 112 | labels, 113 | loc="upper center", 114 | bbox_to_anchor=(0.58, -0.0), # bbox_to_anchor=(0.72, -0.05), 115 | handletextpad=0.0, 116 | columnspacing=0.5, 117 | ncol=2, 118 | title="Technology", 119 | frameon=False, 120 | ) 121 | ax.add_artist(l3) 122 | 123 | circles = [5000, 1000, 100] 124 | handles = make_legend_circles_for(circles, scale=bus_factor, facecolor="lightgray") 125 | labels = [f"{int(s/1e2)} GW" for s in circles] 126 | l4 = ax.legend( 127 | handles, 128 | labels, 129 | loc="upper left", 130 | bbox_to_anchor=(0.82, 0.0), 131 | frameon=False, 132 | labelspacing=2.5, 133 | title="Generation", 134 | handler_map=make_handler_map_to_scale_circles_as_in(ax, True), 135 | ) 136 | ax.add_artist(l4) 137 | 138 | 139 | def plot_network(n, fn=None): 140 | 141 | bus_factor = 5.5e4 142 | branch_factor = 2e3 143 | 144 | fields = ["bus", "carrier", "p_nom_opt"] 145 | pie_components = pd.concat( 146 | [ 147 | n.generators.loc[n.generators.carrier != "load", fields], 148 | n.storage_units[fields], 149 | ] 150 | ) 151 | bus_sizes = pie_components.groupby(["bus", "carrier"]).p_nom_opt.sum() / bus_factor 152 | 153 | def clip(df, thres=500): 154 | return df.where(df > thres, other=0.0) 155 | 156 | line_widths = clip(n.lines.s_nom_opt - n.lines.s_nom) / branch_factor 157 | link_widths = clip(n.links.p_nom_opt - n.links.p_nom) / branch_factor 158 | line_widths_opt = clip(n.lines.s_nom_opt) / branch_factor 159 | 160 | fig, ax = plt.subplots( 161 | figsize=(11, 11), subplot_kw={"projection": ccrs.PlateCarree()} 162 | ) 163 | 164 | n.plot( 165 | ax=ax, 166 | bus_sizes=bus_sizes, 167 | color_geomap=True, 168 | bus_alpha=0.7, 169 | line_widths=line_widths_opt, 170 | line_colors="#dddddd", 171 | ) 172 | 173 | n.plot( 174 | ax=ax, 175 | geomap=False, 176 | bus_sizes=0, 177 | line_widths=line_widths, 178 | link_widths=link_widths, 179 | ) 180 | 181 | add_legend(n, ax, bus_factor, branch_factor) 182 | 183 | if fn is not None: 184 | plt.savefig(fn, bbox_inches="tight") 185 | -------------------------------------------------------------------------------- /scripts/_loss_models.py: -------------------------------------------------------------------------------- 1 | """ 2 | Extra functionality implementing loss models. 3 | """ 4 | 5 | __author__ = "Fabian Neumann (KIT), Anika Bitsch (KIT)" 6 | __copyright__ = ( 7 | "Copyright 2019-2020 Fabian Neumann (KIT), Anika Bitsch (KIT), GNU GPL 3" 8 | ) 9 | 10 | import pandas as pd 11 | import numpy as np 12 | 13 | from pypsa.descriptors import get_switchable_as_dense 14 | from pypsa.opt import LConstraint, l_constraint, LExpression 15 | from pyomo.environ import Var, NonNegativeReals 16 | 17 | 18 | # adapted from pypsa.opf.define_passive_branch_constraints 19 | def redo_passive_branch_constraints(network, snapshots): 20 | 21 | model_components_to_delete = [ 22 | "flow_upper", 23 | "flow_lower", 24 | "flow_upper_index", 25 | "flow_lower_index", 26 | "flow_upper_index_0", 27 | "flow_lower_index_0", 28 | "flow_upper_index_1", 29 | "flow_lower_index_1", 30 | ] 31 | for model_component in model_components_to_delete: 32 | network.model.del_component(model_component) 33 | 34 | passive_branches = network.passive_branches() 35 | extendable_branches = passive_branches[passive_branches.s_nom_extendable] 36 | fixed_branches = passive_branches[~passive_branches.s_nom_extendable] 37 | 38 | s_max_pu = pd.concat( 39 | { 40 | c: get_switchable_as_dense(network, c, "s_max_pu", snapshots) 41 | for c in network.passive_branch_components 42 | }, 43 | axis=1, 44 | sort=False, 45 | ) 46 | 47 | flow_upper = { 48 | (b[0], b[1], sn): [ 49 | [ 50 | (1, network.model.passive_branch_p[b[0], b[1], sn]), 51 | (1, network.model.loss[b[0], b[1], sn]), 52 | ], 53 | "<=", 54 | s_max_pu.at[sn, b] * fixed_branches.at[b, "s_nom"], 55 | ] 56 | for b in fixed_branches.index 57 | for sn in snapshots 58 | } 59 | 60 | flow_upper.update( 61 | { 62 | (b[0], b[1], sn): [ 63 | [ 64 | (1, network.model.passive_branch_p[b[0], b[1], sn]), 65 | (1, network.model.loss[b[0], b[1], sn]), 66 | ( 67 | -s_max_pu.at[sn, b], 68 | network.model.passive_branch_s_nom[b[0], b[1]], 69 | ), 70 | ], 71 | "<=", 72 | 0, 73 | ] 74 | for b in extendable_branches.index 75 | for sn in snapshots 76 | } 77 | ) 78 | 79 | l_constraint( 80 | network.model, "flow_upper", flow_upper, list(passive_branches.index), snapshots 81 | ) 82 | 83 | flow_lower = { 84 | (b[0], b[1], sn): [ 85 | [ 86 | (1, network.model.passive_branch_p[b[0], b[1], sn]), 87 | (-1, network.model.loss[b[0], b[1], sn]), 88 | ], 89 | ">=", 90 | -s_max_pu.at[sn, b] * fixed_branches.at[b, "s_nom"], 91 | ] 92 | for b in fixed_branches.index 93 | for sn in snapshots 94 | } 95 | 96 | flow_lower.update( 97 | { 98 | (b[0], b[1], sn): [ 99 | [ 100 | (1, network.model.passive_branch_p[b[0], b[1], sn]), 101 | (-1, network.model.loss[b[0], b[1], sn]), 102 | ( 103 | s_max_pu.at[sn, b], 104 | network.model.passive_branch_s_nom[b[0], b[1]], 105 | ), 106 | ], 107 | ">=", 108 | 0, 109 | ] 110 | for b in extendable_branches.index 111 | for sn in snapshots 112 | } 113 | ) 114 | 115 | l_constraint( 116 | network.model, "flow_lower", flow_lower, list(passive_branches.index), snapshots 117 | ) 118 | 119 | 120 | # adapted from pypsa.opf.extract_optimisation_results 121 | def get_values(indexedvar): 122 | return pd.Series(indexedvar.get_values()) 123 | 124 | 125 | # adapted from pypsa.opf.extract_optimisation_results 126 | def set_from_series(df, series, snapshots): 127 | df.loc[snapshots] = series.unstack(0).reindex(columns=df.columns) 128 | 129 | 130 | def define_loss_constraints(network, snapshots): 131 | 132 | tangents = network.tangents 133 | 134 | positions = range(1, tangents + 1) 135 | signs = [-1, 1] 136 | 137 | passive_branches = network.passive_branches() 138 | 139 | s_max_pus = get_switchable_as_dense(network, "Line", "s_max_pu") 140 | 141 | network.model.loss = Var( 142 | list(passive_branches.index), snapshots, domain=NonNegativeReals 143 | ) 144 | 145 | redo_passive_branch_constraints(network, snapshots) 146 | 147 | loss_upper = {} 148 | loss_tangents = {} 149 | 150 | for branch in passive_branches.index: 151 | 152 | bus0 = passive_branches.at[branch, "bus0"] 153 | bus1 = passive_branches.at[branch, "bus1"] 154 | bt = branch[0] 155 | bn = branch[1] 156 | 157 | r_pu_eff = passive_branches.at[branch, "r_pu_eff"] 158 | 159 | if passive_branches.at[branch, "s_nom_extendable"]: 160 | attr = "s_nom_max" 161 | elif passive_branches.at[branch, "s_nom_opt"] != 0.0: 162 | attr = "s_nom_opt" 163 | else: 164 | attr = "s_nom" 165 | 166 | s_nom_max = passive_branches.at[branch, attr] 167 | 168 | assert np.isfinite(s_nom_max) and not np.isnan( 169 | s_nom_max 170 | ), f"Infinite or non-existent 's_nom_max' encountered at line {bn}" 171 | 172 | for sn in snapshots: 173 | 174 | s_max_pu = s_max_pus.loc[sn, bn] 175 | 176 | # adjust kcl 177 | # use of ._body because of pyomo bug 178 | for bus in [bus0, bus1]: 179 | network.model.power_balance[bus, sn]._body -= ( 180 | network.model.loss[bt, bn, sn] / 2 181 | ) 182 | 183 | # upper loss limit 184 | lhs = LExpression( 185 | [(1, network.model.loss[bt, bn, sn])], 186 | -r_pu_eff * (s_max_pu * s_nom_max) ** 2, 187 | ) 188 | loss_upper[bt, bn, sn] = LConstraint(lhs, "<=", LExpression()) 189 | 190 | # loss tangents 191 | for k in positions: 192 | 193 | p_k = k / tangents * s_max_pu * s_nom_max 194 | loss_k = r_pu_eff * p_k ** 2 195 | slope_k = 2 * r_pu_eff * p_k 196 | offset_k = loss_k - slope_k * p_k 197 | 198 | for sign in signs: 199 | 200 | lhs = LExpression([(1, network.model.loss[bt, bn, sn])]) 201 | rhs = LExpression( 202 | [(sign * slope_k, network.model.passive_branch_p[bt, bn, sn])], 203 | offset_k, 204 | ) 205 | loss_tangents[sign, k, bt, bn, sn] = LConstraint(lhs, ">=", rhs) 206 | 207 | l_constraint( 208 | network.model, "loss_upper", loss_upper, list(passive_branches.index), snapshots 209 | ) 210 | 211 | l_constraint( 212 | network.model, 213 | "loss_tangents", 214 | loss_tangents, 215 | signs, 216 | list(positions), 217 | list(passive_branches.index), 218 | snapshots, 219 | ) 220 | 221 | 222 | def store_losses(network, snapshots, duals): 223 | 224 | network.lines_t["loss"] = pd.DataFrame( 225 | 0, index=snapshots, columns=network.lines.index 226 | ) 227 | 228 | loss_values = get_values(network.model.loss) 229 | 230 | set_from_series(network.lines_t.loss, loss_values.loc["Line"], snapshots) 231 | -------------------------------------------------------------------------------- /scripts/solve_network.py: -------------------------------------------------------------------------------- 1 | """ 2 | Solve lossy networks. 3 | """ 4 | 5 | __author__ = "Fabian Neumann (KIT), Anika Bitsch (KIT)" 6 | __copyright__ = ( 7 | "Copyright 2019-2020 Fabian Neumann (KIT), Anika Bitsch (KIT), GNU GPL 3" 8 | ) 9 | 10 | import pypsa 11 | import os 12 | import sys 13 | import numpy as np 14 | import pandas as pd 15 | 16 | from vresutils.benchmark import memory_logger 17 | from pypsa.opt import l_constraint 18 | from copy import deepcopy 19 | 20 | import logging 21 | 22 | logger = logging.getLogger(__name__) 23 | 24 | # import loss models from ./loss_models.py 25 | from _loss_models import * 26 | 27 | # Add pypsa-eur scripts to path for import 28 | sys.path.insert(0, os.getcwd() + "/pypsa-eur/scripts") 29 | 30 | from solve_network import * 31 | 32 | # Suppress logging of the slack bus choices 33 | pypsa.pf.logger.setLevel(logging.WARNING) 34 | 35 | 36 | def split_bidirectional_links(n): 37 | 38 | n.links.p_min_pu = 0 39 | n.links["reversed"] = False 40 | rev_links = n.links.copy().rename({"bus0": "bus1", "bus1": "bus0"}, axis=1) 41 | rev_links.capital_cost = 0 42 | rev_links["reversed"] = True 43 | rev_links.index = [f"{i}-reversed" for i in rev_links.index] 44 | 45 | n.links = pd.concat([n.links, rev_links], sort=False) 46 | 47 | 48 | def remove_kvl_constraints(network, snapshots): 49 | 50 | formulation = snakemake.config["solving"]["options"].get("formulation", "kirchhoff") 51 | 52 | if formulation in ["angles", "cycles", "ptdf"]: 53 | n.model.del_component(network.model.passive_branch_p_def) 54 | 55 | if formulation in ["cycles", "kirchhoff"]: 56 | n.model.del_component(network.model.cycle_constraints) 57 | 58 | 59 | def tie_bidirectional_link_p_nom(network, snapshots): 60 | 61 | if not hasattr(n.links, "reversed"): 62 | return 63 | 64 | ext_rev_links = network.links.loc[ 65 | (network.links.reversed == True) & (network.links.p_nom_extendable == True) 66 | ].index 67 | 68 | if len(ext_rev_links) == 0: 69 | return 70 | 71 | constraints = { 72 | lk: [ 73 | [ 74 | (1, network.model.link_p_nom[lk.split("-")[0]]), 75 | (-1, network.model.link_p_nom[lk]), 76 | ], 77 | "==", 78 | 0.0, 79 | ] 80 | for lk in ext_rev_links 81 | } 82 | 83 | l_constraint(network.model, "bidirectional_link", constraints, list(ext_rev_links)) 84 | 85 | network.model.bidirectional_link.pprint() 86 | 87 | 88 | def update_line_parameters(n): 89 | 90 | lines_ext_b = n.lines.s_nom_extendable 91 | 92 | if not lines_ext_b.any(): 93 | return 94 | 95 | lines = pd.DataFrame(n.lines[["r", "x", "type", "num_parallel"]]) 96 | 97 | lines["s_nom"] = ( 98 | np.sqrt(3) 99 | * n.lines["type"].map(n.line_types.i_nom) 100 | * n.lines.bus0.map(n.buses.v_nom) 101 | ).where(n.lines.type != "", n.lines["s_nom"]) 102 | 103 | lines_ext_untyped_b = (n.lines.type == "") & lines_ext_b 104 | lines_ext_typed_b = (n.lines.type != "") & lines_ext_b 105 | 106 | if lines_ext_untyped_b.any(): 107 | for attr in ("r", "x"): 108 | n.lines.loc[lines_ext_untyped_b, attr] = lines[attr].multiply( 109 | lines["s_nom"] / n.lines["s_nom_opt"] 110 | ) 111 | 112 | if lines_ext_typed_b.any(): 113 | n.lines.loc[lines_ext_typed_b, "num_parallel"] = ( 114 | n.lines["s_nom_opt"] / lines["s_nom"] 115 | ) 116 | 117 | 118 | def modify_line_attributes(n, ln_config): 119 | n.lines.s_nom_max = n.lines.apply( 120 | lambda line: max( 121 | line.s_nom + ln_config["s_nom_add"], line.s_nom * ln_config["s_nom_factor"], 122 | ), 123 | axis=1, 124 | ) 125 | n.lines = n.lines.loc[n.lines.s_nom != 0] 126 | n.lines.s_max_pu = ln_config["s_max_pu"] 127 | 128 | 129 | def modify_link_attributes(n, lk_config): 130 | n.links.p_nom_max = lk_config["p_nom_max"] 131 | if "lossy" in n.flow_model: 132 | n.links.efficiency = n.links.apply( 133 | lambda lk: 1 - lk.length * lk_config["loss_per_length"], axis=1 134 | ) 135 | 136 | 137 | def ac_lines_to_links(n, ln_config): 138 | 139 | lk_attrs = [ 140 | "bus0", 141 | "bus1", 142 | "length", 143 | "s_nom", 144 | "s_max_pu", 145 | "capital_cost", 146 | "s_nom_max", 147 | "s_nom_min", 148 | "s_nom_extendable", 149 | ] 150 | lines_lk = n.lines.loc[:, lk_attrs] 151 | 152 | # translate s_ to p_ 153 | lines_lk.columns = [ 154 | f"p_{col[2:]}" if col.startswith("s_") else col for col in lines_lk.columns 155 | ] 156 | 157 | # need to ensure unique naming 158 | lines_lk.index = [f"AC_{ln}" for ln in lines_lk.index] 159 | 160 | lines_lk["efficiency"] = lines_lk.apply( 161 | lambda ln: 1 - ln.length * ln_config["loss_per_length"], axis=1 162 | ) 163 | 164 | lines_lk["p_min_pu"] = -lines_lk.p_max_pu 165 | lines_lk["carrier"] = "AC" 166 | 167 | n.import_components_from_dataframe(lines_lk, "Link") 168 | 169 | n.mremove("Line", n.lines.index) 170 | 171 | 172 | def ac_links_to_lines(n, lines_orig): 173 | 174 | def _get_ac_links(n, reverse=True): 175 | 176 | links = n.links.copy() 177 | links_t_p0 = n.links_t.p0.copy() 178 | links_t_p1 = n.links_t.p1.copy() 179 | 180 | if reverse: 181 | ln = links.loc[(links.reversed == True) & (links.carrier == "AC")] 182 | else: 183 | ln = links.loc[(links.reversed != True) & (links.carrier == "AC")] 184 | 185 | ln_p0 = links_t_p0.loc[:, ln.index] 186 | ln_p1 = links_t_p1.loc[:, ln.index] 187 | 188 | def orig_name(l): 189 | return l.split("-")[0].split("_")[1] 190 | 191 | ln.index = [orig_name(l) for l in ln.index] 192 | ln_p0.columns = [orig_name(l) for l in ln_p0.columns] 193 | ln_p1.columns = [orig_name(l) for l in ln_p1.columns] 194 | 195 | return ln, ln_p0, ln_p1 196 | 197 | lines, p0, p1 = _get_ac_links(n, reverse=False) 198 | lines_rev, p0_rev, p1_rev = _get_ac_links(n, reverse=True) 199 | 200 | n.import_components_from_dataframe(lines_orig, "Line") 201 | 202 | n.lines.s_nom_opt = lines.p_nom_opt 203 | n.lines_t["p0"] = p1_rev - p1 204 | n.lines_t["p1"] = -n.lines_t.p0 # p0 and p1 store effective flow (received flow) 205 | n.lines_t["loss"] = p0 + p1 + p0_rev + p1_rev 206 | 207 | n.mremove("Link", n.links.loc[n.links.carrier == "AC"].index) 208 | n.links.drop( 209 | columns=["underground", "under_construction"], inplace=True 210 | ) # these cause trouble when exporting as .nc 211 | 212 | n.calculate_dependent_values() 213 | n.determine_network_topology() 214 | 215 | 216 | if __name__ == "__main__": 217 | 218 | logging.basicConfig( 219 | filename=snakemake.log.python, level=snakemake.config["logging_level"] 220 | ) 221 | 222 | config = snakemake.config 223 | 224 | flow_model_wc = snakemake.wildcards.model.split("-") 225 | flow_model = flow_model_wc[0] 226 | 227 | assert flow_model in [ 228 | "transport", 229 | "lossytransport", 230 | "lossless", 231 | "lossy", 232 | ], f"The flow model {flow_model} has not been defined. Choose 'transport', 'lossytransport', 'lossless' or 'lossy'." 233 | 234 | with memory_logger( 235 | filename=getattr(snakemake.log, "memory", None), interval=30.0 236 | ) as mem: 237 | 238 | n = pypsa.Network(snakemake.input[0]) 239 | 240 | n.flow_model = flow_model 241 | 242 | modify_line_attributes(n, config["lines"]) 243 | modify_link_attributes(n, config["links"]) 244 | 245 | lines_orig = n.lines.copy() 246 | 247 | if flow_model == "lossytransport": 248 | ac_lines_to_links(n, config["lines"]) 249 | 250 | split_bidirectional_links(n) 251 | 252 | n = prepare_network(n, solve_opts=snakemake.config["solving"]["options"]) 253 | 254 | # set iterations 255 | if flow_model in ["transport", "lossytransport"]: 256 | skip_iterating = True 257 | elif flow_model in ["lossless", "lossy"]: 258 | iterations = int(flow_model_wc[-1]) 259 | if iterations == 0: 260 | skip_iterating = True 261 | else: 262 | skip_iterating = False 263 | snakemake.config["solving"]["options"]["min_iterations"] = iterations 264 | snakemake.config["solving"]["options"]["max_iterations"] = iterations 265 | 266 | # set tangents 267 | if flow_model == "lossy": 268 | n.tangents = int(flow_model_wc[-2]) 269 | 270 | def extra_functionality(network, snapshots): 271 | tie_bidirectional_link_p_nom(network, snapshots) 272 | if network.flow_model == "transport": 273 | remove_kvl_constraints(network, snapshots) 274 | elif network.flow_model == "lossy": 275 | define_loss_constraints(network, snapshots) 276 | 277 | def extra_postprocessing(network, snapshots, duals): 278 | if network.flow_model == "lossy": 279 | store_losses(network, snapshots, duals) 280 | 281 | n = solve_network( 282 | n, 283 | config=snakemake.config["solving"], 284 | solver_log=snakemake.log.solver, 285 | opts=snakemake.wildcards.opts, 286 | extra_functionality=extra_functionality, 287 | extra_postprocessing=extra_postprocessing, 288 | skip_iterating=skip_iterating, 289 | ) 290 | 291 | if flow_model == "lossytransport": 292 | ac_links_to_lines(n, lines_orig) 293 | 294 | update_line_parameters(n) 295 | n.calculate_dependent_values() 296 | 297 | n.export_to_netcdf(snakemake.output[0]) 298 | 299 | logger.info("Maximum memory usage: {}".format(mem.mem_usage)) 300 | -------------------------------------------------------------------------------- /config.pypsaeur.yaml: -------------------------------------------------------------------------------- 1 | version: 0.1 2 | tutorial: false 3 | 4 | logging: 5 | level: INFO 6 | format: '%(levelname)s:%(name)s:%(message)s' 7 | 8 | summary_dir: results 9 | 10 | scenario: 11 | sectors: [E] 12 | simpl: [''] 13 | ll: ['copt'] 14 | clusters: [37, 100] 15 | opts: [Co2L-3H] 16 | 17 | countries: ['AL', 'AT', 'BA', 'BE', 'BG', 'CH', 'CZ', 'DE', 'DK', 'EE', 'ES', 'FI', 'FR', 'GB', 'GR', 'HR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV', 'ME', 'MK', 'NL', 'NO', 'PL', 'PT', 'RO', 'RS', 'SE', 'SI', 'SK'] 18 | 19 | snapshots: 20 | start: "2013-01-01" 21 | end: "2014-01-01" 22 | closed: 'left' # end is not inclusive 23 | 24 | enable: 25 | prepare_links_p_nom: false 26 | retrieve_databundle: true 27 | build_cutout: false 28 | build_natura_raster: false 29 | 30 | electricity: 31 | voltages: [220., 300., 380.] 32 | co2limit: 7.75e+7 # 0.05 * 3.1e9*0.5 33 | co2base: 3.1e+9 # 1 * 3.1e9*0.5 34 | agg_p_nom_limits: data/agg_p_nom_minmax.csv 35 | 36 | extendable_carriers: 37 | Generator: [] 38 | StorageUnit: [battery, H2] 39 | Store: [] # battery, H2 40 | 41 | max_hours: 42 | battery: 6 43 | H2: 168 44 | 45 | powerplants_filter: false # use pandas query strings here, e.g. Country not in ['Germany'] 46 | custom_powerplants: false # use pandas query strings here, e.g. Country in ['Germany'] 47 | conventional_carriers: [] # nuclear, oil, OCGT, CCGT, coal, lignite, geothermal, biomass] 48 | 49 | # estimate_renewable_capacities_from_capacity_stats: 50 | # # Wind is the Fueltype in ppm.data.Capacity_stats, onwind, offwind-{ac,dc} the carrier in PyPSA-Eur 51 | # Wind: [onwind, offwind-ac, offwind-dc] 52 | # Solar: [solar] 53 | 54 | 55 | atlite: 56 | nprocesses: 4 57 | cutouts: 58 | europe-2013-era5: 59 | module: era5 60 | xs: [-12., 35.] 61 | ys: [72., 33.] 62 | years: [2013, 2013] 63 | europe-2013-sarah: 64 | module: sarah 65 | resolution: 0.2 66 | xs: [-12., 42.] 67 | ys: [65., 33.] 68 | years: [2013, 2013] 69 | 70 | renewable: 71 | onwind: 72 | cutout: europe-2013-era5 73 | resource: 74 | method: wind 75 | turbine: Vestas_V112_3MW 76 | capacity_per_sqkm: 3 # ScholzPhd Tab 4.3.1: 10MW/km^2 77 | # correction_factor: 0.93 78 | corine: 79 | # Scholz, Y. (2012). Renewable energy based electricity supply at low costs: 80 | # development of the REMix model and application for Europe. ( p.42 / p.28) 81 | grid_codes: [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 82 | 24, 25, 26, 27, 28, 29, 31, 32] 83 | distance: 1000 84 | distance_grid_codes: [1, 2, 3, 4, 5, 6] 85 | natura: true 86 | potential: simple # or conservative 87 | clip_p_max_pu: 1.e-2 88 | offwind-ac: 89 | cutout: europe-2013-era5 90 | resource: 91 | method: wind 92 | turbine: NREL_ReferenceTurbine_5MW_offshore 93 | capacity_per_sqkm: 3 94 | # correction_factor: 0.93 95 | corine: [44, 255] 96 | natura: true 97 | max_depth: 50 98 | max_shore_distance: 30000 99 | potential: simple # or conservative 100 | clip_p_max_pu: 1.e-2 101 | offwind-dc: 102 | cutout: europe-2013-era5 103 | resource: 104 | method: wind 105 | turbine: NREL_ReferenceTurbine_5MW_offshore 106 | # ScholzPhd Tab 4.3.1: 10MW/km^2 107 | capacity_per_sqkm: 3 108 | # correction_factor: 0.93 109 | corine: [44, 255] 110 | natura: true 111 | max_depth: 50 112 | min_shore_distance: 30000 113 | potential: simple # or conservative 114 | clip_p_max_pu: 1.e-2 115 | solar: 116 | cutout: europe-2013-sarah 117 | resource: 118 | method: pv 119 | panel: CSi 120 | orientation: 121 | slope: 35. 122 | azimuth: 180. 123 | capacity_per_sqkm: 1.7 # ScholzPhd Tab 4.3.1: 170 MW/km^2 124 | # Determined by comparing uncorrected area-weighted full-load hours to those 125 | # published in Supplementary Data to 126 | # Pietzcker, Robert Carl, et al. "Using the sun to decarbonize the power 127 | # sector: The economic potential of photovoltaics and concentrating solar 128 | # power." Applied Energy 135 (2014): 704-720. 129 | correction_factor: 0.854337 130 | corine: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 131 | 14, 15, 16, 17, 18, 19, 20, 26, 31, 32] 132 | natura: true 133 | potential: simple # or conservative 134 | clip_p_max_pu: 1.e-2 135 | hydro: 136 | cutout: europe-2013-era5 137 | carriers: [ror, PHS, hydro] 138 | PHS_max_hours: 6 139 | hydro_max_hours: "energy_capacity_totals_by_country" # one of energy_capacity_totals_by_country, 140 | # estimate_by_large_installations or a float 141 | clip_min_inflow: 1.0 142 | 143 | lines: 144 | types: 145 | 220.: "Al/St 240/40 2-bundle 220.0" 146 | 300.: "Al/St 240/40 3-bundle 300.0" 147 | 380.: "Al/St 240/40 4-bundle 380.0" 148 | s_max_pu: 0.7 149 | length_factor: 1.25 150 | under_construction: 'zero' # 'zero': set capacity to zero, 'remove': remove, 'keep': with full capacity 151 | 152 | links: 153 | p_max_pu: 1.0 154 | include_tyndp: true 155 | under_construction: 'zero' # 'zero': set capacity to zero, 'remove': remove, 'keep': with full capacity 156 | 157 | transformers: 158 | x: 0.1 159 | s_nom: 2000. 160 | type: '' 161 | 162 | load: 163 | scaling_factor: 1.0 164 | 165 | costs: 166 | year: 2030 167 | discountrate: 0.07 # From a Lion Hirth paper, also reflects average of Noothout et al 2016 168 | USD2013_to_EUR2013: 0.7532 # [EUR/USD] ECB: https://www.ecb.europa.eu/stats/exchange/eurofxref/html/eurofxref-graph-usd.en.html 169 | marginal_cost: 170 | solar: 0.01 171 | onwind: 0.015 172 | offwind: 0.015 173 | hydro: 0. 174 | H2: 0. 175 | battery: 0. 176 | emission_prices: # only used with the option Ep 177 | co2: 0. 178 | 179 | solving: 180 | options: 181 | formulation: kirchhoff 182 | load_shedding: false 183 | noisy_costs: true 184 | min_iterations: 3 185 | max_iterations: 5 186 | clip_p_max_pu: 0.01 187 | #nhours: 10 188 | solver: 189 | name: gurobi 190 | threads: 4 191 | method: 2 # barrier 192 | crossover: 0 193 | BarConvTol: 1.e-5 194 | FeasibilityTol: 1.e-6 195 | AggFill: 0 196 | PreDual: 0 197 | GURO_PAR_BARDENSETHRESH: 200 198 | # solver: 199 | # name: cplex 200 | # threads: 4 201 | # lpmethod: 4 # barrier 202 | # solutiontype: 2 # non basic solution, ie no crossover 203 | # barrier_convergetol: 1.e-5 204 | # feasopt_tolerance: 1.e-6 205 | 206 | plotting: 207 | map: 208 | figsize: [7, 7] 209 | boundaries: [-10.2, 29, 35, 72] 210 | p_nom: 211 | bus_size_factor: 5.e+4 212 | linewidth_factor: 3.e+3 213 | 214 | costs_max: 800 215 | costs_threshold: 1 216 | 217 | energy_max: 15000. 218 | energy_min: -10000. 219 | energy_threshold: 50. 220 | 221 | vre_techs: ["onwind", "offwind-ac", "offwind-dc", "solar", "ror"] 222 | conv_techs: ["OCGT", "CCGT", "Nuclear", "Coal"] 223 | storage_techs: ["hydro+PHS", "battery", "H2"] 224 | load_carriers: ["AC load"] 225 | AC_carriers: ["AC line", "AC transformer"] 226 | link_carriers: ["DC line", "Converter AC-DC"] 227 | tech_colors: 228 | "onwind" : "#235ebc" 229 | "onshore wind" : "#235ebc" 230 | 'offwind' : "#6895dd" 231 | 'offwind-ac' : "#6895dd" 232 | 'offshore wind' : "#6895dd" 233 | 'offshore wind ac' : "#6895dd" 234 | 'offwind-dc' : "#74c6f2" 235 | 'offshore wind dc' : "#74c6f2" 236 | "hydro" : "#08ad97" 237 | "hydro+PHS" : "#08ad97" 238 | "PHS" : "#08ad97" 239 | "hydro reservoir" : "#08ad97" 240 | 'hydroelectricity' : '#08ad97' 241 | "ror" : "#4adbc8" 242 | "run of river" : "#4adbc8" 243 | 'solar' : "#f9d002" 244 | 'solar PV' : "#f9d002" 245 | 'solar thermal' : '#ffef60' 246 | 'biomass' : '#0c6013' 247 | 'solid biomass' : '#06540d' 248 | 'biogas' : '#23932d' 249 | 'waste' : '#68896b' 250 | 'geothermal' : '#ba91b1' 251 | "OCGT" : "#d35050" 252 | "OCGT marginal" : "#d35050" 253 | "OCGT-heat" : "#d35050" 254 | "gas boiler" : "#d35050" 255 | "gas boilers" : "#d35050" 256 | "gas boiler marginal" : "#d35050" 257 | "gas-to-power/heat" : "#d35050" 258 | "gas" : "#d35050" 259 | "natural gas" : "#d35050" 260 | "CCGT" : "#b20101" 261 | "CCGT marginal" : "#b20101" 262 | "Nuclear" : "#ff9000" 263 | "Nuclear marginal" : "#ff9000" 264 | "nuclear" : "#ff9000" 265 | "coal" : "#707070" 266 | "Coal" : "#707070" 267 | "Coal marginal" : "#707070" 268 | "lignite" : "#9e5a01" 269 | "Lignite" : "#9e5a01" 270 | "Lignite marginal" : "#9e5a01" 271 | "Oil" : "#262626" 272 | "oil" : "#262626" 273 | "H2" : "#ea048a" 274 | "hydrogen storage" : "#ea048a" 275 | "Sabatier" : "#a31597" 276 | "methanation" : "#a31597" 277 | "helmeth" : "#a31597" 278 | "DAC" : "#d284ff" 279 | "co2 stored" : "#e5e5e5" 280 | "CO2 sequestration" : "#e5e5e5" 281 | "battery" : "#b8ea04" 282 | "battery storage" : "#b8ea04" 283 | "Li ion" : "#b8ea04" 284 | "BEV charger" : "#e2ff7c" 285 | "V2G" : "#7a9618" 286 | "transport fuel cell" : "#e884be" 287 | "retrofitting" : "#e0d6a8" 288 | "building retrofitting" : "#e0d6a8" 289 | "heat pumps" : "#ff9768" 290 | "heat pump" : "#ff9768" 291 | "air heat pump" : "#ffbea0" 292 | "ground heat pump" : "#ff7a3d" 293 | "power-to-heat" : "#a59e7c" 294 | "power-to-gas" : "#db8585" 295 | "power-to-liquid" : "#a9acd1" 296 | "Fischer-Tropsch" : "#a9acd1" 297 | "resistive heater" : "#aa4925" 298 | "water tanks" : "#401f75" 299 | "hot water storage" : "#401f75" 300 | "hot water charging" : "#351c5e" 301 | "hot water discharging" : "#683ab2" 302 | "CHP" : "#d80a56" 303 | "CHP heat" : "#d80a56" 304 | "CHP electric" : "#d80a56" 305 | "district heating" : "#93864b" 306 | "Ambient" : "#262626" 307 | "Electric load" : "#f9d002" 308 | "electricity" : "#f9d002" 309 | "Heat load" : "#d35050" 310 | "heat" : "#d35050" 311 | "Transport load" : "#235ebc" 312 | "transport" : "#235ebc" 313 | "lines" : "#70af1d" 314 | "transmission lines" : "#70af1d" 315 | "AC-AC" : "#70af1d" 316 | "AC line" : "#70af1d" 317 | "links" : "#8a1caf" 318 | "HVDC links" : "#8a1caf" 319 | "DC-DC" : "#8a1caf" 320 | "DC link" : "#8a1caf" 321 | nice_names: 322 | OCGT: "Open-Cycle Gas" 323 | CCGT: "Combined-Cycle Gas" 324 | offwind-ac: "Offshore Wind (AC)" 325 | offwind-dc: "Offshore Wind (DC)" 326 | onwind: "Onshore Wind" 327 | battery: "Battery Storage" 328 | H2: "Hydrogen Storage" 329 | lines: "Transmission lines" 330 | ror: "Run of river" 331 | nice_names_n: 332 | OCGT: "Open-Cycle\nGas" 333 | CCGT: "Combined-Cycle\nGas" 334 | offwind-ac: "Offshore\nWind (AC)" 335 | offwind-dc: "Offshore\nWind (DC)" 336 | onwind: "Onshore\nWind" 337 | battery: "Battery\nStorage" 338 | H2: "Hydrogen\nStorage" 339 | lines: "Transmission\nlines" 340 | ror: "Run of\nriver" 341 | 342 | -------------------------------------------------------------------------------- /scripts/plotting.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Imports" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "%load_ext autoreload\n", 17 | "%autoreload 2" 18 | ] 19 | }, 20 | { 21 | "cell_type": "code", 22 | "execution_count": null, 23 | "metadata": {}, 24 | "outputs": [], 25 | "source": [ 26 | "import pypsa\n", 27 | "import pandas as pd\n", 28 | "import sys, os\n", 29 | "import numpy as np\n", 30 | "import matplotlib.pyplot as plt" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": null, 36 | "metadata": {}, 37 | "outputs": [], 38 | "source": [ 39 | "import plotting.collection as clt\n", 40 | "from plotting.utils import load_memory, assign_carriers" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": null, 46 | "metadata": {}, 47 | "outputs": [], 48 | "source": [ 49 | "%matplotlib inline" 50 | ] 51 | }, 52 | { 53 | "cell_type": "markdown", 54 | "metadata": {}, 55 | "source": [ 56 | "## Preliminaries" 57 | ] 58 | }, 59 | { 60 | "cell_type": "code", 61 | "execution_count": null, 62 | "metadata": {}, 63 | "outputs": [], 64 | "source": [ 65 | "plt.style.use(\"bmh\")" 66 | ] 67 | }, 68 | { 69 | "cell_type": "code", 70 | "execution_count": null, 71 | "metadata": {}, 72 | "outputs": [], 73 | "source": [ 74 | "model_names = {\n", 75 | " \"transport\": \"Transport\",\n", 76 | " \"lossytransport\": \"Lossy\\nTransport\",\n", 77 | " \"lossless-0\": \"Lossless\",\n", 78 | " \"lossy-3-0\": \"Lossy (3T)\",\n", 79 | " \"lossy-5-0\": \"Lossy (5T)\",\n", 80 | " \"lossless-3\": \"Iterative\\nLossless\",\n", 81 | " \"lossy-3-3\": \"Iterative\\nLossy (3T)\",\n", 82 | " \"lossy-5-3\": \"Iterative\\nLossy (5T)\"\n", 83 | "}" 84 | ] 85 | }, 86 | { 87 | "cell_type": "code", 88 | "execution_count": null, 89 | "metadata": {}, 90 | "outputs": [], 91 | "source": [ 92 | "nodes = 200\n", 93 | "opts = \"2H\"" 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": null, 99 | "metadata": {}, 100 | "outputs": [], 101 | "source": [ 102 | "d = \"../summary/\"\n", 103 | "\n", 104 | "if not os.path.exists(d):\n", 105 | " os.makedirs(d)" 106 | ] 107 | }, 108 | { 109 | "cell_type": "code", 110 | "execution_count": null, 111 | "metadata": {}, 112 | "outputs": [], 113 | "source": [ 114 | "csvargs = {\"float_format\": \"%.2f\"}" 115 | ] 116 | }, 117 | { 118 | "cell_type": "markdown", 119 | "metadata": {}, 120 | "source": [ 121 | "## Read Data" 122 | ] 123 | }, 124 | { 125 | "cell_type": "code", 126 | "execution_count": null, 127 | "metadata": {}, 128 | "outputs": [], 129 | "source": [ 130 | "flow_models = [\"transport\", \"lossytransport\", \"lossless-0\", \"lossless-3\", \"lossy-3-0\", \"lossy-5-0\", \"lossy-3-3\", \"lossy-5-3\"]" 131 | ] 132 | }, 133 | { 134 | "cell_type": "code", 135 | "execution_count": null, 136 | "metadata": {}, 137 | "outputs": [], 138 | "source": [ 139 | "logs = {fm: load_memory(f\"../logs/elec_s_{nodes}_lcopt_{opts}_M{fm}_memory.log\") for fm in flow_models}" 140 | ] 141 | }, 142 | { 143 | "cell_type": "code", 144 | "execution_count": null, 145 | "metadata": {}, 146 | "outputs": [], 147 | "source": [ 148 | "pflogs = {fm: pd.read_csv(f\"../results/pf/log_elec_s_{nodes}_ec_lcopt_{opts}_M{fm}_Sdistributed.csv\", index_col=0, header=[0,1]) for fm in flow_models}" 149 | ] 150 | }, 151 | { 152 | "cell_type": "code", 153 | "execution_count": null, 154 | "metadata": {}, 155 | "outputs": [], 156 | "source": [ 157 | "networks = {fm: pypsa.Network(f\"../results/networks/elec_s_{nodes}_ec_lcopt_{opts}_M{fm}.nc\") for fm in flow_models}" 158 | ] 159 | }, 160 | { 161 | "cell_type": "code", 162 | "execution_count": null, 163 | "metadata": {}, 164 | "outputs": [], 165 | "source": [ 166 | "networks_pf = {fm: pypsa.Network(f\"../results/pf/elec_s_{nodes}_ec_lcopt_{opts}_M{fm}_Sdistributed.nc\") for fm in flow_models}" 167 | ] 168 | }, 169 | { 170 | "cell_type": "code", 171 | "execution_count": null, 172 | "metadata": {}, 173 | "outputs": [], 174 | "source": [ 175 | "for n in networks.values():\n", 176 | " assign_carriers(n)\n", 177 | " if \"lossy\" in n.flow_model:\n", 178 | " n.lines_t[\"p0l\"] = n.lines_t.p0 + n.lines_t.loss.where(n.lines_t.p0>0).fillna(0.)\n", 179 | " n.lines_t[\"p1l\"] = n.lines_t.p1 + n.lines_t.loss.where(n.lines_t.p1>0).fillna(0.)\n", 180 | " n.lines_t[\"loading\"] = n.lines_t.p0 + n.lines_t.loss.where(n.lines_t.p0>0).fillna(0.) - n.lines_t.loss.where(n.lines_t.p0<0).fillna(0.)\n", 181 | " else:\n", 182 | " n.lines_t[\"loading\"] = n.lines_t.p0\n", 183 | " \n", 184 | " n.lines_t[\"relative_loading\"] = n.lines_t.loading / n.lines.s_nom_opt" 185 | ] 186 | }, 187 | { 188 | "cell_type": "code", 189 | "execution_count": null, 190 | "metadata": {}, 191 | "outputs": [], 192 | "source": [ 193 | "for npf in networks_pf.values():\n", 194 | " npf.lines_t[\"loading\"] = npf.lines_t.p0.where(npf.lines_t.p0>0).fillna(0.) - npf.lines_t.p1.where(npf.lines_t.p1>0).fillna(0.)\n", 195 | " npf.lines_t[\"relative_loading\"] = npf.lines_t.loading / n.lines.s_nom_opt" 196 | ] 197 | }, 198 | { 199 | "cell_type": "markdown", 200 | "metadata": {}, 201 | "source": [ 202 | "## Make Tables" 203 | ] 204 | }, 205 | { 206 | "cell_type": "code", 207 | "execution_count": null, 208 | "metadata": {}, 209 | "outputs": [], 210 | "source": [ 211 | "pd.DataFrame(\n", 212 | " {k: clt.check_flow_errors(networks[k], networks_pf[k]) for k in networks.keys()},\n", 213 | " index=[\"rmse\", \"mae\", \"mape\", \"corr\", \"r2\"],\n", 214 | ").to_csv(f\"{d}flow_errors.csv\", **csvargs)" 215 | ] 216 | }, 217 | { 218 | "cell_type": "code", 219 | "execution_count": null, 220 | "metadata": {}, 221 | "outputs": [], 222 | "source": [ 223 | "pd.DataFrame({k: clt.check_capacities(v) for k, v in networks.items()}).to_csv(\n", 224 | " f\"{d}capacity.csv\", **csvargs\n", 225 | ")" 226 | ] 227 | }, 228 | { 229 | "cell_type": "code", 230 | "execution_count": null, 231 | "metadata": {}, 232 | "outputs": [], 233 | "source": [ 234 | "pd.DataFrame({k: clt.check_energy_generated(v) for k, v in networks.items()}).to_csv(\n", 235 | " f\"{d}energy.csv\", **csvargs\n", 236 | ")" 237 | ] 238 | }, 239 | { 240 | "cell_type": "code", 241 | "execution_count": null, 242 | "metadata": {}, 243 | "outputs": [], 244 | "source": [ 245 | "pd.DataFrame({k: clt.check_slack(v, pflogs[k]) for k, v in networks_pf.items()}).to_csv(\n", 246 | " f\"{d}slack.csv\", **csvargs\n", 247 | ")" 248 | ] 249 | }, 250 | { 251 | "cell_type": "code", 252 | "execution_count": null, 253 | "metadata": {}, 254 | "outputs": [], 255 | "source": [ 256 | "pd.DataFrame(\n", 257 | " {\n", 258 | " k: [\n", 259 | " clt.check_curtailment(v),\n", 260 | " clt.check_energy_transmitted(v),\n", 261 | " *clt.check_costs(v),\n", 262 | " *clt.check_energy_balance(v),\n", 263 | " ]\n", 264 | " for k, v in networks.items()\n", 265 | " },\n", 266 | " index=[\n", 267 | " \"curtailment\",\n", 268 | " \"energy-transmitted\",\n", 269 | " \"absolute-tsc\",\n", 270 | " \"relative-tsc\",\n", 271 | " \"energy-balance\",\n", 272 | " \"loss-share\",\n", 273 | " \"link-losses\",\n", 274 | " \"line-losses\",\n", 275 | " ],\n", 276 | ").to_csv(f\"{d}misc.csv\", **csvargs)" 277 | ] 278 | }, 279 | { 280 | "cell_type": "markdown", 281 | "metadata": {}, 282 | "source": [ 283 | "## Make Plots (Multiple Models)" 284 | ] 285 | }, 286 | { 287 | "cell_type": "code", 288 | "execution_count": null, 289 | "metadata": {}, 290 | "outputs": [], 291 | "source": [ 292 | "clt.plot_performance(logs, 'peak_mem', model_names, colors=\"forestgreen\", fn=f\"{d}memory.pdf\")\n", 293 | "clt.plot_performance(logs, 'time', model_names, colors=\"midnightblue\", fn=f\"{d}time.pdf\")" 294 | ] 295 | }, 296 | { 297 | "cell_type": "code", 298 | "execution_count": null, 299 | "metadata": {}, 300 | "outputs": [], 301 | "source": [ 302 | "c = ['firebrick', 'indianred', 'midnightblue', 'darkmagenta', \"darkorange\", \"orange\", \"forestgreen\", \"limegreen\"]\n", 303 | "clt.plot_performance(logs, 'peak_mem', model_names, colors=c, fn=f\"{d}memory-c.pdf\")\n", 304 | "clt.plot_performance(logs, 'time', model_names, colors=c, fn=f\"{d}time-c.pdf\")" 305 | ] 306 | }, 307 | { 308 | "cell_type": "code", 309 | "execution_count": null, 310 | "metadata": {}, 311 | "outputs": [], 312 | "source": [ 313 | "groups = {\n", 314 | " \"Generator\": [\"onwind\", \"offwind-ac\", \"offwind-dc\", \"solar\"],\n", 315 | " \"StorageUnit\": [\"H2\", \"battery\"],\n", 316 | " \"Link\": [\"\"],\n", 317 | " \"Line\": [\"\"]\n", 318 | "}\n", 319 | "\n", 320 | "for c, carriers in groups.items():\n", 321 | " for carrier in carriers:\n", 322 | " clt.plot_capacity_correlation(networks, c, model_names, regex=carrier, fn=f\"{d}capacity-correlation-{c}-{carrier}.pdf\")\n", 323 | " clt.plot_capacity_correlation(networks, c, model_names, regex=carrier, triangle=True, fn=f\"{d}capacity-correlation-{c}-{carrier}-triangle.pdf\")" 324 | ] 325 | }, 326 | { 327 | "cell_type": "code", 328 | "execution_count": null, 329 | "metadata": {}, 330 | "outputs": [], 331 | "source": [ 332 | "conv_share = pd.concat([clt.convergence_share(pflogs[fm], fm) for fm in flow_models], axis=1)\n", 333 | "conv_share.to_csv(f\"{d}power-flow-convergence.csv\", **csvargs)\n", 334 | "clt.plot_nonconverged(conv_share, model_names, fn=f\"{d}power-flow-convergence.pdf\")" 335 | ] 336 | }, 337 | { 338 | "cell_type": "code", 339 | "execution_count": null, 340 | "metadata": {}, 341 | "outputs": [], 342 | "source": [ 343 | "clt.plot_cost_bar(networks, model_names, fn=f\"{d}cost-bar.pdf\")" 344 | ] 345 | }, 346 | { 347 | "cell_type": "markdown", 348 | "metadata": {}, 349 | "source": [ 350 | "## Make Plots (Individual Models)" 351 | ] 352 | }, 353 | { 354 | "cell_type": "code", 355 | "execution_count": null, 356 | "metadata": {}, 357 | "outputs": [], 358 | "source": [ 359 | "clt.plot_feasible_space(networks[\"transport\"].lines.iloc[2], fn=f\"{d}feasiblespace.pdf\")" 360 | ] 361 | }, 362 | { 363 | "cell_type": "code", 364 | "execution_count": null, 365 | "metadata": {}, 366 | "outputs": [], 367 | "source": [ 368 | "for name in networks.keys():\n", 369 | " \n", 370 | " print(name)\n", 371 | " \n", 372 | " n = networks[name]\n", 373 | " n_pf = networks_pf[name]\n", 374 | " \n", 375 | " clt.plot_network(n, fn=f\"{d}network-{name}.pdf\")\n", 376 | " clt.plot_negative_marginal_prices(n, fn=f\"{d}negative-lmp-{name}.pdf\")\n", 377 | " \n", 378 | " for vmax in [600, 1200]:\n", 379 | " clt.plot_flow_comparison(n, n_pf, vmax=vmax, fn=f\"{d}flow-comparison-cbar{vmax}-{name}.pdf\")\n", 380 | " \n", 381 | " clt.plot_duration_curve(n, n_pf, apparent=False, fn=f\"{d}flow-duration-curve-p-{name}.pdf\")\n", 382 | " clt.plot_duration_curve(n, n_pf, apparent=True, fn=f\"{d}flow-duration-curve-s-{name}.pdf\")\n", 383 | " \n", 384 | " clt.plot_v_ang_diff(n_pf, fn=f\"{d}v-ang-diff-{name}.pdf\")\n", 385 | " \n", 386 | " if \"lossy\" in name:\n", 387 | " clt.plot_network_losses(n, fn = f\"{d}network-losses-{name}.pdf\")\n", 388 | " for vmax in [100, 200]:\n", 389 | " clt.plot_flow_vs_loss(n, vmax=vmax, fn=f\"{d}flow-vs-loss-cbar{vmax}-{name}.pdf\")\n", 390 | " clt.plot_loss_comparison(n, n_pf, vmax=vmax, fn=f\"{d}loss-comparison-cbar{vmax}-{name}.pdf\")" 391 | ] 392 | }, 393 | { 394 | "cell_type": "code", 395 | "execution_count": null, 396 | "metadata": {}, 397 | "outputs": [], 398 | "source": [] 399 | } 400 | ], 401 | "metadata": { 402 | "kernelspec": { 403 | "display_name": "Python 3", 404 | "language": "python", 405 | "name": "python3" 406 | }, 407 | "language_info": { 408 | "codemirror_mode": { 409 | "name": "ipython", 410 | "version": 3 411 | }, 412 | "file_extension": ".py", 413 | "mimetype": "text/x-python", 414 | "name": "python", 415 | "nbconvert_exporter": "python", 416 | "pygments_lexer": "ipython3", 417 | "version": "3.7.3" 418 | } 419 | }, 420 | "nbformat": 4, 421 | "nbformat_minor": 4 422 | } 423 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | Loss Approximation 635 | Copyright (C) 2020 FN 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Loss Approximation Copyright (C) 2020 FN 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------