Class: Solver
Solver provides asynchronous communication with the solver.
Unlike function solve, Solver
allows to process individual events
happening during the solve and also stop the solver at any time. If you're
interested in the final result only, use solve instead.
Solver inherits from EventEmitter
class from Node.js. You can subscribe to
events using the standard Node.js on
method. The following events are
emitted:
error
: Emits an instance ofError
(standard Node.js class) when an error occurs.warning
: Emits astring
for every issued warning.log
: Emits astring
for every log message.trace
: Emits astring
for every trace message.solution
: Emits a SolutionEvent when a solution is found.lowerBound
: Emits a LowerBoundEvent when a new lower bound is proved.summary
: Emits SolveSummary at the end of the solve.close
: Emitsvoid
. It is always the last event emitted.
Unless method redirectOutput is called, solver text output (log, trace and warnings) is not printed on console.
Example
In the following example, we run a solver asynchronously. We subscribe to
the solution
event to print the objective value of the solution
and value of interval variable x
. After a solution is found, we request
the solver to stop.
We also subscribe to the summary
event to print statistics about the solve.
Finally, we wait for close
event to be emitted to know when the solver has
completed.
import * as events from 'node:events';
import * as CP from '@scheduleopt/optalcp';
...
let solver = new CP.Solver(model, p);
let x = intervalVar({ ... });
...
// Create a new solver:
let solver = new CP.solver(model, {...});
// Subscribe to "solution" events:
solver.on("solution", (msg: CP.SolutionEvent) => {
// Get Solution from SolutionEvent:
let solution = msg.solution;
console.log("At time " + msg.solveTime + ", solution found with objective " + solution.getObjective());
// Print value of interval variable x:
if (solution.isAbsent(x))
console.log(" Interval variable x is absent");
else
console.log(" Interval variable x: [" + solution.getStart(x) + " -- " + solution.getEnd(x) + "]");
// Request the solver to stop as soon as possible
// (the message is only informative):
solver.stop("We are happy with the first solution found.");
});
// Subscribe to "summary" events:
solver.on("summary", (msg: CP.SolveSummary) => {
// Print the statistics. The statistics doesn't exist if an error occurred.
console.log("Total duration of solve: " + msg.duration);
console.log("Number of branches: " + msg.nbBranches);
});
try {
// Let the solver start an wait for the first "close" event.
// Notice the import of "node:events" module above.
await events.once(solver, "close");
// Without the line above, the message "All done" would be printed before the
// solver even starts solving because the solver runs asynchronously.
console.log("All done");
} catch (e) {
// We did not subscribe to "error" events. So an exception is thrown in
// case of an error.
console.error("Exception caught: ", (e as Error).message);
}
Hierarchy
EventEmitter
↳
Solver
Constructors
constructor
• new Solver(model
, params?
)
Creates a new Solver for the given model with the given parameters.
Parameters
Name | Type | Description |
---|---|---|
model | Model | The model to solve |
params | Parameters | The parameters for the solver The solving process starts asynchronously (using standard queueMicrotask ). Therefore, Solver methods called just after its construction will be executed before the solve itself starts. In particular, it is possible to register to solver events this way (see on) or redirect solver output (@see redirectOutput). |
Overrides
EventEmitter.constructor
Methods
on
▸ on(event
, listener
): Solver
With event="error"
, register given listener function to error events. The
function should take an Error
parameter (standard Node.js class) and
return void
.
Parameters
Name | Type | Description |
---|---|---|
event | "error" | - |
listener | (err : Error ) => void | The function to be registered. |
Returns
The Solver itself for chaining.
Remarks
This function is equivalent to function EventEmitter.on
. As
usual with EventEmitter
, if there is no listener registered for the
'error' event, and an 'error' event is emitted, then the error is thrown.
Example
In the following example, we simply log all errors on the console.
let solver = new CP.solver(myModel, { nbWorkers: 4});
solver.on('error', (err: Error) => {
console.error('There was an error: ', err);
});
Overrides
EventEmitter.on
▸ on(event
, listener
): Solver
With event="warning"
, register a listener function for warning events.
Parameters
Name | Type | Description |
---|---|---|
event | "warning" | - |
listener | (msg : string ) => void | The listener function to register. It should take a string parameter (the warning) and return void . |
Returns
Remarks
This function is equivalent to function EventEmitter.on
for even type
warning
. The registered listener function is called for every warning
issued by the solver, the warning message is passed as a parameter to the
function.
Alternatively, you can use function redirectOutput to redirect all solver output (including the warnings) to a stream.
The amount of warning messages can be configured using parameter warningLevel.
Example
In the following example, we simply log all warnings on the console
using console.warn
.
const solver = new CP.Solver(myModel, { searchType: "LNS" });
solver.on('warning', (msg: string) => {
console.warn(`Warning: ${msg}`);
});
Overrides
EventEmitter.on
▸ on(event
, listener
): Solver
With event="log"
, add a listener function for log events.
Parameters
Name | Type | Description |
---|---|---|
event | "log" | - |
listener | (msg : string ) => void | The listener function to add. It should take a string parameter (the log message) and return void . |
Returns
Remarks
This function is equivalent to function EventEmitter.on
for even type
log
. The registered listener function is called for every log message
issued by the solver, the log message is passed as a parameter to the
function.
The amount of log messages and its periodicity can be controlled by parameters logLevel and logPeriod.
Alternatively, you can use function redirectOutput to redirect all solver output (including the logs) to a stream.
Example
In the following example, we simply log all logs on the console
using console.log
.
const solver = new CP.Solver(myModel, { logPeriod: 1 });
solver.on('log', (msg: string) => {
console.log(`Log: ${msg}`);
});
Overrides
EventEmitter.on
▸ on(event
, listener
): Solver
With event="trace"
, add a listener function for trace events.
Parameters
Name | Type | Description |
---|---|---|
event | "trace" | - |
listener | (msg : string ) => void | The listener function to add. It should take a string parameter (the trace message) and return void . |
Returns
Remarks
This function is equivalent to function EventEmitter.on
for even type
trace
. The registered listener function is called for every trace
message sent by the solver, the trace message is passed as a parameter
to the function.
The types of trace messages can be controlled by parameters such as searchTraceLevel or propagationTraceLevel. Note that traces are available only in the Development version of the solver.
Alternatively, you can use function redirectOutput to redirect all solver output (including the traces) to a stream.
Example
In the following example, we simply log all traces on the console
using console.log
.
const solver = new CP.Solver(myModel, { searchTraceLevel: 2, propagationTraceLevel: 1 });
solver.on('trace', (msg: string) => {
console.log(`Trace: ${msg}`);
});
Overrides
EventEmitter.on
▸ on(event
, listener
): Solver
With event="solution"
, add a listener function for solution events.
Parameters
Name | Type | Description |
---|---|---|
event | "solution" | - |
listener | (msg : SolutionEvent ) => void | The listener function to add. It should take a SolutionEvent parameter and return void . |
Returns
Remarks
This function is equivalent to function EventEmitter.on
for even type
solution
. The registered listener function is called for every solution
found by the solver, the solution is passed via SolutionEvent parameter
to the function.
Example
In the following example, we log value of interval variable x
in every
solution using console.log
.
let model = new CP.Model();
let x = model.intervalVar({ length: 5 });
...
const solver = new CP.Solver(myModel);
solver.on('solution', (msg: SolutionEvent) => {
let solution = msg.solution;
let start = solution.getStart(x);
let end = solution.getEnd(x);
if (start === undefined)
console.log("Solution found with x=absent");
else
console.log("Solution found with x=[" + start + "," + end + "]");
});
Note that in Evaluation version of the solver, the reported value of
interval variable x
will be always absent because the real variable
values are masked.
Overrides
EventEmitter.on
▸ on(event
, listener
): Solver
With event="lowerBound"
, add a listener function for lower bound events.
Parameters
Name | Type | Description |
---|---|---|
event | "lowerBound" | - |
listener | (msg : LowerBoundEvent ) => void | The listener function to add. It should take a LowerBoundEvent parameter and return void . |
Returns
Remarks
This function is equivalent to function EventEmitter.on
for even type
lowerBound
. The registered listener function is called for every
lower bound update issued by the solver, the lower bound is passed via
LowerBoundEvent parameter to the function.
Overrides
EventEmitter.on
▸ on(event
, listener
): Solver
With event="summary"
, add a listener function for summary events.
Parameters
Name | Type | Description |
---|---|---|
event | "summary" | - |
listener | (msg : SolveSummary ) => void | The listener function to add. It should take a SolveSummary parameter and return void . |
Returns
Remarks
This function is equivalent to function EventEmitter.on
for even type
summary
. The registered listener function is called at the end of
the search, the summary is passed via SolveSummary parameter
to the function. The summary contains information about the search
such as the number of solutions found, the number of failures, the
search time, etc.
Example
In the following example, we log part of the summary message on the
console using console.log
.
const solver = new CP.Solver(myModel);
solver.on('summary', (msg: SolveSummary) => {
console.log(`Solutions: ${msg.nbSolution}`);
console.log(`Branches: ${msg.nbBranches}`);
console.log(`Duration: ${msg.duration}`);
});
Overrides
EventEmitter.on
▸ on(event
, listener
): Solver
With event="close"
, add a listener function for close events.
Parameters
Name | Type | Description |
---|---|---|
event | "close" | - |
listener | () => void | The listener function to add. It should take no parameter and return void . |
Returns
Remarks
This function is equivalent to function EventEmitter.on
for even type
close
. The registered listener function is called when the solver
is closed, the function takes no parameter.
The event close
is always the last event emitted by the Solver, even in
the case of an error. It could be used, for example, to wait for solver
completion.
See Solver for an example of use.
Overrides
EventEmitter.on
redirectOutput
▸ redirectOutput(stream?
): Solver
Redirects log, trace and warnings to the given stream.
Parameters
Name | Type | Default value | Description |
---|---|---|---|
stream | WritableStream | process.stdout | The stream to write the output into. |
Returns
The Solver itself for chaining.
Normally Solver emits events for log, trace and warning messages. When this function is called then those messages will be also written into the provided stream.
Example
In the following example we store all the solver text output in a file
named log.txt
.
import * as fs from 'fs';
...
let solver = new CP.Solver(model, { timeLimit: 300 });
solver.redirectOutput(fs.createWriteStream('log.txt'));
stop
▸ stop(reason
): Promise
<void
>
Instructs the solver to stop ASAP.
Parameters
Name | Type | Description |
---|---|---|
reason | string | The reason why to stop. The reason will appear in the log. A stop message is sent to the server asynchronously. The server will stop as soon as possible and will send a summary event and close event. However, due to asynchronous nature of the communication, another events may be sent before the summary event (e.g. another solution found or a log message). |
Returns
Promise
<void
>
Example
In the following example, we issue a stop command 1 minute after the first solution is found.
let solver = new CP.Solver(model, { timeLimit: 300 });
timerStarted = false;
solver.on('solution', (_: SolutionEvent) => {
// We just found a solution. Set a timeout if there isn't any.
if (!timerStarted) {
timerStarted = true;
// Register a function to be called after 60 seconds:
setTimeout(() => {
console.log("Requesting solver to stop");
solver.stop("Stop because I said so!");
}, 60); // The timeout is 60 seconds
}
});