VehicleRoutingProblemSolverProperties

サマリー

Provides access to analysis properties from a vehicle routing problem Network Analyst layer. The GetSolverProperties function is used to obtain a VehicleRoutingProblemSolverProperties object from a vehicle routing problem Network Analyst layer.

説明

The VehicleRoutingProblemSolverProperties object provides read and write access to all the analysis properties of a vehicle routing problem Network Analyst layer. The object can be used to modify analysis properties of the vehicle routing problem layer, and the corresponding layer can be re-solved to determine the appropriate results. A new vehicle routing problem layer can be created using the Make Vehicle Routing Problem Analysis Layer geoprocessing tool. Obtaining the VehicleRoutingProblemSolverProperties object from a new vehicle routing problem layer allows you to reuse the existing layer for subsequent analyses rather than create a new layer for each analysis, which can be time consuming.

After modifying the properties of the VehicleRoutingProblemSolverProperties object, the corresponding layer can be immediately used with other functions and geoprocessing tools. There is no refresh or update of the layer required to honor the changes modified through the object.

プロパティ

プロパティ説明データ タイプ
attributeParameters
(読み書き)

Provides the ability to get or set the parameterized attributes to be used in the analysis. The property returns a Python dictionary. The dictionary key is a two-value tuple consisting of the attribute name and the parameter name. The value for each item in the dictionary is the parameter value.

Parameterized network attributes are used to model some dynamic aspect of an attribute's value. For example, a tunnel with a height restriction of 12 feet can be modeled using a parameter. In this case, the vehicle's height in feet should be specified as the parameter value. If the vehicle is taller than 12 feet, this restriction will then evaluate to True, thereby restricting travel through the tunnel. Similarly, a bridge could have a parameter to specify a weight restriction.

Attempting to modify the attributeParameters property in place won't result in updated values. Instead, you should always use a new dictionary object to set values for the property. The following two code blocks demonstrate the difference between these two approaches.

Do not attempt to modify the attributeParameters property in place; this coding method will not work.

solverProps.attributeParameters[('HeightRestriction', 'RestrictionUsage')] = "PROHIBITED"

Modify the attributeParameters property using a new dictionary object.

params = solverProps.attributeParameters
params[('HeightRestriction', 'RestrictionUsage')] = "PROHIBITED"
solverProps.attributeParameters = params
If the network analysis layer does not have parameterized attributes, this property returns None.

Dictionary
defaultDate
(読み書き)

Provides the ability to get or set the implied date for time field values that don't have a date specified with the time. If a time field for an order object, such as TimeWindowStart1, has a time-only value, the date is assumed to be the defaultDate property value. For example, if an order has a TimeWindowStart1 value of 9:00 a.m. and the defaultDate is set to datetime.date(2012, 3, 6), the entire time value for the field is 9:00 a.m., March 6, 2012. The default date has no effect on time field values that already have a date.

The day of the week can also be specified as the default date using the following dates:

  • 今日 - 12/30/1899
  • 日曜 - 12/31/1899
  • 月曜 - 1/1/1900
  • 火曜 - 1/2/1900
  • 水曜 - 1/3/1900
  • 木曜 - 1/4/1900
  • 金曜 - 1/5/1900
  • 土曜 - 1/6/1900

For example, to specify that the implied date for time field values should be Tuesday, specify the property value as 1/2/1900.

DateTime
distanceAttribute
(読み書き)

Provides the ability to get or set the distance cost attribute used to define the length along the elements of the network.

String
distanceFieldUnits
(読み書き)

Provides the ability to get or set the distance units used by distance fields of the analysis layer's sublayers and tables (network analysis classes). The unit does not have to be the same as the unit of the network cost attribute specified as the timeAttribute property value.

  • CentimetersCentimeters
  • DecimetersDecimeters
  • FeetFeet
  • InchesInches
  • KilometersKilometers
  • MetersMeters
  • MilesMiles
  • MillimetersMillimeters
  • NauticalMilesNautical miles
  • YardsYards
String
excessTransitTimeImportance
(読み書き)

Provides the ability to get or set the importance of reducing excess transit time. Excess transit time is the amount of time exceeding the time required to travel directly between the paired orders. The excess time results from breaks or travel to other orders or depots between visits to the paired orders.

This parameter is only relevant if using Order Pairs.

  • HighThe solver tries to find a solution with less excess transit time between paired orders at the expense of increasing the overall travel costs. It makes sense to use this setting if you are transporting people between paired orders and you want to shorten their ride time. This is characteristic of taxi services.
  • MediumThe solver looks for a balance between reducing excess transit time and reducing the overall solution cost.
  • LowThe solver tries to find a solution that minimizes overall solution cost, regardless of excess transit time. This setting is commonly used with courier services. Since couriers transport packages as opposed to people, they don't need to worry about ride time. Using Low allows the couriers to service paired orders in the proper sequence and minimize the overall solution cost.
String
ignoreInvalidLocations
(読み書き)

Specifies whether invalid input locations will be ignored. Typically, locations are invalid if they cannot be located on the network. When invalid locations are ignored, the solver will skip them and attempt to perform the analysis using the remaining locations.

  • SKIPInvalid input locations will be ignored so that the analysis will succeed using only valid locations. This value may also be specified using a Boolean value of True.
  • HALTInvalid locations will not be ignored and will cause the analysis to fail. This value may also be specified using a Boolean value of False.
String
outputPathShape
(読み書き)

Provides the ability to get or set the shape type for the route features that are output by the solver.

  • TRUE_LINES_WITH_MEASURESThe output routes will have the exact shape of the underlying network sources. Furthermore, the output includes route measurements for linear referencing. The measurements increase from the first stop and record the cumulative impedance to reach a given position.
  • TRUE_LINES_WITHOUT_MEASURESThe output routes will have the exact shape of the underlying network sources.
  • STRAIGHT_LINESThe output route shape will be straight lines connecting orders and depot visits, as per the route sequence.
  • NO_LINESNo shape will be generated for the output routes. You will also not be able to generate driving directions.
String
restrictions
(読み書き)

Provides the ability to get or set a list of restriction attributes that are applied for the analysis. An empty list, [], indicates that no restriction attributes are used for the analysis.

String
solverName
(読み取り専用)

Returns the name of the solver being referenced by the Network Analyst layer used to obtain the solver properties object. The property always returns the string value Vehicle Routing Problem Solver when accessed from a VehicleRoutingProblemSolverProperties object.

String
streetDirectionsProperties
(読み書き)

Provides read and write access to StreetDirectionsProperties, allowing you to customize the directions output from your vehicle routing problem layer.

Object
timeAttribute
(読み書き)

Provides the ability to get or set the time-based network cost attribute used to define the traversal time along the elements of the network. This cost attribute is minimized by the solver while finding the solution.

String
timeFieldUnits
(読み書き)

Provides the ability to get or set the time unit used by the temporal fields of the analysis layer's sublayers and tables (network analysis classes). The unit does not have to be the same as the unit of the network cost attribute specified as the timeAttribute property value.

  • DaysDays
  • HoursHours
  • MinutesMinutes
  • SecondsSeconds
String
timeWindowViolationImportance
(読み書き)

Provides the ability to get or set the importance of honoring time windows without causing violations. A time window violation occurs when a route arrives at an order, depot, or break after a time window has closed. The violation is the interval between the end of the time window and the arrival time of a route. The following is a list of possible values:

  • HighThe solver tries to find a solution that minimizes time window violations at the expense of increasing the overall travel time. Choose this option if arriving on time at orders is more important to you than minimizing your overall solution cost. This may be the case if you are meeting customers at your orders and you don't want to inconvenience them with tardy arrivals (another option is to use hard time windows that can't be violated at all).Given other constraints of a vehicle routing problem, it may be impossible to visit all the orders within their time windows. In this case, even using this option might produce violations.
  • MediumThe solver looks for a balance between meeting time windows and reducing the overall solution cost.
  • LowThe solver tries to find a solution that minimizes overall travel time, regardless of time windows. Choose this option if respecting time windows is less important than reducing your overall solution cost. You may want to use this setting if you have a growing backlog of service requests. For the purpose of servicing more orders in a day and reducing the backlog, you can choose this option even though customers will be inconvenienced with your fleet's late arrivals.
String
timeZoneUsageForTimeFields
(読み書き)

Specifies the time zone of datetime fields in the input data, such as the fields used for time windows.

  • GEO_LOCALThe dates and times for order time windows refer to the time zone in which the order is located.
  • UTCThe dates and times for order time windows refer to coordinated universal time (UTC).
String
spatialClustering
(読み書き)

Specifies whether to use spatial clustering.

  • CLUSTERThe orders assigned to a route will be spatially clustered. Clustering orders tends to keep routes in smaller areas and reduce how often route lines intersect one another; yet, clustering can increase overall travel times. This is the default.
  • NO_CLUSTERThe solver will not prioritize spatially clustering orders, and the route lines might intersect. Use this option if route zones are specified.
Boolean
travelMode
(読み取り専用)

Accesses the travel mode set on a network analysis layer as an arcpy.na.TravelMode object.

Object
useHierarchy
(読み書き)

Controls the use of the hierarchy attribute while performing the analysis. The following is a list of possible values:

  • USE_HIERARCHY Use the hierarchy attribute for the analysis. Using a hierarchy results in the solver preferring higher-order edges to lower-order edges. Hierarchical solves are faster, and they can be used to simulate the preference of a driver who chooses to travel on freeways over local roads when possible—even if that means a longer trip. This option is applicable only if the network dataset referenced by the Network Analyst layer has a hierarchy attribute. A value of True can also be used to specify this option.
  • NO_HIERARCHYDo not use the hierarchy attribute for the analysis. Not using a hierarchy yields an exact route for the network dataset. A value of False can also be used to specify this option.
String
uTurns
(読み書き)

Provides the ability to get or set the policy that indicates how the U-turns at junctions that could occur during network traversal between stops are being managed by the solver. The following is a list of possible values:

  • ALLOW_UTURNSU-turns are permitted at junctions with any number of connected edges.
  • NO_UTURNSU-turns are prohibited at all junctions, regardless of junction valency. Note that U-turns are still permitted at network locations even when this setting is chosen; however, you can set the individual network locations' CurbApproach property to prohibit U-turns there as well.
  • ALLOW_DEAD_ENDS_ONLYU-turns are prohibited at all junctions, except those that have only one adjacent edge (a dead end).
  • ALLOW_DEAD_ENDS_AND_INTERSECTIONS_ONLYU-turns are prohibited at junctions where exactly two adjacent edges meet but are permitted at intersections (junctions with three or more adjacent edges) and dead ends (junctions with exactly one adjacent edge). Often, networks have extraneous junctions in the middle of road segments. This option prevents vehicles from making U-turns at these locations.
String

方法の概要

方法説明
applyTravelMode (travel_mode)

Updates the analysis properties of a network analyst layer based on a travel mode object. The updated network analyst layer can then be solved to complete the analysis.

方法

applyTravelMode (travel_mode)
パラメーター説明データ タイプ
travel_mode

A variable that references a travel mode object derived from a network dataset. A list of travel mode objects can be obtained by calling the arcpy.na.GetTravelModes function.

VRP only solves with a time-based impedance, so only time-based impedance travel modes will be allowed.

Object

When a network analyst layer is created, it is assigned default values for all of its analysis properties. The individual analysis properties can be updated using a solver properties object obtained from the network analyst layer. A travel mode stores a predefined set of analysis settings that help to perform a particular analysis, such as a walking time travel mode that stores the analysis settings required to perform a time-based walking analysis.

Using the applyTravelMode method, all the analysis settings that are defined in a travel mode can be applied at once. After the analysis properties are updated, the network analyst layer can be solved to complete the analysis.

If there is an error when updating the solver properties, such as when the provided travel mode references properties that don't exist on the current network dataset or references properties that are no longer applicable to the network dataset that was used to create the network analyst layer corresponding to the solver properties object, no exceptions are raised. The method will execute successfully, but you will get errors when you try to solve such a network analyst layer.

If the travel_mode parameter does not reference a travel mode object or a string, a TypeError exception is raised. If the travel_mode parameter references a string and the string cannot be internally converted to a valid string representation of a travel mode object, a ValueError exception is raised.

コードのサンプル

VehicleRoutingProblemSolverProperties example 1

The script shows how to create a Vehicle Routing Problem layer, add the data, and solve it with the current date as the default date. It then updates the default date to Tuesday and solves again. This is based on the tutorial network dataset of the San Francisco region.

# Name: VehicleRoutingProblemSolverProperties_Workflow.py
# Description: Find the optimal VRP solution solving for today or a day of the
#              week. Uses the SolverProperties to update the existing VRP layer
#              before re-running the analysis.
# Requirements: Network Analyst Extension

# Import system modules
import arcpy
from arcpy import env
import os
import datetime

try:
    # Check out the Network Analyst license if available.
    # Fail if the Network Analyst
    # license is not available.
    if arcpy.CheckExtension("network") == "Available":
        arcpy.CheckOutExtension("network")
    else:
        raise arcpy.ExecuteError("Network Analyst Extension license is not available.")

    # Set environment settings
    output_dir = "C:\Data"
    # The NA layer's data will be saved to the workspace specified here
    env.workspace = os.path.join(output_dir, "Output.gdb")
    env.overwriteOutput = True

    # Set local variables
    input_gdb = "C:/Data/SanFrancisco.gdb"
    network = os.path.join(input_gdb, "Transportation", "Streets_ND")
    layer_name = "StoreDeliveryRoute"
    travel_mode = "Driving Time"
    time_units = "Minutes"
    distance_units = "Miles"
    in_orders = os.path.join(input_gdb, "Analysis/Stores")
    in_depots = os.path.join(input_gdb, "Analysis/DistributionCenter")
    in_routes = os.path.join(input_gdb, "Analysis/Routes")
    routes_today = os.path.join(output_dir, "Output.gdb", "Routes_Today")
    routes_tuesday = os.path.join(output_dir, "Output.gdb", "Routes_Tuesday")


    # Create a new Vehicle Routing Problem (VRP) layer. Since the time-based
    # attributes such as ServiceTime on orders and CostPerUnitTime on routes is
    # recorded in minutes, we use minutes for time_units parameter. As we are
    # using cost per unit distance in routes, we have to specify a distance
    # attribute. The values for CosterPerUnitDistance are in miles, so we
    # specify miles for distance units parameter
    result_object = arcpy.na.MakeVehicleRoutingProblemAnalysisLayer(network,
                                            layer_name, travel_mode,
                                            time_units, distance_units,
                                            line_shape="STRAIGHT_LINES")

    # Get the layer object form the result object. The route layer can now be
    # referenced using the layer object.
    layer_object = result_object.getOutput(0)

    # Get the names of all the sublayers within the VRP layer.
    sub_layer_names = arcpy.na.GetNAClassNames(layer_object)
    # Store the layer names that we will use later
    orders_layer_name = sub_layer_names["Orders"]
    depots_layer_name = sub_layer_names["Depots"]
    routes_layer_name = sub_layer_names["Routes"]

    # Load the store locations as orders. Using field mappings we map the
    # TimeWindowStart1, TimeWindowEnd1, and DeliveryQuantities properties
    # for Orders from the fields of store features and assign a value of
    # 0 to MaxViolationTime1 property. The Name and ServiceTime properties
    # have the correct mapped field names when using the candidate fields
    # from store locations feature class.
    candidate_fields = arcpy.ListFields(in_orders)
    order_field_mappings = arcpy.na.NAClassFieldMappings(layer_object,
                                                         orders_layer_name,
                                                         False, candidate_fields)
    order_field_mappings["TimeWindowStart1"].mappedFieldName = "TimeStart1"
    order_field_mappings["TimeWindowEnd1"].mappedFieldName = "TimeEnd1"
    order_field_mappings["DeliveryQuantities"].mappedFieldName = "Demand"
    order_field_mappings["MaxViolationTime1"].defaultValue = 0
    arcpy.na.AddLocations(layer_object, orders_layer_name, in_orders,
                          order_field_mappings, "")

    # Load the depots from the distribution center features. Using field mappings
    # we map the Name properties for Depots from the fields of distribution
    # center features and assign a value of 8 AM for TimeWindowStart1 and a
    # value of 5 PM for TimeWindowEnd1 properties
    depot_field_mappings = arcpy.na.NAClassFieldMappings(layer_object,
                                                         depots_layer_name)
    depot_field_mappings["Name"].mappedFieldName = "Name"
    depot_field_mappings["TimeWindowStart1"].defaultValue = "8 AM"
    depot_field_mappings["TimeWindowEnd1"].defaultValue = "5 PM"
    arcpy.na.AddLocations(layer_object, depots_layer_name, in_depots,
                          depot_field_mappings, "")

    # Load the routes from a table containing information about routes. In this
    # case, since the fields on the routes table and property names for Routes
    # are the same, we will just use the default field mappings
    arcpy.na.AddLocations(layer_object, routes_layer_name, in_routes, "", "")

    # Solve the VRP layer
    arcpy.na.Solve(layer_object)

    # Save the resulting Routes sublayer
    arcpy.management.CopyFeatures(routes_layer_name, routes_today)

    # Get the solver properties object from the vehicle routing problem layer
    solverProps = arcpy.na.GetSolverProperties(layer_object)

    # Update the default date to tuesday using the specified day in the above
    # doc (Tuesday - 1/2/1900) for the vehicle routing problem layer using the
    #solver properties object
    solverProps.defaultDate = datetime.date(1900, 1, 2)

    # Solve the VRP layer
    arcpy.na.Solve(layer_object)

    # Save the resulting Routes sublayer
    arcpy.management.CopyFeatures(routes_layer_name, routes_tuesday)


except Exception as e:
    # If an error occurred, print line number and error message
    import traceback
    import sys
    tb = sys.exc_info()[2]
    print ("An error occurred on line %i" % tb.tb_lineno)
    print (str(e))
ApplyTravelMode example 2 (workflow)

This script shows how to find routes for a fleet of trucks using the Trucking Time travel mode.

#Get the VRP layer object from a layer named "VRP" in the map
doc = arcpy.mp.ArcGISProject('current')
map_obj = doc.listMaps()[0]
vrp_layer = map_obj.listLayers('VRP')[0]

#Get the Trucking Time travel mode from the network dataset
desc = arcpy.Describe(vrp_layer)
travel_modes = arcpy.na.GetTravelModes(desc.network.catalogPath)
trucking_mode = travel_modes["Trucking Time"]

#Apply the travel mode to the analysis layer
solver_properties = arcpy.na.GetSolverProperties(vrp_layer)
solver_properties.applyTravelMode(trucking_mode)

関連トピック