Analyze network with subnetwork trace

View on GitHub

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.

Image of Analyze network with subnetwork trace sample

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

  1. Create and load a UtilityNetwork with a feature service URL, then get an asset type and a tier by their names.
  2. 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 from UtilityAttributeComparisonOperator.
  3. Create a UtilityElement from this asset type to use as the starting location for the trace.
  4. Update the selected barrier expression and the checked options in the UI using this tier's TraceConfiguration.
  5. When an attribute has been selected, if its Domain is a CodedValueDomain, populate the choice list for the comparison value with its CodedValues. Otherwise, display a TextField for entering an attribute value.
  6. When "Add" is tapped, create a new UtilityNetworkAttributeComparison using the selected comparison source, operator, and selected or typed value. Use the selected source's dataType to convert the comparison value to the correct data type.
  7. If the traversability's list of barriers is not empty, create an UtilityTraceOrCondition with the existing barriers and the new comparison from step 6.
  8. When "Trace" is tapped, create UtilityTraceParameters passing in subnetwork and the default starting location. Set its traceConfiguration with the modified options, selections, and expression; then trace the utility network with UtilityNetwork.trace(using:).
  9. When "Reset" is tapped, set the trace configurations expression back to its original value.
  10. 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

AnalyzeNetworkWithSubnetworkTraceView.swiftAnalyzeNetworkWithSubnetworkTraceView.swiftAnalyzeNetworkWithSubnetworkTraceView.Model.swift
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
// 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 ArcGIS
import 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: 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 }
            }
        }
    }

    @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) { value in
                    selectedValue = value
                }
                .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()
    }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.