Esempio n. 1
0
    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        feedback = QgsProcessingMultiStepFeedback(3, model_feedback)
        results = {}
        outputs = {}

        # Reproject layer
        alg_params = {
            'INPUT': parameters['roadnetwork'],
            'TARGET_CRS': 'ProjectCrs',
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ReprojectLayer'] = processing.run('native:reprojectlayer',
                                                   alg_params,
                                                   context=context,
                                                   feedback=feedback,
                                                   is_child_algorithm=True)

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        # Reproject layer
        alg_params = {
            'INPUT': parameters['region'],
            'TARGET_CRS': 'ProjectCrs',
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ReprojectLayer'] = processing.run('native:reprojectlayer',
                                                   alg_params,
                                                   context=context,
                                                   feedback=feedback,
                                                   is_child_algorithm=True)

        feedback.setCurrentStep(2)
        if feedback.isCanceled():
            return {}

        # Sum line lengths
        alg_params = {
            'COUNT_FIELD': 'COUNT',
            'LEN_FIELD': 'LENGTH',
            'LINES': outputs['ReprojectLayer']['OUTPUT'],
            'POLYGONS': outputs['ReprojectLayer']['OUTPUT'],
            'OUTPUT': parameters['OutputSumRoadNetworkLength']
        }
        outputs['SumLineLengths'] = processing.run('qgis:sumlinelengths',
                                                   alg_params,
                                                   context=context,
                                                   feedback=feedback,
                                                   is_child_algorithm=True)
        results['OutputSumRoadNetworkLength'] = outputs['SumLineLengths'][
            'OUTPUT']
        return results
    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        feedback = QgsProcessingMultiStepFeedback(3, model_feedback)
        results = {}
        outputs = {}

        # Da poligoni a linee
        alg_params = {
            'INPUT': parameters['poligonidellaisocrona'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['DaPoligoniALinee'] = processing.run('native:polygonstolines',
                                                     alg_params,
                                                     context=context,
                                                     feedback=feedback,
                                                     is_child_algorithm=True)

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        # Poligonizza
        alg_params = {
            'INPUT': outputs['DaPoligoniALinee']['OUTPUT'],
            'KEEP_FIELDS': False,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['Poligonizza'] = processing.run('qgis:polygonize',
                                                alg_params,
                                                context=context,
                                                feedback=feedback,
                                                is_child_algorithm=True)

        feedback.setCurrentStep(2)
        if feedback.isCanceled():
            return {}

        # Unione
        alg_params = {
            'INPUT': parameters['poligonidellaisocrona'],
            'OVERLAY': outputs['Poligonizza']['OUTPUT'],
            'OVERLAY_FIELDS_PREFIX': '',
            'OUTPUT': parameters['Output']
        }
        outputs['Unione'] = processing.run('native:union',
                                           alg_params,
                                           context=context,
                                           feedback=feedback,
                                           is_child_algorithm=True)
        results['Output'] = outputs['Unione']['OUTPUT']
        return results
Esempio n. 3
0
    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """

        inputLyrList = self.parameterAsLayerList(parameters, self.INPUTLAYERS,
                                                 context)
        if inputLyrList == []:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.INPUTLAYERS))
        onlySelected = self.parameterAsBool(parameters, self.SELECTED, context)
        self.prepareFlagSink(parameters, inputLyrList[0], QgsWkbTypes.Polygon,
                             context)
        # Compute the number of steps to display within the progress bar and
        # get features from source
        geomDict = dict()
        multiStepFeedback = QgsProcessingMultiStepFeedback(
            len(inputLyrList) + 1, feedback)
        for currentLyrIdx, lyr in enumerate(inputLyrList):
            multiStepFeedback.setCurrentStep(currentLyrIdx)
            featIterator, total = self.getIteratorAndFeatureCount(
                lyr, onlySelected=onlySelected)
            size = 100 / total if total else 0
            lyrName = lyr.name()
            for current, feat in enumerate(featIterator):
                # Stop the algorithm if cancel button has been clicked
                if multiStepFeedback.isCanceled():
                    break
                geom = feat.geometry()
                geomKey = geom.asWkb()
                if geomKey not in geomDict:
                    geomDict[geomKey] = []
                geomDict[geomKey].append({'feat': feat, 'layerName': lyrName})
                # # Update the progress bar
                multiStepFeedback.setProgress(current * size)
        for v in geomDict.values():
            if multiStepFeedback.isCanceled():
                break
            if len(v) > 1:
                flagStrList = [
                    '{lyrName} (id={id})'.format(lyrName=featDict['layerName'],
                                                 id=featDict['feat'].id())
                    for featDict in v
                ]
                flagStr = ', '.join(flagStrList)
                flagText = self.tr(
                    'Features from coverage with same geometry: {0}.').format(
                        flagStr)
                self.flagFeature(v[0]['feat'].geometry(), flagText)

        return {self.FLAGS: self.flag_id}
Esempio n. 4
0
 def getUnifiedLayerFeatures(self, unifiedLyr, layerList, attributeTupple=False, attributeBlackList=None, onlySelected=False, parameterDict=None, feedback=None):
     parameterDict = {} if parameterDict is None else parameterDict
     featList = []
     blackList = attributeBlackList.split(',') if attributeBlackList is not None and ',' in attributeBlackList else []
     if feedback:
         multiStepFeedback = QgsProcessingMultiStepFeedback(len(layerList), feedback)
     for i, layer in enumerate(layerList):
         if feedback:
             if feedback.isCanceled():
                 break
             multiStepFeedback.setCurrentStep(i)
         # recording class name
         layername = layer.name()
         coordinateTransformer = self.getCoordinateTransformer(unifiedLyr, layer)
         iterator, size = self.getFeatureList(layer, onlySelected=onlySelected, returnSize=True)
         for current, feature in enumerate(iterator):
             if feedback:
                 if multiStepFeedback.isCanceled():
                     break
             newFeats = self.featureHandler.createUnifiedFeature(unifiedLyr, feature, layername,\
                                                                bList=blackList, \
                                                                attributeTupple=attributeTupple, \
                                                                parameterDict=parameterDict, \
                                                                coordinateTransformer=coordinateTransformer)
             featList += newFeats
             if feedback:
                 multiStepFeedback.setProgress(current*size)
     return featList
Esempio n. 5
0
    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """
        layerHandler = LayerHandler()
        inputLyr = self.parameterAsVectorLayer(parameters, self.INPUT, context)
        onlySelected = self.parameterAsBool(parameters, self.SELECTED, context)
        ignoreClosed = self.parameterAsBool(parameters, self.IGNORE_CLOSED,
                                            context)
        fixInput = self.parameterAsBool(parameters, self.TYPE, context)
        self.prepareFlagSink(parameters, inputLyr, QgsWkbTypes.Point, context)

        multiStepFeedback = QgsProcessingMultiStepFeedback(2, feedback)
        multiStepFeedback.setCurrentStep(0)
        flagDict = layerHandler.identifyAndFixInvalidGeometries(
            inputLyr=inputLyr,
            ignoreClosed=ignoreClosed,
            fixInput=fixInput,
            onlySelected=onlySelected,
            feedback=multiStepFeedback)
        multiStepFeedback.setCurrentStep(1)
        itemSize = len(flagDict)
        progressSize = 100 / itemSize if itemSize else 0
        for current, (key, outDict) in enumerate(flagDict.items()):
            if multiStepFeedback.isCanceled():
                break
            self.flagFeature(flagGeom=outDict['geom'],
                             flagText=outDict['reason'])
            multiStepFeedback.setProgress(current * progressSize)

        return {self.FLAGS: self.flag_id, self.OUTPUT: inputLyr}
Esempio n. 6
0
    def processAlgorithm(self, parameters, context, model_feedback):
        parameters['lsi'] = self.parameterAsRasterLayer(
            parameters, self.INPUT, context)
        if parameters['lsi'] is None:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.INPUT))

        parameters['class'] = self.parameterAsFile(parameters, self.FILE,
                                                   context).source()
        if parameters['class'] is None:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.FILE))

        feedback = QgsProcessingMultiStepFeedback(1, model_feedback)
        results = {}
        outputs = {}
        # Input
        alg_params = {'INPUT': inLayer.source()}
        outputs['open'] = self.raster2array(alg_params)
        #list_of_values=list(np.arange(10))
        #self.list_of_values=outputs['open'][outputs['open']>-9999].reshape(-1)
        #QgsMessageLog.logMessage(str(len(self.list_of_values)), 'MyPlugin', level=Qgis.Info)

        alg_params = {'INPUT': outputs['open'], 'INPUT1': parameters['class']}
        outputs['class'] = self.classification(alg_params)

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}
        return results
    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        feedback = QgsProcessingMultiStepFeedback(2, model_feedback)
        results = {}
        outputs = {}

        # Download file
        alg_params = {
            'URL': parameters['DownloadURL'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['DownloadFile'] = processing.run('native:filedownloader',
                                                 alg_params,
                                                 context=context,
                                                 feedback=feedback,
                                                 is_child_algorithm=True)

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        # unzipconvert
        alg_params = {
            'INPUT': outputs['DownloadFile']['OUTPUT'],
            'OUTPUT': parameters['Outputfolder'],
            'TYPE': '.tif'
        }
        outputs['Unzipconvert'] = processing.run('script:unzipconvert',
                                                 alg_params,
                                                 context=context,
                                                 feedback=feedback,
                                                 is_child_algorithm=True)
        return results
Esempio n. 8
0
 def make_inventory_from_processing(self,
                                    parent_folder,
                                    format_list,
                                    destination_folder=None,
                                    make_copy=False,
                                    onlyGeo=True,
                                    feedback=None):
     featList = []
     fileList = []
     format_set = self.get_format_set(format_list)
     tuple_list = [i for i in os.walk(parent_folder)]
     nSteps = len(tuple_list) if make_copy else len(tuple_list) - 1
     multiStepFeedback = QgsProcessingMultiStepFeedback(
         nSteps, feedback) if feedback else None
     for current_step, [root, dirs, files] in enumerate(tuple_list):
         if feedback is not None:
             if feedback.isCanceled():
                 return []
             multiStepFeedback.setCurrentStep(current_step)
         n_files = len(files)
         files_progress = 100 / n_files if n_files else 0
         for current, current_file in enumerate(files):
             if multiStepFeedback is not None and multiStepFeedback.isCanceled(
             ):
                 break
             extension = current_file.split('.')[-1]
             if extension not in format_set:
                 continue
             full_path = self.get_full_path(current_file, root)
             if gdal.Open(full_path) or ogr.Open(full_path):
                 bbox_geom, attributes = self.computeBoxAndAttributes(
                     None, full_path, extension, insertIntoMemory=False)
                 new_feat = self.get_new_feat(bbox_geom, attributes)
                 featList.append(new_feat)
                 fileList.append(full_path)
             if multiStepFeedback is not None:
                 multiStepFeedback.setProgress(files_progress * current)
     if make_copy:
         if multiStepFeedback is not None:
             multiStepFeedback.setCurrentStep(nSteps)
         copy_len = len(fileList)
         for current, file_ in fileList:
             if multiStepFeedback is not None and multiStepFeedback.isCanceled:
                 break
             try:
                 self.copy_single_file(file_, destination_folder)
                 if multiStepFeedback is not None:
                     multiStepFeedback.pushInfo(
                         self.tr(
                             'File {file} copied to {destination}').format(
                                 file=file_,
                                 destination=destination_folder))
             except Exception as e:
                 if multiStepFeedback is not None:
                     multiStepFeedback.pushInfo(
                         self.tr('Error copying file {file}: {exception}\n'
                                 ).format(file=file_,
                                          exception='\n'.join(e.args)))
     return featList
Esempio n. 9
0
    def processAlgorithm(self, parameters, context, feedback):

        feedback = QgsProcessingMultiStepFeedback(1, feedback)
        results = {}
        outputs = {}

        parameters['grid'] = self.parameterAsRasterLayer(
            parameters, self.INPUT1, context).source()
        if parameters['grid'] is None:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.INPUT1))

        source = self.parameterAsVectorLayer(parameters, self.INPUT, context)
        parameters['points'] = source.source()
        #parameters['points']=self.asPythonString(parameters,self.INPUT, context)
        #print(parameters['points'])
        if parameters['points'] is None:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.INPUT))

        parameters['poly'] = self.parameterAsExtent(parameters, self.EXTENT,
                                                    context)
        if parameters['poly'] is None:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.EXTENT))

        parameters['field'] = self.parameterAsString(parameters, self.STRING,
                                                     context)
        if parameters['field'] is None:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.STRING))

        # outFile = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
        # parameters['out'], outputFormat = GdalUtils.ogrConnectionStringAndFormat(outFile, context)
        # if parameters['out'] is None:
        #     raise QgsProcessingException(self.invalidSourceError(parameters, self.OUTPUT))

        parameters['out'] = self.parameterAsFileOutput(parameters, self.OUTPUT,
                                                       context)
        if parameters['out'] is None:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.OUTPUT))

        # Intersectionpoly
        alg_params = {
            'STRING': parameters['field'],
            'INPUT_RASTER_LAYER': parameters['grid'],
            'INPUT_EXTENT': parameters['poly'],
            'INPUT_VECTOR_LAYER': parameters['points'],
            'OUTPUT': parameters['out']
        }
        self.extent(alg_params)
        outputs['cleaninventory'] = self.importingandcounting(alg_params)
        #del self.raster
        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        return results
    def processAlgorithm(self, parameters, context, feedback):
        communes = self.parameterAsString(parameters, self.LISTE_CODE_INSEE,
                                          context)
        filtre = self.parameterAsString(parameters, self.FILTRE, context)
        date = self.parameterAsString(parameters, self.DATE, context)
        url = self.parameterAsString(parameters, self.URL_TEMPLATE, context)
        directory = Path(
            self.parameterAsString(parameters, self.DOSSIER, context))

        if not directory.exists():
            feedback.pushDebugInfo(
                "Création du répertoire {}".format(directory))
            os.makedirs(directory, exist_ok=True)

        filtre = [c.strip() for c in filtre.split(',')]

        communes = [c.strip() for c in communes.split(',')]
        departements = []
        self.results = {
            self.DOSSIER: str(directory),
            self.NB_COMMUNES: len(communes),
            self.NB_FEUILLES: 0,
            self.DEPARTEMENTS: "",
        }

        multi_feedback = QgsProcessingMultiStepFeedback(
            len(communes), feedback)

        for i, commune_insee in enumerate(communes):

            commune = Commune(commune_insee, date=date, base_url=url)
            if not self.download_commune(directory, commune, filtre,
                                         multi_feedback, context):
                multi_feedback.reportError("Erreur sur la commune {}".format(
                    commune.insee))
                break

            if multi_feedback.isCanceled():
                break

            multi_feedback.setCurrentStep(i)

            if commune.departement not in departements:
                departements.append(commune.departement)

        self.results[self.DEPARTEMENTS] = ','.join(departements)

        multi_feedback.pushInfo("\n")
        multi_feedback.pushInfo("\n")
        multi_feedback.pushInfo(
            "Téléchargement terminé pour {} communes".format(len(communes)))
        multi_feedback.pushInfo("{} feuilles".format(
            self.results[self.NB_FEUILLES]))
        multi_feedback.pushInfo("dans {}".format(str(directory)))
        multi_feedback.pushInfo("\n")
        multi_feedback.pushInfo("\n")
        return self.results
Esempio n. 11
0
 def prepareInputLayers(self,
                        inputLayers,
                        stepConversionMap,
                        context=None,
                        feedback=None):
     """
     Prepare layers for a translation unit (step) to be executed (e.g. applies filters).
     :param inputLayers: (dict) a map from layer name to each vector layer contained by the
                         input datasource. 
     :param stepConversionMap: (dict) conversion map generated by Datasource Conversion tool
                               for a conversion step.
     :param context: (QgsProcessingContext) environment parameters in which processing tools are used.
     :param feedback: (QgsProcessingMultiStepFeedback) QGIS tool for progress tracking.
     :return: (dict) map of layers to have its features mapped to output format.
     """
     lh = LayerHandler()
     context = context if context is not None else QgsProcessingContext()
     layerFilters = stepConversionMap["filter"]["layer_filter"]
     spatialFilters = stepConversionMap["filter"]["spatial_filter"]
     # in case a selection of layers was made, only chosen layers should be translated
     inputLayers = inputLayers if layerFilters == {} else {
         layer: inputLayers[layer]
         for layer in layerFilters
     }
     multiStepFeedback = QgsProcessingMultiStepFeedback(
         len(inputLayers), feedback)
     if spatialFilters:
         # spatial filtering behaviour is set based on the modes defined in convertLayer2LayerAlgorithm
         behaviour = self.getSpatialFilterBehaviour(
             spatialFilters["predicate"] if "predicate" in
             spatialFilters else None)
         spatialFilterlLayer = self.prepareSpatialFilterLayer(
             spatialFilters, context)
     else:
         behaviour = None
         spatialFilters = None
     preparedLayers = dict()
     currentStep = 0
     for layer, vl in inputLayers.items():
         if feedback is not None:
             multiStepFeedback.setCurrentStep(currentStep)
             if multiStepFeedback.isCanceled():
                 break
             currentStep += 1
         translatedLayer = lh.prepareConversion(
             inputLyr=vl,
             context=context,
             inputExpression=layerFilters[layer]["expression"]
             if layer in layerFilters else None,
             filterLyr=spatialFilterlLayer,
             behavior=behaviour,
             conversionMap=stepConversionMap,
             feedback=multiStepFeedback if feedback is not None else None)
         if translatedLayer.featureCount() > 0:
             preparedLayers[layer] = translatedLayer
     return preparedLayers
Esempio n. 12
0
    def readOutputLayers(self, datasourcePath, feedback=None):
        """
        Prepares output layers to be filled.
        :param datasourcePath: (str) output's datasource path.
        :param context: (QgsProcessingContext) environment parameters in which processing tools are used.
        :param feedback: (QgsProcessingMultiStepFeedback) QGIS tool for progress tracking.
        :return: (dict) a map for output's layers.
        """
        parameters = self.parseDatasourcePath(datasourcePath)
        abstractDb = self.connectToDb(parameters=parameters)
        if abstractDb is None:
            return {}
        layerLoader = LayerLoaderFactory().makeLoader(self.iface, abstractDb)
        outputLayerMap = dict()

        geometricLayers = abstractDb.listGeomClassesFromDatabase([])
        complexLayers = abstractDb.listComplexClassesFromDatabase()
        if feedback is not None:
            multiStepFeedback = QgsProcessingMultiStepFeedback(
                len(geometricLayers) + len(complexLayers), feedback)

        for curr, l in enumerate(geometricLayers):
            if feedback is not None and multiStepFeedback.isCanceled():
                return outputLayerMap
            vl = layerLoader.getLayerByName(l)
            outputLayerMap[vl.name()] = vl
            if feedback is not None:
                multiStepFeedback.setCurrentStep(curr)

        for currComplex, l in enumerate(complexLayers):
            if feedback is not None and multiStepFeedback.isCanceled():
                return outputLayerMap
            vl = layerLoader.getComplexLayerByName(l)
            outputLayerMap[vl.name()] = vl
            if feedback is not None:
                multiStepFeedback.setCurrentStep(curr + currComplex)
        # after reading its layers, db connection will not be used again
        del abstractDb
        return outputLayerMap
Esempio n. 13
0
 def processAlgorithm(self, parameters, context, feedback):
     """
     Method that triggers the data processing algorithm.
     :param parameters: (dict) mapping from algorithms input's name to its
                        value.
     :param context: (QgsProcessingContext) execution's environmental info.
     :param feedback: (QgsProcessingFeedback) QGIS object to keep track of
                      algorithm's progress/status.
     :return: (dict) output mapping for identified flags.
     """
     layers, selected, silent, ratio = self.getParameters(
         parameters, context, feedback)
     if not layers:
         raise QgsProcessingException(self.tr("No layers were provided."))
     for layer in layers:
         if layer.featureCount() > 0:
             geomType = next(layer.getFeatures()).geometry().wkbType()
             break
     else:
         raise QgsProcessingException(self.tr("All layers are empty."))
     self.prepareFlagSink(parameters, layers[0], geomType, context)
     flags = dict()
     lh = LayerHandler()
     flagCount = 0
     # a step for each input + 1 for loading flags into sink
     multiStepFeedback = QgsProcessingMultiStepFeedback(
         len(layers) + 1, feedback)
     multiStepFeedback.setCurrentStep(0)
     for step, layer in enumerate(layers):
         if multiStepFeedback.isCanceled():
             break
         # running polygon slivers to purposely raise an exception if an
         # empty geometry is found
         multiStepFeedback.pushInfo(
             self.tr("Checking {0}...").format(layer.name()))
         slivers = lh.getPolygonSlivers(layer, ratio, selected, silent,
                                        multiStepFeedback)
         if slivers:
             # pushWarnign is only avalailable on 3.16.2+
             # multiStepFeedback.pushWarning(
             multiStepFeedback.pushDebugInfo(
                 self.tr("{0} slivers were found on {1}!")\
                     .format(len(slivers), layer.name())
             )
             flags[layer] = slivers
             flagCount += len(slivers)
         multiStepFeedback.setCurrentStep(step + 1)
     self.tr("Populating flags layer...")
     self.flagPolygonSlivers(flags, flagCount, multiStepFeedback)
     multiStepFeedback.setCurrentStep(step + 2)
     return {self.FLAGS: self.flag_id}
Esempio n. 14
0
    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        feedback = QgsProcessingMultiStepFeedback(2, model_feedback)
        results = {}
        outputs = {}

        # Reclassify with table
        alg_params = {
            'DATA_TYPE': 5,
            'INPUT_RASTER': parameters['RastertoReclassify'],
            'NODATA_FOR_MISSING': False,
            'NO_DATA': -9999,
            'RANGE_BOUNDARIES': 0,
            'RASTER_BAND': 1,
            'TABLE': [-1, 0, 0, 0, 1, 1],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ReclassifyWithTable'] = processing.run(
            'native:reclassifybytable',
            alg_params,
            context=context,
            feedback=feedback,
            is_child_algorithm=True)

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        # Zonal Histogram
        alg_params = {
            'COLUMN_PREFIX':
            QgsExpression('substr( parameter(\'RastertoReclassify\'), 10, 8)').
            evaluate(),
            'INPUT_RASTER':
            outputs['ReclassifyWithTable']['OUTPUT'],
            'INPUT_VECTOR':
            parameters['inputsitespolygon'],
            'RASTER_BAND':
            1,
            'OUTPUT':
            parameters['PolygonsZonalHistogram']
        }
        outputs['ZonalHistogram'] = processing.run('native:zonalhistogram',
                                                   alg_params,
                                                   context=context,
                                                   feedback=feedback,
                                                   is_child_algorithm=True)
        results['PolygonsZonalHistogram'] = outputs['ZonalHistogram']['OUTPUT']
        return results
Esempio n. 15
0
    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        steps = len(parameters['INPUT'])
        feedback = QgsProcessingMultiStepFeedback(steps, model_feedback)

        results = {'OUTPUT': []}
        outputs = {'ClipRasterByMaskLayer': []}
        i = 0
        feedback.pushDebugInfo("OUTFOLDER: " + str(parameters['OUTFOLDER']))
        for filename in parameters['INPUT']:
            if os.path.isdir(str(parameters['OUTFOLDER'])):
                file, ext = os.path.splitext(os.path.basename(filename))
                outfilename = os.path.join(parameters['OUTFOLDER'],
                                           file + "_clipped" + ext)
            else:
                outfilename = QgsProcessing.TEMPORARY_OUTPUT
            # Clip raster by mask layer
            alg_params = {
                'ALPHA_BAND': False,
                'CROP_TO_CUTLINE': True,
                'DATA_TYPE': 0,
                'EXTRA': '',
                'INPUT': filename,
                'KEEP_RESOLUTION': False,
                'MASK': parameters['Masklayer'],
                'MULTITHREADING': False,
                'NODATA': None,
                'OPTIONS': '',
                'SET_RESOLUTION': False,
                'SOURCE_CRS': None,
                'TARGET_CRS': None,
                'X_RESOLUTION': None,
                'Y_RESOLUTION': None,
                'OUTPUT': outfilename
            }
            outputs['ClipRasterByMaskLayer'].append(
                processing.run('gdal:cliprasterbymasklayer',
                               alg_params,
                               context=context,
                               feedback=feedback,
                               is_child_algorithm=True))
            i = i + 1
            feedback.setCurrentStep(i)
            if feedback.isCanceled():
                return {}

        for clipresult in outputs['ClipRasterByMaskLayer']:
            results['OUTPUT'].append(clipresult['OUTPUT'])
        return results
Esempio n. 16
0
    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        feedback = QgsProcessingMultiStepFeedback(2, model_feedback)
        results = {}
        outputs = {}

        # v.split
        temporary_path = os.path.join(gettempdir(), 'segmented_layer.gpkg')
        try:  #valid since 3.6
            # Division des lignes par longueur maximale
            alg_params = {
                'INPUT': parameters[self.LINES],
                'LENGTH': parameters[self.SEGMENT_SIZE],
                'OUTPUT': temporary_path
            }
            output = processing.run('native:splitlinesbylength',
                                    alg_params,
                                    context=context,
                                    feedback=feedback,
                                    is_child_algorithm=True)
            outputs['segmentedLayer'] = output['OUTPUT']
        except:  #valid for 3.4-ltr + Grass
            # Division des lignes par longueur maximale
            alg_params = {
                'INPUT': parameters[self.LINES],
                'DISTANCE': parameters[self.SEGMENT_SIZE],
                'OUTPUT': temporary_path
            }
            output = processing.run('native:segmentizebymaxdistance',
                                    alg_params,
                                    context=context,
                                    feedback=feedback,
                                    is_child_algorithm=True)
            outputs['segmentedLayer'] = output['OUTPUT']

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}
        parameters['LINES'] = outputs['segmentedLayer']
        # Graduated Lines Map
        outputs['GraduatedLinesMap'] = processing.run(
            'visualist:graduatedlinemap',
            parameters,
            context=context,
            feedback=feedback,
            is_child_algorithm=True)
        results['LineMap'] = outputs['GraduatedLinesMap']['OUTPUT_LINE']
        return results
Esempio n. 17
0
 def updateOriginalLayersFromUnifiedLayer(self, lyrList, unifiedLyr, feedback = None, onlySelected = False):
     lenList = len(lyrList)
     parameterDict = self.getDestinationParameters(unifiedLyr)
     multiStepFeedback = QgsProcessingMultiStepFeedback(lenList, feedback) if feedback else None
     for i, lyr in enumerate(lyrList):
         if feedback:
             if multiStepFeedback.isCanceled():
                 break
             multiStepFeedback.setCurrentStep(i)
         innerFeedback = QgsProcessingMultiStepFeedback(3, multiStepFeedback) if multiStepFeedback else None
         innerFeedback.setCurrentStep(0)
         inputDict = self.buildInputDict(lyr, onlySelected=onlySelected, feedback=innerFeedback)
         if innerFeedback:
             if innerFeedback.isCanceled():
                 break
         request = QgsFeatureRequest(QgsExpression("layer = '{0}'".format(lyr.name())))
         innerFeedback.setCurrentStep(1)
         self.populateInputDictFeatList(unifiedLyr, inputDict, pk = 'featid', request = request, feedback=innerFeedback)
         if innerFeedback:
             if innerFeedback.isCanceled():
                 break
         coordinateTransformer = self.getCoordinateTransformer(unifiedLyr, lyr)
         innerFeedback.setCurrentStep(2)
         self.updateOriginalLayerFeatures(lyr, inputDict, parameterDict = parameterDict, coordinateTransformer = coordinateTransformer, feedback=innerFeedback)
    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        steps = len(parameters['INPUT'])
        feedback = QgsProcessingMultiStepFeedback(steps, model_feedback)
        results = {'OUTFOLDER': "", 'OUTPUT': []}

        i = 0
        outputs = {'cliprasterbyextent': {}, 'LISTOFCLIPPEDRASTERS': []}
        i = 0

        #pattern = re.compile(r".+_([0-9]{8})T[0-9]{6}_(B[0-9]{1}[0-9,A]{1})\.jp2$")
        pattern = re.compile(parameters['MASK'])
        for filename in parameters['INPUT']:
            match = pattern.match(filename)
            if not match:
                continue
            clippedfilename = os.path.join(
                parameters['OUTFOLDER'],
                match.group(1) + "_" + match.group(2) + ".tif")

            alg_params = {
                'DATA_TYPE': 0,
                'EXTRA': '',
                'INPUT': filename,
                'NODATA': None,
                'OPTIONS': '',
                'PROJWIN': parameters['CLIPEXTENT'],
                'OUTPUT': clippedfilename,
            }
            if feedback.isCanceled():
                return {}
            outputs['cliprasterbyextent'][filename] = processing.run(
                'gdal:cliprasterbyextent',
                alg_params,
                context=context,
                feedback=feedback,
                is_child_algorithm=True)['OUTPUT']
            feedback.setCurrentStep(i)
            i = i + 1
            outputs['LISTOFCLIPPEDRASTERS'].append(clippedfilename)

        results['OUTFOLDER'] = parameters['OUTFOLDER']
        results['OUTPUT'] = outputs['LISTOFCLIPPEDRASTERS']
        return results
Esempio n. 19
0
    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        feedback = QgsProcessingMultiStepFeedback(2, model_feedback)
        results = {}
        outputs = {}

        # Intersection - 14
        alg_params = {
            'INPUT': parameters['14mvoronoi'],
            'INPUT_FIELDS': None,
            'OVERLAY': parameters['foreststands'],
            'OVERLAY_FIELDS': None,
            'OVERLAY_FIELDS_PREFIX': '',
            'OUTPUT': parameters['1_4m_partiton']
        }
        outputs['Intersection14'] = processing.run('native:intersection',
                                                   alg_params,
                                                   context=context,
                                                   feedback=feedback,
                                                   is_child_algorithm=True)
        results['1_4m_partiton'] = outputs['Intersection14']['OUTPUT']

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        # Intersection - 12
        alg_params = {
            'INPUT': parameters['12mvoronoi2'],
            'INPUT_FIELDS': None,
            'OVERLAY': parameters['foreststands'],
            'OVERLAY_FIELDS': None,
            'OVERLAY_FIELDS_PREFIX': '',
            'OUTPUT': parameters['1_2m_partition']
        }
        outputs['Intersection12'] = processing.run('native:intersection',
                                                   alg_params,
                                                   context=context,
                                                   feedback=feedback,
                                                   is_child_algorithm=True)
        results['1_2m_partition'] = outputs['Intersection12']['OUTPUT']
        return results
Esempio n. 20
0
    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        feedback = QgsProcessingMultiStepFeedback(2, model_feedback)
        results = {}
        outputs = {}

        # Add raster values to points
        alg_params = {
            'GRIDS': parameters['inputndwirasters2018'],
            'RESAMPLING': 0,
            'SHAPES': parameters['inputsitespoints'],
            'RESULT': parameters['Sitespixelvalues2018']
        }
        outputs['AddRasterValuesToPoints'] = processing.run(
            'saga:addrastervaluestopoints',
            alg_params,
            context=context,
            feedback=feedback,
            is_child_algorithm=True)
        results['Sitespixelvalues2018'] = outputs['AddRasterValuesToPoints'][
            'RESULT']

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        # Add raster values to points
        alg_params = {
            'GRIDS': parameters['inputndwirasters2'],
            'RESAMPLING': 0,
            'SHAPES': parameters['inputsitespoints'],
            'RESULT': parameters['Sitespixelvalues']
        }
        outputs['AddRasterValuesToPoints'] = processing.run(
            'saga:addrastervaluestopoints',
            alg_params,
            context=context,
            feedback=feedback,
            is_child_algorithm=True)
        results['Sitespixelvalues'] = outputs['AddRasterValuesToPoints'][
            'RESULT']
        return results
    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        feedback = QgsProcessingMultiStepFeedback(2, model_feedback)
        results = {}
        outputs = {}

        # Intersection
        alg_params = {
            'INPUT': parameters['class'],
            'INPUT_FIELDS': parameters['classfield'],
            'OVERLAY': parameters['zone'],
            'OVERLAY_FIELDS': parameters['zonefield'],
            'OVERLAY_FIELDS_PREFIX': '',
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['Intersection'] = processing.run('native:intersection',
                                                 alg_params,
                                                 context=context,
                                                 feedback=feedback,
                                                 is_child_algorithm=True)

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        # Add geometry attributes
        alg_params = {
            'CALC_METHOD': 0,
            'INPUT': outputs['Intersection']['OUTPUT'],
            'OUTPUT': parameters['Result']
        }
        outputs['AddGeometryAttributes'] = processing.run(
            'qgis:exportaddgeometrycolumns',
            alg_params,
            context=context,
            feedback=feedback,
            is_child_algorithm=True)
        results['Result'] = outputs['AddGeometryAttributes']['OUTPUT']
        return results
    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """
        layerHandler = LayerHandler()
        snapDict = self.parameterAsSnapHierarchy(parameters,
                                                 self.SNAP_HIERARCHY, context)

        onlySelected = self.parameterAsBool(parameters, self.SELECTED, context)

        behavior = self.parameterAsEnum(parameters, self.BEHAVIOR, context)
        nSteps = 0
        for item in snapDict:
            nSteps += len(item['snapLayerList'])
        currStep = 0
        multiStepFeedback = QgsProcessingMultiStepFeedback(nSteps, feedback)
        for current, item in enumerate(snapDict):
            refLyr = self.layerFromProject(item['referenceLayer'])
            for i, lyr in enumerate(item['snapLayerList']):
                lyr = self.layerFromProject(lyr)
                if multiStepFeedback.isCanceled():
                    break
                multiStepFeedback.setCurrentStep(currStep)
                multiStepFeedback.pushInfo(
                    self.
                    tr('Snapping geometries from layer {input} to {reference} with snap {snap}...'
                       ).format(input=lyr.name(),
                                reference=refLyr.name(),
                                snap=item['snap']))
                layerHandler.snapToLayer(lyr,
                                         refLyr,
                                         item['snap'],
                                         behavior,
                                         onlySelected=onlySelected,
                                         feedback=multiStepFeedback)
                currStep += 1
        return {}
    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        feedback = QgsProcessingMultiStepFeedback(2, model_feedback)
        results = {}
        outputs = {}

        # Centroids
        alg_params = {
            'ALL_PARTS': False,
            'INPUT': parameters['citycenter'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['Centroids'] = processing.run('native:centroids',
                                              alg_params,
                                              context=context,
                                              feedback=feedback,
                                              is_child_algorithm=True)

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        # Mean coordinate(s)
        alg_params = {
            'INPUT': outputs['Centroids']['OUTPUT'],
            'UID': None,
            'WEIGHT': None,
            'OUTPUT': parameters['Cbd_as_point']
        }
        outputs['MeanCoordinates'] = processing.run('native:meancoordinates',
                                                    alg_params,
                                                    context=context,
                                                    feedback=feedback,
                                                    is_child_algorithm=True)
        results['Cbd_as_point'] = outputs['MeanCoordinates']['OUTPUT']
        return results
Esempio n. 24
0
    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        feedback = QgsProcessingMultiStepFeedback(2, model_feedback)
        results = {}
        outputs = {}

        indexequation = str(self.indexdefs['Index definitions']['Sentinel2'][list(self.indexdefs['Index definitions']['Sentinel2'].keys())[parameters['INDEX']]])
        vrtname = parameters['SentinelVrtLayer'].split('_',1)[0]
        indexequation = indexequation.replace("SentinelVRTLayer", vrtname)
        feedback.pushDebugInfo("indexequation: " + str(indexequation))
        # Raster calculator
        alg_params = {
            'CELLSIZE': 0,
            'CRS': 'ProjectCrs',
            'EXPRESSION': indexequation,
            'EXTENT': parameters['SentinelVrtLayer'],
            'LAYERS': parameters['SentinelVrtLayer'],
            'OUTPUT': parameters['OUTPUT']
        }
        feedback.pushDebugInfo(str(alg_params))
        outputs['RasterCalculator'] = processing.run('qgis:rastercalculator', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        results['OUTPUT'] = outputs['RasterCalculator']['OUTPUT']

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        # Set layer style
        alg_params = {
            'INPUT': outputs['RasterCalculator']['OUTPUT'],
            'STYLE': parameters['LayerStyledefinition']
        }
        outputs['SetLayerStyle'] = processing.run('native:setlayerstyle', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        return results
    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        feedback = QgsProcessingMultiStepFeedback(5, model_feedback)
        results = {}
        outputs = {}

        # CSVtoStatProcessing
        alg_params = {
            'ENCODING': parameters['encode'],
            'INPUT': parameters['CSVfile'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['Csvtostatprocessing'] = processing.run(
            'QGIS_stat:CSVtoStatProcessing',
            alg_params,
            context=context,
            feedback=feedback,
            is_child_algorithm=True)

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        # 属性テーブルで結合(table join)
        alg_params = {
            'DISCARD_NONMATCHING': False,
            'FIELD': parameters['addressfield'],
            'FIELDS_TO_COPY': None,
            'FIELD_2': 'address',
            'INPUT': parameters['addresslayer'],
            'INPUT_2': outputs['Csvtostatprocessing']['OUTPUT'],
            'METHOD': 1,
            'PREFIX': '',
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['TableJoin'] = processing.run('native:joinattributestable',
                                              alg_params,
                                              context=context,
                                              feedback=feedback,
                                              is_child_algorithm=True)

        feedback.setCurrentStep(2)
        if feedback.isCanceled():
            return {}

        # レイヤをGeoPackage化
        alg_params = {
            'LAYERS': outputs['TableJoin']['OUTPUT'],
            'OVERWRITE': True,
            'SAVE_STYLES': False,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['Geopackage'] = processing.run('native:package',
                                               alg_params,
                                               context=context,
                                               feedback=feedback,
                                               is_child_algorithm=True)

        feedback.setCurrentStep(3)
        if feedback.isCanceled():
            return {}

        # SpatiaLiteでSQLを実行
        alg_params = {
            'DATABASE': outputs['Geopackage']['OUTPUT'],
            'SQL': 'update \"出力レイヤ\" set count=0 where count is NULL'
        }
        outputs['Spatialitesql'] = processing.run('qgis:spatialiteexecutesql',
                                                  alg_params,
                                                  context=context,
                                                  feedback=feedback,
                                                  is_child_algorithm=True)

        feedback.setCurrentStep(4)
        if feedback.isCanceled():
            return {}

        # フォーマット変換(gdal_translate)
        alg_params = {
            'INPUT': outputs['Geopackage']['OUTPUT'],
            'OPTIONS': '',
            'OUTPUT': parameters['GeojsonOutput']
        }
        outputs['Gdal_translate'] = processing.run('gdal:convertformat',
                                                   alg_params,
                                                   context=context,
                                                   feedback=feedback,
                                                   is_child_algorithm=True)
        results['GeojsonOutput'] = outputs['Gdal_translate']['OUTPUT']
        return results
    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """
        self.layerHandler = LayerHandler()
        inputLyr = self.parameterAsVectorLayer(parameters, self.INPUT, context)
        onlySelected = self.parameterAsBool(parameters, self.SELECTED, context)
        searchRadius = self.parameterAsDouble(parameters, self.TOLERANCE,
                                              context)
        lineFilterLyrList = self.parameterAsLayerList(parameters,
                                                      self.LINEFILTERLAYERS,
                                                      context)
        polygonFilterLyrList = self.parameterAsLayerList(
            parameters, self.POLYGONFILTERLAYERS, context)
        ignoreNotSplit = self.parameterAsBool(parameters, self.TYPE, context)
        ignoreInner = self.parameterAsBool(parameters, self.IGNOREINNER,
                                           context)
        self.prepareFlagSink(parameters, inputLyr, QgsWkbTypes.Point, context)

        # Compute the number of steps to display within the progress bar and
        # get features from source
        feedbackTotal = 3
        feedbackTotal += 1 if lineFilterLyrList or polygonFilterLyrList else 0
        feedbackTotal += 1 if not ignoreInner else 0
        multiStep = QgsProcessingMultiStepFeedback(feedbackTotal, feedback)
        currentStep = 0
        multiStep.setCurrentStep(currentStep)
        multiStep.pushInfo(self.tr('Building search structure...'))
        endVerticesDict = self.layerHandler.buildInitialAndEndPointDict(
            inputLyr, onlySelected=onlySelected, feedback=multiStep)

        #search for dangles candidates
        currentStep += 1
        multiStep.setCurrentStep(currentStep)
        multiStep.pushInfo(self.tr('Looking for dangles...'))
        pointList = self.searchDanglesOnPointDict(endVerticesDict, multiStep)
        #build filter layer
        currentStep += 1
        multiStep.setCurrentStep(currentStep)
        multiStep.pushInfo(self.tr('Filtering dangles candidates...'))
        filterLayer = self.buildFilterLayer(lineFilterLyrList,
                                            polygonFilterLyrList,
                                            context,
                                            multiStep,
                                            onlySelected=onlySelected)
        #filter pointList with filterLayer

        if filterLayer:
            currentStep += 1
            multiStep.setCurrentStep(currentStep)
            multiStep.pushInfo(
                self.tr('Filtering dangles candidates with filter...'))
            filteredPointList = self.filterPointListWithFilterLayer(
                pointList, filterLayer, searchRadius, multiStep)
        else:
            filteredPointList = pointList
        #filter with own layer
        if not ignoreInner:  #True when looking for dangles on contour lines
            currentStep += 1
            multiStep.setCurrentStep(currentStep)
            multiStep.pushInfo(self.tr('Filtering inner dangles...'))
            filteredPointList = self.filterPointListWithFilterLayer(
                filteredPointList,
                inputLyr,
                searchRadius,
                multiStep,
                isRefLyr=True,
                ignoreNotSplit=ignoreNotSplit)
        #build flag list with filtered points
        currentStep += 1
        multiStep.setCurrentStep(currentStep)
        multiStep.pushInfo(self.tr('Raising flags...'))
        if filteredPointList:
            # currentValue = feedback.progress()
            currentTotal = 100 / len(filteredPointList)
            for current, point in enumerate(filteredPointList):
                if multiStep.isCanceled():
                    break
                self.flagFeature(
                    QgsGeometry.fromPointXY(point),
                    self.tr('Dangle on {0}').format(inputLyr.name()))
                multiStep.setProgress(current * currentTotal)
        # feedback.setProgress(100)
        return {self.FLAGS: self.flag_id}
Esempio n. 27
0
    def processAlgorithm(self, parameters, context, model_feedback):
        """
        Here is where the processing itself takes place.
        """
        results = {}

        csvfile = self.parameterAsFile(parameters, self.INPUT, context)
        if csvfile is None:
            raise QgsProcessingException(self.tr('csv file error'))

        #df = QgsVirtualLayerDefinition()

        enc = self.parameterAsInt(parameters, 'ENCODING', context)

        meshLayer = self.parameterAsVectorLayer(parameters, "meshlayer",
                                                context)
        if meshLayer is None:
            raise QgsProcessingException(self.tr('mesh layer missed'))

        meshidfields = self.parameterAsFields(parameters, 'meshid', context)

        limit_sample = self.parameterAsInt(parameters, 'limit_sample', context)

        maxdivide = self.parameterAsInt(parameters, 'maxdivide', context)

        uneven_div = self.parameterAsInt(parameters, 'uneven_div', context)

        popmeshLayer = self.parameterAsVectorLayer(parameters, "popmeshlayer",
                                                   context)
        if popmeshLayer is None:
            raise QgsProcessingException(self.tr('popmes  layer missed'))

        popmeshidfields = self.parameterAsFields(parameters, 'popmeshid',
                                                 context)

        popmeshpopfields = self.parameterAsFields(parameters, 'popmeshpop',
                                                  context)

        feedback = QgsProcessingMultiStepFeedback(9 + maxdivide,
                                                  model_feedback)

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        # 住所別集計
        alg_params = {
            'addresslayer': parameters['addresslayer'],
            'addressfield': parameters['addressfield'],
            'INPUT': csvfile,
            'ENCODING': enc,
            'CRS': None,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }

        #Stat_CSVAddressPolygon

        outputs_statv = processing.run('QGIS_stat:Stat_CSVAddressPolygon',
                                       alg_params,
                                       context=context,
                                       feedback=feedback,
                                       is_child_algorithm=True)

        if feedback.isCanceled():
            return {}

        statv = outputs_statv["OUTPUT"]
        meshid = meshidfields[0]

        #   人口メッシュと行政界メッシュのUnion作成する

        new_popfield = 'pv'

        param_uni = {
            'addresslayer': statv,
            'addressfield': parameters['addressfield'][0],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT,
            'popmeshlayer': popmeshLayer,
            'popmeshid': popmeshidfields[0],
            'popmeshpop': popmeshpopfields[0],
            'POPCOLUMN': new_popfield
        }

        feedback.setCurrentStep(2)

        res_uni = processing.run('QGIS_stat:UnionAdmAndPopMeshAlgorithm',
                                 param_uni,
                                 context=context,
                                 feedback=feedback,
                                 is_child_algorithm=True)

        if feedback.isCanceled():
            return {}

        feedback.pushConsoleInfo("csvs 1 union ok  ")

        #     union pop polygon   res_unit["OUTPUT"]
        #   population     pv
        #      address   parameters['addressfield'][0]

        #    行政界別人口の算出

        feedback.setCurrentStep(3)

        param_pop = {
            'inputlayer': res_uni['OUTPUT'],
            'agfield': parameters['addressfield'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT,
            # 'OUTPUT':parameters['OUTPUT'],
            'cfield': new_popfield
        }

        res_adpop = processing.run('QGIS_stat:AggreagteValueAlgorithm',
                                   param_pop,
                                   context=context,
                                   feedback=feedback,
                                   is_child_algorithm=True)

        if feedback.isCanceled():
            return {}

        feedback.pushConsoleInfo("csvs 1  caliculate pop adm ok  ")

        #   UNION mesh と 行政界別 人口の結合

        feedback.setCurrentStep(4)

        param_join = {
            'DISCARD_NONMATCHING': False,
            'FIELD': parameters['addressfield'],
            'FIELDS_TO_COPY': [],
            'FIELD_2': parameters['addressfield'],
            'INPUT': res_uni['OUTPUT'],
            'INPUT_2': res_adpop['OUTPUT'],
            'METHOD': 1,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT,
            #'OUTPUT':parameters['OUTPUT'],
            'PREFIX': 'op'
        }

        res_join = processing.run('qgis:joinattributestable',
                                  param_join,
                                  context=context,
                                  feedback=feedback,
                                  is_child_algorithm=True)

        if feedback.isCanceled():
            return {}

        feedback.pushConsoleInfo("csvs 1  join union mesh and popof adm  ok  ")

        #   UNION MESH  人口 と行政界人口の比率算出

        feedback.setCurrentStep(5)

        param_ratio = {
            'FIELD_LENGTH': 12,
            'FIELD_NAME': 'pvratio',
            'FIELD_PRECISION': 6,
            'FIELD_TYPE': 0,
            'FORMULA': ' \"pv\" / \"oppv\" ',
            'INPUT': res_join["OUTPUT"],
            #'OUTPUT':parameters['OUTPUT']
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT,
        }

        res_ratio = processing.run('qgis:fieldcalculator',
                                   param_ratio,
                                   context=context,
                                   feedback=feedback,
                                   is_child_algorithm=True)

        if feedback.isCanceled():
            return {}

        feedback.pushConsoleInfo(
            "csvs 1 calc ratio of adm pop and union polygon population  ok  ")

        #    Union mesh の想定集計値を算出する   住所別集計値 × ( UNION MESH  人口 と行政界人口の比率算出)

        feedback.setCurrentStep(6)

        param_ratio2 = {
            'FIELD_LENGTH': 12,
            'FIELD_NAME': 'pvsum',
            'FIELD_PRECISION': 6,
            'FIELD_TYPE': 0,
            'FORMULA': ' \"snum\" * \"pvratio\" ',
            'INPUT': res_ratio["OUTPUT"],
            #'OUTPUT':parameters['OUTPUT']
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }

        res_ratio2 = processing.run('qgis:fieldcalculator',
                                    param_ratio2,
                                    context=context,
                                    feedback=feedback,
                                    is_child_algorithm=True)

        if feedback.isCanceled():
            return {}

        feedback.pushConsoleInfo("csvs 1 calc ratio of research sample  ok  ")

        #results["OUTPUT"] = res_ratio2["OUTPUT"]
        #return results

        #    入力メッシュとUnionメッシュのUnion
        feedback.setCurrentStep(7)

        #results["OUTPUT"] = res_ratio['OUTPUT']
        #return results

        #    入力UNIONメッシュの保存

        # レイヤをGeoPackage化
        cnv_paramsg = {
            'LAYERS': res_ratio2["OUTPUT"],
            'OVERWRITE': True,
            'SAVE_STYLES': False,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
            #'OUTPUT':parameters['OUTPUT']
        }
        input_c = processing.run('native:package',
                                 cnv_paramsg,
                                 context=context,
                                 feedback=feedback,
                                 is_child_algorithm=True)

        feedback.pushConsoleInfo("csvs 1 cahnge to geopackage  ok  ")

        #results["OUTPUT"] = input_c["OUTPUT"]
        #return results

        #   集計用 人口+行政界  UNION
        input_union = input_c["OUTPUT"]

        feedback.setCurrentStep(8)
        #    create union  poplation mesh and input mesh

        param1 = {
            'INPUT': input_union,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT,
            'pareafield': 'div_area',
            'polsmpl': 'pvsum',
            'meshid': meshid,
            'meshlayer': meshLayer
        }

        #parameters['OUTPUT']
        #
        res1 = processing.run('QGIS_stat:AggregatePopMeshbyMeshAlgorithm',
                              param1,
                              context=context,
                              feedback=feedback,
                              is_child_algorithm=True)

        if feedback.isCanceled():
            return {}

        feedback.pushConsoleInfo(
            "csvs 1 AggregatePopMeshbyMeshAlgorithm  ok  ")
        numberof_under_limit = 0

        #numberof_under_limit = res1["LIMITPOL"]

        # レイヤをGeoPackage化
        alg_paramsg = {
            'LAYERS': res1["OUTPUT"],
            'OVERWRITE': True,
            'SAVE_STYLES': False,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        retg1 = processing.run('native:package',
                               alg_paramsg,
                               context=context,
                               feedback=feedback,
                               is_child_algorithm=True)
        last_output = retg1["OUTPUT"]

        new_mesh = retg1["OUTPUT"]

        mesh_layb = retg1["OUTPUT"]

        if type(mesh_layb) is str:
            mesh_layb = QgsVectorLayer(mesh_layb, "mesh", "ogr")

        numberof_under_limit = 0

        #    作業用レイヤの作成
        crs_str = mesh_layb.crs()

        layerURI = "Polygon?crs=" + crs_str.authid()
        #feedback.pushConsoleInfo( "work layer  " + layerURI  )
        resLayer = QgsVectorLayer(layerURI, "mesh_result", "memory")

        appended = {}

        adfields = []
        for field in mesh_layb.fields():
            #print(field.name(), field.typeName())
            adfields.append(field)
            #resLayer.addField(field)

        resLayer.dataProvider().addAttributes(adfields)
        resLayer.updateFields()

        lower_ids = []

        value_column = "snum"

        #    limit 値より小さい値のポリゴン数算出
        for f in mesh_layb.getFeatures():
            # feedback.pushConsoleInfo( "value  " +str( f["value"])  )
            if not f[value_column] is None:
                if f[value_column] > 0 and f[value_column] < limit_sample:
                    numberof_under_limit += 1
                    lower_ids.append(f[meshid])

        next_output = None

        stepi = 9

        #   集計結果が最小サンプルより小さいものがある場合
        if numberof_under_limit > 0:
            #  初回の場合は終了

            feedback.pushConsoleInfo("最初の集計で指定値以下の集計値がありましたので集計を中止しました")
            results["OUTPUT"] = None
            return results

            if uneven_div:

                rmid = []
                for tgid in (lower_ids):
                    feedback.pushConsoleInfo("lower id  " + str(tgid))

                    #  next_output   code   の下3桁 削除   C27210-02    -> C27210   が last_output の code 番号
                    #  next_output  では last_output  が同じ番号の最大4メッシュを削除する

                    # リミットより小さいレコードは旧レコードを退避
                    #  リミットにひっかかるレコードを再処理用リストから削除(同一親メッシュのものも削除)
                    #   不均等分割でリミット以下のデータがある場合は last_output -> 分割不能抽出   next_output  分割不能削除  next_output -> last_output 代入
                    parent_code = tgid[0:-3]

                    rmid.append(parent_code)

                addfeatures = []

                alg_paramsg_n = {
                    'LAYERS': last_output,
                    'OVERWRITE': False,
                    'SAVE_STYLES': False,
                    'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
                }
                lmesh = processing.run('native:package',
                                       alg_paramsg_n,
                                       context=context,
                                       feedback=feedback,
                                       is_child_algorithm=True)

                last_output = lmesh["OUTPUT"]

                if type(last_output) is str:
                    last_output = QgsVectorLayer(last_output, "mesh", "ogr")

                last_output.selectAll()

                for lf in last_output.getFeatures():

                    for pcode in (rmid):
                        #    feedback.pushConsoleInfo( "pcode  " + pcode+ " meshid =" + lf[meshid]  )
                        if lf[meshid] == pcode:
                            lf["fid"] = None
                            if not lf[value_column]:
                                lf[value_column] = 0.0

                            if lf[meshid] not in appended:

                                addfeatures.append(lf)
                                appended[lf[meshid]] = lf

                    #       feedback.pushConsoleInfo( "add feature   " + pcode  )

                resLayer.dataProvider().addFeatures(addfeatures)

                deleteFeatures = []

                if type(next_output) is str:
                    next_output = QgsVectorLayer(next_output, "mesh", "ogr")

                #   add check   20210310
                if next_output is None:
                    feedback.pushConsoleInfo("no next  array")
                else:
                    for nf in next_output.getFeatures():

                        for pcode in (rmid):
                            if nf[meshid][0:-3] == pcode:
                                deleteFeatures.append(nf.id())
                                feedback.pushConsoleInfo("delete id  " +
                                                         str(pcode))

                    next_output.dataProvider().deleteFeatures(deleteFeatures)

                last_output = next_output

        #  分割回数ループ
        for divide_c in range(1, maxdivide):
            feedback.setCurrentStep(stepi)

            stepi = stepi + 1

            if numberof_under_limit > 0:
                #  均等分割の場合は終了
                if not uneven_div:
                    break

            if last_output is None:
                feedback.pushConsoleInfo("last output  is none")
            else:
                if type(last_output) is str:
                    feedback.pushConsoleInfo("last output " + last_output)
                else:
                    feedback.pushConsoleInfo("last output " +
                                             last_output.name())

            alg_paramsg_m = {
                'LAYERS': last_output,
                'OVERWRITE': True,
                'SAVE_STYLES': False,
                'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
            }
            spmesh = processing.run('native:package',
                                    alg_paramsg_m,
                                    context=context,
                                    feedback=feedback,
                                    is_child_algorithm=True)

            new_mesh = agtools.SplitMeshLayer(spmesh["OUTPUT"], meshid)

            # statv  行政界別集計データ

            #  再度メッシュ集計
            param2 = {
                'INPUT': input_union,
                'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT,
                'pareafield': 'div_area',
                'polsmpl': 'pvsum',
                'meshid': meshid,
                'meshlayer': new_mesh
            }

            res2 = processing.run('QGIS_stat:AggregatePopMeshbyMeshAlgorithm',
                                  param2,
                                  context=context,
                                  feedback=feedback,
                                  is_child_algorithm=True)

            #numberof_under_limit = res2["LIMITPOL"]
            numberof_under_limit = 0
            # レイヤをGeoPackage化
            alg_paramsg2 = {
                'LAYERS': res2["OUTPUT"],
                'OVERWRITE': True,
                'SAVE_STYLES': False,
                'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
            }
            retg2 = processing.run('native:package',
                                   alg_paramsg2,
                                   context=context,
                                   feedback=feedback,
                                   is_child_algorithm=True)

            mesh_layb = retg2["OUTPUT"]

            if type(mesh_layb) is str:
                mesh_layb = QgsVectorLayer(mesh_layb, "mesh", "ogr")

                #features = mesh_layb.selectedFeatures()
                #feedback.pushConsoleInfo( "feature count  " +str( len(features))  )
            lower_ids = []
            for f in mesh_layb.getFeatures():
                #   feedback.pushConsoleInfo( "value  " +str( f["value"])  )
                if not f[value_column] is None:
                    if f[value_column] > 0 and f[value_column] < limit_sample:
                        numberof_under_limit += 1
                        lower_ids.append(f[meshid])

            if numberof_under_limit == 0:
                last_output = res2["OUTPUT"]
                next_output = retg2["OUTPUT"]
            else:
                #   不均等分割でリミット以下のデータがある場合は last_output -> 分割不能抽出   next_output  分割不能削除  next_output -> last_output 代入
                # last_output = res2["OUTPUT"]
                next_output = retg2["OUTPUT"]

            #   集計結果が最小サンプルより小さいものがある場合
            if numberof_under_limit > 0:
                #  均等分割の場合は終了
                if not uneven_div:

                    break

                #  不均等分割の場合は終了データを保全  それ以外のメッシュの分割
                else:
                    rmid = []
                    for tgid in (lower_ids):
                        feedback.pushConsoleInfo("lower id  " + str(tgid))

                        #  next_output   code   の下3桁 削除   C27210-02    -> C27210   が last_output の code 番号
                        #  next_output  では last_output  が同じ番号の最大4メッシュを削除する

                        # リミットより小さいレコードは旧レコードを退避
                        #  リミットにひっかかるレコードを再処理用リストから削除(同一親メッシュのものも削除)
                        #   不均等分割でリミット以下のデータがある場合は last_output -> 分割不能抽出   next_output  分割不能削除  next_output -> last_output 代入
                        parent_code = tgid[0:-3]

                        rmid.append(parent_code)

                    addfeatures = []

                    #if type(last_output) is str:
                    #    last_output =  QgsVectorLayer(last_output, "mesh", "ogr")

                    alg_paramsg_n = {
                        'LAYERS': last_output,
                        'OVERWRITE': False,
                        'SAVE_STYLES': False,
                        'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
                    }
                    lmesh = processing.run('native:package',
                                           alg_paramsg_n,
                                           context=context,
                                           feedback=feedback,
                                           is_child_algorithm=True)

                    #last_output.removeSelection()
                    last_output = lmesh["OUTPUT"]

                    if type(last_output) is str:
                        last_output = QgsVectorLayer(last_output, "mesh",
                                                     "ogr")

                    last_output.selectAll()

                    for lf in last_output.getFeatures():

                        for pcode in (rmid):
                            #    feedback.pushConsoleInfo( "pcode  " + pcode+ " meshid =" + lf[meshid]  )
                            if lf[meshid] == pcode:
                                lf["fid"] = None

                                if not lf[value_column]:
                                    lf[value_column] = 0.0

                                if lf[meshid] not in appended:

                                    addfeatures.append(lf)
                                    appended[lf[meshid]] = lf

                                    #addfeatures.append(lf)
                                    feedback.pushConsoleInfo("add feature   " +
                                                             pcode)

                    resLayer.dataProvider().addFeatures(addfeatures)

                    deleteFeatures = []

                    if type(next_output) is str:
                        next_output = QgsVectorLayer(next_output, "mesh",
                                                     "ogr")

                    for nf in next_output.getFeatures():

                        for pcode in (rmid):
                            if nf[meshid][0:-3] == pcode:
                                deleteFeatures.append(nf.id())
                                feedback.pushConsoleInfo("delete id  " +
                                                         str(pcode))

                    next_output.dataProvider().deleteFeatures(deleteFeatures)

                    last_output = next_output

        # Return the results of the algorithm. In this case our only result is
        # the feature sink which contains the processed features, but some
        # algorithms may return multiple feature sinks, calculated numeric
        # statistics, etc. These should all be included in the returned
        # dictionary, with keys matching the feature corresponding parameter
        # or output names.

        #  不均等分割の場合   最終作業レイヤの地物がはいってないかも
        if uneven_div:

            alg_paramsg_n = {
                'LAYERS': next_output,
                'OVERWRITE': False,
                'SAVE_STYLES': False,
                'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
            }
            lmesh = processing.run('native:package',
                                   alg_paramsg_n,
                                   context=context,
                                   feedback=feedback,
                                   is_child_algorithm=True)

            #last_output.removeSelection()
            last_output = lmesh["OUTPUT"]

            if type(last_output) is str:
                last_output = QgsVectorLayer(last_output, "mesh", "ogr")

                last_output.selectAll()

            addfeatures = []

            for lf in last_output.getFeatures():

                feedback.pushConsoleInfo("add features  meshid =" + lf[meshid])
                lf["fid"] = None
                if not lf[value_column]:
                    lf[value_column] = 0.0

                if lf[meshid] not in appended:

                    addfeatures.append(lf)
                    appended[lf[meshid]] = lf

                #addfeatures.append(lf)

            resLayer.dataProvider().addFeatures(addfeatures)

            # フォーマット変換(gdal_translate)
            alg_params = {
                'INPUT': resLayer,
                'OPTIONS': '',
                'OUTPUT': parameters['OUTPUT']
            }
            ocv = processing.run('gdal:convertformat',
                                 alg_params,
                                 context=context,
                                 feedback=feedback,
                                 is_child_algorithm=True)

            results["OUTPUT"] = ocv["OUTPUT"]
            return results

    #   均等分割の場合
        else:

            # フォーマット変換(gdal_translate)
            alg_params = {
                'INPUT': last_output,
                'OPTIONS': '',
                'OUTPUT': parameters['OUTPUT']
            }
            ocv = processing.run('gdal:convertformat',
                                 alg_params,
                                 context=context,
                                 feedback=feedback,
                                 is_child_algorithm=True)

            results["OUTPUT"] = ocv["OUTPUT"]
            return results
Esempio n. 28
0
    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        feedback = QgsProcessingMultiStepFeedback(4, model_feedback)
        results = {}
        outputs = {}

        # Mean coordinate(s)
        alg_params = {
            'INPUT': parameters['citycenter'],
            'UID': None,
            'WEIGHT': None,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['MeanCoordinates'] = processing.run('native:meancoordinates', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        # Execute SQL (distance)
        alg_params = {
            'INPUT_DATASOURCES': [parameters['citycenter'],parameters['inputfeatures2']],
            'INPUT_GEOMETRY_CRS': None,
            'INPUT_GEOMETRY_FIELD': '',
            'INPUT_GEOMETRY_TYPE': None,
            'INPUT_QUERY': 'select *, distance(centroid(transform((geometry),4326)) ,  transform((select geometry from input1),4326), true) as [%concat(@fieldnameprefix , \'Dist\')%]\nfrom input2',
            'INPUT_UID_FIELD': '',
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ExecuteSqlDistance'] = processing.run('qgis:executesql', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(2)
        if feedback.isCanceled():
            return {}

        # Field calculator (direction)
        alg_params = {
            'FIELD_LENGTH': 10,
            'FIELD_NAME': QgsExpression('concat( @fieldnameprefix , 'Dir')').evaluate(),
            'FIELD_PRECISION': 3,
            'FIELD_TYPE': 0,
            'FORMULA': 'degrees(azimuth(  \r\n\r\ntransform( make_point(  @Mean_coordinate_s__OUTPUT_maxx ,  @Mean_coordinate_s__OUTPUT_maxy ) ,  layer_property( @citycenter, \'crs\') , \'EPSG:54004\') , \r\ntransform(centroid($geometry) , layer_property (@inputfeatures2, \'crs\') , \'EPSG:54004\')))',
            'INPUT': outputs['ExecuteSqlDistance']['OUTPUT'],
            'NEW_FIELD': True,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['FieldCalculatorDirection'] = processing.run('qgis:fieldcalculator', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(3)
        if feedback.isCanceled():
            return {}

        # Field calculator(cardinal and ordinal direction)
        alg_params = {
            'FIELD_LENGTH': 10,
            'FIELD_NAME': QgsExpression('concat( @fieldnameprefix , 'CardOrd')').evaluate(),
            'FIELD_PRECISION': 3,
            'FIELD_TYPE': 2,
            'FORMULA': 'CASE\r\nWHEN attribute(concat(@fieldnameprefix, \'Dir\'))<=22.5 or attribute(concat(@fieldnameprefix, \'Dir\'))>=337.5 THEN \'N\'\r\nWHEN attribute(concat(@fieldnameprefix, \'Dir\'))<=67.5 and attribute(concat(@fieldnameprefix, \'Dir\'))>=22.5 THEN \'NE\'\r\nWHEN attribute(concat(@fieldnameprefix, \'Dir\'))<=(135-22.5) and attribute(concat(@fieldnameprefix, \'Dir\'))>=(45+22.5) THEN \'E\'\r\nWHEN attribute(concat(@fieldnameprefix, \'Dir\'))<=157.5 and attribute(concat(@fieldnameprefix, \'Dir\'))>=112.5THEN \'SE\'\r\nWHEN attribute(concat(@fieldnameprefix, \'Dir\'))<=292.5 and attribute(concat(@fieldnameprefix, \'Dir\'))>=247.5 THEN \'W\'\r\nWHEN attribute(concat(@fieldnameprefix, \'Dir\'))<=247.5 and attribute(concat(@fieldnameprefix, \'Dir\'))>=202.5 THEN \'SW\'\r\nWHEN attribute(concat(@fieldnameprefix, \'Dir\'))<=337.5 and attribute(concat(@fieldnameprefix, \'Dir\'))>=292.5 THEN \'NW\'\r\nWHEN attribute(concat(@fieldnameprefix, \'Dir\'))<=202.5and attribute(concat(@fieldnameprefix, \'Dir\'))>=157.5 THEN \'S\'\r\nEND\r\n\r\n',
            'INPUT': outputs['FieldCalculatorDirection']['OUTPUT'],
            'NEW_FIELD': True,
            'OUTPUT': parameters['DirectionDistanceOutput']
        }
        outputs['FieldCalculatorcardinalAndOrdinalDirection'] = processing.run('qgis:fieldcalculator', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        results['DirectionDistanceOutput'] = outputs['FieldCalculatorcardinalAndOrdinalDirection']['OUTPUT']
        return results
    def processAlgorithm(self, parameters, context, model_feedback):
        feedback = QgsProcessingMultiStepFeedback(8, model_feedback)
        results = {}
        outputs = {}

        tracks = self.parameterAsSource(parameters, self.TRACKS, context)

        # prepare_tracks
        alg_params = {
            "TRACKS": parameters[self.TRACKS],
            "AXIS": parameters[self.AXIS],
            "NAME_FIELD": parameters[self.NAME_FIELD],
            "OUTPUT": QgsProcessing.TEMPORARY_OUTPUT,
        }
        outputs["PrepareTracks"] = processing.run(
            "precourlis:prepare_tracks",
            alg_params,
            context=context,
            feedback=feedback,
            is_child_algorithm=True,
        )
        current = outputs["PrepareTracks"]["OUTPUT"]

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        # addautoincrementalfield
        alg_params = {
            "INPUT": current,
            "FIELD_NAME": "sec_index",
            "START": 1,
            "GROUP_FIELDS": [],
            "SORT_EXPRESSION": '"abs_long"',
            "SORT_ASCENDING": True,
            "SORT_NULLS_FIRST": False,
            "OUTPUT": QgsProcessing.TEMPORARY_OUTPUT,
        }
        outputs["AddAutoincrementalField"] = processing.run(
            "native:addautoincrementalfield",
            alg_params,
            context=context,
            feedback=feedback,
            is_child_algorithm=True,
        )
        current = outputs["AddAutoincrementalField"]["OUTPUT"]

        feedback.setCurrentStep(2)
        if feedback.isCanceled():
            return {}

        # fieldcalculator
        alg_params = {
            "INPUT": current,
            "FIELD_NAME": "sec_id",
            "FIELD_TYPE": 0,
            "FIELD_LENGTH": 10,
            "FIELD_PRECISION": 3,
            "NEW_FIELD": False,
            "FORMULA": ' "sec_index" ',
            "OUTPUT": QgsProcessing.TEMPORARY_OUTPUT,
        }
        outputs["FieldCalculator"] = processing.run(
            "qgis:fieldcalculator",
            alg_params,
            context=context,
            feedback=feedback,
            is_child_algorithm=True,
        )
        current = outputs["FieldCalculator"]["OUTPUT"]

        feedback.setCurrentStep(3)
        if feedback.isCanceled():
            return {}

        strict_distance = self.parameterAsBool(
            parameters, self.STRICT_DISTANCE, context
        )
        if strict_distance:
            # pointsalonglines
            alg_params = {
                "INPUT": current,
                "DISTANCE": parameters[self.DISTANCE],
                "OUTPUT": QgsProcessing.TEMPORARY_OUTPUT,
            }
            outputs["PointsAlongLines"] = processing.run(
                "precourlis:pointsalonglines",
                alg_params,
                context=context,
                feedback=feedback,
                is_child_algorithm=True,
            )
            current = outputs["PointsAlongLines"]["OUTPUT"]
            points_order_field = "distance"
        else:
            # v.to.points
            v_to_points = QgsApplication.processingRegistry().createAlgorithmById(
                "grass7:v.to.points"
            )
            alg_params = {
                "-i": True,
                "-t": False,
                "dmax": parameters[self.DISTANCE],
                "input": current,
                "type": [1],
                "use": 1,
                "output": v_to_points.parameterDefinition(
                    "output"
                ).generateTemporaryDestination(),
            }
            outputs["Vtopoints"] = processing.run(
                "grass7:v.to.points",
                alg_params,
                context=context,
                feedback=feedback,
                is_child_algorithm=True,
            )
            current = outputs["Vtopoints"]["output"]
            points_order_field = "fid"

        feedback.setCurrentStep(4)
        if feedback.isCanceled():
            return {}

        # assignprojection
        alg_params = {
            "INPUT": current,
            "CRS": tracks.sourceCrs(),
            "OUTPUT": QgsProcessing.TEMPORARY_OUTPUT,
        }
        outputs["AssignProjection"] = processing.run(
            "native:assignprojection",
            alg_params,
            context=context,
            feedback=feedback,
            is_child_algorithm=True,
        )
        current = outputs["AssignProjection"]["OUTPUT"]

        feedback.setCurrentStep(5)
        if feedback.isCanceled():
            return {}

        # point_to_lines
        alg_params = {
            "INPUT": current,
            "FIRST_SECTION_ABS_LONG": parameters.get(self.FIRST_SECTION_ABS_LONG, None),
            "FIRST_AXIS_POINT_ABS_LONG": parameters.get(
                self.FIRST_AXIS_POINT_ABS_LONG, None
            ),
            "GROUP_FIELD": "sec_id",
            "ORDER_FIELD": points_order_field,
            "OUTPUT": QgsProcessing.TEMPORARY_OUTPUT,
        }
        outputs["PointsToLines"] = processing.run(
            "precourlis:points_to_lines",
            alg_params,
            context=context,
            feedback=feedback,
            is_child_algorithm=True,
        )
        current = outputs["PointsToLines"]["OUTPUT"]

        feedback.setCurrentStep(6)
        if feedback.isCanceled():
            return {}

        # import_layer_from_dem (edit layer in place with edit buffer)
        layer = context.getMapLayer(current)
        alg_params = {
            "INPUT": layer,
            "LAYER_NAME": "zfond",
            "DEM": parameters[self.DEM],
            "BAND": 1,
        }
        outputs["ImportLayerFromDem"] = processing.run(
            "precourlis:import_layer_from_dem",
            alg_params,
            context=context,
            feedback=feedback,
            is_child_algorithm=True,
        )

        feedback.setCurrentStep(7)
        if feedback.isCanceled():
            return {}

        # orderbyexpression (dump layer with changes from edit buffer)
        layer.selectAll()
        alg_params = {
            "INPUT": layer,
            "EXPRESSION": '"sec_id"',
            "ASCENDING": True,
            "NULLS_FIRST": False,
            "OUTPUT": self.parameterAsOutputLayer(parameters, self.OUTPUT, context),
        }
        outputs["OrderByExpression"] = processing.run(
            "native:orderbyexpression",
            alg_params,
            context=context,
            feedback=feedback,
            is_child_algorithm=True,
        )
        current = outputs["OrderByExpression"]["OUTPUT"]

        results["OUTPUT"] = current
        return results
Esempio n. 30
0
    def processAlgorithm(self, parameters, context, model_feedback):
        feedback = QgsProcessingMultiStepFeedback(4, model_feedback)
        results = {}
        outputs = {}

        sections = self.parameterAsSource(parameters, self.SECTIONS, context)

        # Retreive first section longitudinal abscissa
        request = (QgsFeatureRequest().setFlags(
            QgsFeatureRequest.NoGeometry
            | QgsFeatureRequest.SubsetOfAttributes).setSubsetOfAttributes(
                ["abs_long"],
                sections.fields()).addOrderBy('"sec_id"', True,
                                              True).setLimit(1))
        first_section = next(sections.getFeatures(request))
        first_abs_long = first_section.attribute("abs_long")

        # Lines to points
        alg_params = {
            "INPUT":
            parameters[self.SECTIONS],
            "OUTPUT":
            QgsProcessingUtils.generateTempFilename("lines_to_points.shp"),
        }
        outputs["LinesToPoints"] = processing.run(
            "precourlis:lines_to_points",
            alg_params,
            context=context,
            feedback=feedback,
            is_child_algorithm=True,
        )
        current = outputs["LinesToPoints"]["OUTPUT"]

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        # Interpolate points
        alg_params = {
            "SECTIONS":
            current,
            "AXIS":
            parameters[self.AXIS],
            "CONSTRAINT_LINES":
            parameters.get(self.CONSTRAINT_LINES),
            "LONG_STEP":
            parameters[self.LONG_STEP],
            "LAT_STEP":
            parameters[self.LAT_STEP],
            "ATTR_CROSS_SECTION":
            "sec_id",
            "OUTPUT":
            QgsProcessingUtils.generateTempFilename("interpolate_points.shp"),
        }
        outputs["InterpolatePoints"] = processing.run(
            "precourlis:interpolate_points",
            alg_params,
            context=context,
            feedback=feedback,
            is_child_algorithm=True,
        )
        current = outputs["InterpolatePoints"]["OUTPUT"]

        feedback.setCurrentStep(2)
        if feedback.isCanceled():
            return {}

        # assignprojection
        alg_params = {
            "INPUT": current,
            "CRS": sections.sourceCrs(),
            "OUTPUT": QgsProcessing.TEMPORARY_OUTPUT,
        }
        outputs["AssignProjection"] = processing.run(
            "native:assignprojection",
            alg_params,
            context=context,
            feedback=feedback,
            is_child_algorithm=True,
        )
        current = outputs["AssignProjection"]["OUTPUT"]

        feedback.setCurrentStep(3)
        if feedback.isCanceled():
            return {}

        output = QgsProcessingOutputLayerDefinition(parameters[self.OUTPUT])
        output.destinationName = self.tr("Interpolated")

        # Points to lines
        alg_params = {
            "INPUT": current,
            "AXIS": parameters[self.AXIS],
            "FIRST_SECTION_ABS_LONG": first_abs_long,
            "GROUP_FIELD": "abs_long",
            "ORDER_FIELD": "p_id",
            "OUTPUT": output,
        }
        outputs["PointsToLines"] = processing.run(
            "precourlis:points_to_lines",
            alg_params,
            context=context,
            feedback=feedback,
            is_child_algorithm=True,
        )
        current = outputs["PointsToLines"]["OUTPUT"]

        results["OUTPUT"] = current
        return results