Beispiel #1
0
def make_dantzig(mp: Platform,
                 solve: bool = False,
                 quiet: bool = False) -> Scenario:
    """Return :class:`ixmp.Scenario` of Dantzig's canning/transport problem.

    Parameters
    ----------
    mp : .Platform
        Platform on which to create the scenario.
    solve : bool, optional
        If :obj:`True`. then solve the scenario before returning. Default :obj:`False`.
    quiet : bool, optional
        If :obj:`True`, suppress console output when solving.

    Returns
    -------
    .Scenario

    See also
    --------
    .DantzigModel
    """
    # add custom units and region for timeseries data
    try:
        mp.add_unit("USD/km")
    except Exception:
        # Unit already exists. Pending bugfix from zikolach
        pass
    mp.add_region("DantzigLand", "country")

    # Initialize a new Scenario, and use the DantzigModel class' initialize()
    # method to populate it
    annot = "Dantzig's transportation problem for illustration and testing"
    scen = Scenario(
        mp,
        **models["dantzig"],  # type: ignore [arg-type]
        version="new",
        annotation=annot,
        scheme="dantzig",
        with_data=True,
    )

    # commit the scenario
    scen.commit("Import Dantzig's transport problem for testing.")

    # set this new scenario as the default version for the model/scenario name
    scen.set_as_default()

    if solve:
        # Solve the model using the GAMS code provided in the `tests` folder
        scen.solve(model="dantzig", case="transport_standard", quiet=quiet)

    # add timeseries data for testing `clone(keep_solution=False)`
    # and `remove_solution()`
    scen.check_out(timeseries_only=True)
    scen.add_timeseries(HIST_DF, meta=True)
    scen.add_timeseries(INP_DF)
    scen.commit("Import Dantzig's transport problem for testing.")

    return scen
Beispiel #2
0
def test_timeseries_remove_single_entry(mp):
    args_single = ('Douglas Adams', 'test_remove_single')

    scen = Scenario(mp, *args_single, version='new', annotation='fo')
    scen.add_timeseries(DATA['timeseries'].pivot_table(values='value',
                                                       index=IDX_COLS))
    scen.commit('importing a testing timeseries')

    scen = Scenario(mp, *args_single)
    assert_timeseries(scen, DATA['timeseries'])

    scen.check_out()
    scen.remove_timeseries(DATA['timeseries'][DATA['timeseries'].year == 2010])
    scen.commit('testing for removing a single timeseries data point')

    exp = DATA['timeseries'][DATA['timeseries'].year == 2020]
    assert_timeseries(scen, exp)
Beispiel #3
0
def test_timeseries_remove_single_entry(mp):
    args_single = ("Douglas Adams", "test_remove_single")

    scen = Scenario(mp, *args_single, version="new", annotation="fo")
    scen.add_timeseries(DATA["timeseries"].pivot_table(values="value",
                                                       index=IDX_COLS))
    scen.commit("importing a testing timeseries")

    scen = Scenario(mp, *args_single)
    assert_timeseries(scen, DATA["timeseries"])

    scen.check_out()
    scen.remove_timeseries(DATA["timeseries"][DATA["timeseries"].year == 2010])
    scen.commit("testing for removing a single timeseries data point")

    exp = DATA["timeseries"][DATA["timeseries"].year == 2020]
    assert_timeseries(scen, exp)
Beispiel #4
0
def test_timeseries_remove_all_data(mp):
    args_all = ('Douglas Adams', 'test_remove_all')

    scen = Scenario(mp, *args_all, version='new', annotation='fo')
    scen.add_timeseries(DATA['timeseries'].pivot_table(values='value',
                                                       index=IDX_COLS))
    scen.commit('importing a testing timeseries')

    scen = Scenario(mp, *args_all)
    assert_timeseries(scen, DATA['timeseries'])

    exp = DATA['timeseries'].copy()
    exp['variable'] = 'Testing2'

    scen.check_out()
    scen.add_timeseries(exp)
    scen.remove_timeseries(DATA['timeseries'])
    scen.commit('testing for removing a full timeseries row')

    assert scen.timeseries(region='World', variable='Testing').empty
    assert_timeseries(scen, exp)
Beispiel #5
0
def test_timeseries_remove_all_data(mp):
    args_all = ("Douglas Adams", "test_remove_all")

    scen = Scenario(mp, *args_all, version="new", annotation="fo")
    scen.add_timeseries(DATA["timeseries"].pivot_table(values="value",
                                                       index=IDX_COLS))
    scen.commit("importing a testing timeseries")

    scen = Scenario(mp, *args_all)
    assert_timeseries(scen, DATA["timeseries"])

    exp = DATA["timeseries"].copy()
    exp["variable"] = "Testing2"

    scen.check_out()
    scen.add_timeseries(exp)
    scen.remove_timeseries(DATA["timeseries"])
    scen.commit("testing for removing a full timeseries row")

    assert scen.timeseries(region="World", variable="Testing").empty
    assert_timeseries(scen, exp)
Beispiel #6
0
def test_store_ts(request, caplog, test_mp):
    # Computer and target scenario
    c = Computer()

    # Target scenario
    model_name = __name__
    scenario_name = "test scenario"
    scen = Scenario(test_mp, model_name, scenario_name, version="new")
    scen.commit("Empty scenario")
    c.add("target", scen)

    # Add test data to the Computer: a pd.DataFrame
    input_1 = test_data[0].assign(variable="Foo")
    c.add("input 1", input_1)

    # A pyam.IamDataFrame
    input_2 = test_data[2050].assign(variable="Bar")
    c.add("input 2", pyam.IamDataFrame(input_2))

    # Expected results: same as input, but with the `model` and `scenario` columns
    # filled automatically.
    expected_1 = input_1.assign(model=model_name, scenario=scenario_name)
    expected_2 = input_2.assign(model=model_name, scenario=scenario_name)

    # Task to update the scenario with the data
    c.add("test 1", store_ts, "target", "input 1", "input 2")

    # Scenario starts empty of time series data
    assert 0 == len(scen.timeseries())

    # The computation runs successfully
    c.get("test 1")

    # All rows from both inputs are present
    assert len(input_1) + len(input_2) == len(scen.timeseries())

    # Input is stored exactly
    assert_frame_equal(expected_1, scen.timeseries(variable="Foo"))
    assert_frame_equal(expected_2, scen.timeseries(variable="Bar"))
Beispiel #7
0
    def test_error_message(self, test_data_path, test_mp):
        """GAMSModel.solve() displays a user-friendly message on error."""
        # Empty Scenario
        s = Scenario(test_mp, model="foo", scenario="bar", version="new")
        s.commit("Initial commit")

        # Expected paths for error message
        paths = map(
            lambda name: re.escape(str(test_data_path.joinpath(name))),
            ["_abort.lst", "default_in.gdx"],
        )

        with pytest.raises(
                ModelError,
                match="""GAMS errored with return code 2:
    There was a compilation error

For details, see the terminal output above, plus:
Listing   : {}
Input data: {}""".format(*paths),
        ):
            s.solve(model_file=test_data_path / "_abort.gms",
                    use_temp_dir=False)