Ejemplo n.º 1
0
def from_json_dict(json_dict):
    """
    Load a pandapower network from a JSON string.
    The index of the returned network is not necessarily in the same order as the original network.
    Index columns of all pandas DataFrames are sorted in ascending order.

    INPUT:
        **json_dict** (json) - The json object representation of the network

    OUTPUT:
        **convert** (bool) - use the convert format function to

        **net** (dict) - The pandapower format network

    EXAMPLE:

        >>> net = pp.pp.from_json_dict(json.loads(json_str))

    """
    net = create_empty_network(name=json_dict["name"], f_hz=json_dict["f_hz"])

    for key in sorted(json_dict.keys()):
        if key == 'dtypes':
            continue
        if key in net and isinstance(net[key], pd.DataFrame) and isinstance(
                json_dict[key], dict):
            net[key] = pd.DataFrame.from_dict(json_dict[key], orient="columns")
            net[key].set_index(net[key].index.astype(numpy.int64),
                               inplace=True)
        else:
            net[key] = json_dict[key]
    return net
Ejemplo n.º 2
0
def _add_missing_tables(net):
    net_new = create_empty_network()
    for key in net_new.keys():
        if key.startswith("_empty_res"):
            net[key] = net_new[key]
        elif key not in net.keys():
            net[key] = net_new[key]
Ejemplo n.º 3
0
def _rename_columns(net):
    net.line.rename(columns={'imax_ka': 'max_i_ka'}, inplace=True)
    for typ, data in net.std_types["line"].items():
        if "imax_ka" in data:
            net.std_types["line"][typ]["max_i_ka"] = net.std_types["line"][typ].pop("imax_ka")
    _update_trafo_parameter_names(net)
    # initialize measurement dataframe
    if "measurement" in net and "type" in net.measurement:
        if net.measurement.empty:
            net["measurement"] = create_empty_network()["measurement"]
        else:
            net.measurement["side"] = None
            bus_measurements = net.measurement.element_type == "bus"
            net.measurement.loc[bus_measurements, "element"] = net.measurement.loc[
                    bus_measurements, "bus"].values
            net.measurement.loc[~bus_measurements, "side"] = net.measurement.loc[
                    ~bus_measurements, "bus"].values
            net.measurement.rename(columns={'type': 'measurement_type'}, inplace=True)
            net.measurement.drop(["bus"], axis=1, inplace=True)
    if "options" in net:
        if "recycle" in net["options"]:
            if "_is_elements" not in net["options"]["recycle"]:
                net["options"]["recycle"]["_is_elements"] = copy.deepcopy(
                    net["options"]["recycle"]["is_elems"])
                net["options"]["recycle"].pop("is_elems", None)
Ejemplo n.º 4
0
def from_json_dict(json_dict):
    """
    Load a pandapower network from a JSON string.
    The index of the returned network is not necessarily in the same order as the original network.
    Index columns of all pandas DataFrames are sorted in ascending order.

    INPUT:
        **json_dict** (json) - The json object representation of the network

    OUTPUT:
        **net** (dict) - The pandapower format network

    EXAMPLE:

        >>> net = pp.pp.from_json_dict(json.loads(json_str))

    """
    name = json_dict["name"] if "name" in json_dict else None
    f_hz = json_dict["f_hz"] if "f_hz" in json_dict else 50
    net = create_empty_network(name=name, f_hz=f_hz)
    if "parameters" in json_dict:
        for par, value in json_dict["parameters"]["parameter"].items():
            net[par] = value

    for key in sorted(json_dict.keys()):
        if key == 'dtypes':
            continue
        if key in net and isinstance(net[key], pd.DataFrame) and isinstance(json_dict[key], dict) \
                or key == "piecewise_linear_cost" or key == "polynomial_cost":
            net[key] = pd.DataFrame.from_dict(json_dict[key], orient="columns")
            net[key].set_index(net[key].index.astype(numpy.int64),
                               inplace=True)
        else:
            net[key] = json_dict[key]
    return net
Ejemplo n.º 5
0
def correct_dtypes(net, error):
    """
    Corrects all dtypes of pp element tables if possile. If not and error is True, an Error is
    raised.
    """
    empty_net = create_empty_network()
    not_corrected = list()
    failed = dict()
    for key, table in empty_net.items():
        if isinstance(table, pd.DataFrame):
            if key in net.keys() and isinstance(net[key], pd.DataFrame):
                cols = table.columns.intersection(net[key].columns)
                diff_cols = cols[~(
                    table.dtypes.loc[cols] == net[key].dtypes.loc[cols])]
                for col in diff_cols:
                    try:
                        net[key][col] = net[key][col].astype(table[col].dtype)
                    except ValueError:
                        if key not in failed.keys():
                            failed[key] = [col]
                        else:
                            failed[key].append(col)
            else:
                not_corrected.append(key)
    if not_corrected:
        logger.warning(
            "These keys were not corrected since they miss or are no dataframes: "
            + str(not_corrected))
    if failed:
        msg = "These dtypes could not be corrected: " + str(failed)
        if error:
            raise ValueError(msg)
        else:
            logger.info(msg)
Ejemplo n.º 6
0
def from_dict_of_dfs(dodfs):
    net = create_empty_network()
    for c in dodfs["parameters"].columns:
        net[c] = dodfs["parameters"].at[0, c]
    for item, table in dodfs.items():
        if item in ("parameters", "dtypes"):
            continue
        elif item in ["line_geodata", "bus_geodata"]:
            df_to_coords(net, item, table)
        elif item.endswith("_std_types"):
            net["std_types"][item[:-10]] = table.T.to_dict()
            continue  # don't go into try..except
        elif item.endswith("_profiles"):
            if "profiles" not in net.keys():
                net["profiles"] = dict()
            net["profiles"][item[:-9]] = table
            continue  # don't go into try..except
        elif item == "user_pf_options":
            net['user_pf_options'] = {
                c: v
                for c, v in zip(table.columns, table.values[0])
            }
            continue  # don't go into try..except
        else:
            net[item] = table
        # set the index to be Int64Index
        try:
            net[item].set_index(net[item].index.astype(numpy.int64),
                                inplace=True)
        except TypeError:
            # TypeError: if not int64 index (e.g. str)
            pass
    restore_all_dtypes(net, dodfs["dtypes"])
    return net
Ejemplo n.º 7
0
def from_dict_of_dfs(dodfs):
    net = create_empty_network()
    for p, v in dodfs["parameters"].iterrows():
        net[p] = v.parameter
    for item, table in dodfs.items():
        if item in ("parameters", "dtypes"):
            continue
        elif item == "line_geodata":
            num_points = len(table.columns) // 2
            for i in table.index:
                coords = table.loc[i]
                # for i, coords in table.iterrows():
                coord = [(coords["x%u" % nr], coords["y%u" % nr]) for nr in range(num_points)
                         if pd.notnull(coords["x%u" % nr])]
                net.line_geodata.loc[i, "coords"] = coord
        elif item.endswith("_std_types"):
            net["std_types"][item[:-10]] = table.T.to_dict()
            continue  # don't go into try..except
        elif item == "user_pf_options":
            net['user_pf_options'] = {c: v for c, v in zip(table.columns, table.values[0])}
            continue  # don't go into try..except
        else:
            net[item] = table
        # set the index to be Int64Index
        try:
            net[item].set_index(net[item].index.astype(numpy.int64), inplace=True)
        except TypeError:
            # TypeError: if not int64 index (e.g. str)
            pass
    restore_all_dtypes(net, dodfs["dtypes"])
    return net
Ejemplo n.º 8
0
 def pandapowerNet(self):
     if isinstance(self.obj, str):  # backwards compatibility
         from pandapower import from_json_string
         return from_json_string(self.obj)
     else:
         net = create_empty_network()
         net.update(self.obj)
         return net
Ejemplo n.º 9
0
 def __init__(self, **kwargs):
     # net = pandapowerNet.__new__(pandapowerNet)
     net = create_empty_network()
     super_kwargs = {
         "object_hook":
         partial(pp_hook, net=net, registry_class=FromSerializableRegistry)
     }
     super_kwargs.update(kwargs)
     super().__init__(**super_kwargs)
Ejemplo n.º 10
0
def from_json(filename, convert=True):
    """
    Load a pandapower network from a JSON file.
    The index of the returned network is not necessarily in the same order as the original network.
    Index columns of all pandas DataFrames are sorted in ascending order.

    INPUT:
        **filename** (string) - The absolute or relative path to the input file.

    OUTPUT:
        **convert** (bool) - use the convert format function to

        **net** (dict) - The pandapower format network

    EXAMPLE:

        >>> net = pp.from_json("example.json")

    """
    with open(filename) as data_file:
        data = json.load(data_file)
        net = create_empty_network(name=data["name"], f_hz=data["f_hz"])

        # checks if field exists in empty network and if yes, matches data type
        def check_equal_type(name):
            if name in net:
                if isinstance(net[name], type(data[name])):
                    return True
                elif isinstance(net[name], pd.DataFrame) and isinstance(
                        data[name], dict):
                    return True
                else:
                    return False
            return True

        for k in sorted(data.keys()):
            if not check_equal_type(k):
                raise UserWarning(
                    "Different data type for existing pandapower field")
            if isinstance(data[k], dict):
                if isinstance(net[k], pd.DataFrame):
                    columns = net[k].columns
                    net[k] = pd.DataFrame.from_dict(data[k], orient="columns")
                    net[k].set_index(net[k].index.astype(numpy.int64),
                                     inplace=True)
                    net[k] = net[k][columns]
                else:
                    net[k] = data[k]
            else:
                net[k] = data[k]
        if convert:
            convert_format(net)
        return net
    return None
Ejemplo n.º 11
0
def from_json_dict(json_dict, convert=True):
    """
    Load a pandapower network from a JSON string.
    The index of the returned network is not necessarily in the same order as the original network.
    Index columns of all pandas DataFrames are sorted in ascending order.

    INPUT:
        **json_dict** (json) - The json object representation of the network

    OUTPUT:
        **convert** (bool) - use the convert format function to

        **net** (dict) - The pandapower format network

    EXAMPLE:

        >>> net = pp.pp.from_json_dict(json.loads(json_str))

    """
    net = create_empty_network(name=json_dict["name"], f_hz=json_dict["f_hz"])

    # checks if field exists in empty network and if yes, matches data type
    def check_equal_type(name):
        if name in net:
            if isinstance(net[name], type(json_dict[name])):
                return True
            elif isinstance(net[name], pd.DataFrame) and isinstance(
                    json_dict[name], dict):
                return True
            else:
                return False
        return True

    for k in sorted(json_dict.keys()):
        if not check_equal_type(k):
            raise UserWarning(
                "Different data type for existing pandapower field")
        if isinstance(json_dict[k], dict):
            if isinstance(net[k], pd.DataFrame):
                columns = net[k].columns
                net[k] = pd.DataFrame.from_dict(json_dict[k], orient="columns")
                net[k].set_index(net[k].index.astype(numpy.int64),
                                 inplace=True)
                net[k] = net[k][columns]
            else:
                net[k] = json_dict[k]
        else:
            net[k] = json_dict[k]
    if convert:
        convert_format(net)
    return net
Ejemplo n.º 12
0
def _set_data_type_of_columns(net):
    new_net = create_empty_network()
    for key, item in net.items():
        if isinstance(item, pd.DataFrame):
            for col in item.columns:
                if key in new_net and col in new_net[key].columns:
                    if set(item.columns) == set(new_net[key]):
                        if version.parse(pd.__version__) < version.parse("0.21"):
                            net[key] = net[key].reindex_axis(new_net[key].columns, axis=1)
                        else:
                            net[key] = net[key].reindex(new_net[key].columns, axis=1)
                    if version.parse(pd.__version__) < version.parse("0.20.0"):
                        net[key][col] = net[key][col].astype(new_net[key][col].dtype,
                                                             raise_on_error=False)
                    else:
                        net[key][col] = net[key][col].astype(new_net[key][col].dtype,
                                                             errors="ignore")
Ejemplo n.º 13
0
def from_excel(filename, convert=True):
    """
    Load a pandapower network from an excel file

    INPUT:
        **filename** (string) - The absolute or relative path to the input file.

    OUTPUT:
        **convert** (bool) - use the convert format function to

        **net** (dict) - The pandapower format network

    EXAMPLE:

        >>> net1 = pp.from_excel(os.path.join("C:", "example_folder", "example1.xlsx")) #absolute path
        >>> net2 = pp.from_excel("example2.xlsx") #relative path

    """
    xls = pd.ExcelFile(filename).parse(sheetname=None)
    par = xls["parameters"]["parameters"]
    name = None if pd.isnull(par.at["name"]) else par.at["name"]
    net = create_empty_network(name=name, f_hz=par.at["f_hz"])

    for item, table in xls.items():
        if item == "parameters":
            continue
        elif item.endswith("std_types"):
            item = item.split("_")[0]
            for std_type, tab in table.iterrows():
                net.std_types[item][std_type] = dict(tab)
        elif item == "line_geodata":
            points = int(len(table.columns) / 2)
            for i, coords in table.iterrows():
                coord = [(coords["x%u" % nr], coords["y%u" % nr])
                         for nr in range(points)
                         if pd.notnull(coords["x%u" % nr])]
                net.line_geodata.loc[i, "coords"] = coord
        else:
            net[item] = table


#    net.line.geodata.coords.
    if convert:
        convert_format(net)
    return net
Ejemplo n.º 14
0
def _rename_columns(net, elements_to_deserialize):
    if _check_elements_to_deserialize('line', elements_to_deserialize):
        net.line.rename(columns={'imax_ka': 'max_i_ka'}, inplace=True)
    for typ, data in net.std_types["line"].items():
        if "imax_ka" in data:
            net.std_types["line"][typ]["max_i_ka"] = net.std_types["line"][
                typ].pop("imax_ka")
    _update_trafo_parameter_names(net, elements_to_deserialize)
    # initialize measurement dataframe
    if _check_elements_to_deserialize('measurement', elements_to_deserialize):
        if "measurement" in net and "type" in net.measurement and "measurement":
            if net.measurement.empty:
                net["measurement"] = create_empty_network()["measurement"]
            else:
                net.measurement["side"] = None
                bus_measurements = net.measurement.element_type == "bus"
                net.measurement.loc[bus_measurements, "element"] = \
                    net.measurement.loc[bus_measurements, "bus"].values
                net.measurement.loc[~bus_measurements, "side"] = \
                    net.measurement.loc[~bus_measurements, "bus"].values
                net.measurement.rename(columns={'type': 'measurement_type'},
                                       inplace=True)
                net.measurement.drop(["bus"], axis=1, inplace=True)
    if _check_elements_to_deserialize('controller', elements_to_deserialize):
        if "controller" in net:
            net["controller"].rename(columns={"controller": "object"},
                                     inplace=True)
    if "options" in net:
        if "recycle" in net["options"]:
            if "Ybus" in net["options"]["recycle"]:
                if net["options"]["recycle"]["Ybus"]:
                    net["options"]["recycle"]["trafo"] = False
                del net["options"]["recycle"]["Ybus"]
            else:
                net["options"]["recycle"]["trafo"] = True
            if "ppc" in net["options"]["recycle"]:
                if net["options"]["recycle"]["ppc"]:
                    net["options"]["recycle"]["bus_pq"] = False
                del net["options"]["recycle"]["ppc"]
            else:
                net["options"]["recycle"]["bus_pq"] = True
Ejemplo n.º 15
0
def _from_excel_old(xls):
    par = xls["parameters"]["parameter"]
    name = None if pd.isnull(par.at["name"]) else par.at["name"]
    net = create_empty_network(name=name, f_hz=par.at["f_hz"])
    net.update(par)
    for item, table in xls.items():
        if item == "parameters":
            continue
        elif item.endswith("std_types"):
            item = item.split("_")[0]
            for std_type, tab in table.iterrows():
                net.std_types[item][std_type] = dict(tab)
        elif item == "line_geodata":
            points = int(len(table.columns) / 2)
            for i, coords in table.iterrows():
                coord = [(coords["x%u" % nr], coords["y%u" % nr]) for nr in range(points)
                         if pd.notnull(coords["x%u" % nr])]
                net.line_geodata.loc[i, "coords"] = coord
        else:
            net[item] = table
    return net
Ejemplo n.º 16
0
def from_json_dict(json_dict, convert=True):
    """
    Load a pandapower network from a JSON string.
    The index of the returned network is not necessarily in the same order as the original network.
    Index columns of all pandas DataFrames are sorted in ascending order.

    INPUT:
        **json_dict** (json) - The json object representation of the network

    OUTPUT:
        **convert** (bool) - use the convert format function to

        **net** (dict) - The pandapower format network

    EXAMPLE:

        >>> net = pp.pp.from_json_dict(json.loads(json_str))

    """
    warn(
        "This function is deprecated and will be removed in a future release.\r\n"
        "Please resave your grid using the current pandapower version.",
        DeprecationWarning)
    net = create_empty_network(name=json_dict["name"], f_hz=json_dict["f_hz"])

    for key in sorted(json_dict.keys()):
        if key == 'dtypes':
            continue
        if key in net and isinstance(net[key], pd.DataFrame) and isinstance(
                json_dict[key], dict):
            net[key] = pd.DataFrame.from_dict(json_dict[key], orient="columns")
            net[key].set_index(net[key].index.astype(numpy.int64),
                               inplace=True)
        else:
            net[key] = json_dict[key]

    if convert:
        convert_format(net)
    return net
Ejemplo n.º 17
0
def convert_format(net):
    """
    Converts old nets to new format to ensure consistency. Converted net is returned
    """
    from pandapower.std_types import add_basic_std_types, create_std_type, parameter_from_std_type
    from pandapower.run import reset_results
    if "std_types" not in net:
        net.std_types = {"line": {}, "trafo": {}, "trafo3w": {}}
        add_basic_std_types(net)

        import os
        import json
        path, file = os.path.split(os.path.realpath(__file__))
        linedb = os.path.join(path, "linetypes.json")
        if os.path.isfile(linedb):
            with open(linedb, 'r') as f:
                lt = json.load(f)
        else:
            lt = {}
        for std_type in net.line.std_type.unique():
            if std_type in lt:
                if "shift_degree" not in lt[std_type]:
                    lt[std_type]["shift_degree"] = 0
                create_std_type(net, lt[std_type], std_type, element="line")
        trafodb = os.path.join(path, "trafotypes.json")
        if os.path.isfile(trafodb):
            with open(trafodb, 'r') as f:
                tt = json.load(f)
        else:
            tt = {}
        for std_type in net.trafo.std_type.unique():
            if std_type in tt:
                create_std_type(net, tt[std_type], std_type, element="trafo")

    net.trafo.tp_side.replace(1, "hv", inplace=True)
    net.trafo.tp_side.replace(2, "lv", inplace=True)
    net.trafo.tp_side = net.trafo.tp_side.where(pd.notnull(net.trafo.tp_side),
                                                None)
    net.trafo3w.tp_side.replace(1, "hv", inplace=True)
    net.trafo3w.tp_side.replace(2, "mv", inplace=True)
    net.trafo3w.tp_side.replace(3, "lv", inplace=True)
    net.trafo3w.tp_side = net.trafo3w.tp_side.where(
        pd.notnull(net.trafo3w.tp_side), None)

    net["bus"] = net["bus"].rename(columns={
        'voltage_level': 'vn_kv',
        'bus_type': 'type',
        "un_kv": "vn_kv"
    })
    net["bus"]["type"].replace("s", "b", inplace=True)
    net["bus"]["type"].replace("k", "n", inplace=True)
    net["line"] = net["line"].rename(columns={'vf': 'df', 'line_type': 'type'})
    net["ext_grid"] = net["ext_grid"].rename(
        columns={
            "angle_degree": "va_degree",
            "ua_degree": "va_degree",
            "sk_max_mva": "s_sc_max_mva",
            "sk_min_mva": "s_sc_min_mva"
        })
    net["line"]["type"].replace("f", "ol", inplace=True)
    net["line"]["type"].replace("k", "cs", inplace=True)
    net["trafo"] = net["trafo"].rename(
        columns={
            'trafotype': 'std_type',
            "type": "std_type",
            "un1_kv": "vn_hv_kv",
            "un2_kv": "vn_lv_kv",
            'vfe_kw': 'pfe_kw',
            "unh_kv": "vn_hv_kv",
            "unl_kv": "vn_lv_kv",
            'trafotype': 'std_type',
            "type": "std_type",
            'vfe_kw': 'pfe_kw',
            "uk_percent": "vsc_percent",
            "ur_percent": "vscr_percent",
            "vnh_kv": "vn_hv_kv",
            "vnl_kv": "vn_lv_kv"
        })
    net["trafo3w"] = net["trafo3w"].rename(
        columns={
            "unh_kv": "vn_hv_kv",
            "unm_kv": "vn_mv_kv",
            "unl_kv": "vn_lv_kv",
            "ukh_percent": "vsc_hv_percent",
            "ukm_percent": "vsc_mv_percent",
            "ukl_percent": "vsc_lv_percent",
            "urh_percent": "vscr_hv_percent",
            "urm_percent": "vscr_mv_percent",
            "url_percent": "vscr_lv_percent",
            "vnh_kv": "vn_hv_kv",
            "vnm_kv": "vn_mv_kv",
            "vnl_kv": "vn_lv_kv",
            "snh_kv": "sn_hv_kv",
            "snm_kv": "sn_mv_kv",
            "snl_kv": "sn_lv_kv"
        })
    net["switch"]["type"].replace("LS", "CB", inplace=True)
    net["switch"]["type"].replace("LTS", "LBS", inplace=True)
    net["switch"]["type"].replace("TS", "DS", inplace=True)
    if "name" not in net.switch.columns:
        net.switch["name"] = None
    net["switch"] = net["switch"].rename(columns={'element_type': 'et'})
    net["ext_grid"] = net["ext_grid"].rename(
        columns={
            'voltage': 'vm_pu',
            "u_pu": "vm_pu",
            "sk_max": "sk_max_mva",
            "ua_degree": "va_degree"
        })
    if "in_service" not in net["ext_grid"].columns:
        net["ext_grid"]["in_service"] = 1
    if "shift_mv_degree" not in net["trafo3w"].columns:
        net["trafo3w"]["shift_mv_degree"] = 0
    if "shift_lv_degree" not in net["trafo3w"].columns:
        net["trafo3w"]["shift_lv_degree"] = 0
    parameter_from_std_type(net, "shift_degree", element="trafo", fill=0)
    if "gen" not in net:
        net["gen"] = pd.DataFrame(
            np.zeros(0,
                     dtype=[("name", np.dtype(object)), ("bus", "u4"),
                            ("p_kw", "f8"), ("vm_pu", "f8"), ("sn_kva", "f8"),
                            ("scaling", "f8"), ("in_service", "i8"),
                            ("min_q_kvar", "f8"), ("max_q_kvar", "f8"),
                            ("type", np.dtype(object))]))

    if "impedance" not in net:
        net["impedance"] = pd.DataFrame(
            np.zeros(0,
                     dtype=[("name", np.dtype(object)), ("from_bus", "u4"),
                            ("to_bus", "u4"), ("r_pu", "f8"), ("x_pu", "f8"),
                            ("sn_kva", "f8"), ("in_service", 'bool')]))
    if "ward" not in net:
        net["ward"] = pd.DataFrame(
            np.zeros(0,
                     dtype=[("name", np.dtype(object)), ("bus", "u4"),
                            ("ps_kw", "u4"), ("qs_kvar", "f8"),
                            ("pz_kw", "f8"), ("qz_kvar", "f8"),
                            ("in_service", "f8")]))
    if "xward" not in net:
        net["xward"] = pd.DataFrame(
            np.zeros(0,
                     dtype=[("name", np.dtype(object)), ("bus", "u4"),
                            ("ps_kw", "u4"),
                            ("qs_kvar", "f8"), ("pz_kw", "f8"),
                            ("qz_kvar", "f8"), ("r_ohm", "f8"),
                            ("x_ohm", "f8"), ("vm_pu", "f8"),
                            ("in_service", "f8")]))
    if "shunt" not in net:
        net["shunt"] = pd.DataFrame(
            np.zeros(0,
                     dtype=[("bus", "u4"), ("name", np.dtype(object)),
                            ("p_kw", "f8"), ("q_kvar", "f8"),
                            ("scaling", "f8"), ("in_service", "i8")]))

    if "parallel" not in net.line:
        net.line["parallel"] = 1
    if "_empty_res_bus" not in net:
        net2 = create_empty_network()
        for key, item in net2.items():
            if key.startswith("_empty"):
                net[key] = copy.copy(item)
        reset_results(net)

    for attribute in ['tp_st_percent', 'tp_pos', 'tp_mid', 'tp_min', 'tp_max']:
        if net.trafo[attribute].dtype == 'O':
            net.trafo[attribute] = pd.to_numeric(net.trafo[attribute])
    net["gen"] = net["gen"].rename(columns={"u_pu": "vm_pu"})
    for element, old, new in [("trafo", "unh_kv", "vn_hv_kv"),
                              ("trafo", "unl_kv", "vn_lv_kv"),
                              ("trafo", "uk_percent", "vsc_percent"),
                              ("trafo", "ur_percent", "vscr_percent"),
                              ("trafo3w", "unh_kv", "vn_hv_kv"),
                              ("trafo3w", "unm_kv", "vn_mv_kv"),
                              ("trafo3w", "unl_kv", "vn_lv_kv")]:
        for std_type, parameters in net.std_types[element].items():
            if old in parameters:
                net.std_types[element][std_type][new] = net.std_types[element][
                    std_type].pop(old)
    net.version = 1.0
    if "f_hz" not in net:
        net["f_hz"] = 50.

    if "type" not in net.load.columns:
        net.load["type"] = None
    if "zone" not in net.bus:
        net.bus["zone"] = None
    for element in ["line", "trafo", "bus", "load", "sgen", "ext_grid"]:
        net[element].in_service = net[element].in_service.astype(bool)
    net.switch.closed = net.switch.closed.astype(bool)
    return net
Ejemplo n.º 18
0
def from_json_string(json_string,
                     convert=False,
                     encryption_key=None,
                     elements_to_deserialize=None,
                     keep_serialized_elements=True):
    """
    Load a pandapower network from a JSON string.
    The index of the returned network is not necessarily in the same order as the original network.
    Index columns of all pandas DataFrames are sorted in ascending order.

    INPUT:
        **json_string** (string) - The json string representation of the network

        **convert** (bool, False) - If True, converts the format of the net loaded from json_string
        from the older version of pandapower to the newer version format

        **encrytion_key** (string, "") - If given, key to decrypt an encrypted json_string

        **elements_to_deserialize** (list, None) - Deserialize only certain pandapower elements.
            If None all elements are deserialized.

        **keep_serialized_elements** (bool, True) - Keep serialized elements if given.
            Default: Serialized elements are kept.

    OUTPUT:
        **net** (dict) - The pandapower format network

    EXAMPLE:

        >>> net = pp.from_json_string(json_str)

    """
    if encryption_key is not None:
        json_string = io_utils.decrypt_string(json_string, encryption_key)

    if elements_to_deserialize is None:
        net = json.loads(json_string, cls=io_utils.PPJSONDecoder)
    else:
        net = json.loads(json_string,
                         cls=io_utils.PPJSONDecoder,
                         deserialize_pandas=False)
        net_dummy = create_empty_network()
        if ('version' not in net.keys()) | (version.parse(net.version) <
                                            version.parse('2.1.0')):
            raise UserWarning(
                'table selection is only possible for nets above version 2.0.1. '
                'Convert and save your net first.')
        if keep_serialized_elements:
            for key in elements_to_deserialize:
                net[key] = json.loads(net[key], cls=io_utils.PPJSONDecoder)
        else:
            if (('version' not in net.keys()) or (net['version'] != net_dummy.version)) and \
                    not convert:
                raise UserWarning(
                    'The version of your net %s you are trying to load differs from the actual '
                    'pandapower version %s. Before you can load only distinct tables, convert '
                    'and save your net first or set convert to True!' %
                    (net['version'], net_dummy.version))
            for key in net.keys():
                if key in elements_to_deserialize:
                    net[key] = json.loads(net[key], cls=io_utils.PPJSONDecoder)
                elif not isinstance(net[key], str):
                    continue
                elif 'pandas' in net[key]:
                    net[key] = net_dummy[key]

    # this can be removed in the future
    # now net is saved with "_module", "_class", "_object"..., so json.load already returns
    # pandapowerNet. Older files don't have it yet, and are loaded as dict.
    # After some time, this part can be removed.
    if not isinstance(net, pandapowerNet):
        warn(
            "This net is saved in older format, which will not be supported in future.\r\n"
            "Please resave your grid using the current pandapower version.",
            DeprecationWarning)
        net = from_json_dict(net)

    if convert:
        convert_format(net, elements_to_deserialize=elements_to_deserialize)
    return net
Ejemplo n.º 19
0
def select_subnet(net,
                  buses,
                  include_switch_buses=False,
                  include_results=False,
                  keep_everything_else=False):
    """
    Selects a subnet by a list of bus indices and returns a net with all elements
    connected to them.
    """
    buses = set(buses)
    if include_switch_buses:
        # we add both buses of a connected line, the one selected is not switch.bus

        # for all line switches
        for _, s in net["switch"].query("et=='l'").iterrows():
            # get from/to-bus of the connected line
            fb = net["line"]["from_bus"].at[s["element"]]
            tb = net["line"]["to_bus"].at[s["element"]]
            # if one bus of the line is selected and its not the switch-bus, add the other bus
            if fb in buses and s["bus"] != fb:
                buses.add(tb)
            if tb in buses and s["bus"] != tb:
                buses.add(fb)

    p2 = create_empty_network()

    p2.bus = net.bus.loc[buses]
    p2.ext_grid = net.ext_grid[net.ext_grid.bus.isin(buses)]
    p2.load = net.load[net.load.bus.isin(buses)]
    p2.sgen = net.sgen[net.sgen.bus.isin(buses)]
    p2.gen = net.gen[net.gen.bus.isin(buses)]
    p2.shunt = net.shunt[net.shunt.bus.isin(buses)]
    p2.ward = net.ward[net.ward.bus.isin(buses)]
    p2.xward = net.xward[net.xward.bus.isin(buses)]

    p2.line = net.line[(net.line.from_bus.isin(buses))
                       & (net.line.to_bus.isin(buses))]
    p2.trafo = net.trafo[(net.trafo.hv_bus.isin(buses))
                         & (net.trafo.lv_bus.isin(buses))]
    p2.impedance = net.impedance[(net.impedance.from_bus.isin(buses))
                                 & (net.impedance.to_bus.isin(buses))]

    if include_results:
        for table in net.keys():
            if net[table] is None:
                continue
            elif table == "res_bus":
                p2[table] = net[table].loc[buses]
            elif table.startswith("res_"):
                p2[table] = net[table].loc[p2[table.split("res_")[1]].index]
    if "bus_geodata" in net:
        p2["bus_geodata"] = net["bus_geodata"].loc[
            net["bus_geodata"].index.isin(buses)]
    if "line_geodata" in net:
        lines = p2.line.index
        p2["line_geodata"] = net["line_geodata"].loc[
            net["line_geodata"].index.isin(lines)]

    # switches
    si = [
        i for i, s in net["switch"].iterrows() if s["bus"] in buses and (
            (s["et"] == "b" and s["element"] in p2["bus"].index) or
            (s["et"] == "l" and s["element"] in p2["line"].index) or
            (s["et"] == "t" and s["element"] in p2["trafo"].index))
    ]
    p2["switch"] = net["switch"].loc[si]
    # return a PandapowerNet
    if keep_everything_else:
        newnet = copy.deepcopy(net)
        newnet.update(p2)
        return PandapowerNet(newnet)
    return PandapowerNet(p2)
Ejemplo n.º 20
0
 def __init__(self, **kwargs):
     # net = pandapowerNet.__new__(pandapowerNet)
     net = create_empty_network()
     super_kwargs = {"object_hook": partial(pp_hook, net=net)}
     super_kwargs.update(kwargs)
     super().__init__(**super_kwargs)