Package google.maps.routeoptimization.v1

Индекс

Оптимизация маршрута

Сервис для оптимизации автомобильных туров.

Срок действия определенных типов полей:

  • google.protobuf.Timestamp
    • Время указано в формате Unix: секунды с 1970-01-01T00:00:00+00:00.
    • секунды должны быть в формате [0, 253402300799], т.е. в формате [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00].
    • nanos должен быть отключен или установлен на 0.
  • google.protobuf.Duration
    • секунды должны быть в формате [0, 253402300799], т.е. в формате [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00].
    • nanos должен быть отключен или установлен на 0.
  • google.type.LatLng
    • широта должна быть в диапазоне [-90.0, 90.0].
    • долгота должна быть в диапазоне [-180,0, 180,0].
    • хотя бы одно из значений широты и долготы должно быть ненулевым.
Пакетная оптимизация туров

rpc BatchOptimizeTours( BatchOptimizeToursRequest ) returns ( Operation )

Оптимизирует автомобильные туры для одного или нескольких сообщений OptimizeToursRequest в пакетном режиме.

Этот метод представляет собой длительную операцию (LRO). Входные данные для оптимизации (сообщения OptimizeToursRequest ) и выходные данные (сообщения OptimizeToursResponse ) считываются и записываются в Cloud Storage в формате, указанном пользователем. Как и метод OptimizeTours , каждый OptimizeToursRequest содержит ShipmentModel и возвращает OptimizeToursResponse , содержащий поля ShipmentRoute , которые представляют собой набор маршрутов, которые должны выполняться транспортными средствами, чтобы минимизировать общую стоимость.

Пользователь может опросить operations.get , чтобы проверить статус LRO:

Если поле LRO done имеет значение false, то по крайней мере один запрос все еще обрабатывается. Другие запросы могли быть выполнены успешно, и их результаты доступны в Cloud Storage.

Если поле done LRO истинно, то все запросы обработаны. Результаты всех успешно обработанных запросов будут доступны в облачном хранилище. Результаты любых невыполненных запросов не будут доступны в Cloud Storage. Если поле error LRO установлено, то оно содержит ошибку одного из неудавшихся запросов.

Области авторизации

Требуется следующая область действия OAuth:

  • https://www.googleapis.com/auth/cloud-platform
IAM-разрешения

Требуется следующее разрешение IAM для parent ресурса:

  • routeoptimization.operations.create

Дополнительную информацию см. в документации IAM .

ОптимизироватьТуры

rpc OptimizeTours( OptimizeToursRequest ) returns ( OptimizeToursResponse )

Отправляет OptimizeToursRequest , содержащий ShipmentModel , и возвращает OptimizeToursResponse , содержащий ShipmentRoute , которые представляют собой набор маршрутов, которые должны выполняться транспортными средствами, чтобы минимизировать общую стоимость.

Модель ShipmentModel состоит в основном из объектов Shipment , которые необходимо выполнить, и Vehicle , которые можно использовать для перевозки объектов Shipment . ShipmentRoute назначает Shipment Vehicle . Точнее, они назначают серию Visit каждому транспортному средству, где Visit соответствует VisitRequest , который представляет собой получение или доставку Shipment .

Цель состоит в том, чтобы обеспечить назначение ShipmentRoute для Vehicle , которое минимизирует общую стоимость, где стоимость имеет множество компонентов, определенных в ShipmentModel .

Области авторизации

Требуется следующая область действия OAuth:

  • https://www.googleapis.com/auth/cloud-platform
IAM-разрешения

Требуется следующее разрешение IAM для parent ресурса:

  • routeoptimization.locations.use

Дополнительную информацию см. в документации IAM .

Агрегированные метрики

Агрегированные показатели для ShipmentRoute (соответственно для OptimizeToursResponse по всем элементам Transition и/или Visit (соответственно по всем элементам ShipmentRoute ).

Поля
performed_ shipment_ count

int32

Количество выполненных отгрузок. Обратите внимание, что пара самовывоза и доставки засчитывается только один раз.

travel_ duration

Duration

Общая продолжительность путешествия по маршруту или решению.

wait_ duration

Duration

Общая продолжительность ожидания маршрута или решения.

delay_ duration

Duration

Общая продолжительность задержки маршрута или решения.

break_ duration

Duration

Общая продолжительность перерыва для маршрута или решения.

visit_ duration

Duration

Общая продолжительность посещения маршрута или решения.

total_ duration

Duration

Общая продолжительность должна быть равна сумме всех указанных выше длительностей. Для маршрутов это также соответствует:

[ShipmentRoute.vehicle_end_time][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_end_time] - [ShipmentRoute.vehicle_start_time][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_start_time]
travel_ distance_ meters

double

Общее расстояние перемещения по маршруту или решению.

max_ loads

map<string, VehicleLoad >

Максимальная нагрузка, достигнутая на всем маршруте (соответственно решение), для каждого количества на этом маршруте (соответственно решение), вычисляемая как максимум по всем Transition.vehicle_loads (соответственно ShipmentRoute.metrics.max_loads .

Пакетная оптимизация туровМетаданные

Этот тип не имеет полей.

Метаданные операции для вызовов BatchOptimizeToursRequest .

Пакетная оптимизацияЗапрос туров

Запрос на пакетную оптимизацию туров как асинхронную операцию. Каждый входной файл должен содержать один OptimizeToursRequest , а каждый выходной файл — один OptimizeToursResponse . Запрос содержит информацию для чтения/записи и анализа файлов. Все входные и выходные файлы должны находиться в одном проекте.

Поля
parent

string

Необходимый. Целевой проект и место для звонка.

Формат: * projects/{project-id} * projects/{project-id}/locations/{location-id}

Если местоположение не указано, регион будет выбран автоматически.

model_ configs[]

AsyncModelConfig

Необходимый. Информация ввода/вывода для каждой модели покупки, например пути к файлам и форматы данных.

АсинкМоделКонфиг

Информация для асинхронного решения одной модели оптимизации.

Поля
display_ name

string

Необязательный. Определяемое пользователем имя модели может использоваться пользователями в качестве псевдонима для отслеживания моделей.

input_ config

InputConfig

Необходимый. Информация о входной модели.

output_ config

OutputConfig

Необходимый. Требуемая информация о местоположении вывода.

Пакетная оптимизацияToursResponse

Этот тип не имеет полей.

Ответ на BatchOptimizeToursRequest . Он возвращается в длительной операции после завершения операции.

BreakRule

Правила создания временных перерывов для транспортного средства (например, перерывы на обед). Перерыв — это непрерывный период времени, в течение которого транспортное средство простаивает на своем текущем месте и не может совершить ни одного визита. Обрыв может произойти:

  • во время путешествия между двумя посещениями (включая время непосредственно перед или сразу после посещения, но не в середине посещения), и в этом случае продлевается соответствующее транзитное время между посещениями,
  • или перед запуском автомобиля (автомобиль может не завестись в середине перерыва), в этом случае это не влияет на время запуска автомобиля.
  • или после окончания транспортного средства (то же самое, со временем окончания транспортного средства).
Поля
break_ requests[]

BreakRequest

Последовательность перерывов. См. сообщение BreakRequest .

frequency_ constraints[]

FrequencyConstraint

Могут применяться несколько FrequencyConstraint . Все они должны быть удовлетворены BreakRequest этого BreakRule . См. FrequencyConstraint .

Запрос на перерыв

Последовательность перерывов (т.е. их количество и порядок), применимых к каждому транспортному средству, должна быть известна заранее. Повторяющиеся BreakRequest определяют эту последовательность в том порядке, в котором они должны происходить. Их временные окна ( earliest_start_time / latest_start_time ) могут перекрываться, но они должны быть совместимы с порядком (это отмечено).

Поля
earliest_ start_ time

Timestamp

Необходимый. Нижняя граница (включительно) на начало перерыва.

latest_ start_ time

Timestamp

Необходимый. Верхняя граница (включительно) на начало перерыва.

min_ duration

Duration

Необходимый. Минимальная продолжительность перерыва. Должно быть позитивным.

Частотное ограничение

Можно дополнительно ограничить частоту и продолжительность перерывов, указанных выше, установив минимальную частоту перерывов, например: «Перерыв должен быть не менее 1 часа каждые 12 часов». Если предположить, что это можно интерпретировать как «В пределах любого скользящего временного окна продолжительностью 12 часов должен быть хотя бы один перерыв продолжительностью не менее одного часа», этот пример можно перевести в следующий FrequencyConstraint :

{
   min_break_duration { seconds: 3600 }         # 1 hour.
   max_inter_break_duration { seconds: 39600 }  # 11 hours (12 - 1 = 11).
}

Время и продолжительность перерывов в решении будут учитывать все подобные ограничения в дополнение к временным окнам и минимальной длительности, уже указанным в BreakRequest .

FrequencyConstraint на практике может применяться к непоследовательным перерывам. Например, следующий график учитывает пример «1 час каждые 12 часов»:

  04:00 vehicle start
   .. performing travel and visits ..
  09:00 1 hour break
  10:00 end of the break
   .. performing travel and visits ..
  12:00 20-min lunch break
  12:20 end of the break
   .. performing travel and visits ..
  21:00 1 hour break
  22:00 end of the break
   .. performing travel and visits ..
  23:59 vehicle end
Поля
min_ break_ duration

Duration

Необходимый. Минимальная продолжительность перерыва для этого ограничения. Неотрицательный. См. описание FrequencyConstraint .

max_ inter_ break_ duration

Duration

Необходимый. Максимально допустимый интервал любого интервала времени в маршруте, который не включает хотя бы частично перерыв duration >= min_break_duration . Должно быть позитивным.

Формат данных

Форматы данных для входных и выходных файлов.

Перечисления
DATA_FORMAT_UNSPECIFIED Недопустимое значение. Формат не должен быть UNSPECIFIED.
JSON Обозначение объектов JavaScript.
PROTO_TEXT Текстовый формат протокольных буферов. См. https://protobuf.dev/reference/protobuf/textformat-spec/.

Предел расстояния

Предел, определяющий максимальное расстояние, которое можно преодолеть. Он может быть как твердым, так и мягким.

Если определен мягкий предел, как soft_max_meters , так и cost_per_kilometer_above_soft_max должны быть определены и быть неотрицательными.

Поля
max_ meters

int64

Жесткий предел, ограничивающий расстояние не более max_meters. Предел должен быть неотрицательным.

soft_ max_ meters

int64

Мягкое ограничение не обеспечивает соблюдение ограничения максимального расстояния, но его нарушение приводит к затратам, которые суммируются с другими затратами, определенными в модели, в той же единице измерения.

Если определено, soft_max_meters должно быть меньше max_meters и должно быть неотрицательным.

cost_ per_ kilometer_ below_ soft_ max

double

Стоимость понесенного километража увеличивается до soft_max_meters по формуле:

  min(distance_meters, soft_max_meters) / 1000.0 *
  cost_per_kilometer_below_soft_max.

Эта стоимость не поддерживается в route_distance_limit .

cost_ per_ kilometer_ above_ soft_ max

double

Стоимость за километр, если расстояние превышает предел soft_max_meters . Дополнительная стоимость равна 0, если расстояние меньше допустимого, в противном случае для расчета стоимости используется следующая формула:

  (distance_meters - soft_max_meters) / 1000.0 *
  cost_per_kilometer_above_soft_max.

Стоимость должна быть неотрицательной.

GcsDestination

Местоположение Google Cloud Storage, куда будут записаны выходные файлы.

Поля
uri

string

Необходимый. URI облачного хранилища Google.

GcsИсточник

Местоположение Google Cloud Storage, из которого будет считываться входной файл.

Поля
uri

string

Необходимый. URI объекта Google Cloud Storage в формате gs://bucket/path/to/object .

Ограничение введенного решения

Решение, добавленное в запрос, включая информацию о том, какие посещения следует ограничить и как их следует ограничить.

Поля
routes[]

ShipmentRoute

Пути введения раствора. Некоторые маршруты могут быть исключены из исходного решения. Маршруты и пропущенные поставки должны удовлетворять основным предположениям достоверности, перечисленным для injected_first_solution_routes .

skipped_ shipments[]

SkippedShipment

Пропущены поставки раствора для инъекций. Некоторые из них могут быть исключены из исходного решения. См. поле routes .

constraint_ relaxations[]

ConstraintRelaxation

Для нуля или более групп транспортных средств указывает, когда и насколько ослаблять ограничения. Если это поле пусто, все непустые маршруты транспортных средств полностью ограничены.

ОграничениеРелаксация

Для группы транспортных средств указывается, при каком пороге(ах) ограничения на посещение будут смягчены и до какого уровня. Отгрузки, перечисленные в поле skipped_shipment , могут быть пропущены; т. е. они не могут быть выполнены.

Поля
relaxations[]

Relaxation

Все ослабления ограничений на посещение, которые будут применяться к посещениям маршрутов с транспортными средствами в vehicle_indices .

vehicle_ indices[]

int32

Указывает индексы транспортных средств, к которым применяются relaxations ограничений на посещение. Если оно пустое, оно считается значением по умолчанию, и relaxations применяются ко всем транспортным средствам, которые не указаны в других constraint_relaxations . Может быть не более одного значения по умолчанию, т. е. не более одного поля ослабления ограничений может быть пустым vehicle_indices . Индекс транспортного средства может быть указан только один раз, даже в пределах нескольких constraint_relaxations .

Индекс транспортного средства отображается так же, как ShipmentRoute.vehicle_index , если interpret_injected_solutions_using_labels имеет значение true (см. комментарий к fields ).

Релаксация

Если relaxations пусто, время начала и последовательность всех посещений routes полностью ограничиваются, и никакие новые посещения не могут быть вставлены или добавлены к этим маршрутам. Кроме того, время начала и окончания движения транспортного средства на routes полностью ограничено, если только транспортное средство не пусто (т. е. не имеет посещений и для used_if_route_is_empty в модели установлено значение false).

relaxations(i).level определяет уровень ослабления ограничений, применяемый к посещению #j, который удовлетворяет:

  • route.visits(j).start_time >= relaxations(i).threshold_time И
  • j + 1 >= relaxations(i).threshold_visit_count

Аналогично, запуск транспортного средства расслабляется до relaxations(i).level если он удовлетворяет:

  • vehicle_start_time >= relaxations(i).threshold_time И
  • relaxations(i).threshold_visit_count == 0 , и конец транспортного средства расслабляется до relaxations(i).level , если он удовлетворяет:
  • vehicle_end_time >= relaxations(i).threshold_time И
  • route.visits_size() + 1 >= relaxations(i).threshold_visit_count

Чтобы применить уровень релаксации, если посещение соответствует threshold_visit_count ИЛИ threshold_time добавьте два relaxations с одним и тем же level : один с установленным только threshold_visit_count , а другой с установленным только threshold_time . Если посещение удовлетворяет условиям многократного relaxations , применяется наиболее расслабленный уровень. В результате от начала движения транспортного средства до посещения маршрута до конца транспортного средства уровень релаксации становится более расслабленным: т.е. уровень релаксации не снижается по мере прохождения маршрута.

Время и последовательность посещений маршрута, которые не удовлетворяют пороговым условиям каких-либо relaxations , полностью ограничены, и никакие посещения не могут быть вставлены в эти последовательности. Также, если начало или конец транспортного средства не удовлетворяет условиям какого-либо расслабления, время фиксируется, если только транспортное средство не пустое.

Поля
level

Level

Уровень ослабления ограничений, который применяется, когда условия в threshold_time или после него И хотя бы threshold_visit_count удовлетворены.

threshold_ time

Timestamp

Время, в течение которого или после которого может быть применен level релаксации.

threshold_ visit_ count

int32

Количество посещений, во время или после которого может быть применен level релаксации. Если threshold_visit_count равен 0 (или не установлен), level можно применять непосредственно при запуске транспортного средства.

Если это route.visits_size() + 1 , level можно применить только к концу транспортного средства. Если оно больше, чем route.visits_size() + 1 , level вообще не применяется к этому маршруту.

Уровень

Выражает различные уровни ослабления ограничений, которые применяются к посещению и после него, когда оно удовлетворяет пороговым условиям.

Ниже перечислено в порядке возрастания релаксации.

Перечисления
LEVEL_UNSPECIFIED

Неявный уровень ослабления по умолчанию: никакие ограничения не ослабляются, т. е. все посещения полностью ограничены.

Это значение не должно быть явно использовано в level .

RELAX_VISIT_TIMES_AFTER_THRESHOLD Время начала посещений и время начала/окончания посещения транспортных средств будут смягчены, но каждое посещение остается привязанным к одному и тому же транспортному средству, и необходимо соблюдать последовательность посещений: ни одно посещение не может быть вставлено между ними или перед ними.
RELAX_VISIT_TIMES_AND_SEQUENCE_AFTER_THRESHOLD То же, что RELAX_VISIT_TIMES_AFTER_THRESHOLD , но последовательность посещений также смягчена: посещения могут выполняться только этим транспортным средством, но потенциально могут стать невыполненными.
RELAX_ALL_AFTER_THRESHOLD То же, что RELAX_VISIT_TIMES_AND_SEQUENCE_AFTER_THRESHOLD , но транспортное средство также расслаблено: посещения полностью бесплатны в пороговое время или после него и потенциально могут стать невыполненными.

Инпутконфиг

Укажите входные данные для [BatchOptimizeTours][google.maps.routeoptimization.v1.RouteOptimizationService.BatchOptimizeTours].

Поля
data_ format

DataFormat

Необходимый. Формат входных данных.

source поля Союза. Необходимый. source может быть только одним из следующих:
gcs_ source

GcsSource

Местоположение облачного хранилища Google. Это должен быть один объект (файл).

Расположение

Инкапсулирует местоположение (географическую точку и необязательный заголовок).

Поля
lat_ lng

LatLng

Географические координаты путевой точки.

heading

int32

Курс компаса связан с направлением потока транспорта. Это значение используется для указания стороны дороги, которая будет использоваться для посадки и высадки. Значения курса могут быть от 0 до 360, где 0 указывает направление на север, 90 указывает направление на восток и т. д.

ОптимизироватьТурЗапрос

Запрос должен быть передан специалисту по оптимизации туров, который определяет модель доставки для решения, а также параметры оптимизации.

Поля
parent

string

Необходимый. Целевой проект или место для звонка.

Формат: * projects/{project-id} * projects/{project-id}/locations/{location-id}

Если местоположение не указано, регион будет выбран автоматически.

timeout

Duration

Если этот тайм-аут установлен, сервер возвращает ответ до истечения периода тайм-аута или достижения крайнего срока сервера для синхронных запросов, в зависимости от того, что наступит раньше.

Для асинхронных запросов сервер сгенерирует решение (если возможно) до истечения времени ожидания.

model

ShipmentModel

Модель отгрузки, которую нужно решить.

solving_ mode

SolvingMode

По умолчанию режим решения DEFAULT_SOLVE (0).

search_ mode

SearchMode

Режим поиска, используемый для решения запроса.

injected_ first_ solution_ routes[]

ShipmentRoute

Помогите алгоритму оптимизации найти первое решение, похожее на предыдущее.

Модель ограничена при построении первого решения. Любые перевозки, не осуществляемые по маршруту, неявно пропускаются в первом решении, но могут выполняться в последующих решениях.

Решение должно удовлетворять некоторым основным предположениям достоверности:

  • для всех маршрутов vehicle_index должен находиться в диапазоне и не дублироваться.
  • для всех посещений shipment_index и visit_request_index должны находиться в допустимом диапазоне.
  • Отгрузка может быть указана только на одном маршруте.
  • Самовывоз отправления самовывоз-доставка должен быть осуществлен до доставки.
  • Может быть реализовано не более одного варианта самовывоза или варианта доставки отправления.
  • для всех маршрутов время увеличивается (т. е. vehicle_start_time <= visits[0].start_time <= visits[1].start_time ... <= vehicle_end_time ).
  • Отгрузка может осуществляться только на разрешенном к перевозке транспортном средстве. Транспортное средство разрешено, если Shipment.allowed_vehicle_indices пусто или его vehicle_index включен в Shipment.allowed_vehicle_indices .

Если введенное решение невозможно, ошибка проверки не обязательно возвращается, вместо этого может быть возвращена ошибка, указывающая на невозможность.

injected_ solution_ constraint

InjectedSolutionConstraint

Ограничьте алгоритм оптимизации поиском окончательного решения, похожего на предыдущее решение. Например, это можно использовать для заморозки частей маршрутов, которые уже завершены или которые должны быть завершены, но не должны быть изменены.

Если введенное решение невозможно, ошибка проверки не обязательно возвращается, вместо этого может быть возвращена ошибка, указывающая на невозможность.

refresh_ details_ routes[]

ShipmentRoute

Если поле не пусто, данные маршруты будут обновлены без изменения базовой последовательности посещений или времени в пути: будут обновлены только другие сведения. Это не решает модель.

Начиная с 2020/11 года, это заполняет только полилинии непустых маршрутов и требует, чтобы populate_polylines имело значение true.

Поля route_polyline переданных маршрутов могут не соответствовать transitions маршрутов.

Это поле не должно использоваться вместе с injected_first_solution_routes или injected_solution_constraint .

Shipment.ignore и Vehicle.ignore не влияют на поведение. Полилинии по-прежнему заполняются между всеми посещениями на всех непустых маршрутах независимо от того, игнорируются ли соответствующие перевозки или транспортные средства.

interpret_ injected_ solutions_ using_ labels

bool

Если это правда:

  • использует ShipmentRoute.vehicle_label вместо vehicle_index для сопоставления маршрутов во внедренном решении с транспортными средствами в запросе; повторно использует сопоставление исходного ShipmentRoute.vehicle_index с новым ShipmentRoute.vehicle_index для обновления ConstraintRelaxation.vehicle_indices , если оно не пусто, но сопоставление должно быть однозначным (т. е. несколько ShipmentRoute не должны использовать один и тот же исходный vehicle_index ).
  • использует ShipmentRoute.Visit.shipment_label вместо shipment_index для сопоставления посещений во внедренном решении с отгрузками в запросе;
  • использует SkippedShipment.label вместо SkippedShipment.index для сопоставления пропущенных поставок во внедренном решении с отгрузками по запросу.

Эта интерпретация применяется к полям injected_first_solution_routes , injected_solution_constraint и refresh_details_routes . Его можно использовать, когда индексы отгрузки или транспортного средства в запросе изменились с момента создания решения, возможно, потому, что отгрузки или транспортные средства были удалены из запроса или добавлены в него.

Если это правда, метки в следующих категориях должны появляться не более одного раза в своей категории:

Если vehicle_label во внедренном решении не соответствует запрошенному транспортному средству, соответствующий маршрут удаляется из решения вместе с его посещениями. Если shipment_label во внедренном решении не соответствует запросу на отправку, соответствующее посещение удаляется из решения. Если SkippedShipment.label во внедренном решении не соответствует запросу на отправку, SkippedShipment удаляется из решения.

Удаление посещений маршрута или целых маршрутов из внедренного решения может повлиять на подразумеваемые ограничения, что может привести к изменению решения, ошибкам проверки или неосуществимости.

ПРИМЕЧАНИЕ. Вызывающий объект должен гарантировать, что каждый Vehicle.label (соответственно Shipment.label ) уникально идентифицирует объект транспортного средства (соответственно отгрузку), используемый в двух соответствующих запросах: прошлом запросе, который создал OptimizeToursResponse используемый во внедренном решении, и текущем запросе, который включает внедренное решение. Описанных выше проверок уникальности недостаточно, чтобы гарантировать выполнение этого требования.

consider_ road_ traffic

bool

Учитывайте оценку трафика при вычислении полей ShipmentRoute Transition.travel_duration , Visit.start_time и vehicle_end_time ; при настройке поля ShipmentRoute.has_traffic_infeasibilities и при расчете поля OptimizeToursResponse.total_cost .

populate_ polylines

bool

Если это правда, полилинии будут заполнены в ответах ShipmentRoute .

populate_ transition_ polylines

bool

Если это правда, полилинии и токены маршрута будут заполнены в ответе ShipmentRoute.transitions .

allow_ large_ deadline_ despite_ interruption_ risk

bool

Если этот параметр установлен, то срок выполнения запроса (см. https://grpc.io/blog/deadlines ) может составлять до 60 минут. В противном случае максимальный срок составляет всего 30 минут. Обратите внимание, что долгоживущие запросы имеют значительно больший (но все же небольшой) риск прерывания.

use_ geodesic_ distances

bool

Если это правда, расстояния путешествия будут рассчитываться с использованием геодезических расстояний вместо расстояний Google Maps, а время в пути будет рассчитываться с использованием геодезических расстояний со скоростью, определяемой geodesic_meters_per_second .

label

string

Метка, которая может использоваться для идентификации этого запроса, указана в OptimizeToursResponse.request_label .

geodesic_ meters_ per_ second

double

Если use_geodesic_distances имеет значение true, это поле должно быть установлено и определяет скорость, применяемую для расчета времени в пути. Его значение должно быть не менее 1,0 метра/секунду.

max_ validation_ errors

int32

Усекает количество возвращаемых ошибок проверки. Эти ошибки обычно прикрепляются к полезным данным ошибки INVALID_ARGUMENT в виде сведений об ошибке BadRequest ( https://cloud.google.com/apis/design/errors#error_details) , за исключением случаев, когда solve_mode=VALIDATE_ONLY: см. поле OptimizeToursResponse.validation_errors . По умолчанию это значение равно 100 и ограничено 10 000.

Режим поиска

Режим, определяющий поведение поиска, компромисс между задержкой и качеством решения. Во всех режимах применяется глобальный крайний срок запроса.

Перечисления
SEARCH_MODE_UNSPECIFIED Неуказанный режим поиска, эквивалентный RETURN_FAST .
RETURN_FAST Остановите поиск после того, как найдете первое хорошее решение.
CONSUME_ALL_AVAILABLE_TIME Потратьте все свободное время на поиск лучших решений.

Режим решения

Определяет, как решатель должен обрабатывать запрос. Во всех режимах, кроме VALIDATE_ONLY , если запрос недействителен, вы получите ошибку INVALID_REQUEST . См. max_validation_errors , чтобы ограничить количество возвращаемых ошибок.

Перечисления
DEFAULT_SOLVE Решите модель. Предупреждения могут быть выданы в [OptimizeToursResponse.validation_errors][google.cloud.optimization.v1.OptimizeToursResponse.validation_errors].
VALIDATE_ONLY Только проверяет модель, не решая ее: заполняет как можно больше OptimizeToursResponse.validation_errors .
DETECT_SOME_INFEASIBLE_SHIPMENTS

Заполняет только OptimizeToursResponse.validation_errors или OptimizeToursResponse.skipped_shipments и фактически не решает остальную часть запроса ( status и routes в ответе не заданы). Если обнаруживаются неосуществимые возможности в маршрутах injected_solution_constraint они заполняются в поле OptimizeToursResponse.validation_errors , а поле OptimizeToursResponse.skipped_shipments остается пустым.

ВАЖНО : сюда возвращаются не все невозможные отправки, а только те, которые определены как невозможные в ходе предварительной обработки.

OptimizeToursResponse

Ответ после решения задачи оптимизации тура, содержащий маршруты, по которым движется каждое транспортное средство, пропущенные поставки и общую стоимость решения.

Поля
routes[]

ShipmentRoute

Маршруты рассчитываются для каждого транспортного средства; i-й маршрут соответствует i-му транспортному средству в модели.

request_ label

string

Копия OptimizeToursRequest.label , если в запросе была указана метка.

skipped_ shipments[]

SkippedShipment

Список всех отправлений пропущен.

validation_ errors[]

OptimizeToursValidationError

Список всех ошибок валидации, которые нам удалось обнаружить самостоятельно. См. объяснение «НЕСКОЛЬКО ОШИБОК» для сообщения OptimizeToursValidationError . Вместо ошибок будут выдаваться предупреждения в случае, если solving_mode имеет значение DEFAULT_SOLVE .

metrics

Metrics

Показатели продолжительности, расстояния и использования для этого решения.

Метрики

Общие показатели, агрегированные по всем маршрутам.

Поля
aggregated_ route_ metrics

AggregatedMetrics

Агрегировано по маршрутам. Каждая метрика представляет собой сумму (или максимум для загрузок) по всем одноименным полям ShipmentRoute.metrics .

skipped_ mandatory_ shipment_ count

int32

Количество пропущенных обязательных отправок.

used_ vehicle_ count

int32

Количество используемых автомобилей. Примечание. Если маршрут транспортного средства пуст и Vehicle.used_if_route_is_empty имеет значение true, транспортное средство считается использованным.

earliest_ vehicle_ start_ time

Timestamp

Самое раннее время начала подержанного автомобиля, вычисляемое как минимальное для всех подержанных автомобилей ShipmentRoute.vehicle_start_time .

latest_ vehicle_ end_ time

Timestamp

Самое позднее время окончания для подержанного автомобиля, вычисляемое как максимальное для всех подержанных автомобилей ShipmentRoute.vehicle_end_time .

costs

map<string, double>

Стоимость решения с разбивкой по полям запроса, связанным со стоимостью. Ключи — это пути прототипов относительно входных данных OptimizeToursRequest, например «model.shipments.pickups.cost», а значения — это общая стоимость, сгенерированная соответствующим полем стоимости, агрегированная по всему решению. Другими словами, затраты["model.shipments.pickups.cost"] — это сумма всех затрат на самовывоз в рамках решения. Здесь подробно представлены все затраты, определенные в модели, за исключением затрат, связанных с TransitionAttributes, которые по состоянию на 2022/01 г. сообщаются только в агрегированном виде.

total_ cost

double

Полная стоимость решения. Сумма всех значений на карте затрат.

Оптимизетурсвалидатионеррор

Описывает ошибку или предупреждение, возникающее при проверке OptimizeToursRequest .

Поля
code

int32

Ошибка проверки определяется парой ( code , display_name ), которая всегда присутствует.

Поля, следующие за этим разделом, предоставляют дополнительную информацию об ошибке.

НЕСКОЛЬКО ОШИБОК : при наличии нескольких ошибок процесс проверки пытается вывести несколько из них. Как и компилятор, это несовершенный процесс. Некоторые ошибки проверки будут «фатальными», то есть они останавливают весь процесс проверки. Это относится, среди прочего, к ошибкам display_name="UNSPECIFIED" . Некоторые ошибки могут привести к тому, что процесс проверки пропустит другие ошибки.

СТАБИЛЬНОСТЬ : code и display_name должны быть очень стабильными. Но со временем могут появиться новые коды и отображаемые имена, что может привести к тому, что данный (недействительный) запрос выдаст другую пару ( code , display_name ), поскольку новая ошибка скрыла старую. Например, см. «НЕСКОЛЬКО ОШИБОК».

display_ name

string

Отображаемое имя ошибки.

fields[]

FieldReference

Контекст ошибки может включать 0, 1 (в большинстве случаев) или более полей. Например, обращение к транспортному средству № 4 и первому забору груза № 2 можно выполнить следующим образом:

fields { name: "vehicles" index: 4}
fields { name: "shipments" index: 2 sub_field {name: "pickups" index: 0} }

Однако обратите внимание, что количество fields не должно меняться для данного кода ошибки.

error_ message

string

Читаемая человеком строка, описывающая ошибку. Между code и error_message существует соотношение 1:1 (когда code != "UNSPECIFIED").

СТАБИЛЬНОСТЬ : Нестабильно: сообщение об ошибке, связанное с данным code может со временем измениться (надеюсь, чтобы это прояснить). Вместо этого полагайтесь на display_name и code .

offending_ values

string

Может содержать значения полей. Это не всегда доступно. На него совершенно не следует полагаться и использовать его только для ручной отладки модели.

ПолеReference

Указывает контекст для ошибки проверки. FieldReference всегда ссылается на данное поле в этом файле и имеет одну и ту же иерархическую структуру. Например, мы можем указать элемент №2 в start_time_windows транспортного средства №5, используя:

name: "vehicles" index: 5 sub_field { name: "end_time_windows" index: 2 }

Однако мы опускаем объекты верхнего уровня, такие как OptimizeToursRequest или ShipmentModel чтобы не перегружать сообщение.

Поля
name

string

Имя поля, например, «транспортные средства».

sub_ field

FieldReference

Рекурсивно вложенное подполе, если необходимо.

Поле объединения index_or_key .

index_or_key может быть только одним из следующих:

index

int32

Индекс поля, если оно повторяется.

key

string

Ключ, если поле является картой.

Выходная конфигурация

Укажите место назначения для результатов [BatchOptimizeTours][google.maps.routeoptimization.v1.RouteOptimizationService.BatchOptimizeTours].

Поля
data_ format

DataFormat

Необходимый. Формат выходных данных.

destination поля Союза. Необходимый. destination может быть только одним из следующих:
gcs_ destination

GcsDestination

Местоположение Google Cloud Storage, в которое можно записать выходные данные.

Модификаторы маршрута

Инкапсулирует набор дополнительных условий, которые необходимо выполнить при расчете маршрутов транспортных средств. Это похоже на RouteModifiers в предпочтительном API маршрутов платформы Google Maps; см.: https://developers.google.com/maps/documentation/routes/reference/rest/v2/RouteModifiers .

Поля
avoid_ tolls

bool

Указывает, следует ли избегать платных дорог, где это возможно. Предпочтение будет отдано маршрутам, не содержащим платных дорог. Применяется только к моторизованным режимам движения.

avoid_ highways

bool

Указывает, следует ли избегать шоссе, где это возможно. Предпочтение будет отдано маршрутам, не содержащим автомобильных дорог. Применяется только к моторизованным режимам движения.

avoid_ ferries

bool

Указывает, следует ли избегать паромов, где это возможно. Предпочтение будет отдано маршрутам, не предполагающим переезды на паромах. Применяется только к моторизованным режимам движения.

avoid_ indoor

bool

Необязательный. Указывает, следует ли избегать навигации в помещении, где это возможно. Предпочтение будет отдано маршрутам, не содержащим внутренней навигации. Применяется только к режиму движения WALKING .

Отгрузка

Отгрузка одного товара от одного его получения до одной из доставок. Чтобы отгрузка считалась выполненной, уникальное транспортное средство должно посетить один из пунктов выдачи (и соответственно уменьшить свои запасные мощности), а затем посетить один из пунктов доставки позже (и, следовательно, соответствующим образом повторно увеличить свои запасные мощности).

Поля
display_ name

string

Определяемое пользователем отображаемое имя отправления. Он может иметь длину до 63 символов и может использовать символы UTF-8.

pickups[]

VisitRequest

Набор вариантов получения, связанных с отправкой. Если не указано иное, транспортному средству необходимо посетить только место, соответствующее доставке.

deliveries[]

VisitRequest

Набор альтернатив доставки, связанных с отправкой. Если не указано иное, транспортному средству необходимо посетить только место, соответствующее пикапу.

load_ demands

map<string, Load >

Требования к загрузке груза (например, вес, объем, количество поддонов и т. д.). Ключами в карте должны быть идентификаторы, описывающие тип соответствующей нагрузки, в идеале также включающие единицы измерения. Например: «вес_кг», «объем_галлонов», «поддон_количество» и т. д. Если данный ключ не отображается на карте, соответствующая нагрузка считается нулевой.

allowed_ vehicle_ indices[]

int32

Набор транспортных средств, которые могут выполнить данную перевозку. Если пусто, все транспортные средства могут это сделать. Транспортные средства задаются по их индексу в списке vehicles ShipmentModel .

costs_ per_ vehicle[]

double

Указывает затраты, возникающие при доставке груза каждым транспортным средством. Если указано, оно должно иметь ЛИБО:

  • то же количество элементов, что и costs_per_vehicle_indices . costs_per_vehicle[i] соответствует costs_per_vehicle_indices[i] модели.
  • столько же элементов, сколько транспортных средств в модели. Элемент I-TH соответствует транспортному средству #I модели.

Эти затраты должны быть в той же единице, что и penalty_cost и не должны быть отрицательными. Оставьте это поле пустым, если такими затратами нет.

costs_ per_ vehicle_ indices[]

int32

Индексы транспортных средств, к которым применяется costs_per_vehicle Если не пустые, он должен иметь одинаковое количество элементов, что и costs_per_vehicle . Индекс транспортного средства не может быть указан более одного раза. Если транспортное средство исключено из costs_per_vehicle_indices , его стоимость равна нулю.

pickup_ to_ delivery_ absolute_ detour_ limit

Duration

Указывает максимальное абсолютное время обхода по сравнению с кратчайшим пути от пикапа до доставки. Если указано, он должен быть неотрицательным, а отгрузка должна содержать хотя бы пикап и доставку.

Например, пусть t - самое короткое время, необходимое, чтобы перейти из выбранной альтернативы пикапа непосредственно к выбранной альтернативе доставки. Затем настройка pickup_to_delivery_absolute_detour_limit обеспечивает соблюдение:

start_time(delivery) - start_time(pickup) <=
t + pickup_to_delivery_absolute_detour_limit

Если как относительные, так и абсолютные пределы указаны на одной и той же отгрузке, более ограниченный предел используется для каждой возможной пары пикапа/доставки. По состоянию на 2017/10 объезд поддерживаются только тогда, когда продолжительность путешествий не зависят от транспортных средств.

pickup_ to_ delivery_ time_ limit

Duration

Указывает максимальную продолжительность от начала пикапа для начала доставки отгрузки. Если указано, он должен быть неотрицательным, а отгрузка должна содержать хотя бы пикап и доставку. Это не зависит от того, какие альтернативы выбраны для получения и доставки, а также от скорости автомобиля. Это может быть указано наряду с максимальными ограничениями обхода: решение будет уважать обе технические характеристики.

shipment_ type

string

Непустые строки, указывающая «тип» для этой партии. Эта функция может быть использована для определения несовместимости или требований между shipment_types (см. shipment_type_incompatibilities and shipment_type_requirements в ShipmentModel ).

Отличается от visit_types , который указан для одного посещения: все пикап/доставка, принадлежащие к одной и той же отправке, имеют одну и ту же shipment_type .

label

string

Определяет этикетку для этой партии. Эта ярлыка сообщается в ответе в shipment_label соответствующего ShipmentRoute.Visit .

ignore

bool

Если это правда, пропустите эту партию, но не применяйте penalty_cost .

Игнорирование отгрузки приводит к ошибке проверки, когда в модели есть какая -либо shipment_type_requirements .

Игнорирование отгрузки, которая выполняется в injected_first_solution_routes или injected_solution_constraint , разрешено; Решатель удаляет связанные с ними посещения пикапа/доставки с маршрута выполнения. precedence_rules , которые ссылаются на игнорируемые поставки также будут игнорироваться.

penalty_ cost

double

Если отправка не завершена, этот штраф добавляется к общей стоимости маршрутов. Отгрузка считается завершенной, если посещается одна из его альтернативы по доставке. Стоимость может быть выражена в одной и той же единице, используемом для всех других связанных с затратами полей в модели, и должна быть положительной.

Важно : если этот штраф не указан, оно считается бесконечным, то есть отгрузка должна быть завершена.

pickup_ to_ delivery_ relative_ detour_ limit

double

Указывает максимальное относительное время обхода по сравнению с кратчайшим пути от пикапа до доставки. Если указано, он должен быть неотрицательным, а отгрузка должна содержать хотя бы пикап и доставку.

Например, пусть t - самое короткое время, необходимое, чтобы перейти из выбранной альтернативы пикапа непосредственно к выбранной альтернативе доставки. Затем настройка pickup_to_delivery_relative_detour_limit обеспечивает соблюдение:

start_time(delivery) - start_time(pickup) <=
std::ceil(t * (1.0 + pickup_to_delivery_relative_detour_limit))

Если как относительные, так и абсолютные пределы указаны на одной и той же отгрузке, более ограниченный предел используется для каждой возможной пары пикапа/доставки. По состоянию на 2017/10 объезд поддерживаются только тогда, когда продолжительность путешествий не зависят от транспортных средств.

Нагрузка

При выполнении посещения предопределенная сумма может быть добавлена ​​в нагрузку автомобиля, если это пикап, или вычитается, если это доставка. Это сообщение определяет такую ​​сумму. Смотрите load_demands .

Поля
amount

int64

Сумма, по которой груз транспортного средства, выполняющего соответствующий посещение, будет варьироваться. Поскольку это целое число, пользователям рекомендуется выбрать подходящую единицу, чтобы избежать потери точности. Должен быть ≥ 0.

Визит

Запрос на посещение, которое может быть совершено транспортным средством: он имеет гео-расположение (или два, см. Ниже), время открытия и закрытия, представленное временными окнами, и время продолжительности обслуживания (время, проведенное транспортным средством после того, как он прибыл на получение или сброс товаров).

Поля
arrival_ location

LatLng

Гео-локация, где автомобиль прибывает при выполнении этого VisitRequest . Если модель отгрузки имеет матрицы расстояния продолжительности, arrival_location не должно быть указано.

arrival_ waypoint

Waypoint

Путь, где автомобиль прибывает при выполнении этого VisitRequest . Если модель отгрузки имеет матрицы расстояния продолжительности, нельзя указать arrival_waypoint .

departure_ location

LatLng

Гео-локация, где автомобиль уходит после завершения этого VisitRequest . Может быть пропущено, если это то же самое, что и arrival_location . Если модель отгрузки имеет матрицы расстояния продолжительности, departure_location не должен быть указан.

departure_ waypoint

Waypoint

Путь, где автомобиль уходит после завершения этого VisitRequest . Может быть пропущен, если он такой же, как arrival_waypoint . Если модель отгрузки имеет матрицы расстояния продолжительности, departure_waypoint не должен быть указан.

tags[]

string

Определяет теги, прикрепленные к запросу посещения. Пустые или дублирующие строки не допускаются.

time_ windows[]

TimeWindow

Временные окна, которые ограничивают время прибытия при посещении. Обратите внимание, что транспортное средство может вылететь за пределами окна времени прибытия, то есть время прибытия + продолжительность не нужно находиться внутри временного окна. Это может привести к времени ожидания, если автомобиль прибывает до TimeWindow.start_time .

Отсутствие TimeWindow означает, что автомобиль может выполнить это посещение в любое время.

Временные окна должны быть не смешаны, т.е. ни одно временное окно не должно перекрываться или быть рядом с другим, и они должны находиться в растущем порядке.

cost_per_hour_after_soft_end_time и soft_end_time можно установить только в том случае, если есть одно временное окно.

duration

Duration

Продолжительность посещения, то есть время, проведенное транспортным средством между прибытием и отъездом (должно быть добавлено в возможное время ожидания; см. time_windows ).

cost

double

Стоимость обслуживания этого запроса посещения на маршруте автомобиля. Это может быть использовано для оплаты разных затрат для каждого альтернативного пикапа или доставки отгрузки. Эта стоимость должна быть в той же единице, что и Shipment.penalty_cost и не должна быть отрицательной.

load_ demands

map<string, Load >

Требования нагрузки этого запроса на посещение. Это похоже на поле Shipment.load_demands , за исключением того, что оно относится только к этому VisitRequest а не к всей Shipment . Требования, перечисленные здесь, добавляются к требованиям, перечисленным в Shipment.load_demands .

visit_ types[]

string

Указывает типы визита. Это может использоваться для выделения дополнительного времени, необходимого для автомобиля, чтобы завершить это посещение (см. Vehicle.extra_visit_duration_for_visit_type ).

Тип может появиться только один раз.

label

string

Определяет этикетку для этого VisitRequest . Эта ярлыка сообщается в ответе как visit_label в соответствующей ShipmentRoute.Visit .

ShipmentModel

Модель отгрузки содержит набор поставок, которые должны выполняться набором транспортных средств, при этом минимизируя общую стоимость, которая является суммой:

  • Стоимость маршрутизации транспортных средств (сумма стоимости за общее время, стоимость за время в пути и фиксированная стоимость по всем транспортным средствам).
  • Неопроверженные штрафы отгрузки.
  • стоимость глобальной продолжительности поставок
Поля
shipments[]

Shipment

Набор поставок, которые должны быть выполнены в модели.

vehicles[]

Vehicle

Набор транспортных средств, которые можно использовать для выполнения посещений.

global_ start_ time

Timestamp

Глобальное время начала и окончания модели: НЕТ ВРЕМЕННЫЕ ВРЕМЕНИ ВРЕМЯ этого диапазона нельзя считать действительным.

Пролет времени модели должен составлять менее года, то есть global_end_time и global_start_time должны быть в течение 31536000 секунд друг от друга.

При использовании полей cost_per_*hour , вы можете установить это окно на меньший интервал для повышения производительности (например, если вы моделируете один день, вам следует установить глобальные временные ограничения на тот день). Если unset, 00:00:00 UTC, 1 января 1970 года (то есть секунд: 0, нано: 0) используется в качестве дефолта.

global_ end_ time

Timestamp

Если unset, 00:00:00 UTC, 1 января 1971 года (то есть секунд: 31536000, нано: 0) используется в качестве дефолта.

global_ duration_ cost_ per_ hour

double

«Глобальная продолжительность» общего плана - это разница между самым ранним эффективным временем начала и последним эффективным временем окончания всех транспортных средств. Пользователи могут назначать стоимость в час этому количеству, чтобы попытаться оптимизировать, например, для самого раннего завершения работы. Эта стоимость должна быть в той же единице, что и Shipment.penalty_cost .

duration_ distance_ matrices[]

DurationDistanceMatrix

Определяет матрицы продолжительности и расстояния, используемых в модели. Если это поле пустое, вместо этого будут использоваться карты Google или геодезические расстояния, в зависимости от значения поля use_geodesic_distances . Если он не пуст, use_geodesic_distances не может быть правдой, и ни duration_distance_matrix_src_tags , ни duration_distance_matrix_dst_tags не могут быть пустыми.

Примеры использования:

  • Есть два места: Loca и LOCB.
  • 1 автомобиль, начинающий свой маршрут в Loca и заканчивая его в Loca.
  • 1 Запрос на посещение в LOCB.
model {
  vehicles { start_tags: "locA"  end_tags: "locA" }
  shipments { pickups { tags: "locB" } }
  duration_distance_matrix_src_tags: "locA"
  duration_distance_matrix_src_tags: "locB"
  duration_distance_matrix_dst_tags: "locA"
  duration_distance_matrix_dst_tags: "locB"
  duration_distance_matrices {
    rows {  # from: locA
      durations { seconds: 0 }   meters: 0    # to: locA
      durations { seconds: 100 } meters: 1000 # to: locB
    }
    rows {  # from: locB
      durations { seconds: 102 } meters: 990 # to: locA
      durations { seconds: 0 }   meters: 0   # to: locB
    }
  }
}
  • Есть три места: loca, locb и locc.
  • 1 автомобиль, начинающий свой маршрут в Loca и заканчивая его в LOCB, используя матрицу "Fast".
  • 1 автомобиль, начинающий свой маршрут в LOCB и заканчивая его в LOCB, используя матрицу «медленная».
  • 1 автомобиль, начинающий свой маршрут в LOCB и заканчивая его в LOCB, используя матрицу "Fast".
  • 1 Запрос на посещение в LOCC.
model {
  vehicles { start_tags: "locA" end_tags: "locB" start_tags: "fast" }
  vehicles { start_tags: "locB" end_tags: "locB" start_tags: "slow" }
  vehicles { start_tags: "locB" end_tags: "locB" start_tags: "fast" }
  shipments { pickups { tags: "locC" } }
  duration_distance_matrix_src_tags: "locA"
  duration_distance_matrix_src_tags: "locB"
  duration_distance_matrix_src_tags: "locC"
  duration_distance_matrix_dst_tags: "locB"
  duration_distance_matrix_dst_tags: "locC"
  duration_distance_matrices {
    vehicle_start_tag: "fast"
    rows {  # from: locA
      durations { seconds: 1000 } meters: 2000 # to: locB
      durations { seconds: 600 }  meters: 1000 # to: locC
    }
    rows {  # from: locB
      durations { seconds: 0 }   meters: 0    # to: locB
      durations { seconds: 700 } meters: 1200 # to: locC
    }
    rows {  # from: locC
      durations { seconds: 702 } meters: 1190 # to: locB
      durations { seconds: 0 }   meters: 0    # to: locC
    }
  }
  duration_distance_matrices {
    vehicle_start_tag: "slow"
    rows {  # from: locA
      durations { seconds: 1800 } meters: 2001 # to: locB
      durations { seconds: 900 }  meters: 1002 # to: locC
    }
    rows {  # from: locB
      durations { seconds: 0 }    meters: 0    # to: locB
      durations { seconds: 1000 } meters: 1202 # to: locC
    }
    rows {  # from: locC
      durations { seconds: 1001 } meters: 1195 # to: locB
      durations { seconds: 0 }    meters: 0    # to: locC
    }
  }
}
duration_ distance_ matrix_ src_ tags[]

string

Теги, определяющие источники продолжительности и матриц расстояния; duration_distance_matrices(i).rows(j) определяет продолжительность и расстояния от посещений с тегом duration_distance_matrix_src_tags(j) до других посещений в матрице i.

Теги соответствуют VisitRequest.tags или Vehicle.start_tags . Данный VisitRequest или Vehicle должно соответствовать точному тегу в этом поле. Обратите внимание, что источник, пункт назначения и матричные теги Vehicle могут быть такими же; Точно так же источник и теги VisitRequest может быть одинаковым. Все теги должны быть разными и не могут быть пустыми струнами. Если это поле не является пустым, то duration_distance_matrices не должно быть пустым.

duration_ distance_ matrix_ dst_ tags[]

string

Теги, определяющие направления по прочтению и дистанционным матрицам; duration_distance_matrices(i).rows(j).durations(k) duration_distance_matrix_src_tags(j) duration_distance_matrices(i).rows(j).meters(k)) duration_distance_matrix_dst_tags(k)

Теги соответствуют VisitRequest.tags или Vehicle.start_tags . Данный VisitRequest или Vehicle должно соответствовать точному тегу в этом поле. Обратите внимание, что источник, пункт назначения и матричные теги Vehicle могут быть такими же; Точно так же источник и теги VisitRequest может быть одинаковым. Все теги должны быть разными и не могут быть пустыми струнами. Если это поле не является пустым, то duration_distance_matrices не должно быть пустым.

transition_ attributes[]

TransitionAttributes

Переходные атрибуты добавлены в модель.

shipment_ type_ incompatibilities[]

ShipmentTypeIncompatibility

Наборы несовместимой отгрузки_types (см. ShipmentTypeIncompatibility

shipment_ type_ requirements[]

ShipmentTypeRequirement

Наборы требований shipment_type (см. ShipmentTypeRequirement

precedence_ rules[]

PrecedenceRule

Набор правил приоритета, которые должны быть применены в модели.

Важно : использование правил приоритета ограничивает размер проблемы, которая может быть оптимизирована. Запросы с использованием правил приоритета, которые включают в себя многие поставки, могут быть отклонены.

max_ active_ vehicles

int32

Ограничивает максимальное количество активных транспортных средств. Автомобиль активен, если его маршрут выполняет по крайней мере одну отправку. Это может быть использовано для ограничения количества маршрутов в случае, когда водителей меньше, чем транспортных средств, и что парк транспортных средств является неоднородным. Затем оптимизация выберет наилучшее подмножество транспортных средств для использования. Должен быть строго положительным.

DurationDistanceMatrix

Определяет матрицу продолжительности и расстояния от мест посещения и запуска автомобиля для посещения и местоположения автомобиля.

Поля
rows[]

Row

Указывает ряды матрицы продолжительности и расстояния. У него должно быть столько элементов, сколько и ShipmentModel.duration_distance_matrix_src_tags .

vehicle_ start_ tag

string

Определение тега, к которому применяются транспортные средства. Если это пусто, это относится ко всем транспортным средствам, и там может быть только одна матрица.

Каждый старт автомобиля должен соответствовать ровской матрице, т.е. точно одно из их поля start_tags должно соответствовать vehicle_start_tag матрицы (и только этой матрицы).

Все матрицы должны иметь другой vehicle_start_tag .

Ряд

Указывает ряд матрицы продолжительности и расстояния.

Поля
durations[]

Duration

Значения продолжительности для данной строки. У него должно быть столько элементов, сколько и ShipmentModel.duration_distance_matrix_dst_tags .

meters[]

double

Значения расстояния для данной строки. Если никакие затраты или ограничения относятся к расстояниям в модели, это можно оставить пустым; В противном случае он должен иметь столько элементов, сколько и durations .

Предшествующий

Правило приоритета между двумя событиями (каждое событие - это пикап или доставка отгрузки): событие «Второе» должно начать, по крайней мере, offset_duration после начала «первого».

Несколько предложений могут ссылаться на те же (или связанные) события, например, «пикап B происходит после доставки« и «пикап C происходит после пикапа B».

Кроме того, предыдущие средства применяются только тогда, когда обе поставки выполняются и в противном случае игнорируются.

Поля
first_ is_ delivery

bool

Указывает, является ли «первое» событие доставкой.

second_ is_ delivery

bool

Указывает, является ли событие «второе» доставкой.

offset_ duration

Duration

Смещение между «первым» и «вторым» событием. Это может быть отрицательным.

first_ index

int32

Индекс отправки "первого" события. Это поле должно быть указано.

second_ index

int32

Индекс отправки "второго" события. Это поле должно быть указано.

Отгрузка

Маршрут транспортного средства может быть разложен, вдоль оси временной, как это (мы предполагаем, что есть n визитов):

  |            |            |          |       |  T[2], |        |      |
  | Transition |  Visit #0  |          |       |  V[2], |        |      |
  |     #0     |    aka     |   T[1]   |  V[1] |  ...   | V[n-1] | T[n] |
  |  aka T[0]  |    V[0]    |          |       | V[n-2],|        |      |
  |            |            |          |       | T[n-1] |        |      |
  ^            ^            ^          ^       ^        ^        ^      ^
vehicle    V[0].start   V[0].end     V[1].   V[1].    V[n].    V[n]. vehicle
 start     (arrival)   (departure)   start   end      start    end     end

Обратите внимание, что мы имеем разницу между:

  • «пунктуальные события», такие как начало и запуск автомобиля, и начало и конец каждого посещения (он же прибытие и отъезд). Они случаются на данную секунду.
  • «интервалы времени», такие как сами визиты, и переход между посещениями. Хотя временные интервалы могут иногда иметь нулевую продолжительность, то есть запуска и заканчиваться в ту же секунду, они часто имеют положительную продолжительность.

Инварианты:

  • Если есть n посещений, есть n+1 переходов.
  • Визит всегда окружен переходом перед ним (тот же индекс) и переходом после него (индекс + 1).
  • За запуском автомобиля всегда следует переход № 0.
  • Конец автомобиля всегда предшествует переход #N.

Увеличение, вот что происходит во время Transition и Visit :

---+-------------------------------------+-----------------------------+-->
   |           TRANSITION[i]             |           VISIT[i]          |
   |                                     |                             |
   |  * TRAVEL: the vehicle moves from   |      PERFORM the visit:     |
   |    VISIT[i-1].departure_location to |                             |
   |    VISIT[i].arrival_location, which |  * Spend some time:         |
   |    takes a given travel duration    |    the "visit duration".    |
   |    and distance                     |                             |
   |                                     |  * Load or unload           |
   |  * BREAKS: the driver may have      |    some quantities from the |
   |    breaks (e.g. lunch break).       |    vehicle: the "demand".   |
   |                                     |                             |
   |  * WAIT: the driver/vehicle does    |                             |
   |    nothing. This can happen for     |                             |
   |    many reasons, for example when   |                             |
   |    the vehicle reaches the next     |                             |
   |    event's destination before the   |                             |
   |    start of its time window         |                             |
   |                                     |                             |
   |  * DELAY: *right before* the next   |                             |
   |    arrival. E.g. the vehicle and/or |                             |
   |    driver spends time unloading.    |                             |
   |                                     |                             |
---+-------------------------------------+-----------------------------+-->
   ^                                     ^                             ^
V[i-1].end                           V[i].start                    V[i].end

Наконец, вот как могут быть организованы путешествия, перерывы, задержка и ожидание во время перехода.

  • Они не перекрываются.
  • Задержка уникальна и должна быть смежный период времени прямо перед следующим посещением (или конец автомобиля). Таким образом, достаточно знать продолжительность задержки, чтобы узнать его время начала и окончания.
  • Перерывы являются смежными, не перекрывающимися периодами времени. Ответ указывает время начала и продолжительность каждого перерыва.
  • Путешествие и ожидание «превентивные»: их можно прервать несколько раз во время этого перехода. Клиенты могут предположить, что путешествие происходит «как можно скорее», и что «подождать» заполняет оставшееся время.

A (комплексный) пример:

                               TRANSITION[i]
--++-----+-----------------------------------------------------------++-->
  ||     |       |           |       |           |         |         ||
  ||  T  |   B   |     T     |       |     B     |         |    D    ||
  ||  r  |   r   |     r     |   W   |     r     |    W    |    e    ||
  ||  a  |   e   |     a     |   a   |     e     |    a    |    l    ||
  ||  v  |   a   |     v     |   i   |     a     |    i    |    a    ||
  ||  e  |   k   |     e     |   t   |     k     |    t    |    y    ||
  ||  l  |       |     l     |       |           |         |         ||
  ||     |       |           |       |           |         |         ||
--++-----------------------------------------------------------------++-->
Поля
vehicle_ index

int32

Транспортное средство, выполняющее маршрут, идентифицированный по его индексу в исходной ShipmentModel .

vehicle_ label

string

Метка транспортного средства, выполняющего этот маршрут, равный ShipmentModel.vehicles(vehicle_index).label , если указано.

vehicle_ start_ time

Timestamp

Время, в которое автомобиль начинает свой маршрут.

vehicle_ end_ time

Timestamp

Время, в которое автомобиль заканчивает свой маршрут.

visits[]

Visit

Упорядоченная последовательность посещений, представляющих маршрут. Посещения [i] это визит на маршруте. Если это поле пустое, транспортное средство считается неиспользованным.

transitions[]

Transition

Заказанный список переходов для маршрута.

has_ traffic_ infeasibilities

bool

Когда OptimizeToursRequest.consider_road_traffic устанавливается на TRUE, это поле указывает, что несоответствия во время маршрута прогнозируются с использованием оценок продолжительности движения на основе движения. Может быть недостаточно времени, чтобы завершить поездок на поправку на движение, задержки и перерывы между посещениями, до первого посещения или после последнего посещения, в то же время удовлетворяя окнам визита и времени транспортного средства. Например,

  start_time(previous_visit) + duration(previous_visit) +
  travel_duration(previous_visit, next_visit) > start_time(next_visit)

Прибытие в next_visit, вероятно, произойдет позже, чем его текущее временное окно из -за повышенной оценки Travel Time travel_duration(previous_visit, next_visit) из -за трафика. Кроме того, перерыв может быть вынужден перекрываться с посещением из -за увеличения оценок времени в пути и посещения или преодоления ограничений по времени.

route_ polyline

EncodedPolyline

Кодированное полилиновое представление маршрута. Это поле заполнено только если OptimizeToursRequest.populate_polylines устанавливается на true.

breaks[]

Break

Перерывы запланированы для автомобиля, выполняющего этот маршрут. Последовательность breaks представляет интервалы времени, каждая из которых начинается с соответствующей start_time и продолжительной duration секунд.

metrics

AggregatedMetrics

Продолжительность, показатели расстояния и нагрузки для этого маршрута. Поля AggregatedMetrics суммируются во ShipmentRoute.visits ShipmentRoute.transitions .

route_ costs

map<string, double>

Стоимость маршрута, разбитая по областям запроса, связанных с затратами. Ключи - это прото -пути, по сравнению с входным оптимизацией, например, «model.shipments.pickups.cost», и значения являются общей стоимостью, полученной по соответствующему полю затрат, агрегированным по всему маршруту. Другими словами, затраты ["model.shipments.pickups.cost"] - это сумма всех затрат на получение по маршруту. Все затраты, определенные в модели, подробно сообщаются здесь, за исключением затрат, связанных с переходными атмосферами, которые сообщаются только агрегированным образом по состоянию на 2022/01.

route_ total_ cost

double

Общая стоимость маршрута. Сумма всех затрат на карте затрат.

Перерыв

Данные, представляющие выполнение перерыва.

Поля
start_ time

Timestamp

Время начала перерыва.

duration

Duration

Продолжительность перерыва.

Кодидополилайн

Кодированное представление полилинии. Более подробную информацию о кодировании полилины можно найти здесь: https://developers.google.com/maps/documentation/uteliets/polylinealgorithm https://developers.google.com/maps/documentation/javascript/reference/geometry#encoding .

Поля
points

string

Строка, представляющая кодируемые точки полилинии.

Переход

Переход между двумя событиями на маршруте. См. Описание ShipmentRoute .

Если транспортное средство не имеет start_location и/или end_location , соответствующие метрики движения составляют 0.

Поля
travel_ duration

Duration

Продолжительность путешествий во время этого перехода.

travel_ distance_ meters

double

Расстояние проходило во время перехода.

traffic_ info_ unavailable

bool

Когда трафик запрашивается с помощью OptimizeToursRequest.consider_road_traffic , а информация о трафике не может быть извлечена для Transition , этот логический язык устанавливается на True. Это может быть временным (редкий сбой на серверах трафика в реальном времени) или постоянным (нет данных для этого места).

delay_ duration

Duration

Сумма длительности задержки применяется к этому переходу. Если таковые имеются, задержка начинается точно по сравнению delay_duration несколько секунд до следующего события (посещение или конец автомобиля). См. TransitionAttributes.delay .

break_ duration

Duration

Сумма продолжительности разрывов, возникающих во время этого перехода, если таковые имеются. Подробная информация о времени начала и продолжительности каждого перерыва хранится в ShipmentRoute.breaks .

wait_ duration

Duration

Время, проведенное в ожидании во время этого перехода. Продолжительность ожидания соответствует временю простоя и не включает время перерыва. Также обратите внимание, что это время ожидания может быть разделено на несколько непосредственных интервалов.

total_ duration

Duration

Общая продолжительность перехода, предоставлена ​​для удобства. Это равно:

  • Следующее посещение start_time (или vehicle_end_time , если это последний переход) - этот переход start_time ;
  • Если ShipmentRoute.has_traffic_infeasibilities .
  • Break_duration + wait_duration`.
start_ time

Timestamp

Время начала этого перехода.

route_ polyline

EncodedPolyline

Кодированное полилиновое представление маршрута, последовавшего во время перехода. Это поле заполнено только если populate_transition_polylines установлено на TRUE.

route_ token

string

Только вывод. Непрозрачный токен, который можно передать в SDK навигации для восстановления маршрута во время навигации, и, в случае перенаправления, соблюдайте первоначальное намерение, когда был создан маршрут. Обратитесь к этому токен как непрозрачный каплей. Не сравнивайте его значение по запросам, так как его значение может измениться, даже если служба возвращает тот же маршрут. Это поле заполнено только если populate_transition_polylines установлено на TRUE.

vehicle_ loads

map<string, VehicleLoad >

Загрузка транспортных средств во время этого перехода, для каждого типа, который либо появляется в автомобиле этого Vehicle.load_limits . Shipment.load_demands

Нагрузки во время первого перехода являются начальные нагрузки маршрута автомобиля. Затем, после каждого посещения, посещение load_demands либо добавлены, либо вычитаются, чтобы получить нагрузки следующего перехода, в зависимости от того, был ли посещение пикапом или доставкой.

Автомобильная загрузка

Сообщает фактическую нагрузку транспортного средства в какой -то момент вдоль маршрута, для данного типа (см. Transition.vehicle_loads ).

Поля
amount

int64

Количество нагрузки на автомобиль, для данного типа. Единица нагрузки обычно обозначается типом. См. Transition.vehicle_loads .

Посещать

Визит, выполненный на маршруте. Этот визит соответствует пикапу или доставке Shipment .

Поля
shipment_ index

int32

Индекс поля shipments в исходном ShipmentModel .

is_ pickup

bool

Если это правда, посещение соответствует выводу Shipment . В противном случае это соответствует доставке.

visit_ request_ index

int32

Индекс VisitRequest в поле для выбора или доставки Shipment (см. is_pickup ).

start_ time

Timestamp

Время, в которое начинается визит. Обратите внимание, что автомобиль может прибыть раньше, чем в месте посещения. Времена согласуются с ShipmentModel .

load_ demands

map<string, Load >

Общее спрос на загрузку посещения в качестве суммы отгрузки и запроса на посещение load_demands . Значения отрицательны, если посещение является доставкой. Требования сообщаются для тех же типов, что и Transition.loads (см. Это поле).

detour

Duration

Дополнительное время обхода из -за поставки, посещаемых на маршруте перед посещением, и потенциального времени ожидания, вызванного временными окнами. Если посещение является доставкой, объезд вычисляется из соответствующего посещения пикапа и равна:

start_time(delivery) - start_time(pickup)
- (duration(pickup) + travel duration from the pickup location
to the delivery location).

В противном случае он вычисляется из start_location транспортного средства и равен:

start_time - vehicle_start_time - travel duration from
the vehicle's `start_location` to the visit.
shipment_ label

string

Копия соответствующей Shipment.label Shipment

visit_ label

string

Копия соответствующего VisitRequest.label VisitRequest

Отгрузка

Определяет несовместимости между поставками в зависимости от их отгрузки_type. Появление несовместимых поставки на том же маршруте ограничено на основе режима несовместимости.

Поля
types[]

string

Список несовместимых типов. Две отправки, имеющие разные shipment_types среди перечисленных, «несовместимы».

incompatibility_ mode

IncompatibilityMode

Режим применяется к несовместимости.

Несовместимость

Режимы, определяющие, как появление несовместимых поставки ограничено на одном и том же маршруте.

Перечисление
INCOMPATIBILITY_MODE_UNSPECIFIED Неуказанный режим несовместимости. Это значение никогда не должно использоваться.
NOT_PERFORMED_BY_SAME_VEHICLE В этом режиме две поставки с несовместимыми типами никогда не могут разделить один и тот же автомобиль.
NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY

Для двух поставок с несовместимыми типами с помощью режима несовместимости NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY несовместимость:

  • Если оба являются только пикапами (без доставки) или только доставки (без пикапов), они вообще не могут разделить одно и то же автомобиль.
  • Если у одной из поставки есть доставка, а другая - пикап, две поставки могут разделить один и тот же автомобиль, если бывшая отправка доставляется до того, как последняя будет поднят.

Отгрузка

Определяет требования между поставками на основе их отгрузки_type. Специфика требования определяется режимом требований.

Поля
required_ shipment_ type_ alternatives[]

string

Список альтернативных типов отгрузки, необходимых для dependent_shipment_types .

dependent_ shipment_ types[]

string

Все поставки с типом в поле dependent_shipment_types требуют, чтобы по крайней мере одна отправка типа required_shipment_type_alternatives для посещения по одному и тому же маршруту.

ПРИМЕЧАНИЕ. Цепочки требований, так что shipment_type зависит от себя, не допускаются.

requirement_ mode

RequirementMode

Режим применяется к требованию.

Требование

Режимы, определяющие внешний вид зависимых отгрузок на маршруте.

Перечисление
REQUIREMENT_MODE_UNSPECIFIED Неуказанный режим требования. Это значение никогда не должно использоваться.
PERFORMED_BY_SAME_VEHICLE В этом режиме все «зависимые» поставки должны иметь то же автомобиль, что и по крайней мере одна из их «требуемых» поставки.
IN_SAME_VEHICLE_AT_PICKUP_TIME

В режиме IN_SAME_VEHICLE_AT_PICKUP_TIME все «зависимые» поставки должны иметь по крайней мере одну «требуемую» отгрузку на своем транспортном средстве во время их выбора.

Таким образом, «зависимый» выписка должен иметь либо:

  • Только доставка «требуется», доставленная по маршруту после, или
  • «Требуемая» отгрузка, поднятая на маршруте перед ним, и если «требуемая» отправка имеет доставку, эта доставка должна выполняться после получения «зависимой» отгрузки.
IN_SAME_VEHICLE_AT_DELIVERY_TIME То же, что и раньше, за исключением того, что «зависимые» поставки должны иметь «обязательную» отправку на их транспортное средство во время их доставки .

Пропущенная

Определяет подробную информацию о неэффективных постах в решении. Для тривиальных случаев и/или, если мы можем определить причину для прохождения, мы сообщаем о причине здесь.

Поля
index

int32

Индекс соответствует индексу отгрузки в исходной ShipmentModel .

label

string

Копия соответствующей Shipment.label Shipment

reasons[]

Reason

Список причин, которые объясняют, почему отправка была пропущена. См. Комментарий выше Reason . Если мы не можем понять, почему отправка была пропущена, причины не будут установлены.

Причина

Если мы сможем объяснить, почему отправка была пропущена, здесь будут перечислены причины. Если причина не совпадает для всех транспортных средств, reason будет иметь более 1 элемента. Пропущенная отгрузка не может иметь дублирования причин, т.е. там, где все поля одинаковы, за исключением, например, example_vehicle_index . Пример:

reasons {
  code: DEMAND_EXCEEDS_VEHICLE_CAPACITY
  example_vehicle_index: 1
  example_exceeded_capacity_type: "Apples"
}
reasons {
  code: DEMAND_EXCEEDS_VEHICLE_CAPACITY
  example_vehicle_index: 3
  example_exceeded_capacity_type: "Pears"
}
reasons {
  code: CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DISTANCE_LIMIT
  example_vehicle_index: 1
}

Пропущенная партия несовместима со всеми транспортными средствами. Причины могут быть разными для всех транспортных средств, но, по крайней мере, будет превышена вместимость «яблоков» одного транспортного средства (включая транспортное средство 1), по крайней мере, будет превышена пропускная способность одного транспортного средства (включая транспортное средство 3), и, по крайней мере, ограничение расстояния одного транспортного средства (включая транспортное средство 1).

Поля
code

Code

Обратитесь к комментариям кода.

example_ exceeded_ capacity_ type

string

Если код причины является DEMAND_EXCEEDS_VEHICLE_CAPACITY , документируют один тип емкости, который превышен.

example_ vehicle_ index

int32

Если причина связана с несовместимостью транспортных средств отгрузки, это поле предоставляет индекс одного соответствующего транспортного средства.

Код

Код идентифицирует тип причины. Порядок здесь бессмыслен. В частности, это не дает никаких признаков того, появится ли данная причина в другой в решении, если оба применяются.

Перечисление
CODE_UNSPECIFIED Это никогда не следует использовать.
NO_VEHICLE В модели нет транспортного средства, делающего все поставки невозможными.
DEMAND_EXCEEDS_VEHICLE_CAPACITY Требование отгрузки превышает емкость транспортного средства для некоторых типов емкости, один из которых является example_exceeded_capacity_type .
CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DISTANCE_LIMIT

Минимальное расстояние, необходимое для выполнения этой партии, то есть от start_location транспортного средства до посадки и/или доставки груза, а также местоположения транспортного средства превышает route_distance_limit .

Обратите внимание, что для этого вычисления мы используем геодезические расстояния.

CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DURATION_LIMIT

Минимальное время, необходимое для выполнения этой доставки, включая время в пути, время ожидания и время обслуживания, превышает route_duration_limit автомобиля.

Примечание. Время в пути вычисляется в лучшем сценарии, а именно в виде геодезического расстояния x 36 м/с (примерно 130 км/час).

CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TRAVEL_DURATION_LIMIT То же, что и выше, но мы сравниваем только минимальное время в пути и транспортное средство travel_duration_limit .
CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TIME_WINDOWS Автомобиль не может выполнить эту партию в сценарии с наилучшим образом (см. CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DURATION_LIMIT для вычисления времени), если он начнется в самое раннее время начала: общее время сделает транспортное средство после его последнего времени окончания.
VEHICLE_NOT_ALLOWED Поле allowed_vehicle_indices отгрузки не является пустым, и это транспортное средство не принадлежит ему.

TimeWindow

Временные окна ограничивают время события, например, время прибытия в посещение или время начала и окончания транспортного средства.

Границы окна трудного времени, start_time и end_time , обеспечивают самое раннее и последнее время события, так что start_time <= event_time <= end_time . Мягкое временное окно, нижняя граница, soft_start_time , выражает предпочтение события, которое произойдет на или после или после soft_start_time , затрачивая стоимость, пропорциональную тому, как долго до того, как произойдет событие. Верхняя граница с мягким временным окном, soft_end_time , выражает предпочтение события, которое произойдет на или до или до soft_end_time , затрачивая стоимость, пропорциональную тому, как долго после soft_end_time событие происходит. start_time , end_time , soft_start_time и soft_end_time должен находиться в глобальных временных пределах (см. ShipmentModel.global_start_time и ShipmentModel.global_end_time ) и должен уважать:

  0 <= `start_time` <= `end_time` and
  0 <= `start_time` <= `soft_start_time` and
  0 <= `soft_end_time` <= `end_time`.
Поля
start_ time

Timestamp

Трудное время начала окна. Если не указано, это будет установлено на ShipmentModel.global_start_time .

end_ time

Timestamp

Трудное время окончания окна. Если не указано, это будет установлено на ShipmentModel.global_end_time .

soft_ start_ time

Timestamp

Мягкое время начала временного окна.

soft_ end_ time

Timestamp

Мягкое время окончания временного окна.

cost_ per_ hour_ before_ soft_ start_ time

double

Стоимость в час, добавленная к другим затратам в модели, если событие происходит перед Soft_Start_Time, вычисляется как:

   max(0, soft_start_time - t.seconds)
                          * cost_per_hour_before_soft_start_time / 3600,
t being the time of the event.

Эта стоимость должна быть положительной, и поле можно установить только в том случае, если установлен Soft_start_time.

cost_ per_ hour_ after_ soft_ end_ time

double

Стоимость в час, добавленная к другим затратам в модели, если событие происходит после soft_end_time , вычисленная как:

   max(0, t.seconds - soft_end_time.seconds)
                    * cost_per_hour_after_soft_end_time / 3600,
t being the time of the event.

Эта стоимость должна быть положительной, и поле можно установить только в том случае, если установлен soft_end_time .

Transitionattributes

Определяет атрибуты переходов между двумя последовательными посещениями по маршруту. Несколько TransitionAttributes могут применяться к одному и тому же переходу: в этом случае все дополнительные затраты увеличиваются, и применяется строгое ограничение или ограничение (после естественной »и« семантики).

Поля
src_ tag

string

Теги, определяющие набор (SRC-> DST) переходов, к этим атрибутам применяется.

Посещение источника или начало транспортного средства совпадает с тем, что его VisitRequest.tags или Vehicle.start_tags либо содержит src_tag , либо не содержит excluded_src_tag (в зависимости от того, какое из этих двух полей не является пустым).

excluded_ src_ tag

string

Смотрите src_tag . Точно один из src_tag и excluded_src_tag должен быть не пустым.

dst_ tag

string

Посещение пункта назначения или конец транспортного средства совпадает с тем, что его VisitRequest.tags или Vehicle.end_tags либо содержит dst_tag , либо не содержит excluded_dst_tag (в зависимости от того, какое из этих двух полей не является пустым).

excluded_ dst_ tag

string

Смотрите dst_tag . Точно один из dst_tag и excluded_dst_tag должен быть непустым.

cost

double

Определяет стоимость выполнения этого перехода. Это в той же единице, что и все другие затраты в модели, и не должно быть отрицательным. Он применяется поверх всех других существующих затрат.

cost_ per_ kilometer

double

Определяет стоимость за километр, применяемый на расстояние, пройденное при выполнении этого перехода. Это добавляется к любому транспортному средству. Vehicle.cost_per_kilometer указанный на транспортных средствах.

distance_ limit

DistanceLimit

Определяет ограничение на расстояние, пройденное во время выполнения этого перехода.

По состоянию на 2021/06 поддерживаются только мягкие пределы.

delay

Duration

Указывает задержку, понесенную при выполнении этого перехода.

Эта задержка всегда происходит после завершения посещения источника и перед началом посещения пункта назначения.

Транспортное средство

Моделируют транспортное средство в проблеме отгрузки. Решение проблемы отгрузки построит маршрут, начиная с start_location и заканчивается на end_location для этого автомобиля. Маршрут - это последовательность посещений (см ShipmentRoute ).

Поля
display_ name

string

Пользовательское имя отображаемого автомобиля. Это может быть до 63 символов в длину и может использовать символы UTF-8.

travel_ mode

TravelMode

Режим путешествий, который влияет на дороги, пригодные для автомобиля и его скорость. См. Также travel_duration_multiple .

route_ modifiers

RouteModifiers

Набор условий, чтобы удовлетворить, как это влияет на то, как рассчитывается маршруты для данного транспортного средства.

start_ location

LatLng

Географическое местоположение, где автомобиль начинается, прежде чем забрать любые поставки. Если не указано, автомобиль начинается с первого пикапа. Если модель отгрузки имеет матрицы продолжительности и расстояния, start_location не должен быть указан.

start_ waypoint

Waypoint

Путь, представляющая географическое местоположение, где автомобиль начинается, прежде чем забрать любые поставки. Если не указано ни start_waypoint , ни start_location , автомобиль начинается с первого пикапа. Если модель отгрузки имеет матрицы продолжительности и расстояния, start_waypoint не должен быть указан.

end_ location

LatLng

Географическое расположение, где транспортное средство заканчивается после того, как он завершил свой последний VisitRequest . Если не указано, ShipmentRoute транспортного средства заканчивается немедленно, когда он завершает свой последний VisitRequest . Если модель отгрузки имеет матрицы продолжительности и расстояния, end_location не должен быть указан.

end_ waypoint

Waypoint

Путь, представляющая географическое местоположение, где транспортное средство заканчивается после того, как он завершил свой последний VisitRequest . Если ни end_waypoint , ни end_location не указано, то транспортное средство ShipmentRoute заканчивается немедленно, когда он завершает свой последний VisitRequest . Если модель отгрузки имеет матрицы продолжительности и расстояния, end_waypoint не должен быть указан.

start_ tags[]

string

Specifies tags attached to the start of the vehicle's route.

Empty or duplicate strings are not allowed.

end_ tags[]

string

Specifies tags attached to the end of the vehicle's route.

Empty or duplicate strings are not allowed.

start_ time_ windows[]

TimeWindow

Time windows during which the vehicle may depart its start location. They must be within the global time limits (see ShipmentModel.global_* fields). If unspecified, there is no limitation besides those global time limits.

Time windows belonging to the same repeated field must be disjoint, ie no time window can overlap with or be adjacent to another, and they must be in chronological order.

cost_per_hour_after_soft_end_time and soft_end_time can only be set if there is a single time window.

end_ time_ windows[]

TimeWindow

Time windows during which the vehicle may arrive at its end location. They must be within the global time limits (see ShipmentModel.global_* fields). If unspecified, there is no limitation besides those global time limits.

Time windows belonging to the same repeated field must be disjoint, ie no time window can overlap with or be adjacent to another, and they must be in chronological order.

cost_per_hour_after_soft_end_time and soft_end_time can only be set if there is a single time window.

unloading_ policy

UnloadingPolicy

Unloading policy enforced on the vehicle.

load_ limits

map<string, LoadLimit >

Capacities of the vehicle (weight, volume, # of pallets for example). The keys in the map are the identifiers of the type of load, consistent with the keys of the Shipment.load_demands field. If a given key is absent from this map, the corresponding capacity is considered to be limitless.

cost_ per_ hour

double

Vehicle costs: all costs add up and must be in the same unit as Shipment.penalty_cost .

Cost per hour of the vehicle route. This cost is applied to the total time taken by the route, and includes travel time, waiting time, and visit time. Using cost_per_hour instead of just cost_per_traveled_hour may result in additional latency.

cost_ per_ traveled_ hour

double

Cost per traveled hour of the vehicle route. This cost is applied only to travel time taken by the route (ie, that reported in ShipmentRoute.transitions ), and excludes waiting time and visit time.

cost_ per_ kilometer

double

Cost per kilometer of the vehicle route. This cost is applied to the distance reported in the ShipmentRoute.transitions and does not apply to any distance implicitly traveled from the arrival_location to the departure_location of a single VisitRequest .

fixed_ cost

double

Fixed cost applied if this vehicle is used to handle a shipment.

used_ if_ route_ is_ empty

bool

This field only applies to vehicles when their route does not serve any shipments. It indicates if the vehicle should be considered as used or not in this case.

If true, the vehicle goes from its start to its end location even if it doesn't serve any shipments, and time and distance costs resulting from its start --> end travel are taken into account.

Otherwise, it doesn't travel from its start to its end location, and no break_rule or delay (from TransitionAttributes ) are scheduled for this vehicle. In this case, the vehicle's ShipmentRoute doesn't contain any information except for the vehicle index and label.

route_ duration_ limit

DurationLimit

Limit applied to the total duration of the vehicle's route. In a given OptimizeToursResponse , the route duration of a vehicle is the difference between its vehicle_end_time and vehicle_start_time .

travel_ duration_ limit

DurationLimit

Limit applied to the travel duration of the vehicle's route. In a given OptimizeToursResponse , the route travel duration is the sum of all its transitions.travel_duration .

route_ distance_ limit

DistanceLimit

Limit applied to the total distance of the vehicle's route. In a given OptimizeToursResponse , the route distance is the sum of all its transitions.travel_distance_meters .

extra_ visit_ duration_ for_ visit_ type

map<string, Duration >

Specifies a map from visit_types strings to durations. The duration is time in addition to VisitRequest.duration to be taken at visits with the specified visit_types . This extra visit duration adds cost if cost_per_hour is specified. Keys (ie visit_types ) cannot be empty strings.

If a visit request has multiple types, a duration will be added for each type in the map.

break_ rule

BreakRule

Describes the break schedule to be enforced on this vehicle. If empty, no breaks will be scheduled for this vehicle.

label

string

Specifies a label for this vehicle. This label is reported in the response as the vehicle_label of the corresponding ShipmentRoute .

ignore

bool

If true, used_if_route_is_empty must be false, and this vehicle will remain unused.

If a shipment is performed by an ignored vehicle in injected_first_solution_routes , it is skipped in the first solution but is free to be performed in the response.

If a shipment is performed by an ignored vehicle in injected_solution_constraint and any related pickup/delivery is constrained to remain on the vehicle (ie, not relaxed to level RELAX_ALL_AFTER_THRESHOLD ), it is skipped in the response. If a shipment has a non-empty allowed_vehicle_indices field and all of the allowed vehicles are ignored, it is skipped in the response.

travel_ duration_ multiple

double

Specifies a multiplicative factor that can be used to increase or decrease travel times of this vehicle. For example, setting this to 2.0 means that this vehicle is slower and has travel times that are twice what they are for standard vehicles. This multiple does not affect visit durations. It does affect cost if cost_per_hour or cost_per_traveled_hour are specified. This must be in the range [0.001, 1000.0]. If unset, the vehicle is standard, and this multiple is considered 1.0.

WARNING: Travel times will be rounded to the nearest second after this multiple is applied but before performing any numerical operations, thus, a small multiple may result in a loss of precision.

See also extra_visit_duration_for_visit_type below.

DurationLimit

A limit defining a maximum duration of the route of a vehicle. It can be either hard or soft.

When a soft limit field is defined, both the soft max threshold and its associated cost must be defined together.

Поля
max_ duration

Duration

A hard limit constraining the duration to be at most max_duration.

soft_ max_ duration

Duration

A soft limit not enforcing a maximum duration limit, but when violated makes the route incur a cost. This cost adds up to other costs defined in the model, with the same unit.

If defined, soft_max_duration must be nonnegative. If max_duration is also defined, soft_max_duration must be less than max_duration.

quadratic_ soft_ max_ duration

Duration

A soft limit not enforcing a maximum duration limit, but when violated makes the route incur a cost, quadratic in the duration. This cost adds up to other costs defined in the model, with the same unit.

If defined, quadratic_soft_max_duration must be nonnegative. If max_duration is also defined, quadratic_soft_max_duration must be less than max_duration , and the difference must be no larger than one day:

max_duration - quadratic_soft_max_duration <= 86400 seconds

cost_ per_ hour_ after_ soft_ max

double

Cost per hour incurred if the soft_max_duration threshold is violated. The additional cost is 0 if the duration is under the threshold, otherwise the cost depends on the duration as follows:

  cost_per_hour_after_soft_max * (duration - soft_max_duration)

The cost must be nonnegative.

cost_ per_ square_ hour_ after_ quadratic_ soft_ max

double

Cost per square hour incurred if the quadratic_soft_max_duration threshold is violated.

The additional cost is 0 if the duration is under the threshold, otherwise the cost depends on the duration as follows:

  cost_per_square_hour_after_quadratic_soft_max *
  (duration - quadratic_soft_max_duration)^2

The cost must be nonnegative.

LoadLimit

Defines a load limit applying to a vehicle, eg "this truck may only carry up to 3500 kg". See load_limits .

Поля
soft_ max_ load

int64

A soft limit of the load. See cost_per_unit_above_soft_max .

cost_ per_ unit_ above_ soft_ max

double

If the load ever exceeds soft_max_load along this vehicle's route, the following cost penalty applies (only once per vehicle): (load - soft_max_load ) * cost_per_unit_above_soft_max . All costs add up and must be in the same unit as Shipment.penalty_cost .

start_ load_ interval

Interval

The acceptable load interval of the vehicle at the start of the route.

end_ load_ interval

Interval

The acceptable load interval of the vehicle at the end of the route.

max_ load

int64

The maximum acceptable amount of load.

Интервал

Interval of acceptable load amounts.

Поля
min

int64

A minimum acceptable load. Must be ≥ 0. If they're both specified, min must be ≤ max .

max

int64

A maximum acceptable load. Must be ≥ 0. If unspecified, the maximum load is unrestricted by this message. If they're both specified, min must be ≤ max .

TravelMode

Travel modes which can be used by vehicles.

These should be a subset of the Google Maps Platform Routes API travel modes, see: https://developers.google.com/maps/documentation/routes/reference/rest/v2/RouteTravelMode

Note: WALKING routes are in beta and might sometimes be missing clear sidewalks or pedestrian paths. You must display this warning to the user for all walking routes that you display in your app.

Enums
TRAVEL_MODE_UNSPECIFIED Unspecified travel mode, equivalent to DRIVING .
DRIVING Travel mode corresponding to driving directions (car, ...).
WALKING Travel mode corresponding to walking directions.

UnloadingPolicy

Policy on how a vehicle can be unloaded. Applies only to shipments having both a pickup and a delivery.

Other shipments are free to occur anywhere on the route independent of unloading_policy .

Enums
UNLOADING_POLICY_UNSPECIFIED Unspecified unloading policy; deliveries must just occur after their corresponding pickups.
LAST_IN_FIRST_OUT Deliveries must occur in reverse order of pickups
FIRST_IN_FIRST_OUT Deliveries must occur in the same order as pickups

Waypoint

Encapsulates a waypoint. Waypoints mark arrival and departure locations of VisitRequests, and start and end locations of Vehicles.

Поля
side_ of_ road

bool

Необязательный. Indicates that the location of this waypoint is meant to have a preference for the vehicle to stop at a particular side of road. When you set this value, the route will pass through the location so that the vehicle can stop at the side of road that the location is biased towards from the center of the road. This option doesn't work for the 'WALKING' travel mode.

Union field location_type . Different ways to represent a location. location_type can be only one of the following:
location

Location

A point specified using geographic coordinates, including an optional heading.

place_ id

string

The POI place ID associated with the waypoint.

When using a place ID to specify arrival or departure location of a VisitRequest, use a place ID that is specific enough to determine a LatLng location for navigation to the place. For example, a place ID representing a building is suitable, but a place ID representing a road is discouraged.

,

Индекс

RouteOptimization

A service for optimizing vehicle tours.

Validity of certain types of fields:

  • google.protobuf.Timestamp
    • Times are in Unix time: seconds since 1970-01-01T00:00:00+00:00.
    • seconds must be in [0, 253402300799], ie in [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00].
    • nanos must be unset or set to 0.
  • google.protobuf.Duration
    • seconds must be in [0, 253402300799], ie in [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00].
    • nanos must be unset or set to 0.
  • google.type.LatLng
    • latitude must be in [-90.0, 90.0].
    • longitude must be in [-180.0, 180.0].
    • at least one of latitude and longitude must be non-zero.
BatchOptimizeTours

rpc BatchOptimizeTours( BatchOptimizeToursRequest ) returns ( Operation )

Optimizes vehicle tours for one or more OptimizeToursRequest messages as a batch.

This method is a Long Running Operation (LRO). The inputs for optimization ( OptimizeToursRequest messages) and outputs ( OptimizeToursResponse messages) are read from and written to Cloud Storage in user-specified format. Like the OptimizeTours method, each OptimizeToursRequest contains a ShipmentModel and returns an OptimizeToursResponse containing ShipmentRoute fields, which are a set of routes to be performed by vehicles minimizing the overall cost.

The user can poll operations.get to check the status of the LRO:

If the LRO done field is false, then at least one request is still being processed. Other requests may have completed successfully and their results are available in Cloud Storage.

If the LRO's done field is true, then all requests have been processed. Any successfully processed requests will have their results available in Cloud Storage. Any requests that failed will not have their results available in Cloud Storage. If the LRO's error field is set, then it contains the error from one of the failed requests.

Области авторизации

Требуется следующая область действия OAuth:

  • https://www.googleapis.com/auth/cloud-platform
IAM Permissions

Requires the following IAM permission on the parent resource:

  • routeoptimization.operations.create

For more information, see the IAM documentation .

OptimizeTours

rpc OptimizeTours( OptimizeToursRequest ) returns ( OptimizeToursResponse )

Sends an OptimizeToursRequest containing a ShipmentModel and returns an OptimizeToursResponse containing ShipmentRoute s, which are a set of routes to be performed by vehicles minimizing the overall cost.

A ShipmentModel model consists mainly of Shipment s that need to be carried out and Vehicle s that can be used to transport the Shipment s. The ShipmentRoute s assign Shipment s to Vehicle s. More specifically, they assign a series of Visit s to each vehicle, where a Visit corresponds to a VisitRequest , which is a pickup or delivery for a Shipment .

The goal is to provide an assignment of ShipmentRoute s to Vehicle s that minimizes the total cost where cost has many components defined in the ShipmentModel .

Области авторизации

Требуется следующая область действия OAuth:

  • https://www.googleapis.com/auth/cloud-platform
IAM Permissions

Requires the following IAM permission on the parent resource:

  • routeoptimization.locations.use

For more information, see the IAM documentation .

AggregatedMetrics

Aggregated metrics for ShipmentRoute (resp. for OptimizeToursResponse over all Transition and/or Visit (resp. over all ShipmentRoute ) elements.

Поля
performed_ shipment_ count

int32

Number of shipments performed. Note that a pickup and delivery pair only counts once.

travel_ duration

Duration

Total travel duration for a route or a solution.

wait_ duration

Duration

Total wait duration for a route or a solution.

delay_ duration

Duration

Total delay duration for a route or a solution.

break_ duration

Duration

Total break duration for a route or a solution.

visit_ duration

Duration

Total visit duration for a route or a solution.

total_ duration

Duration

The total duration should be equal to the sum of all durations above. For routes, it also corresponds to:

[ShipmentRoute.vehicle_end_time][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_end_time] - [ShipmentRoute.vehicle_start_time][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_start_time]
travel_ distance_ meters

double

Total travel distance for a route or a solution.

max_ loads

map<string, VehicleLoad >

Maximum load achieved over the entire route (resp. solution), for each of the quantities on this route (resp. solution), computed as the maximum over all Transition.vehicle_loads (resp. ShipmentRoute.metrics.max_loads .

BatchOptimizeToursMetadata

This type has no fields.

Operation metadata for BatchOptimizeToursRequest calls.

BatchOptimizeToursRequest

Request to batch optimize tours as an asynchronous operation. Each input file should contain one OptimizeToursRequest , and each output file will contain one OptimizeToursResponse . The request contains information to read/write and parse the files. All the input and output files should be under the same project.

Поля
parent

string

Необходимый. Target project and location to make a call.

Format: * projects/{project-id} * projects/{project-id}/locations/{location-id}

If no location is specified, a region will be chosen automatically.

model_ configs[]

AsyncModelConfig

Необходимый. Input/Output information each purchase model, such as file paths and data formats.

AsyncModelConfig

Information for solving one optimization model asynchronously.

Поля
display_ name

string

Необязательный. User defined model name, can be used as alias by users to keep track of models.

input_ config

InputConfig

Необходимый. Information about the input model.

output_ config

OutputConfig

Необходимый. The desired output location information.

BatchOptimizeToursResponse

This type has no fields.

Response to a BatchOptimizeToursRequest . This is returned in the Long Running Operation after the operation is complete.

BreakRule

Rules to generate time breaks for a vehicle (eg lunch breaks). A break is a contiguous period of time during which the vehicle remains idle at its current position and cannot perform any visit. A break may occur:

  • during the travel between two visits (which includes the time right before or right after a visit, but not in the middle of a visit), in which case it extends the corresponding transit time between the visits,
  • or before the vehicle start (the vehicle may not start in the middle of a break), in which case it does not affect the vehicle start time.
  • or after the vehicle end (ditto, with the vehicle end time).
Поля
break_ requests[]

BreakRequest

Sequence of breaks. See the BreakRequest message.

frequency_ constraints[]

FrequencyConstraint

Several FrequencyConstraint may apply. They must all be satisfied by the BreakRequest s of this BreakRule . See FrequencyConstraint .

BreakRequest

The sequence of breaks (ie their number and order) that apply to each vehicle must be known beforehand. The repeated BreakRequest s define that sequence, in the order in which they must occur. Their time windows ( earliest_start_time / latest_start_time ) may overlap, but they must be compatible with the order (this is checked).

Поля
earliest_ start_ time

Timestamp

Необходимый. Lower bound (inclusive) on the start of the break.

latest_ start_ time

Timestamp

Необходимый. Upper bound (inclusive) on the start of the break.

min_ duration

Duration

Необходимый. Minimum duration of the break. Must be positive.

FrequencyConstraint

One may further constrain the frequency and duration of the breaks specified above, by enforcing a minimum break frequency, such as "There must be a break of at least 1 hour every 12 hours". Assuming that this can be interpreted as "Within any sliding time window of 12h, there must be at least one break of at least one hour", that example would translate to the following FrequencyConstraint :

{
   min_break_duration { seconds: 3600 }         # 1 hour.
   max_inter_break_duration { seconds: 39600 }  # 11 hours (12 - 1 = 11).
}

The timing and duration of the breaks in the solution will respect all such constraints, in addition to the time windows and minimum durations already specified in the BreakRequest .

A FrequencyConstraint may in practice apply to non-consecutive breaks. For example, the following schedule honors the "1h every 12h" example:

  04:00 vehicle start
   .. performing travel and visits ..
  09:00 1 hour break
  10:00 end of the break
   .. performing travel and visits ..
  12:00 20-min lunch break
  12:20 end of the break
   .. performing travel and visits ..
  21:00 1 hour break
  22:00 end of the break
   .. performing travel and visits ..
  23:59 vehicle end
Поля
min_ break_ duration

Duration

Необходимый. Minimum break duration for this constraint. Nonnegative. See description of FrequencyConstraint .

max_ inter_ break_ duration

Duration

Необходимый. Maximum allowed span of any interval of time in the route that does not include at least partially a break of duration >= min_break_duration . Must be positive.

DataFormat

Data formats for input and output files.

Enums
DATA_FORMAT_UNSPECIFIED Invalid value, format must not be UNSPECIFIED.
JSON JavaScript Object Notation.
PROTO_TEXT Protocol Buffers text format. See https://protobuf.dev/reference/protobuf/textformat-spec/

DistanceLimit

A limit defining a maximum distance which can be traveled. It can be either hard or soft.

If a soft limit is defined, both soft_max_meters and cost_per_kilometer_above_soft_max must be defined and be nonnegative.

Поля
max_ meters

int64

A hard limit constraining the distance to be at most max_meters. The limit must be nonnegative.

soft_ max_ meters

int64

A soft limit not enforcing a maximum distance limit, but when violated results in a cost which adds up to other costs defined in the model, with the same unit.

If defined soft_max_meters must be less than max_meters and must be nonnegative.

cost_ per_ kilometer_ below_ soft_ max

double

Cost per kilometer incurred, increasing up to soft_max_meters , with formula:

  min(distance_meters, soft_max_meters) / 1000.0 *
  cost_per_kilometer_below_soft_max.

This cost is not supported in route_distance_limit .

cost_ per_ kilometer_ above_ soft_ max

double

Cost per kilometer incurred if distance is above soft_max_meters limit. The additional cost is 0 if the distance is under the limit, otherwise the formula used to compute the cost is the following:

  (distance_meters - soft_max_meters) / 1000.0 *
  cost_per_kilometer_above_soft_max.

The cost must be nonnegative.

GcsDestination

The Google Cloud Storage location where the output file(s) will be written to.

Поля
uri

string

Необходимый. Google Cloud Storage URI.

GcsSource

The Google Cloud Storage location where the input file will be read from.

Поля
uri

string

Необходимый. URI of a Google Cloud Storage object with the format gs://bucket/path/to/object .

InjectedSolutionConstraint

Solution injected in the request including information about which visits must be constrained and how they must be constrained.

Поля
routes[]

ShipmentRoute

Routes of the solution to inject. Some routes may be omitted from the original solution. The routes and skipped shipments must satisfy the basic validity assumptions listed for injected_first_solution_routes .

skipped_ shipments[]

SkippedShipment

Skipped shipments of the solution to inject. Some may be omitted from the original solution. See the routes field.

constraint_ relaxations[]

ConstraintRelaxation

For zero or more groups of vehicles, specifies when and how much to relax constraints. If this field is empty, all non-empty vehicle routes are fully constrained.

ConstraintRelaxation

For a group of vehicles, specifies at what threshold(s) constraints on visits will be relaxed and to which level. Shipments listed in the skipped_shipment field are constrained to be skipped; ie, they cannot be performed.

Поля
relaxations[]

Relaxation

All the visit constraint relaxations that will apply to visits on routes with vehicles in vehicle_indices .

vehicle_ indices[]

int32

Specifies the vehicle indices to which the visit constraint relaxations apply. If empty, this is considered the default and the relaxations apply to all vehicles that are not specified in other constraint_relaxations . There can be at most one default, ie, at most one constraint relaxation field is allowed empty vehicle_indices . A vehicle index can only be listed once, even within several constraint_relaxations .

A vehicle index is mapped the same as ShipmentRoute.vehicle_index , if interpret_injected_solutions_using_labels is true (see fields comment).

Relaxation

If relaxations is empty, the start time and sequence of all visits on routes are fully constrained and no new visits may be inserted or added to those routes. Also, a vehicle's start and end time in routes is fully constrained, unless the vehicle is empty (ie, has no visits and has used_if_route_is_empty set to false in the model).

relaxations(i).level specifies the constraint relaxation level applied to a visit #j that satisfies:

  • route.visits(j).start_time >= relaxations(i).threshold_time AND
  • j + 1 >= relaxations(i).threshold_visit_count

Similarly, the vehicle start is relaxed to relaxations(i).level if it satisfies:

  • vehicle_start_time >= relaxations(i).threshold_time AND
  • relaxations(i).threshold_visit_count == 0 and the vehicle end is relaxed to relaxations(i).level if it satisfies:
  • vehicle_end_time >= relaxations(i).threshold_time AND
  • route.visits_size() + 1 >= relaxations(i).threshold_visit_count

To apply a relaxation level if a visit meets the threshold_visit_count OR the threshold_time add two relaxations with the same level : one with only threshold_visit_count set and the other with only threshold_time set. If a visit satisfies the conditions of multiple relaxations , the most relaxed level applies. As a result, from the vehicle start through the route visits in order to the vehicle end, the relaxation level becomes more relaxed: ie, the relaxation level is non-decreasing as the route progresses.

The timing and sequence of route visits that do not satisfy the threshold conditions of any relaxations are fully constrained and no visits may be inserted into these sequences. Also, if a vehicle start or end does not satisfy the conditions of any relaxation the time is fixed, unless the vehicle is empty.

Поля
level

Level

The constraint relaxation level that applies when the conditions at or after threshold_time AND at least threshold_visit_count are satisfied.

threshold_ time

Timestamp

The time at or after which the relaxation level may be applied.

threshold_ visit_ count

int32

The number of visits at or after which the relaxation level may be applied. If threshold_visit_count is 0 (or unset), the level may be applied directly at the vehicle start.

If it is route.visits_size() + 1 , the level may only be applied to the vehicle end. If it is more than route.visits_size() + 1 , level is not applied at all for that route.

Уровень

Expresses the different constraint relaxation levels, which are applied for a visit and those that follow when it satisfies the threshold conditions.

The enumeration below is in order of increasing relaxation.

Enums
LEVEL_UNSPECIFIED

Implicit default relaxation level: no constraints are relaxed, ie, all visits are fully constrained.

This value must not be explicitly used in level .

RELAX_VISIT_TIMES_AFTER_THRESHOLD Visit start times and vehicle start/end times will be relaxed, but each visit remains bound to the same vehicle and the visit sequence must be observed: no visit can be inserted between them or before them.
RELAX_VISIT_TIMES_AND_SEQUENCE_AFTER_THRESHOLD Same as RELAX_VISIT_TIMES_AFTER_THRESHOLD , but the visit sequence is also relaxed: visits can only be performed by this vehicle, but can potentially become unperformed.
RELAX_ALL_AFTER_THRESHOLD Same as RELAX_VISIT_TIMES_AND_SEQUENCE_AFTER_THRESHOLD , but the vehicle is also relaxed: visits are completely free at or after the threshold time and can potentially become unperformed.

InputConfig

Specify an input for [BatchOptimizeTours][google.maps.routeoptimization.v1.RouteOptimizationService.BatchOptimizeTours].

Поля
data_ format

DataFormat

Необходимый. The input data format.

Union field source . Необходимый. source can be only one of the following:
gcs_ source

GcsSource

A Google Cloud Storage location. This must be a single object (file).

Расположение

Encapsulates a location (a geographic point, and an optional heading).

Поля
lat_ lng

LatLng

The waypoint's geographic coordinates.

heading

int32

The compass heading associated with the direction of the flow of traffic. This value is used to specify the side of the road to use for pickup and drop-off. Heading values can be from 0 to 360, where 0 specifies a heading of due North, 90 specifies a heading of due East, etc.

OptimizeToursRequest

Request to be given to a tour optimization solver which defines the shipment model to solve as well as optimization parameters.

Поля
parent

string

Необходимый. Target project or location to make a call.

Format: * projects/{project-id} * projects/{project-id}/locations/{location-id}

If no location is specified, a region will be chosen automatically.

timeout

Duration

If this timeout is set, the server returns a response before the timeout period has elapsed or the server deadline for synchronous requests is reached, whichever is sooner.

For asynchronous requests, the server will generate a solution (if possible) before the timeout has elapsed.

model

ShipmentModel

Shipment model to solve.

solving_ mode

SolvingMode

By default, the solving mode is DEFAULT_SOLVE (0).

search_ mode

SearchMode

Search mode used to solve the request.

injected_ first_ solution_ routes[]

ShipmentRoute

Guide the optimization algorithm in finding a first solution that is similar to a previous solution.

The model is constrained when the first solution is built. Any shipments not performed on a route are implicitly skipped in the first solution, but they may be performed in successive solutions.

The solution must satisfy some basic validity assumptions:

  • for all routes, vehicle_index must be in range and not be duplicated.
  • for all visits, shipment_index and visit_request_index must be in range.
  • a shipment may only be referenced on one route.
  • the pickup of a pickup-delivery shipment must be performed before the delivery.
  • no more than one pickup alternative or delivery alternative of a shipment may be performed.
  • for all routes, times are increasing (ie, vehicle_start_time <= visits[0].start_time <= visits[1].start_time ... <= vehicle_end_time ).
  • a shipment may only be performed on a vehicle that is allowed. A vehicle is allowed if Shipment.allowed_vehicle_indices is empty or its vehicle_index is included in Shipment.allowed_vehicle_indices .

If the injected solution is not feasible, a validation error is not necessarily returned and an error indicating infeasibility may be returned instead.

injected_ solution_ constraint

InjectedSolutionConstraint

Constrain the optimization algorithm to find a final solution that is similar to a previous solution. For example, this may be used to freeze portions of routes which have already been completed or which are to be completed but must not be modified.

If the injected solution is not feasible, a validation error is not necessarily returned and an error indicating infeasibility may be returned instead.

refresh_ details_ routes[]

ShipmentRoute

If non-empty, the given routes will be refreshed, without modifying their underlying sequence of visits or travel times: only other details will be updated. This does not solve the model.

As of 2020/11, this only populates the polylines of non-empty routes and requires that populate_polylines is true.

The route_polyline fields of the passed-in routes may be inconsistent with route transitions .

This field must not be used together with injected_first_solution_routes or injected_solution_constraint .

Shipment.ignore and Vehicle.ignore have no effect on the behavior. Polylines are still populated between all visits in all non-empty routes regardless of whether the related shipments or vehicles are ignored.

interpret_ injected_ solutions_ using_ labels

bool

If true:

This interpretation applies to the injected_first_solution_routes , injected_solution_constraint , and refresh_details_routes fields. It can be used when shipment or vehicle indices in the request have changed since the solution was created, perhaps because shipments or vehicles have been removed from or added to the request.

If true, labels in the following categories must appear at most once in their category:

If a vehicle_label in the injected solution does not correspond to a request vehicle, the corresponding route is removed from the solution along with its visits. If a shipment_label in the injected solution does not correspond to a request shipment, the corresponding visit is removed from the solution. If a SkippedShipment.label in the injected solution does not correspond to a request shipment, the SkippedShipment is removed from the solution.

Removing route visits or entire routes from an injected solution may have an effect on the implied constraints, which may lead to change in solution, validation errors, or infeasibility.

NOTE: The caller must ensure that each Vehicle.label (resp. Shipment.label ) uniquely identifies a vehicle (resp. shipment) entity used across the two relevant requests: the past request that produced the OptimizeToursResponse used in the injected solution and the current request that includes the injected solution. The uniqueness checks described above are not enough to guarantee this requirement.

consider_ road_ traffic

bool

Consider traffic estimation in calculating ShipmentRoute fields Transition.travel_duration , Visit.start_time , and vehicle_end_time ; in setting the ShipmentRoute.has_traffic_infeasibilities field, and in calculating the OptimizeToursResponse.total_cost field.

populate_ polylines

bool

If true, polylines will be populated in response ShipmentRoute s.

populate_ transition_ polylines

bool

If true, polylines and route tokens will be populated in response ShipmentRoute.transitions .

allow_ large_ deadline_ despite_ interruption_ risk

bool

If this is set, then the request can have a deadline (see https://grpc.io/blog/deadlines ) of up to 60 minutes. Otherwise, the maximum deadline is only 30 minutes. Note that long-lived requests have a significantly larger (but still small) risk of interruption.

use_ geodesic_ distances

bool

If true, travel distances will be computed using geodesic distances instead of Google Maps distances, and travel times will be computed using geodesic distances with a speed defined by geodesic_meters_per_second .

label

string

Label that may be used to identify this request, reported back in the OptimizeToursResponse.request_label .

geodesic_ meters_ per_ second

double

When use_geodesic_distances is true, this field must be set and defines the speed applied to compute travel times. Its value must be at least 1.0 meters/seconds.

max_ validation_ errors

int32

Truncates the number of validation errors returned. These errors are typically attached to an INVALID_ARGUMENT error payload as a BadRequest error detail ( https://cloud.google.com/apis/design/errors#error_details) , unless solving_mode=VALIDATE_ONLY: see the OptimizeToursResponse.validation_errors field. This defaults to 100 and is capped at 10,000.

SearchMode

Mode defining the behavior of the search, trading off latency versus solution quality. In all modes, the global request deadline is enforced.

Enums
SEARCH_MODE_UNSPECIFIED Unspecified search mode, equivalent to RETURN_FAST .
RETURN_FAST Stop the search after finding the first good solution.
CONSUME_ALL_AVAILABLE_TIME Spend all the available time to search for better solutions.

SolvingMode

Defines how the solver should handle the request. In all modes but VALIDATE_ONLY , if the request is invalid, you will receive an INVALID_REQUEST error. See max_validation_errors to cap the number of errors returned.

Enums
DEFAULT_SOLVE Solve the model. Warnings may be issued in [OptimizeToursResponse.validation_errors][google.cloud.optimization.v1.OptimizeToursResponse.validation_errors].
VALIDATE_ONLY Only validates the model without solving it: populates as many OptimizeToursResponse.validation_errors as possible.
DETECT_SOME_INFEASIBLE_SHIPMENTS

Only populates OptimizeToursResponse.validation_errors or OptimizeToursResponse.skipped_shipments , and doesn't actually solve the rest of the request ( status and routes are unset in the response). If infeasibilities in injected_solution_constraint routes are detected they are populated in the OptimizeToursResponse.validation_errors field and OptimizeToursResponse.skipped_shipments is left empty.

IMPORTANT : not all infeasible shipments are returned here, but only the ones that are detected as infeasible during preprocessing.

OptimizeToursResponse

Response after solving a tour optimization problem containing the routes followed by each vehicle, the shipments which have been skipped and the overall cost of the solution.

Поля
routes[]

ShipmentRoute

Routes computed for each vehicle; the i-th route corresponds to the i-th vehicle in the model.

request_ label

string

Copy of the OptimizeToursRequest.label , if a label was specified in the request.

skipped_ shipments[]

SkippedShipment

The list of all shipments skipped.

validation_ errors[]

OptimizeToursValidationError

List of all the validation errors that we were able to detect independently. See the "MULTIPLE ERRORS" explanation for the OptimizeToursValidationError message. Instead of errors, this will include warnings in the case solving_mode is DEFAULT_SOLVE .

metrics

Metrics

Duration, distance and usage metrics for this solution.

Метрики

Overall metrics, aggregated over all routes.

Поля
aggregated_ route_ metrics

AggregatedMetrics

Aggregated over the routes. Each metric is the sum (or max, for loads) over all ShipmentRoute.metrics fields of the same name.

skipped_ mandatory_ shipment_ count

int32

Number of mandatory shipments skipped.

used_ vehicle_ count

int32

Number of vehicles used. Note: if a vehicle route is empty and Vehicle.used_if_route_is_empty is true, the vehicle is considered used.

earliest_ vehicle_ start_ time

Timestamp

The earliest start time for a used vehicle, computed as the minimum over all used vehicles of ShipmentRoute.vehicle_start_time .

latest_ vehicle_ end_ time

Timestamp

The latest end time for a used vehicle, computed as the maximum over all used vehicles of ShipmentRoute.vehicle_end_time .

costs

map<string, double>

Cost of the solution, broken down by cost-related request fields. The keys are proto paths, relative to the input OptimizeToursRequest, eg "model.shipments.pickups.cost", and the values are the total cost generated by the corresponding cost field, aggregated over the whole solution. In other words, costs["model.shipments.pickups.cost"] is the sum of all pickup costs over the solution. All costs defined in the model are reported in detail here with the exception of costs related to TransitionAttributes that are only reported in an aggregated way as of 2022/01.

total_ cost

double

Total cost of the solution. The sum of all values in the costs map.

OptimizeToursValidationError

Describes an error or warning encountered when validating an OptimizeToursRequest .

Поля
code

int32

A validation error is defined by the pair ( code , display_name ) which are always present.

The fields following this section provide more context about the error.

MULTIPLE ERRORS : When there are multiple errors, the validation process tries to output several of them. Much like a compiler, this is an imperfect process. Some validation errors will be "fatal", meaning that they stop the entire validation process. This is the case for display_name="UNSPECIFIED" errors, among others. Some errors may cause the validation process to skip other errors.

STABILITY : code and display_name should be very stable. But new codes and display names may appear over time, which may cause a given (invalid) request to yield a different ( code , display_name ) pair because the new error hid the old one. For example, see "MULTIPLE ERRORS".

display_ name

string

The error display name.

fields[]

FieldReference

An error context may involve 0, 1 (most of the time) or more fields. For example, referring to vehicle #4 and shipment #2's first pickup can be done as follows:

fields { name: "vehicles" index: 4}
fields { name: "shipments" index: 2 sub_field {name: "pickups" index: 0} }

Note, however, that the cardinality of fields should not change for a given error code.

error_ message

string

Human-readable string describing the error. There is a 1:1 mapping between code and error_message (when code != "UNSPECIFIED").

STABILITY : Not stable: the error message associated to a given code may change (hopefully to clarify it) over time. Please rely on the display_name and code instead.

offending_ values

string

May contain the value(s) of the field(s). This is not always available. You should absolutely not rely on it and use it only for manual model debugging.

FieldReference

Specifies a context for the validation error. A FieldReference always refers to a given field in this file and follows the same hierarchical structure. For example, we may specify element #2 of start_time_windows of vehicle #5 using:

name: "vehicles" index: 5 sub_field { name: "end_time_windows" index: 2 }

We however omit top-level entities such as OptimizeToursRequest or ShipmentModel to avoid crowding the message.

Поля
name

string

Name of the field, eg, "vehicles".

sub_ field

FieldReference

Recursively nested sub-field, if needed.

Union field index_or_key .

index_or_key can be only one of the following:

index

int32

Index of the field if repeated.

key

string

Key if the field is a map.

OutputConfig

Specify a destination for [BatchOptimizeTours][google.maps.routeoptimization.v1.RouteOptimizationService.BatchOptimizeTours] results.

Поля
data_ format

DataFormat

Необходимый. The output data format.

Union field destination . Необходимый. destination can be only one of the following:
gcs_ destination

GcsDestination

The Google Cloud Storage location to write the output to.

RouteModifiers

Encapsulates a set of optional conditions to satisfy when calculating vehicle routes. This is similar to RouteModifiers in the Google Maps Platform Routes Preferred API; see: https://developers.google.com/maps/documentation/routes/reference/rest/v2/RouteModifiers .

Поля
avoid_ tolls

bool

Specifies whether to avoid toll roads where reasonable. Preference will be given to routes not containing toll roads. Applies only to motorized travel modes.

avoid_ highways

bool

Specifies whether to avoid highways where reasonable. Preference will be given to routes not containing highways. Applies only to motorized travel modes.

avoid_ ferries

bool

Specifies whether to avoid ferries where reasonable. Preference will be given to routes not containing travel by ferries. Applies only to motorized travel modes.

avoid_ indoor

bool

Необязательный. Specifies whether to avoid navigating indoors where reasonable. Preference will be given to routes not containing indoor navigation. Applies only to the WALKING travel mode.

Отгрузка

The shipment of a single item, from one of its pickups to one of its deliveries. For the shipment to be considered as performed, a unique vehicle must visit one of its pickup locations (and decrease its spare capacities accordingly), then visit one of its delivery locations later on (and therefore re-increase its spare capacities accordingly).

Поля
display_ name

string

The user-defined display name of the shipment. It can be up to 63 characters long and may use UTF-8 characters.

pickups[]

VisitRequest

Set of pickup alternatives associated to the shipment. If not specified, the vehicle only needs to visit a location corresponding to the deliveries.

deliveries[]

VisitRequest

Set of delivery alternatives associated to the shipment. If not specified, the vehicle only needs to visit a location corresponding to the pickups.

load_ demands

map<string, Load >

Load demands of the shipment (for example weight, volume, number of pallets etc). The keys in the map should be identifiers describing the type of the corresponding load, ideally also including the units. For example: "weight_kg", "volume_gallons", "pallet_count", etc. If a given key does not appear in the map, the corresponding load is considered as null.

allowed_ vehicle_ indices[]

int32

The set of vehicles that may perform this shipment. If empty, all vehicles may perform it. Vehicles are given by their index in the ShipmentModel 's vehicles list.

costs_ per_ vehicle[]

double

Specifies the cost that is incurred when this shipment is delivered by each vehicle. If specified, it must have EITHER:

  • the same number of elements as costs_per_vehicle_indices . costs_per_vehicle[i] corresponds to vehicle costs_per_vehicle_indices[i] of the model.
  • the same number of elements as there are vehicles in the model. The i-th element corresponds to vehicle #i of the model.

These costs must be in the same unit as penalty_cost and must not be negative. Leave this field empty, if there are no such costs.

costs_ per_ vehicle_ indices[]

int32

Indices of the vehicles to which costs_per_vehicle applies. If non-empty, it must have the same number of elements as costs_per_vehicle . A vehicle index may not be specified more than once. If a vehicle is excluded from costs_per_vehicle_indices , its cost is zero.

pickup_ to_ delivery_ absolute_ detour_ limit

Duration

Specifies the maximum absolute detour time compared to the shortest path from pickup to delivery. If specified, it must be nonnegative, and the shipment must contain at least a pickup and a delivery.

For example, let t be the shortest time taken to go from the selected pickup alternative directly to the selected delivery alternative. Then setting pickup_to_delivery_absolute_detour_limit enforces:

start_time(delivery) - start_time(pickup) <=
t + pickup_to_delivery_absolute_detour_limit

If both relative and absolute limits are specified on the same shipment, the more constraining limit is used for each possible pickup/delivery pair. As of 2017/10, detours are only supported when travel durations do not depend on vehicles.

pickup_ to_ delivery_ time_ limit

Duration

Specifies the maximum duration from start of pickup to start of delivery of a shipment. If specified, it must be nonnegative, and the shipment must contain at least a pickup and a delivery. This does not depend on which alternatives are selected for pickup and delivery, nor on vehicle speed. This can be specified alongside maximum detour constraints: the solution will respect both specifications.

shipment_ type

string

Non-empty string specifying a "type" for this shipment. This feature can be used to define incompatibilities or requirements between shipment_types (see shipment_type_incompatibilities and shipment_type_requirements in ShipmentModel ).

Differs from visit_types which is specified for a single visit: All pickup/deliveries belonging to the same shipment share the same shipment_type .

label

string

Specifies a label for this shipment. This label is reported in the response in the shipment_label of the corresponding ShipmentRoute.Visit .

ignore

bool

If true, skip this shipment, but don't apply a penalty_cost .

Ignoring a shipment results in a validation error when there are any shipment_type_requirements in the model.

Ignoring a shipment that is performed in injected_first_solution_routes or injected_solution_constraint is permitted; the solver removes the related pickup/delivery visits from the performing route. precedence_rules that reference ignored shipments will also be ignored.

penalty_ cost

double

If the shipment is not completed, this penalty is added to the overall cost of the routes. A shipment is considered completed if one of its pickup and delivery alternatives is visited. The cost may be expressed in the same unit used for all other cost-related fields in the model and must be positive.

IMPORTANT : If this penalty is not specified, it is considered infinite, ie the shipment must be completed.

pickup_ to_ delivery_ relative_ detour_ limit

double

Specifies the maximum relative detour time compared to the shortest path from pickup to delivery. If specified, it must be nonnegative, and the shipment must contain at least a pickup and a delivery.

For example, let t be the shortest time taken to go from the selected pickup alternative directly to the selected delivery alternative. Then setting pickup_to_delivery_relative_detour_limit enforces:

start_time(delivery) - start_time(pickup) <=
std::ceil(t * (1.0 + pickup_to_delivery_relative_detour_limit))

If both relative and absolute limits are specified on the same shipment, the more constraining limit is used for each possible pickup/delivery pair. As of 2017/10, detours are only supported when travel durations do not depend on vehicles.

Нагрузка

When performing a visit, a predefined amount may be added to the vehicle load if it's a pickup, or subtracted if it's a delivery. This message defines such amount. See load_demands .

Поля
amount

int64

The amount by which the load of the vehicle performing the corresponding visit will vary. Since it is an integer, users are advised to choose an appropriate unit to avoid loss of precision. Must be ≥ 0.

VisitRequest

Request for a visit which can be done by a vehicle: it has a geo-location (or two, see below), opening and closing times represented by time windows, and a service duration time (time spent by the vehicle once it has arrived to pickup or drop off goods).

Поля
arrival_ location

LatLng

The geo-location where the vehicle arrives when performing this VisitRequest . If the shipment model has duration distance matrices, arrival_location must not be specified.

arrival_ waypoint

Waypoint

The waypoint where the vehicle arrives when performing this VisitRequest . If the shipment model has duration distance matrices, arrival_waypoint must not be specified.

departure_ location

LatLng

The geo-location where the vehicle departs after completing this VisitRequest . Can be omitted if it is the same as arrival_location . If the shipment model has duration distance matrices, departure_location must not be specified.

departure_ waypoint

Waypoint

The waypoint where the vehicle departs after completing this VisitRequest . Can be omitted if it is the same as arrival_waypoint . If the shipment model has duration distance matrices, departure_waypoint must not be specified.

tags[]

string

Specifies tags attached to the visit request. Empty or duplicate strings are not allowed.

time_ windows[]

TimeWindow

Time windows which constrain the arrival time at a visit. Note that a vehicle may depart outside of the arrival time window, ie arrival time + duration do not need to be inside a time window. This can result in waiting time if the vehicle arrives before TimeWindow.start_time .

The absence of TimeWindow means that the vehicle can perform this visit at any time.

Time windows must be disjoint, ie no time window must overlap with or be adjacent to another, and they must be in increasing order.

cost_per_hour_after_soft_end_time and soft_end_time can only be set if there is a single time window.

duration

Duration

Duration of the visit, ie time spent by the vehicle between arrival and departure (to be added to the possible waiting time; see time_windows ).

cost

double

Cost to service this visit request on a vehicle route. This can be used to pay different costs for each alternative pickup or delivery of a shipment. This cost must be in the same unit as Shipment.penalty_cost and must not be negative.

load_ demands

map<string, Load >

Load demands of this visit request. This is just like Shipment.load_demands field, except that it only applies to this VisitRequest instead of the whole Shipment . The demands listed here are added to the demands listed in Shipment.load_demands .

visit_ types[]

string

Specifies the types of the visit. This may be used to allocate additional time required for a vehicle to complete this visit (see Vehicle.extra_visit_duration_for_visit_type ).

A type can only appear once.

label

string

Specifies a label for this VisitRequest . This label is reported in the response as visit_label in the corresponding ShipmentRoute.Visit .

ShipmentModel

A shipment model contains a set of shipments which must be performed by a set of vehicles, while minimizing the overall cost, which is the sum of:

  • the cost of routing the vehicles (sum of cost per total time, cost per travel time, and fixed cost over all vehicles).
  • the unperformed shipment penalties.
  • the cost of the global duration of the shipments
Поля
shipments[]

Shipment

Set of shipments which must be performed in the model.

vehicles[]

Vehicle

Set of vehicles which can be used to perform visits.

global_ start_ time

Timestamp

Global start and end time of the model: no times outside of this range can be considered valid.

The model's time span must be less than a year, ie the global_end_time and the global_start_time must be within 31536000 seconds of each other.

When using cost_per_*hour fields, you might want to set this window to a smaller interval to increase performance (eg. if you model a single day, you should set the global time limits to that day). If unset, 00:00:00 UTC, January 1, 1970 (ie seconds: 0, nanos: 0) is used as default.

global_ end_ time

Timestamp

If unset, 00:00:00 UTC, January 1, 1971 (ie seconds: 31536000, nanos: 0) is used as default.

global_ duration_ cost_ per_ hour

double

The "global duration" of the overall plan is the difference between the earliest effective start time and the latest effective end time of all vehicles. Users can assign a cost per hour to that quantity to try and optimize for earliest job completion, for example. This cost must be in the same unit as Shipment.penalty_cost .

duration_ distance_ matrices[]

DurationDistanceMatrix

Specifies duration and distance matrices used in the model. If this field is empty, Google Maps or geodesic distances will be used instead, depending on the value of the use_geodesic_distances field. If it is not empty, use_geodesic_distances cannot be true and neither duration_distance_matrix_src_tags nor duration_distance_matrix_dst_tags can be empty.

Usage examples:

  • There are two locations: locA and locB.
  • 1 vehicle starting its route at locA and ending it at locA.
  • 1 pickup visit request at locB.
model {
  vehicles { start_tags: "locA"  end_tags: "locA" }
  shipments { pickups { tags: "locB" } }
  duration_distance_matrix_src_tags: "locA"
  duration_distance_matrix_src_tags: "locB"
  duration_distance_matrix_dst_tags: "locA"
  duration_distance_matrix_dst_tags: "locB"
  duration_distance_matrices {
    rows {  # from: locA
      durations { seconds: 0 }   meters: 0    # to: locA
      durations { seconds: 100 } meters: 1000 # to: locB
    }
    rows {  # from: locB
      durations { seconds: 102 } meters: 990 # to: locA
      durations { seconds: 0 }   meters: 0   # to: locB
    }
  }
}
  • There are three locations: locA, locB and locC.
  • 1 vehicle starting its route at locA and ending it at locB, using matrix "fast".
  • 1 vehicle starting its route at locB and ending it at locB, using matrix "slow".
  • 1 vehicle starting its route at locB and ending it at locB, using matrix "fast".
  • 1 pickup visit request at locC.
model {
  vehicles { start_tags: "locA" end_tags: "locB" start_tags: "fast" }
  vehicles { start_tags: "locB" end_tags: "locB" start_tags: "slow" }
  vehicles { start_tags: "locB" end_tags: "locB" start_tags: "fast" }
  shipments { pickups { tags: "locC" } }
  duration_distance_matrix_src_tags: "locA"
  duration_distance_matrix_src_tags: "locB"
  duration_distance_matrix_src_tags: "locC"
  duration_distance_matrix_dst_tags: "locB"
  duration_distance_matrix_dst_tags: "locC"
  duration_distance_matrices {
    vehicle_start_tag: "fast"
    rows {  # from: locA
      durations { seconds: 1000 } meters: 2000 # to: locB
      durations { seconds: 600 }  meters: 1000 # to: locC
    }
    rows {  # from: locB
      durations { seconds: 0 }   meters: 0    # to: locB
      durations { seconds: 700 } meters: 1200 # to: locC
    }
    rows {  # from: locC
      durations { seconds: 702 } meters: 1190 # to: locB
      durations { seconds: 0 }   meters: 0    # to: locC
    }
  }
  duration_distance_matrices {
    vehicle_start_tag: "slow"
    rows {  # from: locA
      durations { seconds: 1800 } meters: 2001 # to: locB
      durations { seconds: 900 }  meters: 1002 # to: locC
    }
    rows {  # from: locB
      durations { seconds: 0 }    meters: 0    # to: locB
      durations { seconds: 1000 } meters: 1202 # to: locC
    }
    rows {  # from: locC
      durations { seconds: 1001 } meters: 1195 # to: locB
      durations { seconds: 0 }    meters: 0    # to: locC
    }
  }
}
duration_ distance_ matrix_ src_ tags[]

string

Tags defining the sources of the duration and distance matrices; duration_distance_matrices(i).rows(j) defines durations and distances from visits with tag duration_distance_matrix_src_tags(j) to other visits in matrix i.

Tags correspond to VisitRequest.tags or Vehicle.start_tags . A given VisitRequest or Vehicle must match exactly one tag in this field. Note that a Vehicle 's source, destination and matrix tags may be the same; similarly a VisitRequest 's source and destination tags may be the same. All tags must be different and cannot be empty strings. If this field is not empty, then duration_distance_matrices must not be empty.

duration_ distance_ matrix_ dst_ tags[]

string

Tags defining the destinations of the duration and distance matrices; duration_distance_matrices(i).rows(j).durations(k) (resp. duration_distance_matrices(i).rows(j).meters(k)) defines the duration (resp. the distance) of the travel from visits with tag duration_distance_matrix_src_tags(j) to visits with tag duration_distance_matrix_dst_tags(k) in matrix i.

Tags correspond to VisitRequest.tags or Vehicle.start_tags . A given VisitRequest or Vehicle must match exactly one tag in this field. Note that a Vehicle 's source, destination and matrix tags may be the same; similarly a VisitRequest 's source and destination tags may be the same. All tags must be different and cannot be empty strings. If this field is not empty, then duration_distance_matrices must not be empty.

transition_ attributes[]

TransitionAttributes

Transition attributes added to the model.

shipment_ type_ incompatibilities[]

ShipmentTypeIncompatibility

Sets of incompatible shipment_types (see ShipmentTypeIncompatibility ).

shipment_ type_ requirements[]

ShipmentTypeRequirement

Sets of shipment_type requirements (see ShipmentTypeRequirement ).

precedence_ rules[]

PrecedenceRule

Set of precedence rules which must be enforced in the model.

IMPORTANT : Use of precedence rules limits the size of problem that can be optimized. Requests using precedence rules that include many shipments may be rejected.

max_ active_ vehicles

int32

Constrains the maximum number of active vehicles. A vehicle is active if its route performs at least one shipment. This can be used to limit the number of routes in the case where there are fewer drivers than vehicles and that the fleet of vehicles is heterogeneous. The optimization will then select the best subset of vehicles to use. Must be strictly positive.

DurationDistanceMatrix

Specifies a duration and distance matrix from visit and vehicle start locations to visit and vehicle end locations.

Поля
rows[]

Row

Specifies the rows of the duration and distance matrix. It must have as many elements as ShipmentModel.duration_distance_matrix_src_tags .

vehicle_ start_ tag

string

Tag defining to which vehicles this duration and distance matrix applies. If empty, this applies to all vehicles, and there can only be a single matrix.

Each vehicle start must match exactly one matrix, ie exactly one of their start_tags field must match the vehicle_start_tag of a matrix (and of that matrix only).

All matrices must have a different vehicle_start_tag .

Ряд

Specifies a row of the duration and distance matrix.

Поля
durations[]

Duration

Duration values for a given row. It must have as many elements as ShipmentModel.duration_distance_matrix_dst_tags .

meters[]

double

Distance values for a given row. If no costs or constraints refer to distances in the model, this can be left empty; otherwise it must have as many elements as durations .

PrecedenceRule

A precedence rule between two events (each event is the pickup or the delivery of a shipment): the "second" event has to start at least offset_duration after "first" has started.

Several precedences can refer to the same (or related) events, eg, "pickup of B happens after delivery of A" and "pickup of C happens after pickup of B".

Furthermore, precedences only apply when both shipments are performed and are otherwise ignored.

Поля
first_ is_ delivery

bool

Indicates if the "first" event is a delivery.

second_ is_ delivery

bool

Indicates if the "second" event is a delivery.

offset_ duration

Duration

The offset between the "first" and "second" event. It can be negative.

first_ index

int32

Shipment index of the "first" event. This field must be specified.

second_ index

int32

Shipment index of the "second" event. This field must be specified.

ShipmentRoute

A vehicle's route can be decomposed, along the time axis, like this (we assume there are n visits):

  |            |            |          |       |  T[2], |        |      |
  | Transition |  Visit #0  |          |       |  V[2], |        |      |
  |     #0     |    aka     |   T[1]   |  V[1] |  ...   | V[n-1] | T[n] |
  |  aka T[0]  |    V[0]    |          |       | V[n-2],|        |      |
  |            |            |          |       | T[n-1] |        |      |
  ^            ^            ^          ^       ^        ^        ^      ^
vehicle    V[0].start   V[0].end     V[1].   V[1].    V[n].    V[n]. vehicle
 start     (arrival)   (departure)   start   end      start    end     end

Note that we make a difference between:

  • "punctual events", such as the vehicle start and end and each visit's start and end (aka arrival and departure). They happen at a given second.
  • "time intervals", such as the visits themselves, and the transition between visits. Though time intervals can sometimes have zero duration, ie start and end at the same second, they often have a positive duration.

Invariants:

  • If there are n visits, there are n+1 transitions.
  • A visit is always surrounded by a transition before it (same index) and a transition after it (index + 1).
  • The vehicle start is always followed by transition #0.
  • The vehicle end is always preceded by transition #n.

Zooming in, here is what happens during a Transition and a Visit :

---+-------------------------------------+-----------------------------+-->
   |           TRANSITION[i]             |           VISIT[i]          |
   |                                     |                             |
   |  * TRAVEL: the vehicle moves from   |      PERFORM the visit:     |
   |    VISIT[i-1].departure_location to |                             |
   |    VISIT[i].arrival_location, which |  * Spend some time:         |
   |    takes a given travel duration    |    the "visit duration".    |
   |    and distance                     |                             |
   |                                     |  * Load or unload           |
   |  * BREAKS: the driver may have      |    some quantities from the |
   |    breaks (e.g. lunch break).       |    vehicle: the "demand".   |
   |                                     |                             |
   |  * WAIT: the driver/vehicle does    |                             |
   |    nothing. This can happen for     |                             |
   |    many reasons, for example when   |                             |
   |    the vehicle reaches the next     |                             |
   |    event's destination before the   |                             |
   |    start of its time window         |                             |
   |                                     |                             |
   |  * DELAY: *right before* the next   |                             |
   |    arrival. E.g. the vehicle and/or |                             |
   |    driver spends time unloading.    |                             |
   |                                     |                             |
---+-------------------------------------+-----------------------------+-->
   ^                                     ^                             ^
V[i-1].end                           V[i].start                    V[i].end

Lastly, here is how the TRAVEL, BREAKS, DELAY and WAIT can be arranged during a transition.

  • They don't overlap.
  • The DELAY is unique and must be a contiguous period of time right before the next visit (or vehicle end). Thus, it suffice to know the delay duration to know its start and end time.
  • The BREAKS are contiguous, non-overlapping periods of time. The response specifies the start time and duration of each break.
  • TRAVEL and WAIT are "preemptable": they can be interrupted several times during this transition. Clients can assume that travel happens "as soon as possible" and that "wait" fills the remaining time.

A (complex) example:

                               TRANSITION[i]
--++-----+-----------------------------------------------------------++-->
  ||     |       |           |       |           |         |         ||
  ||  T  |   B   |     T     |       |     B     |         |    D    ||
  ||  r  |   r   |     r     |   W   |     r     |    W    |    e    ||
  ||  a  |   e   |     a     |   a   |     e     |    a    |    l    ||
  ||  v  |   a   |     v     |   i   |     a     |    i    |    a    ||
  ||  e  |   k   |     e     |   t   |     k     |    t    |    y    ||
  ||  l  |       |     l     |       |           |         |         ||
  ||     |       |           |       |           |         |         ||
--++-----------------------------------------------------------------++-->
Поля
vehicle_ index

int32

Vehicle performing the route, identified by its index in the source ShipmentModel .

vehicle_ label

string

Label of the vehicle performing this route, equal to ShipmentModel.vehicles(vehicle_index).label , if specified.

vehicle_ start_ time

Timestamp

Time at which the vehicle starts its route.

vehicle_ end_ time

Timestamp

Time at which the vehicle finishes its route.

visits[]

Visit

Ordered sequence of visits representing a route. visits[i] is the i-th visit in the route. If this field is empty, the vehicle is considered as unused.

transitions[]

Transition

Ordered list of transitions for the route.

has_ traffic_ infeasibilities

bool

When OptimizeToursRequest.consider_road_traffic , is set to true, this field indicates that inconsistencies in route timings are predicted using traffic-based travel duration estimates. There may be insufficient time to complete traffic-adjusted travel, delays, and breaks between visits, before the first visit, or after the last visit, while still satisfying the visit and vehicle time windows. Например,

  start_time(previous_visit) + duration(previous_visit) +
  travel_duration(previous_visit, next_visit) > start_time(next_visit)

Arrival at next_visit will likely happen later than its current time window due the increased estimate of travel time travel_duration(previous_visit, next_visit) due to traffic. Also, a break may be forced to overlap with a visit due to an increase in travel time estimates and visit or break time window restrictions.

route_ polyline

EncodedPolyline

The encoded polyline representation of the route. This field is only populated if OptimizeToursRequest.populate_polylines is set to true.

breaks[]

Break

Breaks scheduled for the vehicle performing this route. The breaks sequence represents time intervals, each starting at the corresponding start_time and lasting duration seconds.

metrics

AggregatedMetrics

Duration, distance and load metrics for this route. The fields of AggregatedMetrics are summed over all ShipmentRoute.transitions or ShipmentRoute.visits , depending on the context.

route_ costs

map<string, double>

Cost of the route, broken down by cost-related request fields. The keys are proto paths, relative to the input OptimizeToursRequest, eg "model.shipments.pickups.cost", and the values are the total cost generated by the corresponding cost field, aggregated over the whole route. In other words, costs["model.shipments.pickups.cost"] is the sum of all pickup costs over the route. All costs defined in the model are reported in detail here with the exception of costs related to TransitionAttributes that are only reported in an aggregated way as of 2022/01.

route_ total_ cost

double

Total cost of the route. The sum of all costs in the cost map.

Перерыв

Data representing the execution of a break.

Поля
start_ time

Timestamp

Start time of a break.

duration

Duration

Duration of a break.

EncodedPolyline

The encoded representation of a polyline. More information on polyline encoding can be found here: https://developers.google.com/maps/documentation/utilities/polylinealgorithm https://developers.google.com/maps/documentation/javascript/reference/geometry#encoding .

Поля
points

string

String representing encoded points of the polyline.

Переход

Transition between two events on the route. See the description of ShipmentRoute .

If the vehicle does not have a start_location and/or end_location , the corresponding travel metrics are 0.

Поля
travel_ duration

Duration

Travel duration during this transition.

travel_ distance_ meters

double

Distance traveled during the transition.

traffic_ info_ unavailable

bool

When traffic is requested via OptimizeToursRequest.consider_road_traffic , and the traffic info couldn't be retrieved for a Transition , this boolean is set to true. This may be temporary (rare hiccup in the realtime traffic servers) or permanent (no data for this location).

delay_ duration

Duration

Sum of the delay durations applied to this transition. If any, the delay starts exactly delay_duration seconds before the next event (visit or vehicle end). See TransitionAttributes.delay .

break_ duration

Duration

Sum of the duration of the breaks occurring during this transition, if any. Details about each break's start time and duration are stored in ShipmentRoute.breaks .

wait_ duration

Duration

Time spent waiting during this transition. Wait duration corresponds to idle time and does not include break time. Also note that this wait time may be split into several non-contiguous intervals.

total_ duration

Duration

Total duration of the transition, provided for convenience. It is equal to:

  • next visit start_time (or vehicle_end_time if this is the last transition) - this transition's start_time ;
  • if ShipmentRoute.has_traffic_infeasibilities is false, the following additionally holds: `total_duration = travel_duration + delay_duration
  • break_duration + wait_duration`.
start_ time

Timestamp

Start time of this transition.

route_ polyline

EncodedPolyline

The encoded polyline representation of the route followed during the transition. This field is only populated if populate_transition_polylines is set to true.

route_ token

string

Output only. An opaque token that can be passed to Navigation SDK to reconstruct the route during navigation, and, in the event of rerouting, honor the original intention when the route was created. Treat this token as an opaque blob. Don't compare its value across requests as its value may change even if the service returns the exact same route. This field is only populated if populate_transition_polylines is set to true.

vehicle_ loads

map<string, VehicleLoad >

Vehicle loads during this transition, for each type that either appears in this vehicle's Vehicle.load_limits , or that have non-zero Shipment.load_demands on some shipment performed on this route.

The loads during the first transition are the starting loads of the vehicle route. Then, after each visit, the visit's load_demands are either added or subtracted to get the next transition's loads, depending on whether the visit was a pickup or a delivery.

VehicleLoad

Reports the actual load of the vehicle at some point along the route, for a given type (see Transition.vehicle_loads ).

Поля
amount

int64

The amount of load on the vehicle, for the given type. The unit of load is usually indicated by the type. See Transition.vehicle_loads .

Посещать

A visit performed during a route. This visit corresponds to a pickup or a delivery of a Shipment .

Поля
shipment_ index

int32

Index of the shipments field in the source ShipmentModel .

is_ pickup

bool

If true the visit corresponds to a pickup of a Shipment . Otherwise, it corresponds to a delivery.

visit_ request_ index

int32

Index of VisitRequest in either the pickup or delivery field of the Shipment (see is_pickup ).

start_ time

Timestamp

Time at which the visit starts. Note that the vehicle may arrive earlier than this at the visit location. Times are consistent with the ShipmentModel .

load_ demands

map<string, Load >

Total visit load demand as the sum of the shipment and the visit request load_demands . The values are negative if the visit is a delivery. Demands are reported for the same types as the Transition.loads (see this field).

detour

Duration

Extra detour time due to the shipments visited on the route before the visit and to the potential waiting time induced by time windows. If the visit is a delivery, the detour is computed from the corresponding pickup visit and is equal to:

start_time(delivery) - start_time(pickup)
- (duration(pickup) + travel duration from the pickup location
to the delivery location).

Otherwise, it is computed from the vehicle start_location and is equal to:

start_time - vehicle_start_time - travel duration from
the vehicle's `start_location` to the visit.
shipment_ label

string

Copy of the corresponding Shipment.label , if specified in the Shipment .

visit_ label

string

Copy of the corresponding VisitRequest.label , if specified in the VisitRequest .

ShipmentTypeIncompatibility

Specifies incompatibilties between shipments depending on their shipment_type. The appearance of incompatible shipments on the same route is restricted based on the incompatibility mode.

Поля
types[]

string

List of incompatible types. Two shipments having different shipment_types among those listed are "incompatible".

incompatibility_ mode

IncompatibilityMode

Mode applied to the incompatibility.

IncompatibilityMode

Modes defining how the appearance of incompatible shipments are restricted on the same route.

Enums
INCOMPATIBILITY_MODE_UNSPECIFIED Unspecified incompatibility mode. This value should never be used.
NOT_PERFORMED_BY_SAME_VEHICLE In this mode, two shipments with incompatible types can never share the same vehicle.
NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY

For two shipments with incompatible types with the NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY incompatibility mode:

  • If both are pickups only (no deliveries) or deliveries only (no pickups), they cannot share the same vehicle at all.
  • If one of the shipments has a delivery and the other a pickup, the two shipments can share the same vehicle iff the former shipment is delivered before the latter is picked up.

ShipmentTypeRequirement

Specifies requirements between shipments based on their shipment_type. The specifics of the requirement are defined by the requirement mode.

Поля
required_ shipment_ type_ alternatives[]

string

List of alternative shipment types required by the dependent_shipment_types .

dependent_ shipment_ types[]

string

All shipments with a type in the dependent_shipment_types field require at least one shipment of type required_shipment_type_alternatives to be visited on the same route.

NOTE: Chains of requirements such that a shipment_type depends on itself are not allowed.

requirement_ mode

RequirementMode

Mode applied to the requirement.

RequirementMode

Modes defining the appearance of dependent shipments on a route.

Enums
REQUIREMENT_MODE_UNSPECIFIED Unspecified requirement mode. This value should never be used.
PERFORMED_BY_SAME_VEHICLE In this mode, all "dependent" shipments must share the same vehicle as at least one of their "required" shipments.
IN_SAME_VEHICLE_AT_PICKUP_TIME

With the IN_SAME_VEHICLE_AT_PICKUP_TIME mode, all "dependent" shipments need to have at least one "required" shipment on their vehicle at the time of their pickup.

A "dependent" shipment pickup must therefore have either:

  • A delivery-only "required" shipment delivered on the route after, or
  • A "required" shipment picked up on the route before it, and if the "required" shipment has a delivery, this delivery must be performed after the "dependent" shipment's pickup.
IN_SAME_VEHICLE_AT_DELIVERY_TIME Same as before, except the "dependent" shipments need to have a "required" shipment on their vehicle at the time of their delivery .

SkippedShipment

Specifies details of unperformed shipments in a solution. For trivial cases and/or if we are able to identify the cause for skipping, we report the reason here.

Поля
index

int32

The index corresponds to the index of the shipment in the source ShipmentModel .

label

string

Copy of the corresponding Shipment.label , if specified in the Shipment .

reasons[]

Reason

A list of reasons that explain why the shipment was skipped. See comment above Reason . If we are unable to understand why a shipment was skipped, reasons will not be set.

Причина

If we can explain why the shipment was skipped, reasons will be listed here. If the reason is not the same for all vehicles, reason will have more than 1 element. A skipped shipment cannot have duplicate reasons, ie where all fields are the same except for example_vehicle_index . Пример:

reasons {
  code: DEMAND_EXCEEDS_VEHICLE_CAPACITY
  example_vehicle_index: 1
  example_exceeded_capacity_type: "Apples"
}
reasons {
  code: DEMAND_EXCEEDS_VEHICLE_CAPACITY
  example_vehicle_index: 3
  example_exceeded_capacity_type: "Pears"
}
reasons {
  code: CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DISTANCE_LIMIT
  example_vehicle_index: 1
}

The skipped shipment is incompatible with all vehicles. The reasons may be different for all vehicles but at least one vehicle's "Apples" capacity would be exceeded (including vehicle 1), at least one vehicle's "Pears" capacity would be exceeded (including vehicle 3) and at least one vehicle's distance limit would be exceeded (including vehicle 1).

Поля
code

Code

Refer to the comments of Code.

example_ exceeded_ capacity_ type

string

If the reason code is DEMAND_EXCEEDS_VEHICLE_CAPACITY , documents one capacity type that is exceeded.

example_ vehicle_ index

int32

If the reason is related to a shipment-vehicle incompatibility, this field provides the index of one relevant vehicle.

Код

Code identifying the reason type. The order here is meaningless. In particular, it gives no indication of whether a given reason will appear before another in the solution, if both apply.

Enums
CODE_UNSPECIFIED This should never be used.
NO_VEHICLE There is no vehicle in the model making all shipments infeasible.
DEMAND_EXCEEDS_VEHICLE_CAPACITY The demand of the shipment exceeds a vehicle's capacity for some capacity types, one of which is example_exceeded_capacity_type .
CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DISTANCE_LIMIT

The minimum distance necessary to perform this shipment, ie from the vehicle's start_location to the shipment's pickup and/or delivery locations and to the vehicle's end location exceeds the vehicle's route_distance_limit .

Note that for this computation we use the geodesic distances.

CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DURATION_LIMIT

The minimum time necessary to perform this shipment, including travel time, wait time and service time exceeds the vehicle's route_duration_limit .

Note: travel time is computed in the best-case scenario, namely as geodesic distance x 36 m/s (roughly 130 km/hour).

CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TRAVEL_DURATION_LIMIT Same as above but we only compare minimum travel time and the vehicle's travel_duration_limit .
CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TIME_WINDOWS The vehicle cannot perform this shipment in the best-case scenario (see CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DURATION_LIMIT for time computation) if it starts at its earliest start time: the total time would make the vehicle end after its latest end time.
VEHICLE_NOT_ALLOWED The allowed_vehicle_indices field of the shipment is not empty and this vehicle does not belong to it.

TimeWindow

Time windows constrain the time of an event, such as the arrival time at a visit, or the start and end time of a vehicle.

Hard time window bounds, start_time and end_time , enforce the earliest and latest time of the event, such that start_time <= event_time <= end_time . The soft time window lower bound, soft_start_time , expresses a preference for the event to happen at or after soft_start_time by incurring a cost proportional to how long before soft_start_time the event occurs. The soft time window upper bound, soft_end_time , expresses a preference for the event to happen at or before soft_end_time by incurring a cost proportional to how long after soft_end_time the event occurs. start_time , end_time , soft_start_time and soft_end_time should be within the global time limits (see ShipmentModel.global_start_time and ShipmentModel.global_end_time ) and should respect:

  0 <= `start_time` <= `end_time` and
  0 <= `start_time` <= `soft_start_time` and
  0 <= `soft_end_time` <= `end_time`.
Поля
start_ time

Timestamp

The hard time window start time. If unspecified it will be set to ShipmentModel.global_start_time .

end_ time

Timestamp

The hard time window end time. If unspecified it will be set to ShipmentModel.global_end_time .

soft_ start_ time

Timestamp

The soft start time of the time window.

soft_ end_ time

Timestamp

The soft end time of the time window.

cost_ per_ hour_ before_ soft_ start_ time

double

A cost per hour added to other costs in the model if the event occurs before soft_start_time, computed as:

   max(0, soft_start_time - t.seconds)
                          * cost_per_hour_before_soft_start_time / 3600,
t being the time of the event.

This cost must be positive, and the field can only be set if soft_start_time has been set.

cost_ per_ hour_ after_ soft_ end_ time

double

A cost per hour added to other costs in the model if the event occurs after soft_end_time , computed as:

   max(0, t.seconds - soft_end_time.seconds)
                    * cost_per_hour_after_soft_end_time / 3600,
t being the time of the event.

This cost must be positive, and the field can only be set if soft_end_time has been set.

TransitionAttributes

Specifies attributes of transitions between two consecutive visits on a route. Several TransitionAttributes may apply to the same transition: in that case, all extra costs add up and the strictest constraint or limit applies (following natural "AND" semantics).

Поля
src_ tag

string

Tags defining the set of (src->dst) transitions these attributes apply to.

A source visit or vehicle start matches iff its VisitRequest.tags or Vehicle.start_tags either contains src_tag or does not contain excluded_src_tag (depending on which of these two fields is non-empty).

excluded_ src_ tag

string

See src_tag . Exactly one of src_tag and excluded_src_tag must be non-empty.

dst_ tag

string

A destination visit or vehicle end matches iff its VisitRequest.tags or Vehicle.end_tags either contains dst_tag or does not contain excluded_dst_tag (depending on which of these two fields is non-empty).

excluded_ dst_ tag

string

See dst_tag . Exactly one of dst_tag and excluded_dst_tag must be non-empty.

cost

double

Specifies a cost for performing this transition. This is in the same unit as all other costs in the model and must not be negative. It is applied on top of all other existing costs.

cost_ per_ kilometer

double

Specifies a cost per kilometer applied to the distance traveled while performing this transition. It adds up to any Vehicle.cost_per_kilometer specified on vehicles.

distance_ limit

DistanceLimit

Specifies a limit on the distance traveled while performing this transition.

As of 2021/06, only soft limits are supported.

delay

Duration

Specifies a delay incurred when performing this transition.

This delay always occurs after finishing the source visit and before starting the destination visit.

Транспортное средство

Models a vehicle in a shipment problem. Solving a shipment problem will build a route starting from start_location and ending at end_location for this vehicle. A route is a sequence of visits (see ShipmentRoute ).

Поля
display_ name

string

The user-defined display name of the vehicle. It can be up to 63 characters long and may use UTF-8 characters.

travel_ mode

TravelMode

The travel mode which affects the roads usable by the vehicle and its speed. See also travel_duration_multiple .

route_ modifiers

RouteModifiers

A set of conditions to satisfy that affect the way routes are calculated for the given vehicle.

start_ location

LatLng

Geographic location where the vehicle starts before picking up any shipments. If not specified, the vehicle starts at its first pickup. If the shipment model has duration and distance matrices, start_location must not be specified.

start_ waypoint

Waypoint

Waypoint representing a geographic location where the vehicle starts before picking up any shipments. If neither start_waypoint nor start_location is specified, the vehicle starts at its first pickup. If the shipment model has duration and distance matrices, start_waypoint must not be specified.

end_ location

LatLng

Geographic location where the vehicle ends after it has completed its last VisitRequest . If not specified the vehicle's ShipmentRoute ends immediately when it completes its last VisitRequest . If the shipment model has duration and distance matrices, end_location must not be specified.

end_ waypoint

Waypoint

Waypoint representing a geographic location where the vehicle ends after it has completed its last VisitRequest . If neither end_waypoint nor end_location is specified, the vehicle's ShipmentRoute ends immediately when it completes its last VisitRequest . If the shipment model has duration and distance matrices, end_waypoint must not be specified.

start_ tags[]

string

Specifies tags attached to the start of the vehicle's route.

Empty or duplicate strings are not allowed.

end_ tags[]

string

Specifies tags attached to the end of the vehicle's route.

Empty or duplicate strings are not allowed.

start_ time_ windows[]

TimeWindow

Time windows during which the vehicle may depart its start location. They must be within the global time limits (see ShipmentModel.global_* fields). If unspecified, there is no limitation besides those global time limits.

Time windows belonging to the same repeated field must be disjoint, ie no time window can overlap with or be adjacent to another, and they must be in chronological order.

cost_per_hour_after_soft_end_time and soft_end_time can only be set if there is a single time window.

end_ time_ windows[]

TimeWindow

Time windows during which the vehicle may arrive at its end location. They must be within the global time limits (see ShipmentModel.global_* fields). If unspecified, there is no limitation besides those global time limits.

Time windows belonging to the same repeated field must be disjoint, ie no time window can overlap with or be adjacent to another, and they must be in chronological order.

cost_per_hour_after_soft_end_time and soft_end_time can only be set if there is a single time window.

unloading_ policy

UnloadingPolicy

Unloading policy enforced on the vehicle.

load_ limits

map<string, LoadLimit >

Capacities of the vehicle (weight, volume, # of pallets for example). The keys in the map are the identifiers of the type of load, consistent with the keys of the Shipment.load_demands field. If a given key is absent from this map, the corresponding capacity is considered to be limitless.

cost_ per_ hour

double

Vehicle costs: all costs add up and must be in the same unit as Shipment.penalty_cost .

Cost per hour of the vehicle route. This cost is applied to the total time taken by the route, and includes travel time, waiting time, and visit time. Using cost_per_hour instead of just cost_per_traveled_hour may result in additional latency.

cost_ per_ traveled_ hour

double

Cost per traveled hour of the vehicle route. This cost is applied only to travel time taken by the route (ie, that reported in ShipmentRoute.transitions ), and excludes waiting time and visit time.

cost_ per_ kilometer

double

Cost per kilometer of the vehicle route. This cost is applied to the distance reported in the ShipmentRoute.transitions and does not apply to any distance implicitly traveled from the arrival_location to the departure_location of a single VisitRequest .

fixed_ cost

double

Fixed cost applied if this vehicle is used to handle a shipment.

used_ if_ route_ is_ empty

bool

This field only applies to vehicles when their route does not serve any shipments. It indicates if the vehicle should be considered as used or not in this case.

If true, the vehicle goes from its start to its end location even if it doesn't serve any shipments, and time and distance costs resulting from its start --> end travel are taken into account.

Otherwise, it doesn't travel from its start to its end location, and no break_rule or delay (from TransitionAttributes ) are scheduled for this vehicle. In this case, the vehicle's ShipmentRoute doesn't contain any information except for the vehicle index and label.

route_ duration_ limit

DurationLimit

Limit applied to the total duration of the vehicle's route. In a given OptimizeToursResponse , the route duration of a vehicle is the difference between its vehicle_end_time and vehicle_start_time .

travel_ duration_ limit

DurationLimit

Limit applied to the travel duration of the vehicle's route. In a given OptimizeToursResponse , the route travel duration is the sum of all its transitions.travel_duration .

route_ distance_ limit

DistanceLimit

Limit applied to the total distance of the vehicle's route. In a given OptimizeToursResponse , the route distance is the sum of all its transitions.travel_distance_meters .

extra_ visit_ duration_ for_ visit_ type

map<string, Duration >

Specifies a map from visit_types strings to durations. The duration is time in addition to VisitRequest.duration to be taken at visits with the specified visit_types . This extra visit duration adds cost if cost_per_hour is specified. Keys (ie visit_types ) cannot be empty strings.

If a visit request has multiple types, a duration will be added for each type in the map.

break_ rule

BreakRule

Describes the break schedule to be enforced on this vehicle. If empty, no breaks will be scheduled for this vehicle.

label

string

Specifies a label for this vehicle. This label is reported in the response as the vehicle_label of the corresponding ShipmentRoute .

ignore

bool

If true, used_if_route_is_empty must be false, and this vehicle will remain unused.

If a shipment is performed by an ignored vehicle in injected_first_solution_routes , it is skipped in the first solution but is free to be performed in the response.

If a shipment is performed by an ignored vehicle in injected_solution_constraint and any related pickup/delivery is constrained to remain on the vehicle (ie, not relaxed to level RELAX_ALL_AFTER_THRESHOLD ), it is skipped in the response. If a shipment has a non-empty allowed_vehicle_indices field and all of the allowed vehicles are ignored, it is skipped in the response.

travel_ duration_ multiple

double

Specifies a multiplicative factor that can be used to increase or decrease travel times of this vehicle. For example, setting this to 2.0 means that this vehicle is slower and has travel times that are twice what they are for standard vehicles. This multiple does not affect visit durations. It does affect cost if cost_per_hour or cost_per_traveled_hour are specified. This must be in the range [0.001, 1000.0]. If unset, the vehicle is standard, and this multiple is considered 1.0.

WARNING: Travel times will be rounded to the nearest second after this multiple is applied but before performing any numerical operations, thus, a small multiple may result in a loss of precision.

See also extra_visit_duration_for_visit_type below.

DurationLimit

A limit defining a maximum duration of the route of a vehicle. It can be either hard or soft.

When a soft limit field is defined, both the soft max threshold and its associated cost must be defined together.

Поля
max_ duration

Duration

A hard limit constraining the duration to be at most max_duration.

soft_ max_ duration

Duration

A soft limit not enforcing a maximum duration limit, but when violated makes the route incur a cost. This cost adds up to other costs defined in the model, with the same unit.

If defined, soft_max_duration must be nonnegative. If max_duration is also defined, soft_max_duration must be less than max_duration.

quadratic_ soft_ max_ duration

Duration

A soft limit not enforcing a maximum duration limit, but when violated makes the route incur a cost, quadratic in the duration. This cost adds up to other costs defined in the model, with the same unit.

If defined, quadratic_soft_max_duration must be nonnegative. If max_duration is also defined, quadratic_soft_max_duration must be less than max_duration , and the difference must be no larger than one day:

max_duration - quadratic_soft_max_duration <= 86400 seconds

cost_ per_ hour_ after_ soft_ max

double

Cost per hour incurred if the soft_max_duration threshold is violated. The additional cost is 0 if the duration is under the threshold, otherwise the cost depends on the duration as follows:

  cost_per_hour_after_soft_max * (duration - soft_max_duration)

The cost must be nonnegative.

cost_ per_ square_ hour_ after_ quadratic_ soft_ max

double

Cost per square hour incurred if the quadratic_soft_max_duration threshold is violated.

The additional cost is 0 if the duration is under the threshold, otherwise the cost depends on the duration as follows:

  cost_per_square_hour_after_quadratic_soft_max *
  (duration - quadratic_soft_max_duration)^2

The cost must be nonnegative.

LoadLimit

Defines a load limit applying to a vehicle, eg "this truck may only carry up to 3500 kg". See load_limits .

Поля
soft_ max_ load

int64

A soft limit of the load. See cost_per_unit_above_soft_max .

cost_ per_ unit_ above_ soft_ max

double

If the load ever exceeds soft_max_load along this vehicle's route, the following cost penalty applies (only once per vehicle): (load - soft_max_load ) * cost_per_unit_above_soft_max . All costs add up and must be in the same unit as Shipment.penalty_cost .

start_ load_ interval

Interval

The acceptable load interval of the vehicle at the start of the route.

end_ load_ interval

Interval

The acceptable load interval of the vehicle at the end of the route.

max_ load

int64

The maximum acceptable amount of load.

Интервал

Interval of acceptable load amounts.

Поля
min

int64

A minimum acceptable load. Must be ≥ 0. If they're both specified, min must be ≤ max .

max

int64

A maximum acceptable load. Must be ≥ 0. If unspecified, the maximum load is unrestricted by this message. If they're both specified, min must be ≤ max .

TravelMode

Travel modes which can be used by vehicles.

These should be a subset of the Google Maps Platform Routes API travel modes, see: https://developers.google.com/maps/documentation/routes/reference/rest/v2/RouteTravelMode

Note: WALKING routes are in beta and might sometimes be missing clear sidewalks or pedestrian paths. You must display this warning to the user for all walking routes that you display in your app.

Enums
TRAVEL_MODE_UNSPECIFIED Unspecified travel mode, equivalent to DRIVING .
DRIVING Travel mode corresponding to driving directions (car, ...).
WALKING Travel mode corresponding to walking directions.

UnloadingPolicy

Policy on how a vehicle can be unloaded. Applies only to shipments having both a pickup and a delivery.

Other shipments are free to occur anywhere on the route independent of unloading_policy .

Enums
UNLOADING_POLICY_UNSPECIFIED Unspecified unloading policy; deliveries must just occur after their corresponding pickups.
LAST_IN_FIRST_OUT Deliveries must occur in reverse order of pickups
FIRST_IN_FIRST_OUT Deliveries must occur in the same order as pickups

Waypoint

Encapsulates a waypoint. Waypoints mark arrival and departure locations of VisitRequests, and start and end locations of Vehicles.

Поля
side_ of_ road

bool

Необязательный. Indicates that the location of this waypoint is meant to have a preference for the vehicle to stop at a particular side of road. When you set this value, the route will pass through the location so that the vehicle can stop at the side of road that the location is biased towards from the center of the road. This option doesn't work for the 'WALKING' travel mode.

Union field location_type . Different ways to represent a location. location_type can be only one of the following:
location

Location

A point specified using geographic coordinates, including an optional heading.

place_ id

string

The POI place ID associated with the waypoint.

When using a place ID to specify arrival or departure location of a VisitRequest, use a place ID that is specific enough to determine a LatLng location for navigation to the place. For example, a place ID representing a building is suitable, but a place ID representing a road is discouraged.