diff --git a/ci/312-latest.yaml b/ci/312-latest.yaml index 0b860c1c8..17eac1fa7 100644 --- a/ci/312-latest.yaml +++ b/ci/312-latest.yaml @@ -35,4 +35,5 @@ dependencies: - xarray - pip - pip: - - pulp<4 + - pulp + - highspy diff --git a/ci/313-latest.yaml b/ci/313-latest.yaml index e5e736ac7..f6fb1979f 100644 --- a/ci/313-latest.yaml +++ b/ci/313-latest.yaml @@ -35,4 +35,5 @@ dependencies: - xarray - pip - pip: - - pulp<4 + - pulp + - highspy diff --git a/ci/314-latest.yaml b/ci/314-latest.yaml index 5931d0465..b75389cc3 100644 --- a/ci/314-latest.yaml +++ b/ci/314-latest.yaml @@ -34,4 +34,5 @@ dependencies: - xarray - pip - pip: - - pulp<4 + - pulp + - highspy diff --git a/libpysal/graph/_matching.py b/libpysal/graph/_matching.py index 8c372b8b5..d9c2ebe21 100644 --- a/libpysal/graph/_matching.py +++ b/libpysal/graph/_matching.py @@ -8,6 +8,48 @@ _VALID_GEOMETRY_TYPES = ["Point"] +def _match_variables(pulp, problem, row, col, cat): + """Create one decision variable per candidate match. + + pulp 3.3 added ``pulp.LpProblem.add_variable_dict``, which pulp 4 kept and + older pulp 3 releases lack, so those fall back to ``pulp.LpVariable.dicts``. + Both return a dict keyed by the ``(row, col)`` pair of the match. + """ + indices = list(zip(row, col, strict=True)) + if hasattr(problem, "add_variable_dict"): + return problem.add_variable_dict( + "match_%s_%s", indices=indices, lowBound=0, upBound=1, cat=cat + ) + return pulp.LpVariable.dicts( + "match", lowBound=0, upBound=1, indices=iter(indices), cat=cat + ) + + +def _add_constraint(problem, summand, sense, rhs): + """Add ``summand {>=, <=, ==} rhs`` to `problem` + + The comparison operators are understood by pulp 3 and pulp 4 alike, while + the ``pulp.LpConstraint`` constructor changed signature in pulp 4. + """ + if sense > 0: + problem += summand >= rhs + elif sense < 0: + problem += summand <= rhs + else: + problem += summand == rhs + + +def _solve_status(pulp, status): + """Return the numeric status code and its name. + + pulp 3 returns an integer from ``pulp.LpProblem.solve`` and keeps the names + in ``pulp.LpStatus``; pulp 4 returns a ``pulp.LpSolveStats`` object. + """ + if isinstance(status, int): + return status, pulp.LpStatus[status] + return int(status.status), status.status_str + + def _spatial_matching( x, y=None, @@ -57,6 +99,8 @@ def _spatial_matching( a solver defined by the pulp optimization library. If no solver is provided, pulp's default solver will be used. This is generally pulp.COIN(), but this may vary depending on your configuration. + pulp 4 does not keep a default solver, so the first solver reported + as available is used instead. return_mip : bool (default: False) whether or not to return the instance of the pulp.LpProblem. By default, the problem is not returned to the user. @@ -108,11 +152,11 @@ def _spatial_matching( mp = pulp.LpProblem("optimal-neargraph", sense=pulp.LpMinimize) # a match is as binary decision variable, connecting observation i to observation j - match_vars = pulp.LpVariable.dicts( - "match", - lowBound=0, - upBound=1, - indices=zip(row, col, strict=True), + match_vars = _match_variables( + pulp, + mp, + row, + col, cat="Continuous" if allow_partial_match else "Binary", ) # we want to minimize the geographic distance of links in the graph @@ -145,17 +189,29 @@ def _spatial_matching( ] ) sense = int(not allow_partial_match) - mp += pulp.LpConstraint(summand, sense=sense, rhs=n_matches) + _add_constraint(mp, summand, sense, n_matches) if match_between: # but, we may choose to ignore some sources for i in range(n_sources): summand = pulp.lpSum([match_vars[j, i] for j in range(n_targets)]) - mp += pulp.LpConstraint(summand, sense=-1, rhs=n_matches) + _add_constraint(mp, summand, -1, n_matches) + + if solver is None and pulp.LpSolverDefault is None: + # pulp 4 does not pick a solver on its own, so fall back to whatever + # solver is available rather than failing for lack of a default + available = pulp.listSolvers(onlyAvailable=True) + if available: + solver = getattr(pulp, available[0])() status = mp.solve(solver) + status_code, status_name = _solve_status(pulp, status) + if not hasattr(mp, "sol_status"): + # pulp 4 reports the status only through the object returned by solve(), + # keep exposing it on the problem passed on with return_mip=True + mp.sol_status = status_code - if (status != 1) & (not allow_partial_match): + if (status_code != 1) & (not allow_partial_match): warnings.warn( - f"Problem is {pulp.LpStatus[status]}, so edge weights may be non-integer!", + f"Problem is {status_name}, so edge weights may be non-integer!", stacklevel=2, ) @@ -165,7 +221,13 @@ def _spatial_matching( if not match_between: edges.extend([(*tuple(reversed(edge[:-1])), edge[-1]) for edge in edges]) - heads, tails, weights = map(numpy.asarray, zip(*sorted(edges), strict=True)) + if edges: + heads, tails, weights = map(numpy.asarray, zip(*sorted(edges), strict=True)) + else: + # no match was selected, which happens for an infeasible problem + heads = numpy.asarray([], dtype=int) + tails = numpy.asarray([], dtype=int) + weights = numpy.asarray([], dtype=float) if return_mip: return x_ids[heads], y_ids[tails], weights, mp diff --git a/libpysal/graph/tests/test_matching.py b/libpysal/graph/tests/test_matching.py index f07d55096..7e7fd6968 100644 --- a/libpysal/graph/tests/test_matching.py +++ b/libpysal/graph/tests/test_matching.py @@ -115,3 +115,13 @@ def test_returns_mip(): simple, n_matches=6, return_mip=True, solver=default_solver ) assert mip.sol_status == -1 + + +def test_infeasible_problem_returns_arrays(): + # a pulp 4 solver can leave no selected match behind for an infeasible + # problem, which used to break the unpacking of the resulting edge triple + with pytest.warns(UserWarning, match="Problem is Infeasible"): + heads, tails, weights = _spatial_matching( + simple, n_matches=6, solver=default_solver + ) + assert heads.size == tails.size == weights.size diff --git a/pyproject.toml b/pyproject.toml index 63aac55ef..9fd435339 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -48,7 +48,7 @@ plus = [ "networkx>=3.4", "numba>=0.60", "pandarm>=0.0", - "pulp<4", + "pulp", "pyarrow>=16.1", "sqlalchemy>=2.0", "xarray>=2024.5",