How to use the pypsa.descriptors.Dict 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 / pypsa / linopf.py View on Github external
def prepare_lopf(n, snapshots=None, keep_files=False,
                 extra_functionality=None, solver_dir=None):
    """
    Sets up the linear problem and writes it out to a lp file

    Returns
    -------
    Tuple (fdp, problem_fn) indicating the file descriptor and the file name of
    the lp file

    """
    n._xCounter, n._cCounter = 1, 1
    n.vars, n.cons = Dict(), Dict()

    cols = ['component', 'name', 'pnl', 'specification']
    n.variables = pd.DataFrame(columns=cols).set_index(cols[:2])
    n.constraints = pd.DataFrame(columns=cols).set_index(cols[:2])

    snapshots = n.snapshots if snapshots is None else snapshots
    start = time.time()

    tmpkwargs = dict(text=True, dir=solver_dir)
    # mkstemp(suffix, prefix, **tmpkwargs)
    fdo, objective_fn = mkstemp('.txt', 'pypsa-objectve-', **tmpkwargs)
    fdc, constraints_fn = mkstemp('.txt', 'pypsa-constraints-', **tmpkwargs)
    fdb, bounds_fn = mkstemp('.txt', 'pypsa-bounds-', **tmpkwargs)
    fdi, binaries_fn = mkstemp('.txt', 'pypsa-binaries-', **tmpkwargs)
    fdp, problem_fn = mkstemp('.lp', 'pypsa-problem-', **tmpkwargs)
github PyPSA / PyPSA / examples / new_components / add_components_simple.py View on Github external
import pypsa, pandas as pd, numpy as np

from pypsa.descriptors import Dict

#take a copy of the components pandas.DataFrame
override_components = pypsa.components.components.copy()

#Pass it the list_name, description and component type.
override_components.loc["ShadowPrice"] = ["shadow_prices","Shadow price for a global constraint.",np.nan]

print("\nNew components table:\n")
print(override_components)

#create a pandas.DataFrame with the properties of the new component attributes.
#the format should be the same as pypsa/component_attrs/*.csv
override_component_attrs = Dict({k : v.copy() for k,v in pypsa.components.component_attrs.items()})
override_component_attrs["ShadowPrice"] = pd.DataFrame(columns = ["type","unit","default","description","status"])
override_component_attrs["ShadowPrice"].loc["name"] = ["string","n/a","n/a","Unique name","Input (required)"]
override_component_attrs["ShadowPrice"].loc["value"] = ["float","n/a",0.,"shadow value","Output"]

print("\nComponent attributes for ShadowPrice:\n")
print(override_component_attrs["ShadowPrice"])

#pass Network the information
n = pypsa.Network(override_components=override_components,
                  override_component_attrs=override_component_attrs)

n.add("ShadowPrice","line_volume_constraint",value=4567.1)
n.add("ShadowPrice","co2_constraint",value=326.3)

print("\nnetwork.shadow_prices:\n")
github PyPSA / PyPSA / pypsa / linopf.py View on Github external
to_component = c in n.all_components
        if is_pnl:
            n.dualvalues.at[(c, attr), 'in_comp'] = to_component
            duals = constraints.stack().map(sign * constraints_dual).unstack()
            if c not in n.duals and not to_component:
                n.duals[c] = Dict(df=pd.DataFrame(), pnl={})
            pnl = n.pnl(c) if to_component else n.duals[c].pnl
            set_from_frame(pnl, attr, duals)
        else:
            # here to_component can change
            duals = constraints.map(sign * constraints_dual)
            if to_component:
                to_component = (duals.index.isin(n.df(c).index).all())
            n.dualvalues.at[(c, attr), 'in_comp'] = to_component
            if c not in n.duals and not to_component:
                n.duals[c] = Dict(df=pd.DataFrame(), pnl={})
            df = n.df(c) if to_component else n.duals[c].df
            df[attr] = duals
github PyPSA / PyPSA / pypsa / linopt.py View on Github external
def set_varref(n, variables, c, attr, spec=''):
    """
    Sets variable references to the network.
    One-dimensional variable references will be collected at n.vars[c].df,
    two-dimensional varaibles in n.vars[c].pnl
    For example:
    * nominal capacity variables for generators are stored in
      `n.vars.Generator.df.p_nom`
    * operational variables for generators are stored in
      `n.vars.Generator.pnl.p`
    """
    if not variables.empty:
        pnl = variables.ndim == 2
        if c not in n.variables.index:
            n.vars[c] = Dict(df=pd.DataFrame(), pnl=Dict())
        if ((c, attr) in n.variables.index) and (spec != ''):
            n.variables.at[idx[c, attr], 'specification'] += ', ' + spec
        else:
            n.variables.loc[idx[c, attr], :] = [pnl, spec]
        _add_reference(n.vars[c], variables, attr, pnl=pnl)
github PyPSA / PyPSA / examples / sector-coupling / chp-fixed-heat-power-ratio.py View on Github external
## Demonstration of Link with multiple outputs: Combined-Heat-and-Power (CHP) with fixed heat-power ratio
#
#For a CHP with a more complicated heat-power feasible operational area, see https://www.pypsa.org/examples/power-to-gas-boiler-chp.html.
#
#This example demonstrates a Link component with more than one bus output ("bus2" in this case). In general links can have many output buses.
#
#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)
github PyPSA / PyPSA / pypsa / linopt.py View on Github external
def set_conref(n, constraints, c, attr, spec=''):
    """
    Sets variable references to the network.
    One-dimensional constraint references will be collected at n.cons[c].df,
    two-dimensional in n.cons[c].pnl
    For example:
    * constraints for nominal capacity variables for generators are stored in
      `n.cons.Generator.df.mu_upper`
    * operational capacity limits for generators are stored in
      `n.cons.Generator.pnl.mu_upper`
    """
    if not constraints.empty:
        pnl = constraints.ndim == 2
        if c not in n.constraints.index:
            n.cons[c] = Dict(df=pd.DataFrame(), pnl=Dict())
        if ((c, attr) in n.constraints.index) and (spec != ''):
            n.constraints.at[idx[c, attr], 'specification'] += ', ' + spec
        else:
            n.constraints.loc[idx[c, attr], :] = [pnl, spec]
        _add_reference(n.cons[c], constraints, attr, pnl=pnl)
github PyPSA / PyPSA / pypsa / pf.py View on Github external
itdf[sub_network.name],\
                difdf[sub_network.name],\
                cnvdf[sub_network.name] = sub_network_pf_singlebus(sub_network, snapshots=snapshots, skip_pre=True,
                                                                   distribute_slack=distribute_slack,
                                                                   slack_weights=sn_slack_weights)
            else:
                itdf[sub_network.name],\
                difdf[sub_network.name],\
                cnvdf[sub_network.name] = sub_network_pf_fun(sub_network, snapshots=snapshots,
                                                             skip_pre=True, distribute_slack=distribute_slack,
                                                             slack_weights=sn_slack_weights, **kwargs)
        else:
            sub_network_pf_fun(sub_network, snapshots=snapshots, skip_pre=True, **kwargs)

    if not linear:
        return Dict({ 'n_iter': itdf, 'error': difdf, 'converged': cnvdf })