-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Fix suboptimal assignment in cell-matching Hungarian algorithm #10654
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
winklemad
wants to merge
3
commits into
marimo-team:main
Choose a base branch
from
winklemad:fix/hungarian-optimal-cell-matching
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+222
−72
Draft
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| # Copyright 2026 Marimo. All rights reserved. | ||
| from __future__ import annotations | ||
|
|
||
| import itertools | ||
| import random | ||
|
|
||
| from marimo._utils.cell_matching import ( | ||
| _hungarian_algorithm, | ||
| match_cell_ids_by_similarity, | ||
| ) | ||
|
|
||
|
|
||
| def _assignment_cost(scores: list[list[float]], result: list[int]) -> float: | ||
| """Total cost of the matching returned by _hungarian_algorithm. | ||
|
|
||
| `result[column] = row`; raises if the matching is not a permutation. | ||
| """ | ||
| n = len(scores) | ||
| col_to_row = {j: result[j] for j in range(n) if result[j] != -1} | ||
| assert len(col_to_row) == n, "matching is not complete" | ||
| assert len(set(col_to_row.values())) == n, "matching is not a permutation" | ||
| return sum(scores[row][col] for col, row in col_to_row.items()) | ||
|
|
||
|
|
||
| def _brute_force_optimal(scores: list[list[float]]) -> float: | ||
| n = len(scores) | ||
| return min( | ||
| sum(scores[i][perm[i]] for i in range(n)) | ||
| for perm in itertools.permutations(range(n)) | ||
| ) | ||
|
|
||
|
|
||
| def test_hungarian_empty() -> None: | ||
| assert _hungarian_algorithm([]) == [] | ||
|
|
||
|
|
||
| def test_hungarian_single() -> None: | ||
| assert _hungarian_algorithm([[5.0]]) == [0] | ||
|
|
||
|
|
||
| def test_hungarian_known_suboptimal_case() -> None: | ||
| # Regression test: the previous covering heuristic returned a cost-17 | ||
| # assignment here; the optimal cost is 13. | ||
| scores = [ | ||
| [7.0, 7.0, 8.0], | ||
| [3.0, 5.0, 3.0], | ||
| [3.0, 7.0, 4.0], | ||
| ] | ||
| result = _hungarian_algorithm(scores) | ||
| assert _assignment_cost(scores, result) == 13.0 | ||
| assert _assignment_cost(scores, result) == _brute_force_optimal(scores) | ||
|
|
||
|
|
||
| def test_hungarian_matches_brute_force() -> None: | ||
| # The assignment must be optimal for every matrix, not merely valid. | ||
| rng = random.Random(20260825) | ||
| for _ in range(500): | ||
| n = rng.randint(1, 6) | ||
| scores = [ | ||
| [float(rng.randint(0, 9)) for _ in range(n)] for _ in range(n) | ||
| ] | ||
| result = _hungarian_algorithm([row[:] for row in scores]) | ||
| assert _assignment_cost(scores, result) == _brute_force_optimal(scores) | ||
|
|
||
|
|
||
| def test_hungarian_handles_negative_and_float_costs() -> None: | ||
| rng = random.Random(1234) | ||
| for _ in range(200): | ||
| n = rng.randint(1, 5) | ||
| scores = [[rng.uniform(-5.0, 5.0) for _ in range(n)] for _ in range(n)] | ||
| result = _hungarian_algorithm([row[:] for row in scores]) | ||
| assert ( | ||
| abs( | ||
| _assignment_cost(scores, result) - _brute_force_optimal(scores) | ||
| ) | ||
| < 1e-9 | ||
| ) | ||
|
|
||
|
|
||
| def test_match_cell_ids_identical_notebook() -> None: | ||
| data = {"a": "x = 1", "b": "y = 2", "c": "z = 3"} | ||
| assert match_cell_ids_by_similarity(dict(data), dict(data)) == { | ||
| "a": "a", | ||
| "b": "b", | ||
| "c": "c", | ||
| } | ||
|
|
||
|
|
||
| def test_match_cell_ids_prefers_most_similar() -> None: | ||
| # Every cell was edited (no exact matches), so matching falls back to the | ||
| # similarity assignment. Each next cell should keep the id of the prev cell | ||
| # it most closely resembles. | ||
| prev = { | ||
| "imp": "import pandas as pd", | ||
| "tot": "x = compute_total(data)", | ||
| "plt": "df.plot(kind='bar')", | ||
| } | ||
| nxt = { | ||
| "n_plt": "df.plot(kind='line')", | ||
| "n_tot": "x = compute_total(rows)", | ||
| "n_imp": "import polars as pd", | ||
| } | ||
| mapping = match_cell_ids_by_similarity(dict(prev), dict(nxt)) | ||
| assert mapping == {"plt": "n_plt", "tot": "n_tot", "imp": "n_imp"} | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If this takes more than a second, I'd like to reduce this