def processAlgorithm(self, parameters, context, feedback):
        feedback.pushInfo(self.tr('This is a QNEAT Algorithm'))
        network = self.parameterAsSource(parameters, self.INPUT, context) #QgsProcessingFeatureSource
        startPoints = self.parameterAsSource(parameters, self.START_POINTS, context) #QgsProcessingFeatureSource
        id_field = self.parameterAsString(parameters, self.ID_FIELD, context) #str
        max_dist = self.parameterAsDouble(parameters, self.MAX_DIST, context)#float
        strategy = self.parameterAsEnum(parameters, self.STRATEGY, context) #int

        directionFieldName = self.parameterAsString(parameters, self.DIRECTION_FIELD, context) #str (empty if no field given)
        forwardValue = self.parameterAsString(parameters, self.VALUE_FORWARD, context) #str
        backwardValue = self.parameterAsString(parameters, self.VALUE_BACKWARD, context) #str
        bothValue = self.parameterAsString(parameters, self.VALUE_BOTH, context) #str
        defaultDirection = self.parameterAsEnum(parameters, self.DEFAULT_DIRECTION, context) #int
        speedFieldName = self.parameterAsString(parameters, self.SPEED_FIELD, context) #str
        defaultSpeed = self.parameterAsDouble(parameters, self.DEFAULT_SPEED, context) #float
        tolerance = self.parameterAsDouble(parameters, self.TOLERANCE, context) #float

        analysisCrs = context.project().crs()
        input_coordinates = getListOfPoints(startPoints)
        
        net = Qneat3Network(network, input_coordinates, strategy, directionFieldName, forwardValue, backwardValue, bothValue, defaultDirection, analysisCrs, speedFieldName, defaultSpeed, tolerance, feedback)
        
        list_apoints = [Qneat3AnalysisPoint("from", feature, id_field, net.network, net.list_tiedPoints[i]) for i, feature in enumerate(getFeaturesFromQgsIterable(startPoints))]
        
        feedback.pushInfo("Calculating Iso-Pointcloud...")
        
        fields = QgsFields()
        fields.append(QgsField('vertex_id', QVariant.Int, '', 254, 0))
        fields.append(QgsField('cost', QVariant.Double, '', 254, 7))
        fields.append(QgsField('origin_point_id', getFieldDatatype(startPoints, id_field)))
        
        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context, fields, QgsWkbTypes.Point, network.sourceCrs())
        
        iso_pointcloud = net.calcIsoPoints(list_apoints, max_dist)
        
        sink.addFeatures(iso_pointcloud, QgsFeatureSink.FastInsert)
        
        feedback.pushInfo("Ending Algorithm")        
        
        results = {}
        results[self.OUTPUT] = dest_id
        return results
Example #2
0
    def __init__(
            self,
            input_network,  #QgsProcessingParameterFeatureSource
            input_points,  #[QgsPointXY] or QgsProcessingParameterFeatureSource or QgsVectorLayer --> Implement List of QgsFeatures [QgsFeatures]
            input_strategy,  #int
            input_directionFieldName,  #str, empty if field not given
            input_forwardValue,  #str
            input_backwardValue,  #str
            input_bothValue,  #str
            input_defaultDirection,  #int
            input_analysisCrs,  #QgsCoordinateReferenceSystem
            input_speedField,  #str
            input_defaultSpeed,  #float
            input_tolerance,  #float
            feedback  #feedback object from processing (log window)
    ):
        """
        Constructor for a Qneat3Network object.
        @type input_network: QgsProcessingParameterFeatureSource
        @param input_network: input network dataset from processing algorithm 
        @type input_points: QgsProcessingParameterFeatureSource/QgsVectorLayer/[QgsPointXY]
        @param input_points: input point dataset from processing algorithm
        @type input_strategy: int
        @param input_strategy: Strategy parameter (0 for distance evaluation, 1 time evaluation)
        @type directionFieldName: string
        @param directionFieldName: Field name of field containing direction information
        @type input_forwardValue: string
        @param input_forwardValue: Value assigned to forward-directed edges
        @type input_backwardValue: string
        @param input_backwardValue: Value assigned to backward-directed edges
        @type input_bothValue: string
        @param input_bothValues: Value assigned to undirected edges (accessible from both directions)
        @type input_defaultDirection: QgsVectorLayerDirector.DirectionForward/DirectionBackward/DirectionBoth
        @param input_defaultDirection: QgsVectorLayerDirector Direction enum to determine default direction
        @type input_analysisCrs: QgsCoordinateReferenceSystem
        @param input_analysisCrs: Analysis coordinate system
        @type input_speedField: string
        @param input_speedField: Field name of field containing speed information
        @type input_tolerance: float
        @param input_tolerance: tolerance value when connecting graph edges
        @type feedback: QgsProcessingFeedback
        @param feedback: feedback object from processing algorithm
        """

        #initialize feedback
        self.feedback = feedback

        self.feedback.pushInfo(
            "[QNEAT3Network][__init__] Setting up parameters")
        self.AnalysisCrs = input_analysisCrs

        #enable polygon calculation in geographic coordinate systems
        distUnit = self.AnalysisCrs.mapUnits()
        self.meter_to_unit_factor = QgsUnitTypes.fromUnitToUnitFactor(
            QgsUnitTypes.DistanceMeters, distUnit)

        #init direction fields
        self.feedback.pushInfo(
            "[QNEAT3Network][__init__] Setting up network direction parameters"
        )
        self.directedAnalysis = self.setNetworkDirection(
            (input_directionFieldName, input_forwardValue, input_backwardValue,
             input_bothValue, input_defaultDirection))
        self.director = QgsVectorLayerDirector(
            input_network,
            getFieldIndexFromQgsProcessingFeatureSource(
                input_network, input_directionFieldName), input_forwardValue,
            input_backwardValue, input_bothValue, input_defaultDirection)

        #init analysis points
        self.feedback.pushInfo(
            "[QNEAT3Network][__init__] Setting up analysis points")
        if isinstance(input_points, (list, )):
            self.list_input_points = input_points  #[QgsPointXY]
        else:
            self.list_input_points = getListOfPoints(
                input_points)  #[QgsPointXY]
            self.input_points = input_points

        #Setup cost-strategy pattern.
        self.feedback.pushInfo(
            "[QNEAT3Network][__init__] Setting analysis strategy: {}".format(
                input_strategy))
        self.default_speed = input_defaultSpeed

        self.setNetworkStrategy(input_strategy, input_network,
                                input_speedField, input_defaultSpeed)

        #add the strategy to the QgsGraphDirector
        self.director.addStrategy(self.strategy)
        self.builder = QgsGraphBuilder(self.AnalysisCrs)
        #tell the graph-director to make the graph using the builder object and tie the start point geometry to the graph

        self.feedback.pushInfo(
            "[QNEAT3Network][__init__] Start tying analysis points to the graph and building it."
        )
        self.feedback.pushInfo(
            "[QNEAT3Network][__init__] This is a compute intensive task and may take some time depending on network size"
        )
        start_local_time = time.localtime()
        start_time = time.time()
        self.feedback.pushInfo(
            "[QNEAT3Network][__init__] Start Time: {}".format(
                time.strftime(":%Y-%m-%d %H:%M:%S", start_local_time)))
        self.feedback.pushInfo("[QNEAT3Network][__init__] Building...")
        self.list_tiedPoints = self.director.makeGraph(self.builder,
                                                       self.list_input_points,
                                                       self.feedback)
        self.network = self.builder.graph()
        end_local_time = time.localtime()
        end_time = time.time()
        self.feedback.pushInfo("[QNEAT3Network][__init__] End Time: {}".format(
            time.strftime(":%Y-%m-%d %H:%M:%S", end_local_time)))
        self.feedback.pushInfo(
            "[QNEAT3Network][__init__] Total Build Time: {}".format(
                end_time - start_time))
        self.feedback.pushInfo(
            "[QNEAT3Network][__init__] Analysis setup complete")
    def processAlgorithm(self, parameters, context, feedback):
        feedback.pushInfo(
            self.tr(
                "[QNEAT3Algorithm] This is a QNEAT3 Algorithm: '{}'".format(
                    self.displayName())))
        network = self.parameterAsSource(parameters, self.INPUT,
                                         context)  #QgsProcessingFeatureSource
        startPoints = self.parameterAsSource(
            parameters, self.START_POINTS,
            context)  #QgsProcessingFeatureSource
        id_field = self.parameterAsString(parameters, self.ID_FIELD,
                                          context)  #str
        max_dist = self.parameterAsDouble(parameters, self.MAX_DIST,
                                          context)  #float
        cell_size = self.parameterAsInt(parameters, self.CELL_SIZE,
                                        context)  #int
        strategy = self.parameterAsEnum(parameters, self.STRATEGY,
                                        context)  #int

        directionFieldName = self.parameterAsString(
            parameters, self.DIRECTION_FIELD,
            context)  #str (empty if no field given)
        forwardValue = self.parameterAsString(parameters, self.VALUE_FORWARD,
                                              context)  #str
        backwardValue = self.parameterAsString(parameters, self.VALUE_BACKWARD,
                                               context)  #str
        bothValue = self.parameterAsString(parameters, self.VALUE_BOTH,
                                           context)  #str
        defaultDirection = self.parameterAsEnum(parameters,
                                                self.DEFAULT_DIRECTION,
                                                context)  #int
        speedFieldName = self.parameterAsString(parameters, self.SPEED_FIELD,
                                                context)  #str
        defaultSpeed = self.parameterAsDouble(parameters, self.DEFAULT_SPEED,
                                              context)  #float
        tolerance = self.parameterAsDouble(parameters, self.TOLERANCE,
                                           context)  #float
        output_path = self.parameterAsOutputLayer(parameters, self.OUTPUT,
                                                  context)

        analysisCrs = context.project().crs()
        input_coordinates = getListOfPoints(startPoints)

        feedback.pushInfo("[QNEAT3Algorithm] Building Graph...")
        feedback.setProgress(10)
        net = Qneat3Network(network, input_coordinates, strategy,
                            directionFieldName, forwardValue, backwardValue,
                            bothValue, defaultDirection, analysisCrs,
                            speedFieldName, defaultSpeed, tolerance, feedback)
        feedback.setProgress(40)

        list_apoints = [
            Qneat3AnalysisPoint("from", feature, id_field, net,
                                net.list_tiedPoints[i], feedback) for i,
            feature in enumerate(getFeaturesFromQgsIterable(startPoints))
        ]

        feedback.pushInfo("[QNEAT3Algorithm] Calculating Iso-Pointcloud...")
        iso_pointcloud = net.calcIsoPoints(list_apoints, max_dist)
        feedback.setProgress(70)

        uri = "Point?crs={}&field=vertex_id:int(254)&field=cost:double(254,7)&field=origin_point_id:string(254)&index=yes".format(
            analysisCrs.authid())

        iso_pointcloud_layer = QgsVectorLayer(uri, "iso_pointcloud_layer",
                                              "memory")
        iso_pointcloud_provider = iso_pointcloud_layer.dataProvider()
        iso_pointcloud_provider.addFeatures(iso_pointcloud,
                                            QgsFeatureSink.FastInsert)

        feedback.pushInfo(
            "[QNEAT3Algorithm] Calculating Iso-Interpolation-Raster using QGIS TIN-Interpolator..."
        )
        net.calcIsoTinInterpolation(iso_pointcloud_layer, cell_size,
                                    output_path)
        feedback.setProgress(99)

        feedback.pushInfo("[QNEAT3Algorithm] Ending Algorithm")
        feedback.setProgress(100)

        results = {}
        results[self.OUTPUT] = output_path
        return results
    def processAlgorithm(self, parameters, context, feedback):
        feedback.pushInfo(self.tr("[QNEAT3Algorithm] This is a QNEAT3 Algorithm: '{}'".format(self.displayName())))
        network = self.parameterAsSource(parameters, self.INPUT, context) #QgsProcessingFeatureSource
        startPoints = self.parameterAsSource(parameters, self.START_POINTS, context) #QgsProcessingFeatureSource
        id_field = self.parameterAsString(parameters, self.ID_FIELD, context) #str
        interval = self.parameterAsDouble(parameters, self.INTERVAL, context)#float
        max_dist = self.parameterAsDouble(parameters, self.MAX_DIST, context)#float
        cell_size = self.parameterAsInt(parameters, self.CELL_SIZE, context)#int
        strategy = self.parameterAsEnum(parameters, self.STRATEGY, context) #int

        directionFieldName = self.parameterAsString(parameters, self.DIRECTION_FIELD, context) #str (empty if no field given)
        forwardValue = self.parameterAsString(parameters, self.VALUE_FORWARD, context) #str
        backwardValue = self.parameterAsString(parameters, self.VALUE_BACKWARD, context) #str
        bothValue = self.parameterAsString(parameters, self.VALUE_BOTH, context) #str
        defaultDirection = self.parameterAsEnum(parameters, self.DEFAULT_DIRECTION, context) #int
        speedFieldName = self.parameterAsString(parameters, self.SPEED_FIELD, context) #str
        defaultSpeed = self.parameterAsDouble(parameters, self.DEFAULT_SPEED, context) #float
        tolerance = self.parameterAsDouble(parameters, self.TOLERANCE, context) #float
        output_path = self.parameterAsOutputLayer(parameters, self.OUTPUT_INTERPOLATION, context) #string

        analysisCrs = network.sourceCrs()
        input_coordinates = getListOfPoints(startPoints)

        if analysisCrs.isGeographic():
            raise QgsProcessingException('QNEAT3 algorithms are designed to work with projected coordinate systems. Please use a projected coordinate system (eg. UTM zones) instead of geographic coordinate systems (eg. WGS84)!')

        if analysisCrs != startPoints.sourceCrs():
            raise QgsProcessingException('QNEAT3 algorithms require that all inputs to be the same projected coordinate reference system (including project coordinate system).')

        feedback.pushInfo("[QNEAT3Algorithm] Building Graph...")
        feedback.setProgress(10)
        net = Qneat3Network(network, input_coordinates, strategy, directionFieldName, forwardValue, backwardValue, bothValue, defaultDirection, analysisCrs, speedFieldName, defaultSpeed, tolerance, feedback)
        feedback.setProgress(40)

        list_apoints = [Qneat3AnalysisPoint("from", feature, id_field, net, net.list_tiedPoints[i], feedback) for i, feature in enumerate(getFeaturesFromQgsIterable(startPoints))]

        feedback.pushInfo("[QNEAT3Algorithm] Calculating Iso-Pointcloud...")
        iso_pointcloud = net.calcIsoPoints(list_apoints, max_dist+(max_dist*0.1))
        feedback.setProgress(50)

        uri = "Point?crs={}&field=vertex_id:int(254)&field=cost:double(254,7)&field=origin_point_id:string(254)&index=yes".format(analysisCrs.authid())

        iso_pointcloud_layer = QgsVectorLayer(uri, "iso_pointcloud_layer", "memory")
        iso_pointcloud_provider = iso_pointcloud_layer.dataProvider()
        iso_pointcloud_provider.addFeatures(iso_pointcloud, QgsFeatureSink.FastInsert)

        feedback.pushInfo("[QNEAT3Algorithm] Calculating Iso-Interpolation-Raster using QGIS TIN-Interpolator...")
        net.calcIsoTinInterpolation(iso_pointcloud_layer, cell_size, output_path)
        feedback.setProgress(70)

        fields = QgsFields()
        fields.append(QgsField('id', QVariant.Int, '', 254, 0))
        fields.append(QgsField('cost_level', QVariant.Double, '', 20, 7))

        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT_CONTOURS, context, fields, QgsWkbTypes.LineString, network.sourceCrs())

        feedback.pushInfo("[QNEAT3Algorithm] Calculating Iso-Contours using numpy and matplotlib...")
        contour_featurelist = net.calcIsoContours(max_dist, interval, output_path)
        feedback.setProgress(90)

        sink.addFeatures(contour_featurelist, QgsFeatureSink.FastInsert)

        feedback.pushInfo("[QNEAT3Algorithm] Ending Algorithm")
        feedback.setProgress(100)

        results = {}
        results[self.OUTPUT_INTERPOLATION] = output_path
        results[self.OUTPUT_CONTOURS] = dest_id
        return results
    def processAlgorithm(self, parameters, context, feedback):
        feedback.pushInfo(
            self.tr(
                "[QNEAT3Algorithm] This is a QNEAT3 Algorithm: '{}'".format(
                    self.displayName())))
        network = self.parameterAsSource(parameters, self.INPUT,
                                         context)  #QgsProcessingFeatureSource
        from_points = self.parameterAsSource(
            parameters, self.FROM_POINT_LAYER,
            context)  #QgsProcessingFeatureSource
        from_id_field = self.parameterAsString(parameters, self.FROM_ID_FIELD,
                                               context)  #str
        to_points = self.parameterAsSource(parameters, self.TO_POINT_LAYER,
                                           context)
        to_id_field = self.parameterAsString(parameters, self.TO_ID_FIELD,
                                             context)
        strategy = self.parameterAsEnum(parameters, self.STRATEGY,
                                        context)  #int

        entry_cost_calc_method = self.parameterAsEnum(
            parameters, self.ENTRY_COST_CALCULATION_METHOD, context)  #int
        directionFieldName = self.parameterAsString(
            parameters, self.DIRECTION_FIELD,
            context)  #str (empty if no field given)
        forwardValue = self.parameterAsString(parameters, self.VALUE_FORWARD,
                                              context)  #str
        backwardValue = self.parameterAsString(parameters, self.VALUE_BACKWARD,
                                               context)  #str
        bothValue = self.parameterAsString(parameters, self.VALUE_BOTH,
                                           context)  #str
        defaultDirection = self.parameterAsEnum(parameters,
                                                self.DEFAULT_DIRECTION,
                                                context)  #int
        speedFieldName = self.parameterAsString(parameters, self.SPEED_FIELD,
                                                context)  #str
        defaultSpeed = self.parameterAsDouble(parameters, self.DEFAULT_SPEED,
                                              context)  #float
        tolerance = self.parameterAsDouble(parameters, self.TOLERANCE,
                                           context)  #float

        analysisCrs = network.sourceCrs()

        #Points of both layers have to be merged into one layer --> then tied to the Qneat3Network
        #get point list of from layer
        from_coord_list = getListOfPoints(from_points)
        from_coord_list_length = len(from_coord_list)
        to_coord_list = getListOfPoints(to_points)

        merged_coords = from_coord_list + to_coord_list

        feedback.pushInfo("[QNEAT3Algorithm] Building Graph...")
        net = Qneat3Network(network, merged_coords, strategy,
                            directionFieldName, forwardValue, backwardValue,
                            bothValue, defaultDirection, analysisCrs,
                            speedFieldName, defaultSpeed, tolerance, feedback)

        #read the merged point-list seperately for the two layers --> index at the first element of the second layer begins at len(firstLayer) and gets added the index of the current point of layer b.
        list_from_apoints = [
            Qneat3AnalysisPoint("from", feature, from_id_field, net,
                                net.list_tiedPoints[i], entry_cost_calc_method,
                                feedback) for i, feature in enumerate(
                                    getFeaturesFromQgsIterable(from_points))
        ]
        list_to_apoints = [
            Qneat3AnalysisPoint(
                "to", feature, to_id_field, net,
                net.list_tiedPoints[from_coord_list_length + i],
                entry_cost_calc_method, feedback)
            for i, feature in enumerate(getFeaturesFromQgsIterable(to_points))
        ]

        feat = QgsFeature()
        fields = QgsFields()
        output_id_field_data_type = getFieldDatatype(from_points,
                                                     from_id_field)
        fields.append(
            QgsField('origin_id', output_id_field_data_type, '', 254, 0))
        fields.append(
            QgsField('destination_id', output_id_field_data_type, '', 254, 0))
        fields.append(QgsField('entry_cost', QVariant.Double, '', 20, 7))
        fields.append(QgsField('network_cost', QVariant.Double, '', 20, 7))
        fields.append(QgsField('exit_cost', QVariant.Double, '', 20, 7))
        fields.append(QgsField('total_cost', QVariant.Double, '', 20, 7))
        feat.setFields(fields)

        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT,
                                               context, fields,
                                               QgsWkbTypes.LineString,
                                               network.sourceCrs())

        total_workload = float(len(from_coord_list) * len(to_coord_list))
        feedback.pushInfo(
            "[QNEAT3Algorithm] Expecting total workload of {} iterations".
            format(int(total_workload)))

        current_workstep_number = 0

        for start_point in list_from_apoints:
            #optimize in case of undirected (not necessary to call calcDijkstra as it has already been calculated - can be replaced by reading from list)
            dijkstra_query = net.calcDijkstra(start_point.network_vertex_id, 0)
            for query_point in list_to_apoints:
                if (current_workstep_number % 1000) == 0:
                    feedback.pushInfo(
                        "[QNEAT3Algorithm] {} OD-pairs processed...".format(
                            current_workstep_number))
                if dijkstra_query[0][query_point.network_vertex_id] == -1:
                    feat['origin_id'] = start_point.point_id
                    feat['destination_id'] = query_point.point_id
                    feat['entry_cost'] = None
                    feat['network_cost'] = None
                    feat['exit_cost'] = None
                    feat['total_cost'] = None
                    sink.addFeature(feat, QgsFeatureSink.FastInsert)
                else:
                    entry_cost = start_point.entry_cost
                    network_cost = dijkstra_query[1][
                        query_point.network_vertex_id]
                    exit_cost = query_point.entry_cost
                    total_cost = network_cost + entry_cost + exit_cost

                    feat.setGeometry(
                        QgsGeometry.fromPolylineXY(
                            [start_point.point_geom, query_point.point_geom]))
                    feat['origin_id'] = start_point.point_id
                    feat['destination_id'] = query_point.point_id
                    feat['entry_cost'] = entry_cost
                    feat['network_cost'] = network_cost
                    feat['exit_cost'] = exit_cost
                    feat['total_cost'] = total_cost
                    sink.addFeature(feat, QgsFeatureSink.FastInsert)
                current_workstep_number = current_workstep_number + 1
                feedback.setProgress(
                    (current_workstep_number / total_workload) * 100)

        feedback.pushInfo(
            "[QNEAT3Algorithm] Total number of OD-pairs processed: {}".format(
                current_workstep_number))

        feedback.pushInfo("[QNEAT3Algorithm] Ending Algorithm")

        results = {}
        results[self.OUTPUT] = dest_id
        return results
Example #6
0
    def __init__(self, 
                 input_network, #QgsProcessingParameterFeatureSource
                 input_points, #[QgsPointXY] or QgsProcessingParameterFeatureSource or QgsVectorLayer --> Implement List of QgsFeatures [QgsFeatures]
                 input_strategy, #int
                 input_directionFieldName, #str, empty if field not given
                 input_forwardValue, #str
                 input_backwardValue, #str
                 input_bothValue, #str
                 input_defaultDirection, #int
                 input_analysisCrs, #QgsCoordinateReferenceSystem
                 input_speedField, #str
                 input_defaultSpeed, #float
                 input_tolerance, #float
                 feedback #feedback object from processing (log window)
                 ): 
        
        #initialize feedback
        self.feedback = feedback
        
        self.feedback.pushInfo("[QNEAT3Network]: setting up parameters")
        self.AnalysisCrs = input_analysisCrs
        
        #init direction fields
        self.feedback.pushInfo("[QNEAT3Network]: setting up network direction parameters")
        self.directedAnalysis = self.setNetworkDirection((input_directionFieldName, input_forwardValue, input_backwardValue, input_bothValue, input_defaultDirection))
        self.director = QgsVectorLayerDirector(input_network,
                                    getFieldIndexFromQgsProcessingFeatureSource(input_network, input_directionFieldName),
                                    input_forwardValue,
                                    input_backwardValue,
                                    input_bothValue,
                                    input_defaultDirection)

        #init analysis points
        self.feedback.pushInfo("[QNEAT3Network]: setting up analysis points")
        if isinstance(input_points,(list,)):
            self.list_input_points = input_points #[QgsPointXY]
        else:
            self.list_input_points = getListOfPoints(input_points) #[QgsPointXY]
            self.input_points = input_points
    
        #Setup cost-strategy pattern.
        self.feedback.pushInfo("[QNEAT3Network]: Setting analysis strategy: {}".format(input_strategy))
        self.setNetworkStrategy(input_strategy, input_network, input_speedField, input_defaultSpeed)
        self.director.addStrategy(self.strategy)
        #add the strategy to the QgsGraphDirector
        self.director.addStrategy(self.strategy)
        self.builder = QgsGraphBuilder(self.AnalysisCrs)
        #tell the graph-director to make the graph using the builder object and tie the start point geometry to the graph
        
        self.feedback.pushInfo("[QNEAT3Network]: Start tying analysis points to the graph and building it.")
        self.feedback.pushInfo("...This is a compute intensive task and may take some time depending on network size")
        start_local_time = time.localtime()
        start_time = time.time()
        self.feedback.pushInfo("...Start Time: {}".format(time.strftime(":%Y-%m-%d %H:%M:%S", start_local_time)))
        self.list_tiedPoints = self.director.makeGraph(self.builder, self.list_input_points)
        self.network = self.builder.graph()
        end_local_time = time.localtime()
        end_time = time.time()
        self.feedback.pushInfo("...End Time: {}".format(time.strftime(":%Y-%m-%d %H:%M:%S", end_local_time)))
        self.feedback.pushInfo("...Total Build Time: {}".format(end_time-start_time))
        self.feedback.pushInfo("[QNEAT3Network]: Analysis setup complete")
Example #7
0
    def processAlgorithm(self, parameters, context, feedback):
        feedback.pushInfo(
            self.tr(
                "[QNEAT3Algorithm] This is a QNEAT3 Algorithm: '{}'".format(
                    self.displayName())))
        network = self.parameterAsSource(parameters, self.INPUT,
                                         context)  #QgsProcessingFeatureSource
        startPoints = self.parameterAsSource(
            parameters, self.START_POINTS,
            context)  #QgsProcessingFeatureSource
        id_field = self.parameterAsString(parameters, self.ID_FIELD,
                                          context)  #str
        max_dist = self.parameterAsDouble(parameters, self.MAX_DIST,
                                          context)  #float
        strategy = self.parameterAsEnum(parameters, self.STRATEGY,
                                        context)  #int

        directionFieldName = self.parameterAsString(
            parameters, self.DIRECTION_FIELD,
            context)  #str (empty if no field given)
        forwardValue = self.parameterAsString(parameters, self.VALUE_FORWARD,
                                              context)  #str
        backwardValue = self.parameterAsString(parameters, self.VALUE_BACKWARD,
                                               context)  #str
        bothValue = self.parameterAsString(parameters, self.VALUE_BOTH,
                                           context)  #str
        defaultDirection = self.parameterAsEnum(parameters,
                                                self.DEFAULT_DIRECTION,
                                                context)  #int
        speedFieldName = self.parameterAsString(parameters, self.SPEED_FIELD,
                                                context)  #str
        defaultSpeed = self.parameterAsDouble(parameters, self.DEFAULT_SPEED,
                                              context)  #float
        tolerance = self.parameterAsDouble(parameters, self.TOLERANCE,
                                           context)  #float

        analysisCrs = network.sourceCrs()
        input_coordinates = getListOfPoints(startPoints)

        if analysisCrs.isGeographic():
            raise QgsProcessingException(
                'QNEAT3 algorithms are designed to work with projected coordinate systems. Please use a projected coordinate system (eg. UTM zones) instead of geographic coordinate systems (eg. WGS84)!'
            )

        if analysisCrs != startPoints.sourceCrs():
            raise QgsProcessingException(
                'QNEAT3 algorithms require that all inputs to be the same projected coordinate reference system (including project coordinate system).'
            )

        feedback.pushInfo("[QNEAT3Algorithm] Building Graph...")
        feedback.setProgress(10)
        net = Qneat3Network(network, input_coordinates, strategy,
                            directionFieldName, forwardValue, backwardValue,
                            bothValue, defaultDirection, analysisCrs,
                            speedFieldName, defaultSpeed, tolerance, feedback)
        feedback.setProgress(40)

        list_apoints = [
            Qneat3AnalysisPoint("from", feature, id_field, net,
                                net.list_tiedPoints[i], feedback) for i,
            feature in enumerate(getFeaturesFromQgsIterable(startPoints))
        ]

        fields = QgsFields()
        fields.append(QgsField('vertex_id', QVariant.Int, '', 254, 0))
        fields.append(QgsField('cost', QVariant.Double, '', 254, 7))
        fields.append(
            QgsField('origin_point_id',
                     getFieldDatatype(startPoints, id_field)))

        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT,
                                               context, fields,
                                               QgsWkbTypes.Point,
                                               network.sourceCrs())

        feedback.pushInfo("[QNEAT3Algorithm] Calculating Iso-Pointcloud...")
        iso_pointcloud = net.calcIsoPoints(list_apoints, max_dist)
        feedback.setProgress(90)

        sink.addFeatures(iso_pointcloud, QgsFeatureSink.FastInsert)

        feedback.pushInfo("[QNEAT3Algorithm] Ending Algorithm")
        feedback.setProgress(100)

        results = {}
        results[self.OUTPUT] = dest_id
        return results