How to use the pypsa.Network function in pypsa

To help you get started, we’ve selected a few pypsa examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github PyPSA / PyPSA / test / test_pf_against_pypower.py View on Github external
columns = 'bus0, bus1, r, x, b, rateA, rateB, rateC, ratio, angle, status, angmin, angmax, p0, q0, p1, q1'.split(", ")
    results_df['branch'] = pd.DataFrame(data=results["branch"],columns=columns)

    #buses
    columns = ["bus","type","Pd","Qd","Gs","Bs","area","v_mag_pu","v_ang","v_nom","zone","Vmax","Vmin"]
    results_df['bus'] = pd.DataFrame(data=results["bus"],columns=columns,index=results["bus"][:,0])

    #generators
    columns = "bus, p, q, q_max, q_min, Vg, mBase, status, p_max, p_min, Pc1, Pc2, Qc1min, Qc1max, Qc2min, Qc2max, ramp_agc, ramp_10, ramp_30, ramp_q, apf".split(", ")
    results_df['gen'] = pd.DataFrame(data=results["gen"],columns=columns)



    #now compute in PyPSA

    network = pypsa.Network()
    network.import_from_pypower_ppc(ppc)

    #PYPOWER uses PI model for transformers, whereas PyPSA defaults to
    #T since version 0.8.0
    network.transformers.model = "pi"

    network.pf()

    #compare branch flows
    for c in network.iterate_components(network.passive_branch_components):
        for si in ["p0","p1","q0","q1"]:
            si_pypsa = getattr(c.pnl,si).loc["now"].values
            si_pypower = results_df['branch'][si][c.df.original_index].values
            np.testing.assert_array_almost_equal(si_pypsa,si_pypower)
github PyPSA / PyPSA / test / test_opf_storage.py View on Github external
def test_opf():


    csv_folder_name = os.path.join(os.path.dirname(__file__), "../examples/opf-storage-hvdc/opf-storage-data")

    network = pypsa.Network(csv_folder_name)

    #test results were generated with GLPK and other solvers may differ
    solver_name = "glpk"

    snapshots = network.snapshots

    network.lopf(snapshots=snapshots,solver_name=solver_name)


    results_folder_name = "results"


    network.export_to_csv_folder(results_folder_name)

    good_results_filename =  os.path.join(csv_folder_name,"results","generators-p.csv")
github PyPSA / PyPSA / test / test_pf_against_pandapower.py View on Github external
b3 = pp.create_bus(net, vn_kv=0.4, name="Bus 3")

    #create bus elements
    pp.create_ext_grid(net, bus=b1, vm_pu=1.02, name="Grid Connection")
    pp.create_load(net, bus=b3, p_mw=0.1, q_mvar=0.05, name="Load")

    #create branch elements
    tid = pp.create_transformer(net, hv_bus=b1, lv_bus=b2, std_type="0.4 MVA 20/0.4 kV",
                                                            name="Trafo")
    pp.create_line(net, from_bus=b2, to_bus=b3, length_km=0.1, name="Line",
                                  std_type="NAYY 4x50 SE")

    #because of phase angles, need to init with DC
    pp.runpp(net,calculate_voltage_angles=True, init="dc")

    n = pypsa.Network()

    n.import_from_pandapower_net(net)

    #seed PF with LPF solution because of phase angle jumps
    n.lpf()
    n.pf(use_seed=True)

    #use same index for everything
    net.res_bus.index = net.bus.name.values
    net.res_line.index = net.line.name.values

    #compare bus angles
    np.testing.assert_array_almost_equal(n.buses_t.v_ang.loc["now"]*180/np.pi,net.res_bus.va_degree)

    #compare bus voltage magnitudes
    np.testing.assert_array_almost_equal(n.buses_t.v_mag_pu.loc["now"],net.res_bus.vm_pu)
github PyPSA / PyPSA / examples / opf.py View on Github external
from pypsa.dicthelpers import attrfilter

import datetime
import pandas as pd

import networkx as nx

import numpy as np


# In[2]:

#Build the Network object, which stores all other objects

network = pypsa.Network()

#Build the snapshots we consider for the first T hours in 2015

T = 10

network.index = pd.to_datetime([datetime.datetime(2015,1,1) + datetime.timedelta(hours=i) for i in range(T)])

network.now = network.index[0]

print("network:",network)
print("index:",network.index)
print("current snapshot:",network.now)


# In[3]:
github PyPSA / PyPSA / examples / scigrid-de / scigrid-lopf-then-pf.py View on Github external
import os

import matplotlib.pyplot as plt

import cartopy.crs as ccrs

#%matplotlib inline

#You may have to adjust this path to where 
#you downloaded the github repository
#https://github.com/PyPSA/PyPSA

csv_folder_name = os.path.dirname(pypsa.__file__) + "/../examples/scigrid-de/scigrid-with-load-gen-trafos/"

network = pypsa.Network(csv_folder_name=csv_folder_name)

### Plot the distribution of the load and of generating tech

fig,ax = plt.subplots(1,1,subplot_kw={"projection":ccrs.PlateCarree()})

fig.set_size_inches(6,6)

load_distribution = network.loads_t.p_set.loc[network.snapshots[0]].groupby(network.loads.bus).sum()

network.plot(bus_sizes=0.5*load_distribution,ax=ax,title="Load distribution")

fig.tight_layout()
#fig.savefig('load-distribution.png')

network.generators.groupby("carrier")["p_nom"].sum()
github PyPSA / PyPSA / examples / ac-dc-meshed / ac-dc-lpf.py View on Github external
# make the code as Python 3 compatible as possible
from __future__ import print_function, division
from __future__ import absolute_import


import pypsa, os

import pandas as pd

import numpy as np

from itertools import chain

network = pypsa.Network()

folder_name = "ac-dc-data"
network.import_from_csv_folder(folder_name)

network.lpf(network.snapshots)


print("\nSub-Networks:")

for sn in network.sub_networks.obj:
    print(sn,network.sub_networks.at[sn.name,"carrier"],len(sn.buses()),len(sn.branches()))


print("\nControllable branches:")

print(network.links)
github PyPSA / PyPSA / examples / opf-storage-hvdc / opf-storage.py View on Github external
import networkx as nx

import numpy as np

from itertools import chain

import os


from distutils.spawn import find_executable




csv_folder_name = "opf-storage-data"
network = pypsa.Network(csv_folder_name=csv_folder_name)
print(network,network.co2_limit)

#useful for debugging
network.opf_keep_files = True

network.determine_network_topology()

print("Connected networks:\n",network.sub_networks)


solver_search_order = ["glpk","gurobi"]

solver_executable = {"glpk" : "glpsol", "gurobi" : "gurobi_cl"}

solver_name = None
github PyPSA / PyPSA / examples / sector-coupling / battery-electric-vehicle-charging.py View on Github external
# consumption pattern of BEV
bev_usage = pd.Series([0.]*7 + [9.]*2 + [0.]*8 + [9.]*2 + [0.]*5,index)

# solar PV panel generation per unit of capacity
pv_pu = pd.Series([0.]*7 + [0.2,0.4,0.6,0.75,0.85,0.9,0.85,0.75,0.6,0.4,0.2,0.1] + [0.]*5,index)

# availability of charging - i.e. only when parked at office
charger_p_max_pu = pd.Series(0.,index=index)
charger_p_max_pu["2016-01-01 09:00":"2016-01-01 16:00"] = 1.

bev_usage.plot()
pv_pu.plot()
charger_p_max_pu.plot()


network = pypsa.Network()

network.set_snapshots(index)

network.add("Bus",
            "place of work",
            carrier="AC")

network.add("Bus",
            "battery",
            carrier="Li-ion")

network.add("Generator",
            "PV panel",
            bus="place of work",
            p_nom_extendable=True,
            p_max_pu=pv_pu,
github PyPSA / PyPSA / examples / unit-commitment.py View on Github external
nu.add("Generator","gas",bus="bus",
       marginal_cost=70,
       p_nom=4000)

nu.add("Load","load",bus="bus",p_set=[4000,7000,7000,7000,7000,3000])

nu.lopf(nu.snapshots)

nu.generators.p_nom_opt

nu.generators_t.p

import pypsa

nu = pypsa.Network()

nu.set_snapshots(range(7))

nu.add("Bus","bus")


#Can get bad interactions if SU > RU and p_min_pu; similarly if SD > RD


nu.add("Generator","coal",bus="bus",
       marginal_cost=20,
       committable=True,
       p_min_pu=0.05,
       initial_status=0,
       ramp_limit_start_up=0.1,
       ramp_limit_up=0.2,
github PyPSA / PyPSA / examples / sector-coupling / chp-fixed-heat-power-ratio.py View on Github external
#
#In this example a CHP must be heat-following because there is no other supply of heat to the bus "Frankfurt heat".

import pypsa, numpy as np

#First tell PyPSA that links will have a 2nd bus by
#overriding the component_attrs. This can be done for
#as many buses as you need with format busi for i = 2,3,4,5,....

override_component_attrs = pypsa.descriptors.Dict({k : v.copy() for k,v in pypsa.components.component_attrs.items()})
override_component_attrs["Link"].loc["bus2"] = ["string",np.nan,np.nan,"2nd bus","Input (optional)"]
override_component_attrs["Link"].loc["efficiency2"] = ["static or series","per unit",1.,"2nd bus efficiency","Input (optional)"]
override_component_attrs["Link"].loc["p2"] = ["series","MW",0.,"2nd bus output","Output"]


network = pypsa.Network(override_component_attrs=override_component_attrs)

network.add("Bus",
            "Frankfurt",
            carrier="AC")

network.add("Load",
            "Frankfurt",
            bus="Frankfurt",
            p_set=5)

network.add("Bus",
            "Frankfurt heat",
            carrier="heat")

network.add("Load",
            "Frankfurt heat",