QGIS API Documentation 4.1.0-Master (5bf3c20f3c9)
Loading...
Searching...
No Matches
qgsalgorithmnetworkanalysisbase.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmnetworkanalysisbase.cpp
3 ---------------------
4 begin : July 2018
5 copyright : (C) 2018 by Alexander Bruy
6 email : alexander dot bruy at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
19
20#include "qgsgraphanalyzer.h"
23#include "qgsunittypes.h"
24
25#include <QString>
26
27using namespace Qt::StringLiterals;
28
30
31//
32// QgsNetworkAnalysisAlgorithmBase
33//
34
35QString QgsNetworkAnalysisAlgorithmBase::group() const
36{
37 return QObject::tr( "Network analysis" );
38}
39
40QString QgsNetworkAnalysisAlgorithmBase::groupId() const
41{
42 return u"networkanalysis"_s;
43}
44
45Qgis::ProcessingAlgorithmFlags QgsNetworkAnalysisAlgorithmBase::flags() const
46{
47 // TODO -- remove the dependency on the project from these algorithms, it shouldn't be required
49}
50
51Qgis::ProcessingAlgorithmDocumentationFlags QgsNetworkAnalysisAlgorithmBase::documentationFlags() const
52{
54}
55
56void QgsNetworkAnalysisAlgorithmBase::addCommonParams()
57{
58 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Vector layer representing network" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) ) );
59 addParameter( new QgsProcessingParameterEnum( u"STRATEGY"_s, QObject::tr( "Path type to calculate" ), QStringList() << QObject::tr( "Shortest" ) << QObject::tr( "Fastest" ), false, 0 ) );
60
61 auto directionField
62 = std::make_unique<QgsProcessingParameterField>( u"DIRECTION_FIELD"_s, QObject::tr( "Direction field" ), QVariant(), u"INPUT"_s, Qgis::ProcessingFieldParameterDataType::Any, false, true );
63 directionField->setHelp( QObject::tr( "The attribute field specifying the direction of traffic flow for each segment." ) );
64 directionField->setFlags( directionField->flags() | Qgis::ProcessingParameterFlag::Advanced );
65 addParameter( directionField.release() );
66
67 auto forwardValue = std::make_unique<QgsProcessingParameterString>( u"VALUE_FORWARD"_s, QObject::tr( "Value for forward direction" ), QVariant(), false, true );
68 forwardValue->setHelp( QObject::tr( "The string value in the direction field that indicates one-way traffic in the digitized direction." ) );
69 forwardValue->setFlags( forwardValue->flags() | Qgis::ProcessingParameterFlag::Advanced );
70 addParameter( forwardValue.release() );
71
72 auto backwardValue = std::make_unique<QgsProcessingParameterString>( u"VALUE_BACKWARD"_s, QObject::tr( "Value for backward direction" ), QVariant(), false, true );
73 backwardValue->setHelp( QObject::tr( "The string value in the direction field that indicates one-way traffic opposite to the digitized direction." ) );
74 backwardValue->setFlags( backwardValue->flags() | Qgis::ProcessingParameterFlag::Advanced );
75 addParameter( backwardValue.release() );
76
77 auto bothValue = std::make_unique<QgsProcessingParameterString>( u"VALUE_BOTH"_s, QObject::tr( "Value for both directions" ), QVariant(), false, true );
78 bothValue->setHelp( QObject::tr( "The string value in the direction field that indicates two-way traffic." ) );
79 bothValue->setFlags( bothValue->flags() | Qgis::ProcessingParameterFlag::Advanced );
80 addParameter( bothValue.release() );
81
82 auto directionValue = std::make_unique<
83 QgsProcessingParameterEnum>( u"DEFAULT_DIRECTION"_s, QObject::tr( "Default direction" ), QStringList() << QObject::tr( "Forward direction" ) << QObject::tr( "Backward direction" ) << QObject::tr( "Both directions" ), false, 2 );
84 directionValue->setFlags( directionValue->flags() | Qgis::ProcessingParameterFlag::Advanced );
85 addParameter( directionValue.release() );
86
87 auto speedField = std::make_unique<QgsProcessingParameterField>( u"SPEED_FIELD"_s, QObject::tr( "Speed field" ), QVariant(), u"INPUT"_s, Qgis::ProcessingFieldParameterDataType::Numeric, false, true );
88 speedField->setFlags( speedField->flags() | Qgis::ProcessingParameterFlag::Advanced );
89 addParameter( speedField.release() );
90
91 auto speed = std::make_unique<QgsProcessingParameterNumber>( u"DEFAULT_SPEED"_s, QObject::tr( "Default speed (km/h)" ), Qgis::ProcessingNumberParameterType::Double, 50, false, 0 );
92 speed->setFlags( speed->flags() | Qgis::ProcessingParameterFlag::Advanced );
93 addParameter( speed.release() );
94
95 std::unique_ptr<QgsProcessingParameterNumber> tolerance = std::make_unique<QgsProcessingParameterDistance>( u"TOLERANCE"_s, QObject::tr( "Topology tolerance" ), 0, u"INPUT"_s, false, 0 );
96 tolerance->setFlags( tolerance->flags() | Qgis::ProcessingParameterFlag::Advanced );
97 addParameter( tolerance.release() );
98}
99
100void QgsNetworkAnalysisAlgorithmBase::loadCommonParams( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
101{
102 Q_UNUSED( feedback )
103
104 mNetwork.reset( parameterAsSource( parameters, u"INPUT"_s, context ) );
105 if ( !mNetwork )
106 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
107
108 const int strategy = parameterAsInt( parameters, u"STRATEGY"_s, context );
109 const QString directionFieldName = parameterAsString( parameters, u"DIRECTION_FIELD"_s, context );
110 const QString forwardValue = parameterAsString( parameters, u"VALUE_FORWARD"_s, context );
111 const QString backwardValue = parameterAsString( parameters, u"VALUE_BACKWARD"_s, context );
112 const QString bothValue = parameterAsString( parameters, u"VALUE_BOTH"_s, context );
113 const QgsVectorLayerDirector::Direction defaultDirection = static_cast<QgsVectorLayerDirector::Direction>( parameterAsInt( parameters, u"DEFAULT_DIRECTION"_s, context ) );
114 const QString speedFieldName = parameterAsString( parameters, u"SPEED_FIELD"_s, context );
115 const double defaultSpeed = parameterAsDouble( parameters, u"DEFAULT_SPEED"_s, context );
116 const double tolerance = parameterAsDouble( parameters, u"TOLERANCE"_s, context );
117
118 int directionField = -1;
119 if ( !directionFieldName.isEmpty() )
120 {
121 directionField = mNetwork->fields().lookupField( directionFieldName );
122 }
123
124 int speedField = -1;
125 if ( !speedFieldName.isEmpty() )
126 {
127 speedField = mNetwork->fields().lookupField( speedFieldName );
128 }
129
130 mDirector = new QgsVectorLayerDirector( mNetwork.get(), directionField, forwardValue, backwardValue, bothValue, defaultDirection );
131
132 const Qgis::DistanceUnit distanceUnits = context.project()->crs().mapUnits();
134
135 if ( strategy )
136 {
137 mDirector->addStrategy( new QgsNetworkSpeedStrategy( speedField, defaultSpeed, mMultiplier * 1000.0 / 3600.0 ) );
138 mMultiplier = 3600;
139 }
140 else
141 {
142 mDirector->addStrategy( new QgsNetworkDistanceStrategy() );
143 }
144
145 mBuilder = std::make_unique<QgsGraphBuilder>( mNetwork->sourceCrs(), true, tolerance, context.ellipsoid() );
146}
147
148void QgsNetworkAnalysisAlgorithmBase::loadPoints(
149 QgsFeatureSource *source, QVector<QgsPointXY> *points, QHash<int, QgsAttributes> *attributes, QgsProcessingContext &context, QgsProcessingFeedback *feedback, QHash<int, QgsFeature> *featureHash
150)
151{
152 feedback->pushInfo( QObject::tr( "Loading points…" ) );
153
154 QgsFeature feat;
155 int i = 0;
156 int pointId = 1;
157 const double step = source->featureCount() > 0 ? 100.0 / source->featureCount() : 0;
158 QgsFeatureIterator features = source->getFeatures( QgsFeatureRequest().setDestinationCrs( mNetwork->sourceCrs(), context.transformContext() ) );
159
160 while ( features.nextFeature( feat ) )
161 {
162 i++;
163 if ( feedback->isCanceled() )
164 {
165 break;
166 }
167
168 feedback->setProgress( i * step );
169 if ( !feat.hasGeometry() )
170 continue;
171
172 const QgsGeometry geom = feat.geometry();
174 while ( it != geom.vertices_end() )
175 {
176 if ( points )
177 points->push_back( QgsPointXY( *it ) );
178 if ( attributes )
179 attributes->insert( pointId, feat.attributes() );
180 if ( featureHash )
181 featureHash->insert( pointId, feat );
182 it++;
183 pointId++;
184 }
185 }
186}
187
@ VectorLine
Vector line layers.
Definition qgis.h:3649
DistanceUnit
Units of distance.
Definition qgis.h:5170
@ Meters
Meters.
Definition qgis.h:5171
@ Numeric
Accepts numeric fields.
Definition qgis.h:3935
@ RespectsEllipsoid
Algorithm respects the context's ellipsoid settings, and uses ellipsoidal based measurements.
Definition qgis.h:3736
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3724
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3745
@ RequiresProject
The algorithm requires that a valid QgsProject is available from the processing context in order to e...
Definition qgis.h:3711
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3880
@ Double
Double/float values.
Definition qgis.h:3921
The vertex_iterator class provides an STL-style iterator for vertices.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
Wraps a request for features to a vector layer (or directly its vector data provider).
An interface for objects which provide features via a getFeatures method.
virtual QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const =0
Returns an iterator for the features in the source.
virtual long long featureCount() const =0
Returns the number of features contained in the source, or -1 if the feature count is unknown.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
QgsAttributes attributes
Definition qgsfeature.h:69
QgsGeometry geometry
Definition qgsfeature.h:71
bool hasGeometry() const
Returns true if the feature has an associated geometry.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:56
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:65
A geometry is the spatial representation of a feature.
QgsAbstractGeometry::vertex_iterator vertices_begin() const
Returns STL-style iterator pointing to the first vertex of the geometry.
QgsAbstractGeometry::vertex_iterator vertices_end() const
Returns STL-style iterator pointing to the imaginary vertex after the last vertex of the geometry.
Strategy for calculating edge cost based on its length.
Strategy for calculating edge cost based on travel time.
Represents a 2D point.
Definition qgspointxy.h:62
virtual Qgis::ProcessingAlgorithmFlags flags() const
Returns the flags indicating how and when the algorithm operates and should be exposed to users.
Contains information about the context in which a processing algorithm is executed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
QgsProject * project() const
Returns the project in which the algorithm is being executed.
QString ellipsoid() const
Returns the ellipsoid to use for distance and area calculations.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
void setFlags(Qgis::ProcessingParameterFlags flags)
Sets the flags associated with the parameter.
An enum based parameter for processing algorithms, allowing for selection from predefined values.
An input feature source (such as vector layers) parameter for processing algorithms.
QgsCoordinateReferenceSystem crs
Definition qgsproject.h:119
static Q_INVOKABLE double fromUnitToUnitFactor(Qgis::DistanceUnit fromUnit, Qgis::DistanceUnit toUnit)
Returns the conversion factor between the specified distance units.
Determines creating a graph from a vector line layer.
Direction
Edge direction Edge can be one-way with direct flow (one can move only from the start point to the en...