Skip to content

Commit bfc33ba

Browse files
committed
[processing] new tool: random point in given extent
Work done for Faunalia funded by Prof. António Mira (University of Évora, Portugal, Unidade de Biologia da Conservação) and Dr. Rosana Peixoto
1 parent bae196b commit bfc33ba

File tree

2 files changed

+132
-3
lines changed

2 files changed

+132
-3
lines changed

python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@
9090
from ZonalStatistics import ZonalStatistics
9191
from PointsFromPolygons import PointsFromPolygons
9292
from PointsFromLines import PointsFromLines
93+
from RandomPointsExtent import RandomPointsExtent
9394

9495
# from VectorLayerHistogram import VectorLayerHistogram
9596
# from VectorLayerScatterplot import VectorLayerScatterplot
@@ -119,8 +120,9 @@ def __init__(self):
119120
VariableDistanceBuffer(), Dissolve(), Difference(),
120121
Intersection(), Union(), Clip(), ExtentFromLayer(),
121122
RandomSelection(), RandomSelectionWithinSubsets(),
122-
SelectByLocation(), RandomExtract(), RandomExtractWithinSubsets(),
123-
ExtractByLocation(), SpatialJoin(),
123+
SelectByLocation(), RandomExtract(),
124+
RandomExtractWithinSubsets(), ExtractByLocation(),
125+
SpatialJoin(),
124126
# ------ mmqgisx ------
125127
mmqgisx_delete_columns_algorithm(),
126128
mmqgisx_delete_duplicate_geometries_algorithm(),
@@ -141,7 +143,7 @@ def __init__(self):
141143
StatisticsByCategories(), ConcaveHull(), Polygonize(),
142144
RasterLayerStatistics(), PointsDisplacement(),
143145
ZonalStatistics(), PointsFromPolygons(),
144-
PointsFromLines(),
146+
PointsFromLines(), RandomPointsExtent(),
145147
# ------ raster ------
146148
# CreateConstantRaster(),
147149
# ------ graphics ------
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
# -*- coding: utf-8 -*-
2+
3+
"""
4+
***************************************************************************
5+
RandomPointsExtent.py
6+
---------------------
7+
Date : April 2014
8+
Copyright : (C) 2014 by Alexander Bruy
9+
Email : alexander dot bruy at gmail dot com
10+
***************************************************************************
11+
* *
12+
* This program is free software; you can redistribute it and/or modify *
13+
* it under the terms of the GNU General Public License as published by *
14+
* the Free Software Foundation; either version 2 of the License, or *
15+
* (at your option) any later version. *
16+
* *
17+
***************************************************************************
18+
"""
19+
20+
__author__ = 'Alexander Bruy'
21+
__date__ = 'April 2014'
22+
__copyright__ = '(C) 2014, Alexander Bruy'
23+
24+
# This will get replaced with a git SHA1 when you do a git archive
25+
26+
__revision__ = '$Format:%H$'
27+
28+
import math
29+
import random
30+
31+
from PyQt4.QtCore import *
32+
33+
from qgis.core import *
34+
35+
from processing import interface
36+
from processing.core.GeoAlgorithm import GeoAlgorithm
37+
from processing.core.ProcessingLog import ProcessingLog
38+
from processing.parameters.ParameterExtent import ParameterExtent
39+
from processing.parameters.ParameterNumber import ParameterNumber
40+
from processing.outputs.OutputVector import OutputVector
41+
42+
43+
class RandomPointsExtent(GeoAlgorithm):
44+
45+
EXTENT = 'EXTENT'
46+
POINT_NUMBER = 'POINT_NUMBER'
47+
MIN_DISTANCE = 'MIN_DISTANCE'
48+
OUTPUT = 'OUTPUT'
49+
50+
def defineCharacteristics(self):
51+
self.name = 'Random points in extent'
52+
self.group = 'Vector creation tools'
53+
self.addParameter(ParameterExtent(self.EXTENT, 'Input extent'))
54+
self.addParameter(
55+
ParameterNumber(self.POINT_NUMBER, 'Points number', 1, 9999999, 1))
56+
self.addParameter(ParameterNumber(
57+
self.MIN_DISTANCE, 'Minimum distance', 0.0, 9999999, 0.0))
58+
self.addOutput(OutputVector(self.OUTPUT, 'Random points'))
59+
60+
def processAlgorithm(self, progress):
61+
pointCount = int(self.getParameterValue(self.POINT_NUMBER))
62+
minDistance = float(self.getParameterValue(self.MIN_DISTANCE))
63+
extent = str(self.getParameterValue(self.EXTENT)).split(',')
64+
65+
xMin = float(extent[0])
66+
xMax = float(extent[1])
67+
yMin = float(extent[2])
68+
yMax = float(extent[3])
69+
extent = QgsGeometry().fromRect(
70+
QgsRectangle(xMin, yMin, xMax, yMax))
71+
72+
fields = QgsFields()
73+
fields.append(QgsField('id', QVariant.Int, '', 10, 0))
74+
mapCRS = interface.iface.mapCanvas().mapSettings().destinationCrs()
75+
writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(
76+
fields, QGis.WKBPoint, mapCRS)
77+
78+
nPoints = 0
79+
nIterations = 0
80+
maxIterations = pointCount * 200
81+
total = 100.0 / pointCount
82+
83+
index = QgsSpatialIndex()
84+
points = dict()
85+
86+
while nIterations < maxIterations and nPoints < pointCount:
87+
rx = xMin + (xMax - xMin) * random.random()
88+
ry = yMin + (yMax - yMin) * random.random()
89+
90+
pnt = QgsPoint(rx, ry)
91+
geom = QgsGeometry.fromPoint(pnt)
92+
if geom.within(extent) and \
93+
self.checkMinDistance(pnt, index, minDistance, points):
94+
f = QgsFeature(nPoints)
95+
f.initAttributes(1)
96+
f.setFields(fields)
97+
f.setAttribute('id', nPoints)
98+
f.setGeometry(geom)
99+
writer.addFeature(f)
100+
index.insertFeature(f)
101+
points[nPoints] = pnt
102+
nPoints += 1
103+
progress.setPercentage(int(nPoints * total))
104+
nIterations += 1
105+
106+
if nPoints < pointCount:
107+
ProcessingLog.addToLog(
108+
ProcessingLog.LOG_INFO,
109+
'Can not generate requested number of random points. Maximum '
110+
'number of attempts exceeded.')
111+
112+
del writer
113+
114+
def checkMinDistance(self, point, index, distance, points):
115+
if distance == 0:
116+
return True
117+
118+
neighbors = index.nearestNeighbor(point, 1)
119+
if len(neighbors) == 0:
120+
return True
121+
122+
if neighbors[0] in points:
123+
np = points[neighbors[0]]
124+
if np.sqrDist(point) < (distance * distance):
125+
return False
126+
127+
return True

0 commit comments

Comments
 (0)