improve python exprs

This commit is contained in:
Laurent Perron
2025-06-12 11:52:00 +02:00
parent 43c874a733
commit 7d58c118f6
5 changed files with 59 additions and 7 deletions

View File

@@ -460,6 +460,26 @@ PYBIND11_MODULE(model_builder_helper, m) {
return expr->AddFloat(cst);
},
py::arg("cst"), "Returns `self` + `cst`.")
.def(
"__iadd__",
[](py::object self,
std::shared_ptr<LinearExpr> other) -> std::shared_ptr<LinearExpr> {
std::shared_ptr<SumArray> expr =
self.cast<std::shared_ptr<SumArray>>();
expr->AddInPlace(other);
return expr;
},
py::arg("other").none(false),
"Returns the sum of `self` and `other`.")
.def(
"__iadd__",
[](py::object self, double cst) -> std::shared_ptr<LinearExpr> {
std::shared_ptr<SumArray> expr =
self.cast<std::shared_ptr<SumArray>>();
expr->AddFloatInPlace(cst);
return expr;
},
py::arg("cst"), "Returns `self` + `cst`.")
.def("__radd__", &LinearExpr::Add, py::arg("other").none(false),
"Returns `self` + `other`.")
.def(
@@ -502,6 +522,25 @@ PYBIND11_MODULE(model_builder_helper, m) {
return expr->SubFloat(cst);
},
py::arg("cst"), "Returns `self` - `cst`.")
.def(
"__isub__",
[](py::object self,
std::shared_ptr<LinearExpr> other) -> std::shared_ptr<LinearExpr> {
std::shared_ptr<SumArray> expr =
self.cast<std::shared_ptr<SumArray>>();
expr->AddInPlace(other->Neg());
return expr;
},
py::arg("other").none(false), "Returns `self` - `other`.")
.def(
"__isub__",
[](py::object self, double cst) -> std::shared_ptr<LinearExpr> {
std::shared_ptr<SumArray> expr =
self.cast<std::shared_ptr<SumArray>>();
expr->AddFloatInPlace(-cst);
return expr;
},
py::arg("cst"), "Returns `self` - `cst`.")
.def_property_readonly(
"num_exprs", &SumArray::num_exprs,
"Returns the number of linear expressions in the sum.")

View File

@@ -364,6 +364,20 @@ ENDATA
c5 = x - y == 3
self.assertEqual(str(c5), "(x - y) == 3")
def test_large_iadd(self):
model = mb.Model()
s = 0
for _ in range(300000):
s += model.new_bool_var("")
model.add(s == 10)
def test_large_isub(self):
model = mb.Model()
s = 0
for _ in range(300000):
s -= model.new_bool_var("")
model.add(s == 10)
def test_variables(self):
model = mb.Model()
x = model.new_int_var(0.0, 4.0, "x")