QGIS API Documentation 3.99.0-Master (2fe06baccd8)
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
26
27//
28// QgsNetworkAnalysisAlgorithmBase
29//
30
31QString QgsNetworkAnalysisAlgorithmBase::group() const
32{
33 return QObject::tr( "Network analysis" );
34}
35
36QString QgsNetworkAnalysisAlgorithmBase::groupId() const
37{
38 return QStringLiteral( "networkanalysis" );
39}
40
41Qgis::ProcessingAlgorithmFlags QgsNetworkAnalysisAlgorithmBase::flags() const
42{
43 // TODO -- remove the dependency on the project from these algorithms, it shouldn't be required
45}
46
47Qgis::ProcessingAlgorithmDocumentationFlags QgsNetworkAnalysisAlgorithmBase::documentationFlags() const
48{
50}
51
52void QgsNetworkAnalysisAlgorithmBase::addCommonParams()
53{
54 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Vector layer representing network" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) ) );
55 addParameter( new QgsProcessingParameterEnum( QStringLiteral( "STRATEGY" ), QObject::tr( "Path type to calculate" ), QStringList() << QObject::tr( "Shortest" ) << QObject::tr( "Fastest" ), false, 0 ) );
56
57 auto directionField = std::make_unique<QgsProcessingParameterField>( QStringLiteral( "DIRECTION_FIELD" ), QObject::tr( "Direction field" ), QVariant(), QStringLiteral( "INPUT" ), Qgis::ProcessingFieldParameterDataType::Any, false, true );
58 directionField->setFlags( directionField->flags() | Qgis::ProcessingParameterFlag::Advanced );
59 addParameter( directionField.release() );
60
61 auto forwardValue = std::make_unique<QgsProcessingParameterString>( QStringLiteral( "VALUE_FORWARD" ), QObject::tr( "Value for forward direction" ), QVariant(), false, true );
62 forwardValue->setFlags( forwardValue->flags() | Qgis::ProcessingParameterFlag::Advanced );
63 addParameter( forwardValue.release() );
64
65 auto backwardValue = std::make_unique<QgsProcessingParameterString>( QStringLiteral( "VALUE_BACKWARD" ), QObject::tr( "Value for backward direction" ), QVariant(), false, true );
66 backwardValue->setFlags( backwardValue->flags() | Qgis::ProcessingParameterFlag::Advanced );
67 addParameter( backwardValue.release() );
68
69 auto bothValue = std::make_unique<QgsProcessingParameterString>( QStringLiteral( "VALUE_BOTH" ), QObject::tr( "Value for both directions" ), QVariant(), false, true );
70 bothValue->setFlags( bothValue->flags() | Qgis::ProcessingParameterFlag::Advanced );
71 addParameter( bothValue.release() );
72
73 auto directionValue = std::make_unique<QgsProcessingParameterEnum>( QStringLiteral( "DEFAULT_DIRECTION" ), QObject::tr( "Default direction" ), QStringList() << QObject::tr( "Forward direction" ) << QObject::tr( "Backward direction" ) << QObject::tr( "Both directions" ), false, 2 );
74 directionValue->setFlags( directionValue->flags() | Qgis::ProcessingParameterFlag::Advanced );
75 addParameter( directionValue.release() );
76
77 auto speedField = std::make_unique<QgsProcessingParameterField>( QStringLiteral( "SPEED_FIELD" ), QObject::tr( "Speed field" ), QVariant(), QStringLiteral( "INPUT" ), Qgis::ProcessingFieldParameterDataType::Numeric, false, true );
78 speedField->setFlags( speedField->flags() | Qgis::ProcessingParameterFlag::Advanced );
79 addParameter( speedField.release() );
80
81 auto speed = std::make_unique<QgsProcessingParameterNumber>( QStringLiteral( "DEFAULT_SPEED" ), QObject::tr( "Default speed (km/h)" ), Qgis::ProcessingNumberParameterType::Double, 50, false, 0 );
82 speed->setFlags( speed->flags() | Qgis::ProcessingParameterFlag::Advanced );
83 addParameter( speed.release() );
84
85 std::unique_ptr<QgsProcessingParameterNumber> tolerance = std::make_unique<QgsProcessingParameterDistance>( QStringLiteral( "TOLERANCE" ), QObject::tr( "Topology tolerance" ), 0, QStringLiteral( "INPUT" ), false, 0 );
86 tolerance->setFlags( tolerance->flags() | Qgis::ProcessingParameterFlag::Advanced );
87 addParameter( tolerance.release() );
88}
89
90void QgsNetworkAnalysisAlgorithmBase::loadCommonParams( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
91{
92 Q_UNUSED( feedback )
93
94 mNetwork.reset( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
95 if ( !mNetwork )
96 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
97
98 const int strategy = parameterAsInt( parameters, QStringLiteral( "STRATEGY" ), context );
99 const QString directionFieldName = parameterAsString( parameters, QStringLiteral( "DIRECTION_FIELD" ), context );
100 const QString forwardValue = parameterAsString( parameters, QStringLiteral( "VALUE_FORWARD" ), context );
101 const QString backwardValue = parameterAsString( parameters, QStringLiteral( "VALUE_BACKWARD" ), context );
102 const QString bothValue = parameterAsString( parameters, QStringLiteral( "VALUE_BOTH" ), context );
103 const QgsVectorLayerDirector::Direction defaultDirection = static_cast<QgsVectorLayerDirector::Direction>( parameterAsInt( parameters, QStringLiteral( "DEFAULT_DIRECTION" ), context ) );
104 const QString speedFieldName = parameterAsString( parameters, QStringLiteral( "SPEED_FIELD" ), context );
105 const double defaultSpeed = parameterAsDouble( parameters, QStringLiteral( "DEFAULT_SPEED" ), context );
106 const double tolerance = parameterAsDouble( parameters, QStringLiteral( "TOLERANCE" ), context );
107
108 int directionField = -1;
109 if ( !directionFieldName.isEmpty() )
110 {
111 directionField = mNetwork->fields().lookupField( directionFieldName );
112 }
113
114 int speedField = -1;
115 if ( !speedFieldName.isEmpty() )
116 {
117 speedField = mNetwork->fields().lookupField( speedFieldName );
118 }
119
120 mDirector = new QgsVectorLayerDirector( mNetwork.get(), directionField, forwardValue, backwardValue, bothValue, defaultDirection );
121
122 const Qgis::DistanceUnit distanceUnits = context.project()->crs().mapUnits();
124
125 if ( strategy )
126 {
127 mDirector->addStrategy( new QgsNetworkSpeedStrategy( speedField, defaultSpeed, mMultiplier * 1000.0 / 3600.0 ) );
128 mMultiplier = 3600;
129 }
130 else
131 {
132 mDirector->addStrategy( new QgsNetworkDistanceStrategy() );
133 }
134
135 mBuilder = std::make_unique<QgsGraphBuilder>( mNetwork->sourceCrs(), true, tolerance, context.ellipsoid() );
136}
137
138void QgsNetworkAnalysisAlgorithmBase::loadPoints( QgsFeatureSource *source, QVector<QgsPointXY> *points, QHash<int, QgsAttributes> *attributes, QgsProcessingContext &context, QgsProcessingFeedback *feedback, QHash<int, QgsFeature> *featureHash )
139{
140 feedback->pushInfo( QObject::tr( "Loading points…" ) );
141
142 QgsFeature feat;
143 int i = 0;
144 int pointId = 1;
145 const double step = source->featureCount() > 0 ? 100.0 / source->featureCount() : 0;
146 QgsFeatureIterator features = source->getFeatures( QgsFeatureRequest().setDestinationCrs( mNetwork->sourceCrs(), context.transformContext() ) );
147
148 while ( features.nextFeature( feat ) )
149 {
150 i++;
151 if ( feedback->isCanceled() )
152 {
153 break;
154 }
155
156 feedback->setProgress( i * step );
157 if ( !feat.hasGeometry() )
158 continue;
159
160 const QgsGeometry geom = feat.geometry();
162 while ( it != geom.vertices_end() )
163 {
164 if ( points )
165 points->push_back( QgsPointXY( *it ) );
166 if ( attributes )
167 attributes->insert( pointId, feat.attributes() );
168 if ( featureHash )
169 featureHash->insert( pointId, feat );
170 it++;
171 pointId++;
172 }
173 }
174}
175
@ VectorLine
Vector line layers.
Definition qgis.h:3535
DistanceUnit
Units of distance.
Definition qgis.h:5013
@ Meters
Meters.
Definition qgis.h:5014
@ Numeric
Accepts numeric fields.
Definition qgis.h:3818
@ RespectsEllipsoid
Algorithm respects the context's ellipsoid settings, and uses ellipsoidal based measurements.
Definition qgis.h:3621
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3609
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3630
@ RequiresProject
The algorithm requires that a valid QgsProject is available from the processing context in order to e...
Definition qgis.h:3596
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3763
@ Double
Double/float values.
Definition qgis.h:3804
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:58
QgsAttributes attributes
Definition qgsfeature.h:67
QgsGeometry geometry
Definition qgsfeature.h:69
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:53
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:61
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:60
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.
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:115
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...