Example #1
0
def model():
    m = Model()
    lower = xr.DataArray(np.zeros((10, 10)), coords=[range(10), range(10)])
    upper = xr.DataArray(np.ones((10, 10)), coords=[range(10), range(10)])
    m.add_variables(lower, upper, name="x")
    m.add_variables(lower, upper, name="y")
    return m
Example #2
0
def test_constraint_repr():
    m = Model()

    x = m.add_variables()
    c = m.add_constraints(x, ">=", 0)
    c.__repr__()
    c._repr_html_()
Example #3
0
def test_variable_modification():
    m = Model()
    x = m.add_variables(0, 10)
    x.upper = 20
    assert x.upper.item() == 20

    x.lower = 8
    assert x.lower == 8
Example #4
0
def test_str_arrays_chunked():
    m = Model(chunk="auto")

    x = m.add_variables(4, pd.Series([8, 10]))
    y = m.add_variables(0, pd.DataFrame([[1, 2], [3, 4], [5, 6]]).T)

    da = int_to_str(y.compute().values)
    assert da.dtype == object
Example #5
0
def test_str_arrays():
    m = Model()

    x = m.add_variables(4, pd.Series([8, 10]))
    y = m.add_variables(0, pd.DataFrame([[1, 2], [3, 4], [5, 6]]).T)

    da = int_to_str(x.values)
    assert da.dtype == object
Example #6
0
def test_variable_sanitize():
    m = Model()
    x = m.add_variables(coords=[range(10)])
    # convert intentionally to float with nans
    x = x.where([True] * 4 + [False] * 6, np.nan)
    x = x.sanitize()
    assert isinstance(x, linopy.variables.Variable)
    assert x.loc[9].item() == -1
Example #7
0
def test_variable_type_preservation():
    m = Model()
    x = m.add_variables(coords=[range(10)])

    assert isinstance(x.bfill("dim_0"), linopy.variables.Variable)
    assert isinstance(x.broadcast_like(x.to_array()),
                      linopy.variables.Variable)
    assert isinstance(x.clip(max=20), linopy.variables.Variable)
    assert isinstance(x.ffill("dim_0"), linopy.variables.Variable)
    assert isinstance(x.fillna(-1), linopy.variables.Variable)
Example #8
0
def test_str_arrays_with_nans():
    m = Model()

    x = m.add_variables(4, pd.Series([8, 10]), name="x")
    # now expand the second dimension, expended values of x will be nan
    y = m.add_variables(0, pd.DataFrame([[1, 2], [3, 4], [5, 6]]), name="y")
    assert m["x"][-1].item() == -1

    da = int_to_str(m["x"].values)
    assert da.dtype == object
Example #9
0
def create_model(N):
    m = Model()
    coords = [arange(N), arange(N)]
    x = m.add_variables(coords=coords)
    y = m.add_variables(coords=coords)
    m.add_constraints(x - y >= arange(N))
    m.add_constraints(x + y >= 0)
    m.add_objective((2 * x).sum() + y.sum())
    return m
Example #10
0
def masked_variable_model():
    m = Model()

    lower = pd.Series(0, range(10))
    x = m.add_variables(lower, name="x")
    mask = pd.Series([True] * 8 + [False, False])
    y = m.add_variables(lower, name="y", mask=mask)

    m.add_constraints(x + y, ">=", 10)

    m.add_constraints(y, ">=", 0)

    m.add_objective(2 * x + y)
    return m
Example #11
0
def model_chunked():
    m = Model(chunk="auto")

    x = m.add_variables(name="x")
    y = m.add_variables(name="y")

    m.add_constraints(2 * x + 6 * y, ">=", 10)
    m.add_constraints(4 * x + 2 * y, ">=", 3)

    m.add_objective(2 * y + x)
    return m
Example #12
0
def model_anonymous_constraint():
    m = Model(chunk=None)

    x = m.add_variables(name="x")
    y = m.add_variables(name="y")

    m.add_constraints(2 * x + 6 * y >= 10)
    m.add_constraints(4 * x + 2 * y >= 3)

    m.add_objective(2 * y + x)
    return m
Example #13
0
def test_variable_modification_M():
    m = Model()
    lower = pd.Series(0, index=range(10))
    upper = pd.Series(range(10, 20), index=range(10))
    x = m.add_variables(lower, upper)

    new_upper = pd.Series(range(25, 35), index=range(10))
    x.upper = new_upper
    assert isinstance(x.upper, xr.DataArray)
    assert (x.upper == new_upper).all()

    new_lower = pd.Series(range(15, 25), index=range(10))
    x.lower = new_lower
    assert isinstance(x.lower, xr.DataArray)
    assert (x.lower == new_lower).all()
Example #14
0
def test_to_blocks(tmp_path):
    m = Model()

    lower = pd.Series(range(20))
    upper = pd.Series(range(30, 50))
    x = m.add_variables(lower, upper)
    y = m.add_variables(lower, upper)

    m.add_constraints(x + y, "<=", 10)

    m.add_objective(2 * x + 3 * y)

    m.blocks = xr.DataArray([1] * 10 + [2] * 10)

    m.to_block_files(tmp_path)
Example #15
0
def test_variable_repr():
    m = Model()
    m.variables.__repr__()

    x = m.add_variables()
    x.__repr__()
    x._repr_html_()

    m.variables.__repr__()

    y = m.add_variables(coords=[pd.Index([1, 2, 3], name="time")], name="y")
    y.__repr__()
    y._repr_html_()

    m.variables.__repr__()
Example #16
0
def test_get_name_by_label():
    m = Model()
    x = m.add_variables(coords=[range(10)])
    y = m.add_variables(coords=[range(10)])

    m.add_constraints(x + y <= 10, name="first")
    m.add_constraints(x - y >= 5, name="second")

    assert m.constraints.get_name_by_label(4) == "first"
    assert m.constraints.get_name_by_label(14) == "second"

    with pytest.raises(ValueError):
        m.constraints.get_name_by_label(30)

    with pytest.raises(ValueError):
        m.constraints.get_name_by_label("first")
Example #17
0
def test_to_file(tmp_path):
    import gurobipy

    m = Model()

    x = m.add_variables(4, pd.Series([8, 10]))
    y = m.add_variables(0, pd.DataFrame([[1, 2], [3, 4], [5, 6]]))

    m.add_constraints(x + y, "<=", 10)

    m.add_objective(2 * x + 3 * y)

    fn = tmp_path / "test.lp"
    m.to_file(fn)

    gurobipy.read(str(fn))
Example #18
0
def model_with_inf():
    m = Model()

    lower = pd.Series(0, range(10))
    x = m.add_variables(coords=[lower.index], name="x", binary=True)
    y = m.add_variables(lower, name="y")

    m.add_constraints(x + y, ">=", 10)
    m.add_constraints(1 * x, "<=", np.inf)

    m.objective = 2 * x + y

    return m
Example #19
0
def model(n, solver, integerlabels):
    m = Model()
    if integerlabels:
        N, M = [arange(n), arange(n)]
    else:
        N, M = [arange(n).astype(float), arange(n).astype(str)]
    x = m.add_variables(coords=[N, M])
    y = m.add_variables(coords=[N, M])
    m.add_constraints(x - y >= N)
    m.add_constraints(x + y >= 0)
    m.add_objective((2 * x).sum() + y.sum())
    m.solve(solver)
    return
Example #20
0
def test_to_netcdf(tmp_path):
    m = Model()

    x = m.add_variables(4, pd.Series([8, 10]))
    y = m.add_variables(0, pd.DataFrame([[1, 2], [3, 4], [5, 6]]))
    m.add_constraints(x + y, "<=", 10)
    m.add_objective(2 * x + 3 * y)

    fn = tmp_path / "test.nc"
    m.to_netcdf(fn)
    p = read_netcdf(fn)

    for k in m.scalar_attrs:
        if k != "objective_value":
            assert getattr(m, k) == getattr(p, k)
    for k in m.dataset_attrs:
        assert_equal(getattr(m, k), getattr(p, k))
Example #21
0
def masked_constraint_model():
    m = Model()

    lower = pd.Series(0, range(10))
    x = m.add_variables(lower, name="x")
    y = m.add_variables(lower, name="y")

    mask = pd.Series([True] * 8 + [False, False])
    m.add_constraints(x + y, ">=", 10, mask=mask)
    # for the last two entries only the following constraint will be active
    m.add_constraints(x + y, ">=", 5)

    m.add_objective(2 * x + y)
    return m
Example #22
0
def milp_model_r():
    m = Model()

    lower = pd.Series(0, range(10))
    x = m.add_variables(coords=[lower.index], name="x", binary=True)
    y = m.add_variables(lower, name="y")

    m.add_constraints(x + y, ">=", 10)

    m.add_objective(2 * x + y)
    return m
Example #23
0
def test_constraint_accessor():
    m = Model()
    x = m.add_variables()
    y = m.add_variables()
    c = m.add_constraints(x, ">=", 0)
    assert c.rhs.item() == 0
    assert c.vars.item() == 0
    assert c.coeffs.item() == 1
    assert c.sign.item() == ">="

    c.rhs = 2
    assert c.rhs.item() == 2

    c.vars = y
    assert c.vars.item() == 1

    c.coeffs = 3
    assert c.coeffs.item() == 3

    c.sign = "=="
    assert c.sign.item() == "=="
Example #24
0
def test_constraint_matrix():
    m = Model()
    x = m.add_variables(coords=[range(10)])
    y = m.add_variables()
    m.add_constraints(x, "=", 0)
    A = m.constraints.to_matrix()
    assert A.shape == (10, 11)
Example #25
0
def test_constraint_accessor_M():
    m = Model()
    lower = pd.Series(range(10), range(10))
    upper = pd.Series(range(10, 20), range(10))
    x = m.add_variables(lower, upper)
    y = m.add_variables(lower, upper)
    c = m.add_constraints(x, ">=", 0)
    assert c.rhs.item() == 0
    assert (c.rhs == 0).all()

    assert c.vars.shape == (10, 1)
    assert c.coeffs.shape == (10, 1)

    assert c.sign.item() == ">="

    c.rhs = 2
    assert c.rhs.item() == 2

    c.lhs = 3 * y
    assert (c.vars.squeeze() == y.data).all()
    assert (c.coeffs == 3).all()
    assert isinstance(c.lhs, linopy.LinearExpression)
Example #26
0
def test_nvars():
    m = Model()
    m.add_variables(coords=[range(10)])
    assert m.variables.nvars == 10

    mask = pd.Series([True] * 5 + [False] * 5)
    m.add_variables(coords=[range(10)], mask=mask)
    assert m.variables.nvars == 15
Example #27
0
def test_constraint_matrix_masked_constraints_and_variables():
    """
    Test constraint matrix with missing constraints.
    """
    # now with missing variables
    m = Model()
    mask = pd.Series([False] * 5 + [True] * 5)
    x = m.add_variables(coords=[range(10)], mask=mask)
    m.add_variables()
    m.add_constraints(x, "=", 0, mask=mask)
    A = m.constraints.to_matrix(filter_missings=True)
    assert A.shape == (5, 6)
    assert A.shape == (m.ncons, m.nvars)

    A = m.constraints.to_matrix(filter_missings=False)
    assert A.shape == (m._cCounter, m._xCounter)
Example #28
0
def test_get_name_by_label():
    m = Model()
    m.add_variables(coords=[range(10)], name="x")
    m.add_variables(coords=[range(10)], name="asd")

    assert m.variables.get_name_by_label(4) == "x"
    assert m.variables.get_name_by_label(14) == "asd"

    with pytest.raises(ValueError):
        m.variables.get_name_by_label(30)

    with pytest.raises(ValueError):
        m.variables.get_name_by_label("asd")
Example #29
0
def test_constraints_accessor():
    m = Model()

    lower = xr.DataArray(np.zeros((10, 10)), coords=[range(10), range(10)])
    upper = xr.DataArray(np.ones((10, 10)), coords=[range(10), range(10)])
    x = m.add_variables(lower, upper)
    y = m.add_variables()
    m.add_constraints(1 * x + 10 * y, "=", 0)
    assert m.constraints["con0"].shape == (10, 10)
    assert isinstance(m.constraints[["con0"]], linopy.constraints.Constraints)
    assert isinstance(m.constraints.inequalities,
                      linopy.constraints.Constraints)
    assert isinstance(m.constraints.equalities, linopy.constraints.Constraints)
Example #30
0
def modified_model():
    m = Model()

    lower = pd.Series(0, range(10))
    x = m.add_variables(coords=[lower.index], name="x", binary=True)
    y = m.add_variables(lower, name="y")

    c = m.add_constraints(x + y, ">=", 10)

    y.lower = 9
    c.lhs = 2 * x + y
    m.objective = 2 * x + y

    return m