def grassMapsetFolder():
     """
     Creates and returns the GRASS temporary DB LOCATION directory.
     """
     folder = os.path.join(Grass7Utils.grassDataFolder(), 'temp_location')
     mkdir(folder)
     return folder
 def grassDataFolder():
     """
     Creates and returns the GRASS temporary DB directory.
     """
     tempfolder = os.path.normpath(
         os.path.join(QgsProcessingUtils.tempFolder(), 'grassdata'))
     mkdir(tempfolder)
     return tempfolder
    def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.INPUT, context)
        fieldName = self.parameterAsString(parameters, self.FIELD, context)
        directory = self.parameterAsString(parameters, self.OUTPUT, context)

        mkdir(directory)

        fieldIndex = source.fields().lookupField(fieldName)
        uniqueValues = source.uniqueValues(fieldIndex)
        baseName = os.path.join(directory, '{0}'.format(fieldName))

        fields = source.fields()
        crs = source.sourceCrs()
        geomType = source.wkbType()

        total = 100.0 / len(uniqueValues) if uniqueValues else 1
        output_layers = []

        for current, i in enumerate(uniqueValues):
            if feedback.isCanceled():
                break
            fName = u'{0}_{1}.shp'.format(baseName, str(i).strip())
            feedback.pushInfo(self.tr('Creating layer: {}').format(fName))

            sink, dest = QgsProcessingUtils.createFeatureSink(
                fName, context, fields, geomType, crs)

            filter = '{} = {}'.format(QgsExpression.quotedColumnRef(fieldName),
                                      QgsExpression.quotedValue(i))
            req = QgsFeatureRequest().setFilterExpression(filter)

            count = 0
            for f in source.getFeatures(req):
                if feedback.isCanceled():
                    break
                sink.addFeature(f, QgsFeatureSink.FastInsert)
                count += 1
            feedback.pushInfo(
                self.tr('Added {} features to layer').format(count))
            output_layers.append(fName)
            del sink

            feedback.setProgress(int(current * total))

        return {self.OUTPUT: directory, self.OUTPUT_LAYERS: output_layers}
예제 #4
0
def configFile(alg, parameters, context, feedback, outputTxt=False):
    """Handle inline configuration
    :param parameters:
    """
    # Where is the GRASS7 user directory ?
    userGrass7Path = rliPath()
    if not os.path.isdir(userGrass7Path):
        mkdir(userGrass7Path)
    if not os.path.isdir(os.path.join(userGrass7Path, 'output')):
        mkdir(os.path.join(userGrass7Path, 'output'))

    # If we have a configuration file, we need to copy it into user dir
    if parameters['config']:
        fileName = alg.parameterAsString(parameters, 'config', context)
        configFilePath = os.path.join(userGrass7Path,
                                      os.path.basename(fileName))
        # Copy the file
        shutil.copy(parameters['config'], configFilePath)
        # Change the parameter value
        parameters['config'] = os.path.basename(configFilePath)
    # Handle inline configuration
    elif parameters['config_txt']:
        # Creates a temporary txt file in user r.li directory
        tempConfig = os.path.basename(getTempFilename())
        configFilePath = os.path.join(userGrass7Path, tempConfig)
        # Inject rules into temporary txt file
        with open(configFilePath, "w") as f:
            f.write(alg.parameterAsString(parameters, 'config_txt', context))
            f.write("\n")

        # Use temporary file as rules file
        parameters['config'] = os.path.basename(configFilePath)
        alg.removeParameter('config_txt')

    # For ascii output, we need a virtual output
    if outputTxt:
        param = QgsProcessingParameterString(
            'output', 'virtual output',
            'a' + os.path.basename(getTempFilename()), False, False)
        alg.addParameter(param)

    alg.processCommand(parameters, context, feedback, outputTxt)

    # Remove Config file:
    removeConfigFile(alg, parameters, context)
    def createTempMapset():
        """
        Creates a temporary location and mapset(s) for GRASS data
        processing. A minimal set of folders and files is created in the
        system's default temporary directory. The settings files are
        written with sane defaults, so GRASS can do its work. The mapset
        projection will be set later, based on the projection of the first
        input image or vector
        """
        folder = Grass7Utils.grassMapsetFolder()
        mkdir(os.path.join(folder, 'PERMANENT'))
        mkdir(os.path.join(folder, 'PERMANENT', '.tmp'))
        Grass7Utils.writeGrassWindow(
            os.path.join(folder, 'PERMANENT', 'DEFAULT_WIND'))
        with open(os.path.join(folder, 'PERMANENT', 'MYNAME'), 'w') as outfile:
            outfile.write(
                'QGIS GRASS GIS 7 interface: temporary data processing location.\n'
            )

        Grass7Utils.writeGrassWindow(os.path.join(folder, 'PERMANENT', 'WIND'))
        mkdir(os.path.join(folder, 'PERMANENT', 'sqlite'))
        with open(os.path.join(folder, 'PERMANENT', 'VAR'), 'w') as outfile:
            outfile.write('DB_DRIVER: sqlite\n')
            outfile.write(
                'DB_DATABASE: $GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db\n'
            )
예제 #6
0
 def defaultModelsFolder():
     folder = str(os.path.join(userFolder(), 'models'))
     mkdir(folder)
     return os.path.abspath(folder)
def preconfiguredAlgorithmsFolder():
    folder = str(os.path.join(userFolder(), 'preconfigured'))
    mkdir(folder)
    return folder
예제 #8
0
def defaultScriptsFolder():
    folder = str(os.path.join(userFolder(), "scripts"))
    mkdir(folder)
    return os.path.abspath(folder)