Skip to content
Merged
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
10 changes: 3 additions & 7 deletions src/tracksdata/io/_ctc.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,12 +96,14 @@ def _load_tracks_file(tracks_file: Path) -> dict[int, int]:
A dictionary mapping track IDs to their parent track IDs.
"""
tracklet_id_graph = {}
columns = ["tracklet_id", "start", "end", "parent_tracklet_id"]

try:
df = pl.read_csv(
tracks_file,
separator=" ",
has_header=False,
new_columns=columns,
use_pyarrow=True,
)
except pa.ArrowInvalid:
Expand All @@ -110,16 +112,10 @@ def _load_tracks_file(tracks_file: Path) -> dict[int, int]:
tracks_file,
separator=" ",
has_header=False,
new_columns=columns,
use_pyarrow=False,
)

df = df.rename(
{
"column_1": "tracklet_id",
"column_4": "parent_tracklet_id",
}
)

df = df.filter(pl.col("parent_tracklet_id") > 0)

for tracklet_id, parent_tracklet_id in zip(
Expand Down
16 changes: 16 additions & 0 deletions src/tracksdata/io/_test/test_ctc_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,25 @@

from tracksdata.constants import DEFAULT_ATTR_KEYS
from tracksdata.graph import RustWorkXGraph
from tracksdata.io._ctc import _load_tracks_file
from tracksdata.nodes._mask import Mask


@pytest.mark.parametrize(
("contents", "expected"),
[
("7 2 5 0\n", {}),
("9 6 8 7\n", {9: 7}),
("7 2 5 0\n9 6 8 7\n10 6 9 7\n", {9: 7, 10: 7}),
],
)
def test_load_tracks_file(tmp_path: Path, contents: str, expected: dict[int, int]) -> None:
tracks_file = tmp_path / "man_track.txt"
tracks_file.write_text(contents)

assert _load_tracks_file(tracks_file) == expected


@pytest.mark.parametrize("metadata_shape", [True, False])
def test_export_from_ctc_roundtrip(tmp_path: Path, metadata_shape: bool) -> None:
"""Test that exporting and loading CTC format preserves graph structure."""
Expand Down
61 changes: 59 additions & 2 deletions src/tracksdata/solvers/_ilp_solver.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from collections.abc import Sequence

import numpy as np
import polars as pl
from ilpy import (
Expand All @@ -18,6 +20,50 @@
from tracksdata.solvers._base_solver import BaseSolver
from tracksdata.utils._logging import LOG

_DEFAULT_SOLVER_PREFERENCE = (Preference.Gurobi, Preference.Scip)
_PREFERENCE_BY_NAME = {name.lower(): member for name, member in Preference.__members__.items()}
_VALID_PREFERENCE_NAMES = ", ".join(sorted(Preference.__members__))


def _coerce_preference(value: Preference | str) -> Preference:
"""Return the ilpy Preference for a Preference or a backend name."""
if isinstance(value, Preference):
return value
if isinstance(value, str):
key = value.strip().lower()
if key in _PREFERENCE_BY_NAME:
return _PREFERENCE_BY_NAME[key]
if key == "cuopt":
raise ValueError(
"Solver preference 'cuopt' needs ilpy >= 0.6.0, which adds Preference.CuOpt. "
f"The installed ilpy exposes these backends: {_VALID_PREFERENCE_NAMES}."
)
raise ValueError(f"Unknown solver preference {value!r}. Valid backends: {_VALID_PREFERENCE_NAMES}.")
raise TypeError(f"A solver preference must be a Preference or a str, not {type(value).__name__}.")


def _normalize_solver_preference(
solver_preference: Preference | str | Sequence[Preference | str] | None,
) -> list[Preference]:
"""Return the ordered list of backends to try.

None gives the default order. A single value gives a one-item list. A
sequence keeps its order. The list must not be empty.
"""
if solver_preference is None:
return list(_DEFAULT_SOLVER_PREFERENCE)
if isinstance(solver_preference, (Preference, str)):
return [_coerce_preference(solver_preference)]
if isinstance(solver_preference, Sequence):
preferences = [_coerce_preference(value) for value in solver_preference]
if not preferences:
raise ValueError("solver_preference must name at least one backend.")
return preferences
raise TypeError(
"solver_preference must be a Preference, a str, or a sequence of these, "
f"not {type(solver_preference).__name__}."
)


class ILPSolver(BaseSolver):
"""
Expand Down Expand Up @@ -64,6 +110,12 @@ class ILPSolver(BaseSolver):
Optimality gap tolerance (0.0 for exact solutions).
timeout : float | None
Time limit for solving in seconds. If None, no timeout is set.
solver_preference : Preference | str | Sequence[Preference | str] | None, default None
Solver backends to try, in order. The solver uses the first backend that
succeeds and stops. Accepts an ilpy Preference, a backend name as a string
(for example "gurobi", "cuopt", or "scip"), or a sequence of either. A
string is matched to a Preference by name, without case. The name "cuopt"
needs ilpy >= 0.6.0. When None, the order is Gurobi, then SCIP.

Attributes
----------
Expand Down Expand Up @@ -146,6 +198,7 @@ def __init__(
return_solution: bool = True,
gap: float = 0.0,
timeout: float | None = None,
solver_preference: Preference | str | Sequence[Preference | str] | None = None,
):
super().__init__(output_key=output_key, reset=reset, return_solution=return_solution)
self.edge_weight_expr = EdgeAttr(edge_weight)
Expand All @@ -157,6 +210,7 @@ def __init__(
self.num_threads = num_threads
self.gap = gap
self.timeout = timeout
self._solver_preference = _normalize_solver_preference(solver_preference)
self.reset_model()

def reset_model(self) -> None:
Expand Down Expand Up @@ -344,7 +398,7 @@ def _solve(self) -> Solution:
raise ValueError("No edges found in the graph, there is nothing to solve.")

solution = None
for preference in [Preference.Gurobi, Preference.Scip]:
for preference in self._solver_preference:
try:
solver = Solver(
num_variables=self._count,
Expand All @@ -360,7 +414,10 @@ def _solve(self) -> Solution:
solution = solver.solve()
break
except Exception as e:
LOG.warning(f"Solver failed with {preference.name}, trying Scip.\nGot error:\n{e}")
LOG.warning(
f"Solver failed with preference {preference.name}. "
f"Trying the next preference, if any.\nGot error:\n{e}"
)
continue

if solution is None:
Expand Down
103 changes: 103 additions & 0 deletions src/tracksdata/solvers/_test/test_ilp_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import polars as pl
import pytest
from ilpy import Preference

from tracksdata.attrs import Attr
from tracksdata.constants import DEFAULT_ATTR_KEYS
Expand Down Expand Up @@ -833,3 +834,105 @@ def test_ilp_solver_init_with_merge_weight() -> None:
solver = ILPSolver(merge_weight=merge_expr)
assert solver.merge_weight_expr is not None
assert str(solver.merge_weight_expr) == str(merge_expr)


def test_ilp_solver_preference_default() -> None:
"""The default order is Gurobi, then SCIP, which keeps old behavior."""
solver = ILPSolver()
assert solver._solver_preference == [Preference.Gurobi, Preference.Scip]


def test_ilp_solver_preference_single_values() -> None:
"""A single enum or a single name gives a one-item list."""
assert ILPSolver(solver_preference=Preference.Scip)._solver_preference == [Preference.Scip]
assert ILPSolver(solver_preference="scip")._solver_preference == [Preference.Scip]
# The name match ignores case.
assert ILPSolver(solver_preference="SCIP")._solver_preference == [Preference.Scip]


def test_ilp_solver_preference_sequence() -> None:
"""A sequence of enums and names keeps its order."""
solver = ILPSolver(solver_preference=[Preference.Gurobi, "scip"])
assert solver._solver_preference == [Preference.Gurobi, Preference.Scip]


def test_ilp_solver_preference_unknown_name() -> None:
"""An unknown backend name raises a clear ValueError."""
with pytest.raises(ValueError, match="Unknown solver preference"):
ILPSolver(solver_preference="not_a_solver")


def test_ilp_solver_preference_empty_sequence() -> None:
"""An empty sequence names no backend and is an error."""
with pytest.raises(ValueError, match="at least one backend"):
ILPSolver(solver_preference=[])


def test_ilp_solver_preference_invalid_type() -> None:
"""A value that is not a Preference, a str, or a sequence raises TypeError."""
with pytest.raises(TypeError, match="Preference, a str, or a sequence"):
ILPSolver(solver_preference=3)


def test_ilp_solver_tries_each_preference(monkeypatch: pytest.MonkeyPatch) -> None:
"""The solve loop tries every preference in order and then raises.

A fake Solver fails for every backend. The test checks that the loop tries
both preferences, in order, and then raises the final error.
"""
from tracksdata.solvers import _ilp_solver

attempted: list[Preference] = []

class _FailingSolver:
def __init__(self, *args: object, preference: Preference, **kwargs: object) -> None:
attempted.append(preference)
raise RuntimeError("no backend available in this test")

monkeypatch.setattr(_ilp_solver, "Solver", _FailingSolver)

graph = RustWorkXGraph()
graph.add_node_attr_key("x", dtype=pl.Float64)
graph.add_node_attr_key("y", dtype=pl.Float64)
graph.add_edge_attr_key(DEFAULT_ATTR_KEYS.EDGE_DIST, dtype=pl.Float64)
node0 = graph.add_node({DEFAULT_ATTR_KEYS.T: 0, "x": 0.0, "y": 0.0})
node1 = graph.add_node({DEFAULT_ATTR_KEYS.T: 1, "x": 1.0, "y": 1.0})
graph.add_edge(node0, node1, {DEFAULT_ATTR_KEYS.EDGE_DIST: -1.0})

solver = ILPSolver(solver_preference=[Preference.Gurobi, Preference.Scip])
with pytest.raises(RuntimeError, match="Failed to solve"):
solver.solve(graph)

assert attempted == [Preference.Gurobi, Preference.Scip]


def test_ilp_solver_solve_with_preference_scip() -> None:
"""A solve that selects SCIP finds a non-trivial solution.

SCIP is open-source, so this test needs no Gurobi license and no GPU.
"""
graph = RustWorkXGraph()

graph.add_node_attr_key("x", dtype=pl.Float64)
graph.add_node_attr_key("y", dtype=pl.Float64)
graph.add_edge_attr_key(DEFAULT_ATTR_KEYS.EDGE_DIST, dtype=pl.Float64)

node0 = graph.add_node({DEFAULT_ATTR_KEYS.T: 0, "x": 0.0, "y": 0.0})
node1 = graph.add_node({DEFAULT_ATTR_KEYS.T: 1, "x": 1.0, "y": 1.0})
node2 = graph.add_node({DEFAULT_ATTR_KEYS.T: 1, "x": 2.0, "y": 2.0})

graph.add_edge(node0, node1, {DEFAULT_ATTR_KEYS.EDGE_DIST: -1.0})
graph.add_edge(node0, node2, {DEFAULT_ATTR_KEYS.EDGE_DIST: -2.0})

solver = ILPSolver(solver_preference="scip", return_solution=True)
solution_graph = solver.solve(graph)

node_attrs = graph.node_attrs()
edge_attrs = graph.edge_attrs()

selected_edges = edge_attrs.filter(edge_attrs[DEFAULT_ATTR_KEYS.SOLUTION])
selected_nodes = node_attrs.filter(node_attrs[DEFAULT_ATTR_KEYS.SOLUTION])

assert len(selected_edges) > 0
assert len(selected_nodes) > 0
assert solution_graph is not None
3 changes: 2 additions & 1 deletion src/tracksdata/utils/_dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ def unpack_array_attrs(df: pl.DataFrame) -> pl.DataFrame:
return df

for col in array_cols:
df = df.with_columns(pl.col(col).arr.to_struct(lambda x: f"{col}_{x}")).unnest(col) # noqa: B023
fields = [f"{col}_{i}" for i in range(df.schema[col].shape[0])]
df = df.with_columns(pl.col(col).arr.to_struct(fields)).unnest(col)

return unpack_array_attrs(df)

Expand Down
Loading