The router engine works with common constraints in vehicle routing problems (VRPs) out of the box, such as capacity or limits. But some problems may need very specific constraints.
The router
engine provides the Constraint
option to add a custom constraint. This is done by defining a custom type that implements the Constraint
interface of the vehicle
engine. An instance of this type is then passed into the Constraint
option with the vehicle IDs to which this constraint should be applied. It is possible to use the Constraint
option multiple times to add multiple custom constraints.
Constraints make sure that when stops are being inserted into a route, the route is still feasible. Filters, however, are used to prevent assigning stops to a vehicle that they are incompatible with under any circumstance. It is often good practice to also make use of a filter
when using a custom constraint.
Example
The aim of this example is to define a custom type to create a custom constraint. The introductory router example is used as a base, where routes are created to visit seven landmarks in Kyoto using two vehicles.
Save the following information in an input.json
file (see input and output for more information on working with input files).
Code
The following program uses the CLI Runner to obtain a solution and requires access to the Nextmv code repository on GitHub. To request access, please contact support@nextmv.io.
To proceed with running the example, create a main.go
file and use the code snippet below. We create a custom type that implements the Constraint
interface, which we then pass into the Constraint
option together with a slice of vehicle IDs.
To execute the example, specify the path to the input.json
file using command-line flags and use jq to extract the solution state (see runners for more information on building and running programs).
Solution
The solution should look similar to this one:
You can see that none of the given routes has more than four stops assigned due to the constraint which was applied to both vehicles v1
and v2
.