Get a server-defined trace configuration for a given tier and modify its traversability scope, add new condition barriers, and control what is included in the subnetwork trace result.

Use case
While some traces are built from an ad-hoc group of parameters, many are based on a variation of the trace configuration taken from the subnetwork definition. For example, an electrical trace will be based on the trace configuration of the subnetwork, but may add additional clauses to constrain the trace along a single phase. Similarly, a trace in a gas or electric design application may include features with a status of “In Design” that are normally excluded from trace results.
How to use the sample
The sample loads with a server-defined trace configuration from a tier. Use the switches to toggle which options to include in the trace - such as containers or barriers. Tap the middle button on the bottom toolbar to create a new condition to add to the list. Swipe left on a condition under “List of conditions” to delete it or tap “Reset” to delete the whole list. Tap “Trace” to run a subnetwork trace with this modified configuration from a default starting location.
Example barrier conditions for the default dataset:
- ‘Transformer Load’ equal ‘15’
- ‘Phases Current’ doesNotIncludeTheValues ‘A’
- ‘Generation KW’ lessThan ‘50’
How it works
- Create and load a
UtilityNetworkwith aServiceGeodatabasefrom a feature service URL, then get an asset type and a tier by their names. - Populate the choice list for the comparison source with the non-system defined
UtilityNetworkDefinition.networkAttributes. Populate the choice list for the comparison operator with the enum values fromUtilityAttributeComparisonOperator. - Create a
UtilityElementfrom this asset type to use as the starting location for the trace. - Update the selected barrier expression and the checked options in the UI using this tier’s
TraceConfiguration. - When an attribute has been selected, if its
Domainis aCodedValueDomain, populate the choice list for the comparison value with itsCodedValues. Otherwise, display aTextFieldfor entering an attribute value. - When “Add” is tapped, create a new
UtilityNetworkAttributeComparisonusing the selected comparison source, operator, and selected or typed value. Use the selected source’sdataTypeto convert the comparison value to the correct data type. - If the traversability’s list of
barriersis not empty, create anUtilityTraceOrConditionwith the existingbarriersand the new comparison from step 6. - When “Trace” is tapped, create
UtilityTraceParameterspassing insubnetworkand the default starting location. Set itstraceConfigurationwith the modified options, selections, and expression; then trace the utility network withUtilityNetwork.trace(using:). - When “Reset” is tapped, set the trace configurations expression back to its original value.
- Display the count of returned
UtilityElementTraceResult.elements.
Relevant API
- CodedValueDomain
- UtilityAssetType
- UtilityCategory
- UtilityCategoryComparison
- UtilityCategoryComparisonOperator
- UtilityDomainNetwork
- UtilityElement
- UtilityElementTraceResult
- UtilityNetwork
- UtilityNetworkAttribute
- UtilityNetworkAttributeComparison
- UtilityNetworkAttributeComparison.Operator
- UtilityNetworkDefinition
- UtilityTerminal
- UtilityTier
- UtilityTraceAndCondition
- UtilityTraceConfiguration
- UtilityTraceOrCondition
- UtilityTraceParameters
- UtilityTraceResult
- UtilityTraceType
- UtilityTraversability
About the data
The Naperville electrical network feature service, hosted on ArcGIS Online, contains a utility network used to run the subnetwork-based trace shown in this sample.
Additional information
Using utility network on ArcGIS Enterprise 10.8 requires an ArcGIS Enterprise member account licensed with the Utility Network user type extension. Please refer to the utility network services documentation.
Tags
category comparison, condition barriers, network analysis, network attribute comparison, subnetwork trace, trace configuration, traversability, utility network, validate consistency
Sample code
// Copyright 2023 Esri//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// https://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.
import ArcGISimport SwiftUI
struct AnalyzeNetworkWithSubnetworkTraceView: View { /// The view model for the sample. @StateObject private var model = Model()
/// The attribute selected by the user. @State private var selectedAttribute: UtilityNetworkAttribute?
/// The comparison selected by the user. @State private var selectedComparison: UtilityNetworkAttributeComparison.Operator?
/// The value selected by the user. @State private var selectedValue: (any Sendable)?
/// A Boolean value indicating if the add condition menu is presented. @State private var isConditionMenuPresented = false
/// The value input by the user. @State private var inputValue: Double?
/// A Boolean value indicating if the trace results should be presented in an alert. @State private var presentTraceResults = false
/// A Boolean value indicating whether to include barriers in the trace results. @State private var includesBarriers = true
/// A Boolean value indicating whether to include containment features in the trace results. @State private var includesContainers = true
/// The error shown in the error alert. @State private var error: (any Error)?
var body: some View { if !model.isSetUp { loadingView .task { do { try await model.setup() } catch { self.error = error } } } else { Form { Section("Trace Options") { Toggle("Includes barriers", isOn: $includesBarriers) Toggle("Includes containers", isOn: $includesContainers) } Section { ForEach(model.conditions, id: \.self) { condition in Text(condition) } .onDelete { indexSet in model.deleteConditionalExpression(atOffsets: indexSet) } } header: { Text("Conditions") } footer: { Text(model.expressionString) } } .alert("Trace Result", isPresented: $presentTraceResults, actions: {}, message: { if model.traceResultsCount == 0 { Text("No element found.") } else { Text("\(model.traceResultsCount, format: .number) element(s) found.") } }) .sheet(isPresented: $isConditionMenuPresented) { NavigationStack { conditionMenu } } .overlay(alignment: .center) { loadingView } .toolbar { ToolbarItemGroup(placement: .bottomBar) { toolbarItems } } .onTeardown { model.tearDown() } } }
@ViewBuilder private var toolbarItems: some View { Button("Reset") { model.reset() } .disabled(model.conditions.count == 1) Spacer() Button { isConditionMenuPresented = true inputValue = nil } label: { Image(systemName: "plus") .imageScale(.large) } Spacer() Button("Trace") { Task { do { try await model.trace(includeBarriers: includesBarriers, includeContainers: includesContainers) presentTraceResults = true } catch { self.error = error } } } .disabled(!model.traceEnabled) }
@ViewBuilder private var loadingView: some View { ZStack { if !model.statusText.isEmpty { Color.clear.background(.ultraThinMaterial) VStack { Text(model.statusText) ProgressView() .progressViewStyle(.circular) } .padding() .background(.ultraThickMaterial) .clipShape(.rect(cornerRadius: 10)) .shadow(radius: 50) } } .errorAlert(presentingError: $error) }
@ViewBuilder private var conditionMenu: some View { List { NavigationLink { attributesView } label: { HStack { Text("Attributes") if let selectedAttribute = selectedAttribute { Spacer() Text(selectedAttribute.name) .foregroundStyle(.secondary) } } } NavigationLink { operatorsView } label: { HStack { Text("Comparison") if let selectedComparison = selectedComparison { Spacer() Text(selectedComparison.title) .foregroundStyle(.secondary) } } } if selectedAttribute?.domain is CodedValueDomain { NavigationLink { valuesView } label: { HStack { Text("Value") if let value = selectedValue as? CodedValue { Spacer() Text(value.name) .foregroundStyle(.secondary) } } } .disabled(selectedAttribute == nil && selectedComparison == nil) } else { HStack { Text("Value") TextField("Comparison value", value: $inputValue, format: .number, prompt: Text("Value")) .multilineTextAlignment(.trailing) .lineLimit(1) } .onChange(of: inputValue) { selectedValue = inputValue } .disabled(selectedAttribute == nil && selectedComparison == nil) } } .navigationTitle("Add Condition") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { isConditionMenuPresented = false guard let attribute = selectedAttribute, let comparison = selectedComparison, let value = selectedValue else { // show error return } do { try model.addConditionalExpression( attribute: attribute, comparison: comparison, value: value ) selectedAttribute = nil selectedComparison = nil selectedValue = nil inputValue = nil } catch { self.error = error } } .disabled( selectedAttribute == nil || selectedComparison == nil || selectedValue == nil ) } ToolbarItem(placement: .cancellationAction) { Button("Cancel") { isConditionMenuPresented = false selectedAttribute = nil selectedComparison = nil selectedValue = nil inputValue = nil } } } }
@ViewBuilder private var attributesView: some View { List(model.possibleAttributes, id: \.name) { attribute in HStack { Text(attribute.name) Spacer() if attribute === selectedAttribute { Image(systemName: "checkmark") .foregroundStyle(Color.accentColor) } } .contentShape(Rectangle()) .onTapGesture { selectedAttribute = attribute } } .navigationTitle("Attributes") }
@ViewBuilder private var operatorsView: some View { Section { List(UtilityNetworkAttributeComparison.Operator.allCases, id: \.self) { comparison in HStack { Text(comparison.title) Spacer() if comparison == selectedComparison { Image(systemName: "checkmark") .foregroundStyle(Color.accentColor) } } .contentShape(Rectangle()) .onTapGesture { selectedComparison = comparison } } } .navigationTitle("Operators") }
@ViewBuilder private var valuesView: some View { if let domain = selectedAttribute?.domain as? CodedValueDomain { Section { List(domain.codedValues, id: \.name) { value in HStack { Text(value.name) Spacer() if value === selectedValue as? CodedValue { Image(systemName: "checkmark") .foregroundStyle(Color.accentColor) } } .contentShape(Rectangle()) .onTapGesture { selectedValue = value } } } .navigationTitle("Values") } }}
private extension UtilityNetworkAttributeComparison.Operator { static var allCases: [UtilityNetworkAttributeComparison.Operator] { [.equal, .notEqual, .greaterThan, .greaterThanEqual, .lessThan, .lessThanEqual, .includesTheValues, .doesNotIncludeTheValues, .includesAny, .doesNotIncludeAny] }}
#Preview { NavigationStack { AnalyzeNetworkWithSubnetworkTraceView() }}// Copyright 2023 Esri//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// https://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.
import ArcGISimport Combineimport Foundation
extension AnalyzeNetworkWithSubnetworkTraceView { /// The view model for this sample. @MainActor class Model: ObservableObject { /// An electric utility network in Naperville, Illinois. private let utilityNetwork = UtilityNetwork(serviceGeodatabase: .naperville())
/// An array of condition expressions. private var traceConditionalExpressions: [UtilityTraceConditionalExpression] = []
/// An array of string representations of condition expressions. @Published private(set) var conditions: [String] = []
/// The utility element to start the trace from. private var startingLocation: UtilityElement?
/// The initial conditional expression. private var initialExpression: UtilityTraceConditionalExpression?
/// The trace configuration. private var configuration: UtilityTraceConfiguration?
/// A chained expression string. var expressionString: String { if let expression = chainExpressions(traceConditionalExpressions) { return string(for: expression) } else { return "Expressions failed to convert to string." } }
/// An array of possible network attributes. @Published private(set) var possibleAttributes: [UtilityNetworkAttribute] = []
/// A Boolean value indicating if running the trace is enabled. @Published private(set) var traceEnabled = false
/// The status text to display to the user. @Published private(set) var statusText: String = "Loading utility network"
/// The number of trace results from a trace. @Published private(set) var traceResultsCount = 0
/// A Boolean value indicating if the sample has been setup. @Published private(set) var isSetUp = false
// MARK: Methods
/// Performs important tasks including adding credentials, loading utility network and setting trace parameters. func setup() async throws { do { try await ArcGISEnvironment.authenticationManager.arcGISCredentialStore.add(.publicSample) try await setupTraceParameters() } catch { throw error } }
/// Cleans up the model's setup. func tearDown() { ArcGISEnvironment.authenticationManager.arcGISCredentialStore.removeAll() }
/// Loads the utility network and sets the trace parameters and other information /// used for running this sample. private func setupTraceParameters() async throws { defer { statusText = "" }
// Constants for creating the default trace configuration. let domainNetworkName = "ElectricDistribution" let tierName = "Medium Voltage Radial"
// Load the utility network. try await utilityNetwork.load()
// Create a default starting location. let startingLocation = try makeStartingLocation() self.startingLocation = startingLocation
guard let domainNetwork = utilityNetwork.definition?.domainNetwork(named: domainNetworkName), let utilityTierConfiguration = domainNetwork.tier(named: tierName)?.defaultTraceConfiguration else { throw SetupError() }
// Set the traversability. if utilityTierConfiguration.traversability == nil { utilityTierConfiguration.traversability = UtilityTraversability() }
// Set the default expression (if provided). guard let expression = utilityTierConfiguration.traversability?.barriers as? UtilityTraceConditionalExpression else { throw SetupError() } self.initialExpression = expression
if !traceConditionalExpressions.contains(where: { $0 === expression }) { traceConditionalExpressions.append(expression) conditions.append(string(for: expression)) }
// Set the traversability scope. utilityTierConfiguration.traversability?.scope = .junctions if let attributes = utilityNetwork.definition?.networkAttributes.filter({ !$0.systemIsDefined }) { possibleAttributes = attributes }
self.configuration = utilityTierConfiguration traceEnabled = true isSetUp = true }
/// When the utility network is loaded, creates a `UtilityElement` /// from the asset type to use as the starting location for the trace. private func makeStartingLocation() throws -> UtilityElement { // Constants for creating the default starting location. let deviceTableName = "Electric Distribution Device" let assetGroupName = "Circuit Breaker" let assetTypeName = "Three Phase" let globalID = UUID(uuidString: "1CAF7740-0BF4-4113-8DB2-654E18800028")!
// Create a default starting location. guard let networkSource = self.utilityNetwork.definition?.networkSource(named: deviceTableName), let assetType = networkSource.assetGroup(named: assetGroupName)?.assetType(named: assetTypeName), let startingLocation = utilityNetwork.makeElement(assetType: assetType, globalID: globalID) else { throw SetupError() } // Set the terminal for this location. (For our case, use the "Load" terminal.) startingLocation.terminal = startingLocation.assetType.terminalConfiguration?.terminals.first(where: { $0.name == "Load" }) return startingLocation }
/// Runs a trace with the pending trace configuration. /// - Parameters: /// - includeBarriers: A Boolean value indicating whether to include barriers in the trace results. /// - includeContainers: A Boolean value indicating whether to include containment features in the trace results. /// - Precondition: `startingLocation` and `configuration`are not `nil`. func trace(includeBarriers: Bool, includeContainers: Bool) async throws { defer { statusText = "" } defer { traceEnabled = true } traceEnabled = false statusText = "Tracing" guard let location = startingLocation else { preconditionFailure() }
// Create utility trace parameters for the starting location. let parameters = UtilityTraceParameters(traceType: .subnetwork, startingLocations: [location])
guard let configuration = configuration else { preconditionFailure() } configuration.includesBarriers = includeBarriers configuration.includesContainers = includeContainers configuration.traversability?.barriers = chainExpressions(traceConditionalExpressions) parameters.traceConfiguration = configuration
do { // Trace the utility network. let traceResults = try await utilityNetwork .trace(using: parameters) let elementResult = traceResults.first( where: { $0 is UtilityElementTraceResult } ) as! UtilityElementTraceResult? // Display the number of elements found by the trace. traceResultsCount = elementResult?.elements.count ?? .zero } catch { throw error } }
/// Resets the trace barrier conditions. func reset() { // Reset the barrier condition to the initial value. configuration?.traversability?.barriers = initialExpression if let initialExpression = initialExpression { // Add back the initial expression. traceConditionalExpressions = [initialExpression] conditions = [string(for: initialExpression)] } else { traceConditionalExpressions.removeAll() conditions.removeAll() } statusText = "" }
/// Chains the conditional expressions together with AND or OR operators. /// - Parameter expressions: An array of `UtilityTraceConditionalExpression`s. /// - Returns: The chained conditional expression. func chainExpressions( _ expressions: [UtilityTraceConditionalExpression] ) -> UtilityTraceConditionalExpression? { guard let firstExpression = expressions.first else { return nil } /// The operator to chain conditions together, i.e. `AND` or `OR`. /// - Note: You may also combine expressions with /// `UtilityTraceAndCondition`. i.e. `UtilityTraceAndCondition.init` let chainingOperator = UtilityTraceOrCondition.init return expressions.dropFirst().reduce(firstExpression) { leftCondition, rightCondition in chainingOperator(leftCondition, rightCondition) } }
/// Converts a `UtilityTraceConditionalExpression` into a readable string. /// - Parameter expression: A `UtilityTraceConditionalExpression`. /// - Returns: A string describing the expression. private func string(for expression: UtilityTraceConditionalExpression) -> String { switch expression { case let categoryComparison as UtilityCategoryComparison: return "`\(categoryComparison.category.name)` \(categoryComparison.operator.title)" case let attributeComparison as UtilityNetworkAttributeComparison: let attributeName = attributeComparison.networkAttribute.name let comparisonOperator = attributeComparison.operator.title
if let otherName = attributeComparison.otherNetworkAttribute?.name { // Comparing with another network attribute. return "`\(attributeName)` \(comparisonOperator) `\(otherName)`" } else if let value = attributeComparison.value { // Comparing with a value domain value or user input. let dataType = attributeComparison.networkAttribute.dataType
if let domain = attributeComparison.networkAttribute.domain as? CodedValueDomain, let codedValue = domain.codedValues.first( where: { compareAttributeData(dataType: dataType, value1: $0.code!, value2: value) } ) { // Check if attribute domain is a coded value domain. return "'\(attributeName)' \(comparisonOperator) '\(codedValue.name)'" } else if let formattedValue = value as? Double { // Comparing with user input of type `Double`. return "`\(attributeName)` \(comparisonOperator) `\(formattedValue.formatted())`" } else { // Comparing with user input. return "`\(attributeName)` \(comparisonOperator) `\(value)`" } } else { fatalError("Unknown attribute comparison expression") } case let andCondition as UtilityTraceAndCondition: return """ (\(string(for: andCondition.leftExpression))) AND (\(string(for: andCondition.rightExpression))) """ case let orCondition as UtilityTraceOrCondition: return """ (\(string(for: orCondition.leftExpression))) OR (\(string(for: orCondition.rightExpression))) """ default: fatalError("Unknown trace condition expression type") } }
/// Compares two attribute values. /// - Parameters: /// - dataType: A `UtilityNetworkAttributeDataType` enum that tells the type of 2 values. /// - value1: The lhs value to compare. /// - value2: The rhs value to compare. /// - Returns: A boolean indicating if the values are equal both in type and in value. func compareAttributeData(dataType: UtilityNetworkAttribute.DataType, value1: Any, value2: Any) -> Bool { switch dataType { case .boolean: return value1 as? Bool == value2 as? Bool case .double: return value1 as? Double == value2 as? Double case .float: return value1 as? Float == value2 as? Float case .integer: if let value1 = value1 as? Int16, let value2 = value2 as? Int { return value1 == value2 } else if let value1 = value1 as? Int16, let value2 = value2 as? Int16 { return value1 == value2 } else { return false } @unknown default: fatalError("Unexpected utility network attribute data type.") } }
/// Adds a conditional expression. func addConditionalExpression( attribute: UtilityNetworkAttribute, comparison: UtilityNetworkAttributeComparison.Operator, value: any Sendable ) throws { let convertedValue: any Sendable
if let codedValue = value as? CodedValue, attribute.domain is CodedValueDomain { convertedValue = convertToDataType(value: codedValue.code!, dataType: attribute.dataType) } else { convertedValue = convertToDataType(value: value, dataType: attribute.dataType) }
if let expression = UtilityNetworkAttributeComparison( networkAttribute: attribute, operator: comparison, value: convertedValue ) { traceConditionalExpressions.append(expression) conditions.append(string(for: expression)) } else { throw InitExpressionError() } }
/// Deletes a conditional expression. func deleteConditionalExpression(atOffsets indexSet: IndexSet) { guard let index = indexSet.first else { return } let condition = conditions[index] conditions = conditions.filter { $0 != condition } traceConditionalExpressions.remove(atOffsets: indexSet) }
/// Converts the values to matching data types. /// - Note: The input value can either be an `CodedValue` populated from the left hand side /// attribute's domain, or a numeric value entered by the user. /// - Parameters: /// - value: The right hand side value used in the conditional expression. /// - dataType: An `UtilityNetworkAttribute.DataType` enum case. /// - Returns: Converted value. func convertToDataType(value: any Sendable, dataType: UtilityNetworkAttribute.DataType) -> any Sendable { switch dataType { case .integer: if let value = value as? Int16 { return value } else if let value = value as? Int64 { return value } else if let value = value as? Double { return Int64(value) } else { return value as! Int64 } case .float: return value as! Float case .double: return value as! Double case .boolean: return value as! Bool @unknown default: fatalError("Unexpected utility network attribute data type.") } } }}
private extension ArcGISCredential { /// The public credentials for the data in this sample. /// - Note: Never hardcode login information in a production application. This is done solely /// for the sake of the sample. static var publicSample: ArcGISCredential { get async throws { try await TokenCredential.credential( for: .featureServiceURL, username: "viewer01", password: "I68VGU^nMurF" ) } }}
private extension AnalyzeNetworkWithSubnetworkTraceView.Model { /// An error returned when data required to setup the sample cannot be found. struct SetupError: LocalizedError { var errorDescription: String? { .init( localized: "Cannot find data required to setup the sample.", comment: "Description of error thrown when the setup for the sample fails." ) } }
/// An error returned when the conditional expression cannot be initialized. struct InitExpressionError: LocalizedError { var errorDescription: String? { .init( localized: "Could not initialize conditional expression.", comment: "Description of error thrown when the conditional expression cannot be initialized." ) } }}
private extension URL { /// The URL to the feature service for running the isolation trace. static var featureServiceURL: URL { URL(string: "https://sampleserver7.arcgisonline.com/server/rest/services/UtilityNetwork/NapervilleElectric/FeatureServer")! }}
private extension ServiceGeodatabase { /// The Naperville, Illinois electric utility network service geodatabase. static func naperville() -> ServiceGeodatabase { .init(url: .featureServiceURL) }}
private extension UtilityCategoryComparison.Operator { /// An extension of `UtilityCategoryComparison.Operator` that returns a human readable description. /// - Note: You may also create a `UtilityCategoryComparison` with /// `UtilityNetworkDefinition.categories` and `UtilityCategoryComparison.Operator`. var title: String { switch self { case .exists: return "Exists" case .doesNotExist: return "DoesNotExist" @unknown default: return "Unknown" } }}
extension UtilityNetworkAttributeComparison.Operator { /// A human-readable label for each utility attribute comparison operator. var title: String { switch self { case .equal: return "Equal" case .notEqual: return "Not Equal" case .greaterThan: return "Greater Than" case .greaterThanEqual: return "Greater Than Equal" case .lessThan: return "Less Than" case .lessThanEqual: return "Less Than Equal" case .includesTheValues: return "Includes The Values" case .doesNotIncludeTheValues: return "Does Not Include The Values" case .includesAny: return "Includes Any" case .doesNotIncludeAny: return "Does Not Include Any" @unknown default: return "Unknown" } }}