Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion ci/312-latest.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,5 @@ dependencies:
- xarray
- pip
- pip:
- pulp<4
- pulp
- highspy
3 changes: 2 additions & 1 deletion ci/313-latest.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,5 @@ dependencies:
- xarray
- pip
- pip:
- pulp<4
- pulp
- highspy
3 changes: 2 additions & 1 deletion ci/314-latest.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,5 @@ dependencies:
- xarray
- pip
- pip:
- pulp<4
- pulp
- highspy
82 changes: 72 additions & 10 deletions libpysal/graph/_matching.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
)

Expand All @@ -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
Expand Down
10 changes: 10 additions & 0 deletions libpysal/graph/tests/test_matching.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading