Utility Network Tracing with the ArcGIS Maps SDK for JavaScript and Python
This post explains the utility network concepts you need before writing trace code, then runs traces three ways: the ArcGIS Maps SDK for JavaScript 5.2 (UtilityNetwork.trace() and the REST trace() function), the ArcGIS API for Python 2.4.4 (UtilityNetworkManager), and arcpy (arcpy.un.Trace). The TypeScript type-checks against @arcgis/core@5.2.9, and the Python method signatures match the published packages and documentation.
Core concepts
A trace fails or returns nonsense when one of these concepts is misread, so it pays to get them straight first.
- Domain network. One commodity, such as electric distribution, gas or water. A utility network has one or more domain networks plus a structure network that holds poles, vaults and other supporting features. Each domain network has its own device, junction, line and subnetline classes. Each feature has an asset group and an asset type, which the rules refer to.
- Tier. A level in the network hierarchy inside a domain network, for example Subtransmission and Medium Voltage Radial. Tiers can be radial or mesh, and they define how subnetworks are managed. Upstream and downstream traces stop at the tier boundary unless you give them a target tier.
- Subnetwork and subnetwork controller. A subnetwork is the connected part of a tier fed by one or more controllers, such as a circuit breaker at a substation. Controllers are sources (or sinks), and they define flow direction. Upstream means toward the controller and downstream means away from it. The subnetworks table records each subnetwork's name and whether it is dirty.
- Terminals. A device such as a transformer can have several terminals (high side and low side). A trace location on a junction needs a
terminalId. A location on a line needs apercentAlong. - Associations. Relationships that are not geometric connections. Connectivity associations connect features that do not touch. Containment puts content inside a container, for example devices in a vault. Structural attachment ties a device to a structure, such as a transformer on a pole. Trace options such as
includeContainersandincludeStructuresact on these associations. - Network topology and dirty areas. Traces do not read your features. They read the network topology, a graph the server builds from features, connectivity and associations. Every edit creates a dirty area marking where the topology no longer matches the features. Until you validate the topology there, a trace may return stale results.
One domain network, two tiers, and two subnetworks, each fed by a controller. Upstream and downstream are measured from the starting point.
What you need on the server side
The JavaScript SDK and the ArcGIS API for Python work against utility network services, not against geodatabases. You need these pieces:
- ArcGIS Enterprise, with the utility network in an enterprise geodatabase that is registered with the server.
- The data shared from ArcGIS Pro as a web layer, using a geodatabase connection whose versioning type is Branch. The utility network's feature dataset must be registered as branch versioned.
- A feature service with the Utility Network capability, which provides the
UtilityNetworkServerendpoint for trace, validate and subnetwork operations. Add Version Management if you work with named versions. - Licensing. The Enterprise documentation says the portal account needs the ArcGIS Advanced Editing user type extension to create, publish and edit a utility network, and that query and trace operations do not need it. Validating topology counts as editing. The Pro tool page for Validate Network Topology requires Advanced Editing in an enterprise deployment.
Two caveats. First, the Python API's trace() docstring says Advanced Editing is required. That contradicts the Enterprise page, so test with the account your users actually have. Second, the 5.2 trace component checks licensing only against servers at 11.1 or earlier. There it checks for the older Utility Network user type extension that Advanced Editing replaced.
ArcGIS Online cannot host a utility network. You can share an Enterprise utility network service into Online through a proxied service, but the trace component's documentation states that it does not support proxied services or services that use stored credentials. File and mobile geodatabases hold utility networks for single-user work in ArcGIS Pro, where arcpy can trace them directly.
Trace types and naming
The trace types are connected, upstream, downstream, subnetwork, subnetwork controllers, loops, isolation, path, circuit (telecom only) and shortest path. Shortest path is deprecated with ArcGIS Pro 3.7 and Enterprise 12.1, so use path for new code. Each API spells these names differently:
- JavaScript:
"upstream","subnetwork-controller", location type"starting-point". - REST and Python API:
"upstream","subnetworkController", location type"startingPoint". - arcpy:
"UPSTREAM","SUBNETWORK_CONTROLLERS". Locations come from a starting points feature class.
Tracing from the JavaScript SDK
Get the UtilityNetwork object
The UtilityNetwork class lives in @arcgis/core/networks/UtilityNetwork. You can get one from a web map that has a utility network saved in it, or construct one from the utility network layer URL:
import "@arcgis/map-components/components/arcgis-map";
import UtilityNetwork from "@arcgis/core/networks/UtilityNetwork";
import WebMap from "@arcgis/core/WebMap";
// Option A: the utility network saved in a web map
export async function getNetworkFromMap(): Promise<UtilityNetwork> {
const viewElement = document.querySelector("arcgis-map")!;
await viewElement.viewOnReady();
const webMap = viewElement.map as WebMap;
const un = webMap.utilityNetworks?.at(0);
if (!un) throw new Error("This web map has no utility network");
await un.load();
return un;
}
// Option B: straight from the utility network layer URL
export async function getNetworkFromUrl(layerUrl: string): Promise<UtilityNetwork> {
const un = new UtilityNetwork({ layerUrl });
await un.load();
return un;
}
Run an upstream trace
createTraceLocation() builds a trace location from a feature graphic, using its GlobalID and terminal. trace() fills in gdbVersion and the historic moment from the network object for you. Element results come back as network source IDs and GlobalIDs. getObjectIdsFromElements() converts them to layer URLs and object IDs that you can query or highlight:
// Upstream trace from one device feature (a junction)
export async function traceUpstream(un: UtilityNetwork, device: Graphic): Promise<TraceResult> {
const start = un.createTraceLocation(device, "starting-point");
const result = await un.trace({
traceType: "upstream",
traceLocations: [start],
traceConfiguration: {
domainNetworkName: "ElectricDistribution",
tierName: "Medium Voltage Radial",
includeContainers: true,
includeStructures: false,
},
resultTypes: [{ type: "elements", includeGeometry: false, includePropagatedValues: false, networkAttributeNames: [], diagramTemplateName: "", resultTypeFields: [] }],
});
for (const info of un.getObjectIdsFromElements(result.elements)) {
console.log(`${info.layerUrl}: ${info.objectIds.length} features`);
}
return result;
}
The domain network and tier names must match the schema exactly. Read them at runtime from un.domainNetworkNames and un.getTierNames(domain) instead of hard-coding them.
Use a named trace configuration
Named trace configurations store the trace type, tiers, barriers and filters on the server, so the client sends only the starting points. In a shared app this is the better default, because editors in ArcGIS Pro and web users run the same trace definition:
// Named trace configuration: the service supplies the trace type and settings
export async function traceNamed(un: UtilityNetwork, configTitle: string, start: TraceLocation): Promise<TraceResult> {
const config = un.sharedNamedTraceConfigurations.find((c) => c.title === configTitle);
if (!config) throw new Error(`No shared trace configuration named ${configTitle}`);
return un.trace({ namedTraceConfigurationGlobalId: config.globalId, traceLocations: [start] });
}
The low-level REST function
@arcgis/core/rest/networks/trace exposes trace(url, params). It takes the networkServiceUrl, and unlike the class method it does not fill in the version for you:
// Low-level REST helper: you pass the networkServiceUrl and the gdbVersion yourself
export async function traceConnectedRest(un: UtilityNetwork, globalId: string, terminalId: number): Promise<TraceResult> {
const params = new TraceParameters({
traceType: "connected",
gdbVersion: un.gdbVersion,
traceLocations: [new TraceLocation({ type: "starting-point", globalId, terminalId })],
});
return trace(un.networkServiceUrl, params);
}
No-code option: the trace analysis component
If you only need the standard workflow (pick a named configuration, click starting points and barriers, view results), use the component. It was added in 5.0, and arcgis-utility-network-trace is deprecated in its favor:
<arcgis-map item-id="YOUR_WEBMAP_ID">
<arcgis-utility-network-trace-analysis slot="top-right"></arcgis-utility-network-trace-analysis>
<arcgis-utility-network-validate-network-topology slot="bottom-right"></arcgis-utility-network-validate-network-topology>
</arcgis-map>
The web map must contain the utility network and its named trace configurations. The component supports every trace type except circuit, and it fires arcgisTraceResultFeaturesReady when result features are available.
Tracing from the ArcGIS API for Python
arcgis.features.UtilityNetworkManager wraps the UtilityNetworkServer REST endpoint. Its trace() method takes locations, trace_type, an optional configuration dict (or a TraceConfiguration model), result_types, trace_config_global_id, out_sr and future for asynchronous jobs. It returns the raw JSON response:
from collections import Counter
from arcgis.gis import GIS
from arcgis.features import FeatureLayer, FeatureLayerCollection, UtilityNetworkManager
FS_URL = "https://gis.example.com/server/rest/services/Electric/FeatureServer"
DEVICE_LAYER_ID = 3 # the device layer in this service
gis = GIS("https://gis.example.com/portal", profile="un_reader") # stored credential profile
flc = FeatureLayerCollection(FS_URL, gis)
un = UtilityNetworkManager(FS_URL.rsplit("/", 1)[0] + "/UtilityNetworkServer", gis=gis)
# 1. Find the starting feature's GlobalID
devices = FeatureLayer(f"{FS_URL}/{DEVICE_LAYER_ID}", gis)
fset = devices.query(where="ASSETID = 'SW-1042'", out_fields="GLOBALID", return_geometry=False)
if not fset.features:
raise SystemExit("Device not found")
global_id = fset.features[0].attributes["GLOBALID"]
# 2. Upstream trace on the Medium Voltage tier
result = un.trace(
locations=[{"traceLocationType": "startingPoint", "globalId": global_id, "terminalId": 1}], # terminal from the device's terminal configuration
trace_type="upstream",
configuration={
"domainNetworkName": "ElectricDistribution",
"tierName": "Medium Voltage Radial",
"includeContainers": True,
"includeStructures": False,
"includeBarriers": True,
"validateConsistency": True,
},
result_types=[{"type": "elements", "includeGeometry": False}],
)
if not result.get("success", False):
raise SystemExit(f"Trace failed: {result}")
elements = result["traceResults"]["elements"]
per_source = Counter(e["networkSourceId"] for e in elements)
print(f"{len(elements)} elements upstream")
for source_id, count in per_source.most_common():
print(f" network source {source_id}: {count}")
The arcpy Trace documentation notes that when you run a subnetwork-based trace from Python, the tier's subnetwork trace configuration is not applied automatically. Its barriers, such as open devices, must be passed explicitly. A named trace configuration carries those settings with it, which is one more reason to prefer one. The configuration keys are the REST names (domainNetworkName, tierName, targetTierName, subnetworkName and so on). A subnetwork trace by name needs no starting point. Pass an empty locations list:
# 3. Subnetwork trace by name: no starting points needed
sub = un.trace(
locations=[],
trace_type="subnetwork",
configuration={
"domainNetworkName": "ElectricDistribution",
"tierName": "Medium Voltage Radial",
"subnetworkName": "RMT001",
},
result_types=[{"type": "elements", "includeGeometry": False}],
)
print("subnetwork elements:", len(sub["traceResults"]["elements"]))
To trace a named branch version, get it from flc.versions and use version.utility. That returns a UtilityNetworkManager that sends the version name and session ID with each request.
Tracing with arcpy
arcpy.un.Trace runs inside ArcGIS Pro's Python. With an enterprise geodatabase, the input must be a utility network from a feature service. A database connection is not supported. The tool has more than 60 optional parameters. Esri's own samples pass arguments by position while skipping some, which shifts values into the wrong parameters (the seventh positional argument is target_tier). Always use keyword arguments:
import json
import arcpy
UN_LAYER = "Electric Utility Network" # utility network layer added from the feature service
STARTS = r"C:\Work\Project.gdb\UN_Temp_Starting_Points"
OUT_JSON = r"C:\Work\upstream_elements.json"
# Validate first: traces read the network topology, not the features
arcpy.un.ValidateNetworkTopology(UN_LAYER, "470789 3597733 531454 3639864")
arcpy.un.Trace(
in_utility_network=UN_LAYER,
trace_type="UPSTREAM",
starting_points=STARTS,
domain_network="ElectricDistribution",
tier="Medium Voltage Radial",
include_containers="INCLUDE_CONTAINERS",
include_structures="EXCLUDE_STRUCTURES",
include_barriers="INCLUDE_BARRIERS",
validate_consistency="VALIDATE_CONSISTENCY",
result_types=["ELEMENTS"],
out_json_file=OUT_JSON,
)
with open(OUT_JSON, encoding="utf-8") as f:
data = json.load(f)
print("result sections:", sorted(data)) # inspect once, then read the keys you need
# Same trace driven by a named trace configuration stored in the network
arcpy.un.Trace(
in_utility_network=UN_LAYER,
starting_points=STARTS,
use_trace_config="USE_TRACE_CONFIGURATION",
trace_config_name="{8F6C2C0A-1E2B-4C47-9D1E-0B9C2A4E7F11}",
result_types=["SELECTION"],
)
Starting points come from a table or feature class with a FEATUREGLOBALID field. The Trace pane's UN_Temp_Starting_Points has the right schema. validate_consistency makes the trace fail when it crosses a dirty area, so stale results do not pass silently. The licensing section of the Trace tool lists Basic as Limited, supported in an enterprise deployment with named user licensing, and Standard and Advanced as Yes.
Dirty areas and validating topology
Before you trust a trace in an area that was just edited, check for dirty areas there and validate if any exist. In JavaScript, the dirty areas layer URL is on networkSystemLayers, and validateTopology() is on the network object:
// Dirty areas: count them in the current extent, then validate
export async function validateDirty(un: UtilityNetwork, extent: Extent): Promise<void> {
const url = un.networkSystemLayers.dirtyAreasLayerUrl;
if (!url) throw new Error("Dirty areas layer not available");
const dirtyAreas = new FeatureLayer({ url, gdbVersion: un.gdbVersion ?? undefined });
const dirtyCount = await dirtyAreas.queryFeatureCount({ geometry: extent, spatialRelationship: "intersects" });
if (dirtyCount === 0) return;
const result = await un.validateTopology({ validateArea: extent });
console.log("full update:", result.fullUpdate, "discovered subnetworks:", result.discoveredSubnetworks?.length ?? 0);
}
The Python equivalent is un.validate_topology(envelope=extent), which also accepts validation_type (normal, rebuild or forceRebuild) and future=True for large areas. In arcpy, call arcpy.un.ValidateNetworkTopology(un_layer, extent). On the Default version only one validate can run at a time. Editing and tracing stay available while it runs. Validate also reports the subnetworks it marked dirty. Run Update Subnetwork on those to refresh subnetwork names and the subnetworks table.
Summary
A utility network trace walks the network topology, not your features. It is only as current as your last validate, and the domain network, tier and terminal decide where it can go. On the server you need an ArcGIS Enterprise feature service with the Utility Network capability, on a branch versioned enterprise geodatabase. Editing and validating need the Advanced Editing user type extension. In JavaScript, load a UtilityNetwork, build locations with createTraceLocation(), and call trace(), preferably with a named trace configuration. In Python, UtilityNetworkManager.trace() sends the same REST request. In ArcGIS Pro, arcpy.un.Trace does the job, called with keyword arguments only. Check dirty areas first and validate where you find them.
Comments