Create load report

View on GitHub
Sample viewer app

Create a simple electric distribution report that displays the count of customers and total load per phase by tracing downstream from a given point.

Image of create load report

Use case

You can use a load report to display the customers per phase as well as the load per phase based on a chosen starting point in a utility network. Load reports are used for electric load restoration and balancing.

How to use the sample

Choose phases to be included in the report. Tap "Run" to initiate a downstream trace on the network and create a load report. Tap "Reset" to clear the phase summaries in the report and start over.

How it works

  1. Create and load an AGSUtilityNetwork with a feature service URL, then get an asset type, tier, network attributes, and category by their names.
  2. Create an AGSUtilityElement from the asset type to use as the starting location for the trace.
  3. Get a base condition by calling the utility tier's makeDefaultTraceConfiguration method.
  4. Create AGSUtilityTraceParameters passing in downstream trace type and the default starting location. Set its traceConfiguration property with the trace configuration above, and set includeBarriers to false.
  5. Create an AGSUtilityCategoryComparison where "ServicePoint" category exists.
  6. Reset the functions property of the trace configuration with a new AGSUtilityTraceFunction adding a "Service Load" network attribute where this category comparison applies. This will limit the function results.
  7. Set outputCondition with this category comparison to limit the element results.
  8. Populate the choice list for phases using the network attribute's codedValues property.
  9. When the "Add" button is tapped, add the selected phase to a phases list.
  10. When the "Run" button is tapped, run a trace for every AGSCodedValue in the phases list. Do this by creating an AGSUtilityTraceOrCondition with the base condition and an AGSUtilityNetworkAttributeComparison where the "Phases Current" network attribute does not include the coded value.
  11. Display the count of "Total Customers" using the elements property of the result, and the result of "Total Load" using the first and only output in functionOutputs property.

Relevant API

  • AGSUtilityAssetType
  • AGSUtilityCategoryComparison
  • AGSUtilityDomainNetwork
  • AGSUtilityElement
  • AGSUtilityElementTraceResult
  • AGSUtilityNetwork
  • AGSUtilityNetworkAttribute
  • AGSUtilityNetworkAttributeComparison
  • AGSUtilityNetworkDefinition
  • AGSUtilityNetworkSource
  • AGSUtilityTerminal
  • AGSUtilityTier
  • AGSUtilityTraceConfiguration
  • AGSUtilityTraceFunction
  • AGSUtilityTraceParameters
  • AGSUtilityTraceResult
  • AGSUtilityTraceType
  • AGSUtilityTraversability

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

condition barriers, downstream trace, network analysis, subnetwork trace, trace configuration, traversability, upstream trace, utility network, validate consistency

Sample Code

CreateLoadReportViewController.swift
                                                                                                                                                                                                                                                                                                                                                                        
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
// Copyright 2021 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
//
//   http://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 UIKit
import ArcGIS

class CreateLoadReportViewController: UIViewController {
    // MARK: Storyboard views

    /// The table view to display the load reports.
    @IBOutlet var tableView: UITableView!
    /// The button to reset the phase summaries.
    @IBOutlet var resetBarButtonItem: UIBarButtonItem!
    /// The button to run the trace and create a load report.
    @IBOutlet var runBarButtonItem: UIBarButtonItem!

    // MARK: Properties

    /// A feature service of an electric utility network in Naperville, Illinois.
    let utilityNetwork = AGSUtilityNetwork(url: URL(string: "https://sampleserver7.arcgisonline.com/server/rest/services/UtilityNetwork/NapervilleElectric/FeatureServer")!)
    /// The initial conditional expression.
    var initialExpression: AGSUtilityTraceConditionalExpression!
    /// The trace parameters for creating load reports.
    var traceParameters: AGSUtilityTraceParameters!
    /// The network attributes for the comparison.
    var phasesNetworkAttribute: AGSUtilityNetworkAttribute!

    /// A list of possible phases populated from the network's attributes.
    /// By default, they are not included in the load report.
    var excludedPhases = [AGSCodedValue]()
    /// A list of phases that are included in the load report.
    var includedPhases = [AGSCodedValue]()
    /// The phase summaries in the load report.
    var summaries = [AGSCodedValue: PhaseSummary]()

    /// The number formatter for phase summaries.
    let numberFormatter: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.usesGroupingSeparator = true
        return formatter
    }()

    /// A struct for the phase summary, which contains the total customers
    /// and total load for the phase.
    struct PhaseSummary {
        let totalCustomers: Int
        let totalLoad: Int
    }

    // MARK: Methods

    /// Load the utility network.
    func loadUtilityNetwork() {
        UIApplication.shared.showProgressHUD(message: "Loading utility network…")
        // NOTE: Never hardcode login information in a production application.
        // This is done solely for the sake of the sample.
        utilityNetwork.credential = AGSCredential(user: "viewer01", password: "I68VGU^nMurF")
        utilityNetwork.load { [weak self] error in
            UIApplication.shared.hideProgressHUD()
            guard let self = self else { return }
            guard error == nil else {
                self.presentAlert(error: error!)
                return
            }
            // Create a default starting location.
            guard let startingLocation = self.makeStartingLocation() else {
                self.presentAlert(message: "Fail to create starting location.")
                return
            }
            // Get the base condition and trace configuration from a default tier.
            guard let utilityTierConfiguration = self.getTraceConfiguration() else {
                self.presentAlert(message: "Fail to get trace configuration.")
                return
            }
            // Proceed if the utility network loaded without issue.
            self.utilityNetworkDidLoad(startingLocation: startingLocation, traceConfiguration: utilityTierConfiguration)
        }
    }

    /// Called in response to the utility network load operation completing.
    /// - Parameters:
    ///   - startingLocation: The utility element to start the trace from.
    ///   - traceConfiguration: The utility tier's trace configuration.
    func utilityNetworkDidLoad(startingLocation: AGSUtilityElement, traceConfiguration: AGSUtilityTraceConfiguration) {
        // Set the default expression.
        initialExpression = traceConfiguration.traversability?.barriers as? AGSUtilityTraceConditionalExpression

        // Create downstream trace parameters with elements and function outputs.
        let traceParameters = AGSUtilityTraceParameters(traceType: .downstream, startingLocations: [startingLocation])
        traceParameters.resultTypes = [.ags_value(with: .elements), .ags_value(with: .functionOutputs)]

        // The service category for counting total customers.
        if let serviceCategory = utilityNetwork.definition.categories.first(where: { $0.name == "ServicePoint" }),
           // The load attribute for counting total load.
           let loadAttribute = utilityNetwork.definition.networkAttributes.first(where: { $0.name == "Service Load" }),
           // The phase attribute for getting total phase current load.
           let phasesNetworkAttribute = utilityNetwork.definition.networkAttributes.first(where: { $0.name == "Phases Current" }) {
            self.phasesNetworkAttribute = phasesNetworkAttribute
            // Get possible coded phase values from the attributes.
            if let domain = phasesNetworkAttribute.domain as? AGSCodedValueDomain {
                excludedPhases = domain.codedValues.sorted { $0.name < $1.name }
                DispatchQueue.main.async { [weak self] in
                    guard let self = self else { return }
                    self.tableView.reloadSection(.excluded)
                    self.tableView.isEditing = true
                }
            }
            // Create a comparison to check the existence of service points.
            let serviceCategoryComparison = AGSUtilityCategoryComparison(category: serviceCategory, comparisonOperator: .exists)
            let addLoadAttributeFunction = AGSUtilityTraceFunction(functionType: .add, networkAttribute: loadAttribute, condition: serviceCategoryComparison)
            // Create function input and output condition.
            traceConfiguration.functions = [addLoadAttributeFunction]
            traceConfiguration.outputCondition = serviceCategoryComparison
            // Set to false to ensure that service points with incorrect phasing
            // (which therefore act as barriers) are not counted with results.
            traceConfiguration.includeBarriers = false
            // Assign the trace configuration to trace parameters.
            traceParameters.traceConfiguration = traceConfiguration
            self.traceParameters = traceParameters
        }
    }

    /// When the utility network is loaded, create an `AGSUtilityElement`
    /// from the asset type to use as the starting location for the trace.
    func makeStartingLocation() -> AGSUtilityElement? {
        // Constants for creating the default starting location.
        let deviceTableName = "Electric Distribution Device"
        let assetGroupName = "Circuit Breaker"
        let assetTypeName = "Three Phase"
        let terminalName = "Load"
        let globalID = UUID(uuidString: "1CAF7740-0BF4-4113-8DB2-654E18800028")!

        // Create a default starting location.
        if let networkSource = utilityNetwork.definition.networkSource(withName: deviceTableName),
           let assetType = networkSource.assetGroup(withName: assetGroupName)?.assetType(withName: assetTypeName),
           let startingLocation = utilityNetwork.createElement(with: assetType, globalID: globalID) {
            // Set the terminal for the location. (For our case, use the "Load" terminal.)
            startingLocation.terminal = assetType.terminalConfiguration?.terminals.first(where: { $0.name == terminalName })
            return startingLocation
        } else {
            return nil
        }
    }

    /// Get the utility tier's trace configuration.
    func getTraceConfiguration() -> AGSUtilityTraceConfiguration? {
        // Get a default trace configuration from a tier in the network.
        utilityNetwork
            .definition
            .domainNetwork(withDomainNetworkName: "ElectricDistribution")?
            .tier(withName: "Medium Voltage Radial")?
            .makeDefaultTraceConfiguration()
    }

    // MARK: Actions

    @IBAction func resetBarButtonItemTapped(_ sender: UIBarButtonItem) {
        summaries.removeAll()
        tableView.reloadSection(.included)
        resetBarButtonItem.isEnabled = false
    }

    @IBAction func runBarButtonItemTapped(_ sender: UIBarButtonItem) {
        UIApplication.shared.showProgressHUD(message: "Creating load report…")

        let traceGroup = DispatchGroup()
        var summaries = [AGSCodedValue: PhaseSummary]()
        for phase in includedPhases {
            guard let phaseCode = phase.code else { continue }
            // Create a conditional expression.
            let phasesAttributeComparison = AGSUtilityNetworkAttributeComparison(networkAttribute: phasesNetworkAttribute, comparisonOperator: .doesNotIncludeAny, value: phaseCode)!
            // Chain it with the base condition using an OR operator.
            traceParameters.traceConfiguration?.traversability?.barriers = AGSUtilityTraceOrCondition(leftExpression: initialExpression, rightExpression: phasesAttributeComparison)

            traceGroup.enter()
            utilityNetwork.trace(with: traceParameters) { results, _ in
                defer { traceGroup.leave() }
                // If the trace gives not result, return and ignore any error.
                guard let results = results else { return }
                var totalCustomers = 0
                var totalLoad = 0
                results.forEach { result in
                    switch result {
                    case let elementResult as AGSUtilityElementTraceResult:
                        // Get the unique customers count.
                        totalCustomers = Set(elementResult.elements.map(\.objectID)).count
                    case let functionResult as AGSUtilityFunctionTraceResult:
                        // Get the total load with a function output.
                        totalLoad = functionResult.functionOutputs.first?.result as? Int ?? 0
                    default:
                        break
                    }
                }
                summaries[phase] = PhaseSummary(totalCustomers: totalCustomers, totalLoad: totalLoad)
            }
        }
        // Reload the load report table when trace completes.
        traceGroup.notify(queue: .main) { [weak self] in
            UIApplication.shared.hideProgressHUD()
            guard let self = self else { return }
            self.summaries = summaries
            self.tableView.reloadSection(.included)
            self.resetBarButtonItem.isEnabled = true
        }
    }

    // MARK: UIViewController

    override func viewDidLoad() {
        super.viewDidLoad()
        // Add the source code button item to the right of navigation bar.
        (navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = ["CreateLoadReportViewController"]
        // Load the utility network and initialize properties.
        loadUtilityNetwork()
    }
}

// MARK: - UITableViewDelegate

extension CreateLoadReportViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        Section.allCases[section].titleForHeader
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        Section.allCases.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch Section.allCases[section] {
        case .included:
            return includedPhases.count
        case .excluded:
            return excludedPhases.count
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: Section.allCases[indexPath.section].cellIdentifier, for: indexPath)
        switch Section.allCases[indexPath.section] {
        case .included:
            let phase = includedPhases[indexPath.row]
            cell.textLabel?.text = String(format: "Phase: %@", phase.name)
            if let summary = summaries[phase] {
                let formattedString = String(format: "C: %@  L: %@", numberFormatter.string(from: summary.totalCustomers as NSNumber)!, numberFormatter.string(from: summary.totalLoad as NSNumber)!)
                cell.detailTextLabel?.text = formattedString
            } else {
                cell.detailTextLabel?.text = "N/A"
            }
        case .excluded:
            cell.textLabel?.text = excludedPhases[indexPath.row].name
        }
        return cell
    }

    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        switch Section.allCases[indexPath.section] {
        case .included:
            return .delete
        case .excluded:
            return .insert
        }
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        /// Binary search to find the insertion index in a sorted array.
        func index(forInserting phase: AGSCodedValue, into array: [AGSCodedValue]) -> Int {
            (array as NSArray).index(
                of: phase,
                inSortedRange: NSRange(array.indices),
                options: [.insertionIndex],
                usingComparator: { ($0 as! AGSCodedValue).name.compare(($1 as! AGSCodedValue).name) }
            )
        }

        switch editingStyle {
        case .delete:
            let phase = includedPhases[indexPath.row]
            includedPhases.remove(at: indexPath.row)
            let insertionIndex = index(forInserting: phase, into: excludedPhases)
            excludedPhases.insert(phase, at: insertionIndex)
            // Remove the summary.
            summaries.removeValue(forKey: phase)
            // Update the table.
            tableView.performBatchUpdates {
                tableView.deleteRows(at: [indexPath], with: .automatic)
                tableView.insertRows(at: [IndexPath(row: insertionIndex, section: .excluded)], with: .automatic)
            }
        case .insert:
            let phase = excludedPhases[indexPath.row]
            excludedPhases.remove(at: indexPath.row)
            let insertionIndex = index(forInserting: phase, into: includedPhases)
            includedPhases.insert(phase, at: insertionIndex)
            tableView.performBatchUpdates {
                tableView.deleteRows(at: [indexPath], with: .automatic)
                tableView.insertRows(at: [IndexPath(row: insertionIndex, section: .included)], with: .automatic)
            }
        default:
            return
        }
        // Toggle button state.
        runBarButtonItem.isEnabled = !includedPhases.isEmpty
        resetBarButtonItem.isEnabled = !summaries.isEmpty
    }

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        true
    }
}

// MARK: Section Enum

extension CreateLoadReportViewController {
    /// A convenience type for the table view sections.
    enum Section: Int, CaseIterable {
        case included, excluded

        var titleForHeader: String {
            switch self {
            case .included:
                return "Phases, Total Customers(C), Total Load(L)"
            case .excluded:
                return "More Phases"
            }
        }

        var cellIdentifier: String {
            switch self {
            case .included:
                return "RightDetail"
            case .excluded:
                return "Basic"
            }
        }
    }
}

private extension UITableView {
    func reloadSection(_ section: CreateLoadReportViewController.Section) {
        reloadSections([section.rawValue], with: .automatic)
    }
}

private extension IndexPath {
    init(row: Int, section: CreateLoadReportViewController.Section) {
        self.init(row: row, section: section.rawValue)
    }
}

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