Back to all posts

Script example: Assign the subcatchment Raingage attribute with closest Raingage point

This script example assigns the subcatchment 'Raingage' attribute.

This script is provided as-is, please see the disclaimer below for more information.

How the script works

The script iterates each subcatchment and finds the closest rain gage point to it. The subcatchment 'Raingage' attribute is assigned with the 'GageName' attribute of the closest rain gage point.

How to use this script

Users need to prepare a rain gage background layer with one user-defined attribute called 'GageName', where a point represents the location of a rain gage and attribute 'GageName' is the name of each rain gage point.

Download script

# this script is to assign each raingage point to its nearest subcatchment

# define Raingage class to hold rainage data read from background layer
class Raingage():
  def __init__(self, name, x, y):
    self.name = name
    self.x = x
    self.y = y

# read raingage data from background layer 'Raingage' and store it in a dictionary
raingage = pcpy.Map.Layer['Raingage'].get_entities()
rain = {}
for rg in raingage:
  name = rg['GageName']     # raingage attribute must exist in this Raingage layer
  centroid = rg.Centroid    # Centroid is an object of class TGIS_Point
  x, y = centroid.X, centroid.Y
  rain[name] = Raingage(name, x, y)   # store class data in a dictionary
  
# calculate distance from each subcatchment to every raingage and identify the minimum distance
subcatchments = pcpy.Map.Layer['Subcatchments'].get_entities()
for sub in subcatchments:
  centroid = sub.Centroid    # Centroid is an object of class TGIS_Point
  x, y = centroid.X, centroid.Y

# find the minimum distance
  min = float('inf')
  for key, val in rain.iteritems():  # rain is the dictionary holding all raingage data
# use square of distance to save time for calculating square root
    dist = (x - val.x)*(x - val.x) + (y - val.y)*(y - val.y)
    if dist < min:
      min = dist
      name = key

  sub['RainGage'] = name  # set the subcatchment RainGage attribute

print 'Task complete'

Disclaimer

All scripts are provided as-is, and no warranty is made as to the script's accuracy, completeness, or suitability for any particular purpose. This script may contain errors and require correction or modification by the modeler before its use.

The modeler is obligated to review the script code in its entirety and determine its suitability for its intended usage.

This script may also be updated from time to time to fix issues or provide enhanced functionality. If you have suggestions for improvement, please create a support ticket to let us know.