Skip to main content

Add Optimization with Orders in the Same Route

|

This example demonstrates how to create an optimization where specific orders must be visited by the same vehicle, ensuring they are part of the same route. The example covers the following features:

  • Adding an optimization with custom configuration parameters.
  • Defining orders with specific sequences that must be visited by the same vehicle.
  • Displaying the optimized solution on a map.

When you run the example application:

  • An optimization is created and saved.
  • The optimized solution is returned and displayed on the map.

Step-by-Step Guide

Step 1: Initialize the API Key and the Environment

To use the Magic Lane SDK, we first need to initialize the API key (project API token) and set up the environment. This ensures that the SDK is properly authenticated and configured for further usage.

Initializing the API Key

There are three ways to set the API key in the code:

  1. Manual Assignment

    • If neither the macro nor the environment variable is set, the API key must be manually assigned by modifying the source code.
    • This is the least secure method and is only recommended for development purposes.
  2. Predefined Macro (API_TOKEN)

    • If the API key is defined at compile time as API_TOKEN, it is automatically assigned to projectApiToken.
    • This approach is useful when the API key is included in the build configuration.
  3. Environment Variable (GEM_TOKEN)

    • If API_TOKEN is not defined, the program attempts to retrieve the API key from the system environment variable GEM_TOKEN.
    • This method allows for better security as the API key does not need to be hardcoded.
    std::string projectApiToken = "YOUR_API_KEY_HERE"; // Manual Assignment

#if defined(API_TOKEN)
projectApiToken = std::string(API_TOKEN); // Predefined Macro
#else
auto value = std::getenv("GEM_TOKEN"); // Environment Variable
if (value != nullptr)
projectApiToken = value;
#endif

You must choose one method to initialize the API_KEY. If you are unsure what an API_KEY is, you can visit the Get Started page for more information

Preparing the Environment

Once the API key is set, we need to initialize the environment using the SdkSession class. The Environment class manages the SDK setup and provides functionalities for initializing and releasing the SDK, handling OpenGL rendering, managing event listeners and UI callbacks, and waiting for events like timeouts or window closures.

    Environment::SdkSession session(projectApiToken, { argc > 1 ? argv[1] : "" }); // Initialize log file path with the first command-line argument if it exists; otherwise, it initializes it to an empty string

Step 2: Create Customers and Orders

note

Each order must have a customer associated with it. You can either:

  • Create a new customer and assign it to the order.
  • Use an existing customer (refer to the Get Customer example).

Initializing and Adding Customers

  1. Initialize a ProgressListener and vrp::Service.
  2. Create twelve vrp::Customer objects and set the desired fields, and add them to the database.
  3. Call the addCustomer() method from the vrp::Service using the vrp::Customer and ProgressListener and wait for the operation to be done.
ProgressListener listener;
gem::vrp::Service serv;

gem::vrp::Customer c0;
c0.setCoordinates(gem::Coordinates(48.234270, -2.133208));
c0.setAlias("c0");
c0.setPhoneNumber("+12312312");
c0.setEmail("c0@yahoo.com");
int ret = serv.addCustomer(&listener, c0);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);

gem::vrp::Customer c1;
c1.setCoordinates(gem::Coordinates(45.854137, 2.853998));
c1.setAlias("c1");
c1.setEmail("c1@yahoo.com");
c1.setPhoneNumber("+12312312");
ret = serv.addCustomer(&listener, c1);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);

gem::vrp::Customer c2(gem::Coordinates(46.199373, 0.069986));
c2.setAlias("c2");
c2.setPhoneNumber("+12312312");
c2.setEmail("c2@yahoo.com");
ret = serv.addCustomer(&listener, c2);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);

gem::vrp::Customer c3(gem::Coordinates(48.052503, 0.119726));
c3.setAlias("c3");
c3.setPhoneNumber("+12312312");
c3.setEmail("c3@yahoo.com");
ret = serv.addCustomer(&listener, c3);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);

gem::vrp::Customer c4(gem::Coordinates(44.346051, 4.694878));
c4.setAlias("c4");
c4.setPhoneNumber("+12312312");
c4.setEmail("c4@yahoo.com");
ret = serv.addCustomer(&listener, c4);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);

gem::vrp::Customer c5(gem::Coordinates(44.464582, 2.455020));
c5.setAlias("c5");
c5.setPhoneNumber("+12312312");
c5.setEmail("c5@yahoo.com");
ret = serv.addCustomer(&listener, c5);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);

gem::vrp::Customer c6(gem::Coordinates(48.656644, 5.907131));
c6.setAlias("c6");
c6.setPhoneNumber("+12312312");
c6.setEmail("c6@yahoo.com");
ret = serv.addCustomer(&listener, c6);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);

gem::vrp::Customer c7(gem::Coordinates(49.161539, 0.500580));
c7.setAlias("c7");
c7.setPhoneNumber("+12312312");
c7.setEmail("c7@yahoo.com");
ret = serv.addCustomer(&listener, c7);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);

gem::vrp::Customer c8(gem::Coordinates(47.702421, 3.384226));
c8.setAlias("c8");
c8.setPhoneNumber("+12312312");
c8.setEmail("c8@yahoo.com");
ret = serv.addCustomer(&listener, c8);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);

gem::vrp::Customer c9(gem::Coordinates(47.198274, 4.630011));
c9.setAlias("c9");
c9.setPhoneNumber("+12312312");
c9.setEmail("c9@yahoo.com");
ret = serv.addCustomer(&listener, c9);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);

gem::vrp::Customer c10(gem::Coordinates(49.655296, 2.243181));
c10.setAlias("c10");
c10.setPhoneNumber("+12312312");
c10.setEmail("c10@yahoo.com");
ret = serv.addCustomer(&listener, c10);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);

gem::vrp::Customer c11(gem::Coordinates(50.719729, 2.160877));
c11.setAlias("c11");
c11.setPhoneNumber("+12312312");
c11.setEmail("c11@yahoo.com");
ret = serv.addCustomer(&listener, c11);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);

Initializing and Adding Orders

  1. Create a vrp::OrderList and add orders to it. Each order must have a customer associated with it.
  2. Create twelve vrp::Order objects and associate one customer for each, set the desired fields, and add them to the database.
  3. Call the addOrder() method from the vrp::Service using the vrp::Order and ProgressListener and wait for the operation to be done.
 gem::vrp::OrderList orders;
gem::vrp::Order order0(c0);
ret = serv.addOrder(&listener, order0, false);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);
orders.push_back(order0);
gem::vrp::Order order1(c1);
ret = serv.addOrder(&listener, order1, false);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);
orders.push_back(order1);
gem::vrp::Order order2(c2);
ret = serv.addOrder(&listener, order2, false);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);
orders.push_back(order2);
gem::vrp::Order order3(c3);
ret = serv.addOrder(&listener, order3, false);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);
orders.push_back(order3);
gem::vrp::Order order4(c4);
ret = serv.addOrder(&listener, order4, false);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);
orders.push_back(order4);
gem::vrp::Order order5(c5);
ret = serv.addOrder(&listener, order5, false);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);
orders.push_back(order5);
gem::vrp::Order order6(c6);
ret = serv.addOrder(&listener, order6, false);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);
orders.push_back(order6);
gem::vrp::Order order7(c7);
ret = serv.addOrder(&listener, order7, false);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);
orders.push_back(order7);
gem::vrp::Order order8(c8);
ret = serv.addOrder(&listener, order8, false);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);
orders.push_back(order8);
gem::vrp::Order order9(c9);
ret = serv.addOrder(&listener, order9, false);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);
orders.push_back(order9);
gem::vrp::Order order10(c10);
ret = serv.addOrder(&listener, order10, false);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);
orders.push_back(order10);
gem::vrp::Order order11(c11);
ret = serv.addOrder(&listener, order11, false);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);
orders.push_back(order11);

Configure Optimization Parameters

note

Configuration Parameters define key settings that influence the behavior of the route optimization process. These settings determine aspects such as optimization goals, search time limits, and flexibility in handling orders.

  1. Create a vrp::ConfigurationParameters object and set the desired parameters.
  2. Create a gem::vrp::OrdersSequenceMap to specify the association between different orders that should be visited in a certain order. In this example, we define two sequences of orders that must be visited by the same vehicle.
gem::vrp::OrdersSequenceMap ordersSequence;
gem::LargeIntListList sequence = { { orders[2].getId(), orders[6].getId(), orders[1].getId() }, { orders[8].getId(), orders[3].getId()} };
ordersSequence.insert(std::make_pair(gem::vrp::EOrdersSequenceOption::OSO_InSameRoute, sequence));

gem::vrp::ConfigurationParameters params;
params.setOrderSequenceOptions(ordersSequence);

Create Vehicles and Define Vehicle Constraints

note

Vehicle constraints define the limitations and requirements applied to a vehicle during the route optimization process. Ensure that the vehicle operates within its capabilities, such as time windows, capacity, distance, and revenue.

Initializing and Adding Vehicles

  1. Create a gem::vrp::VehicleList and add vehicles to it.
  2. Create two vrp::Vehicle objects and set the desired fields, and add them to the database.
  3. Call the addVehicle() method from the vrp::Service using the vrp::Vehicle and ProgressListener and wait for the operation to be done.
gem::vrp::VehicleList vehicles;
gem::vrp::Vehicle vehicle1;
vehicle1.setName("Vehicle 1");
vehicle1.setType(gem::vrp::EVehicleType::VT_Car);
vehicle1.setStatus(gem::vrp::EVehicleStatus::VS_Available);
vehicle1.setManufacturer("Kia");
vehicle1.setModel("Ceed");
vehicle1.setFuelType(gem::vrp::EFuelType::FT_GasolinePremium);
vehicle1.setConsumption(6.5);
vehicle1.setLicensePlate("BV01ASD");
vehicle1.setMaxWeight(15);
vehicle1.setMaxCube(2);
vehicle1.setStartTime(420); //7:00 AM
vehicle1.setEndTime(1920); //8:00 AM next day

ret = serv.addVehicle(&listener, vehicle1);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);
vehicles.push_back(vehicle1);

gem::vrp::Vehicle vehicle2;
vehicle2.setName("Vehicle 1");
vehicle2.setType(gem::vrp::EVehicleType::VT_Car);
vehicle2.setStatus(gem::vrp::EVehicleStatus::VS_Available);
vehicle2.setManufacturer("Kia");
vehicle2.setModel("Sportage");
vehicle2.setFuelType(gem::vrp::EFuelType::FT_GasolinePremium);
vehicle2.setConsumption(6.6);
vehicle2.setLicensePlate("B123ABC");
vehicle2.setMaxWeight(20);
vehicle2.setMaxCube(3);
vehicle2.setStartTime(420); //7:00 AM
vehicle2.setEndTime(2160); //12:00 PM next day

ret = serv.addVehicle(&listener, vehicle2);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 5000);
vehicles.push_back(vehicle2);

Define Vehicle Constraints

  1. Create a vrp::VehicleConstraints object for each vehicle.
  2. Add these constraints to a vrp::VehicleConstraintsList.
gem::vrp::VehicleConstraintsList vehConstraintsList;
gem::vrp::VehicleConstraints vehConstr1;
vehConstr1.setStartDate(gem::Time(2024, 11, 1));
vehConstraintsList.push_back(vehConstr1);

Create the Departure and Destinations

note

Departures define the starting points for vehicle routes. These locations serve as the origin of a route and can impact optimization by influencing travel distance and time. Destinations define the final stop for a vehicle route. These locations mark the endpoint of a route and play a key role in optimizing route efficiency.

Initializing Departures and Destinations

  1. Create a vrp::Departure object.
  2. Create a vrp::Destination object.
gem::vrp::Departure departure;
departure.setAlias("departure");
departure.setCoordinates(gem::Coordinates(48.618893, -1.353635));

gem::vrp::Destination destination;
destination.setAlias("destination");
destination.setCoordinates(gem::Coordinates(47.617484, 1.152466));

Create the Optimization

Note

An optimization represents a set of orders, vehicles, constraints, and other parameters that define a routing problem.

  1. Create a vrp::Optimization object.
  2. Assign the OrderList, ConfigurationParameters, VehicleList, VehicleConstraintsList, Departures, and Destinations to the optimization.
gem::vrp::Optimization optimization;
optimization.setOrders(orders);
optimization.setDepartures({ departure });
optimization.setVehicles(vehicles);
optimization.setVehiclesConstraints(vehConstraintsList);
optimization.setConfigurationParameters(params);

Displaying Orders on the Map

Once the orders have been added, we can display them on the map.

Initialize Map Components

  1. Create a MapServiceListener, OpenGLContext, and MapView.
MapViewListenerImpl mapListener;
auto oglContext = session.produceOpenGLContext(Environment::WindowFrameworks::Available, "AddOptimizationWithOrdersInSameRoute");
gem::StrongPointer<gem::MapView> mapView = gem::MapView::produce(oglContext, &mapListener);

Highlight Orders and Departures

  1. Create a LandmarkList and CoordinatesList using the OrderList, Departures, and Destinations.
  2. Instruct the MapView to highlight the landmarks (orders, departures, and destinations).
  3. For better visibility, create a PolygonGeographicArea from the CoordinatesList and center the MapView on this area.
gem::LandmarkList lmks;
gem::CoordinatesList coords;

for (int i = 0; i < optimization.getDepartures().size(); i++)
{
gem::Landmark landmark;
landmark.setName(optimization.getDepartures()[i].getAlias());
landmark.setCoordinates(optimization.getDepartures()[i].getCoordinates());
landmark.setImage(gem::Icon::Core::GreenBall);

lmks.push_back(landmark);
coords.push_back(optimization.getDepartures()[i].getCoordinates());
}

for (int i = 0; i < orders.size(); i++)
{
gem::Landmark landmark;
landmark.setName(orders[i].getAlias());
landmark.setCoordinates(orders[i].getCoordinates());
landmark.setImage(gem::Icon::Core::BlueBall);

lmks.push_back(landmark);
coords.push_back(orders[i].getCoordinates());
}

for (int i = 0; i < optimization.getDestinations().size(); i++)
{
gem::Landmark landmark;
landmark.setName(optimization.getDestinations()[i].getAlias());
landmark.setCoordinates(optimization.getDestinations()[i].getCoordinates());
landmark.setImage(gem::Icon::Core::RedBall);

lmks.push_back(landmark);
coords.push_back(optimization.getDestinations()[i].getCoordinates());
}

mapView->activateHighlight(lmks);
gem::PolygonGeographicArea polyArea(coords);
mapView->centerOnArea(polyArea);

ret = WAIT_UNTIL(std::bind(&MapViewListenerImpl::IsFinished, &mapListener), 15000);

Run the Optimization

  1. Call the addOptimization() method from vrp::Service, passing the Optimization object and the ProgressListener.
  2. After the operation is finished, a solution for optimization will be generated. To view the solution, you need to call the getSolution method from the optimization, which will return a vrp::RouteList containing the optimization results.
std::shared_ptr<gem::vrp::Request> request = std::make_shared<gem::vrp::Request>();
ret = serv.addOptimization(&listener, optimization, request);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 10000);

WAIT_UNTIL([&]() {
serv.getRequest(&listener, request, request->id);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 7000);
return request->status == gem::vrp::ERequestStatus::eFinished;
}, 40000);

gem::vrp::RouteList routes;
ret = optimization.getSolution(&listener, routes);
WAIT_UNTIL(std::bind(&ProgressListener::IsFinished, &listener), 10000);

Display Routes on the Map

Once the optimization is complete and a solution has been found, we can display the solution on the map.

  1. Ensure that the operation was done, and a solution was found.
  2. Create a MarkerCollection of type Polyline for each route.
  3. Add the route shapes to the MarkerCollection.
  4. Set the MarkerCollection in the map view preferences.
  5. After highlighting on the map, center the screen over the routes.
if (listener.IsFinished() && listener.GetError() == gem::KNoError && ret == gem::KNoError)
{
std::cout << "Problem optimized successfully" << std::endl;

gem::CoordinatesList shape0 = routes[0].getShape();
gem::CoordinatesList shape1 = routes[1].getShape();

// Display routes shapes on map
auto col1 = gem::MarkerCollection(gem::EMarkerType::MT_Polyline, "shape0");
col1.add(gem::Marker(shape0));

mapView->preferences().markers().add(col1);

auto col2 = gem::MarkerCollection(gem::EMarkerType::MT_Polyline, "shape1");
col2.add(gem::Marker(shape1));
gem::MarkerCollectionRenderSettings markerCollDisplaySettings;
markerCollDisplaySettings.polylineInnerColor = gem::Rgba(0, 0, 255, 0);

mapView->preferences().markers().add(col2, markerCollDisplaySettings);
ret = WAIT_UNTIL(std::bind(&MapViewListenerImpl::IsFinished, &mapListener), 15000);

gem::CoordinatesList shapesCoordinates;
shapesCoordinates.insert(shapesCoordinates.end(), shape0.begin(), shape0.end());
shapesCoordinates.insert(shapesCoordinates.end(), shape1.begin(), shape1.end());

gem::PolygonGeographicArea polyArea(shapesCoordinates);
mapView->centerOnArea(polyArea);
ret = WAIT_UNTIL(std::bind(&MapViewListenerImpl::IsFinished, &mapListener), 15000);

WAIT_UNTIL_WINDOW_CLOSE();
}
else
std::cout << "Problem couldn't be optimized" << std::endl;