コード例 #1
0
    def createDataItem(self, path, parentItem):  # pylint: disable=missing-docstring
        file_info = QFileInfo(path)

        if file_info.suffix().lower() == 'style':
            return EsriStyleItem(parentItem, file_info.fileName(), path)
        elif file_info.suffix().lower() == 'lyr':
            return EsriLyrItem(parentItem, file_info.fileName(), path)
        elif DatDropHandler.is_bookmark_dat(path):
            return EsriDatItem(parentItem, file_info.fileName(), path)
        elif file_info.suffix().lower() in ('mxd', 'pmf', 'sxd', '3dd', 'mxt'):
            return EsriMxdItem(parentItem, file_info.fileName(), path)
        return None
コード例 #2
0
def load_mf_obd(self):
    APEXMOD_path_dict = self.dirs_and_paths()
    settings = QSettings()
    if settings.contains('/APEXMOD/LastInputPath'):
        path = str(settings.value('/APEXMOD/LastInputPath'))
    else:
        path = ''
    title = "Provide 'modflow.obd' file!"
    inFileName, __ = QFileDialog.getOpenFileNames(
        None, title, path,
        "Observation data (*.obd *.OBD);; All files (*.*)"
        )
    if inFileName:
        settings.setValue('/APEXMOD/LastInputPath', os.path.dirname(str(inFileName)))           
        output_dir = APEXMOD_path_dict['apexmf_model']
        inInfo = QFileInfo(inFileName[0])
        inFile = inInfo.fileName()
        pattern = os.path.splitext(inFileName[0])[0] + '.*'
        # inName = os.path.splitext(inFile)[0]
        inName = 'modflow'
        for f in glob.iglob(pattern):
            suffix = os.path.splitext(f)[1]
            if os.name == 'nt':
                outfile = ntpath.join(output_dir, inName + '.obd')
            else:
                outfile = posixpath.join(output_dir, inName + '.obd')             
            shutil.copy(f, outfile)
コード例 #3
0
 def selFile(self):
     sf = QFileInfo(QFileDialog.getOpenFileName(self, 'Select SLD file', '', 'SLD files (*.sld)'))
     f = sf.fileName()
     if f!='':
         df = os.path.join(os.path.join(self.plugin_dir, 'sld'), f)
         shutil.copy(sf.absoluteFilePath(), df)
     return f
コード例 #4
0
ファイル: xprint.py プロジェクト: IZSVenezie/VetEpiGIS-Tool
 def selFile(self):
     sf = QFileInfo(QFileDialog.getOpenFileName(self, 'Open logo file', QDir.homePath(), 'Image files (*.png)'))
     f = sf.fileName()
     if f!='':
         self.logopath = sf.absoluteFilePath()
         self.label.setPixmap(QPixmap(self.logopath))
     return f
コード例 #5
0
    def AddVector(self):

        file = QFileDialog.getOpenFileName(self.dlg, "Open shapefile", ".",
                                           "Shp (*.shp)")
        fileInfo = QFileInfo(file)
        layer = QgsVectorLayer(file, fileInfo.fileName(), "ogr")
        QgsProject.instance().addMapLayer(layer)
        self.canvas.setExtent(layer.extent())
コード例 #6
0
 def selFile(self):
     sf = QFileInfo(QFileDialog.getOpenFileName(self, 'Select SLD file', '', 'SLD files (*.sld)')[0])
     f = sf.fileName()
     if f!='':
         df = os.path.join(os.path.join(self.plugin_dir, 'sld'), f)
         if not (os.path.samefile(sf, df)):
             shutil.copy(sf.absoluteFilePath(), df)
     return f
コード例 #7
0
ファイル: xprint.py プロジェクト: IZSVenezie/VetEpiGIS-Tool
 def outFile(self):
     of = QFileInfo(
         QFileDialog.getSaveFileName(self, 'Output map file',
                                     QDir.homePath(),
                                     'PDF files (*.pdf)')[0])
     f = of.fileName()
     if f != '':
         self.lineEdit_3.setText(of.absoluteFilePath())
     return f
コード例 #8
0
def sub_shapefile(self):
    APEXMOD_path_dict = self.dirs_and_paths() 
    settings = QSettings()
    if settings.contains('/APEXMOD/LastInputPath'):
        path = str(settings.value('/APEXMOD/LastInputPath'))
    else:
        path = ''
    title = "Choose SUB Shapefile!"
    inFileName, __ = QFileDialog.getOpenFileNames(
        None, title, path,
        "Shapefiles (*.shp);;All files (*.*)"
        )
    if inFileName:
        settings.setValue('/APEXMOD/LastInputPath', os.path.dirname(str(inFileName)))           
        output_dir = APEXMOD_path_dict['org_shps']
        inInfo = QFileInfo(inFileName[0])
        inFile = inInfo.fileName()
        pattern = os.path.splitext(inFileName[0])[0] + '.*'
        
        inName = 'sub_org'
        for f in glob.iglob(pattern):
            suffix = os.path.splitext(f)[1]
            if os.name == 'nt':
                outfile = ntpath.join(output_dir, inName + suffix)
            else:
                outfile = posixpath.join(output_dir, inName + suffix)                    
            shutil.copy(f, outfile)
        if os.name == 'nt':
            sub_obj = ntpath.join(output_dir, inName + ".shp")
        else:
            sub_obj = posixpath.join(output_dir, inName + ".shp")
        # time stamp
        time = datetime.now().strftime('[%m/%d/%y %H:%M:%S]')
        self.dlg.textEdit_sm_link_log.append(time+' -> ' + "Checking SUB geometries ... processing")
        self.dlg.label_StepStatus.setText("Checking 'SUB' ... ")
        QCoreApplication.processEvents()
        # fixgeometries
        sub_shp_file = 'sub_apex.shp'
        sub_shp_f = os.path.join(output_dir, sub_shp_file)
        params = {
            'INPUT': sub_obj,
            'OUTPUT': sub_shp_f
        }
        processing.run('native:fixgeometries', params)
        layer = QgsVectorLayer(sub_shp_f, '{0} ({1})'.format("sub","APEX"), 'ogr')

        # Put in the group          
        root = QgsProject.instance().layerTreeRoot()
        swat_group = root.findGroup("APEX") 
        QgsProject.instance().addMapLayer(layer, False)
        swat_group.insertChildNode(0, QgsLayerTreeLayer(layer))
        self.dlg.lineEdit_subbasin_shapefile.setText(sub_shp_f)

        time = datetime.now().strftime('[%m/%d/%y %H:%M:%S]')
        self.dlg.textEdit_sm_link_log.append(time+' -> ' + "Checking SUB geometries ... passed")
        self.dlg.label_StepStatus.setText("Step Status: ")
        QCoreApplication.processEvents()   
コード例 #9
0
ファイル: xprint.py プロジェクト: IZSVenezie/VetEpiGIS-Tool
 def selFile(self):
     sf = QFileInfo(
         QFileDialog.getOpenFileName(self, 'Open logo file',
                                     QDir.homePath(),
                                     'Image files (*.png)')[0])
     f = sf.fileName()
     if f != '':
         self.logopath = sf.absoluteFilePath()
         self.label.setPixmap(QPixmap(self.logopath))
     return f
コード例 #10
0
    def define_year_soils(self):
        if self.window2.comboBox.currentText() == '2019':
            # display file in canvas
            fileCI = QGIS_DIR + '/python/plugins/coal_mine/Base_dados_solos.shp'
            file_info_norm = QFileInfo(str(fileCI))
            # vector layer
            vlayer = QgsVectorLayer(fileCI, file_info_norm.fileName(), 'ogr')

            if not vlayer.isValid():
                return
            QgsProject.instance().addMapLayer(vlayer)
            #self.canvas.setExtent(vlayer.extent())
        if self.window2.comboBox.currentText() == '2020':
            QMessageBox.about(self.window2, 'teste', '2020')
        if self.window2.comboBox.currentText() == '2021':
            QMessageBox.about(self.window2, 'teste', '2021')
コード例 #11
0
    def AddRaster(self):
        file = QFileDialog.getOpenFileName(
            self.dlg, "Open raster", ".",
            "Images(*.tif *.png *.jpg *.jpeg *.img)")
        fileInfo = QFileInfo(file)

        # add the raster
        layer = QgsRasterLayer(file, fileInfo.fileName(), "gdal")

        # add layer to the registry
        QgsProject.instance().addMapLayer(layer)

        # set extent to the extent of our layer
        self.canvas.setExtent(layer.extent())

        # set the map canvas layer set
        self.canvas.setLayerSet([QgsMapCanvasLayer(layer)])
コード例 #12
0
ファイル: write_rt3d.py プロジェクト: spark-brc/QSWATMOD2
def use_obs_points(self):
    QSWATMOD_path_dict = self.dirs_and_paths()

    settings = QSettings()
    if settings.contains('/QSWATMOD2/LastInputPath'):
        path = str(settings.value('/QSWATMOD2/LastInputPath'))
    else:
        path = ''
    title = "Choose RT3D observation point shapefile"
    inFileName, __ = QFileDialog.getOpenFileName(
        None, title, path, "Shapefiles (*.shp);; All files (*.*)")

    if inFileName:
        settings.setValue('/QSWATMOD2/LastInputPath',
                          os.path.dirname(str(inFileName)))
        Out_folder = QSWATMOD_path_dict['org_shps']
        inInfo = QFileInfo(inFileName)
        inFile = inInfo.fileName()
        pattern = os.path.splitext(inFileName)[0] + '.*'

        # inName = os.path.splitext(inFile)[0]
        inName = 'rt3d_obs_points'
        for f in glob.iglob(pattern):
            suffix = os.path.splitext(f)[1]
            if os.name == 'nt':
                outfile = ntpath.join(Out_folder, inName + suffix)
            else:
                outfile = posixpath.join(Out_folder, inName + suffix)
            shutil.copy(f, outfile)
        if os.name == 'nt':
            rt3d_obs_points = ntpath.join(Out_folder, inName + ".shp")
        else:
            rt3d_obs_points = posixpath.join(Out_folder, inName + ".shp")

        layer = QgsVectorLayer(rt3d_obs_points,
                               '{0} ({1})'.format("rt3d_obs_points",
                                                  "RT3D"), 'ogr')

        # Put in the group
        root = QgsProject.instance().layerTreeRoot()
        rt3d_group = root.findGroup("RT3D")
        QgsProject.instance().addMapLayer(layer, False)
        rt3d_group.insertChildNode(0, QgsLayerTreeLayer(layer))
        self.lineEdit_rt3d_obs_points.setText(rt3d_obs_points)
コード例 #13
0
def get_rat(raster_layer, band, colors=('R', 'G', 'B', 'A')):
    """Extracts RAT from raster layer and given band

    :param raster_layer: the raster layer to classify
    :type raster_layer: QgsRasterLayer
    :param band: band number (1-based)
    :type band: int
    :param colors: name of the RGB(A) columns for sidecar DBF files, defaults to ('R', 'G', 'B', 'A')
    :type red_column_name: tuple, optional
    :return: RAT
    :rtype: RAT
    """

    headers = []
    values = {}
    fields = {}
    # For sidecar files
    path = None

    COLOR_ROLES = (gdal.GFU_Red, gdal.GFU_Green, gdal.GFU_Blue, gdal.GFU_Alpha)

    is_sidecar = False

    ds = gdal.OpenEx(raster_layer.source())
    if ds:
        band = ds.GetRasterBand(band)
        if band:
            rat = band.GetDefaultRAT()
            if rat is not None:
                for i in range(0, rat.GetColumnCount()):
                    column = rat.GetNameOfCol(i)
                    headers.append(column)
                    values[column] = []
                    fields[column] = RATField(column, rat.GetUsageOfCol(i),
                                              rat.GetTypeOfCol(i))

                for r in range(0, rat.GetRowCount()):
                    for c in range(0, rat.GetColumnCount()):
                        column = headers[c]
                        if fields[column].type == gdal.GFT_Integer:
                            values[headers[c]].append(rat.GetValueAsInt(r, c))
                        elif fields[column].type == gdal.GFT_Real:
                            values[headers[c]].append(
                                rat.GetValueAsDouble(r, c))
                        else:
                            values[headers[c]].append(
                                html.unescape(rat.GetValueAsString(r, c)))

            path = raster_layer.source() + '.aux.xml'

    # Search for sidecar DBF files, `band` is ignored!
    if not values:

        info = QFileInfo(raster_layer.publicSource())
        directory = info.dir().path()
        basename = info.baseName()
        filename = info.fileName()
        candidates = (basename + '.dbf', basename + '.vat.dbf',
                      filename + '.dbf', filename + '.vat.dbf')

        for candidate in candidates:
            if os.path.exists(os.path.join(directory, candidate)):
                rat_layer = QgsVectorLayer(os.path.join(directory, candidate),
                                           'rat', 'ogr')
                if rat_layer.isValid():
                    path = os.path.join(directory, candidate)
                    for f in rat_layer.fields():
                        headers.append(f.name())
                        if f.name().upper() in colors:
                            fields[f.name()] = RATField(
                                f.name(),
                                COLOR_ROLES[colors.index(f.name().upper())],
                                gdal.GFT_Integer if f.type()
                                in (QVariant.Int,
                                    QVariant.LongLong) else gdal.GFT_Real)
                        elif f.name().upper() == 'COUNT':
                            fields[f.name()] = RATField(
                                f.name(), gdal.GFU_PixelCount,
                                gdal.GFT_Integer)
                        elif f.name().upper() == 'VALUE':
                            fields[f.name()] = RATField(
                                f.name(), gdal.GFU_MinMax,
                                gdal.GFT_Integer if f.type()
                                in (QVariant.Int,
                                    QVariant.LongLong) else gdal.GFT_Real)
                        else:
                            if f.type() in (QVariant.Int, QVariant.LongLong):
                                type = gdal.GFT_Integer
                            elif f.type() == QVariant.Double:
                                type = gdal.GFT_Real
                            else:
                                type = gdal.GFT_String

                            fields[f.name()] = RATField(
                                f.name(), gdal.GFU_Generic, type)

                    for header in headers:
                        values[header] = []
                    for f in rat_layer.getFeatures():
                        for header in headers:
                            values[header].append(f.attribute(header))
                    is_sidecar = True
                    break

    # Colors
    if headers:
        red = None
        green = None
        blue = None
        alpha = None
        is_integer = False

        for name, f in fields.items():
            if f.usage == gdal.GFU_Red:
                red = name
                is_integer = f.type == gdal.GFT_Integer
                continue
            if f.usage == gdal.GFU_Green:
                green = name
                continue
            if f.usage == gdal.GFU_Blue:
                blue = name
                continue
            if f.usage == gdal.GFU_Alpha:
                alpha = name
                continue

        if red and green and blue:
            headers.append(RAT_COLOR_HEADER_NAME)
            values[RAT_COLOR_HEADER_NAME] = []
            for i in range(len(values[red])):
                func = 'fromRgb' if is_integer else 'fromRgbF'
                if alpha:
                    values[RAT_COLOR_HEADER_NAME].append(
                        getattr(QColor,
                                func)(values[red][i], values[green][i],
                                      values[blue][i], values[alpha][i]))
                else:
                    values[RAT_COLOR_HEADER_NAME].append(
                        getattr(QColor, func)(values[red][i], values[green][i],
                                              values[blue][i]))

    return RAT(values, is_sidecar, fields, path)
コード例 #14
0
ファイル: xprint.py プロジェクト: IZSVenezie/VetEpiGIS-Tool
 def outFile(self):
     of = QFileInfo(QFileDialog.getSaveFileName(self, 'Output map file', QDir.homePath(), 'PDF files (*.pdf)'))
     f = of.fileName()
     if f!='':
         self.lineEdit_3.setText(of.absoluteFilePath())
     return f
コード例 #15
0
ファイル: write_rt3d.py プロジェクト: spark-brc/QSWATMOD2
def loadP(self):
    QSWATMOD_path_dict = self.dirs_and_paths()
    settings = QSettings()
    if settings.contains('/QSWATMOD2/LastInputPath'):
        path = str(settings.value('/QSWATMOD2/LastInputPath'))
    else:
        path = ''
    title = "Choose Initial P Rasterfile"
    inFileName, __ = QFileDialog.getOpenFileName(
        None, title, path, "Rasterfiles (*.tif);; All files (*.*)")
    if inFileName:
        settings.setValue('/QSWATMOD2/LastInputPath',
                          os.path.dirname(str(inFileName)))
        Out_folder = QSWATMOD_path_dict['org_shps']
        inInfo = QFileInfo(inFileName)
        inFile = inInfo.fileName()
        pattern = os.path.splitext(inFileName)[0] + '.*'
        baseName = inInfo.baseName()
        # inName = os.path.splitext(inFile)[0]
        inName = 'p'
        for f in glob.iglob(pattern):
            suffix = os.path.splitext(f)[1]
            if os.name == 'nt':
                outfile = ntpath.join(Out_folder, inName + suffix)
            else:
                outfile = posixpath.join(Out_folder, inName + suffix)
            shutil.copy(f, outfile)
        if os.name == 'nt':
            shp = ntpath.join(Out_folder, inName + ".tif")
        else:
            shp = posixpath.join(Out_folder, inName + ".tif")
        # Delete existing "bot_elev (SMfolder)" raster file"
        for lyr in list(QgsProject.instance().mapLayers().values()):
            if lyr.name() == ("p (DATA)"):
                QgsProject.instance().removeMapLayers([lyr.id()])
        layer = QgsRasterLayer(shp, '{0} ({1})'.format("p", "DATA"))
        # Put in the group
        root = QgsProject.instance().layerTreeRoot()
        mf_group = root.findGroup("RT3D")
        QgsProject.instance().addMapLayer(layer, False)
        mf_group.insertChildNode(0, QgsLayerTreeLayer(layer))
        self.lineEdit_p_r.setText(shp)

    des = 'Extracting P CONC from Raster'
    self.time_stamp_start(des)
    input1 = QgsProject.instance().mapLayersByName("rt3d_grid (RT3D)")[0]
    input2 = QgsProject.instance().mapLayersByName("p (DATA)")[0]
    provider1 = input1.dataProvider()
    provider2 = input2.dataProvider()
    rpath = provider2.dataSourceUri()
    if provider1.fields().indexFromName("p_mean") != -1:
        attrIdx = provider1.fields().indexFromName("p_mean")
        provider1.deleteAttributes([attrIdx])
    params = {
        'INPUT_RASTER': input2,
        'RASTER_BAND': 1,
        'INPUT_VECTOR': input1,
        'COLUMN_PREFIX': 'p_',
        'STATS': [2]
    }
    processing.run("qgis:zonalstatistics", params)
    self.time_stamp_end(des)
コード例 #16
0
def import_mf_grid(self):
    # Initiate function
    APEXMOD_path_dict = self.dirs_and_paths()
    settings = QSettings()
    if settings.contains('/APEXMOD/LastInputPath'):
        path = str(settings.value('/APEXMOD/LastInputPath'))
    else:
        path = ''
    title = "Choose MODFLOW Grid Shapefile!"
    inFileName, __ = QFileDialog.getOpenFileNames(
        None, title, path,
        "Shapefiles (*.shp);;All files (*.*)"
        )
    if inFileName:
        settings.setValue('/APEXMOD/LastInputPath', os.path.dirname(str(inFileName)))
        output_dir = APEXMOD_path_dict['org_shps']
        inInfo = QFileInfo(inFileName[0])
        inFile = inInfo.fileName()
        pattern = os.path.splitext(inFileName[0])[0] + '.*'

        time = datetime.now().strftime('[%m/%d/%y %H:%M:%S]')
        self.dlg.textEdit_sm_link_log.append(time+' -> ' + "Importing MODFLOW object ... processing")
        self.dlg.label_StepStatus.setText("Importing 'MODFLOW object' ... ")
        self.dlg.progressBar_step.setValue(0)
        QCoreApplication.processEvents()

        # inName = os.path.splitext(inFile)[0]
        inName = 'mf_grid_org'
        for f in glob.iglob(pattern):
            suffix = os.path.splitext(f)[1]
            if os.name == 'nt':
                outfile = ntpath.join(output_dir, inName + suffix)
            else:
                outfile = posixpath.join(output_dir, inName + suffix)
            shutil.copy(f, outfile)

        if os.name == 'nt':
            mf_grid_obj = ntpath.join(output_dir, inName + ".shp")
        else:
            mf_grid_obj = posixpath.join(output_dir, inName + ".shp")    
        
        # fix geometries
        mf_grid_shp_file = 'mf_grid.shp'
        mf_grid_shp_f = os.path.join(output_dir, mf_grid_shp_file)
        params = {
            'INPUT': mf_grid_obj,
            'OUTPUT': mf_grid_shp_f
        }
        processing.run('native:fixgeometries', params)
        layer = QgsVectorLayer(mf_grid_shp_f, '{0} ({1})'.format("mf_grid","MODFLOW"), 'ogr')        

        # if there is an existing mf_grid shapefile, it will be removed
        for lyr in list(QgsProject.instance().mapLayers().values()):
            if lyr.name() == ("mf_grid (MODFLOW)"):
                QgsProject.instance().removeMapLayers([lyr.id()])

        # Put in the group
        root = QgsProject.instance().layerTreeRoot()
        swat_group = root.findGroup("MODFLOW")  
        QgsProject.instance().addMapLayer(layer, False)
        swat_group.insertChildNode(0, QgsLayerTreeLayer(layer))
        self.dlg.lineEdit_MODFLOW_grid_shapefile.setText(mf_grid_shp_f) 

        time = datetime.now().strftime('[%m/%d/%y %H:%M:%S]')
        self.dlg.textEdit_sm_link_log.append(time+' -> ' + "Importing MODFLOW object ... passed")
        self.dlg.label_StepStatus.setText("Step Status: ")
        self.dlg.progressBar_step.setValue(100)
        QCoreApplication.processEvents()
コード例 #17
0
    def reloadData(self):
        self.beginResetModel()
        self._document_list = []

        if self._relation.isValid() is False or self._feature.isValid(
        ) is False:
            self.endResetModel()
            return

        feature_list = []
        layer = self._relation.referencingLayer()
        request = self._relation.getRelatedFeaturesRequest(self._feature)
        for feature in layer.getFeatures(request):
            feature_list.append(feature)

        if self._nmRelation.isValid():
            filters = []
            for joinTableFeature in feature_list:
                referencedFeatureRequest = self._nmRelation.getReferencedFeatureRequest(
                    joinTableFeature)
                filterExpression = referencedFeatureRequest.filterExpression()
                filters.append("(" + filterExpression.expression() + ")")

            nmRequest = QgsFeatureRequest()
            nmRequest.setFilterExpression(" OR ".join(filters))

            feature_list = []
            layer = self._nmRelation.referencedLayer()
            for documentFeature in layer.getFeatures(nmRequest):
                feature_list.append(documentFeature)

        for documentFeature in feature_list:
            documents_path = str()
            if self._documents_path:
                exp = QgsExpression(self._documents_path)
                context = QgsExpressionContext()
                context.appendScopes(
                    QgsExpressionContextUtils.globalProjectLayerScopes(layer))
                context.setFeature(documentFeature)
                documents_path = exp.evaluate(context)

            document_filename = str()
            if self._document_filename:
                exp = QgsExpression(self._document_filename)
                context = QgsExpressionContext()
                context.appendScopes(
                    QgsExpressionContextUtils.globalProjectLayerScopes(layer))
                context.setFeature(documentFeature)
                document_filename = exp.evaluate(context)
            file_info = QFileInfo(QDir(str(documents_path)),
                                  str(document_filename))

            # ToolTip
            toolTipList = []
            toolTipList.append("<ul>")
            for field in documentFeature.fields():
                index = documentFeature.fields().indexFromName(field.name())
                toolTipList.append("<li><strong>{0}</strong>: {1}</li>".format(
                    field.displayName(), documentFeature[index]))
            toolTipList.append("</ul>")

            self._document_list.append({
                self.DocumentIdRole:
                documentFeature.id(),
                self.DocumentPathRole:
                file_info.filePath(),
                self.DocumentNameRole:
                file_info.fileName(),
                self.DocumentExistsRole:
                file_info.exists(),
                self.DocumentToolTipRole:
                "".join(toolTipList),
                self.DocumentIsImageRole:
                PreviewImageProvider.isMimeTypeSupported(file_info.filePath())
            })

        self.endResetModel()
コード例 #18
0
def get_rat(raster_layer, band, colors=('R', 'G', 'B', 'A')):
    """Extracts RAT from raster layer and given band

    :param raster_layer: the raster layer to classify
    :type raster_layer: QgsRasterLayer
    :param band: band number (1-based)
    :type band: int
    :param colors: default name of the RGB(A) columns for sidecar DBF files, defaults to ('R', 'G', 'B', 'A'), these are searched first
    :type red_column_name: tuple, optional
    :return: RAT
    :rtype: RAT
    """

    headers = []
    values = {}
    fields = {}
    # For sidecar files
    path = None

    COLOR_ROLES = (gdal.GFU_Red, gdal.GFU_Green, gdal.GFU_Blue, gdal.GFU_Alpha)

    is_dbf = False

    ds = gdal.OpenEx(raster_layer.source())
    if ds:
        band = ds.GetRasterBand(band)
        if band:
            rat = band.GetDefaultRAT()
            if rat is not None:
                for i in range(0, rat.GetColumnCount()):
                    column = rat.GetNameOfCol(i)
                    headers.append(column)
                    values[column] = []
                    fields[column] = RATField(
                        column, rat.GetUsageOfCol(i), rat.GetTypeOfCol(i))

                for r in range(0, rat.GetRowCount()):
                    for c in range(0, rat.GetColumnCount()):
                        column = headers[c]
                        if fields[column].type == gdal.GFT_Integer:
                            values[headers[c]].append(rat.GetValueAsInt(r, c))
                        elif fields[column].type == gdal.GFT_Real:
                            values[headers[c]].append(
                                rat.GetValueAsDouble(r, c))
                        else:
                            values[headers[c]].append(
                                html.unescape(rat.GetValueAsString(r, c)))

                # Try to identify fields in case of RAT with wrong usages
                usages = [f.usage for f in fields.values()]
                if gdal.GFU_MinMax not in usages and not {gdal.GFU_Min, gdal.GFU_Max}.issubset(usages):
                    try:
                        field_name = [f.name for f in fields.values() if f.name.upper() == 'VALUE'][0]
                        fields[field_name].usage = gdal.GFU_MinMax
                    except IndexError:
                        pass

                    try:
                        field_name = [f.name for f in fields.values() if f.name.upper() in ('VALUE MIN', 'MIN', 'MIN VALUE', 'VALUE_MIN', 'MIN_VALUE')][0]
                        fields[field_name].usage = gdal.GFU_Min
                    except IndexError:
                        pass

                    try:
                        field_name = [f.name for f in fields.values() if f.name.upper() in ('VALUE MAX', 'MAX', 'MAX VALUE', 'VALUE_MAX', 'MAX_VALUE')][0]
                        fields[field_name].usage = gdal.GFU_Max
                    except IndexError:
                        pass

                if gdal.GFU_PixelCount not in usages:
                    try:
                        field_name = [f.name for f in fields.values() if f.name.upper() == 'COUNT'][0]
                        fields[field_name].usage = gdal.GFU_PixelCount
                    except IndexError:
                        pass

                path = raster_layer.source() + '.aux.xml'

    # Search for sidecar DBF files, `band` is ignored!
    if not values:

        info = QFileInfo(raster_layer.publicSource())
        directory = info.dir().path()
        basename = info.baseName()
        filename = info.fileName()
        candidates = (basename + '.dbf', basename + '.vat.dbf',
                      filename + '.dbf', filename + '.vat.dbf')

        for candidate in candidates:

            if os.path.exists(os.path.join(directory, candidate)):
                rat_layer = QgsVectorLayer(os.path.join(
                    directory, candidate), 'rat', 'ogr')

                if rat_layer.isValid():
                    path = os.path.join(directory, candidate)

                    # Get fields
                    # Check if color fields are there, fall-back to RED GREEN BLUE ALPHA if not
                    field_upper_names = [f.name().upper() for f in rat_layer.fields()]
                    upper_colors = [c.upper() for c in colors]

                    def _search_color():
                        color_found = True
                        for color_field_name in upper_colors[:3]:
                            if color_field_name not in field_upper_names:
                                color_found = False
                        return color_found

                    if not _search_color() and colors == ('R', 'G', 'B', 'A'):
                        upper_colors = ('RED', 'GREEN', 'BLUE', 'ALPHA')

                    # Create fields
                    for f in rat_layer.fields():

                        headers.append(f.name())
                        field_name_upper = f.name().upper()
                        if field_name_upper in upper_colors:
                            fields[f.name()] = RATField(
                                f.name(), COLOR_ROLES[upper_colors.index(field_name_upper)], gdal.GFT_Integer if f.type() in (QVariant.Int, QVariant.LongLong) else gdal.GFT_Real)
                        elif field_name_upper == 'COUNT':
                            fields[f.name()] = RATField(
                                f.name(), gdal.GFU_PixelCount, gdal.GFT_Integer)
                        elif field_name_upper == 'VALUE':
                            fields[f.name()] = RATField(
                                f.name(), gdal.GFU_MinMax, gdal.GFT_Integer if f.type() in (QVariant.Int, QVariant.LongLong) else gdal.GFT_Real)
                        elif field_name_upper in ('VALUE MIN', 'VALUE_MIN', 'MIN VALUE', 'MIN_VALUE'):
                            fields[f.name()] = RATField(
                                f.name(), gdal.GFU_Min, gdal.GFT_Integer if f.type() in (QVariant.Int, QVariant.LongLong) else gdal.GFT_Real)
                        elif field_name_upper in ('VALUE MAX', 'VALUE_MAX', 'MAX VALUE', 'MAX_VALUE'):
                            fields[f.name()] = RATField(
                                f.name(), gdal.GFU_Max, gdal.GFT_Integer if f.type() in (QVariant.Int, QVariant.LongLong) else gdal.GFT_Real)
                        else:
                            if f.type() in (QVariant.Int, QVariant.LongLong):
                                type = gdal.GFT_Integer
                            elif f.type() == QVariant.Double:
                                type = gdal.GFT_Real
                            else:
                                type = gdal.GFT_String

                            fields[f.name()] = RATField(
                                f.name(), gdal.GFU_Generic, type)

                    for header in headers:
                        values[header] = []
                    for f in rat_layer.getFeatures():
                        for header in headers:
                            values[header].append(f.attribute(header))
                    is_dbf = True
                    break

    # Colors
    if headers:
        red = None
        green = None
        blue = None
        alpha = None
        is_integer = False

        for name, f in fields.items():
            if f.usage == gdal.GFU_Red:
                red = name
                is_integer = f.type == gdal.GFT_Integer
                continue
            if f.usage == gdal.GFU_Green:
                green = name
                continue
            if f.usage == gdal.GFU_Blue:
                blue = name
                continue
            if f.usage == gdal.GFU_Alpha:
                alpha = name
                continue

        if red and green and blue:
            headers.append(RAT_COLOR_HEADER_NAME)
            values[RAT_COLOR_HEADER_NAME] = []
            for i in range(len(values[red])):
                func = 'fromRgb' if is_integer else 'fromRgbF'
                if alpha:
                    values[RAT_COLOR_HEADER_NAME].append(getattr(QColor, func)(
                        values[red][i], values[green][i], values[blue][i], values[alpha][i]))
                else:
                    values[RAT_COLOR_HEADER_NAME].append(getattr(QColor, func)(
                        values[red][i], values[green][i], values[blue][i]))

    return RAT(values, is_dbf, fields, path)
コード例 #19
0
    def terrain_analysis_run(self):
        gdal.AllRegister()
        inputLayer_dem = self.lineEdit.currentText()
        gdalRaster = gdal.Open(str(inputLayer_dem))
        x = gdalRaster.RasterXSize
        y = gdalRaster.RasterYSize
        geo = gdalRaster.GetGeoTransform()
        minx = geo[0]
        maxy = geo[3]
        maxx = minx + geo[1] * x
        miny = maxy + geo[5] * y
        extent_raster = str(minx) + "," + str(maxx) + "," + str(
            miny) + "," + str(maxy)
        pixelSize = geo[1]

        outSlope = self.lineEdit_4.text()
        outAspect = self.lineEdit_5.text()

        # pixel size is the same as the dem raster, miss reamostragem

        Processing.initialize()

        # slope and aspect from DEM
        Processing.runAlgorithm(
            "grass7:r.slope.aspect", {
                'elevation': inputLayer_dem,
                'format': 1,
                'precision': 0,
                '-a': True,
                'zscale': 1,
                'min_slope': 0,
                'slope': outSlope,
                'aspect': outAspect,
                'pcurvature': None,
                'tcurvature': None,
                'dx': None,
                'dy': None,
                'dxx': None,
                'dyy': None,
                'dxy': None,
                'GRASS_REGION_PARAMETER': extent_raster + '[EPSG:3763]',
                'GRASS_REGION_CELLSIZE_PARAMETER': pixelSize,
                'GRASS_RASTER_FORMAT_OPT': '',
                'GRASS_RASTER_FORMAT_META': ''
            })

        # add result into canvas
        file_info_slope = QFileInfo(str(outSlope))
        file_info_aspect = QFileInfo(str(outAspect))
        slope = QgsRasterLayer(outSlope, file_info_slope.fileName(), 'gdal')
        aspect = QgsRasterLayer(outSlope, file_info_aspect.fileName(), 'gdal')
        self.layers = []
        rlayerslope = QgsRasterLayer(slope, "my_layer", "ogr")
        rlayeraspect = QgsRasterLayer(aspect, "my_layer", "ogr")

        self.layers.append(rlayerslope)
        self.layers.append(rlayeraspect)

        if rlayer.isValid():
            self.widget.setLayers(self.layers)
            self.widget.waitWhileRendering()
            self.widget.setExtent(rlayer.extent())
            self.widget.refresh()
        else:
            print("Layer not valid")
コード例 #20
0
ファイル: sourcedocument.py プロジェクト: ollawone/stdm
class DocumentWidget(WIDGET, BASE):
    """
    Widget for displaying source document details
    """
    # Reference removed signal is raised prior
    # to destroying the widget.
    referencesRemoved = pyqtSignal(int)
    fileUploadComplete = pyqtSignal()

    def __init__(
            self,
            document_model=None,
            fileManager=None,
            mode=UPLOAD_MODE,
            parent=None,
            canRemove=True,
            view_manager=None
    ):
        QWidget.__init__(self, parent)
        self.setupUi(self)

        self.lblClose.setPixmap(GuiUtils.get_icon_pixmap('close.png'))

        self.initGui()
        self.fileInfo = None
        self.fileUUID = None
        self.document_model = document_model
        self.fileManager = fileManager
        self._mode = mode
        self._displayName = ""
        self._docSize = 0
        self._srcDoc = None
        self._fileName = ""
        self._canRemove = canRemove
        self._view_manager = view_manager

        self.curr_profile = current_profile()
        self.removed_doc = []
        self.lblClose.installEventFilter(self)
        self.lblName.installEventFilter(self)
        self._source_entity = ""
        self._doc_type = ""
        self._doc_type_id = None
        # Set defaults
        self.fileNameColor = "#5555ff"
        self.fileMetaColor = "#8f8f8f"

    def eventFilter(self, watched, e):
        """
        Capture label mouse release events
        for deleting and opening a source
        document respectively.
        """
        if QEvent is None:
            return False

        if watched == self.lblClose and e.type() == QEvent.MouseButtonRelease:
            self.removeDocument()
            return True

        elif watched == self.lblName and e.type() == QEvent.MouseButtonRelease:
            self.openDocument()
            return True

        else:
            return QWidget.eventFilter(self, watched, e)

    def initGui(self):
        """
        Initialize GUI
        """
        self.lblName.clear()
        self.pgBar.setVisible(False)
        self.pgBar.setValue(0)

    def mode(self):
        """
        Returns the mode that the widget is configured to run.
        Returns either UPLOAD_MODE or DOWNLOAD_MODE.
        """
        return self._mode

    def view_manager(self):
        """
        Manager for viewing the document contents.
        """
        return self._view_manager

    def removeDocument(self):
        """
        Destroy the document widget and removes file references in the network drive
        and corresponding database record.
        """
        msgConfirm = QApplication.translate("DocumentWidget",
                                            """Are you sure you want to delete this document? This action cannot be undone.
                                            \nClick Yes to proceed or No to cancel.""")
        response = QMessageBox.warning(self.parent(),
                                       QApplication.translate("DocumentWidget", "Delete Source Document"),
                                       msgConfirm, QMessageBox.Yes | QMessageBox.No)

        if response == QMessageBox.No:
            return

        self._remove_doc()

    def clean_up(self):
        """
        Remove the referenced uploaded
        file which has not yet been saved.
        :return: True to indicate that the document was
        successfully removed or False if an error was encountered.
        :rtype: bool
        """
        if self._mode == UPLOAD_MODE:
            return self._remove_doc(True)

        return True

    def _remove_doc(self, suppress_messages=False):
        """
        :param suppress_messages: Set whether user messages
        should be displayed or the system should continue with
        execution.
        :type suppress_messages: bool
        :return: True to indicate that the document was
        successfully removed or False if an error was encountered.
        :rtype: bool
        """
        status = True
        if self._mode == UPLOAD_MODE:
            status = self.fileManager.deleteDocument()
        else:
            doc_type = self.doc_type_value()
            self.removed_doc.append(self._srcDoc)
            # Before anything, we check if file exist!
            if self.fileManager.file_exist(self._srcDoc, doc_type):
                status = self.fileManager.deleteDocument(self._srcDoc, doc_type)

        if not status:
            if not suppress_messages:
                msg = QApplication.translate("DocumentWidget",
                                             "The system could not delete the document. Please "
                                             "check your document repository settings.")
                QMessageBox.critical(self.parent(),
                                     QApplication.translate("DocumentWidget",
                                                            "Delete Source Document"),
                                     msg)
            return False

        if self._mode == DOWNLOAD_MODE:
            # Try to delete document and suppress error if it does not exist
            try:
                self._srcDoc.delete()
                # Remove the same document from supporting
                # doc table linked to other str record as the file doesn't exist.
                doc_obj = self.document_model()
                other_party_doc = doc_obj.queryObject().filter(
                    self.document_model.document_identifier ==
                    self._srcDoc.document_identifier
                ).all()

                for docs in other_party_doc:
                    self.removed_doc.append(docs)
                    docs.delete()

            except sqlalchemy.exc.SQLAlchemyError as exc:
                LOGGER.debug(str(exc))

        # Emit signal to indicate the widget is ready to be removed
        self.referencesRemoved.emit(self._doc_type_id)

        self.deleteLater()

        return True

    def openDocument(self):
        """
        Open the document referenced by this widget.
        """
        if not self._view_manager is None:
            self._view_manager.load_viewer(self)

    def setCanRemoveDocument(self, state):
        """
        Disable the close button so that users are not able to remove the
        document from the list.
        """
        self.lblClose.setVisible(state)

    def setFile(self, dfile, source_entity, doc_type, doc_type_id):
        """
        Set the absolute file path including the name, that is to be associated
        with the document widget.
        """
        if self._mode == UPLOAD_MODE:
            self.fileInfo = QFileInfo(dfile)
            self._displayName = str(self.fileInfo.fileName())
            self._docSize = self.fileInfo.size()
            self._source_entity = source_entity
            self._doc_type = doc_type
            self._doc_type_id = doc_type_id
            self.uploadDoc()
            self.buildDisplay()

    def setModel(self, sourcedoc):
        """
        Set the SourceDocument model that is to be associated with the widget.
        Only valid if the widget mode is in DOWNLOAD_MODE.
        """
        self.pgBar.setVisible(False)

        if self._mode == DOWNLOAD_MODE:
            self._displayName = sourcedoc.filename
            self._docSize = sourcedoc.document_size
            self.fileUUID = sourcedoc.document_identifier
            self._srcDoc = sourcedoc
            self._source_entity = sourcedoc.source_entity
            self._doc_type_id = sourcedoc.document_type
            self.buildDisplay()

    def doc_type_value(self):
        """
        Returns the document type value.
        :return: the document type value in
        which a document is uploaded.
        :type: String
        :rtype: String
        """
        entity = self.curr_profile.entity_by_name(self._source_entity)

        doc_type_entity = entity.supporting_doc.document_type_entity
        self._doc_type = entity_id_to_attr(
            doc_type_entity, 'value', self._doc_type_id
        )
        return self._doc_type

    def doc_source_entity(self):
        """
        Returns the document type (enumeration) that the widget currently references.
        """
        return self._source_entity

    def set_source_entity(self, source_entity):
        """
        Set the document type using its code. See enumeration options.
        """
        self._source_entity = source_entity

    def displayName(self):
        """
        Returns the original file name of the supporting document.
        """
        return self._displayName

    def file_identifier(self):
        """
        Returns the unique identifier of the file generated by the system upon
        uploading.
        """
        return self.fileUUID

    def sourceDocument(self, doc_type_id):
        """
        Builds the database model for the source document file reference.
        """
        if self._mode == UPLOAD_MODE:
            entity_doc_obj = self.document_model()
            entity_doc_obj.document_identifier = self.fileUUID
            entity_doc_obj.filename = self.fileInfo.fileName()
            entity_doc_obj.document_size = self._docSize
            entity_doc_obj.creation_date = datetime.now()
            entity_doc_obj.source_entity = self._source_entity
            entity_doc_obj.document_type = doc_type_id
            self._srcDoc = entity_doc_obj

        return self._srcDoc

    def set_thumbnail(self):
        """
        Sets thumbnail to the document widget by
        cropping if necessary.
        :return: None
        :rtype: NoneType
        """
        extension = self._displayName[self._displayName.rfind('.'):]

        QApplication.processEvents()
        doc_path = '{}/{}/{}/{}/{}{}'.format(
            source_document_location(),
            str(self.curr_profile.name),
            str(self._source_entity),
            str(self.doc_type_value()).replace(' ', '_'),
            str(self.fileUUID),
            str(extension)
        ).lower()

        ph_image = QImage(doc_path)
        ph_pixmap = QPixmap.fromImage(ph_image)
        # If width is larger than height, use height as width and height
        if ph_pixmap.width() > ph_pixmap.height():
            rectangle = QRect(0, 0, ph_pixmap.height(), ph_pixmap.height())
            ph_pixmap = ph_pixmap.copy(rectangle)
        # If height is larger than width, use width as width and height
        elif ph_pixmap.height() > ph_pixmap.width():
            rectangle = QRect(0, 0, ph_pixmap.width(), ph_pixmap.width())
            ph_pixmap = ph_pixmap.copy(rectangle)

        self.lblThumbnail.setPixmap(ph_pixmap)
        self.lblThumbnail.setScaledContents(True)

    def buildDisplay(self):
        """
        Build html text for displaying file information.
        """

        if not self._docSize is None:
            display_doc_size = str(size(self._docSize))
        else:
            display_doc_size = '0'

        html = '<html>' \
               '<head/>' \
               '<body>' \
               '<p>' \
               '<span ' \
               'style="font-weight:600;' \
               'text-decoration: underline;' \
               'color:#5555ff;"' \
               '>' \
               '{}</span>' \
               '<span ' \
               'style="font-weight:600;' \
               'color:#8f8f8f;"' \
               '>&nbsp;({})' \
               '</span>' \
               '</p>' \
               '</body>' \
               '</html>'.format(
            str(self._displayName),
            display_doc_size
        )
        self.lblName.setText(html)

        # Enable/disable close
        self.setCanRemoveDocument(self._canRemove)

        # Disable link if no view manager has been configured
        if self._view_manager is None:
            self.lblName.setEnabled(False)

        self.set_thumbnail()

    def uploadDoc(self):
        """
        Upload the file to the central repository in a separate thread using the specified file manager
        """
        if isinstance(self.fileManager, NetworkFileManager):
            self.pgBar.setVisible(True)
            self._docSize = self.fileInfo.size()
            '''
            Create document transfer helper for multi-threading capabilities.
            Use of queued connections will guarantee that signals and slots are captured
            in any thread.
            '''
            workerThread = QThread(self)
            docWorker = DocumentTransferWorker(
                self.fileManager,
                self.fileInfo,
                "%s" % (self._source_entity),
                "%s" % (self._doc_type),
                self
            )
            docWorker.moveToThread(workerThread)

            workerThread.started.connect(docWorker.transfer)
            docWorker.blockWrite.connect(self.onBlockWritten)
            docWorker.complete.connect(self.onCompleteTransfer)
            workerThread.finished.connect(docWorker.deleteLater)
            workerThread.finished.connect(workerThread.deleteLater)

            workerThread.start()
            # Call transfer() to get fileUUID early
            # docWorker.transfer()
            self.fileUUID = docWorker.file_uuid

    def onBlockWritten(self, size):
        """
        Raised when a block of data is written to the central repository.
        Updates the progress bar with the bytes transferred as a percentage.
        """
        progress = (size * 100) / self._docSize

        self.pgBar.setValue(progress)
        QApplication.processEvents()

    def onCompleteTransfer(self, fileid):
        """
        Slot raised when file has been successfully transferred.
        """
        self.pgBar.setVisible(False)
        self.fileUUID = str(fileid)
        self.fileUploadComplete.emit()