Skip to content

Analyze network with subnetwork trace

View on GitHubSample 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 analyze network with 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 from a ServiceGeodatabase, 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 Configuration' is clicked, create a new UtilityNetworkAttributeComparison using the selected comparison source, operator, and selected or typed value. Use the selected source's UtilityNetworkAttributeDataType to convert the comparison value to the correct data type.
  7. If the traversability 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.trace(...).
  9. When Reset is clicked, set the trace configurations expression back to its original value.
  10. Display the count of returned UtilityElementTraceResult.elements.count().

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 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 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 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 /* 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  *  * 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.  *  */  package com.esri.arcgismaps.sample.analyzenetworkwithsubnetworktrace  import android.os.Bundle import android.text.InputType import android.util.Log import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView import android.widget.CheckBox import android.widget.RelativeLayout import android.widget.TextView import android.widget.ToggleButton import androidx.appcompat.app.AlertDialog import androidx.databinding.DataBindingUtil import androidx.lifecycle.lifecycleScope import com.arcgismaps.ArcGISEnvironment import com.arcgismaps.Guid import com.arcgismaps.LoadStatus import com.arcgismaps.data.CodedValue import com.arcgismaps.data.CodedValueDomain import com.arcgismaps.data.ServiceGeodatabase import com.arcgismaps.httpcore.authentication.ArcGISAuthenticationChallengeHandler import com.arcgismaps.httpcore.authentication.ArcGISAuthenticationChallengeResponse import com.arcgismaps.httpcore.authentication.TokenCredential import com.arcgismaps.utilitynetworks.UtilityAttributeComparisonOperator import com.arcgismaps.utilitynetworks.UtilityCategoryComparison import com.arcgismaps.utilitynetworks.UtilityElement import com.arcgismaps.utilitynetworks.UtilityElementTraceResult import com.arcgismaps.utilitynetworks.UtilityNetwork import com.arcgismaps.utilitynetworks.UtilityNetworkAttribute import com.arcgismaps.utilitynetworks.UtilityNetworkAttributeComparison import com.arcgismaps.utilitynetworks.UtilityNetworkAttributeDataType import com.arcgismaps.utilitynetworks.UtilityTier import com.arcgismaps.utilitynetworks.UtilityTraceAndCondition import com.arcgismaps.utilitynetworks.UtilityTraceConditionalExpression import com.arcgismaps.utilitynetworks.UtilityTraceConfiguration import com.arcgismaps.utilitynetworks.UtilityTraceOrCondition import com.arcgismaps.utilitynetworks.UtilityTraceParameters import com.arcgismaps.utilitynetworks.UtilityTraceType import com.arcgismaps.utilitynetworks.UtilityTraversability import com.esri.arcgismaps.sample.analyzenetworkwithsubnetworktrace.databinding.AnalyzeNetworkWithSubnetworkTraceActivityMainBinding import com.esri.arcgismaps.sample.analyzenetworkwithsubnetworktrace.databinding.LoadingOptionsDialogBinding import com.esri.arcgismaps.sample.sampleslib.EdgeToEdgeCompatActivity import com.google.android.material.button.MaterialButton import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar import com.google.android.material.textfield.TextInputEditText import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking  class MainActivity : EdgeToEdgeCompatActivity() {   // set up data binding for the activity  private val activityMainBinding: AnalyzeNetworkWithSubnetworkTraceActivityMainBinding by lazy {  DataBindingUtil.setContentView(this, R.layout.analyze_network_with_subnetwork_trace_activity_main)  }   private val sourceDropdown: AutoCompleteTextView by lazy {  activityMainBinding.sourceDropdown  }   private val operatorDropdown: AutoCompleteTextView by lazy {  activityMainBinding.operatorDropdown  }   private val expressionTextView: TextView by lazy {  activityMainBinding.expressionTextView  }   private val valuesDropdown: AutoCompleteTextView by lazy {  activityMainBinding.valuesDropdown  }   private val valuesBackgroundView: RelativeLayout by lazy {  activityMainBinding.valuesBackgroundView  }   private val valueBooleanButton: ToggleButton by lazy {  activityMainBinding.valueBooleanButton  }   private val valuesEditText: TextInputEditText by lazy {  activityMainBinding.valuesEditText  }   private val barriersCheckbox: CheckBox by lazy {  activityMainBinding.barriersCheckBox  }   private val containersCheckbox: CheckBox by lazy {  activityMainBinding.containersCheckbox  }   private val traceButton: MaterialButton by lazy {  activityMainBinding.traceButton  }   private val utilityNetwork by lazy {  UtilityNetwork(ServiceGeodatabase(getString(R.string.utility_network_url)))  }   private var initialExpression: UtilityTraceConditionalExpression? = null  private var sourceTier: UtilityTier? = null  private var utilityTraceConfiguration: UtilityTraceConfiguration? = null  private var sourcesList: List<UtilityNetworkAttribute>? = null  private var operatorsList: Array<UtilityAttributeComparisonOperator>? = null  private var startingLocation: UtilityElement? = null  private var codedValuesList: List<CodedValue>? = null  private var sourcePosition: Int = 0  private var operatorPosition: Int = 0  private var valuePosition: Int = 0  private var dialog: AlertDialog? = null   override fun onCreate(savedInstanceState: Bundle?) {  super.onCreate(savedInstanceState)   ArcGISEnvironment.applicationContext = this  ArcGISEnvironment.authenticationManager.arcGISAuthenticationChallengeHandler =  getAuthenticationChallengeHandler()   // create and display the loading dialog  showLoadingDialog(true)   // load the utility network  lifecycleScope.launch {  utilityNetwork.load().getOrElse {  dialog?.dismiss()  traceButton.isEnabled = false  return@launch showError("Error loading utility network: ${it.message}")  }   // create a list of utility network attributes whose system is not defined  sourcesList =  utilityNetwork.definition?.networkAttributes?.filter { !it.isSystemDefined }   sourceDropdown.apply {  // add the list of sources to the drop down view  setAdapter(sourcesList?.let { utilityNetworkAttributes ->  ArrayAdapter(  applicationContext,  com.esri.arcgismaps.sample.sampleslib.R.layout.custom_dropdown_item,  utilityNetworkAttributes.map { it.name })  })   // add an on item selected listener which calls on comparison source changed  onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->  sourcePosition = position  sourcesList?.get(position)?.let { onComparisonSourceChanged(it) }  }  }   // create a list of utility attribute comparison operators  operatorsList =  UtilityAttributeComparisonOperator::class.sealedSubclasses.mapNotNull { it.objectInstance }  .toTypedArray()   operatorDropdown.apply {  // add the list of sources to the drop down view  setAdapter(operatorsList?.let { utilityAttributeComparisonOperator ->  ArrayAdapter(applicationContext,  com.esri.arcgismaps.sample.sampleslib.R.layout.custom_dropdown_item,  utilityAttributeComparisonOperator.map { it::class.simpleName })  })   // add an on item selected listener which calls on comparison source changed  onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->  operatorPosition = position  }  }   // 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 = Guid("1CAF7740-0BF4-4113-8DB2-654E18800028")   if (assetType == null) return@launch   val terminal = assetType.terminalConfiguration?.terminals?.first { it.name == "Load" }   // utility element to start the trace from  startingLocation = utilityNetwork.createElementOrNull(assetType, globalId, terminal)   // get a default trace configuration from a tier to update the UI  val domainNetwork = utilityNetwork.definition?.getDomainNetwork(  "ElectricDistribution"  )   // set source utility tier from the utility domain network  sourceTier = domainNetwork?.getTier("Medium Voltage Radial")?.apply {  utilityTraceConfiguration = getDefaultTraceConfiguration()  }   // set initial barrier condition  val defaultConditionalExpression = sourceTier.let {  utilityTraceConfiguration?.traversability?.barriers as UtilityTraceConditionalExpression  }  // set the text view  expressionTextView.text = expressionToString(defaultConditionalExpression)  // use the initial expression when resetting trace  initialExpression = defaultConditionalExpression   showLoadingDialog(false)  }  }   /**  * Returns a [ArcGISAuthenticationChallengeHandler] to access the utility network URL.  */  private fun getAuthenticationChallengeHandler(): ArcGISAuthenticationChallengeHandler {  return ArcGISAuthenticationChallengeHandler { challenge ->  val result: Result<TokenCredential> = runBlocking {  TokenCredential.create(challenge.requestUrl, "viewer01", "I68VGU^nMurF", 0)  }  if (result.getOrNull() != null) {  val credential = result.getOrNull()  return@ArcGISAuthenticationChallengeHandler ArcGISAuthenticationChallengeResponse  .ContinueWithCredential(credential!!)  } else {  val ex = result.exceptionOrNull()  return@ArcGISAuthenticationChallengeHandler ArcGISAuthenticationChallengeResponse  .ContinueAndFailWithError(ex!!)  }  }  }   /**  * When a comparison source [attribute] is chosen check if it's a coded value domain and, if it is,  * present a dropdown of coded value domains. If not, show the correct UI view for the utility  * network attribute data type.  */  private fun onComparisonSourceChanged(attribute: UtilityNetworkAttribute) {  // if the domain is a coded value domain  if (attribute.domain is CodedValueDomain) {  (attribute.domain as CodedValueDomain).let { codedValueDomain ->  // update the list of coded values  codedValuesList = codedValueDomain.codedValues  // show the values dropdown  setVisible(valuesBackgroundView.id)  // update the values dropdown adapter  valuesDropdown.setAdapter(ArrayAdapter(applicationContext,  com.esri.arcgismaps.sample.sampleslib.R.layout.custom_dropdown_item,  // add the coded values from the coded value domain to the values dropdown  codedValueDomain.codedValues.map { it.name }))  // add an on item selected listener which calls on comparison source changed  valuesDropdown.onItemClickListener =  AdapterView.OnItemClickListener { _, _, position, _ ->  valuePosition = position  }  }  } // if the domain is not a coded value domain  else {  when (attribute.dataType) {  UtilityNetworkAttributeDataType.Boolean -> {  // show true/false toggle button  setVisible(valueBooleanButton.id)  }  UtilityNetworkAttributeDataType.Double, UtilityNetworkAttributeDataType.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)  }  UtilityNetworkAttributeDataType.Integer -> {  // show the edit text only allowing for integer input  valuesEditText.inputType = InputType.TYPE_CLASS_NUMBER  setVisible(valuesEditText.id)  }  else -> {  showError("Unexpected utility network attribute data type.")  }  }  }  }   /**  * Add a new barrier condition to the trace options when [addConditionButton] is tapped.  */  fun addBarrierCondition(addConditionButton: View) {  // if source tier doesn't contain a trace configuration, create one  val traceConfiguration = utilityTraceConfiguration ?: UtilityTraceConfiguration().apply {  // if the trace configuration doesn't contain traversability, create one  traversability ?: UtilityTraversability()  }   // get the currently selected attribute  sourcesList?.get(sourcePosition)?.let { sourceAttribute ->  // if the other value is a coded value domain  val otherValue = if (sourceAttribute.domain is CodedValueDomain) {  codedValuesList?.get(valuePosition)?.code?.let {  convertToDataType(it, sourceAttribute.dataType)  }  } else {  convertToDataType(valuesEditText.text.toString(), sourceAttribute.dataType)  }   if (otherValue.toString().contains("Error") || otherValue == null) {  return showError(otherValue.toString())  }   // get the currently selected attribute operator>  operatorsList?.get(operatorPosition)?.let { comparisonOperator ->  // NOTE: You may also create a UtilityNetworkAttributeComparison  // with another NetworkAttribute  var expression: UtilityTraceConditionalExpression =  UtilityNetworkAttributeComparison(  sourceAttribute,  comparisonOperator,  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)  }  }  }   /**  * Show the UI of the given [id] and hide the others which share the same space.  */  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  }  }  }   /**  * Run the network trace with the parameters and display the result in an alert dialog  * when the [traceButton] is clicked.  */  fun trace(traceButton: View) {  if (utilityNetwork.loadStatus.value != LoadStatus.Loaded) {  return showError("Utility network is not loaded")  }   // set the utility trace parameters  val parameters = UtilityTraceParameters(  UtilityTraceType.Subnetwork,  listOf(startingLocation).requireNoNulls()  ).apply {  // set the utility trace configuration options to include  traceConfiguration = utilityTraceConfiguration?.apply {  includeBarriers = barriersCheckbox.isChecked  includeContainers = containersCheckbox.isChecked  }  }   // launch trace in a coroutine scope  lifecycleScope.launch {  showLoadingDialog(true)  val utilityTraceResults = utilityNetwork.trace(parameters).getOrElse {  return@launch showError(it.message + getString(R.string.example_condition))  }  // get the UtilityElementTraceResult  val elementTraceResult = utilityTraceResults.first() as UtilityElementTraceResult   showLoadingDialog(false)  MaterialAlertDialogBuilder(this@MainActivity).apply {  // set the result dialog title  setTitle("Trace result")  // show the element result count  setMessage(elementTraceResult.elements.count().toString() + " elements found.")  }.show()  }  }   /**  * Convert the given [expression] into 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 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  )  }  // 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::class.simpleName + " "   // check whether the network attribute has a coded value domain  val codedValueDomain = expression.networkAttribute.domain as? CodedValueDomain  return if (codedValueDomain != null) {  networkAttributeNameAndOperator +  getCodedValueFromExpression(codedValueDomain, expression)?.name  } else {  // if there's no coded value domain  networkAttributeNameAndOperator +  (expression.otherNetworkAttribute?.name ?: expression.value)  }  }  else -> {  return null  }  }  }   /**  * 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: UtilityNetworkAttributeDataType,  ): Any {  return try {  if (dataType::class.isInstance(UtilityNetworkAttributeDataType.Boolean)) {  otherValue.toString().toBoolean()  } else if (dataType::class.isInstance(UtilityNetworkAttributeDataType.Double)) {  otherValue.toString().toDouble()  } else if (dataType::class.isInstance(UtilityNetworkAttributeDataType.Float)) {  otherValue.toString().toFloat()  } else if (dataType::class.isInstance(UtilityNetworkAttributeDataType.Integer)) {  otherValue.toString().toInt()  } else {  }  } catch (e: Exception) {  return ("Error converting value to a datatype")  }  }   /**  * Returns a [CodedValue] found in the [expression] using the  * list of coded values in the [codedValueDomain].  */  private fun getCodedValueFromExpression(  codedValueDomain: CodedValueDomain,  expression: UtilityNetworkAttributeComparison,  ): CodedValue? {  // if there's a coded value domain name  return codedValueDomain.codedValues.first { codedValue ->  val code = codedValue.code  val value = expression.value  if (code != null && value != null) {  return@first (convertToDataType(code,  expression.networkAttribute.dataType) == convertToDataType(value,  expression.networkAttribute.dataType))  } else  return null  }  }   /**  * Reset the current barrier condition to the initial expression  * "Operational Device Status EQUAL Open" and resets the UI.  */  fun reset(view: View) {  initialExpression?.let {  utilityTraceConfiguration = sourceTier?.getDefaultTraceConfiguration()?.apply {  traversability?.barriers = it  }  expressionTextView.text = expressionToString(it)  }  }   private fun showLoadingDialog(isVisible: Boolean) {  if (isVisible) {  dialog = MaterialAlertDialogBuilder(this).apply {  setCancelable(false)  setView(LoadingOptionsDialogBinding.inflate(layoutInflater).root)  }.show()  } else {  dialog?.dismiss()  }  }   private fun showError(message: String) {  Log.e(localClassName, message)  Snackbar.make(activityMainBinding.root, message, Snackbar.LENGTH_SHORT).show()  } }

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