Note

You can download this example as a Jupyter notebook or start it in interactive mode.

Testing with Linopy#

In some cases you want to make sure the objects you create with linopy are correct and behave as expected. For this purpose, linopy provides a small testing framework, available at linopy.testing. In the following, we will show how to use it.

[1]:
import pandas as pd
import linopy
from linopy.testing import assert_varequal, assert_linequal, assert_conequal
/tmp/ipykernel_1955/4293665023.py:1: DeprecationWarning:
Pyarrow will become a required dependency of pandas in the next major release of pandas (pandas 3.0),
(to allow more performant data types, such as the Arrow string type, and better interoperability with other libraries)
but was not found to be installed on your system.
If this would cause problems for you,
please provide us feedback at https://github.com/pandas-dev/pandas/issues/54466

  import pandas as pd
[2]:
m = linopy.Model()

Check the equality of two variables#

The most basic test is to check the equality of two variables. This can be done with the assert_varequal function. If the two variables are not equal, an AssertionError is raised.

[3]:
x = m.add_variables(coords=[pd.RangeIndex(10, name="first")], name="x")

assert_varequal(x, m.variables.x)
# or
assert_varequal(x, m.variables["x"])

Check the equality of two expressions#

Analogeous to the assert_varequal function, the assert_expr_equal function can be used to check the equality of two expressions.

[4]:
y = m.add_variables(coords=[pd.RangeIndex(10, name="first")], name="y")

expr = 2 * x + y
assert_linequal(expr, 2 * x + y)

Check the equality of two constraints#

And finally, the assert_constraint_equal function can be used to check the equality of two constraints.

[5]:
con = m.add_constraints(expr >= 3, name='con')

assert_conequal(con, m.constraints.con)

Note that we cannot compare the con object with the original unassigned constraint expr >= 3. This is because a constraint object gets labels as soon as we add it to model. However we can make a workaround, and compare a new unassigned constraint, derived from con with the original constraint.

[6]:

assert_conequal(expr >= 3, con.lhs >= con.rhs)