API reference¶
Generated from the docstrings when the site is built (mkdocs serve, see the README), so
on GitHub you see only the three ::: lines below. In Python, help(ms.Model) or
help(ms.matrix) show the same text, and for an example
from misdp.examples import REGISTRY and help(REGISTRY["max_cut"].build). Everything
listed under misdp is available as ms.<name> after import misdp as ms.
misdp ¶
Model mixed-integer semidefinite programs in Python and export them as CBF files.
A first model with the public API:
import misdp as ms
m = ms.Model("stable_set")
X = m.add_matrix_var(3, vtype="binary", name="X")
m.add_constraint(X >> 0, name="psd")
m.optimize(ms.trace(X), sense="max")
m.write("stable_set.cbf")
ConstraintGroup ¶
ConstraintGroup(
name: str,
latex: str | None,
members: tuple[LinearConstraint | PsdConstraint, ...],
positions: tuple[int, ...],
)
Constraints added together by one Model.add_constraint call.
A group keeps the name and the optional LaTeX source of the constraints, so
exporters can print the group as one formula.
Model.add_constraint returns it; do not
instantiate this class directly.
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> X = m.add_matrix_var(2, "X")
>>> group = m.add_constraint(X >> 0, name="psd", latex=r"X \succeq 0")
>>> group.name, group.latex, len(group.members)
('psd', 'X \\succeq 0', 1)
name
property
¶
name: str
Name of the group.
The name given to Model.add_constraint;
without one, a default name (group0, ...) if latex was given, the
constraint's name for a single constraint, and "" otherwise.
members
property
¶
members: tuple[LinearConstraint | PsdConstraint, ...]
The constraints of the group in the order they were added.
__repr__ ¶
__repr__() -> str
Return e.g. <ConstraintGroup 'edge': 2 constraints>.
A group without a name shows (unnamed) instead of ''.
LinearConstraint ¶
LinearConstraint(expr: LinExpr, sense: ConstraintSense)
Bases: ConstraintOperand
A scalar constraint expr <sense> 0 with expr = lhs - rhs.
Created by comparing variables or expressions with ==, <= or >=;
add it to a model with Model.add_constraint.
Using it as a truth value (for example in 0 <= x <= 1) raises
ChainedComparisonError.
Operators other than == and != (identity) raise a misdp error too
(issue #103), e.g. (x <= 1) & (y <= 1).
A number on the left is moved to the right by Python: 5 <= x is stored as
x - 5 >= 0. A constraint without variables, such as (x - x) >= 1, is
accepted here; Model.compile drops it if it holds and
raises
InfeasibleConstantConstraintError
if not.
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> x = m.add_var("x")
>>> y = m.add_var("y")
>>> c = 2 * x <= y + 1
>>> c.sense, c.expr.constant
('<=', -1.0)
>>> {var.name: coef for var, coef in c.expr.coefficients().items()}
{'x': 2.0, 'y': -1.0}
__bool__ ¶
__bool__() -> NoReturn
Raise ChainedComparisonError.
Python calls bool() on the first comparison of 0 <= x <= 1, and in
if, and, or, not and x in [y].
LinExpr ¶
LinExpr(
model: Model | None = None,
coef: dict[int, float] | None = None,
const: float = 0.0,
)
Bases: Operand
An affine expression sum(coef * var) + constant.
Built from Var objects with + - * /; do not instantiate
it directly. Multiplying two non-constant expressions raises
NonlinearExpressionError.
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> x = m.add_var("x")
>>> y = m.add_var("y")
>>> e = 2 * x - y / 4 + 1
>>> {var.name: coef for var, coef in e.coefficients().items()}
{'x': 2.0, 'y': -0.25}
>>> e.constant
1.0
coefficients ¶
coefficients() -> dict[Var, float]
Return the nonzero coefficient of every variable, in variable order.
Returns:
| Type | Description |
|---|---|
dict of Var to float
|
A new dict; changing it does not change the expression. |
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> x = m.add_var("x")
>>> (3 * x + x).coefficients()[x]
4.0
__mul__ ¶
__mul__(other: float) -> LinExpr
__mul__(other: NDArray[Any]) -> MatExpr
__mul__(other: float | NDArray[Any]) -> LinExpr | MatExpr
Return self * other; with a square ndarray the result is a matrix.
__rmul__ ¶
__rmul__(other: float) -> LinExpr
__rmul__(other: NDArray[Any]) -> MatExpr
__rmul__(other: float | NDArray[Any]) -> LinExpr | MatExpr
Return other * self; with a square ndarray the result is a matrix.
__rtruediv__ ¶
__rtruediv__(other: float) -> LinExpr
Return other / self; only valid if self is a nonzero constant.
__pow__ ¶
__pow__(exponent: float) -> LinExpr
Return self ** 1; a constant expression counts as its number.
Any other power raises NonlinearExpressionError, or
UnsupportedConstruct if neither side has a variable. An exponent
expression of another model raises ModelMismatchError.
__rpow__ ¶
__rpow__(base: float) -> LinExpr
Return base ** self if self is the constant 1.
Any other power raises NonlinearExpressionError, or
UnsupportedConstruct if self has no variable.
MatExpr ¶
MatExpr(
model: Model | None,
size: int,
entries: dict[tuple[int, int], LinExpr],
labels: tuple[Label, ...] | None = None,
text: str | None = None,
)
Bases: Operand
A symmetric affine matrix expression sum_j x_j A_j + A_0.
Built from SymMatrixVar, ndarray * Var or
misdp.matrix, combined with + -, numbers (*, /)
and symmetric ndarrays. M >> 0 and M << A give a
PsdConstraint; M[i, j] gives an entry as a
LinExpr.
Only the lower triangle (i >= j) is stored. Arrays must be square,
symmetric up to 1e-9 * max(1, max|A|) and finite; within the tolerance
the lower triangle is used.
Examples:
>>> import numpy as np
>>> import misdp as ms
>>> m = ms.Model()
>>> y1 = m.add_var("y1")
>>> y2 = m.add_var("y2")
>>> c = ms.matrix([[y1, 1.5], [1.5, y2]]) >> 0
>>> M = y1 * np.eye(2) - np.array([[0.0, 1.0], [1.0, 0.0]])
>>> M[0, 1].constant
-1.0
__getitem__ ¶
__getitem__(key: tuple[Label, Label]) -> LinExpr
Return entry (a, b) as a scalar expression; symmetric.
Entries are addressed by the labels of the matrix variable the expression
came from, otherwise by positions 0 .. size-1.
__rmul__ ¶
__rmul__(other: float) -> MatExpr
Return other * self for a number or a scalar expression.
__pow__ ¶
__pow__(exponent: float) -> MatExpr
Return self ** 1, the same matrix; any other power raises.
** 1 is linear, so it does not say "nonlinear" (issue #251). A
power of a matrix with variables raises NonlinearExpressionError;
a power of a constant matrix raises UnsupportedConstruct.
__rshift__ ¶
__rshift__(other: MatOperand) -> PsdConstraint
Return the constraint self - other is PSD (M >> 0, M >> A).
__lshift__ ¶
__lshift__(other: MatOperand) -> PsdConstraint
Return the constraint other - self is PSD (M << A).
__rrshift__ ¶
__rrshift__(other: MatOperand) -> PsdConstraint
Return the constraint other - self is PSD (A >> M).
__rlshift__ ¶
__rlshift__(other: MatOperand) -> PsdConstraint
Return the constraint self - other is PSD (A << M).
Model ¶
Model(name: str = 'model')
A mixed-integer semidefinite program.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the model; it becomes the model name in the CBF annotations.
Any string is allowed; anything else raises |
"model"
|
Examples:
>>> import misdp as ms
>>> E = [(0, 1), (1, 2)]
>>> m = ms.Model("stable_set")
>>> X = m.add_matrix_var(3, vtype="binary", name="X")
>>> group = m.add_constraint(X >> 0, name="psd")
>>> group = m.add_constraint((X[u, v] == 0 for u, v in E), name="edge")
>>> m.optimize(ms.trace(X), sense="max")
>>> cbf = m.to_cbf(annotate=False)
name
property
writable
¶
name: str
Name of the model, any string; it becomes the model name in the CBF file.
variables
property
¶
variables: tuple[Var, ...]
All scalar variables in creation order (matrix entries included).
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> X = m.add_matrix_var(2, "X")
>>> [v.name for v in m.variables]
['X[0,0]', 'X[1,0]', 'X[1,1]']
constraints
property
¶
constraints: tuple[LinearConstraint | PsdConstraint, ...]
All constraints in the order they were added.
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> x = m.add_var("x")
>>> _ = m.add_constraint([x >= 0, x <= 1], name="box")
>>> m.constraints
(<LinearConstraint x >= 0>, <LinearConstraint x <= 1>)
add_var ¶
add_var(
name: str | None = None,
*,
vtype: VType = "continuous",
lb: float = -math.inf,
ub: float = math.inf,
) -> Var
Add a scalar variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Identifier-like name; defaults to |
None
|
vtype
|
('continuous', 'integer', 'binary')
|
Variable type. |
"continuous"
|
lb
|
float
|
Bounds. |
-inf, inf
|
ub
|
float
|
Bounds. |
-inf, inf
|
Returns:
| Type | Description |
|---|---|
Var
|
The new variable. |
Raises:
| Type | Description |
|---|---|
(InvalidNameError, DuplicateNameError)
|
|
(InvalidVTypeError, InvalidBoundsError)
|
Unknown |
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> x = m.add_var("x", lb=0)
>>> b = m.add_var("b", vtype="binary")
>>> (b.lb, b.ub)
(0.0, 1.0)
add_vars ¶
add_vars(
index: Index,
name: str | None = None,
*,
vtype: VType = "continuous",
lb: float = -math.inf,
ub: float = math.inf,
) -> VarVector
Add a vector of scalar variables, one per label of index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int or iterable of int or str
|
Labels; an |
required |
name
|
str
|
Identifier-like name; defaults to the first free |
None
|
vtype
|
('continuous', 'integer', 'binary')
|
Type of every entry. |
"continuous"
|
lb
|
float
|
Bounds of every entry. |
-inf, inf
|
ub
|
float
|
Bounds of every entry. |
-inf, inf
|
Returns:
| Type | Description |
|---|---|
VarVector
|
The new vector variable; entries are named |
Raises:
| Type | Description |
|---|---|
DimensionError
|
|
(InvalidNameError, DuplicateNameError)
|
Invalid or used name; labels that are not int or str (e.g. tuples), repeated labels. |
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> y = m.add_vars(["a", "b", "c"], "y", lb=0)
>>> y["b"].name
'y[b]'
add_matrix_var ¶
add_matrix_var(
index: Index,
name: str | None = None,
*,
vtype: VType = "continuous",
lb: float = -math.inf,
ub: float = math.inf,
) -> SymMatrixVar
Add a symmetric matrix variable with one scalar per lower-triangle entry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int or iterable of int or str
|
Row (and column) labels; an |
required |
name
|
str
|
Identifier-like name; defaults to the first free |
None
|
vtype
|
('continuous', 'integer', 'binary')
|
Type of every entry. |
"continuous"
|
lb
|
float
|
Bounds of every entry. |
-inf, inf
|
ub
|
float
|
Bounds of every entry. |
-inf, inf
|
Returns:
| Type | Description |
|---|---|
SymMatrixVar
|
The new matrix variable. Entry |
Raises:
| Type | Description |
|---|---|
DimensionError
|
|
(InvalidNameError, DuplicateNameError)
|
Invalid or used name; labels that are not int or str (e.g. tuples), repeated labels. |
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> X = m.add_matrix_var(3, "X", vtype="binary")
>>> X[0, 2] is X[2, 0]
True
>>> nodes = ["a", "b", "c"]
>>> Y = m.add_matrix_var(nodes, "Y")
>>> Y["a", "c"].name
'Y[c,a]'
set_vtype ¶
set_vtype(
variables: Var
| VarVector
| SymMatrixVar
| Iterable[Var],
vtype: VType,
) -> None
Change the type of one or more variables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
variables
|
Var, VarVector, SymMatrixVar or iterable of Var
|
Variables of this model; a container means all its entries. |
required |
vtype
|
('continuous', 'integer', 'binary')
|
New type. The current bounds are kept and then adjusted as in
|
"continuous"
|
Notes
Either every variable is changed or, on an error, none.
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> X = m.add_matrix_var(2, "X")
>>> m.set_vtype(X.diagonal(), "integer")
>>> X[1, 1].vtype
'integer'
set_bounds ¶
set_bounds(
variables: Var
| VarVector
| SymMatrixVar
| Iterable[Var],
lb: float | None = None,
ub: float | None = None,
) -> None
Change the bounds of one or more variables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
variables
|
Var, VarVector, SymMatrixVar or iterable of Var
|
Variables of this model; a container means all its entries. |
required |
lb
|
float
|
New bounds; |
None
|
ub
|
float
|
New bounds; |
None
|
Notes
Either every variable is changed or, on an error, none.
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> x = m.add_var("x")
>>> m.set_bounds(x, lb=0)
>>> (x.lb, x.ub)
(0.0, inf)
add_constraint ¶
add_constraint(
constraint: LinearConstraint
| PsdConstraint
| Iterable[LinearConstraint | PsdConstraint],
name: str | None = None,
*,
latex: str | None = None,
group: bool = True,
) -> ConstraintGroup
Add one constraint or an iterable of constraints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
constraint
|
LinearConstraint, PsdConstraint or iterable of them
|
The constraint(s); a generator works. |
required |
name
|
str
|
Name of a single constraint, or the group name for an iterable
(members are then called |
None
|
latex
|
str
|
LaTeX source of the constraint(s), used by the exporters. |
None
|
group
|
bool
|
|
True
|
Returns:
| Type | Description |
|---|---|
ConstraintGroup
|
The added constraints. It also goes into the IR (and the CBF
annotations) as a group when |
Raises:
| Type | Description |
|---|---|
(InvalidNameError, DuplicateNameError)
|
|
ModelMismatchError
|
A constraint uses variables of another model. |
UnsupportedConstruct
|
|
Notes
Default names: c0, c1, ... for linear constraints, psd0, psd1, ...
for PSD constraints, group0, ... for a group with latex but no
name; names the user already took are skipped. Constraint and group
names share one namespace, except that a single named constraint and its
group have the same name. The iterable is read completely and checked
before the model changes, so a failed call adds nothing.
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> X = m.add_matrix_var(3, "X", vtype="binary")
>>> group = m.add_constraint(X >> 0, name="psd")
>>> group.name
'psd'
optimize ¶
optimize(
expr: LinExpr | Var | float,
sense: Literal["min", "max"] = "min",
) -> None
Set the objective to minimize or maximize expr.
A second call replaces an earlier objective.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expr
|
(LinExpr, Var or number)
|
A linear expression of this model's variables. A number gives a
constant objective; |
required |
sense
|
('min', 'max')
|
Minimize or maximize |
"min"
|
Raises:
| Type | Description |
|---|---|
DimensionError
|
|
ModelMismatchError
|
|
NonFiniteCoefficientError
|
|
UnsupportedConstruct
|
|
Warns:
| Type | Description |
|---|---|
ObjectiveReplacedWarning
|
An objective was already set; the new one replaces it. |
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> x = m.add_var("x", lb=0)
>>> m.optimize(2 * x + 1)
>>> m2 = ms.Model()
>>> X = m2.add_matrix_var(2, "X", vtype="binary")
>>> m2.optimize(X[0, 0] + X[1, 1], sense="max")
summary ¶
summary() -> str
Return a readable description of the model.
The first line is repr() without the angle brackets. Then follow
the objective, the constraints (groups with their LaTeX and first
members), the variables and the key figures of
ProblemIR.summary, computed without compiling.
Long listings show their first entries and count the rest.
Returns:
| Type | Description |
|---|---|
str
|
Several lines, no trailing newline. |
Examples:
>>> import misdp as ms
>>> m = ms.Model("lp")
>>> x = m.add_var("x", lb=0)
>>> _ = m.add_constraint(2 * x <= 3, name="cap")
>>> m.optimize(x, sense="max")
>>> print(m.summary())
Model 'lp': 1 variable, 1 linear constraint, 0 PSD constraints, maximize
maximize
x
subject to
cap: 2*x <= 3
variables
x: continuous, x >= 0
key figures
name: lp
sense: MAX
variables: 1
integer_variables: 0
rows_by_cone: L= 0, L+ 0, L- 1
bound_rows: 1
psd_blocks: []
has_objective: True
compile ¶
compile() -> ProblemIR
Validate the model and return its intermediate representation.
Returns:
| Type | Description |
|---|---|
ProblemIR
|
The canonical form that every exporter reads; it passes
|
Raises:
| Type | Description |
|---|---|
EmptyModelError
|
The model has no variables. |
InfeasibleConstantConstraintError
|
A linear constraint without variables is false, e.g. |
Warns:
| Type | Description |
|---|---|
NoObjectiveWarning
|
No objective was set. |
TrivialConstraintWarning
|
Linear constraints without variables that are always true were dropped. |
MisdpWarning
|
Once per PSD constraint without variables: it is written unchanged, but SCIP-SDP 4.4.0 refuses to read such blocks (issue #42). Also once per PSD constraint whose variable coefficients all have magnitude at most 1e-9: SCIP-SDP 4.4.0 drops them while reading and then refuses the block in the same way (issue #83). |
NumericsWarning
|
A coefficient or constant has magnitude above 1e8 or a nonzero
magnitude below 1e-8. Variable bounds and the objective constant are
checked only from magnitude 1e20 on ( |
Examples:
>>> import misdp as ms
>>> m = ms.Model("beispiel_a")
>>> y1 = m.add_var("y1", vtype="integer")
>>> y2 = m.add_var("y2", vtype="integer")
>>> group = m.add_constraint(ms.matrix([[y1, 1.5], [1.5, y2]]) >> 0)
>>> m.optimize(y1 + y2)
>>> ir = m.compile()
>>> ir.psd[0].d
((1, 0, 1.5),)
to_cbf ¶
to_cbf(*, annotate: bool = True) -> str
Return the model as CBF version 2 text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
annotate
|
bool
|
Write the |
True
|
Returns:
| Type | Description |
|---|---|
str
|
The CBF file content. |
Raises:
| Type | Description |
|---|---|
EmptyModelError
|
The model has no variables (from |
InfeasibleConstantConstraintError
|
A linear constraint without variables is false (from |
UnsupportedConstruct
|
The file would hold more variables, constraint rows (bound rows included) or lower-triangle PSD block entries than misdp supports (10**6 each). |
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> x = m.add_var("x", vtype="integer")
>>> m.optimize(x)
>>> print(m.to_cbf(annotate=False).splitlines()[:5])
['VER', '2', '', 'OBJSENSE', 'MIN']
write ¶
write(
path: str | PathLike[str], *, annotate: bool = True
) -> pathlib.Path
Write the model to a CBF version 2 file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str or path - like
|
Target file. |
required |
annotate
|
bool
|
Write the |
True
|
Returns:
| Type | Description |
|---|---|
Path
|
The path that was written. |
Raises:
| Type | Description |
|---|---|
EmptyModelError
|
The model has no variables (from |
InfeasibleConstantConstraintError
|
A linear constraint without variables is false (from |
UnsupportedConstruct
|
The file would hold more variables, constraint rows (bound rows included) or lower-triangle PSD block entries than misdp supports (10**6 each). |
OSError
|
The file cannot be written. The subclass (e.g. |
PsdConstraint ¶
PsdConstraint(expr: MatExpr)
Bases: ConstraintOperand
A constraint expr is positive semidefinite.
Created with >> or << on matrix variables and matrix expressions;
add it to a model with Model.add_constraint.
A >> B and B << A both mean A - B is PSD. Using it as a truth
value, or with an operator other than == and != (identity), raises a
misdp error (issue #103).
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> X = m.add_matrix_var(2, "X")
>>> c = X >> 0
>>> c.expr.size
2
__bool__ ¶
__bool__() -> NoReturn
Raise UnsupportedConstruct (issue #103).
m.add_constraint(p and q) would otherwise add only q.
SymMatrixVar ¶
SymMatrixVar(
model: Model,
name: str,
first_var: int,
labels: tuple[Label, ...],
)
Bases: Operand
A symmetric matrix of scalar variables, one per lower-triangle entry.
Create it with Model.add_matrix_var.
X[a, b] and X[b, a] return the same Var. X >> 0
gives a PsdConstraint.
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> X = m.add_matrix_var(3, "X", vtype="binary")
>>> c = X >> 0
__getitem__ ¶
__getitem__(key: tuple[LabelLike, LabelLike]) -> Var
Return the entry variable for the labels (a, b); symmetric.
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> X = m.add_matrix_var(["a", "b"], "X")
>>> X["a", "b"] is X["b", "a"]
True
>>> X["b", "a"].name
'X[b,a]'
diagonal ¶
diagonal() -> list[Var]
Return the diagonal entries in label order.
Returns:
| Type | Description |
|---|---|
list of Var
|
|
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> X = m.add_matrix_var(["a", "b"], "X")
>>> [v.name for v in X.diagonal()]
['X[a,a]', 'X[b,b]']
entries ¶
entries() -> Iterator[tuple[Label, Label, Var]]
Yield (label_i, label_j, var) for every lower-triangle entry (i >= j).
The order is the creation order of the entries (row-major lower triangle).
Yields:
| Type | Description |
|---|---|
tuple of (label, label, Var)
|
Row label, column label and the entry variable. |
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> X = m.add_matrix_var(2, "X")
>>> [(i, j, v.name) for i, j, v in X.entries()]
[(0, 0, 'X[0,0]'), (1, 0, 'X[1,0]'), (1, 1, 'X[1,1]')]
__pow__ ¶
__pow__(exponent: float) -> MatExpr
Return self ** 1, the same matrix; any other power raises.
__rshift__ ¶
__rshift__(other: MatOperand) -> PsdConstraint
Return the constraint self - other is PSD (X >> 0, X >> A).
__lshift__ ¶
__lshift__(other: MatOperand) -> PsdConstraint
Return the constraint other - self is PSD (X << A).
__rrshift__ ¶
__rrshift__(other: MatOperand) -> PsdConstraint
Return the constraint other - self is PSD (A >> X).
__rlshift__ ¶
__rlshift__(other: MatOperand) -> PsdConstraint
Return the constraint self - other is PSD (A << X).
Var ¶
Var(
model: Model,
index: int,
name: str,
vtype: VType,
lb: float,
ub: float,
)
Bases: Operand
A scalar decision variable of a Model.
Create variables with Model.add_var,
Model.add_vars or
Model.add_matrix_var; do not instantiate this
class directly.
Arithmetic with numbers and other variables gives a
LinExpr; ==, <= and >= give a
LinearConstraint; Var * ndarray gives a
MatExpr. Variables hash by identity, so they can be
dictionary keys.
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> x = m.add_var("x", lb=0)
>>> c = 2 * x + 1 <= 5
__mul__ ¶
__mul__(other: float) -> LinExpr
__mul__(other: NDArray[Any]) -> MatExpr
__mul__(other: float | NDArray[Any]) -> LinExpr | MatExpr
Return self * other; with a square ndarray the result is a matrix.
A product with another variable raises NonlinearExpressionError.
__rmul__ ¶
__rmul__(other: float) -> LinExpr
__rmul__(other: NDArray[Any]) -> MatExpr
__rmul__(other: float | NDArray[Any]) -> LinExpr | MatExpr
Return other * self; with a square ndarray the result is a matrix.
__rtruediv__ ¶
__rtruediv__(other: float) -> LinExpr
Raise NonlinearExpressionError: other / x is not linear.
__pow__ ¶
__pow__(exponent: float) -> LinExpr
Return x ** 1; any other power raises NonlinearExpressionError.
__rpow__ ¶
__rpow__(base: float) -> LinExpr
Raise NonlinearExpressionError: base ** x is not linear.
VarVector ¶
VarVector(
model: Model,
name: str,
first_var: int,
labels: tuple[Label, ...],
)
Bases: Operand
A vector of scalar variables indexed by labels.
Create it with Model.add_vars. v[label] returns
the Var for that label; ndarray @ v gives a
LinExpr.
Examples:
>>> import numpy as np
>>> import misdp as ms
>>> m = ms.Model()
>>> y = m.add_vars(3, "y", vtype="integer")
>>> e = np.array([1.0, 2.0, 3.0]) @ y
__rmatmul__ ¶
__rmatmul__(other: NDArray[Any]) -> LinExpr
Return other @ self for a 1-D array of matching length.
A list of numbers works too. Zero coefficients are left out.
Raises:
| Type | Description |
|---|---|
NonlinearExpressionError
|
|
DimensionError
|
|
UnsupportedConstruct
|
|
NonFiniteCoefficientError
|
|
Examples:
>>> import numpy as np
>>> import misdp as ms
>>> m = ms.Model()
>>> y = m.add_vars(3, "y")
>>> e = np.array([2.0, 0.0, -1.0]) @ y
>>> [var.name for var in e.coefficients()]
['y[0]', 'y[2]']
__matmul__ ¶
__matmul__(other: NDArray[Any]) -> LinExpr
Return self @ other, the same as other @ self.
BoundsRoundedWarning ¶
Bases: MisdpWarning
Fractional bounds of an integer variable were rounded inward.
ChainedComparisonError ¶
ChainedComparisonError(
message: str,
*,
element: str | None = None,
hint: str | None = None,
)
DimensionError ¶
DimensionError(
message: str,
*,
element: str | None = None,
hint: str | None = None,
)
DuplicateNameError ¶
DuplicateNameError(
message: str,
*,
element: str | None = None,
hint: str | None = None,
)
EmptyModelError ¶
EmptyModelError(
message: str,
*,
element: str | None = None,
hint: str | None = None,
)
IndexOutOfRangeError ¶
IndexOutOfRangeError(
message: str,
*,
element: str | None = None,
hint: str | None = None,
)
InfeasibleConstantConstraintError ¶
InfeasibleConstantConstraintError(
message: str,
*,
element: str | None = None,
hint: str | None = None,
)
InvalidBoundsError ¶
InvalidBoundsError(
message: str,
*,
element: str | None = None,
hint: str | None = None,
)
InvalidNameError ¶
InvalidNameError(
message: str,
*,
element: str | None = None,
hint: str | None = None,
)
InvalidVTypeError ¶
InvalidVTypeError(
message: str,
*,
element: str | None = None,
hint: str | None = None,
)
IRValidationError ¶
IRValidationError(problems: list[str])
Bases: MisdpError
A ProblemIR violates one or more invariants.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problems
|
list of str
|
Every violated invariant, one sentence each. |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
problems |
list of str
|
A copy of the list passed in. |
MisdpError ¶
MisdpError(
message: str,
*,
element: str | None = None,
hint: str | None = None,
)
Bases: Exception
Base class of all errors raised by misdp.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
What is wrong, in the form |
required |
element
|
str or None
|
Name of the model element the error is about (variable, constraint, model), as the user named it. Tools such as the AI frontend use it to point at the offending element. |
None
|
hint
|
str or None
|
How to fix the problem. Appended to the message after one space. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
message |
str
|
The message without hint. |
element |
str or None
|
See above. |
hint |
str or None
|
See above. |
MisdpWarning ¶
Bases: UserWarning
Base class of all warnings issued by misdp.
ModelingError ¶
ModelingError(
message: str,
*,
element: str | None = None,
hint: str | None = None,
)
ModelMismatchError ¶
ModelMismatchError(
message: str,
*,
element: str | None = None,
hint: str | None = None,
)
NonFiniteCoefficientError ¶
NonFiniteCoefficientError(
message: str,
*,
element: str | None = None,
hint: str | None = None,
)
NonlinearExpressionError ¶
NonlinearExpressionError(
message: str,
*,
element: str | None = None,
hint: str | None = None,
)
NonSymmetricMatrixError ¶
NonSymmetricMatrixError(
message: str,
*,
element: str | None = None,
hint: str | None = None,
)
NoObjectiveWarning ¶
Bases: MisdpWarning
The model has no objective and is written as a feasibility problem.
NumericsWarning ¶
Bases: MisdpWarning
A value has a magnitude SCIP-SDP 4.4.0 may not handle reliably.
compile() warns about coefficients and constraint constants (not bounds or the
objective constant) with magnitude above 1e8 or a nonzero magnitude below 1e-8;
compile() and the CBF writer warn about any written value of magnitude 1e20 or
more, bounds and the objective constant included.
ObjectiveReplacedWarning ¶
Bases: MisdpWarning
The objective was set again; the last call wins.
TrivialConstraintWarning ¶
Bases: MisdpWarning
A constraint without variables is always true and was dropped.
UnsupportedConstruct ¶
UnsupportedConstruct(
message: str,
*,
element: str | None = None,
hint: str | None = None,
)
ProblemIR
dataclass
¶
ProblemIR(
name: str,
sense: Sense,
variables: tuple[VarInfo, ...],
objective: tuple[tuple[int, float], ...] = (),
objective_const: float = 0.0,
has_objective: bool = True,
rows: tuple[LinearRow, ...] = (),
psd: tuple[PsdBlock, ...] = (),
vector_vars: tuple[VectorVarInfo, ...] = (),
matrix_vars: tuple[MatrixVarInfo, ...] = (),
groups: tuple[Group, ...] = (),
)
A complete MISDP in dual form; the contract between all packages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Model name. |
required |
sense
|
('MIN', 'MAX')
|
Objective sense. |
"MIN"
|
variables
|
tuple of VarInfo
|
Scalar variables; position = variable index. |
required |
objective
|
tuple of (int, float)
|
Objective coefficients, sorted by variable index, nonzero. |
()
|
objective_const
|
float
|
Constant term of the objective. |
0.0
|
has_objective
|
bool
|
|
True
|
rows
|
tuple of LinearRow
|
Scalar constraints, grouped by cone in the order |
()
|
psd
|
tuple of PsdBlock
|
PSD constraints. |
()
|
vector_vars
|
tuple
|
Structure of vector and matrix variables (metadata). |
()
|
matrix_vars
|
tuple
|
Structure of vector and matrix variables (metadata). |
()
|
groups
|
tuple of Group
|
Constraint groups (metadata). |
()
|
Notes
Building a ProblemIR does not check it; call
validate.
validate ¶
validate() -> None
Check that the IR is well formed.
The invariants are: variable indices are in range (I1); objective and row
coefficients are sorted by variable, unique, nonzero and finite, and the
objective and row constants are finite (I2); PSD entries are sorted,
unique, nonzero, finite and in the lower triangle (I3); bounds are valid,
and finite bounds of integer variables are integral (I4); names are unique
within each kind, and no vector or matrix variable has the name of a
variable (I5); vector and matrix variables cover disjoint index ranges with
matching entry names (I6); group indices are valid and each row or block is
in at most one group (I7); a feasibility problem has no objective data
(I8); PSD blocks and matrix variables have size at least 1, and a PSD block
at most 1413, the largest that a CBF file of misdp holds (I9); rows are
grouped by cone in the order L=, L+, L- (I10).
All problems are collected before raising. Each problem starts with the
invariant it violates ("I3: ..."), or with "Types: ..." when a
field has the wrong type.
Raises:
| Type | Description |
|---|---|
IRValidationError
|
If at least one invariant is violated; |
equivalent ¶
equivalent(
other: ProblemIR,
*,
tol: float = 1e-09,
match_by: Literal["index", "name"] = "index",
ignore_row_order: bool = False,
compare_names: bool = False,
) -> bool
Return whether two IRs describe the same problem.
Both IRs should be valid (see validate).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
ProblemIR
|
The IR to compare with. |
required |
tol
|
float
|
Floats |
1e-09
|
match_by
|
('index', 'name')
|
|
"index"
|
ignore_row_order
|
bool
|
Compare the rows of each cone and the PSD blocks as multisets, with the same tolerance as the ordered comparison. Matching is greedy. |
False
|
compare_names
|
bool
|
Also compare the model name, row and block names, variable names
(with |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
|
diff ¶
diff(
other: ProblemIR,
*,
tol: float = 1e-09,
match_by: Literal["index", "name"] = "index",
ignore_row_order: bool = False,
compare_names: bool = False,
) -> list[str]
Describe the differences between two IRs, one line each.
Takes the same options as
equivalent, and returns an empty list exactly
when it returns True. Meant for test failure messages; at most about
100 lines are returned.
Returns:
| Type | Description |
|---|---|
list of str
|
Human-readable differences; |
summary ¶
summary() -> dict[str, Any]
Return key figures of the problem.
The IR must be valid; on an invalid one (for example an int bound beyond
the float range) it may raise a plain OverflowError. Call validate
first for an IR that was not built by misdp.
Returns:
| Type | Description |
|---|---|
dict
|
Keys |
to_dict ¶
to_dict() -> dict[str, Any]
Convert the IR to a JSON-safe dictionary.
The IR must be valid, as for summary: call validate first for an IR
that was not built by misdp.
Tuples become lists. Infinite and NaN floats become the strings
"inf", "-inf" and "nan", so the result passes
json.dumps(..., allow_nan=False). The key ir_version (currently
1) identifies the format.
Returns:
| Type | Description |
|---|---|
dict
|
Input for |
from_dict
classmethod
¶
from_dict(data: dict[str, Any]) -> ProblemIR
Build an IR from the output of to_dict (or parsed JSON of it).
Keys with default values in the data classes may be omitted. Unknown
keys are rejected. The result is not validated; call
validate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict
|
Dictionary in the format of |
required |
Returns:
| Type | Description |
|---|---|
ProblemIR
|
The rebuilt IR. |
Raises:
| Type | Description |
|---|---|
IRValidationError
|
If the data does not have the expected shape or types; the single
problem names the offending path, e.g. |
inner ¶
inner(
C: NDArray[Any], M: SymMatrixVar | MatExpr
) -> LinExpr
Return the inner product sum_ij C[i, j] * M[i, j].
For an off-diagonal entry the coefficient is C[i, j] + C[j, i], so C
need not be symmetric.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
C
|
ndarray
|
Square coefficient matrix of the same size as |
required |
M
|
SymMatrixVar or MatExpr
|
The matrix. |
required |
Returns:
| Type | Description |
|---|---|
LinExpr
|
The inner product. |
Examples:
>>> import numpy as np
>>> import misdp as ms
>>> m = ms.Model()
>>> X = m.add_matrix_var(2, "X")
>>> e = ms.inner(np.array([[1.0, 2.0], [0.0, 3.0]]), X)
>>> {var.name: c for var, c in e.coefficients().items()}
{'X[0,0]': 1.0, 'X[1,0]': 2.0, 'X[1,1]': 3.0}
matrix ¶
matrix(rows: Sequence[Sequence[LinOperand]]) -> MatExpr
Build a symmetric matrix expression from nested rows.
Entries are variables, expressions or numbers. rows[i][j] must equal
rows[j][i] up to 1e-9 * max(1, largest coefficient); the lower
triangle is used.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rows
|
sequence of sequences of Var, LinExpr or number
|
Square and symmetric: |
required |
Returns:
| Type | Description |
|---|---|
MatExpr
|
The matrix expression. |
Raises:
| Type | Description |
|---|---|
DimensionError
|
|
NonSymmetricMatrixError
|
|
UnsupportedConstruct
|
An entry is not a variable, expression or number. |
Examples:
>>> import misdp as ms
>>> m = ms.Model("beispiel_a")
>>> y1 = m.add_var("y1", vtype="integer")
>>> y2 = m.add_var("y2", vtype="integer")
>>> M = ms.matrix([[y1, 1.5], [1.5, y2]])
>>> M[1, 0].constant
1.5
quicksum ¶
quicksum(items: Iterable[LinOperand]) -> LinExpr
quicksum(
items: Iterable[MatExpr | SymMatrixVar],
) -> MatExpr
quicksum(
items: Iterable[LinOperand]
| Iterable[MatExpr | SymMatrixVar],
) -> LinExpr | MatExpr
Sum scalar or matrix expressions faster than the built-in sum.
sum() builds a new expression for every term, so its cost grows with the
square of the number of terms; quicksum adds all terms into one
expression (about 5 ms for 10 000 terms, against 0.2 s for sum()).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
iterable of Var, LinExpr, number, MatExpr or SymMatrixVar
|
The terms; scalar and matrix terms cannot be mixed. |
required |
Returns:
| Type | Description |
|---|---|
LinExpr or MatExpr
|
The sum; an empty iterable gives the constant |
Raises:
| Type | Description |
|---|---|
ModelMismatchError
|
Terms come from two different models. |
UnsupportedConstruct
|
A term is not a variable, expression or number. |
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> y = m.add_vars(3, "y")
>>> e = ms.quicksum(k * y[k] for k in range(3))
>>> [coef for coef in e.coefficients().values()]
[1.0, 2.0]
trace ¶
trace(M: SymMatrixVar | MatExpr) -> LinExpr
Return the trace of a matrix variable or matrix expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
M
|
SymMatrixVar or MatExpr
|
The matrix. |
required |
Returns:
| Type | Description |
|---|---|
LinExpr
|
Sum of the diagonal entries. |
Examples:
>>> import misdp as ms
>>> m = ms.Model()
>>> X = m.add_matrix_var(2, "X")
>>> [var.name for var in ms.trace(X).coefficients()]
['X[0,0]', 'X[1,1]']
write_cbf ¶
write_cbf(
ir: ProblemIR,
path: None = None,
*,
annotate: bool = True,
) -> str
write_cbf(
ir: ProblemIR,
path: str | PathLike[str],
*,
annotate: bool = True,
) -> Path
write_cbf(
ir: ProblemIR,
path: str | PathLike[str] | None = None,
*,
annotate: bool = True,
) -> str | Path
Return ir as CBF text, or write it to path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ir
|
ProblemIR
|
The problem. |
required |
path
|
str or path - like
|
Target file. Without it the CBF text is returned. |
None
|
annotate
|
bool
|
Write the |
True
|
Returns:
| Type | Description |
|---|---|
str or Path
|
The CBF text if |
misdp.ir ¶
Intermediate representation (IR) of an MISDP.
The IR is the fixed interface between all packages of misdp.
The canonicalizer (Model.compile) produces it, and the CBF writer only reads it.
All classes are frozen dataclasses that hold tuples, so an IR never changes after it is built. The IR describes the problem in dual form:
min/max sum_j c_j x_j + c_0
s.t. a_i . x + b_i in K_i for every row i, K_i in {L=, L+, L-}
sum_j x_j H_kj + D_k is PSD for every PSD block k
lb_j <= x_j <= ub_j, x_j integer where requested
Matrices of PSD blocks are symmetric; only the lower triangle (row >= col)
is stored. Vector and matrix variables, constraint groups and all names are
metadata for back-translation; they do not change the mathematical problem.
Examples:
>>> from misdp.ir import ProblemIR, PsdBlock, VarInfo
>>> ir = ProblemIR(
... name="beispiel_a",
... sense="MIN",
... variables=(VarInfo("y1", integer=True), VarInfo("y2", integer=True)),
... objective=((0, 1.0), (1, 1.0)),
... psd=(PsdBlock("psd0", 2, h=((0, 0, 0, 1.0), (1, 1, 1, 1.0)),
... d=((1, 0, 1.5),)),),
... )
>>> ir.validate()
>>> ir.summary()["psd_blocks"]
[2]
>>> ProblemIR.from_dict(ir.to_dict()) == ir
True
VarInfo
dataclass
¶
VarInfo(
name: str,
integer: bool = False,
lb: float = -math.inf,
ub: float = math.inf,
)
A scalar variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique variable name, e.g. |
required |
integer
|
bool
|
Whether the variable must take integer values. Binary variables are integer variables with bounds 0 and 1. |
False
|
lb
|
float
|
Lower and upper bound; |
-inf
|
ub
|
float
|
Lower and upper bound; |
-inf
|
LinearRow
dataclass
¶
LinearRow(
name: str,
cone: Cone,
coeffs: tuple[tuple[int, float], ...],
const: float = 0.0,
)
A scalar constraint sum(coef * x[var]) + const in cone.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique row name. |
required |
cone
|
('L=', 'L+', 'L-')
|
|
"L="
|
coeffs
|
tuple of (int, float)
|
|
required |
const
|
float
|
Constant term. |
0.0
|
PsdBlock
dataclass
¶
PsdBlock(
name: str,
size: int,
h: tuple[tuple[int, int, int, float], ...],
d: tuple[tuple[int, int, float], ...] = (),
)
A PSD constraint sum_j x[j] * H_j + D is PSD (one CBF PSDCON entry).
Only lower-triangle entries (row >= col) are stored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique block name. |
required |
size
|
int
|
Matrix dimension, at least 1. |
required |
h
|
tuple of (int, int, int, float)
|
|
required |
d
|
tuple of (int, int, float)
|
|
()
|
VectorVarInfo
dataclass
¶
VectorVarInfo(
name: str, first_var: int, labels: tuple[Label, ...]
)
A vector variable: consecutive scalar variables with labels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the vector; entries are named |
required |
first_var
|
int
|
Index of the first entry; the entries are |
required |
labels
|
tuple of int or str
|
One label per entry. |
required |
MatrixVarInfo
dataclass
¶
MatrixVarInfo(
name: str,
size: int,
first_var: int,
labels: tuple[Label, ...],
)
A symmetric matrix variable: one scalar variable per lower-triangle entry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the matrix; entries are named |
required |
size
|
int
|
Matrix dimension, at least 1. |
required |
first_var
|
int
|
Entry |
required |
labels
|
tuple of int or str
|
Row (and column) labels; |
required |
Group
dataclass
¶
Group(
name: str,
latex: str | None,
rows: tuple[int, ...],
psd: tuple[int, ...],
)
A named group of constraints, created by one Model.add_constraint call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique group name. |
required |
latex
|
str or None
|
LaTeX formula of the group as the user wrote it, if any. |
required |
rows
|
tuple of int
|
Indices into |
required |
psd
|
tuple of int
|
Indices into |
required |
ProblemIR
dataclass
¶
ProblemIR(
name: str,
sense: Sense,
variables: tuple[VarInfo, ...],
objective: tuple[tuple[int, float], ...] = (),
objective_const: float = 0.0,
has_objective: bool = True,
rows: tuple[LinearRow, ...] = (),
psd: tuple[PsdBlock, ...] = (),
vector_vars: tuple[VectorVarInfo, ...] = (),
matrix_vars: tuple[MatrixVarInfo, ...] = (),
groups: tuple[Group, ...] = (),
)
A complete MISDP in dual form; the contract between all packages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Model name. |
required |
sense
|
('MIN', 'MAX')
|
Objective sense. |
"MIN"
|
variables
|
tuple of VarInfo
|
Scalar variables; position = variable index. |
required |
objective
|
tuple of (int, float)
|
Objective coefficients, sorted by variable index, nonzero. |
()
|
objective_const
|
float
|
Constant term of the objective. |
0.0
|
has_objective
|
bool
|
|
True
|
rows
|
tuple of LinearRow
|
Scalar constraints, grouped by cone in the order |
()
|
psd
|
tuple of PsdBlock
|
PSD constraints. |
()
|
vector_vars
|
tuple
|
Structure of vector and matrix variables (metadata). |
()
|
matrix_vars
|
tuple
|
Structure of vector and matrix variables (metadata). |
()
|
groups
|
tuple of Group
|
Constraint groups (metadata). |
()
|
Notes
Building a ProblemIR does not check it; call
validate.
validate ¶
validate() -> None
Check that the IR is well formed.
The invariants are: variable indices are in range (I1); objective and row
coefficients are sorted by variable, unique, nonzero and finite, and the
objective and row constants are finite (I2); PSD entries are sorted,
unique, nonzero, finite and in the lower triangle (I3); bounds are valid,
and finite bounds of integer variables are integral (I4); names are unique
within each kind, and no vector or matrix variable has the name of a
variable (I5); vector and matrix variables cover disjoint index ranges with
matching entry names (I6); group indices are valid and each row or block is
in at most one group (I7); a feasibility problem has no objective data
(I8); PSD blocks and matrix variables have size at least 1, and a PSD block
at most 1413, the largest that a CBF file of misdp holds (I9); rows are
grouped by cone in the order L=, L+, L- (I10).
All problems are collected before raising. Each problem starts with the
invariant it violates ("I3: ..."), or with "Types: ..." when a
field has the wrong type.
Raises:
| Type | Description |
|---|---|
IRValidationError
|
If at least one invariant is violated; |
equivalent ¶
equivalent(
other: ProblemIR,
*,
tol: float = 1e-09,
match_by: Literal["index", "name"] = "index",
ignore_row_order: bool = False,
compare_names: bool = False,
) -> bool
Return whether two IRs describe the same problem.
Both IRs should be valid (see validate).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
ProblemIR
|
The IR to compare with. |
required |
tol
|
float
|
Floats |
1e-09
|
match_by
|
('index', 'name')
|
|
"index"
|
ignore_row_order
|
bool
|
Compare the rows of each cone and the PSD blocks as multisets, with the same tolerance as the ordered comparison. Matching is greedy. |
False
|
compare_names
|
bool
|
Also compare the model name, row and block names, variable names
(with |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
|
diff ¶
diff(
other: ProblemIR,
*,
tol: float = 1e-09,
match_by: Literal["index", "name"] = "index",
ignore_row_order: bool = False,
compare_names: bool = False,
) -> list[str]
Describe the differences between two IRs, one line each.
Takes the same options as
equivalent, and returns an empty list exactly
when it returns True. Meant for test failure messages; at most about
100 lines are returned.
Returns:
| Type | Description |
|---|---|
list of str
|
Human-readable differences; |
summary ¶
summary() -> dict[str, Any]
Return key figures of the problem.
The IR must be valid; on an invalid one (for example an int bound beyond
the float range) it may raise a plain OverflowError. Call validate
first for an IR that was not built by misdp.
Returns:
| Type | Description |
|---|---|
dict
|
Keys |
to_dict ¶
to_dict() -> dict[str, Any]
Convert the IR to a JSON-safe dictionary.
The IR must be valid, as for summary: call validate first for an IR
that was not built by misdp.
Tuples become lists. Infinite and NaN floats become the strings
"inf", "-inf" and "nan", so the result passes
json.dumps(..., allow_nan=False). The key ir_version (currently
1) identifies the format.
Returns:
| Type | Description |
|---|---|
dict
|
Input for |
from_dict
classmethod
¶
from_dict(data: dict[str, Any]) -> ProblemIR
Build an IR from the output of to_dict (or parsed JSON of it).
Keys with default values in the data classes may be omitted. Unknown
keys are rejected. The result is not validated; call
validate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict
|
Dictionary in the format of |
required |
Returns:
| Type | Description |
|---|---|
ProblemIR
|
The rebuilt IR. |
Raises:
| Type | Description |
|---|---|
IRValidationError
|
If the data does not have the expected shape or types; the single
problem names the offending path, e.g. |
misdp.examples ¶
Example models with their LaTeX formulation and known optimum.
Every example module defines TITLE, REFERENCE, LATEX,
EXPECTED_OPTIMUM (the optimum of build() with its default arguments)
and build(...) -> Model. REGISTRY maps the example name to its module.
Examples:
>>> from misdp.examples import REGISTRY
>>> REGISTRY["beispiel_a"].EXPECTED_OPTIMUM
4.0
beispiel_a ¶
Beispiel A: two integer variables and one 2x2 LMI (optimum 4).
The code compiles to the IR fixture BEISPIEL_A and writes the golden file
beispiel_a.cbf. The LMI says y1, y2 >= 0 and y1 * y2 >= 2.25; the
continuous optimum is 3 at (1.5, 1.5), the integer optimum 4, e.g. at (1, 3).
max_cut ¶
Max-Cut as an MISDP with one binary variable per node pair (default: C5, optimum 4).
X = (x_u x_v) for a cut vector x in {-1, 1}^n has unit diagonal, is
PSD, and X_uv = 1 - 2 z_uv where z_uv = 1 iff the edge uv is cut.
Conversely a PSD matrix with unit diagonal and entries in {-1, 1} is
x x^T, so the model is exact. Known optima: triangle 2, C5 4, K4 4.
X is the matrix expression X(z) in the binary variables, not a matrix
variable with linking rows: the same model with fewer variables, and the
brute-force oracle can enumerate it.
build ¶
build(
graph: Any = CYCLE_C5, n: int | None = None
) -> ms.Model
Build the Max-Cut model of graph (unweighted: each cut edge counts 1).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
edge list or networkx graph
|
Edges |
CYCLE_C5
|
n
|
int
|
Number of nodes of an edge list; default: largest node plus one. |
None
|
Returns:
| Type | Description |
|---|---|
Model
|
The model |
stable_set ¶
Stable set example of the project slides (default: path P3, optimum 3).
The code is the slide example; on the default path 0-1-2 it compiles to the IR
fixture STABLE_SET_P3.
Note: X = I satisfies every constraint for every graph, so the optimum is
the number of nodes, not the stability number of the graph (C5 gives 5, not 2).
An exact stable set model needs rank(X) = 1 (out of scope) or a different
formulation.
build ¶
build(
graph: Any = PATH_P3, n: int | None = None
) -> ms.Model
Build the slide's stable set model on graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
edge list or networkx graph
|
Edges |
PATH_P3
|
n
|
int
|
Number of nodes of an edge list; default: largest node plus one. |
None
|
Returns:
| Type | Description |
|---|---|
Model
|
The model |