How do I used the random module to create triangles?

4836
11
08-13-2015 04:11 AM
fumaniwada1
New Contributor

I have a shapefile of the world and I am trying to create 75 random triangles over this shapefile using the random package. I'm just not sure how to do this and use a for loop to create the lat and.

0 Kudos
11 Replies
DanPatterson_Retired
MVP Emeritus

The post has been removed Xander...the 404 message with This question was voluntarily removed by its author.

0 Kudos
XanderBakker
Esri Esteemed Contributor

I though I would do another intent by creating some equilateral triangles with a size ranging between 2.5 and 10 degrees:

This is the code used (see code below). For the visualization, I calculated the area in km² using the WGS_1984_Web_Mercator_Auxiliary_Sphere (WKID: 3857) and used that to extrude and symbolize the triangles in ArcGlobe.

import random
import arcpy
import math

def main():
    # settings
    triangles = 75
    x_range = (-180.0, 180.0)
    y_range = (-85.0, 85.0)
    size_range = (2.5, 10) # decimal degrees
    sr = arcpy.SpatialReference(4326) # GC_WGS_1984
    fc = r"C:\GeoNet\RandomTriangles\test02.shp"

    feats = []
    for i in range(triangles):
        feat = []
        pnt = arcpy.Point(random.uniform(x_range[0], x_range[1]),
                          random.uniform(y_range[0], y_range[1]))
        polygon = createTriangle(pnt, random.uniform(size_range[0], size_range[1]), sr)
        polygon = movePolygonInsideExtent(polygon, x_range, y_range)
        feats.append(polygon)
    arcpy.CopyFeatures_management(feats, fc)

def createTriangle(pnt_cc, size, sr):
    rotation_range = (0, 120)
    rotation = random.uniform(rotation_range[0], rotation_range[1])
    feat = []
    for i in range(3):
        pnt = createPointAtAngleWithBearing(pnt_cc, rotation + i*120, size)
        feat.append(pnt)
    feat.append(feat[0])
    return arcpy.Polygon(arcpy.Array(feat), sr)

def createPointAtAngleWithBearing(pnt, angle, size):
    radius = size / math.sqrt(3) # translate side of equilateral triangle to
    angle = math.radians(angle)
    dist_x, dist_y = (radius * math.cos(angle), radius * math.sin(angle))
    return arcpy.Point(pnt.X + dist_x, pnt.Y + dist_y)

def movePolygonInsideExtent(polygon, x_range, y_range):
    ext = polygon.extent
    x_move, y_move = 0, 0
    if ext.XMin < x_range[0]:
        x_move = x_range[0] - ext.XMin
    elif ext.XMax > x_range[1]:
        x_move = x_range[1] - ext.XMax
    if ext.YMin < y_range[0]:
        y_move = y_range[0] - ext.YMin
    elif ext.YMax > y_range[1]:
        y_move = y_range[1] - ext.YMax

    if x_move != 0 or y_move != 0:
        feat = []
        for part in polygon:
            for pnt in part:
                pnt = arcpy.Point(pnt.X + x_move, pnt.Y + y_move)
                feat.append(pnt)
        return arcpy.Polygon(arcpy.Array(feat), polygon.spatialReference)
    else:
        return polygon

if __name__ == '__main__':
    main()