NetworkDataset
Краткая информация
Предоставляет доступ к свойствам набора сетевых данных. Этот класс можно использовать для получения свойств и значений атрибутов ребер, соединений и поворотов набора сетевых данных, а также других свойств набора сетевых данных.
Синтаксис
NetworkDataset(in_network)
| Имя | Объяснение | Тип данных |
|---|---|---|
|
in_network |
Набор сетевых данных, свойства которого вы хотите получить. Аргумент можно задать с помощью пути к каталогу ч набором сетевых данных, объекту слоя набора сетевых данных или строки с именем слоя набора сетевых данных. |
String |
Свойства
| Имя | Объяснение | Тип данных |
|---|---|---|
|
buildTimestamp (Только для чтения) |
Дата и время последнего построения набора сетевых данных. |
DateTime |
|
customEvaluators (Чтение / Запись) |
Список классов Python, которые настраивают значения сетевых атрибутов для ребер, соединений и поворотов во время операции решения. Свойство должно быть указано как список экземпляров пользовательских классов, наследуемых от класса Классы пользовательского анализатора не могут быть постоянно связаны с набором сетевых данных с помощью этого свойства. Связь является временной и применяется только для выполнения операций в том же скрипте, где установлено это свойство. Чтобы навсегда сохранить связь с классом пользовательского анализатора, используйте метод |
Object |
|
directionsCustomizer (Чтение / Запись) |
Класс Python, который настраивает текст маневра по направлениям, возвращаемый при использовании набора сетевых данных в операции решения. Свойство должно быть указано как экземпляр определяемого пользователем класса, наследуемого от класса Классы пользовательских маршрутов не могут быть постоянно связаны с набором сетевых данных с помощью этого свойства. Связь является временной и применяется только для выполнения операций в том же скрипте, где установлено это свойство. Чтобы навсегда сохранить связь с классом пользовательских маршрутов, используйте метод |
Object |
|
edgeCount (Только для чтения) |
Число ребер сети. |
Integer |
|
isBuilt (Только для чтения) |
Указывает, построен ли набор сетевых данных. Значение |
Boolean |
|
junctionCount (Только для чтения) |
Число соединений сети. |
Integer |
|
travelModes (Только для чтения) |
Возвращает словарь объектов режимов передвижения, которые доступны в наборе сетевых данных. Ключи словаря – это имена режимов передвижения, а значения словаря – это объекты режимов передвижения. Это свойство возвращает такие же выходные данные, как и функция |
Dictionary |
|
turnCount (Только для чтения) |
Число поворотов в сети. |
Integer |
Методы
checkIntersectingFeatures(feature_layer, cutoff)
Возвращает значение Boolean, определяющее, является ли количество исходных объектов-ребер из заданного набора сетевых данных, которые пересекаются объектами в заданном векторном слое, меньшим или равным заданной предельной величине. Эта функция применяется для ограничения количества объектов, которые могут быть загружены, как линейные или полигональные барьеры в слой сетевого анализа.
Этот метод схож с функцией CheckIntersectingFeatures.
| Имя | Объяснение | Тип данных |
|---|---|---|
|
feature_layer |
Объект |
Layer |
|
cutoff |
Максимальное число пересекающих объектов. |
Integer |
Возвращаемое значение
| Тип данных | Объяснение |
|---|---|
|
Boolean |
Возвращает |
describe()
Возвращает объект Describe, содержащий дополнительные свойства набора сетевых данных. Это равнозначно использованию команды arcpy.Describe для набора сетевых данных.
Возвращаемое значение
| Тип данных | Объяснение |
|---|---|
|
Object |
Объект |
edges({edge_properties[edge_properties,...]}, {attribute_names[attribute_names,...]}, {time_of_day}, {eids[eids,...]}, {travel_mode}, {area_of_interest})
Возвращает итератор ребер набора сетевых данных, который можно использовать для доступа к значениям определенных свойств ребер и сетевых атрибутов в указанное время дня.
| Имя | Объяснение | Тип данных |
|---|---|---|
|
edge_properties[edge_properties,...] (Дополнительный) |
A list of strings representing the network edge properties to retrieve. For a single property, you can use a string instead of a list of strings. The available properties include the following:
To request the |
String |
|
attribute_names[attribute_names,...] (Дополнительный) |
The list of network dataset attribute names, such as costs or restrictions, for which to retrieve the value for each network element. If the value is time dependent, you can specify the time of day using the |
String |
|
time_of_day (Дополнительный) |
The time of day for which to retrieve time-dependent attribute values for this network element. When no time of day value is passed, the time-neutral value will be returned. |
DateTime |
|
eids[eids,...] (Дополнительный) |
A list of The |
Integer |
|
travel_mode (Дополнительный) |
The travel mode to apply when requesting edge properties and attribute values. The travel mode settings may impact the returned property and attribute values, particularly if the travel mode uses nondefault values for any attribute parameters. When no travel mode is specified, all values requested from The travel mode should be specified as a |
Object |
|
area_of_interest (Дополнительный) |
The spatial filter to apply when requesting edge properties and attribute values. This allows you to return only the subset of edges that intersect the specified area of interest. The parameter should be specified as an The |
Object |
Возвращаемое значение
| Тип данных | Объяснение |
|---|---|
|
Object |
Для итерирования по возвращенным ребрам может использоваться объект |
getDataSourceFromSourceID(source_id)
Возвращает путь к каталогу класса объектов исходного набора сетевых данных, идентифицированного по указанному идентификатору источника.
Подсказка:
Этот метод работает фактически мгновенно, поскольку считывает кэшированное значение. Ваш код может многократно вызывать этот метод с минимальным влиянием на производительность.
| Имя | Объяснение | Тип данных |
|---|---|---|
|
source_id |
The network source ID for which the corresponding source feature class's catalog path will be retrieved. |
Integer |
Возвращаемое значение
| Тип данных | Объяснение |
|---|---|
|
String |
Путь к каталогу класса объектов исходного набора сетевых данных. |
getLiveTrafficStatus(wait_for_update)
В наборе сетевых данных с настроенным текущим трафиком OpenLR, getLiveTrafficStatus считывает локальный кеш трафика и возвращает словарь с ключевыми индикаторами состояния.
| Имя | Объяснение | Тип данных |
|---|---|---|
|
wait_for_update |
Specifies whether the function will wait for any ongoing cache update to complete before retuning the status.
(Значение по умолчанию — False) |
Boolean |
Возвращаемое значение
| Тип данных | Объяснение |
|---|---|
|
Dictionary |
Словарь, содержащий ключевые индикаторы состояния о потоке текущего трафика и его кеше. Поддерживаются следующие ключи словаря:
Поддерживаются следующие ключи словаря
Пример выходного словаря
|
junctions({junction_properties[junction_properties,...]}, {attribute_names[attribute_names,...]}, {time_of_day}, {eids[eids,...]}, {travel_mode}, {area_of_interest})
Возвращает итератор соединений набора сетевых данных, который можно использовать для доступа к значениям определенных свойств соединений и сетевых атрибутов в указанное время дня.
| Имя | Объяснение | Тип данных |
|---|---|---|
|
junction_properties[junction_properties,...] (Дополнительный) |
A list of strings representing the network junction properties to retrieve. For a single property, you can use a string instead of a list of strings. The available properties include the following:
To request the |
String |
|
attribute_names[attribute_names,...] (Дополнительный) |
The list of network dataset attribute names, such as costs or restrictions, for which the value of each network element will be retrieved. If the value is time dependent, you can specify the time of day using the |
String |
|
time_of_day (Дополнительный) |
The time of day that time-dependent attribute values for this network element will be retrieved. When no time of day value is passed, the time-neutral value will be returned. |
DateTime |
|
eids[eids,...] (Дополнительный) |
A list of The |
Integer |
|
travel_mode (Дополнительный) |
The travel mode to apply when requesting junction properties and attribute values. The travel mode settings may impact the returned property and attribute values, particularly if the travel mode uses nondefault values for any attribute parameters. When no travel mode is specified, all values requested from The travel mode should be specified as a |
Object |
|
area_of_interest (Дополнительный) |
The spatial filter to apply when requesting junction properties and attribute values. This allows you to return only the subset of junctions that intersect the specified area of interest. The parameter should be specified as an The |
Object |
Возвращаемое значение
| Тип данных | Объяснение |
|---|---|
|
Object |
Объект |
turns({turn_properties[turn_properties,...]}, {attribute_names[attribute_names,...]}, {eids[eids,...]}, {travel_mode}, {area_of_interest})
Возвращает итератор элементов поворотов набора сетевых данных, которые используются для доступа к значению определенных свойств поворота и атрибутов сети.
| Имя | Объяснение | Тип данных |
|---|---|---|
|
turn_properties[turn_properties,...] (Дополнительный) |
A list of strings representing the network turn properties to retrieve. For a single property, you can use a string instead of a list of strings. The available properties include the following:
To request the |
String |
|
attribute_names[attribute_names,...] (Дополнительный) |
The list of network dataset attribute names, such as costs or restrictions, for which to retrieve the value for each network element. For a single attribute, you can use a string instead of a list of strings. |
String |
|
eids[eids,...] (Дополнительный) |
A list of The |
Integer |
|
travel_mode (Дополнительный) |
The travel mode to apply when requesting turn properties and attribute values. The travel mode settings may impact the returned property and attribute values, particularly if the travel mode uses nondefault values for any attribute parameters. When no travel mode is specified, all values requested from The travel mode should be specified as a |
Object |
|
area_of_interest (Дополнительный) |
The spatial filter to apply when requesting turn properties and attribute values. This allows you to return only the subset of turns that intersect the specified area of interest. The parameter should be specified as an The |
Object |
Возвращаемое значение
| Тип данных | Объяснение |
|---|---|
|
Object |
Объект |
updateNetworkDatasetSchema({custom_evaluators}, {custom_directions}, {openlr_traffic_service_id}, {openlr_traffic_feed_ids})
Обновляет набор сетевых данных, чтобы связать с сетью пользовательский анализатор или класс Python путевых листов или задает идентификатор сервиса Текущего трафика OpenLR или идентификаторы каналов.
| Имя | Объяснение | Тип данных |
|---|---|---|
|
custom_evaluators (Дополнительный) |
A dictionary that describes the custom evaluators that will be associated with the network dataset. The dictionary keys are the network attribute names that the custom evaluator will be applied to. The values are a dictionary with a This code snippet shows a dictionary with the correct structure to update the network dataset's
Only include a given network attribute in the dictionary once. You can only associate one custom evaluator with a given attribute. To remove a reference to existing custom evaluators from the network dataset schema, use a value of
Внимание:Positional arguments are not supported with this method. To associate a custom evaluator with the network, you must use the named argument |
Dictionary |
|
custom_directions (Дополнительный) |
A dictionary that describes the directions customization classes that will be associated with the network dataset. The dictionary must have a This code snippet shows a dictionary with the correct structure to update the network dataset schema with a custom directions class named
To remove a reference to existing custom directions classes from the network dataset schema, use a value of
Внимание:Positional arguments are not supported with this method. To associate a custom directions class with the network, you must use the named argument |
Dictionary |
|
openlr_traffic_service_id (Дополнительный) |
Specifies an ID that represents the OpenLR live traffic service that the network will use. Valid values are as follows:
|
String |
|
openlr_traffic_feed_ids (Дополнительный) |
Specifies one or more IDs that represents the OpenLR live traffic feed IDs that the network will use. The schema can only have the traffic service ID or the traffic feed IDs set. Setting one will clear the other from the schema. Setting both in a single call with raise an exception. Valid values are as follows:
|
String |
updateTrafficCache({timeout_seconds})
В наборе сетевых данных с настроенным текущим трафиком OpenLR, updateTrafficCache обновляет локальный кэш трафика, добавляя актуальные данные о скорости, перекрытиях дорог и сопутствующими метаданными.
| Имя | Объяснение | Тип данных |
|---|---|---|
|
timeout_seconds (Дополнительный) |
The maximum duration in seconds the function can run. If this time limit is exceeded, the function will automatically terminate. If no value is specified, the timeout duration will be the number of seconds specified by the |
Long |
Пример кода
Выдает время в пути для каждого ребра сети, по которому не ограничено движение автомобилей.
# Print the travel time for each edge in the network that is not restricted to automobiles
import datetime
import arcpy
nds_path = r"E:\TutorialData\Network Analyst\Tutorial\SanDiego.gdb\Transportation\Streets_ND"
# Initialize the NetworkDataset object
nds = arcpy.nax.NetworkDataset(nds_path)
# Print network dataset build information
print(f"Network dataset is built: {nds.isBuilt}")
print(f"Most recent build time: {nds.buildTimestamp}")
# Iterate through all the edges in the network and get the TravelTime cost attribute
# value for a specific time of day. Only print the value if the edge is not restricted
# to automobiles
edges = nds.edges("EID", ["TravelTime", "Driving an Automobile"], datetime.datetime(2019, 4, 19, 8, 0, 0))
for edge in edges:
if not edge[2]:
print(f"TravelTime for EID {edge[0]}: {edge[1]}")
Получает значения ObjectID всех соединений для всех ребер, которые участвуют в поворотах.
# Retrieve the ObjectIDs of all junctions for all edges that participate in turns
import arcpy
nds_path = r"E:\TutorialData\Network Analyst\Tutorial\SanDiego.gdb\Transportation\Streets_ND"
# Initialize the NetworkDataset object
nds = arcpy.nax.NetworkDataset(nds_path)
# Iterate through all turns in the network and get the edges that participate
turns = nds.turns(["SOURCEOID", "EDGEEIDS"])
for turn in turns:
# For the edges in the turn, get the from and to junctions
edges = nds.edges(["SOURCEOID", "FROMJUNCTION", "TOJUNCTION"], eids=turn[1])
for edge in edges:
# For the from and to junction, get the SOURCEOID
junctions = nds.junctions("SOURCEOID", eids=[edge[1], edge[2]])
junctionOIDs = [j[0] for j in junctions]
Получает стоимость и статус запрета для всех ребер сети для режима передвижения Walking Time.
# Retrieve the cost and restricted status for all network edges for the Walking Time travel mode
import arcpy
nds_path = r"E:\TutorialData\Network Analyst\Tutorial\SanDiego.gdb\Transportation\Streets_ND"
# Initialize the NetworkDataset object
nds = arcpy.nax.NetworkDataset(nds_path)
# Iterate through all the edges in the network and print the cost to traverse it with the Walking Time travel mode and
# whether or not the edge is restricted.
for edge in nds.edges(["EID", "COST", "ISRESTRICTED"], travel_mode=nds.travelModes["Walking Time"]):
print(f"EID {edge[0]} -- COST: {edge[1]}; RESTRICTED: {edge[2]}")
Получает значения ObjectID всех соединений в пределах указанного экстента.
# Retrieve the ObjectID values for junctions within a specified extent
import arcpy
nds_path = r"E:\TutorialData\Network Analyst\Tutorial\SanDiego.gdb\Transportation\Streets_ND"
extent_fc = r"E:\TutorialData\Network Analyst\Tutorial\SanDiego.gdb\Analysis\AnalysisExtent"
# Initialize the NetworkDataset object
nds = arcpy.nax.NetworkDataset(nds_path)
# Get the extent from the feature class
extent = arcpy.Describe(extent_fc).extent
# Retrieve the junctions that fall within the designated extent
for junction in nds.junctions(["SOURCEOID"], area_of_interest=extent):
print(junction)
Получает значения ObjectID всех соединений в пределах указанных областей.
# Retrieve the ObjectID values for junctions within specified territories
import arcpy
nds_path = r"E:\TutorialData\Network Analyst\Tutorial\SanDiego.gdb\Transportation\Streets_ND"
territories = r"E:\TutorialData\Network Analyst\Tutorial\SanDiego.gdb\Analysis\Territories"
# Initialize the NetworkDataset object
nds = arcpy.nax.NetworkDataset(nds_path)
# Iterate through the polygons in the Territories feature class and retrieve
# the junctions that fall within each territory's boundary.
for row in arcpy.da.SearchCursor(territories, ["Name", "SHAPE@"]):
print(f"Junctions in territory {row[0]}:")
for junction in nds.junctions(["SOURCEOID"], area_of_interest=row[1]):
print(junction[0])