Beispiel #1
0
def from_pickle(filename, convert=True):
    """
    Load a pandapower format Network from pickle file

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

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

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

    EXAMPLE:

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

    """

    net = pandapowerNet(io_utils.get_raw_data_from_pickle(filename))
    io_utils.transform_net_with_df_and_geo(net, ["bus_geodata"],
                                           ["line_geodata"])

    if convert:
        convert_format(net)
    return net
Beispiel #2
0
def test_convert_format():
    """ Testing a very simple network without transformer for voltage
    constraints with OPF """

    # boundaries:
    vm_max = 1.05
    vm_min = 0.95

    # create net
    net = pp.create_empty_network()
    pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10.)
    pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4)
    pp.create_gen(net, 1, p_mw=0.1, controllable=True, min_p_mw=0.005, max_p_mw=0.15,
                  max_q_mvar=0.05, min_q_mvar=-0.005)
    net.gen["cost_per_mw"] = 100
    pp.create_ext_grid(net, 0)
    pp.create_load(net, 1, p_mw=0.02, controllable=False)
    pp.create_line_from_parameters(net, 0, 1, 50, name="line2", r_ohm_per_km=0.876,
                                   c_nf_per_km=260.0, max_i_ka=0.123, x_ohm_per_km=0.1159876,
                                   max_loading_percent=100 * 690)
    # run OPF
    convert_format(net)
    for init in ["pf", "flat"]:
        pp.runopp(net, init=init)
        assert net["OPF_converged"]

    # check and assert result
    logger.debug("test_simplest_voltage")
    logger.debug("res_gen:\n%s" % net.res_gen)
    logger.debug("res_ext_grid:\n%s" % net.res_ext_grid)
    logger.debug("res_bus.vm_pu: \n%s" % net.res_bus.vm_pu)
    assert max(net.res_bus.vm_pu) < vm_max
    assert min(net.res_bus.vm_pu) > vm_min
Beispiel #3
0
def from_json_string(json_string, convert=False):
    """
    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

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

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

    EXAMPLE:

        >>> net = pp.from_json_string(json_str)

    """
    data = json.loads(json_string, cls=PPJSONDecoder)
    net = from_json_dict(data)

    if convert:
        convert_format(net)
    return net
Beispiel #4
0
def from_json_string(json_string, convert=False):
    """
    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

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

    EXAMPLE:

        >>> net = pp.from_json_string(json_str)

    """
    net = json.loads(json_string, cls=PPJSONDecoder)
    # 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)
    return net
Beispiel #5
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.

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

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

    EXAMPLE:

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

    """

    if not os.path.isfile(filename):
        raise UserWarning("File %s does not exist!" % filename)
    pd_version = version.parse(pd.__version__)
    if pd_version < version.parse("0.21"):
        xls = pd.ExcelFile(filename).parse(sheetname=None)
    elif pd_version < version.parse("0.24"):
        xls = pd.ExcelFile(filename).parse(sheet_name=None)
    else:
        if not openpyxl_INSTALLED:
            soft_dependency_error(
                str(sys._getframe().f_code.co_name) + "()", "openpyxl")
        xls = pd.read_excel(filename,
                            sheet_name=None,
                            index_col=0,
                            engine="openpyxl")

    try:
        net = io_utils.from_dict_of_dfs(xls)
    except:
        net = _from_excel_old(xls)
    if convert:
        convert_format(net)
    return net
Beispiel #6
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 or file) - The absolute or relative path to the input file or file-like object

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

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

    EXAMPLE:

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

    """
    if hasattr(filename, 'read'):
        net = json.load(filename, cls=PPJSONDecoder)
    elif not os.path.isfile(filename):
        raise UserWarning("File {} does not exist!!".format(filename))
    else:
        with open(filename) as fp:
            net = json.load(fp, cls=PPJSONDecoder)
            # 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)
    return net
Beispiel #7
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

    """

    if not os.path.isfile(filename):
        raise UserWarning("File %s does not exist!" % filename)
    pd_version = version.parse(pd.__version__)
    if pd_version < version.parse("0.21"):
        xls = pd.ExcelFile(filename).parse(sheetname=None)
    elif pd_version < version.parse("0.24"):
        xls = pd.ExcelFile(filename).parse(sheet_name=None)
    else:
        xls = pd.ExcelFile(filename).parse(sheet_name=None, index_col=0)

    try:
        net = from_dict_of_dfs(xls)
    except:
        net = _from_excel_old(xls)
    if convert:
        convert_format(net)
    return net
Beispiel #8
0
def from_pickle(filename, convert=True):
    """
    Load a pandapower format Network from pickle file

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

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

    EXAMPLE:

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

    """

    def read(f):
        if sys.version_info >= (3, 0):
            return pickle.load(f, encoding='latin1')
        else:
            return pickle.load(f)

    if hasattr(filename, 'read'):
        net = read(filename)
    elif not os.path.isfile(filename):
        raise UserWarning("File %s does not exist!!" % filename)
    else:
        with open(filename, "rb") as f:
            net = read(f)
    net = pandapowerNet(net)

    try:
        epsg = net.gis_epsg_code
    except AttributeError:
        epsg = None

    for key, item in net.items():
        if isinstance(item, dict) and "DF" in item:
            df_dict = item["DF"]
            if "columns" in df_dict:
                # make sure the index is Int64Index
                try:
                    df_index = pd.Int64Index(df_dict['index'])
                except TypeError:
                    df_index = df_dict['index']
                if GEOPANDAS_INSTALLED and "geometry" in df_dict["columns"] \
                        and epsg is not None:
                    # convert primitive data-types to shapely-objects
                    if key == "bus_geodata":
                        data = {"x": [row[0] for row in df_dict["data"]],
                                "y": [row[1] for row in df_dict["data"]]}
                        geo = [Point(row[2][0], row[2][1]) for row in df_dict["data"]]
                    elif key == "line_geodata":
                        data = {"coords": [row[0] for row in df_dict["data"]]}
                        geo = [LineString(row[1]) for row in df_dict["data"]]

                    net[key] = GeoDataFrame(data, crs=from_epsg(epsg), geometry=geo,
                                            index=df_index)
                else:
                    net[key] = pd.DataFrame(columns=df_dict["columns"], index=df_index,
                                            data=df_dict["data"])
            else:
                net[key] = pd.DataFrame.from_dict(df_dict)
                if "columns" in item:
                    if version.parse(pd.__version__) < version.parse("0.21"):
                        net[key] = net[key].reindex_axis(item["columns"], axis=1)
                    else:
                        net[key] = net[key].reindex(item["columns"], axis=1)

            if "dtypes" in item:
                if "columns" in df_dict and "geometry" in df_dict["columns"]:
                    pass
                else:
                    try:
                        # only works with pandas 0.19 or newer
                        net[key] = net[key].astype(item["dtypes"])
                    except:
                        # works with pandas <0.19
                        for column in net[key].columns:
                            net[key][column] = net[key][column].astype(item["dtypes"][column])
    if convert:
        convert_format(net)
    return net
Beispiel #9
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