Skip to content

Commit d148224

Browse files
authored
Merge branch 'master' into master
2 parents a4337d5 + be883d5 commit d148224

File tree

3 files changed

+32
-2
lines changed

3 files changed

+32
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
### Fixed
1111
- Raised an error when an expression is used when a variable is required
1212
### Changed
13+
- MatrixExpr.sum() now supports axis arguments and can return either a scalar or MatrixExpr depending on the result dimensions
1314
### Removed
1415

1516
## 5.5.0 - 2025.05.06

src/pyscipopt/matrix.pxi

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,13 @@ def _is_number(e):
1717

1818
class MatrixExpr(np.ndarray):
1919
def sum(self, **kwargs):
20-
return super().sum(**kwargs).item()
21-
20+
"""
21+
Based on `numpy.ndarray.sum`, but returns a scalar if the result is a single value.
22+
This is useful for matrix expressions where the sum might reduce to a single value.
23+
"""
24+
res = super().sum(**kwargs)
25+
return res if res.size > 1 else res.item()
26+
2227
def __le__(self, other: Union[float, int, Variable, np.ndarray, 'MatrixExpr']) -> np.ndarray:
2328

2429
expr_cons_matrix = np.empty(self.shape, dtype=object)

tests/test_matrix_variable.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,30 @@ def test_expr_from_matrix_vars():
164164
for term, coeff in expr_list:
165165
assert len(term) == 3
166166

167+
def test_matrix_sum_argument():
168+
m = Model()
169+
170+
# compare the result of summing 2d array to a scalar with a scalar
171+
x = m.addMatrixVar((2, 3), "x", "I", ub=4)
172+
m.addCons(x.sum() == 24)
173+
174+
# compare the result of summing 2d array to 1d array
175+
y = m.addMatrixVar((2, 4), "y", "I", ub=4)
176+
m.addMatrixCons(x.sum(axis=1) == y.sum(axis=1))
177+
178+
# compare the result of summing 3d array to a 2d array with a 2d array
179+
z = m.addMatrixVar((2, 3, 4), "z", "I", ub=4)
180+
m.addMatrixCons(z.sum(axis=2) == x)
181+
m.addMatrixCons(z.sum(axis=1) == y)
182+
183+
# to fix the element values
184+
m.addMatrixCons(z == np.ones((2, 3, 4)))
185+
186+
m.setObjective(x.sum() + y.sum() + z.sum(), "maximize")
187+
m.optimize()
188+
189+
assert (m.getVal(x) == np.full((2, 3), 4)).all().all()
190+
assert (m.getVal(y) == np.full((2, 4), 3)).all().all()
167191

168192
def test_add_cons_matrixVar():
169193
m = Model()

0 commit comments

Comments
 (0)