diff --git a/doc/release-notes.md b/doc/release-notes.md index a1c3ff1e..a48348a0 100644 --- a/doc/release-notes.md +++ b/doc/release-notes.md @@ -149,6 +149,7 @@ linopy 1.0 makes the strict arithmetic convention the only behaviour and puts de *Solvers* +- `solve`, `to_file` and `Model.restrict` raise for a constraint row without a nonzero term that cannot hold, e.g. `0 * x >= 5`, instead of leaving it out and solving "optimal". ([\#1175](https://github.com/PyPSA/linopy/pull/1175)) - With `add_objective(..., scaling=...)`, the solve log reports objective and dual bound in model units. ([\#1077](https://github.com/PyPSA/linopy/issues/1077)) - CPLEX: "optimal with unscaled infeasibilities" is reported as `imprecise` and its solution is imported. ([\#368](https://github.com/PyPSA/linopy/issues/368)) - HiGHS: a solve that stops at a limit without a solution no longer returns all-zero values, and a MIP no longer returns all-zero duals. `log_fn` and solver options also apply to a re-solve of a direct-API model. ([\#1130](https://github.com/PyPSA/linopy/issues/1130)) diff --git a/linopy/common.py b/linopy/common.py index bddd5e5c..c2ec6e8f 100644 --- a/linopy/common.py +++ b/linopy/common.py @@ -1250,6 +1250,21 @@ def is_constant(x: SideLike) -> bool: ) +def unsatisfied( + rhs: np.ndarray, sense: np.ndarray, tol: float | np.ndarray +) -> np.ndarray: + """ + Per row, whether ``0 sense rhs`` fails by more than ``tol``. + + ``sense`` holds one character per row: ``"="``, ``"<"`` or ``">"``. + """ + return ( + ((sense == "=") & (np.abs(rhs) > tol)) + | ((sense == "<") & (rhs < -tol)) + | ((sense == ">") & (rhs > tol)) + ) + + def values_to_lookup_array( values: np.ndarray, labels: np.ndarray, size: int | None = None ) -> np.ndarray: diff --git a/linopy/constants.py b/linopy/constants.py index 4a1c9758..54f4acab 100644 --- a/linopy/constants.py +++ b/linopy/constants.py @@ -18,6 +18,8 @@ GREATER_EQUAL = ">=" LESS_EQUAL = "<=" +DROPPED_ROW_TOL = 1e-9 + class PerformanceWarning(UserWarning): """Warning raised when an operation triggers expensive Dataset reconstruction.""" diff --git a/linopy/constraints.py b/linopy/constraints.py index 87eae77b..a5558ee1 100644 --- a/linopy/constraints.py +++ b/linopy/constraints.py @@ -62,9 +62,11 @@ skip_full_indexers, slice_indexers, to_dataframe, + unsatisfied, ) from linopy.config import options from linopy.constants import ( + DROPPED_ROW_TOL, EQUAL, GREATER_EQUAL, HELPER_DIMS, @@ -1007,6 +1009,18 @@ def active_row_mask(self) -> np.ndarray: """Boolean mask over raveled rows: label set and at least one variable present.""" return (self._label_values() != -1) & self._lhs._store.has_terms() + def unsatisfiable_empty_rows(self) -> np.ndarray: + """ + Boolean mask over raveled rows: label set, no nonzero term, and + ``0 sign rhs`` fails. + """ + sense = self.sign.values.ravel().astype("U1") + rows = self._label_values() != -1 + rows &= unsatisfied(self.rhs.values.ravel(), sense, DROPPED_ROW_TOL) + if rows.any(): + rows[rows] = ~self._lhs._store.has_live_terms(rows) + return rows + def active_labels(self) -> np.ndarray: """Active constraint labels in build order, without building the CSR.""" return self._label_values()[self.active_row_mask()] @@ -1522,6 +1536,26 @@ def sanitize_infinities(self) -> None: for con in self.data.values(): con.sanitize_infinities() + def check_empty_rows(self) -> None: + """ + Raise for a row without a nonzero term whose ``0 sign rhs`` fails. + + Matrices and LP files leave such rows out, so the solver would never + see them. Rows without a nonzero term that hold are left out silently. + """ + for con in self.data.values(): + if con.is_indicator: + continue + rows = con.unsatisfiable_empty_rows() + if rows.any(): + labels = con._label_values()[rows] + raise ValueError( + f"Constraint `{con.name}` has {labels.size} row(s) without a " + f"nonzero term that cannot hold, first: " + f"{self.format_labels(labels[:1])}. Fix their coefficients " + "or right-hand side, or mask them." + ) + def format_labels( self, values: Sequence[int], display_max_terms: int | None = None ) -> str: diff --git a/linopy/csr.py b/linopy/csr.py index 7e3893cb..2c86ee8a 100644 --- a/linopy/csr.py +++ b/linopy/csr.py @@ -583,6 +583,15 @@ def terms( counts -= np.bincount(rows, minlength=self.n_cells).astype(counts.dtype) return counts, self.csr.indices[keep], data[keep] + def has_live_terms(self, cells: np.ndarray) -> np.ndarray: + indptr = self.csr.indptr + counts = np.diff(indptr) + zeros = np.flatnonzero(self.csr.data == 0) + if zeros.size: + rows = np.searchsorted(indptr, zeros, side="right") - 1 + counts = counts - np.bincount(rows, minlength=self.n_cells) + return counts[cells] > 0 + def variable_labels(self) -> np.ndarray: return self.csr.indices diff --git a/linopy/io.py b/linopy/io.py index 139683a8..38c9b952 100644 --- a/linopy/io.py +++ b/linopy/io.py @@ -812,6 +812,8 @@ def to_file( if progress is None: progress = m._xCounter > 10_000 + m.constraints.check_empty_rows() + if io_api == "lp" or io_api == "lp-polars": to_lp_file( m, diff --git a/linopy/model.py b/linopy/model.py index ba07b436..aaba27ed 100644 --- a/linopy/model.py +++ b/linopy/model.py @@ -46,6 +46,7 @@ to_path, ) from linopy.constants import ( + DROPPED_ROW_TOL, FACTOR_DIM, GREATER_EQUAL, LESS_EQUAL, @@ -92,7 +93,6 @@ add_piecewise_formulation, ) from linopy.remote import RemoteHandler -from linopy.restrict.matrix import DROPPED_ROW_TOL from linopy.scaling import scalar_scaling, validate_scaling from linopy.semantics import check_user_nan, enforce_no_multiindex from linopy.solver_capabilities import solver_supports @@ -2205,6 +2205,7 @@ def solve( "`m.add_objective(...)` first (e.g. `m.add_objective(0 * x)` " "for a pure feasibility problem)." ) + self.constraints.check_empty_rows() solved = remote.solve_on_remote( self, solver_name=solver_name, @@ -2620,6 +2621,8 @@ def _mock_solve( if sanitize_infinities: self.constraints.sanitize_infinities() + self.constraints.check_empty_rows() + self.objective._value = 0.0 self.status = "ok" self.termination_condition = TerminationCondition.optimal.value diff --git a/linopy/restrict/matrix.py b/linopy/restrict/matrix.py index e8d3c68b..57ebb43c 100644 --- a/linopy/restrict/matrix.py +++ b/linopy/restrict/matrix.py @@ -22,20 +22,20 @@ import numpy as np import pandas as pd import scipy.sparse +from numpy.typing import DTypeLike from xarray import DataArray from xarray.indexes import PandasIndex from linopy.alignment import as_dataarray -from linopy.common import lookup_table +from linopy.common import lookup_table, unsatisfied +from linopy.constants import DROPPED_ROW_TOL from linopy.csr import indptr_from_counts, repeat_per_row from linopy.matrices import Matrices if TYPE_CHECKING: from linopy.model import Model -__all__ = ["DROPPED_ROW_TOL", "MatrixWindow", "RestrictionError"] - -DROPPED_ROW_TOL = 1e-9 +__all__ = ["MatrixWindow", "RestrictionError"] class RestrictionError(ValueError): @@ -102,12 +102,16 @@ def _select(containers: Any, indexers: _Indexers) -> dict[str, DataArray]: return selected +def _flat(selected: dict[str, DataArray], dtype: DTypeLike) -> np.ndarray: + """The selected labels of all containers, raveled, in container order.""" + empty = np.empty(0, dtype=dtype) + return np.concatenate([empty, *(lab.values.ravel() for lab in selected.values())]) + + def _positions( - selected: dict[str, DataArray], label_to_pos: np.ndarray, distinct: bool + flat: np.ndarray, label_to_pos: np.ndarray, distinct: bool ) -> np.ndarray: """Parent matrix positions of the selected active labels, in container order.""" - empty = np.empty(0, dtype=label_to_pos.dtype) - flat = np.concatenate([empty, *(lab.values.ravel() for lab in selected.values())]) positions = _active_positions(flat, label_to_pos) if not distinct and np.unique(positions).size != positions.size: raise RestrictionError("Cannot restrict model: the selection repeats labels.") @@ -146,28 +150,24 @@ def _equal(value: DataArray, indexes: dict[str, pd.Index]) -> bool: ) -def _check_dropped( - rhs: np.ndarray, - sense: np.ndarray, - magnitude: np.ndarray, - clabels: np.ndarray, - tol: float, -) -> None: - """Raise when a row that lost every term violates its sign beyond ``tol``.""" - tolerance = tol * np.maximum(1.0, magnitude) - violated = ( - ((sense == "=") & (np.abs(rhs) > tolerance)) - | ((sense == "<") & (rhs < -tolerance)) - | ((sense == ">") & (rhs > tolerance)) +def _empty_rows(model: Model) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + Labels, right-hand sides and signs of the labelled rows without a term, + which the model's matrices leave out. + """ + labels, rhs, sense = [], [], [] + for con in model.constraints.data.values(): + own = con.labels.values.ravel() + rows = (own != -1) & ~con.active_row_mask() + labels.append(own[rows]) + rhs.append(con.rhs.values.ravel()[rows]) + sense.append(con.sign.values.ravel()[rows].astype("U1")) + dtype = model._dtypes["labels"] + return ( + np.concatenate([np.empty(0, dtype=dtype), *labels]), + np.concatenate([np.empty(0), *rhs]), + np.concatenate([np.empty(0, dtype="U1"), *sense]), ) - if violated.any(): - raise RestrictionError( - "Cannot window the matrices: folding the dangling terms makes " - f"constraint labels {clabels[violated].tolist()} unsatisfiable " - f"(folded rhs {rhs[violated].tolist()} against sign " - f"{sense[violated].tolist()}). Raise `tol` or exclude the rows " - "via `drop`." - ) class MatrixWindow: @@ -197,6 +197,7 @@ def __init__(self, model: Model) -> None: raise NotImplementedError("Matrix windows require at least one constraint.") self._model = model self._matrices = matrices + self._empty = _empty_rows(model) self._A = matrices.A frame = {f.name: vars(matrices)[f.name] for f in fields(Matrices)} self._frame = Matrices(**{**frame, "A": None}) @@ -217,7 +218,8 @@ def select( ``fix`` maps variable names to the values of out-of-window terms, which are folded into the right-hand side at their actual coefficient; a row that loses every term is dropped when its folded right-hand side - satisfies its sign within ``tol``, relative to the folded magnitude. + satisfies its sign within ``tol``, relative to the folded magnitude. A + selected row without any term in the parent is checked alike. ``drop`` maps constraint names to boolean masks of rows removed from the window before folding. @@ -236,13 +238,19 @@ def select( indexers = _Indexers(selection) variables = _select(m.variables, indexers) constraints = _select(m.constraints, indexers) + dtype = m._dtypes["labels"] cols = _positions( - variables, m.variables.label_index.label_to_pos, indexers.distinct + _flat(variables, dtype), + m.variables.label_index.label_to_pos, + indexers.distinct, ) + clabels = _flat(constraints, dtype) rows = _positions( - constraints, m.constraints.label_index.label_to_pos, indexers.distinct + clabels, m.constraints.label_index.label_to_pos, indexers.distinct ) - rows = rows[~self._excluded(drop)[rows]] + excluded = self._excluded(drop) + rows = rows[~excluded[mat.clabels[rows]]] + self._check_empty(clabels, excluded, tol) if not cols.size: raise RestrictionError( f"Cannot restrict model: the selection {dict(selection)} is empty." @@ -273,7 +281,7 @@ def select( keep = counts > 0 magnitude = np.bincount(outer_rows, np.abs(folded), minlength=rows.size) dropped = rows[~keep] - _check_dropped( + self._check_dropped( rhs[~keep], mat.sense[dropped], magnitude[~keep], mat.clabels[dropped], tol ) indptr = indptr_from_counts(counts[keep], A.indptr.dtype) @@ -301,10 +309,39 @@ def _fixed(self, fix: Mapping[str, Any] | None, cols: np.ndarray) -> np.ndarray: values[own] = aligned[labels[own] - start] return values * mat.var_scaling[cols] + def _check_dropped( + self, + rhs: np.ndarray, + sense: np.ndarray, + magnitude: np.ndarray, + clabels: np.ndarray, + tol: float, + ) -> None: + """Raise when a row without a term in the window violates its sign beyond ``tol``.""" + violated = unsatisfied(rhs, sense, tol * np.maximum(1.0, magnitude)) + if violated.any(): + first = self._model.constraints.format_labels(clabels[violated][:1]) + raise RestrictionError( + "Cannot window the matrices: constraint labels " + f"{clabels[violated].tolist()} have no term in the window and " + f"are unsatisfiable (rhs {rhs[violated].tolist()} against sign " + f"{sense[violated].tolist()}), first: {first}. Raise `tol` or " + "exclude the rows via `drop`." + ) + + def _check_empty( + self, clabels: np.ndarray, excluded: np.ndarray, tol: float + ) -> None: + """Raise for a selected row without a term that ``drop`` keeps and that fails.""" + labels, rhs, sense = self._empty + kept = np.isin(labels, clabels) & ~excluded[labels] + magnitude = np.zeros(int(kept.sum())) + self._check_dropped(rhs[kept], sense[kept], magnitude, labels[kept], tol) + def _excluded(self, drop: Mapping[str, Any] | None) -> np.ndarray: - """Whether each parent row is excluded by ``drop``, by matrix position.""" + """Whether each parent row is excluded by ``drop``, by constraint label.""" constraints = self._model.constraints - excluded = np.zeros(self._matrices.clabels.size, dtype=bool) + excluded = np.zeros(self._model._cCounter, dtype=bool) for name, given in (drop or {}).items(): if name not in constraints: raise RestrictionError( @@ -317,6 +354,6 @@ def _excluded(self, drop: Mapping[str, Any] | None) -> np.ndarray: raise RestrictionError( f"{what} must be boolean, got dtype {mask.dtype}." ) - label_to_pos = constraints.label_index.label_to_pos - excluded[_active_positions(labels.values[mask], label_to_pos)] = True + dropped = labels.values[mask] + excluded[dropped[dropped != -1]] = True return excluded diff --git a/linopy/restrict/window.py b/linopy/restrict/window.py index 40870054..50d50656 100644 --- a/linopy/restrict/window.py +++ b/linopy/restrict/window.py @@ -17,7 +17,8 @@ from xarray import DataArray from linopy.common import to_path -from linopy.restrict.matrix import DROPPED_ROW_TOL, MatrixWindow, RestrictionError +from linopy.constants import DROPPED_ROW_TOL +from linopy.restrict.matrix import MatrixWindow, RestrictionError if TYPE_CHECKING: from linopy.constants import Result, Solution diff --git a/linopy/solvers.py b/linopy/solvers.py index 449ca314..6b811485 100644 --- a/linopy/solvers.py +++ b/linopy/solvers.py @@ -1008,6 +1008,7 @@ def _build_direct( """Build the native solver model from the matrices of ``self.model``.""" model = self.model assert model is not None + model.constraints.check_empty_rows() M = model.matrices names = ( linopy.io.get_printers_scalar( @@ -1233,6 +1234,7 @@ def _apply_locked( if isinstance(diff, RebuildReason): self._fall_back_to_rebuild(diff, rebuild, disallow_rebuild) return diff + model.constraints.check_empty_rows() n_vars = model.variables.label_index.n_active_vars n_cons = model.constraints.label_index.n_active_cons if self._apply_or_rebuild(diff, n_vars, n_cons, rebuild, disallow_rebuild): diff --git a/linopy/store.py b/linopy/store.py index 3ff09b15..6939ca95 100644 --- a/linopy/store.py +++ b/linopy/store.py @@ -210,6 +210,13 @@ def terms( per-term index. """ + @abstractmethod + def has_live_terms(self, cells: np.ndarray) -> np.ndarray: + """ + Per cell selected by the boolean ``cells``, whether it holds a term + with a label and a nonzero coefficient. + """ + @abstractmethod def variable_labels(self) -> np.ndarray: """ @@ -757,6 +764,12 @@ def terms( counts = np.count_nonzero(keep, axis=-1).reshape(-1) return counts, vars_[keep], coeffs[keep] + def has_live_terms(self, cells: np.ndarray) -> np.ndarray: + coeffs, vars_ = self._term_views() + live = vars_ != -1 + live &= coeffs != 0 + return live.any(axis=-1).reshape(-1)[cells] + def variable_labels(self) -> np.ndarray: return self.ds.vars.values.ravel() diff --git a/test/test_io.py b/test/test_io.py index 6550a990..96763532 100644 --- a/test/test_io.py +++ b/test/test_io.py @@ -870,6 +870,19 @@ def test_to_file_rejects_mismatched_extension( assert not (tmp_path / fn).exists() +@pytest.mark.parametrize( + "io_api,fn", + [("lp", "problem.lp"), ("lp-polars", "problem.lp"), ("mps", "problem.mps")], +) +def test_to_file_raises_for_empty_row_that_cannot_hold( + model: Model, tmp_path: Path, io_api: str, fn: str +) -> None: + model.add_constraints(0 * model.variables["x"] >= 5, name="con") + with pytest.raises(ValueError, match=r"cannot hold, first: con\[0\]"): + model.to_file(tmp_path / fn, io_api=io_api) + assert not (tmp_path / fn).exists() + + def test_to_blocks(tmp_path: Path) -> None: m: Model = Model() diff --git a/test/test_optimization.py b/test/test_optimization.py index bb4b9fcc..67c8e055 100644 --- a/test/test_optimization.py +++ b/test/test_optimization.py @@ -10,6 +10,7 @@ import itertools import logging from typing import Any +from unittest.mock import Mock import numpy as np import pandas as pd @@ -17,9 +18,10 @@ import xarray as xr from xarray.testing import assert_allclose, assert_equal -from linopy import GREATER_EQUAL, LESS_EQUAL, Model, solvers +from linopy import GREATER_EQUAL, LESS_EQUAL, Model, Variable, solvers from linopy.common import to_path from linopy.expressions import LinearExpression +from linopy.remote import RemoteHandler from linopy.solver_capabilities import ( get_available_solvers_with_feature, solver_supports, @@ -414,6 +416,95 @@ def test_default_setting_expression_sol_accessor( assert_equal(qexpr.solution, 4 * x.solution * y.solution) +empty_row_params = list( + itertools.product(["lp", "lp-polars", "mps", "direct"], [True, False]) +) + + +def empty_row_model( + coeff: Any, rhs: Any, sign: str = GREATER_EQUAL +) -> tuple[Model, Variable]: + m = Model() + i = pd.RangeIndex(2, name="i") + x = m.add_variables(lower=0, upper=10, coords=[i], name="x") + coeffs = xr.DataArray(coeff, coords=[i]) if isinstance(coeff, list) else coeff + m.add_constraints(coeffs * x, sign, rhs, name="con") + m.add_objective(x.sum()) + return m, x + + +@pytest.mark.skipif("highs" not in licensed_solvers, reason="highs not installed") +@pytest.mark.parametrize("io_api,sanitize_zeros", empty_row_params) +@pytest.mark.parametrize( + "coeff,rows", [([0.0, 1.0], 1), (0, 2)], ids=["zero-coeff", "zero-times-x"] +) +def test_empty_row_that_cannot_hold_raises( + io_api: str, sanitize_zeros: bool, coeff: Any, rows: int +) -> None: + m, _ = empty_row_model(coeff, 5) + match = rf"Constraint `con` has {rows} row\(s\) .*cannot hold, first: con\[0\]" + with pytest.raises(ValueError, match=match): + m.solve("highs", io_api=io_api, sanitize_zeros=sanitize_zeros) + + +@pytest.mark.skipif("highs" not in licensed_solvers, reason="highs not installed") +@pytest.mark.parametrize("sparse", [False, True], ids=["dense", "sparse"]) +@pytest.mark.parametrize("sanitize_zeros", [True, False]) +@pytest.mark.parametrize( + "sign,rhs,holds", + [ + (">=", 5, False), + (">=", -5, True), + ("<=", -5, False), + ("<=", 5, True), + ("==", 1e-8, False), + ("==", 1e-10, True), + ], +) +def test_empty_row_is_checked_against_its_sign( + sign: str, rhs: float, holds: bool, sanitize_zeros: bool, sparse: bool +) -> None: + m, _ = empty_row_model([0.0, 1.0], xr.DataArray([rhs, 1.0], dims="i"), sign) + if sparse: + m.constraints["con"].to_sparse() + if holds: + assert m.solve("highs", sanitize_zeros=sanitize_zeros) == ("ok", "optimal") + return + with pytest.raises(ValueError, match=r"cannot hold, first: con\[0\]"): + m.solve("highs", sanitize_zeros=sanitize_zeros) + + +@pytest.mark.parametrize("remote", [False, True], ids=["mock", "remote"]) +def test_empty_row_that_cannot_hold_raises_before_mock_or_remote_solve( + remote: bool, +) -> None: + m, _ = empty_row_model(0, 5) + handler = Mock(spec=RemoteHandler) + kwargs: dict[str, Any] = {"remote": handler} if remote else {"mock_solve": True} + with pytest.raises(ValueError, match="cannot hold"): + m.solve(**kwargs) + handler.solve_on_remote.assert_not_called() + + +@pytest.mark.skipif("highs" not in licensed_solvers, reason="highs not installed") +def test_constant_row_that_cannot_hold_raises() -> None: + m = Model() + x = m.add_variables(lower=0, name="x") + m.add_constraints(LinearExpression(12, m) == 13, name="con") + m.add_objective(1 * x) + with pytest.raises(ValueError, match=r"Constraint `con` has 1 row\(s\)"): + m.solve("highs") + + +@pytest.mark.skipif("highs" not in licensed_solvers, reason="highs not installed") +@pytest.mark.parametrize("io_api,sanitize_zeros", empty_row_params) +def test_empty_row_that_holds_is_dropped(io_api: str, sanitize_zeros: bool) -> None: + m, x = empty_row_model([0.0, 1.0], xr.DataArray([-5, 5], dims="i")) + status, _ = m.solve("highs", io_api=io_api, sanitize_zeros=sanitize_zeros) + assert status == "ok" + np.testing.assert_allclose(x.solution.values, [0, 5]) + + @pytest.mark.parametrize("solver,io_api,explicit_coordinate_names", params) def test_constant_expression_in_constraint( model_with_constant_expression: Model, diff --git a/test/test_persistent_apply_update.py b/test/test_persistent_apply_update.py index b481cbfb..55d44ef2 100644 --- a/test/test_persistent_apply_update.py +++ b/test/test_persistent_apply_update.py @@ -4,6 +4,7 @@ import numpy as np import pytest +import xarray as xr from linopy import Model from linopy.persistent import RebuildReason @@ -206,6 +207,27 @@ def test_cross_model_in_place(solver_name: str) -> None: assert np.isclose(cross_obj, _obj(m3)) +@pytest.mark.parametrize("solver_name", SOLVER_PARAMS) +@pytest.mark.parametrize( + "sign,rhs,update", + [(">=", -5.0, {"rhs": 5.0}), ("<=", 5.0, {"sign": ">="})], + ids=["rhs", "sign"], +) +def test_update_raises_for_dropped_row_that_cannot_hold( + solver_name: str, sign: str, rhs: float, update: dict[str, Any] +) -> None: + m = _base_model() + x = m.variables["x"] + m.add_constraints(xr.DataArray([0, 1, 1]) * x, sign, rhs, name="c3") + m.constraints.sanitize_zeros() + s = _built(solver_name, m) + s.solve(assign=True) + + m.constraints["c3"].update(**update) + with pytest.raises(ValueError, match=r"cannot hold, first: c3\[0\]"): + s.solve(m) + + @pytest.mark.parametrize("solver_name", SOLVER_PARAMS) def test_sign_flip(solver_name: str) -> None: m = _base_model() diff --git a/test/test_restrict_matrix.py b/test/test_restrict_matrix.py index c9eb5ce6..e73b3af9 100644 --- a/test/test_restrict_matrix.py +++ b/test/test_restrict_matrix.py @@ -157,6 +157,32 @@ def test_folded_residual_passes_within_tol_or_when_dropped( assert window.matrices.clabels.size == 2 +@pytest.mark.parametrize( + ("kwargs", "raises"), + [ + ({"time": TIME[:3]}, True), + ({"time": TIME[1:3]}, False), + ({"time": TIME[:3], "drop": {"pin": TIME == 0}}, False), + ], + ids=["selected", "outside", "dropped"], +) +def test_selected_row_without_terms_is_checked_against_its_sign( + kwargs: dict[str, Any], raises: bool +) -> None: + m = Model() + x = m.add_variables(lower=0, upper=10, coords=[TIME], name="x") + m.add_constraints(xr.DataArray(TIME != 0, coords=[TIME]) * x >= 2, name="pin") + m.add_objective(x.sum()) + m.constraints.sanitize_zeros() + if raises: + with pytest.raises(RestrictionError, match=r"unsatisfiable.*pin\[0\]"): + m.restrict(**kwargs) + return + window = m.restrict(**kwargs).solve(solver_name="highs", output_flag=False) + + assert window.termination_condition == "optimal" + + def test_advance_keeps_the_tolerance() -> None: window = pinned_model("==", 1e-7).restrict(time=TIME[1:3], fix=ZERO_X, tol=1e-6) window.advance(time=TIME[2:4])