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.
To solve a model, create a new Solver
object and call its method Solver.solve.
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.
The solver output (log, trace and warnings) is printed on console by default, it can be redirected to a file or a stream or suppressed completely using function redirectOutput.
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 the first solution is found, we request
the solver to stop.
We also subscribe to the summary
event to print statistics about the solve.
import * as CP from '@scheduleopt/optalcp';
...
let model = new CP.Model();
let x = model.intervalVar({ ... });
...
// Create a new solver:
let solver = new CP.Solver;
// 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 {
await solver.solve(model, { timeLimit: 60 });
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);
}
Extends
EventEmitter
Constructors
new Solver()
new Solver():
Solver
Returns
Overrides
EventEmitter.constructor
Methods
on()
on(event, listener)
on(
event
:"error"
,listener
: (err
:Error
) =>void
):this
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
Parameter | Type | Description |
---|---|---|
event | "error" | - |
listener | (err : Error ) => void | The function to be registered. |
Returns
this
The Solver itself for chaining.
Overrides
EventEmitter.on
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;
solver.on('error', (err: Error) => {
console.error('There was an error: ', err);
});
let result = await solver.solve(myModel, { timeLimit: 60 });
on(event, listener)
on(
event
:"warning"
,listener
: (msg
:string
) =>void
):this
With event="warning"
, register a listener function for warning events.
Parameters
Parameter | 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
this
Overrides
EventEmitter.on
Remarks
This function is equivalent to function EventEmitter.on
for event 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 Parameters.warningLevel.
Example
In the following example, we simply log all warnings on the console
using console.warn
.
const solver = new CP.Solver;
solver.on('warning', (msg: string) => {
console.warn(`Warning: ${msg}`);
});
let result = wait solver.solve(myModel, { searchType: "LNS"});
on(event, listener)
on(
event
:"log"
,listener
: (msg
:string
) =>void
):this
With event="log"
, add a listener function for log events.
Parameters
Parameter | 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
this
Overrides
EventEmitter.on
Remarks
This function is equivalent to function EventEmitter.on
for event 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 Parameters.logLevel and Parameters.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;
solver.on('log', (msg: string) => {
console.log(`Log: ${msg}`);
});
let result = await solver.solve(myModel, { logPeriod: 1 });
on(event, listener)
on(
event
:"trace"
,listener
: (msg
:string
) =>void
):this
With event="trace"
, add a listener function for trace events.
Parameters
Parameter | 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
this
Overrides
EventEmitter.on
Remarks
This function is equivalent to function EventEmitter.on
for event 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 Parameters.searchTraceLevel or Parameters.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;
solver.on('trace', (msg: string) => {
console.log(`Trace: ${msg}`);
});
let result = await solver.solve(myModel, { nbWorkers: 2 });
on(event, listener)
on(
event
:"solution"
,listener
: (msg
:SolutionEvent
) =>void
):this
With event="solution"
, add a listener function for solution events.
Parameters
Parameter | Type | Description |
---|---|---|
event | "solution" | - |
listener | (msg : SolutionEvent ) => void | The listener function to add. It should take a |
SolutionEvent parameter and return void . |
Returns
this
Overrides
EventEmitter.on
Remarks
This function is equivalent to function EventEmitter.on
for event 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;
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 + "]");
});
let result = await solver.solve(myModel);
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.
on(event, listener)
on(
event
:"lowerBound"
,listener
: (msg
:LowerBoundEvent
) =>void
):this
With event="lowerBound"
, add a listener function for lower bound events.
Parameters
Parameter | Type | Description |
---|---|---|
event | "lowerBound" | - |
listener | (msg : LowerBoundEvent ) => void | The listener function to add. It should take a |
LowerBoundEvent parameter and return void . |
Returns
this
Overrides
EventEmitter.on
Remarks
This function is equivalent to function EventEmitter.on
for event 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.
on(event, listener)
on(
event
:"summary"
,listener
: (msg
:SolveSummary
) =>void
):this
With event="summary"
, add a listener function for summary events.
Parameters
Parameter | Type | Description |
---|---|---|
event | "summary" | - |
listener | (msg : SolveSummary ) => void | The listener function to add. It should take a |
SolveSummary parameter and return void . |
Returns
this
Overrides
EventEmitter.on
Remarks
This function is equivalent to function EventEmitter.on
for event 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;
solver.on('summary', (msg: SolveSummary) => {
console.log(`Solutions: ${msg.nbSolution}`);
console.log(`Branches: ${msg.nbBranches}`);
console.log(`Duration: ${msg.duration}`);
});
let result = await solver.solve(myModel);
on(event, listener)
on(
event
:"close"
,listener
: () =>void
):this
With event="close"
, add a listener function for close events.
Parameters
Parameter | Type | Description |
---|---|---|
event | "close" | - |
listener | () => void | The listener function to add. It should take no |
parameter and return void . |
Returns
this
Overrides
EventEmitter.on
Remarks
This function is equivalent to function EventEmitter.on
for event 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.
redirectOutput()
redirectOutput(
stream
:null
|WritableStream
):Solver
Redirects log, trace and warnings to the given stream. Or suppresses them when
stream
is null
.
Parameters
Parameter | Type | Description |
---|---|---|
stream | null | WritableStream | The stream to write the output into, or null to suppress the output. |
Returns
The Solver itself for chaining.
Normally Solver writes log, trace and warning messages to its standard output. This function allows to redirect those messages to another stream (e.g. a file) or suppress them completely.
Note that besides writing the messages to the standard output, the solver also emits events for log, trace and warning messages. Those events can be intercepted using functions on.
If the output stream becomes non-writable (e.g. a broken pipe) then the solver stops as soon as possible (function stop is called).
Example
In the following example, we store all the solver text output in a file
named log.txt
.
import * as fs from 'fs';
import 8 as CP from '@scheduleopt/optalcp';
...
let solver = new CP.Solver;
solver.redirectOutput(fs.createWriteStream('log.txt'));
sendSolution()
sendSolution(
solution
:Solution
):Promise
<void
>
Send an external solution to the solver.
Parameters
Parameter | Type | Description |
---|---|---|
solution | Solution | The solution to send. It must be compatible with the model otherwise an error is raised. |
Returns
Promise
<void
>
Remarks
This function can be used to send an external solution to the solver, e.g. found by another solver, a heuristic or a user. The solver will take advantage of the solution to speed up the search: it will search only for better solutions (if it is a minimization or maximization problem). The solver may try to improve the provided solution by Large Neighborhood Search.
The solution does not have to be better than the current best solution found by the solver. It is up to the solver whether it will use the solution in this case or not.
Sending a solution to a solver that has already stopped has no effect.
The solution is sent to the solver asynchronously. Unless parameter Parameters.logLevel is set to 0, the solver will log a message when it receives the solution.
solve()
solve(
model
:Model
,params
?:Parameters
,warmStart
?:Solution
,log
?:null
|WritableStream
):Promise
<SolveResult
>
Solves a given model with the given parameters.
Parameters
Parameter | Type | Description |
---|---|---|
model | Model | The model to solve |
params ? | Parameters | The parameters for the solver |
warmStart ? | Solution | An initial solution to start the solver with |
log ? | null | WritableStream | A stream to redirect the solver output to. If null , the output is suppressed. |
If undefined , the output stream is not changed (the default is standard output). |
Returns
Promise
<SolveResult
>
A promise that resolves to a SolveResult object when the solve is finished.
Remarks
The solving process starts asynchronously. Use await
to wait for the
solver to finish. During the solve, the solver emits events that can be
intercepted (see on) to execute a code when the event occurs.
Note that JavaScript is single-threaded. Therefore it cannot communicate
with the solver subprocess while the user code is running. The user code
must be idle (using await
or waiting for an event) for the solver to
function correctly.
Note that function solve cannot be called only once. If you need to
solve multiple models or run multiple solves in parallel then create multiple
Solver
objects.
Warm start and external solutions
If warmStart
parameter is specified then the solver will start with the
given solution. The solution must be compatible with the model otherwise
an error is raised. The solver will take advantage of the
solution to speed up the search: it will search only for better solutions
(if it is a minimization or maximization problem). The solver may try to
improve the provided solution by Large Neighborhood Search.
There are two ways to pass a solution to the solver: using warmStart
parameter and using function sendSolution.
The difference is that warmStart
is guaranteed to be used by the solver
before the solve starts. On the other hand, sendSolution
can be called
at any time during the solve.
stop()
stop(
reason
:string
):Promise
<void
>
Instructs the solver to stop ASAP.
Parameters
Parameter | 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).
Requesting stop on a solver that has already stopped has no effect. |
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;
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
}
});
let result = await solver.solve(model, { timeLimit: 300 });