RandomPointsLayer.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. """
  2. ***************************************************************************
  3. RandomPointsLayer.py
  4. ---------------------
  5. Date : April 2014
  6. Copyright : (C) 2014 by Alexander Bruy
  7. Email : alexander dot bruy at gmail dot com
  8. ***************************************************************************
  9. * *
  10. * This program is free software; you can redistribute it and/or modify *
  11. * it under the terms of the GNU General Public License as published by *
  12. * the Free Software Foundation; either version 2 of the License, or *
  13. * (at your option) any later version. *
  14. * *
  15. ***************************************************************************
  16. """
  17. __author__ = 'Alexander Bruy'
  18. __date__ = 'April 2014'
  19. __copyright__ = '(C) 2014, Alexander Bruy'
  20. import os
  21. import random
  22. from qgis.PyQt.QtGui import QIcon
  23. from qgis.PyQt.QtCore import QVariant
  24. from qgis.core import (QgsApplication,
  25. QgsField,
  26. QgsFeatureSink,
  27. QgsFeature,
  28. QgsFields,
  29. QgsGeometry,
  30. QgsPointXY,
  31. QgsWkbTypes,
  32. QgsSpatialIndex,
  33. QgsFeatureRequest,
  34. QgsProcessing,
  35. QgsProcessingException,
  36. QgsProcessingParameterNumber,
  37. QgsProcessingParameterDistance,
  38. QgsProcessingParameterFeatureSource,
  39. QgsProcessingParameterFeatureSink,
  40. QgsProcessingParameterDefinition)
  41. from processing.algs.qgis.QgisAlgorithm import QgisAlgorithm
  42. from processing.tools import vector
  43. pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0]
  44. class RandomPointsLayer(QgisAlgorithm):
  45. INPUT = 'INPUT'
  46. POINTS_NUMBER = 'POINTS_NUMBER'
  47. MIN_DISTANCE = 'MIN_DISTANCE'
  48. OUTPUT = 'OUTPUT'
  49. def icon(self):
  50. return QgsApplication.getThemeIcon("/algorithms/mAlgorithmRandomPointsWithinExtent.svg")
  51. def svgIconPath(self):
  52. return QgsApplication.iconPath("/algorithms/mAlgorithmRandomPointsWithinExtent.svg")
  53. def group(self):
  54. return self.tr('Vector creation')
  55. def groupId(self):
  56. return 'vectorcreation'
  57. def __init__(self):
  58. super().__init__()
  59. def initAlgorithm(self, config=None):
  60. self.addParameter(QgsProcessingParameterFeatureSource(self.INPUT,
  61. self.tr('Input layer'),
  62. [QgsProcessing.TypeVectorPolygon]))
  63. self.addParameter(QgsProcessingParameterNumber(self.POINTS_NUMBER,
  64. self.tr('Number of points'),
  65. QgsProcessingParameterNumber.Integer,
  66. 1, False, 1, 1000000000))
  67. self.addParameter(QgsProcessingParameterDistance(self.MIN_DISTANCE,
  68. self.tr('Minimum distance between points'),
  69. 0, self.INPUT, False, 0, 1000000000))
  70. self.addParameter(QgsProcessingParameterFeatureSink(self.OUTPUT,
  71. self.tr('Random points'),
  72. type=QgsProcessing.TypeVectorPoint))
  73. def name(self):
  74. return 'randompointsinlayerbounds'
  75. def displayName(self):
  76. return self.tr('Random points in layer bounds')
  77. def processAlgorithm(self, parameters, context, feedback):
  78. source = self.parameterAsSource(parameters, self.INPUT, context)
  79. if source is None:
  80. raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT))
  81. pointCount = self.parameterAsDouble(parameters, self.POINTS_NUMBER, context)
  82. minDistance = self.parameterAsDouble(parameters, self.MIN_DISTANCE, context)
  83. bbox = source.sourceExtent()
  84. sourceIndex = QgsSpatialIndex(source, feedback)
  85. fields = QgsFields()
  86. fields.append(QgsField('id', QVariant.Int, '', 10, 0))
  87. (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
  88. fields, QgsWkbTypes.Point, source.sourceCrs(), QgsFeatureSink.RegeneratePrimaryKey)
  89. if sink is None:
  90. raise QgsProcessingException(self.invalidSinkError(parameters, self.OUTPUT))
  91. nPoints = 0
  92. nIterations = 0
  93. maxIterations = pointCount * 200
  94. total = 100.0 / pointCount if pointCount else 1
  95. index = QgsSpatialIndex()
  96. points = {}
  97. random.seed()
  98. while nIterations < maxIterations and nPoints < pointCount:
  99. if feedback.isCanceled():
  100. break
  101. rx = bbox.xMinimum() + bbox.width() * random.random()
  102. ry = bbox.yMinimum() + bbox.height() * random.random()
  103. p = QgsPointXY(rx, ry)
  104. geom = QgsGeometry.fromPointXY(p)
  105. ids = sourceIndex.intersects(geom.buffer(5, 5).boundingBox())
  106. if len(ids) > 0 and \
  107. vector.checkMinDistance(p, index, minDistance, points):
  108. request = QgsFeatureRequest().setFilterFids(ids).setSubsetOfAttributes([])
  109. for f in source.getFeatures(request):
  110. if feedback.isCanceled():
  111. break
  112. tmpGeom = f.geometry()
  113. if geom.within(tmpGeom):
  114. f = QgsFeature(nPoints)
  115. f.initAttributes(1)
  116. f.setFields(fields)
  117. f.setAttribute('id', nPoints)
  118. f.setGeometry(geom)
  119. sink.addFeature(f, QgsFeatureSink.FastInsert)
  120. index.addFeature(f)
  121. points[nPoints] = p
  122. nPoints += 1
  123. feedback.setProgress(int(nPoints * total))
  124. nIterations += 1
  125. if nPoints < pointCount:
  126. feedback.pushInfo(self.tr('Could not generate requested number of random points. '
  127. 'Maximum number of attempts exceeded.'))
  128. return {self.OUTPUT: dest_id}