Skip to content

API: Should we merge addCons and addMatrixCons #1034

@Zeroto521

Description

@Zeroto521

Should we merge addCons and addMatrixCons? Or should we let addMatrixCons's cons argument accept ExprCons?
Because MatrixExprCons supports .sum(axis=0) now, and the result could be a MatrixExprCons or a scalar.

from pyscipopt import ExprCons, MatrixExprCons, Model

model = Model()

m = 1  # I don't know the specific value, it is from outside. 
n = 1  # as above
x = model.addMatrixVar((m, n), "x", "I")
y = model.addMatrixVar((m, n), "y", "I")

# I want to compare the result of summing row values
model.addMatrixCons(x.sum(axis=0) == y.sum(axis=0))
# But this raises an error, because `x.sum(axis=0)` is `(1, 1)` shape, and it will be changed to a scalar to compare.

# AssertionError                            Traceback (most recent call last)
# Cell In[9], line 1
# ----> 1 model.addMatrixCons(x.sum(axis=0) == y.sum(axis=0))

# File src/pyscipopt/scip.pxi:5774, in pyscipopt.scip.Model.addMatrixCons()

# AssertionError: given constraint is not MatrixExprCons but ExprCons

Based on this case, I needed to add a helper function.
And I thought the answer to the title question was.

from pyscipopt import (
    Constraint,
    ExprCons,
    MatrixConstraint,
    MatrixExprCons,
    Model,
)

def addCons(
    model: Model, cons: ExprCons | MatrixExprCons, **kwargs
) -> Constraint | MatrixConstraint:
    """
    A helper function to add constraints to the model.
    This function handles both ExprCons and MatrixExprCons types.
    """
    if isinstance(cons, ExprCons):
        return model.addCons(cons, **kwargs)
    elif isinstance(cons, MatrixExprCons):
        return model.addMatrixCons(cons, **kwargs)
    raise TypeError(f"Unsupported constraint type: {type(cons)}")

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions