Changeset 799


Ignore:
Timestamp:
Jan 27, 2005, 4:20:58 PM (20 years ago)
Author:
ole
Message:

Added populate_polygon and tested it

Location:
inundation/ga/storm_surge/pyvolution
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • inundation/ga/storm_surge/pyvolution/test_util.py

    r671 r799  
    511511       
    512512
     513    def test_populate_polygon(self):
     514
     515        polygon = [[0,0], [1,0], [1,1], [0,1]]
     516        points = populate_polygon(polygon, 5)
     517
     518        assert len(points) == 5
     519        for point in points:
     520            assert inside_polygon(point, polygon)
     521
     522
     523        #Very convoluted polygon
     524        polygon = [[0,0], [10,10], [15,5], [20, 10], [25,0], [30,10], [40,-10]]
     525
     526        points = populate_polygon(polygon, 5)
     527
     528        assert len(points) == 5
     529        for point in points:
     530            assert inside_polygon(point, polygon)
     531           
     532
    513533                     
    514534#-------------------------------------------------------------
  • inundation/ga/storm_surge/pyvolution/util.py

    r750 r799  
    494494   
    495495
    496 
     496def populate_polygon(polygon, number_of_points, seed = None):
     497    """Populate given polygon with uniformly distributed points.
     498
     499    Input:
     500       polygon - list of vertices of polygon
     501       number_of_points - (optional) number of points
     502       seed - seed for random number generator (default=None)
     503       
     504    Output:
     505       points - list of points inside polygon
     506       
     507    Examples:
     508       populate_polygon( [[0,0], [1,0], [1,1], [0,1]], 5 )
     509       will return five randomly sleected points inside the unit square
     510    """
     511
     512    from random import uniform, seed
     513
     514    seed(seed)
     515
     516    points = []
     517
     518    #Find outer extent of polygon
     519    max_x = min_x = polygon[0][0]
     520    max_y = min_y = polygon[0][1]
     521    for point in polygon[1:]:
     522        x = point[0]
     523        if x > max_x: max_x = x
     524        if x < min_x: min_x = x           
     525        y = point[1]
     526        if y > max_y: max_y = y
     527        if y < min_y: min_y = y           
     528
     529
     530    while len(points) < number_of_points:     
     531        x = uniform(min_x, max_x)
     532        y = uniform(min_y, max_y)       
     533
     534        if inside_polygon( [x,y], polygon ):
     535            points.append([x,y])
     536
     537    return points
    497538
    498539####################################################################
Note: See TracChangeset for help on using the changeset viewer.