You are viewing Nextmv legacy docs. ⚡️ Go to latest docs ⚡️

Sdk

Sorter

You will learn how to use the Sorter option with a practical example.

By default the router engine determines the order in which the solver attempts to assign locations to vehicles by predicting the cost of that assignment. However, when the value function is overridden, the cost prediction for an assignment should also be adjusted. Its goal is to order vehicles in such a way that those vehicles come first where the assignment of the given locations is cheap in terms of the overridden value function. The router engine provides the Sorter option to set up a custom sorter for vehicles. This is done by writing a function that returns a sorted list of vehicle indices.

Example

The router example is used as a base, where routes are created to visit seven landmarks in Kyoto using two vehicles and a score for each stop. This time, we define a function in code, not in the input file, to create a custom sorter. Note that this change is only needed when you also change the value function and this example is only to demonstrate the usage of the option. To keep the example simple it does not evaluate the cost of an assignment in terms of a changed value function.

sorter-input

Save the following information in an input.json file (see input and output for more information on working with input files).

{
  "stops": [
    {
      "id": "Fushimi Inari Taisha",
      "position": { "lon": 135.772695, "lat": 34.967146 }
    },
    {
      "id": "Kiyomizu-dera",
      "position": { "lon": 135.78506, "lat": 34.994857 }
    },
    {
      "id": "Nijō Castle",
      "position": { "lon": 135.748134, "lat": 35.014239 }
    },
    {
      "id": "Kyoto Imperial Palace",
      "position": { "lon": 135.762057, "lat": 35.025431 }
    },
    {
      "id": "Gionmachi",
      "position": { "lon": 135.775682, "lat": 35.002457 }
    },
    {
      "id": "Kinkaku-ji",
      "position": { "lon": 135.728898, "lat": 35.039705 }
    },
    {
      "id": "Arashiyama Bamboo Forest",
      "position": { "lon": 135.672009, "lat": 35.017209 }
    }
  ],
  "vehicles": ["v1", "v2"],
  "score": [1, 2]
}
Copy

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 function to sort the vehicles tried for assignment based on a score which we then pass into the Sorter option.

package main

import (
    "sort"

    "github.com/nextmv-io/code/engines/route"
    fleetEngine "github.com/nextmv-io/code/engines/route/fleet"
    "github.com/nextmv-io/code/hop/model"
    "github.com/nextmv-io/code/hop/run/cli"
    "github.com/nextmv-io/code/hop/solve"
)

// Struct to read from JSON in.
type input struct {
    Stops    []route.Stop `json:"stops,omitempty"`
    Vehicles []string     `json:"vehicles,omitempty"`
    Score    []int        `json:"score,omitempty"`
}

// Use the CLI runner to solve a Vehicle Routing Problem.
func main() {
    f := func(i input, opt solve.Options) (solve.Solver, error) {
        // Define a vehicle sorter. This vehicle sorter sorts the vehicles that
        // can service the selected stops and returns their vehicle indices in
        // the sorted order.
        sorter := func(s fleetEngine.State, stops, vehicles model.IntDomain) []int {
            vehicleIndices := vehicles.Slice()
            sort.SliceStable(vehicleIndices, func(j, k int) bool {
                return i.Score[j] > i.Score[k]
            })
            return vehicleIndices
        }
        router, err := route.NewRouter(
            i.Stops,
            i.Vehicles,
            route.Sorter(sorter),
        )
        if err != nil {
            return nil, err
        }

        return router.Solver(opt)
    }

    cli.Run(f)
}
Copy

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).

go run main.go -hop.runner.input.path input.json | jq .state
Copy

Solution

The solution should look similar to this one:

{
  "unassigned": [],
  "vehicles": [
    {
      "id": "v1",
      "route": [
        {
          "id": "Kinkaku-ji",
          "position": {
            "lon": 135.728898,
            "lat": 35.039705
          }
        },
        {
          "id": "Nijō Castle",
          "position": {
            "lon": 135.748134,
            "lat": 35.014239
          }
        },
        {
          "id": "Kyoto Imperial Palace",
          "position": {
            "lon": 135.762057,
            "lat": 35.025431
          }
        },
        {
          "id": "Gionmachi",
          "position": {
            "lon": 135.775682,
            "lat": 35.002457
          }
        },
        {
          "id": "Kiyomizu-dera",
          "position": {
            "lon": 135.78506,
            "lat": 34.994857
          }
        },
        {
          "id": "Fushimi Inari Taisha",
          "position": {
            "lon": 135.772695,
            "lat": 34.967146
          }
        }
      ],
      "route_duration": 1242
    },
    {
      "id": "v2",
      "route": [
        {
          "id": "Arashiyama Bamboo Forest",
          "position": {
            "lon": 135.672009,
            "lat": 35.017209
          }
        }
      ],
      "route_duration": 0
    }
  ]
}
Copy

To find this solution, the highest priority stops were selected and assigned first.

sorter-output

Page last updated

Go to on-page nav menu