Skip to content

Commit

Permalink
Add event callback to solver backend to monitor progress (#56)
Browse files Browse the repository at this point in the history
* feat: add event callback

* lint

* add some data

* simplify code

* working for gurobi

* remove std::visit

* fix windows

* add test and typing
  • Loading branch information
tlambert03 authored Mar 26, 2024
1 parent c6d58ca commit a7d1f60
Show file tree
Hide file tree
Showing 12 changed files with 512 additions and 225 deletions.
3 changes: 3 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,6 @@ clean:
rm -rf build dist
rm -rf ilpy/*.cpp
rm -rf ilpy/*.so

build:
python setup.py build_ext --inplace
8 changes: 7 additions & 1 deletion ilpy/_functional.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

from typing import TYPE_CHECKING, Iterable, Literal, Sequence, Tuple
from typing import TYPE_CHECKING, Callable, Iterable, Literal, Mapping, Sequence, Tuple

from .expressions import Expression
from .wrapper import (
Expand All @@ -27,6 +27,7 @@ def solve(
variable_type: VariableTypeType = VariableType.Continuous,
verbose: bool = False,
preference: PreferenceType = Preference.Any,
on_event: Callable[[Mapping], None] | None = None,
) -> list[float]:
"""Solve an objective subject to constraints.
Expand Down Expand Up @@ -56,6 +57,10 @@ def solve(
preference : Preference | Literal["any", "cplex", "gurobi", "scip"]
Backend preference, either an `ilpy.Preference` or a string in
{"any", "cplex", "gurobi", "scip"}. By default, `Preference.Any`.
on_event : Callable[[Mapping], None], optional
A callback function that is called when an event occurs, by default None.
The callback function should accept a dict which will contain event
metadata.
Returns
-------
Expand Down Expand Up @@ -92,6 +97,7 @@ def solve(
)
solver.add_constraint(const)

solver.set_event_callback(on_event)
solution = solver.solve()
return list(solution) # type: ignore

Expand Down
2 changes: 2 additions & 0 deletions ilpy/decl.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ from libcpp.memory cimport shared_ptr
from libcpp.map cimport map
from libcpp.pair cimport pair
from libcpp.vector cimport vector
from cpython.object cimport PyObject

cdef extern from "impl/solvers/Relation.h":
cdef enum Relation:
Expand Down Expand Up @@ -99,6 +100,7 @@ cdef extern from "impl/solvers/SolverBackend.h":
void setNumThreads(unsigned int)
void setVerbose(bool)
bool solve(Solution& solution, string& message) except +
void setEventCallback(PyObject* callback)

cdef extern from "impl/solvers/ScipBackend.cpp":
pass
Expand Down
Loading

0 comments on commit a7d1f60

Please sign in to comment.