I am using QGIS 2.18.11 and I have overlaid a 50m x 50m grid on a map (through Vector Grid) and have 98 grid cells in total. What I need to do is to generate 12 points randomly per grid cell that is “reproducible”. Setting the seed of “RandomPointspolygonfixed.py” didn’t work because the result shows the random points have similar pattern across the cells as shown in a snapshot below. Is there any way to do it?
Found this python on my local install (2.18.10) and saw the same behaviour.
It seems to have been moved elsewhere in Master branch on GitHub, so this will change in QGIS 3
I don't normally suggest local fixes like this as
- they can cause problems
- even if they don't, you'll lose changes next time you upgrade QGIS
That said, looking at the code of RandomPointsPolygonsFixed.py I see why this might be happening
features = vector.features(layer) for current, f in enumerate(features): fGeom = QgsGeometry(f.geometry()) bbox = fGeom.boundingBox() if strategy == 0: pointCount = int(value) else: pointCount = int(round(value * da.measure(fGeom))) index = QgsSpatialIndex() points = dict() nPoints = 0 nIterations = 0 maxIterations = pointCount * 200 total = 100.0 / pointCount random.seed() # <-- here's your problem, it's inside the loop! ... snip ...
The problem is that random.seed() is inside the loop. That will explain why it's repeating in each cell.
Comment it out, and put it outside the loop like so...
random.seed(MY_SEED_VALUE) features = vector.features(layer) for current, f in enumerate(features): fGeom = QgsGeometry(f.geometry()) .. snip ...
This seems to have been fixed in Master so this behaviour will be different in QGIS 3.
Doing this, I was able to run Random Points inside Polygons (fixed) twice and got the same results...
(Note, you need to restart QGIS after any code changes like this)
It might be worth putting in a feature request to allow the seed value to be set by the user, rather than messing around with installed code ;-)
To add 12 points randomly in each grid polygon, you need to do the following steps:
- Add a new field in the polygon grid layer of Type integer and length of 2
- In the attribute table, select the new field, enter 12, and Update All
- Go to
Processing Toolbox -> QGIS Geoalgorithms -> Vector Creation Tools -> Random points inside polygons (Variable)
- Select the grid polygon layer
- Sampling strategy: Select
- Select the New Field that you defined in the first step
- Save the output file
Here is the result:
As you can see in the zoomed view, there are 12 points randomly distributed within each polygon.