Skip to content

Use SciPy MILP for default spatial matching - #940

Open
anshurajbisoyi98-ctrl wants to merge 3 commits into
pysal:mainfrom
anshurajbisoyi98-ctrl:feature-916-scipy-spatial-matching
Open

anshurajbisoyi98-ctrl wants to merge 3 commits into
pysal:mainfrom
anshurajbisoyi98-ctrl:feature-916-scipy-spatial-matching

Conversation

@anshurajbisoyi98-ctrl

@anshurajbisoyi98-ctrl anshurajbisoyi98-ctrl commented Oct 3, 2026 •

Copy link
Copy Markdown

Description

Related to #916.

Default spatial matching currently requires PuLP to construct and solve its optimization problem. This change uses scipy.optimize.milp, which supports the existing within-dataset and between-dataset constraints, multiple matches, and fractional weights. A one-to-one bipartite assignment solver alone cannot cover all of these cases.

The implementation constructs a sparse edge-incidence matrix and preserves the existing objective and degree bounds. Successful default calls no longer need PuLP. Explicit PuLP solvers and return_mip=True continue to use the existing implementation. If SciPy optimization is unsuccessful, the code falls back to PuLP and retains its existing warning behavior. PuLP therefore remains an optional dependency rather than being removed entirely.

Precomputed distances now receive positional IDs, fixing the previously uninitialized IDs in that path. The matching docstrings describe solver selection and fallback requirements.

Validation

  • Complete graph suite on macOS / Python 3.13: 453 passed, zero failures, errors, or skips, with 37 warnings.
  • 14 new cases compare SciPy and PuLP objective values and constraints, test operation without PuLP, preserve input IDs, exercise coincident points and fractional matching, cover precomputed distances, and verify infeasible-solution fallback.
  • Configured Ruff lint and formatting hooks passed; git diff --check passed.
  • Preliminary local timings on four 30-point cases (within/between datasets, integer/fractional weights, k=2) showed approximately 2–14x lower median runtime than PuLP/CBC. These are small-case measurements, not a general performance guarantee.

The installed macOS Pandarm wheel lacked its OpenMP runtime linkage. For the complete graph run, Homebrew's libomp was loaded with ctypes.CDLL(..., mode=ctypes.RTLD_GLOBAL) inside the Python process before calling pytest.main, leaving CBC subprocesses unaffected. No workaround was added to project code. Both travel-network tests passed.

The full project suite, other platforms, and remote CI have not been verified.

CI compatibility

CI and docs environments now use pulp<4, matching the existing optional dependency requirement. This avoids removed PuLP APIs in the compatibility paths and documentation example. Sparse constraint construction uses solver-compatible indices for SciPy 1.14. All 18 matching tests passed locally with both SciPy 1.14.1 and 1.18.1, and every code cell in the matching documentation notebook executed successfully.

Review request

Please review whether using SciPy MILP by default with the PuLP compatibility paths is the intended scope for #916. No maintainer approval of this approach is implied.

Contributor checklist

  • Tests were run locally using pytest.
  • The PR targets the current upstream default branch, main (the template still refers to master).
  • New functionality is covered by docstrings and tests.
  • A reviewer and relevant labels have been assigned.

AI assistance

Codex assisted with investigation, implementation, regression tests and local verification. I take responsibility for the submitted changes and reviewer interactions.

Signed-off-by: Anshu Raj Bisoyi <anshurajbisoyi98@gmail.com>
Signed-off-by: Anshu Raj Bisoyi <anshurajbisoyi98@gmail.com>
Signed-off-by: Anshu Raj Bisoyi <anshurajbisoyi98@gmail.com>
@codecov

codecov Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 86.0%. Comparing base (5773346) to head (8014293).
⚠️ Report is 6 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##            main    #940     +/-   ##
=======================================
+ Coverage   85.9%   86.0%   +0.1%     
=======================================
  Files        151     152      +1     
  Lines      16511   16626    +115     
=======================================
+ Hits       14184   14301    +117     
+ Misses      2327    2325      -2     
Files with missing lines Coverage Δ
libpysal/graph/_matching.py 100.0% <100.0%> (+4.0%) ⬆️
libpysal/graph/base.py 96.0% <ø> (ø)
libpysal/graph/tests/test_matching_scipy.py 100.0% <100.0%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@martinfleis
martinfleis requested a review from ljwolf October 4, 2026 05:56
@sjsrey

sjsrey commented Nov 24, 2026

Copy link
Copy Markdown
Member

Thanks for this, and for the careful write-up and the AI-assistance disclosure.

I checked the SciPy formulation against the existing PuLP model and it matches: within a dataset, integer matching requires at least k matches per point and partial matching exactly k; between datasets, each target gets at least k and each source at most k; bounds are 0–1, and edge order is the same as before. On random 60×80 point sets covering all 8 combinations of within/between, integer/partial and k=1/3, SciPy and CBC gave identical objectives and identical edge sets, with SciPy 2–10× faster. So the core change looks good to me. A few things before merging:

1. Tie-breaking changes the default output. On a regular 6×6 lattice, SciPy (HiGHS) and CBC return different edge sets for both k=1 and k=2. The total distance is the same, but the graph differs. This means Graph.build_spatial_matches() with default arguments can return a different graph after upgrading. @ljwolf, since you wrote the matching code, are you OK with that? If so, I think it needs a changelog entry and probably a sentence in the docstring saying solutions are not unique when there are ties.

2. The existing known-answer tests don't exercise the new default path. test_correctness_k1 passes solver=default_solver and test_coincident uses return_mip=True, so both still run through PuLP. And test_matching.py skips the whole module when PuLP isn't installed. Could you parametrize those tests over solver=None and move the PuLP import into the tests that need it? Then the hand-worked solutions also check the SciPy path.

3. The infeasibility fallback. When HiGHS reports a problem infeasible, re-solving it with CBC gives the same infeasible result plus a warning and non-integer weights that mean nothing. It also solves large problems twice, and users without PuLP get an ImportError instead of a clear message. I'd lean toward checking result.status and raising (or warning) straight away, and dropping the fallback. That is a behaviour change, so I'd like maintainer input before you do it.

4. Rebase. main has since pinned pulp<4 in the CI and docs environments, so rebasing should remove those file changes from this PR.

Smaller points:

  • test_precomputed_matches passes y=True to switch to two-dataset mode. On a square distance matrix that matches every point to itself (weight 1 on the diagonal), and the test locks that in. Testing y=None (within one dataset) would be more meaningful.
  • selected = values > 0 could keep tiny positive weights like 1e-12 from the LP solver. A small tolerance would be safer.
  • Please add a blank line before the Notes heading in the _spatial_matching docstring so numpydoc parses it.
  • Not from this PR, but while you're in there: the two-dataset branch calls pairwise_distances(x, y, metric=metric) without passing **metric_kwargs.

Keeping PuLP as an optional extra for return_mip and custom solvers seems like the right scope for #916 to me.

@martinfleis

Copy link
Copy Markdown
Member

a changelog entry

@sjsrey which changelog entry? Our changelog is autogenerated from PR titles...

@sjsrey

sjsrey commented Nov 24, 2026

Copy link
Copy Markdown
Member

a changelog entry

@sjsrey which changelog entry? Our changelog is autogenerated from PR titles...

Good point. I think a note in the docstring should suffice.

@ljwolf

ljwolf commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

In principle, I think this is the right move. I think we should explore using scipy instead of moving to pulp 5---no knock on pulp 5, but using scipy's linear assignment method is more in keeping with the purposes of the library. This renders redundant the other projects to update the matching engine for pulp (#963,#960,#907 and I think #939 will need to be updated).

I would like to see the following. Guide your botnet accordingly.

  1. What is the performance penalty (speed, memory, solution quality) for the scipy implementation over the following test spec? locate points randomly in the unit square.
  • k = 1, 2, 5, 10, 50, 99
  • n = 100, 250, 1000, 5000
  1. If these penalties are not too high, a deprecation framework needs to be implemented for the pulp implementation. return_mip needs to be phased out. I think it would be more useful to build a pulp problem, populate its result with the HiGHS solution, and set it to "solved", rather than allowing two separate problem representation systems to exist at once for a long time.
  2. During this reimplementation, the cross-dataset matching functionality should also be exposed clearly in a separate function, not a private function. It cannot be a "W," but should output a sparse matrix (or maybe a sparse-backed pandas data frame?) encoding the match.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants