Guest User

Untitled

a guest
Nov 21st, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. import random
  2. from PyQt4.QtCore import QVariant
  3.  
  4. def checkMinDistance(point, index, distance, points):
  5. if distance == 0:
  6. return True
  7. neighbors = index.nearestNeighbor(point, 1)
  8. if len(neighbors) == 0:
  9. return True
  10. if neighbors[0] in points:
  11. np = points[neighbors[0]]
  12. if np.sqrDist(point) < (distance * distance):
  13. return False
  14. return True
  15.  
  16. def generate_wind_turbines(spacing):
  17. layer = iface.activeLayer()
  18. crs = layer.crs()
  19. # Memory layer
  20. memory_lyr = QgsVectorLayer("Point?crs=epsg:" + unicode(crs.postgisSrid()) + "&index=yes", "Wind turbines for " + str(layer.name()), "memory")
  21. QgsMapLayerRegistry.instance().addMapLayer(memory_lyr)
  22. memory_lyr.startEditing()
  23. provider = memory_lyr.dataProvider()
  24. provider.addAttributes([QgsField("ID", QVariant.Int)])
  25. # Variables
  26. point_density = 0.0001
  27. fid = 1
  28. distance_area = QgsDistanceArea()
  29. # List of features
  30. fts = []
  31. # Create points
  32. for f in layer.getFeatures():
  33. fGeom = QgsGeometry(f.geometry())
  34. bbox = fGeom.boundingBox()
  35. pointCount = int(round(point_density * distance_area.measure(fGeom)))
  36. index = QgsSpatialIndex()
  37. points = dict()
  38. nPoints = 0
  39. fid += 1
  40. nIterations = 0
  41. maxIterations = pointCount * 200
  42. random.seed()
  43. while nIterations < maxIterations and nPoints < pointCount:
  44. rx = bbox.xMinimum() + bbox.width() * random.random()
  45. ry = bbox.yMinimum() + bbox.height() * random.random()
  46. pnt = QgsPoint(rx, ry)
  47. geom = QgsGeometry.fromPoint(pnt)
  48. if geom.within(fGeom) and checkMinDistance(pnt, index, spacing, points):
  49. f = QgsFeature(nPoints)
  50. f.initAttributes(1)
  51. f.setAttributes([fid])
  52. f.setGeometry(geom)
  53. fts.append(f)
  54. index.insertFeature(f)
  55. points[nPoints] = pnt
  56. nPoints += 1
  57. nIterations += 1
  58. provider.addFeatures(fts)
  59. memory_lyr.updateFields()
  60. memory_lyr.commitChanges()
  61.  
  62. generate_wind_turbines(500)
Add Comment
Please, Sign In to add comment