ObserverBuilt incomes with cpbenchy
cpbenchy run instances/ -s ortools -t 60 -p cpbenchy.observers:SaveSolution- Version
- cpbenchy 0.1.0.dev0
- Last updated
- 6 Oct 2026 · 1 commit
- Authors
- ThomSerg
- Tags
- solutionsstorage
What it does
Writes the final solution of every run that has one to logs/<run_id>.solution.json:
{"status": "optimal", "objective": -9, "solution": {"x1": true, "x2": true, "x3": false, "x4": true}}Optionally, it also puts the solution in the result itself. Saved solutions can be checked later with
cpbenchy check, without running anything again.
Use it
import cpbenchy
from cpbenchy import observers
cpbenchy.run("instances/", solvers=["ortools"], time_limit=60, plugins=[observers.SaveSolution()])
cpbenchy.run("instances/", solvers=["ortools"], time_limit=60, plugins=[observers.SaveSolution(record=True)])cpbenchy run instances/ -s ortools -t 60 -p cpbenchy.observers:SaveSolution
cpbenchy run instances/ -s ortools -t 60 -p "cpbenchy.observers:SaveSolution(record=True)"Options
| Argument | |
|---|---|
record |
also store the solution in the result, as extra["solution"]. Handy for small models, but it makes results.jsonl large. Default False |
What it records
logs/<run_id>.solution.json |
status, objective, and {name: value} of the instance’s variables |
extra["solution"] |
with record=True: the same {name: value} |
In the parent, the file is run.artifact("solution.json").
Implementation
The SaveSolution in src/cpbenchy/observers.py, lines 145–160 of 222, as of this version of the docs.
class SaveSolution(Observer):
"""The final solution as JSON, `{"status": ..., "objective": ..., "solution": {name: value}}`, in
`<run_id>.solution.json` (in the parent: `run.artifact("solution.json")`). With `record=True`, also in
the result, as `extra["solution"]`: handy for small models, but it makes results.jsonl large."""
def __init__(self, record=False):
self.record = record
def on_finish(self, ctx):
if ctx.status not in ("optimal", "feasible"):
return
solution = fmt.solution_dict(fmt.instance_variables(ctx.model))
data = {"status": ctx.status, "objective": ctx.objective, "solution": solution}
ctx.artifact("solution.json").write_text(json.dumps(data))
if self.record:
ctx.record("solution", solution)