def processAlgorithm(self, parameters, context, feedback): feedback.pushInfo(self.tr('This is a QNEAT Algorithm')) network = self.parameterAsSource(parameters, self.INPUT, context) #QgsProcessingFeatureSource points = self.parameterAsSource(parameters, self.POINTS, context) #QgsProcessingFeatureSource id_field = self.parameterAsString(parameters, self.ID_FIELD, context) #str 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.parameterAsFileOutput(parameters, self.OUTPUT, context) #str (filepath) feedback.pushInfo(pluginPath) analysisCrs = context.project().crs() net = Qneat3Network(network, points, strategy, directionFieldName, forwardValue, backwardValue, bothValue, defaultDirection, analysisCrs, speedFieldName, defaultSpeed, tolerance, feedback) list_analysis_points = [Qneat3AnalysisPoint("point", feature, id_field, net.network, net.list_tiedPoints[i]) for i, feature in enumerate(getFeaturesFromQgsIterable(net.input_points))] total_workload = float(pow(len(list_analysis_points),2)) feedback.pushInfo("Expecting total workload of {} iterations".format(int(total_workload))) with open(output_path, 'w', newline='') as csvfile: csv_writer = csv.writer(csvfile, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL) #write header csv_writer.writerow(["origin_id","destination_id","cost"]) current_workstep_number = 0 for start_point in list_analysis_points: #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_analysis_points: if (current_workstep_number%1000)==0: feedback.pushInfo("{} OD-pairs processed...".format(current_workstep_number)) if query_point.point_id == start_point.point_id: csv_writer.writerow([start_point.point_id, query_point.point_id, float(0)]) elif dijkstra_query[0][query_point.network_vertex_id] == -1: csv_writer.writerow([start_point.point_id, query_point.point_id, None]) else: entry_cost = start_point.calcEntryCost(strategy)+query_point.calcEntryCost(strategy) total_cost = dijkstra_query[1][query_point.network_vertex_id]+entry_cost csv_writer.writerow([start_point.point_id, query_point.point_id, total_cost]) current_workstep_number=current_workstep_number+1 feedback.setProgress(current_workstep_number/total_workload) feedback.pushInfo("Total number of OD-pairs processed: {}".format(current_workstep_number)) feedback.pushInfo("Initialization Done") feedback.pushInfo("Ending Algorithm") 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 startPoint = self.parameterAsPoint(parameters, self.START_POINT, context, network.sourceCrs()) #QgsPointXY max_dist = self.parameterAsDouble(parameters, self.MAX_DIST, context)#float 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() input_coordinates = [startPoint] input_point = getFeatureFromPointParameter(startPoint) 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) analysis_point = Qneat3AnalysisPoint("point", input_point, "point_id", net, net.list_tiedPoints[0], entry_cost_calc_method, feedback) 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',QVariant.String, '', 254, 7)) (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context, fields, QgsWkbTypes.Point, network.sourceCrs()) feedback.pushInfo("[QNEAT3Algorithm] Calculating Iso-Pointcloud...") iso_pointcloud = net.calcIsoPoints([analysis_point], 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
def processAlgorithm(self, parameters, context, feedback): feedback.pushInfo(self.tr('This is a QNEAT Algorithm')) network = self.parameterAsSource(parameters, self.INPUT, context) #QgsProcessingFeatureSource startPoint = self.parameterAsPoint(parameters, self.START_POINT, context, network.sourceCrs()) #QgsPointXY max_dist = self.parameterAsDouble(parameters, self.MAX_DIST, context)#float interval = self.parameterAsDouble(parameters, self.INTERVAL, 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 = [startPoint] input_point = getFeatureFromPointParameter(startPoint) net = Qneat3Network(network, input_coordinates, strategy, directionFieldName, forwardValue, backwardValue, bothValue, defaultDirection, analysisCrs, speedFieldName, defaultSpeed, tolerance, feedback) analysis_point = Qneat3AnalysisPoint("point", input_point, "point_id", net.network, net.list_tiedPoints[0]) start_vertex_idx = analysis_point.network_vertex_id feedback.pushInfo("Calculating Iso-Pointcloud...") fields = QgsFields() fields.append(QgsField('vertex_id', QVariant.Int, '', 254, 0)) fields.append(QgsField('cost', QVariant.Double, '', 254, 7)) (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context, fields, QgsWkbTypes.Point, network.sourceCrs()) #dijkstra_query = net.calcDijkstra(start_vertex_idx, 0) iso_pointcloud = net.calcIsoPoints([analysis_point], max_dist) sink.addFeatures(iso_pointcloud, QgsFeatureSink.FastInsert) feedback.pushInfo("Ending Algorithm") results = {} results[self.OUTPUT] = dest_id return results
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
def processAlgorithm(self, parameters, context, feedback): feedback.pushInfo( self.tr( "[QNEAT3Algorithm] This is a QNEAT3 Algorithm: '{}'".format( self.displayName()))) feedback.pushInfo(self.tr('[QNEAT3Algorithm] Initializing Variables')) network = self.parameterAsSource(parameters, self.INPUT, context) #QgsProcessingFeatureSource startPoint = self.parameterAsPoint(parameters, self.START_POINT, context, network.sourceCrs()) #QgsPointXY endPoint = self.parameterAsPoint(parameters, self.END_POINT, context, network.sourceCrs()) #QgsPointXY 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() input_qgspointxy_list = [startPoint, endPoint] input_points = [ getFeatureFromPointParameter(startPoint), getFeatureFromPointParameter(endPoint) ] feedback.pushInfo(self.tr('[QNEAT3Algorithm] Building Graph')) feedback.setProgress(10) net = Qneat3Network(network, input_qgspointxy_list, strategy, directionFieldName, forwardValue, backwardValue, bothValue, defaultDirection, analysisCrs, speedFieldName, defaultSpeed, tolerance, feedback) feedback.setProgress(40) list_analysis_points = [ Qneat3AnalysisPoint("point", feature, "point_id", net, net.list_tiedPoints[i], entry_cost_calc_method, feedback) for i, feature in enumerate(input_points) ] start_vertex_idx = list_analysis_points[0].network_vertex_id end_vertex_idx = list_analysis_points[1].network_vertex_id feedback.pushInfo("[QNEAT3Algorithm] Calculating shortest path...") feedback.setProgress(50) dijkstra_query = net.calcDijkstra(start_vertex_idx, 0) if dijkstra_query[0][end_vertex_idx] == -1: raise QgsProcessingException( self. tr('Could not find a path from start point to end point - Check your graph or alter the input points.' )) path_elements = [list_analysis_points[1].point_geom ] #start route with the endpoint outside the network path_elements.append(net.network.vertex(end_vertex_idx).point( )) #then append the corresponding vertex of the graph count = 1 current_vertex_idx = end_vertex_idx while current_vertex_idx != start_vertex_idx: current_vertex_idx = net.network.edge( dijkstra_query[0][current_vertex_idx]).fromVertex() path_elements.append( net.network.vertex(current_vertex_idx).point()) count = count + 1 if count % 10 == 0: feedback.pushInfo( "[QNEAT3Algorithm] Taversed {} Nodes...".format(count)) path_elements.append(list_analysis_points[0].point_geom ) #end path with startpoint outside the network feedback.pushInfo( "[QNEAT3Algorithm] Total number of Nodes traversed: {}".format( count + 1)) path_elements.reverse( ) #reverse path elements because it was built from end to start start_entry_cost = list_analysis_points[0].entry_cost end_exit_cost = list_analysis_points[1].entry_cost cost_on_graph = dijkstra_query[1][end_vertex_idx] total_cost = start_entry_cost + cost_on_graph + end_exit_cost feedback.pushInfo("[QNEAT3Algorithm] Writing path-feature...") feedback.setProgress(80) feat = QgsFeature() fields = QgsFields() fields.append(QgsField('start_id', QVariant.String, '', 254, 0)) fields.append( QgsField('start_coordinates', QVariant.String, '', 254, 0)) fields.append(QgsField('start_entry_cost', QVariant.Double, '', 20, 7)) fields.append(QgsField('end_id', QVariant.String, '', 254, 0)) fields.append(QgsField('end_coordinates', QVariant.String, '', 254, 0)) fields.append(QgsField('end_exit_cost', QVariant.Double, '', 20, 7)) fields.append(QgsField('cost_on_graph', 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()) feat['start_id'] = "A" feat['start_coordinates'] = startPoint.toString() feat['start_entry_cost'] = start_entry_cost feat['end_id'] = "B" feat['end_coordinates'] = endPoint.toString() feat['end_exit_cost'] = end_exit_cost feat['cost_on_graph'] = cost_on_graph feat['total_cost'] = total_cost geom = QgsGeometry.fromPolylineXY(path_elements) feat.setGeometry(geom) sink.addFeature(feat, QgsFeatureSink.FastInsert) feedback.pushInfo("[QNEAT3Algorithm] Ending Algorithm") feedback.setProgress(100) results = {} results[self.OUTPUT] = 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 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 startPoint = self.parameterAsPoint(parameters, self.START_POINT, context, network.sourceCrs()) #QgsPointXY 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 = [startPoint] input_point = getFeatureFromPointParameter(startPoint) 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) analysis_point = Qneat3AnalysisPoint("point", input_point, "point_id", net, net.list_tiedPoints[0], feedback) feedback.pushInfo("[QNEAT3Algorithm] Calculating Iso-Pointcloud...") iso_pointcloud = net.calcIsoPoints([analysis_point], 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_POLYGONS, context, fields, QgsWkbTypes.Polygon, network.sourceCrs()) feedback.pushInfo( "[QNEAT3Algorithm] Calculating Iso-Polygons using numpy and matplotlib..." ) polygon_featurelist = net.calcIsoPolygons(max_dist, interval, output_path) feedback.setProgress(90) sink.addFeatures(polygon_featurelist, QgsFeatureSink.FastInsert) feedback.pushInfo("[QNEAT3Algorithm] Ending Algorithm") feedback.setProgress(100) results = {} results[self.OUTPUT_INTERPOLATION] = output_path results[self.OUTPUT_POLYGONS] = 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 startPoint = self.parameterAsPoint(parameters, self.START_POINT, context, network.sourceCrs()) #QgsPointXY 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 = [startPoint] input_point = getFeatureFromPointParameter(startPoint) 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 != context.project().crs(): 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) analysis_point = Qneat3AnalysisPoint("point", input_point, "point_id", net, net.list_tiedPoints[0], feedback) 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', QVariant.String, '', 254, 7)) (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context, fields, QgsWkbTypes.Point, network.sourceCrs()) feedback.pushInfo("[QNEAT3Algorithm] Calculating Iso-Pointcloud...") iso_pointcloud = net.calcIsoPoints([analysis_point], 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
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 points = self.parameterAsSource(parameters, self.POINTS, context) #QgsProcessingFeatureSource id_field = self.parameterAsString(parameters, self.ID_FIELD, context) #str 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() 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 != points.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...") net = Qneat3Network(network, points, strategy, directionFieldName, forwardValue, backwardValue, bothValue, defaultDirection, analysisCrs, speedFieldName, defaultSpeed, tolerance, feedback) list_analysis_points = [ Qneat3AnalysisPoint("point", feature, id_field, net, net.list_tiedPoints[i], feedback) for i, feature in enumerate( getFeaturesFromQgsIterable(net.input_points)) ] feat = QgsFeature() fields = QgsFields() output_id_field_data_type = getFieldDatatype(points, id_field) fields.append( QgsField('InputID', output_id_field_data_type, '', 254, 0)) fields.append( QgsField('TargetID', 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(pow(len(list_analysis_points), 2)) feedback.pushInfo( "[QNEAT3Algorithm] Expecting total workload of {} iterations". format(int(total_workload))) current_workstep_number = 0 for start_point in list_analysis_points: #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_analysis_points: if (current_workstep_number % 1000) == 0: feedback.pushInfo( "[QNEAT3Algorithm] {} OD-pairs processed...".format( current_workstep_number)) if query_point.point_id == start_point.point_id: feat['InputID'] = start_point.point_id feat['TargetID'] = query_point.point_id feat['entry_cost'] = 0.0 feat['network_cost'] = 0.0 feat['exit_cost'] = 0.0 feat['total_cost'] = 0.0 sink.addFeature(feat, QgsFeatureSink.FastInsert) elif dijkstra_query[0][query_point.network_vertex_id] == -1: feat['InputID'] = start_point.point_id feat['TargetID'] = query_point.point_id #do not populate cost field so that it defaults to null sink.addFeature(feat, QgsFeatureSink.FastInsert) else: network_cost = dijkstra_query[1][ query_point.network_vertex_id] feat.setGeometry( QgsGeometry.fromPolylineXY( [start_point.point_geom, query_point.point_geom])) feat['InputID'] = start_point.point_id feat['TargetID'] = query_point.point_id feat['entry_cost'] = start_point.entry_cost feat['network_cost'] = network_cost feat['exit_cost'] = query_point.entry_cost feat[ 'total_cost'] = network_cost + start_point.entry_cost + query_point.entry_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
def processAlgorithm(self, parameters, context, feedback): feedback.pushInfo(self.tr('This is a QNEAT Algorithm')) network = self.parameterAsSource(parameters, self.INPUT, context) #QgsProcessingFeatureSource points = self.parameterAsSource(parameters, self.POINTS, context) #QgsProcessingFeatureSource id_field = self.parameterAsString(parameters, self.ID_FIELD, context) #str 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() net = Qneat3Network(network, points, strategy, directionFieldName, forwardValue, backwardValue, bothValue, defaultDirection, analysisCrs, speedFieldName, defaultSpeed, tolerance, feedback) list_analysis_points = [Qneat3AnalysisPoint("point", feature, id_field, net.network, net.list_tiedPoints[i]) for i, feature in enumerate(getFeaturesFromQgsIterable(net.input_points))] feat = QgsFeature() fields = QgsFields() output_id_field_data_type = getFieldDatatype(points, 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('network_cost', QVariant.Double, '', 20, 7)) feat.setFields(fields) (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context, fields, QgsWkbTypes.NoGeometry, network.sourceCrs()) total_workload = float(pow(len(list_analysis_points),2)) feedback.pushInfo("Expecting total workload of {} iterations".format(int(total_workload))) current_workstep_number = 0 for start_point in list_analysis_points: #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_analysis_points: if (current_workstep_number%1000)==0: feedback.pushInfo("{} OD-pairs processed...".format(current_workstep_number)) if query_point.point_id == start_point.point_id: feat['origin_id'] = start_point.point_id feat['destination_id'] = query_point.point_id feat['network_cost'] = 0.0 sink.addFeature(feat, QgsFeatureSink.FastInsert) elif dijkstra_query[0][query_point.network_vertex_id] == -1: feat['origin_id'] = start_point.point_id feat['destination_id'] = query_point.point_id #do not populate cost field so that it defaults to null sink.addFeature(feat, QgsFeatureSink.FastInsert) else: entry_cost = start_point.calcEntryCost(strategy)+query_point.calcEntryCost(strategy) total_cost = dijkstra_query[1][query_point.network_vertex_id]+entry_cost feat['origin_id'] = start_point.point_id feat['destination_id'] = query_point.point_id feat['network_cost'] = total_cost sink.addFeature(feat, QgsFeatureSink.FastInsert) current_workstep_number=current_workstep_number+1 feedback.setProgress(current_workstep_number/total_workload) feedback.pushInfo("Total number of OD-pairs processed: {}".format(current_workstep_number)) feedback.pushInfo("Initialization Done") feedback.pushInfo("Ending Algorithm") results = {} results[self.OUTPUT] = 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 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
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 startPoint = self.parameterAsPoint(parameters, self.START_POINT, context, network.sourceCrs()) #QgsPointXY 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 interpolation_method = self.parameterasEnum(parameters, self.METHOD, 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 output_path = self.parameterAsOutputLayer(parameters, self.OUTPUT, context) analysisCrs = network.sourceCrs() input_coordinates = [startPoint] input_point = getFeatureFromPointParameter(startPoint) 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) analysis_point = Qneat3AnalysisPoint("point", input_point, "point_id", net, net.list_tiedPoints[0], entry_cost_calc_method, feedback) feedback.pushInfo("[QNEAT3Algorithm] Calculating Iso-Pointcloud...") iso_pointcloud = net.calcIsoPoints([analysis_point], 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..." ) if interpolation_method == 0: feedback.pushInfo( "[QNEAT3Algorithm] Calculating Iso-Interpolation-Raster using QGIS TIN-Interpolator..." ) net.calcIsoTinInterpolation(iso_pointcloud_layer, cell_size, output_path) feedback.setProgress(99) else: #implement spatial index for lines (closest line, etc...) spt_idx = QgsSpatialIndex( iso_pointcloud_layer.getFeatures(QgsFeatureRequest()), self.feedback) #prepare numpy coordinate grids NoData_value = -9999 raster_rectangle = iso_pointcloud_layer.extent() #top left point xmin = raster_rectangle.xMinimum() ymin = raster_rectangle.yMinimum() xmax = raster_rectangle.xMaximum() ymax = raster_rectangle.yMaximum() cols = int((xmax - xmin) / cell_size) rows = int((ymax - ymin) / cell_size) output_interpolation_raster = gdal.GetDriverByName('GTiff').Create( output_path, cols, rows, 1, gdal.GDT_Float64) output_interpolation_raster.SetGeoTransform( (xmin, cell_size, 0, ymax, 0, -cell_size)) band = output_interpolation_raster.GetRasterBand(1) band.SetNoDataValue(NoData_value) #initialize zero array with 2 dimensions (according to rows and cols) raster_routingcost_data = zeros(shape=(rows, cols)) #compute raster cell MIDpoints x_pos = linspace(xmin + (cell_size / 2), xmax - (cell_size / 2), raster_routingcost_data.shape[1]) y_pos = linspace(ymax - (cell_size / 2), ymin + (cell_size / 2), raster_routingcost_data.shape[0]) x_grid, y_grid = meshgrid(x_pos, y_pos) gridpoint_list = array( list(zip(x_grid.flatten(), y_grid.flatten()))) list_cellpoints_interpolation = [ QgsPointXY(coords[0], coords[1]) for coords in gridpoint_list ] list_cellpoints_interpolation.insert(0, startPoint) iso_net = Qneat3Network(network, list_cellpoints_interpolation, strategy, directionFieldName, forwardValue, backwardValue, bothValue, defaultDirection, analysisCrs, speedFieldName, defaultSpeed, tolerance, feedback) iso_analysis_start_point = Qneat3AnalysisPoint( "point", input_point, "point_id", iso_net, iso_net.list_tiedPoints[0], entry_cost_calc_method, feedback) #add 1 because of iso_analysis_start_point that is prepended list_to_apoints = [ Qneat3AnalysisPoint("to", feature, "vertex_id", iso_net, iso_net.list_tiedPoints[1 + i], entry_cost_calc_method, feedback) for i, feature in enumerate( getFeaturesFromQgsIterable(iso_pointcloud_layer)) ] total_workload = float(len(list_to_apoints)) current_point_index = 0 #raster data indices dijkstra_query = net.calcDijkstra( iso_analysis_start_point.network_vertex_id, 0) i = 0 while i < len(raster_routingcost_data): j = 0 while j < len(raster_routingcost_data[i]): if (current_point_index % 1000) == 0: feedback.pushInfo( "[QNEAT3Algorithm] {} cells interpolated...". format(current_point_index)) if dijkstra_query[0][list_to_apoints[current_point_index]. network_vertex_id] == -1: #write nodata to raster raster_routingcost_data[i][j] = -9999 else: network_cost = dijkstra_query[1][list_to_apoints[ current_point_index].network_vertex_id] raster_routingcost_data[i][ j] = iso_analysis_start_point.entry_cost + network_cost + list_to_apoints[ current_point_index].entry_cost current_point_index = current_point_index + 1 feedback.setProgress( (current_point_index / total_workload) * 100) j = j + 1 i = i + 1 band.WriteArray(raster_routingcost_data) outRasterSRS = osr.SpatialReference() outRasterSRS.ImportFromWkt(self.AnalysisCrs.toWkt()) output_interpolation_raster.SetProjection( outRasterSRS.ExportToWkt()) band.FlushCache() 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.parameterAsVectorLayer(parameters, self.INPUT, context) #QgsVectorLayer startPoint = self.parameterAsPoint(parameters, self.START_POINT, context, network.sourceCrs()) #QgsPointXY 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 interpolation_method = self.parameterAsEnum(parameters, self.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 output_path = self.parameterAsOutputLayer(parameters, self.OUTPUT, context) analysisCrs = network.sourceCrs() input_coordinates = [startPoint] input_point = getFeatureFromPointParameter(startPoint) 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 != startPoint.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) analysis_point = Qneat3AnalysisPoint("point", input_point, "point_id", net, net.list_tiedPoints[0], feedback) feedback.pushInfo("[QNEAT3Algorithm] Calculating Iso-Pointcloud...") iso_pointcloud = net.calcIsoPoints([analysis_point], 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..." ) if interpolation_method == 0: feedback.pushInfo( "[QNEAT3Algorithm] Calculating Iso-Interpolation-Raster using QGIS TIN-Interpolator..." ) net.calcIsoTinInterpolation(iso_pointcloud_layer, cell_size, output_path) feedback.setProgress(99) else: #prepare numpy coordinate grids NoData_value = -9999 raster_rectangle = iso_pointcloud_layer.extent() #implement spatial index for lines (closest line, etc...) spt_idx = QgsSpatialIndex( iso_pointcloud_layer.getFeatures(QgsFeatureRequest()), feedback) #top left point xmin = raster_rectangle.xMinimum() ymin = raster_rectangle.yMinimum() xmax = raster_rectangle.xMaximum() ymax = raster_rectangle.yMaximum() cols = int((xmax - xmin) / cell_size) rows = int((ymax - ymin) / cell_size) output_interpolation_raster = gdal.GetDriverByName('GTiff').Create( output_path, cols, rows, 1, gdal.GDT_Float64) output_interpolation_raster.SetGeoTransform( (xmin, cell_size, 0, ymax, 0, -cell_size)) band = output_interpolation_raster.GetRasterBand(1) band.SetNoDataValue(NoData_value) #initialize zero array with 2 dimensions (according to rows and cols) raster_routingcost_data = zeros(shape=(rows, cols)) #compute raster cell MIDpoints x_pos = linspace(xmin + (cell_size / 2), xmax - (cell_size / 2), raster_routingcost_data.shape[1]) y_pos = linspace(ymax - (cell_size / 2), ymin + (cell_size / 2), raster_routingcost_data.shape[0]) x_grid, y_grid = meshgrid(x_pos, y_pos) feedback.pushInfo( '[QNEAT3Network][calcQneatInterpolation] Beginning with interpolation' ) total_work = rows * cols counter = 0 feedback.pushInfo( '[QNEAT3Network][calcQneatInterpolation] Total workload: {} cells' .format(total_work)) feedback.setProgress(0) for i in range(rows): for j in range(cols): current_pixel_midpoint = QgsPointXY( x_grid[i, j], y_grid[i, j]) nearest_vertex_fid = spt_idx.nearestNeighbor( current_pixel_midpoint, 1)[0] nearest_feature = iso_pointcloud_layer.getFeature( nearest_vertex_fid) nearest_vertex = net.network.vertex( nearest_feature['vertex_id']) #yields a list of all incoming and outgoing edges edges = nearest_vertex.incomingEdges( ) + nearest_vertex.outgoingEdges() vertex_found = False nearest_counter = 2 while vertex_found == False: #find the second nearest vertex (eg, the vertex with least cost of all edges incoming to the first nearest vertex) second_nearest_feature_fid = spt_idx.nearestNeighbor( current_pixel_midpoint, nearest_counter)[nearest_counter - 1] second_nearest_feature = iso_pointcloud_layer.getFeature( second_nearest_feature_fid) second_nearest_vertex_id = second_nearest_feature[ 'vertex_id'] for edge_id in edges: from_vertex_id = net.network.edge( edge_id).fromVertex() to_vertex_id = net.network.edge(edge_id).toVertex() if second_nearest_vertex_id == from_vertex_id: vertex_found = True vertex_type = "from_vertex" from_point = second_nearest_feature.geometry( ).asPoint() from_vertex_cost = second_nearest_feature[ 'cost'] if second_nearest_vertex_id == to_vertex_id: vertex_found = True vertex_type = "to_vertex" to_point = second_nearest_feature.geometry( ).asPoint() to_vertex_cost = second_nearest_feature['cost'] nearest_counter = nearest_counter + 1 """ if nearest_counter == 5: vertex_found = True vertex_type = "end_vertex" """ if vertex_type == "from_vertex": nearest_edge_geometry = QgsGeometry().fromPolylineXY( [from_point, nearest_vertex.point()]) res = nearest_edge_geometry.closestSegmentWithContext( current_pixel_midpoint) segment_point = res[ 1] #[0: distance, 1: point, 2: left_of, 3: epsilon for snapping] dist_to_segment = segment_point.distance( current_pixel_midpoint) dist_edge = from_point.distance(segment_point) #feedback.pushInfo("dist_to_segment = {}".format(dist_to_segment)) #feedback.pushInfo("dist_on_edge = {}".format(dist_edge)) #feedback.pushInfo("cost = {}".format(from_vertex_cost)) pixel_cost = from_vertex_cost + dist_edge + dist_to_segment raster_routingcost_data[i, j] = pixel_cost elif vertex_type == "to_vertex": nearest_edge_geometry = QgsGeometry().fromPolylineXY( [nearest_vertex.point(), to_point]) res = nearest_edge_geometry.closestSegmentWithContext( current_pixel_midpoint) segment_point = res[ 1] #[0: distance, 1: point, 2: left_of, 3: epsilon for snapping] dist_to_segment = segment_point.distance( current_pixel_midpoint) dist_edge = to_point.distance(segment_point) #feedback.pushInfo("dist_to_segment = {}".format(dist_to_segment)) #feedback.pushInfo("dist_on_edge = {}".format(dist_edge)) #feedback.pushInfo("cost = {}".format(from_vertex_cost)) pixel_cost = to_vertex_cost + dist_edge + dist_to_segment raster_routingcost_data[i, j] = pixel_cost else: pixel_cost = -99999 #nearest_feature['cost'] + (nearest_vertex.point().distance(current_pixel_midpoint)) """ nearest_feature_pointxy = nearest_feature.geometry().asPoint() nearest_feature_cost = nearest_feature['cost'] dist_to_vertex = current_pixel_midpoint.distance(nearest_feature_pointxy) #implement time cost pixel_cost = dist_to_vertex + nearest_feature_cost raster_data[i,j] = pixel_cost """ counter = counter + 1 if counter % 1000 == 0: feedback.pushInfo( "[QNEAT3Network][calcQneatInterpolation] Interpolated {} cells..." .format(counter)) feedback.setProgress((counter / total_work) * 100) band.WriteArray(raster_routingcost_data) outRasterSRS = osr.SpatialReference() outRasterSRS.ImportFromWkt(net.AnalysisCrs.toWkt()) output_interpolation_raster.SetProjection( outRasterSRS.ExportToWkt()) band.FlushCache() 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 points = self.parameterAsSource(parameters, self.POINTS, context) #QgsProcessingFeatureSource id_field = self.parameterAsString(parameters, self.ID_FIELD, context) #str 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.parameterAsFileOutput(parameters, self.OUTPUT, context) #str (filepath) feedback.pushInfo(pluginPath) analysisCrs = network.sourceCrs() 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 != points.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...") net = Qneat3Network(network, points, strategy, directionFieldName, forwardValue, backwardValue, bothValue, defaultDirection, analysisCrs, speedFieldName, defaultSpeed, tolerance, feedback) list_analysis_points = [ Qneat3AnalysisPoint("point", feature, id_field, net, net.list_tiedPoints[i], feedback) for i, feature in enumerate( getFeaturesFromQgsIterable(net.input_points)) ] total_workload = float(pow(len(list_analysis_points), 2)) feedback.pushInfo( "[QNEAT3Algorithm] Expecting total workload of {} iterations". format(int(total_workload))) with open(output_path, 'w', newline='') as csvfile: csv_writer = csv.writer(csvfile, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL) #write header csv_writer.writerow([ "InputID", "TargetID", "entry_cost", "network_cost", "exit_cost", "total_cost" ]) current_workstep_number = 0 for start_point in list_analysis_points: #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_analysis_points: if (current_workstep_number % 1000) == 0: feedback.pushInfo( "[QNEAT3Algorithm] {} OD-pairs processed...". format(current_workstep_number)) if query_point.point_id == start_point.point_id: csv_writer.writerow([ start_point.point_id, query_point.point_id, float(0) ]) elif dijkstra_query[0][ query_point.network_vertex_id] == -1: csv_writer.writerow( [start_point.point_id, query_point.point_id, None]) 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 = entry_cost + network_cost + exit_cost csv_writer.writerow([ start_point.point_id, query_point.point_id, entry_cost, network_cost, exit_cost, total_cost ]) 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 = {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 startPoint = self.parameterAsPoint(parameters, self.START_POINT, context, network.sourceCrs()) #QgsPointXY 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 = network.sourceCrs() input_coordinates = [startPoint] input_point = getFeatureFromPointParameter(startPoint) 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 != context.project().crs(): 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) analysis_point = Qneat3AnalysisPoint("point", input_point, "point_id", net, net.list_tiedPoints[0], feedback) feedback.pushInfo("[QNEAT3Algorithm] Calculating Iso-Pointcloud...") iso_pointcloud = net.calcIsoPoints([analysis_point], 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