Exemplo n.º 1
0
 def test_scenario_transmisson_error(self):
     old_value = cfg.get("transmission", "general_efficiency")
     cfg.tmp_set("transmission", "general_efficiency", "None")
     msg = "The calculation of the efficiency by distance is not yet"
     with assert_raises_regexp(NotImplementedError, msg):
         basic_scenario.scenario_transmission(self.pp, self.regions, "de22")
     cfg.tmp_set("transmission", "general_efficiency", old_value)
Exemplo n.º 2
0
def test_scenario_creation_main():
    sc = scenario_tools.DeflexScenario(name="test", year=2014)
    csv_path = os.path.join(os.path.dirname(__file__), "data",
                            "deflex_2014_de21_test_csv")
    sc.load_csv(csv_path)
    basic_scenario.create_scenario = MagicMock(
        return_value=sc.table_collection)
    cfg.tmp_set(
        "paths",
        "scenario",
        os.path.join(os.path.expanduser("~"), "deflex_tmp_test_dir"),
    )

    fn = basic_scenario.create_basic_scenario(2014, "de21", only_out="csv")
    ok_(fn.xls is None)
    eq_(fn.csv[-52:], "deflex_tmp_test_dir/deflex/2014/deflex_2014_de21_csv")

    fn = basic_scenario.create_basic_scenario(2014, "de21", only_out="xls")
    ok_(fn.csv is None)
    eq_(fn.xls[-52:], "deflex_tmp_test_dir/deflex/2014/deflex_2014_de21.xls")

    fn = basic_scenario.create_basic_scenario(2014,
                                              "de21",
                                              csv_dir="fancy_csv",
                                              xls_name="fancy.xls")
    eq_(fn.xls[-41:], "deflex_tmp_test_dir/deflex/2014/fancy.xls")
    eq_(fn.csv[-41:], "deflex_tmp_test_dir/deflex/2014/fancy_csv")
Exemplo n.º 3
0
def scenario_feedin_test():
    """Test scenario feed-in."""
    cfg.tmp_set("init", "map", "de21")
    regions = geometries.deflex_regions(rmap="de21")
    f = basic_scenario.scenario_feedin(regions, 2014, "de21")
    eq_(int(f["DE01"].sum()["wind"]), 2159)
    eq_(int(f["DE01"].sum()["solar"]), 913)
    eq_(int(f["DE16"].sum()["wind"]), 1753)
Exemplo n.º 4
0
def test_03_not_existing_file():
    old_value = cfg.get("paths", "powerplants")
    cfg.tmp_set("paths", "powerplants", "/home/pet/")
    de = geometries.deflex_regions("de22")
    powerplants.pp_reegis2deflex = MagicMock(return_value="/home/pet/pp.h5")

    with assert_raises_regexp(
        Exception, "File /home/pet/pp.h5 does not exist"
    ):
        powerplants.get_deflex_pp_by_year(de, 2012, "de22")
    cfg.tmp_set("paths", "powerplants", old_value)
Exemplo n.º 5
0
def test_set_temp_value():
    files = [
        os.path.join(os.path.dirname(__file__), "data", "config_test.ini")
    ]
    config.init(files=files)
    with pytest.raises(
        NoOptionError, match="No option 'blubb' in section: 'type_tester'"
    ):
        config.get("type_tester", "blubb")
    config.tmp_set("type_tester", "blubb", "None")
    assert config.get("type_tester", "blubb") is None
    config.tmp_set("type_tester", "blubb", "5.5")
    assert config.get("type_tester", "blubb") == 5.5
Exemplo n.º 6
0
def main(year, rmap, csv=True, es=None, plot_graph=False, extra_regions=None):
    """

    Parameters
    ----------
    year : int
        Year of an existing  basic scenario.
    rmap : str
        A valid deflex map id (de02, de17, de21, de22) of an existing scenario.
    csv : bool
        Use csv collection. If set to False the xls-file is used.
    es : oemof.solph.EnergySystem
        A valid energy system if needed.
    plot_graph : bool
        Set to True to plot the energy system.
    extra_regions : list
        Use separate resource buses for these regions.

    Returns
    -------

    Examples
    --------
    >>> main(2014, 'de21')  # doctest: +SKIP
    """
    stopwatch()
    cfg.tmp_set("init", "map", rmap)
    name = "{0}_{1}_{2}".format("deflex", year, cfg.get("init", "map"))

    path = os.path.join(cfg.get("paths", "scenario"), "deflex", str(year))

    if csv is True:
        csv_dir = name + "_csv"
        csv_path = os.path.join(path, csv_dir)
        excel_path = None
    else:
        excel_path = os.path.join(path, name + ".xls")
        csv_path = None

    model_scenario(
        xls_file=excel_path,
        csv_path=csv_path,
        res_path=path,
        name=name,
        rmap=rmap,
        year=year,
        es=es,
        plot_graph=plot_graph,
        extra_regions=extra_regions,
    )
Exemplo n.º 7
0
    def setup_class(cls):
        path = os.path.join(TEST_PATH, "de22_heat_transmission_csv")
        sc = st.DeflexScenario()
        sc.read_csv(path)
        cls.tables = sc.input_data
        tmp_tables = {}
        parameter = {
            "costs_source": "ewi",
            "downtime_bioenergy": 0.1,
            "limited_transformer": "bioenergy",
            "local_fuels": "district heating",
            "map": "de22",
            "mobility_other": "petrol",
            "round": 1,
            "separate_heat_regions": "de22",
            "copperplate": False,
            "default_transmission_efficiency": 0.9,
            "group_transformer": False,
            "heat": True,
            "use_CO2_costs": True,
            "use_downtime_factor": True,
            "use_variable_costs": False,
            "year": 2014,
        }
        config.init(paths=[os.path.dirname(dfile)])
        for option, value in parameter.items():
            cfg.tmp_set("creator", option, str(value))
            config.tmp_set("creator", option, str(value))

        name = "heat_demand_deflex"
        fn = os.path.join(os.path.dirname(__file__), "data", name + ".csv")
        tmp_tables[name] = pd.read_csv(fn, index_col=[0], header=[0, 1])

        name = "transformer_balance"
        fn = os.path.join(os.path.dirname(__file__), "data", name + ".csv")
        tmp_tables[name] = pd.read_csv(fn, index_col=[0, 1, 2], header=[0])

        powerplants.scenario_powerplants = MagicMock(
            return_value={
                "volatile plants": cls.tables["volatile plants"],
                "power plants": cls.tables["power plants"],
            })

        powerplants.scenario_chp = MagicMock(
            return_value={
                "heat-chp plants": cls.tables["heat-chp plants"],
                "power plants": cls.tables["power plants"],
            })

        feedin.scenario_feedin = MagicMock(
            return_value=cls.tables["volatile series"])

        demand_table = {
            "electricity demand series":
            cls.tables["electricity demand series"],
            "heat demand series": cls.tables["heat demand series"],
        }
        demand.scenario_demand = MagicMock(return_value=demand_table)

        name = "deflex_2014_de22_heat_transmission"

        polygons = deflex_regions(rmap=parameter["map"], rtype="polygons")
        lines = deflex_power_lines(parameter["map"]).index
        cls.input_data = scenario_creator.create_scenario(
            polygons, 2014, name, lines)
Exemplo n.º 8
0
 def setUpClass(cls):
     cls.date_time_index = pd.date_range("1/1/2014", periods=30, freq="H")
     cls.es = solph.EnergySystem(timeindex=cls.date_time_index)
     cls.base_path = os.path.join(os.path.dirname(__file__), "data")
     cfg.tmp_set("paths", "scenario", cls.base_path)
Exemplo n.º 9
0
def create_basic_scenario(
    year,
    rmap=None,
    path=None,
    csv_dir=None,
    xls_name=None,
    round_values=None,
    only_out=None,
):
    """
    Create a basic scenario for a given year and region-set and store it into
    an excel-file or csv-collection.

    Parameters
    ----------
    year : int
    rmap : str
    path : str
    csv_dir : str
    xls_name : str
    round_values : bool
    only_out : str

    Returns
    -------
    namedtuple : Path

    Examples
    --------
    >>> year=2014  # doctest: +SKIP
    >>> my_rmap='de21'  # doctest: +SKIP
    >>> p=create_basic_scenario(year, rmap=my_rmap)  # doctest: +SKIP
    >>> print("Xls path: {0}".format(p.xls))  # doctest: +SKIP
    >>> print("Csv path: {0}".format(p.csv))  # doctest: +SKIP

    """
    paths = namedtuple("paths", "xls, csv")
    if rmap is not None:
        cfg.tmp_set("init", "map", rmap)
    name = cfg.get("init", "map")
    regions = geometries.deflex_regions(rmap=cfg.get("init", "map"))

    table_collection = create_scenario(regions, year, name, round_values)
    table_collection = clean_time_series(table_collection)
    name = "{0}_{1}_{2}".format("deflex", year, cfg.get("init", "map"))
    sce = scenario_tools.Scenario(table_collection=table_collection,
                                  name=name,
                                  year=year)

    if path is None:
        path = os.path.join(cfg.get("paths", "scenario"), "deflex", str(year))

    if only_out == "xls":
        csv_path = None
    elif csv_dir is None:
        csv_path = os.path.join(path, "{0}_csv".format(name))
    else:
        csv_path = os.path.join(path, csv_dir)

    if only_out == "csv":
        xls_path = None
    elif xls_name is None:
        xls_path = os.path.join(path, name + ".xls")
    else:
        xls_path = os.path.join(path, xls_name)

    fullpath = paths(xls=xls_path, csv=csv_path)
    if not only_out == "csv":
        os.makedirs(path, exist_ok=True)
        sce.to_excel(fullpath.xls)
    if not only_out == "xls":
        os.makedirs(csv_path, exist_ok=True)
        sce.to_csv(fullpath.csv)

    return fullpath
Exemplo n.º 10
0
def create_basic_reegis_scenario(
    name,
    regions,
    parameter,
    lines=None,
    csv_path=None,
    excel_path=None,
):
    """
    Create a basic scenario for a given year and region-set.

    Parameters
    ----------
    name : str
        Name of the scenario
    regions : geopandas.geoDataFrame
        Set of region polygons.
    lines : geopandas.geoDataFrame
        Set of transmission lines.
    parameter : dict
        Parameter set for the creation process. Some parameters will have a
        default value. For the default values see below.
    csv_path : str
        A directory to store the scenario as csv collection. If None no csv
        collection will be created. Either csv_path or excel_path must not be
        'None'.
    excel_path : str
        A file to store the scenario as an excel map. If None no excel file
        will be created. Both suffixes 'xls' or 'xlsx' are possible. The excel
        format can be used in most spreadsheet programs such as LibreOffice or
        Gnumeric. Either csv_path or excel_path must not be 'None'.

    Returns
    -------
    namedtuple : Path

    Notes
    -----

    List of default values:

        * copperplate: True
        * default_transmission_efficiency: 0.9
        * costs_source: "ewi"
        * downtime_bioenergy: 0.1
        * group_transformer: False
        * heat: False
        * limited_transformer: "bioenergy",
        * local_fuels: "district heating",
        * map: "de02",
        * mobility_other: "petrol",
        * round: 1,
        * separate_heat_regions: "de22",
        * use_CO2_costs: False,
        * use_downtime_factor: True,
        * use_variable_costs: False,
        * year: 2014

    Examples
    --------
    >>> from oemof.tools import logger
    >>> from deflex.geometries import deflex_power_lines
    >>> from deflex.geometries import deflex_regions
    >>>
    >>> logger.define_logging(screen_level=logging.DEBUG)  # doctest: +SKIP
    >>>
    >>> my_parameter = {
    ...     "year": 2014,
    ...     "map": "de02",
    ...     "copperplate": True,
    ...     "heat": True,
    ... }
    >>>
    >>> my_name = "deflex"
    >>> for k, v in my_parameter.items():
    ...     my_name += "_" + str(k) + "-" + str(v)
    >>>
    >>> polygons = deflex_regions(rmap=my_parameter["map"], rtype="polygons")
    >>> my_lines = deflex_power_lines(my_parameter["map"]).index
    >>> path = "/my/path/creator/{0}{1}".format(my_name, "{0}")
    >>>
    >>> create_basic_reegis_scenario(
    ...     name=my_name,
    ...     regions=polygons,
    ...     lines=my_lines,
    ...     parameter=my_parameter,
    ...     excel_path=path.format(".xlsx"),
    ...     csv_path=path.format("_csv"),
    ... )  # doctest: +SKIP
    """
    # The default parameter can be found in "creator.ini".

    config.init(paths=[os.path.dirname(dfile)])
    for option, value in parameter.items():
        cfg.tmp_set("creator", option, str(value))
        config.tmp_set("creator", option, str(value))

    year = cfg.get("creator", "year")

    configuration = json.dumps(cfg.get_dict("creator"),
                               indent=4,
                               sort_keys=True)

    logging.info(
        "The following configuration is used to build the scenario:"
        " %s",
        configuration,
    )
    paths = namedtuple("paths", "xls, csv")

    table_collection = create_scenario(regions, year, name, lines)

    table_collection = clean_time_series(table_collection)

    name = table_collection["general"].get("name")
    sce = scenario.Scenario(input_data=table_collection, name=name, year=year)

    if csv_path is not None:
        os.makedirs(csv_path, exist_ok=True)
        sce.to_csv(csv_path)
    if excel_path is not None:
        os.makedirs(os.path.dirname(excel_path), exist_ok=True)
        sce.to_xlsx(excel_path)

    return paths(xls=excel_path, csv=csv_path)
Exemplo n.º 11
0
def test_set_temp_without_init():
    config.tmp_set("type_tester", "blubb", "None")