QGIS API Documentation  2.14.0-Essen
qgspointsample.cpp
Go to the documentation of this file.
1 #include "qgspointsample.h"
2 #include "qgsgeometry.h"
3 #include "qgsspatialindex.h"
4 #include "qgsvectorfilewriter.h"
5 #include "qgsvectorlayer.h"
6 #include <QFile>
7 #include "mersenne-twister.h"
8 
9 
10 QgsPointSample::QgsPointSample( QgsVectorLayer* inputLayer, const QString& outputLayer, const QString& nPointsAttribute, const QString& minDistAttribute ): mInputLayer( inputLayer ),
11  mOutputLayer( outputLayer ), mNumberOfPointsAttribute( nPointsAttribute ), mMinDistanceAttribute( minDistAttribute ), mNCreatedPoints( 0 )
12 {
13 }
14 
16  : mInputLayer( nullptr )
17  , mNCreatedPoints( 0 )
18 {
19 }
20 
22 {
23  Q_UNUSED( pd );
24 
25  //create input layer from id (test if polygon, valid)
26  if ( !mInputLayer )
27  {
28  return 1;
29  }
30 
31  if ( mInputLayer->geometryType() != QGis::Polygon )
32  {
33  return 2;
34  }
35 
36  //delete output file if it already exists
37  if ( QFile::exists( mOutputLayer ) )
38  {
40  }
41 
42  //create vector file writer
43  QgsFields outputFields;
44  outputFields.append( QgsField( "id", QVariant::Int ) );
45  outputFields.append( QgsField( "station_id", QVariant::Int ) );
46  outputFields.append( QgsField( "stratum_id", QVariant::Int ) );
47  QgsVectorFileWriter writer( mOutputLayer, "UTF-8",
48  outputFields,
50  &( mInputLayer->crs() ) );
51 
52  //check if creation of output layer successfull
53  if ( writer.hasError() != QgsVectorFileWriter::NoError )
54  {
55  return 3;
56  }
57 
58  //init random number generator
59  mt_srand( QTime::currentTime().msec() );
60  QgsFeature fet;
61  int nPoints = 0;
62  double minDistance = 0;
63  mNCreatedPoints = 0;
64 
65  QgsFeatureIterator fIt = mInputLayer->getFeatures( QgsFeatureRequest().setSubsetOfAttributes(
66  QStringList() << mNumberOfPointsAttribute << mMinDistanceAttribute, mInputLayer->fields() ) );
67  while ( fIt.nextFeature( fet ) )
68  {
69  nPoints = fet.attribute( mNumberOfPointsAttribute ).toInt();
70  if ( !mMinDistanceAttribute.isEmpty() )
71  {
72  minDistance = fet.attribute( mMinDistanceAttribute ).toDouble();
73  }
74  addSamplePoints( fet, writer, nPoints, minDistance );
75  }
76 
77  return 0;
78 }
79 
80 void QgsPointSample::addSamplePoints( QgsFeature& inputFeature, QgsVectorFileWriter& writer, int nPoints, double minDistance )
81 {
82  if ( !inputFeature.constGeometry() )
83  return;
84 
85  const QgsGeometry* geom = inputFeature.constGeometry();
86  QgsRectangle geomRect = geom->boundingBox();
87  if ( geomRect.isEmpty() )
88  {
89  return;
90  }
91 
92  QgsSpatialIndex sIndex; //to check minimum distance
93  QMap< QgsFeatureId, QgsPoint > pointMapForFeature;
94 
95  int nIterations = 0;
96  int maxIterations = nPoints * 200;
97  int points = 0;
98 
99  double randX = 0;
100  double randY = 0;
101 
102  while ( nIterations < maxIterations && points < nPoints )
103  {
104  randX = (( double )mt_rand() / MD_RAND_MAX ) * geomRect.width() + geomRect.xMinimum();
105  randY = (( double )mt_rand() / MD_RAND_MAX ) * geomRect.height() + geomRect.yMinimum();
106  QgsPoint randPoint( randX, randY );
107  QgsGeometry* ptGeom = QgsGeometry::fromPoint( randPoint );
108  if ( ptGeom->within( geom ) && checkMinDistance( randPoint, sIndex, minDistance, pointMapForFeature ) )
109  {
110  //add feature to writer
111  QgsFeature f( mNCreatedPoints );
112  f.setAttribute( "id", mNCreatedPoints + 1 );
113  f.setAttribute( "station_id", points + 1 );
114  f.setAttribute( "stratum_id", inputFeature.id() );
115  f.setGeometry( ptGeom );
116  writer.addFeature( f );
117  sIndex.insertFeature( f );
118  pointMapForFeature.insert( mNCreatedPoints, randPoint );
119  ++points;
120  ++mNCreatedPoints;
121  }
122  else
123  {
124  delete ptGeom;
125  }
126  ++nIterations;
127  }
128 }
129 
130 bool QgsPointSample::checkMinDistance( QgsPoint& pt, QgsSpatialIndex& index, double minDistance, QMap< QgsFeatureId, QgsPoint >& pointMap )
131 {
132  if ( minDistance <= 0 )
133  {
134  return true;
135  }
136 
137  QList<QgsFeatureId> neighborList = index.nearestNeighbor( pt, 1 );
138  if ( neighborList.isEmpty() )
139  {
140  return true;
141  }
142 
143  QMap< QgsFeatureId, QgsPoint >::const_iterator it = pointMap.find( neighborList[0] );
144  if ( it == pointMap.constEnd() ) //should not happen
145  {
146  return true;
147  }
148 
149  QgsPoint neighborPt = it.value();
150  if ( neighborPt.sqrDist( pt ) < ( minDistance * minDistance ) )
151  {
152  return false;
153  }
154  return true;
155 }
156 
157 
158 
159 
QgsFeatureId id() const
Get the feature ID for this feature.
Definition: qgsfeature.cpp:65
Wrapper for iterator of features from vector data provider or vector layer.
static unsigned index
A rectangle specified with double values.
Definition: qgsrectangle.h:35
bool isEmpty() const
test if rectangle is empty.
int createRandomPoints(QProgressDialog *pd)
Starts calculation of random points.
static bool deleteShapeFile(const QString &theFileName)
Delete a shapefile (and its accompanying shx / dbf / prf)
QgsFields fields() const
Returns the list of fields of this layer.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest())
Query the provider for features specified in request.
QgsRectangle boundingBox() const
Returns the bounding box of this feature.
Container of fields for a vector layer.
Definition: qgsfield.h:187
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:76
bool setAttribute(int field, const QVariant &attr)
Set an attribute&#39;s value by field index.
Definition: qgsfeature.cpp:222
bool addFeature(QgsFeature &feature, QgsFeatureRendererV2 *renderer=nullptr, QGis::UnitType outputUnit=QGis::Meters)
Add feature to the currently opened data source.
bool exists() const
A convenience class for writing vector files to disk.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:187
double sqrDist(double x, double y) const
Returns the squared distance between this point and x,y.
Definition: qgspoint.cpp:345
#define MD_RAND_MAX
int mt_rand()
void setGeometry(const QgsGeometry &geom)
Set this feature&#39;s geometry from another QgsGeometry object.
Definition: qgsfeature.cpp:124
int toInt(bool *ok) const
double yMinimum() const
Get the y minimum value (bottom side of rectangle)
Definition: qgsrectangle.h:202
bool isEmpty() const
bool isEmpty() const
const_iterator constEnd() const
This class wraps a request for features to a vector layer (or directly its vector data provider)...
void mt_srand(unsigned value)
bool append(const QgsField &field, FieldOrigin origin=OriginProvider, int originIndex=-1)
Append a field. The field must have unique name, otherwise it is rejected (returns false) ...
Definition: qgsfield.cpp:309
const T & value() const
QGis::GeometryType geometryType() const
Returns point, line or polygon.
Encapsulate a field in an attribute table or data source.
Definition: qgsfield.h:44
A class to represent a point.
Definition: qgspoint.h:65
QList< QgsFeatureId > nearestNeighbor(const QgsPoint &point, int neighbors) const
Returns nearest neighbors (their count is specified by second parameter)
static QgsGeometry * fromPoint(const QgsPoint &point)
Creates a new geometry from a QgsPoint object.
QTime currentTime()
bool insertFeature(const QgsFeature &f)
Add feature to index.
WriterError hasError()
Checks whether there were any errors in constructor.
QVariant attribute(const QString &name) const
Lookup attribute value from attribute name.
Definition: qgsfeature.cpp:271
bool within(const QgsGeometry *geometry) const
Test for if geometry is within another (uses GEOS)
const QgsGeometry * constGeometry() const
Gets a const pointer to the geometry object associated with this feature.
Definition: qgsfeature.cpp:82
const QgsCoordinateReferenceSystem & crs() const
Returns layer&#39;s spatial reference system.
double toDouble(bool *ok) const
iterator insert(const Key &key, const T &value)
bool nextFeature(QgsFeature &f)
QgsPointSample(QgsVectorLayer *inputLayer, const QString &outputLayer, const QString &nPointsAttribute, const QString &minDistAttribute=QString())
double width() const
Width of the rectangle.
Definition: qgsrectangle.h:207
Represents a vector layer which manages a vector based data sets.
double xMinimum() const
Get the x minimum value (left side of rectangle)
Definition: qgsrectangle.h:192
iterator find(const Key &key)
double height() const
Height of the rectangle.
Definition: qgsrectangle.h:212