Advertisement
mwtoews

random_points_in_india.py

Jun 6th, 2011
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1.  
  2. import csv
  3. import random
  4. from datetime import datetime
  5. from osgeo import ogr
  6. from shapely.geometry import Point
  7. from shapely.prepared import prep
  8. from shapely.wkb import loads
  9.  
  10. start_time = all_start_time = datetime.now()
  11. g = ogr.Open('world.shp') # Open the shapefile with all the world's countries
  12. # Loop over the different features until we find INDIA
  13. for feat in g.GetLayer(0):
  14.     if feat.GetFieldAsString('NAME').find('INDIA') >= 0:
  15.         break # We found India, break out of the loop
  16.               # feat now holds the feature of INDIA
  17. # Get the geometry of India
  18. India = loads(feat.GetGeometryRef().ExportToWkb())
  19. IndiaP = prep(India)
  20. print 'reading/searching shapefile:', datetime.now() - start_time
  21. start_time = datetime.now()
  22. lon_min, lat_min, lon_max, lat_max = India.bounds # Now get the envelope
  23.  
  24. n_points = 0 # A counter
  25. india_lonlat = [] # A list where we'll store longitudes/latitudes within India
  26. while n_points < 10000: # Until we reach our required number of points...
  27.     # Draw random longitudes and latitudes within the envelope
  28.     r_lon = random.uniform(lon_min, lon_max)
  29.     r_lat = random.uniform(lat_min, lat_max)
  30.     pt = Point(r_lon, r_lat)
  31.     # Is this geometry within India?
  32.     if IndiaP.contains(pt):
  33.         # yes! Store the latitude&longitude and update counter
  34.         india_lonlat.append([r_lon, r_lat])
  35.         n_points += 1
  36. print 'generated', n_points, 'points:', datetime.now() - start_time
  37. start_time = datetime.now()
  38. # Save to a CSV file
  39. fp = open('india.csv', 'wb')
  40. w = csv.writer(fp)
  41. w.writerow(['Longitude', 'Latitude'])# Header
  42. w.writerows(india_lonlat)
  43. fp.close()
  44. print 'wrote CSV file:', datetime.now() - start_time
  45. start_time = datetime.now()
  46. print 'total time:', datetime.now() - all_start_time
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement