Back to all posts

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

This script example assigns the subcatchment 'Raingage' attribute. Users need to prepare a raingage background layer with one user-defined attribute called 'GageName', where a point represents the location of a raingage and attribute 'GageName' is the name of each raingage point.

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


# 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): = 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'