Configure subnetwork trace

View on GitHub
Sample viewer app

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 configure subnetwork trace

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. Check or uncheck which options to include in the trace - such as containers or barriers. Use the selection boxes to define a new condition network attribute comparison, and then use 'Add' to add the it to the trace configuration. Click '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 UtilityTraceConfiguration.
  5. When 'Network Attribute' is selected, if its Domain is a CodedValueDomain, populate the choice list for the comparison value with its CodedValues. Otherwise, display a free-form textbox for entering an attribute value.
  6. When 'Add' is clicked, create a new UtilityNetworkAttributeComparison using the selected comparison source, operator, and selected or typed value. Use the selected source's UtilityNetworkAttribute.DataType to convert the comparison value to the correct data type.
  7. If the Traversability's list of Barriers is not empty, create a UtilityTraceOrCondition with the existing Barriers and the new comparison from Step 6.
  8. When 'Trace' is clicked, create UtilityTraceParameters passing in UtilityTraceType.SUBNETWORK and the default starting location. Set its UtilityTraceConfiguration with the modified options, selections, and expression; then run a UtilityNetwork.traceAsync(...).
  9. When Reset is clicked, set the trace configurations expression back to its original value.
  10. Display the count of returned UtilityElementTraceResult.elements.

Relevant API

  • CodedValueDomain
  • UtilityAssetType
  • UtilityAttributeComparisonOperator
  • UtilityCategory
  • UtilityCategoryComparison
  • UtilityCategoryComparisonOperator
  • UtilityDomainNetwork
  • UtilityElement
  • UtilityElementTraceResult
  • UtilityNetwork
  • UtilityNetworkAttribute
  • UtilityNetworkAttributeComparison
  • 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

MainActivity.kt
Use dark colors for code blocks
                                                                                                                                                                                                                                                                                                                                                                                                                                      
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package com.esri.arcgisruntime.sample.configuresubnetworktrace

import android.os.Bundle
import android.text.InputType
import android.text.method.ScrollingMovementMethod
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.RelativeLayout
import android.widget.Spinner
import android.widget.TextView
import android.widget.Toast
import android.widget.ToggleButton
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.data.CodedValue
import com.esri.arcgisruntime.data.CodedValueDomain
import com.esri.arcgisruntime.loadable.LoadStatus
import com.esri.arcgisruntime.security.UserCredential
import com.esri.arcgisruntime.sample.configuresubnetworktrace.databinding.ActivityMainBinding
import com.esri.arcgisruntime.utilitynetworks.UtilityAttributeComparisonOperator
import com.esri.arcgisruntime.utilitynetworks.UtilityCategoryComparison
import com.esri.arcgisruntime.utilitynetworks.UtilityElement
import com.esri.arcgisruntime.utilitynetworks.UtilityElementTraceResult
import com.esri.arcgisruntime.utilitynetworks.UtilityNetwork
import com.esri.arcgisruntime.utilitynetworks.UtilityNetworkAttribute
import com.esri.arcgisruntime.utilitynetworks.UtilityNetworkAttributeComparison
import com.esri.arcgisruntime.utilitynetworks.UtilityTier
import com.esri.arcgisruntime.utilitynetworks.UtilityTraceAndCondition
import com.esri.arcgisruntime.utilitynetworks.UtilityTraceConditionalExpression
import com.esri.arcgisruntime.utilitynetworks.UtilityTraceConfiguration
import com.esri.arcgisruntime.utilitynetworks.UtilityTraceOrCondition
import com.esri.arcgisruntime.utilitynetworks.UtilityTraceParameters
import com.esri.arcgisruntime.utilitynetworks.UtilityTraceType
import com.esri.arcgisruntime.utilitynetworks.UtilityTraversability
import com.esri.arcgisruntime.utilitynetworks.UtilityTraversabilityScope

class MainActivity : AppCompatActivity() {

  private val TAG: String = MainActivity::class.java.simpleName

  private val activityMainBinding by lazy {
    ActivityMainBinding.inflate(layoutInflater)
  }

  private val exampleTextView: TextView by lazy {
    activityMainBinding.exampleTextView
  }

  private val sourceSpinner: Spinner by lazy {
    activityMainBinding.sourceSpinner
  }

  private val operatorSpinner: Spinner by lazy {
    activityMainBinding.operatorSpinner
  }

  private val expressionTextView: TextView by lazy {
    activityMainBinding.expressionTextView
  }

  private val valuesSpinner: Spinner by lazy {
    activityMainBinding.valuesSpinner
  }

  private val valuesBackgroundView: RelativeLayout by lazy {
    activityMainBinding.valuesBackgroundView
  }

  private val valueBooleanButton: ToggleButton by lazy {
    activityMainBinding.valueBooleanButton
  }

  private val valuesEditText: EditText by lazy {
    activityMainBinding.valuesEditText
  }

  private val utilityNetwork by lazy {
    UtilityNetwork("https://sampleserver7.arcgisonline.com/server/rest/services/UtilityNetwork/NapervilleElectric/FeatureServer").apply {
      // set user credentials to authenticate with the service
      // NOTE: a licensed user is required to perform utility network operations
      credential =  UserCredential("viewer01", "I68VGU^nMurF")
    }
  }

  private var initialExpression: UtilityTraceConditionalExpression? = null
  private var sourceTier: UtilityTier? = null
  private var sources: List<UtilityNetworkAttribute>? = null
  private var operators: Array<UtilityAttributeComparisonOperator>? = null
  private var startingLocation: UtilityElement? = null
  private var values: List<CodedValue>? = null

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(activityMainBinding.root)

    exampleTextView.movementMethod = ScrollingMovementMethod()

    // create a utility network and wait for it to finish to load
    utilityNetwork.loadAsync()
    utilityNetwork.addDoneLoadingListener {
      if (utilityNetwork.loadStatus == LoadStatus.LOADED) {
        // create a list of utility network attributes whose system is not defined
        sources = utilityNetwork.definition.networkAttributes.filter { !it.isSystemDefined }
          .also { sources ->

            sourceSpinner.apply {
              // assign an adapter to the spinner with source names
              adapter = ArrayAdapter<String>(
                applicationContext,
                android.R.layout.simple_list_item_1,
                sources.map { it.name })

              // add an on item selected listener which calls on comparison source changed
              onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                  parent: AdapterView<*>?,
                  view: View?,
                  position: Int,
                  id: Long
                ) {
                  (sources[sourceSpinner.selectedItemPosition])
                  onComparisonSourceChanged(sources[sourceSpinner.selectedItemPosition])
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {}
              }
            }
          }

        // create a list of utility attribute comparison operators
        operators = UtilityAttributeComparisonOperator.values().also { operators ->
          // assign operator spinner an adapter of operator names
          operatorSpinner.adapter = ArrayAdapter<String>(
            applicationContext,
            android.R.layout.simple_list_item_1,
            operators.map { it.name })
        }

        // create a default starting location
        val networkSource =
          utilityNetwork.definition.getNetworkSource("Electric Distribution Device")
        val assetGroup = networkSource.getAssetGroup("Circuit Breaker")
        val assetType = assetGroup.getAssetType("Three Phase")
        val globalId = java.util.UUID.fromString("1CAF7740-0BF4-4113-8DB2-654E18800028")

        // utility element to start the trace from
        startingLocation = utilityNetwork.createElement(assetType, globalId).apply {
          terminal = assetType.terminalConfiguration.terminals.first { it.name == "Load" }
        }

        // get a default trace configuration from a tier to update the UI
        val domainNetwork = utilityNetwork.definition.getDomainNetwork("ElectricDistribution")
        sourceTier = domainNetwork.getTier("Medium Voltage Radial")?.apply {
          (traceConfiguration.traversability.barriers as? UtilityTraceConditionalExpression)?.let {
            expressionTextView.text = expressionToString(it)
            initialExpression = it
          }
          // set the traversability scope
          traceConfiguration.traversability.scope = UtilityTraversabilityScope.JUNCTIONS
        }
      } else {
        ("Utility network failed to load!").also {
          Toast.makeText(this, it, Toast.LENGTH_LONG).show()
          Log.e(TAG, it)
        }
      }
    }
  }

  /**
   * When a comparison source attribute is chosen check if it's a coded value domain and, if it is,
   * present a spinner of coded value domains. If not, show the correct UI view for the utility
   * network attribute data type.
   *
   * @param attribute being compared
   */
  private fun onComparisonSourceChanged(attribute: UtilityNetworkAttribute) {
    // if the domain is a coded value domain
    (attribute.domain as? CodedValueDomain)?.let { codedValueDomain ->
      // update the list of coded values
      values = codedValueDomain.codedValues
      // show the values spinner
      setVisible(valuesBackgroundView.id)
      // update the values spinner adapter
      valuesSpinner.adapter = ArrayAdapter<String>(
        applicationContext,
        android.R.layout.simple_list_item_1,
        // add the coded values from the coded value domain to the values spinner
        codedValueDomain.codedValues.map { it.name }
      )
      // if the domain is not a coded value domain
    } ?: when (attribute.dataType) {
      UtilityNetworkAttribute.DataType.BOOLEAN -> {
        setVisible(valueBooleanButton.id)
      }
      UtilityNetworkAttribute.DataType.DOUBLE, UtilityNetworkAttribute.DataType.FLOAT -> {
        // show the edit text and only allow numbers (decimals allowed)
        valuesEditText.inputType =
          InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
        setVisible(valuesEditText.id)
      }
      UtilityNetworkAttribute.DataType.INTEGER -> {
        // show the edit text only allowing for integer input
        valuesEditText.inputType = InputType.TYPE_CLASS_NUMBER
        setVisible(valuesEditText.id)
      }
      else -> {
        ("Unexpected utility network attribute data type.").also {
          Toast.makeText(this, it, Toast.LENGTH_LONG).show()
          Log.e(TAG, it)
        }
      }
    }
  }

  /**
   * Show the given UI view and hide the others which share the same space.
   *
   * @param id of the view to make visible
   */
  private fun setVisible(id: Int) {
    when (id) {
      valuesBackgroundView.id -> {
        valuesBackgroundView.visibility = View.VISIBLE
        valueBooleanButton.visibility = View.GONE
        valuesEditText.visibility = View.GONE
      }
      valuesEditText.id -> {
        valuesEditText.visibility = View.VISIBLE
        valueBooleanButton.visibility = View.GONE
        valuesBackgroundView.visibility = View.GONE
      }
      valueBooleanButton.id -> {
        valueBooleanButton.visibility = View.VISIBLE
        valuesBackgroundView.visibility = View.GONE
        valuesEditText.visibility = View.GONE
      }
    }
  }

  /**
   * Add a new barrier condition to the trace options.
   *
   * @param view of the add button
   */
  fun addCondition(view: View) {
    // if source tier doesn't contain a trace configuration, create one
    val traceConfiguration = sourceTier?.traceConfiguration ?: UtilityTraceConfiguration().apply {
      // if the trace configuration doesn't contain traversability, create one
      traversability ?: UtilityTraversability()
    }

    // get the currently selected attribute
    val attribute = sources?.get(sourceSpinner.selectedItemPosition)
    attribute?.let {
      // get the currently selected attribute operator
      val attributeOperator = operators?.get(operatorSpinner.selectedItemPosition)
      attributeOperator?.let {
        // if the other value is a coded value domain
        val otherValue = if (attribute.domain is CodedValueDomain) {
          values?.get(valuesSpinner.selectedItemPosition)?.code?.let {
            convertToDataType(it, attribute.dataType)
          }
        } else {
          convertToDataType(valuesEditText.text, attribute.dataType)
        }
        try {
          // NOTE: You may also create a UtilityNetworkAttributeComparison with another
          // NetworkAttribute
          var expression: UtilityTraceConditionalExpression = UtilityNetworkAttributeComparison(
            attribute,
            attributeOperator,
            otherValue
          )
          (traceConfiguration.traversability.barriers as? UtilityTraceConditionalExpression)?.let { otherExpression ->
            // NOTE: You may also combine expressions with UtilityTraceAndCondition
            expression = UtilityTraceOrCondition(otherExpression, expression)
          }
          traceConfiguration.traversability.barriers = expression
          expressionTextView.text = expressionToString(expression)
        } catch (e: Exception) {
          val error =
            "Error creating UtilityNetworkAttributeComparison! Did you forget to input a numeric value? ${e.message}"
          Log.e(TAG, error)
          Toast.makeText(this@MainActivity, error, Toast.LENGTH_LONG).show()
          return
        }
      }
    }
  }

  /**
   * Run the network trace with the parameters and display the result in an alert dialog.
   *
   * @param view of the trace button
   */
  fun trace(view: View) {
    // don't attempt a trace on an unloaded utility network
    if (utilityNetwork.loadStatus != LoadStatus.LOADED) {
      return
    }
    try {
      val parameters =
        UtilityTraceParameters(UtilityTraceType.SUBNETWORK, listOf(startingLocation)).apply {
          sourceTier?.traceConfiguration?.let {
            traceConfiguration = it
          }
        }
      val traceFuture = utilityNetwork.traceAsync(parameters)
      traceFuture.addDoneListener {
        try {
          val results = traceFuture.get()
          (results.firstOrNull() as? UtilityElementTraceResult)?.let { elementResult ->
            // create an alert dialog
            AlertDialog.Builder(this).apply {
              // set the alert dialog title
              setTitle("Trace result")
              // show the element result count
              setMessage(elementResult.elements.count().toString() + " elements found.")
            }.show()
          }
        } catch (e: Exception) {
          (e.cause?.message + "\nFor a working barrier condition, try \"Transformer Load\" Equal \"15\".").also {
            Toast.makeText(this, it, Toast.LENGTH_LONG).show()
            Log.e(TAG, it)
          }
        }
      }
    } catch (e: Exception) {
      ("Error during trace operation: " + e.message).also {
        Toast.makeText(this, it, Toast.LENGTH_LONG).show()
        Log.e(TAG, it)
      }
    }
  }

  /**
   * Convert the given UtilityTraceConditionalExpression into a string.
   *
   * @param expression to convert to a string
   */
  private fun expressionToString(expression: UtilityTraceConditionalExpression): String? {
    when (expression) {
      // when the expression is a category comparison expression
      is UtilityCategoryComparison -> {
        return expression.category.name + " " + expression.comparisonOperator
      }
      // when the expression is an attribute comparison expression
      is UtilityNetworkAttributeComparison -> {
        // the name and comparison operator of the expression
        val networkAttributeNameAndOperator =
          expression.networkAttribute.name + " " + expression.comparisonOperator + " "
        // check whether the network attribute has a coded value domain
        (expression.networkAttribute.domain as? CodedValueDomain)?.let { codedValueDomain ->
          // if there's a coded value domain name
          val codedValueDomainName = codedValueDomain.codedValues.first {
            convertToDataType(it.code, expression.networkAttribute.dataType) ==
                convertToDataType(expression.value, expression.networkAttribute.dataType)
          }.name
          return networkAttributeNameAndOperator + codedValueDomainName
        }
        // if there's no coded value domain name
          ?: return networkAttributeNameAndOperator + (expression.otherNetworkAttribute?.name
            ?: expression.value)
      }
      // when the expression is an utility trace AND condition
      is UtilityTraceAndCondition -> {
        return expressionToString(expression.leftExpression) + " AND\n" + expressionToString(
          expression.rightExpression
        )
      }
      // when the expression is an utility trace OR condition
      is UtilityTraceOrCondition -> {
        return expressionToString(expression.leftExpression) + " OR\n" + expressionToString(
          expression.rightExpression
        )
      }
      else -> {
        return null
      }
    }
  }

  /**
   * Reset the current barrier condition to the initial expression
   * "Operational Device Status EQUAL Open".
   *
   * @param view of the rest button
   */
  fun reset(view: View) {
    initialExpression?.let {
      val traceConfiguration = sourceTier?.traceConfiguration
      traceConfiguration?.traversability?.barriers = it
      expressionTextView.text = expressionToString(it)
    }
  }

  /**
   * Convert the given value into the correct Kotlin data type by using the attribute's data type.
   *
   * @param otherValue which will be converted
   * @param dataType to be converted to
   */
  private fun convertToDataType(otherValue: Any, dataType: UtilityNetworkAttribute.DataType): Any {
    return try {
      when (dataType) {
        UtilityNetworkAttribute.DataType.BOOLEAN -> otherValue.toString().toBoolean()
        UtilityNetworkAttribute.DataType.DOUBLE -> otherValue.toString().toDouble()
        UtilityNetworkAttribute.DataType.FLOAT -> otherValue.toString().toFloat()
        UtilityNetworkAttribute.DataType.INTEGER -> otherValue.toString().toInt()
      }
    } catch (e: Exception) {
      ("Error converting data type: " + e.message).also {
        Toast.makeText(this, it, Toast.LENGTH_LONG).show()
        Log.e(TAG, it)
      }
    }
  }
}

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