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 в пакетном режиме.

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.

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

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

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

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

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

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

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

  • routeoptimization.operations.create

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

OptimizeTours

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 .

OptimizeToursLongRunning

rpc OptimizeToursLongRunning( OptimizeToursRequest ) returns ( Operation )

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

Возвращаемая long-running operation (LRO) будет иметь имя в формате <parent>/operations/<operation_id> и может использоваться для отслеживания хода вычислений. Тип поля metadataOptimizeToursLongRunningMetadata . Тип поля responseOptimizeToursResponse , если выполнение выполнено успешно.

Экспериментальный вариант: более подробную информацию см. на странице https://developers.google.com/maps/tt/route-optimization/experimental/otlr/make-request .

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

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

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

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

  • routeoptimization.operations.create

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

OptimizeToursUri

rpc OptimizeToursUri( OptimizeToursUriRequest ) returns ( Operation )

Это вариант метода OptimizeToursLongRunning предназначенный для оптимизаций с большими значениями тайм-аута и большими размерами ввода/вывода.

Клиент указывает URI OptimizeToursRequest сохраненного в Google Cloud Storage, а сервер записывает OptimizeToursResponse в указанный клиентом URI Google Cloud Storage.

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

Возвращаемая long-running operation (LRO) будет иметь имя в формате <parent>/operations/<operation_id> и может использоваться для отслеживания хода вычислений. Тип поля metadataOptimizeToursLongRunningMetadata . Тип поля responseOptimizeToursUriResponse , если выполнение выполнено успешно.

Экспериментальный вариант: более подробную информацию см. на странице https://developers.google.com/maps/tt/route-optimization/experimental/otlr/make-request .

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

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

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

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

  • routeoptimization.operations.create

Более подробную информацию см. в документации 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 .

performed_mandatory_shipment_count

int32

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

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

performed_shipment_penalty_cost_sum

double

Сумма Shipment.penalty_cost выполненных перевозок.

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

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

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

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

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

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

Поля
parent

string

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

Формат:

  • projects/{project-id}
  • projects/{project-id}/locations/{location-id}

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

model_configs[]

AsyncModelConfig

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

AsyncModelConfig

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

Поля
display_name

string

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

input_config

InputConfig

Обязательно. Информация о входной модели.

output_config

OutputConfig

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

BatchOptimizeToursResponse

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

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

BreakRule

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

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

BreakRequest

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

frequency_constraints[]

FrequencyConstraint

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

BreakRequest

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

Поля
earliest_start_time

Timestamp

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

latest_start_time

Timestamp

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

min_duration

Duration

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

Ограничение частоты

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

Время и продолжительность перерывов в решении будут учитывать все подобные ограничения, в дополнение к временным окнам и минимальной продолжительности, уже указанным в 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 Недопустимое значение, формат не должен быть НЕУКАЗАН.
JSON Нотация объектов JavaScript.
PROTO_TEXT Текстовый формат буферов протокола. См. https://protobuf.dev/reference/protobuf/textformat-spec/

DistanceLimit

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

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

Поля
max_meters

int64

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

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, куда будут записаны выходные файлы.

Поля
uri

string

Обязательно. URI облачного хранилища Google.

GcsSource

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

Поля
uri

string

Обязательно. URI объекта Google Cloud Storage в формате gs://bucket/path/to/object .

InjectedSolutionConstraint

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

Поля
routes[]

ShipmentRoute

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

skipped_shipments[]

SkippedShipment

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

constraint_relaxations[]

ConstraintRelaxation

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

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

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

Поля
relaxations[]

Relaxation

Все смягчения ограничений посещений, которые будут применяться к посещениям на маршрутах с транспортными средствами, указанными в 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 .

Индекс транспортного средства сопоставляется так же, как 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

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.

Время и последовательность посещений маршрутов, не удовлетворяющих пороговым условиям каких-либо 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 , но транспортное средство также расслаблено: посещения полностью бесплатны в или после порогового времени и потенциально могут стать невыполненными.

InputConfig

Укажите входные данные для [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 — на восток и т. д.

ОптимизацияToursLongRunningMetadata

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

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

OptimizeToursRequest

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

Поля
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

Если верно:

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

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

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.

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

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

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

populate_polylines

bool

Если true, полилинии будут заполнены в ответе ShipmentRoute s.

populate_transition_polylines

bool

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

allow_large_deadline_despite_interruption_risk

bool

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

use_geodesic_distances

bool

Если значение равно true, расстояния перемещения будут вычисляться с использованием геодезических расстояний вместо расстояний 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) , если не задан параметр solved_mode=VALIDATE_ONLY: см. поле OptimizeToursResponse.validation_errors . Значение по умолчанию — 100, ограничение — 10 000.

Режим поиска

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

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

SolvingMode

Определяет, как решатель должен обрабатывать запрос. Во всех режимах, кроме 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

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.

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

TRANSFORM_AND_RETURN_REQUEST

Этот режим работает только если ShipmentModel.objectives не пустое. Запрос не решается. Он только проверяется и заполняется стоимостью, соответствующей заданным целям. См. также документацию по ShipmentModel.objectives . Результирующий запрос возвращается как OptimizeToursResponse.processed_request .

Экспериментальный вариант: более подробную информацию см. по адресу https://developers.google.com/maps/tt/route-optimization/experimental/objectives/make-request .

OptimizeToursResponse

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

Поля
routes[]

ShipmentRoute

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

request_label

string

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

skipped_shipments[]

SkippedShipment

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

validation_errors[]

OptimizeToursValidationError

Список всех ошибок валидации, которые нам удалось обнаружить независимо. См. пояснение к сообщению OptimizeToursValidationError в разделе «МНОЖЕСТВЕННЫЕ ОШИБКИ». Вместо ошибок будут выведены предупреждения, если solving_modeDEFAULT_SOLVE .

processed_request

OptimizeToursRequest

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

Экспериментальный вариант: более подробную информацию см. по адресу https://developers.google.com/maps/tt/route-optimization/experimental/objectives/make-request .

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>

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

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

OptimizeToursUriMetadata

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

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

OptimizeToursUriRequest

Запрос, используемый методом OptimizeToursUri .

Поля
parent

string

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

Формат:

  • projects/{project-id}
  • projects/{project-id}/locations/{location-id}

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

input

Uri

Обязательно. URI объекта облачного хранилища, содержащего OptimizeToursRequest .

output

Uri

Обязательно. URI объекта облачного хранилища, который будет содержать OptimizeToursResponse .

OptimizeToursUriResponse

Ответ, возвращаемый методом OptimizeToursUri .

Поля
output

Uri

Необязательно. URI объекта облачного хранилища, содержащего OptimizeToursResponse закодированный в формате JSON или textproto. Если объект закодирован в формате JSON, расширение имени объекта будет .json . Если объект закодирован в формате textproto, расширение имени объекта будет .txtpb .

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

OptimizeToursValidationError

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

Поля
code

int32

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

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

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.

СТАБИЛЬНОСТЬ : code и display_name должны быть очень стабильными. Однако со временем могут появляться новые коды и 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 может со временем меняться (надеюсь, для большей ясности). Вместо этого ориентируйтесь на display_name и code .

offending_values

string

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

FieldReference

Указывает контекст ошибки проверки. 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

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

OutputConfig

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

Поля
data_format

DataFormat

Обязательно. Формат выходных данных.

Union field destination . Required. destination can be only one of the following:
gcs_destination

GcsDestination

The Google Cloud Storage location to write the output to.

RouteModifiers

Инкапсулирует набор дополнительных условий, которые необходимо учитывать при расчёте маршрутов транспортных средств. Аналогично RouteModifiers в API предпочтительных маршрутов платформы Google Карт; см.: 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 >

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

allowed_vehicle_indices[]

int32

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

costs_per_vehicle[]

double

Указывает стоимость доставки груза каждым транспортным средством. Если указано, необходимо указать ОДНО ИЗ следующих условий:

  • 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.
  • Число элементов равно числу транспортных средств в модели. i-й элемент соответствует транспортному средству № i в модели.

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

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

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

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

pickup_to_delivery_time_limit

Duration

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

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

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

ВАЖНО : Если данный штраф не указан, он считается бесконечным, т.е. отправка должна быть завершена.

pickup_to_delivery_relative_detour_limit

double

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

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

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

Нагрузка

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

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

Поля
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

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

time_windows[]

TimeWindow

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

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

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

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

Стоимость обслуживания этого запроса на посещение по маршруту транспортного средства. Эта сумма может быть использована для оплаты различных вариантов забора или доставки груза. Эта стоимость должна быть выражена в тех же единицах, что и 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

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

avoid_u_turns

bool

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

Экспериментальный вариант: более подробную информацию см. на странице https://developers.google.com/maps/tt/route-optimization/experimental/u-turn-avoidance/make-request .

ShipmentModel

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

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

Shipment

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

vehicles[]

Vehicle

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

objectives[]

Objective

The set of objectives for this model, that we will transform into costs. If not empty, the input model has to be costless. To obtain the modified request, please use solving_mode = TRANSFORM_AND_RETURN_REQUEST. Note that the request will not be solved in this case. See corresponding documentation.

Экспериментальный вариант: более подробную информацию см. по адресу https://developers.google.com/maps/tt/route-optimization/experimental/objectives/make-request .

global_start_time

Timestamp

Глобальное время начала и окончания модели: никакое время за пределами этого диапазона не может считаться действительным.

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.

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

global_end_time

Timestamp

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

global_duration_cost_per_hour

double

«Глобальная продолжительность» общего плана — это разница между самым ранним фактическим временем начала и самым поздним фактическим временем окончания для всех транспортных средств. Пользователи могут назначить этому количеству почасовую стоимость, например, чтобы оптимизировать её для скорейшего завершения работы. Эта стоимость должна быть выражена в тех же единицах, что и 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.

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

  • Существует два местоположения: 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, используя матрицу «slow».
  • 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

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

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

shipment_type_incompatibilities[]

ShipmentTypeIncompatibility

Наборы несовместимых shipment_types (см. ShipmentTypeIncompatibility ).

shipment_type_requirements[]

ShipmentTypeRequirement

Sets of shipment_type requirements (see ShipmentTypeRequirement ).

precedence_rules[]

PrecedenceRule

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

ВАЖНО : Использование правил приоритета ограничивает размер задачи, которую можно оптимизировать. Запросы, использующие правила приоритета, которые включают множество поставок, могут быть отклонены.

max_active_vehicles

int32

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

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 .

Цель

Objectives replace the cost model completely, and are therefore incompatible with pre-existing costs. Each objective maps to a number of pre-defined costs for, eg, vehicles, shipments or transition attributes.

Экспериментальный вариант: более подробную информацию см. по адресу https://developers.google.com/maps/tt/route-optimization/experimental/objectives/make-request .

Поля
type

Type

The type of the objective.

weight

double

How much this objective should count relatively to the others. This can be any non-negative number, weights do not have to sum to 1. Weights default to 1.0.

Тип

The objective type that will be mapped to a set of costs.

Перечисления
DEFAULT A default set of costs will be used, to ensure a reasonable solution. Note: this objective can be used on its own, but will also always be added with weight 1.0, as a baseline, to the objectives specified by the user, if it's not already present.
MIN_DISTANCE "MIN" objectives. Minimize the total distance traveled.
MIN_WORKING_TIME Minimize the total working time, summed over all vehicles.
MIN_TRAVEL_TIME Same as above but focusing on travel time only.
MIN_NUM_VEHICLES Minimize the number of vehicles used.

Правило приоритета

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.

  • Они не пересекаются.
  • 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. For example,

  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.

vehicle_fullness

VehicleFullness

VehicleFullness field for computing how close the capped metrics are to their respective vehicle limits. Its fields are ratios between a capped metric field (eg AggregatedMetrics.travel_distance_meters ) and the related vehicle limit (eg Vehicle.route_distance_limit ).

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

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 .

injected_solution_location_token

int32

An opaque token representing information about a visit location.

This field may be populated in the result routes' visits when VisitRequest.avoid_u_turns was set to true for this visit or if ShipmentModel.avoid_u_turns was set to true in the request OptimizeToursRequest .

Экспериментальный вариант: более подробную информацию см. на странице https://developers.google.com/maps/tt/route-optimization/experimental/u-turn-avoidance/make-request .

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.

Перечисления
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

In this mode, two shipments with incompatible types can never be on the same vehicle at the same time:

  • They can share the same vehicle only if one is delivered before the other is picked up.
  • When both shipments are pickups-only (no deliveries) or deliveries-only (no pickups), they can't share the same vehicle at all.

ТипОтгрузкиТребования

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.

Перечисления
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.

penalty_cost

double

This is a copy of the Shipment.penalty_cost , included here to make it easier to see the severity of a skipped shipment.

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

estimated_incompatible_vehicle_ratio

double

Estimated ratio of vehicles that cannot perform this shipment for at least one of the reasons below. Note: this is only filled when reasons involve a vehicle.

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

Причина

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 . Example:

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_vehicle_indices[]

int32

Same as example_vehicle_index except that we provide the list of multiple identified vehicles. This list is not necessarily exhaustive. This is only filled if [fill_example_vehicle_indices_in_skipped_reasons][] is true.

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

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.

Перечисления
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.
VEHICLE_IGNORED

The vehicle's ignore field is true.

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

SHIPMENT_IGNORED

The shipment's ignore field is true.

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

SKIPPED_IN_INJECTED_SOLUTION_CONSTRAINT

The shipment is skipped in the injected_solution_constraint .

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

VEHICLE_ROUTE_IS_FULLY_SEQUENCE_CONSTRAINED

The vehicle route relaxation specified in the injected_solution_constraint doesn't permit any visit to be inserted.

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

ZERO_PENALTY_COST

The shipment has a zero penalty cost. While this can be useful as an advanced modelling choice, it may also explain after the fact why a shipment was skipped.

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

TimeWindow

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

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

Время начала жёсткого временного окна. Если не указано, будет установлено значение 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

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.

Атрибуты перехода

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.

Ури

A Universal Resource Identifier that points to a resource that can be read and written by the Route Optimization API.

Поля
uri

string

The URI of the resource. The resource may not yet exist.

The contents of the resource are encoded as either JSON or textproto. Only Google Cloud Storage resources are supported. If the resource is encoded as JSON, the resource name must be suffixed with .json . If the resource is encoded as textproto, the resource name must be suffixed with .txtpb . For example, a Google Cloud Storage URI to a JSON encoded file might look like: gs://bucket/path/input/object.json .

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

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

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

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

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

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

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

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

end_tags[]

string

Указывает теги, прикрепленные к концу маршрута транспортного средства.

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

start_time_windows[]

TimeWindow

Временные интервалы, в течение которых транспортное средство может покинуть пункт отправления. Они должны соответствовать глобальным временным ограничениям (см. поля ShipmentModel.global_* ). Если не указано иное, то никаких ограничений, помимо этих глобальных временных ограничений, нет.

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

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

Временные интервалы, в течение которых транспортное средство может прибыть в конечный пункт назначения. Они должны соответствовать глобальным временным ограничениям (см. поля ShipmentModel.global_* ). Если не указано иное, то никаких ограничений, помимо этих глобальных временных ограничений, нет.

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

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

В отношении транспортного средства применяются правила разгрузки.

load_limits

map<string, LoadLimit >

Грузоподъёмность транспортного средства (например, вес, объём, количество поддонов). Ключи в карте — это идентификаторы типа груза, соответствующие ключам поля Shipment.load_demands . Если указанный ключ отсутствует в карте, соответствующая грузоподъёмность считается неограниченной.

cost_per_hour

double

Стоимость транспортного средства: все расходы суммируются и должны быть выражены в тех же единицах, что и 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

Стоимость за час в пути по маршруту транспортного средства. Эта стоимость применяется только к времени, затраченному на поездку по маршруту (т.е. указанному в ShipmentRoute.transitions ), и не включает время ожидания и время посещения.

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

Фиксированная стоимость применяется, если данное транспортное средство используется для перевозки груза.

used_if_route_is_empty

bool

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

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

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

Ограничение, применяемое к длительности движения транспортного средства по маршруту. В заданном OptimizeToursResponse длительность движения по маршруту равна сумме всех его transitions.travel_duration .

route_distance_limit

DistanceLimit

Ограничение применяется к общей дистанции маршрута транспортного средства. В данном OptimizeToursResponse дистанция маршрута представляет собой сумму всех его 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.

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

break_rule

BreakRule

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

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.

ВНИМАНИЕ: Время в пути будет округлено до ближайшей секунды после применения этого множителя, но до выполнения любых числовых операций, поэтому небольшое множитель может привести к потере точности.

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 . Soft limits may only be defined on types that apply to either pickups only or deliveries only throughout the model.

start_load_interval

Interval

Допустимый интервал загрузки транспортного средства в начале маршрута.

end_load_interval

Interval

Допустимый интервал загрузки транспортного средства в конце маршрута.

max_load

int64

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

cost_per_kilometer

LoadCost

Стоимость перемещения одной единицы груза на расстояние одного километра для данного транспортного средства. Это можно использовать в качестве показателя расхода топлива: если груз — это вес (в ньютонах), то нагрузка*километр имеет размерность энергии.

Экспериментальный вариант: более подробную информацию см. на странице https://developers.google.com/maps/tt/route-optimization/experimental/load-cost/make-request .

cost_per_traveled_hour

LoadCost

Стоимость проезда с единицей груза в течение одного часа для данного транспортного средства.

Экспериментальный вариант: более подробную информацию см. на странице https://developers.google.com/maps/tt/route-optimization/experimental/load-cost/make-request .

Интервал

Интервал допустимых величин нагрузки.

Поля
min

int64

Минимально допустимая нагрузка. Должна быть ≥ 0. Если указаны оба значения, min должен быть ≤ max .

max

int64

Максимально допустимая нагрузка. Должна быть ≥ 0. Если значение не указано, максимальная нагрузка не ограничивается этим сообщением. Если указаны оба значения, min должно быть ≤ max .

LoadCost

Стоимость перемещения одной единицы груза за время Transition . Для данного груза стоимость складывается из двух частей:

  • min(load, load_threshold ) * cost_per_unit_below_threshold
  • max(0, load - load_threshold ) * cost_per_unit_above_threshold

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

load_limit {
  key: "weight"
  value {
    cost_per_kilometer {
      load_threshold: 15
      cost_per_unit_below_threshold: 2.0
      cost_per_unit_above_threshold: 10.0
    }
  }
}

и его маршрут - начало, самовывоз, самовывоз, доставка, доставка, конец с переходами:

transition { vehicle_load['weight'] { amount: 0 }
             travel_distance_meters: 1000.0 }
transition { vehicle_load['weight'] { amount: 10 }
             travel_distance_meters: 1000.0 }
transition { vehicle_load['weight'] { amount: 20 }
             travel_distance_meters: 1000.0 }
transition { vehicle_load['weight'] { amount: 10 }
             travel_distance_meters: 1000.0 }
transition { vehicle_load['weight'] { amount: 0 }
             travel_distance_meters: 1000.0 }

тогда стоимость, понесенная этим LoadCost составляет (cost_below * load_below * miles + cost_above * load_above * kms)

  • переход 0: 0.0
  • переход 1: 2,0 * 10 * 1,0 + 10,0 * 0 * 1,0 = 20,0
  • переход 2: 2,0 * 15 * 1,0 + 10,0 * (20 - 15) * 1,0 = 80,0
  • переход 3: 2,0 * 10 * 1,0 + 10,0 * 0 * 1,0 = 20,0
  • переход 4: 0.0

Таким образом, LoadCost по маршруту составляет 120,0.

Однако, если маршрут имеет вид «начало, самовывоз, доставка, самовывоз, доставка, конец» с переходами:

transition { vehicle_load['weight'] { amount: 0 }
             travel_distance_meters: 1000.0 }
transition { vehicle_load['weight'] { amount: 10 }
             travel_distance_meters: 1000.0 }
transition { vehicle_load['weight'] { amount: 0 }
             travel_distance_meters: 1000.0 }
transition { vehicle_load['weight'] { amount: 10 }
             travel_distance_meters: 1000.0 }
transition { vehicle_load['weight'] { amount: 0 }
             travel_distance_meters: 1000.0 }

тогда стоимость, понесенная этим LoadCost составляет

  • переход 0: 0.0
  • переход 1: 2,0 * 10 * 1,0 + 10,0 * 0 * 1,0 = 20,0
  • переход 2: 0.0
  • переход 3: 2,0 * 10 * 1,0 + 10,0 * 0 * 1,0 = 20,0
  • переход 4: 0.0

В данном случае LoadCost по маршруту составляет 40,0.

LoadCost делает решения с большими объемами переходов более дорогими.

Экспериментальный вариант: более подробную информацию см. на странице https://developers.google.com/maps/tt/route-optimization/experimental/load-cost/make-request .

Поля
load_threshold

int64

Amount of load above which the cost of moving a unit of load changes from cost_per_unit_below_threshold to cost_per_unit_above_threshold. Must be >= 0.

cost_per_unit_below_threshold

double

Стоимость перемещения единицы груза для каждой единицы от 0 до порогового значения. Должна быть конечным значением и >= 0.

cost_per_unit_above_threshold

double

Cost of moving a unit of load, for each unit above threshold. In the special case threshold = 0, this is a fixed cost per unit. Must be a finite value, and >= 0.

TravelMode

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

Они должны быть подмножеством режимов перемещения API маршрутов платформы Google Карт, см.: https://developers.google.com/maps/documentation/routes/reference/rest/v2/RouteTravelMode

Примечание: WALKING маршруты находятся в стадии бета-тестирования и иногда могут отсутствовать чёткие тротуары или пешеходные дорожки. Это предупреждение необходимо отображать для всех пешеходных маршрутов, отображаемых в приложении.

Перечисления
TRAVEL_MODE_UNSPECIFIED Неуказанный режим движения, эквивалентный DRIVING .
DRIVING Способ передвижения, соответствующий направлению движения (автомобиль, ...).
WALKING Режим передвижения, соответствующий пешеходным маршрутам.

Политика разгрузки

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

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

Перечисления
UNLOADING_POLICY_UNSPECIFIED Политика разгрузки не определена; поставки должны осуществляться только после соответствующего забора груза.
LAST_IN_FIRST_OUT Доставка должна осуществляться в порядке, обратном порядку получения.
FIRST_IN_FIRST_OUT Доставка должна осуществляться в том же порядке, что и самовывоз.

VehicleFullness

VehicleFullness is a metric which computes how full a vehicle is. Each VehicleFullness field is between 0 and 1, computed as the ratio between a capped metric field (eg AggregatedMetrics.travel_distance_meters ) and its related vehicle limit (eg Vehicle.route_distance_limit ), if it exists. Otherwise the fullness ratio stays unset. If the limit is 0, the field is set to 1. Note: when a route is subject to traffic infeasibilities, some raw fullness ratios might exceed 1.0, eg the vehicle might exceed its distance limit. In these cases, we cap the fullness values at 1.0.

Поля
max_fullness

double

Maximum of all other fields in this message.

distance

double

The ratio between AggregatedMetrics.travel_distance_meters and Vehicle.route_distance_limit . If Vehicle.route_distance_limit is unset, this field will be unset.

travel_duration

double

The ratio between [AggregatedMetrics.travel_duration_seconds][] and Vehicle.travel_duration_limit . If Vehicle.travel_duration_limit is unset, this field will be unset.

active_duration

double

The ratio between [AggregatedMetrics.total_duration_seconds][] and Vehicle.route_duration_limit . If Vehicle.route_duration_limit is unset, this field will be unset.

max_load

double

The maximum ratio among all types of [AggregatedMetrics.max_load][] and their respective Vehicle.load_limits . If all Vehicle.load_limits fields are unset, this field will be unset.

active_span

double

The ratio (vehicle_end_time - vehicle_start_time) / (latest_vehicle_end_time - earliest_vehicle_start_time) for a given vehicle. If the denominator is not present, it uses ( ShipmentModel.global_end_time - ShipmentModel.global_start_time ) instead.

Путевая точка

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

Поля
side_of_road

bool

Необязательно. Указывает, что местоположение этой путевой точки должно быть приоритетным для остановки транспортного средства на определённой стороне дороги. При установке этого значения маршрут будет проходить через эту точку, чтобы транспортное средство могло остановиться на той стороне дороги, к которой она смещена относительно центра дороги. Эта опция не работает в режиме движения «ПЕШКОМ».

vehicle_stopover

bool

Indicates that the waypoint is meant for vehicles to stop at, where the intention is to either pick up or drop off. This option works only for the 'DRIVING' travel mode, and when the 'location_type' is 'location'.

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

Объединенное поле location_type . Различные способы представления местоположения. location_type может быть только одним из следующих:
location

Location

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

place_id

string

Идентификатор точки интереса (POI), связанный с путевой точкой.

При использовании идентификатора места для указания места прибытия или отправления в запросе VisitRequest используйте идентификатор, достаточно точный для определения координат LatLng для навигации к этому месту. Например, идентификатор здания подойдёт, но идентификатор дороги использовать не рекомендуется.