Ejemplo n.º 1
0
    def on_cmdSaveCSVFile_clicked(self):
        lastFolder = read_setting(PLUGIN_NAME + "/" + self.toolKey +
                                  "/LastOutFolder")
        if lastFolder is None or not os.path.exists(lastFolder):
            lastFolder = read_setting(PLUGIN_NAME + '/BASE_OUT_FOLDER')

        lyrTarget = self.mcboPointsLayer.currentLayer()
        filename = os.path.splitext(lyrTarget.name())[0] + '_pixelvals.csv'

        # replace more than one instance of underscore with a single one.
        # ie'file____norm__control___yield_h__' to 'file_norm_control_yield_h_'
        filename = re.sub(r"_+", "_", filename)

        s = save_as_dialog(self,
                           self.tr("Save As"),
                           self.tr("Comma Delimited") + " (*.csv);;",
                           default_name=os.path.join(lastFolder, filename))

        if s == '' or s is None:
            return

        s = os.path.normpath(s)
        self.lneSaveCSVFile.setText(s)

        if file_in_use(s):
            self.lneSaveCSVFile.setStyleSheet('color:red')
            self.lblSaveCSVFile.setStyleSheet('color:red')
        else:
            self.lblSaveCSVFile.setStyleSheet('color:black')
            self.lneSaveCSVFile.setStyleSheet('color:black')
            write_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastOutFolder",
                          os.path.dirname(s))
Ejemplo n.º 2
0
    def on_cmdSaveFile_clicked(self):
        lastFolder = read_setting(PLUGIN_NAME + "/" + self.toolKey +
                                  "/LastOutFolder")
        if lastFolder is None or not os.path.exists(lastFolder):
            lastFolder = read_setting(PLUGIN_NAME + '/BASE_OUT_FOLDER')

        # get first layer in the list
        str_pixel_size = numeric_pixelsize_to_string(float(self.pixel_size[0]))
        filename = 'k-means_{}clusters_{}rasters_{}'.format(
            self.spnClusters.value(), self.tabList.rowCount(), str_pixel_size)

        # replace more than one instance of underscore with a single one.
        # ie'file____norm__control___yield_h__' to 'file_norm_control_yield_h_'
        filename = re.sub(r"_+", "_", filename)

        s = save_as_dialog(self,
                           self.tr("Save As"),
                           self.tr("Tiff") + " (*.tif);;",
                           default_name=os.path.join(lastFolder,
                                                     filename + '.tif'))

        if s == '' or s is None:
            return

        s = os.path.normpath(s)
        self.lneSaveFile.setText(s)

        if file_in_use(s):
            self.lneSaveFile.setStyleSheet('color:red')
            self.lblSaveFile.setStyleSheet('color:red')
        else:
            self.lblSaveFile.setStyleSheet('color:black')
            self.lneSaveFile.setStyleSheet('color:black')
            write_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastOutFolder",
                          os.path.dirname(s))
Ejemplo n.º 3
0
    def on_cmdSaveFile_clicked(self):
        lastFolder = read_setting(PLUGIN_NAME + "/" + self.toolKey +
                                  "/LastOutFolder")
        if lastFolder is None or not os.path.exists(lastFolder):
            lastFolder = read_setting(PLUGIN_NAME + '/BASE_OUT_FOLDER')

        if self.cboMethod.currentText() == 'Target Over All Years':
            filename = 'persistor_allyears.tif'
        else:
            filename = 'persistor_targetprob.tif'

        # replace more than one instance of underscore with a single one.
        # ie'file____norm__control___yield_h__' to 'file_norm_control_yield_h_'
        filename = re.sub(r"_+", "_", filename)

        s = save_as_dialog(self,
                           self.tr("Save As"),
                           self.tr("GeoTIFF, TIFF") + " (*.tif);;",
                           default_name=os.path.join(lastFolder, filename))

        if s == '' or s is None:
            return

        s = os.path.normpath(s)
        self.lneSaveFile.setText(s)

        if file_in_use(s):
            self.lneSaveFile.setStyleSheet('color:red')
            self.lblSaveFile.setStyleSheet('color:red')
        else:
            self.lblSaveFile.setStyleSheet('color:black')
            self.lneSaveFile.setStyleSheet('color:black')
            write_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastOutFolder",
                          os.path.dirname(s))
Ejemplo n.º 4
0
    def validate(self):
        """Check to see that all required gui elements have been entered and are valid."""
        self.cleanMessageBars(AllBars=True)
        try:
            errorList = []

            if self.tabList.rowCount() > 0:
                self.cmdAdd.setStyleSheet('color:black')
                self.tabList.horizontalHeader().setStyleSheet('color:black')
                self.lblRasterLayer.setStyleSheet('color:black')

            elif self.mcboRasterLayer.currentLayer(
            ) is None or self.tabList.rowCount() == 0:
                self.cmdAdd.setStyleSheet('color:red')
                self.tabList.horizontalHeader().setStyleSheet('color:red')
                self.lblRasterLayer.setStyleSheet('color:red')

                if self.tabList.rowCount() < 2:
                    errorList.append(
                        self.tr('Please add at least TWO raster to analyse'))
                else:
                    errorList.append(
                        self.
                        tr('No raster layers to process. Please add a RASTER layer into QGIS'
                           ))

            if self.lneSaveFile.text() == '':
                self.lneSaveFile.setStyleSheet('color:red')
                self.lblSaveFile.setStyleSheet('color:red')
                errorList.append(self.tr("Please enter an output filename"))
            elif not os.path.exists(os.path.dirname(self.lneSaveFile.text())):
                self.lneSaveFile.setStyleSheet('color:red')
                self.lblSaveFile.setStyleSheet('color:red')
                errorList.append(self.tr("Output folder does not exist."))
            elif os.path.exists(self.lneSaveFile.text()) and file_in_use(
                    self.lneSaveFile.text(), False):
                self.lneSaveFile.setStyleSheet('color:red')
                self.lblSaveFile.setStyleSheet('color:red')
                errorList.append(
                    self.tr(
                        "Output file {} is open in QGIS or another application"
                        .format(os.path.basename(self.lneSaveFile.text()))))
            else:
                self.lneSaveFile.setStyleSheet('color:black')
                self.lblSaveFile.setStyleSheet('color:black')

            if len(errorList) > 0:
                raise ValueError(errorList)

        except ValueError as e:
            self.cleanMessageBars(True)
            if len(errorList) > 0:
                for i, ea in enumerate(errorList):
                    self.send_to_messagebar(str(ea),
                                            level=Qgis.Warning,
                                            duration=(i + 1) * 5)
                return False

        return True
Ejemplo n.º 5
0
    def on_cmdSaveFile_clicked(self):
        lastFolder = read_setting(PLUGIN_NAME + "/" + self.toolKey +
                                  "/LastOutFolder")
        if lastFolder is None or not os.path.exists(lastFolder):
            lastFolder = read_setting(PLUGIN_NAME + '/BASE_OUT_FOLDER')

        if self.cboMethod.currentText() == 'Target Over All Years':
            if self.optGreaterThan.isChecked():
                result_operator = 'gt'
            else:
                result_operator = 'lt'

            filename = 'persistor_allyears_{}{}'.format(
                result_operator, self.cboAllYearTargetPerc.currentText())
        else:
            filename = 'persistor_targetprob_{}gte{}_{}lt{}'.format(
                self.cboUpperProb.currentText(),
                self.cboUpperPerc.currentText(),
                self.cboLowerProb.currentText(),
                self.cboLowerPerc.currentText())

        # Only use alpha numerics and underscore and hyphens.
        filename = re.sub('[^A-Za-z0-9_-]+', '', filename)

        # replace more than one instance of underscore with a single one.
        # ie'file____norm__control___yield_h__' to 'file_norm_control_yield_h_'
        filename = re.sub(r"_+", "_", filename)

        s = save_as_dialog(self,
                           self.tr("Save As"),
                           self.tr("GeoTIFF, TIFF") + " (*.tif);;",
                           default_name=os.path.join(lastFolder, filename))

        if s == '' or s is None:
            return

        s = os.path.normpath(s)
        self.lneSaveFile.setText(s)

        if file_in_use(s):
            self.lneSaveFile.setStyleSheet('color:red')
            self.lblSaveFile.setStyleSheet('color:red')
        else:
            self.lblSaveFile.setStyleSheet('color:black')
            self.lneSaveFile.setStyleSheet('color:black')
            write_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastOutFolder",
                          os.path.dirname(s))
    def on_cmdSavePolyFile_clicked(self):

        lastFolder = read_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastOutFolder")
        if lastFolder is None or not os.path.exists(lastFolder):
            lastFolder = read_setting(PLUGIN_NAME + '/BASE_OUT_FOLDER')

        # start building a filename
        if self.optLayer.isChecked():
            lyrTarget = self.mcboTargetLayer.currentLayer()
            filename = lyrTarget.name()
        else:
            filename = os.path.splitext(os.path.basename(self.lneInCSVFile.text()))[0]


        # add the chosen field name to the filename
        filename = '{}_polygon.shp'.format(filename)

        # replace more than one instance of underscore with a single one.
        # ie'file____norm__control___yield_h__' to 'file_norm_control_yield_h_'
        filename = re.sub(r"_+", "_", filename)

        s = save_as_dialog(self, self.tr("Save Polygon As"),
                           self.tr("ESRI Shapefile") + " (*.shp);;",
                           default_name=os.path.join(lastFolder, filename))

        if s == '' or s is None:
            return

        s = os.path.normpath(s)
        self.lneSavePolyFile.setText(s)

        if file_in_use(s):
            self.lneSavePolyFile.setStyleSheet('color:red')
            self.lblSavePolyFile.setStyleSheet('color:red')
        else:
            self.lblSavePolyFile.setStyleSheet('color:black')
            self.lneSavePolyFile.setStyleSheet('color:black')
            write_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastOutFolder", os.path.dirname(s))
Ejemplo n.º 7
0
    def validate(self):
        """Check to see that all required gui elements have been entered and are valid."""
        self.cleanMessageBars(AllBars=True)
        try:
            errorList = []
            pointsLayer = self.mcboPointsLayer.currentLayer()
            if pointsLayer is None or self.mcboPointsLayer.currentText() == '':
                self.lblPointsLayer.setStyleSheet('color:red')
                errorList.append(
                    self.
                    tr('No points layers to process. Please load a POINTS layer into QGIS'
                       ))
            else:
                self.lblPointsLayer.setStyleSheet('color:black')

            if self.tabList.rowCount() > 0:
                self.cmdAdd.setStyleSheet('color:black')
                self.tabList.horizontalHeader().setStyleSheet('color:black')
                self.lblRasterLayer.setStyleSheet('color:black')

            elif self.mcboRasterLayer.currentLayer(
            ) is None or self.tabList.rowCount() == 0:
                self.cmdAdd.setStyleSheet('color:red')
                self.tabList.horizontalHeader().setStyleSheet('color:red')
                self.lblRasterLayer.setStyleSheet('color:red')

                if self.tabList.rowCount() == 0:
                    errorList.append(
                        self.tr('Please add at least ONE raster to analyse'))
                else:
                    errorList.append(
                        self.
                        tr('No raster layers to process. Please add a RASTER layer into QGIS'
                           ))

            # check if any statistics are selected. All are children of the qframe
            chkbox_list = self.fraStatistics.findChildren(QtGui.QCheckBox)
            if any(x.isChecked() for x in chkbox_list):
                self.lblCalcStats.setStyleSheet('color:black')
            else:
                self.lblCalcStats.setStyleSheet('color:red')
                errorList.append(
                    self.tr("Please check a statistic to calculate."))

            if self.lneSaveCSVFile.text() == '':
                self.lneSaveCSVFile.setStyleSheet('color:red')
                self.lblSaveCSVFile.setStyleSheet('color:red')
                errorList.append(
                    self.tr("Please enter an output csv filename"))
            elif not os.path.exists(os.path.dirname(
                    self.lneSaveCSVFile.text())):
                self.lneSaveCSVFile.setStyleSheet('color:red')
                self.lblSaveCSVFile.setStyleSheet('color:red')
                errorList.append(self.tr("Output folder does not exist."))
            elif os.path.exists(self.lneSaveCSVFile.text()) and file_in_use(
                    self.lneSaveCSVFile.text(), False):
                self.lneSaveCSVFile.setStyleSheet('color:red')
                self.lblSaveCSVFile.setStyleSheet('color:red')
                errorList.append(
                    self.tr(
                        "Output file {} is open in QGIS or another application"
                        .format(os.path.basename(self.lneSaveCSVFile.text()))))
            else:
                self.lneSaveCSVFile.setStyleSheet('color:black')
                self.lblSaveCSVFile.setStyleSheet('color:black')

            # if self.mcboPointsLayer.currentLayer().providerType() == 'delimitedtext':
            #     url = urlparse(self.mcboPointsLayer.currentLayer().source())
            #
            #     if os.path.normpath(url.path.strip('/')).upper() == os.path.normpath(self.lneSaveCSVFile.text()).upper():
            #         self.lneSaveCSVFile.setStyleSheet('color:red')
            #         errorList.append(self.tr("Output file in use as the input points layer"))

            if len(errorList) > 0:
                raise ValueError(errorList)

        except ValueError as e:
            self.cleanMessageBars(True)
            if len(errorList) > 0:
                for i, ea in enumerate(errorList):
                    self.send_to_messagebar(unicode(ea),
                                            level=QgsMessageBar.WARNING,
                                            duration=(i + 1) * 5)
                return False

        return True
    def validate(self):
        """Check to see that all required gui elements have been entered and are valid."""
        try:
            self.cleanMessageBars(AllBars=True)
            errorList = []

            widget_page = self.stackedWidget.currentWidget().objectName()
            widget_idx = self.stackedWidget.currentIndex() + 1

            if widget_page =='pgeSource' or widget_idx == self.stackedWidget.count():
                if self.optFile.isChecked():
                    if self.lneInCSVFile.text()== '':
                        self.optFile.setStyleSheet('color:red')
                        errorList.append(self.tr("Select an input file"))
                    else:
                        self.optLayer.setStyleSheet('color:black')
                        self.optFile.setStyleSheet('color:black')
                else:
                    targetLayer = self.mcboTargetLayer.currentLayer()
                    if targetLayer is None or self.mcboTargetLayer.currentLayer().name() == '':
                        self.optLayer.setStyleSheet('color:red')
                        errorList.append(self.tr("Select a layer"))
                    else:
                        self.optLayer.setStyleSheet('color:black')
                        self.optFile.setStyleSheet('color:black')

            if widget_page == 'pgeFromFile' or widget_idx == self.stackedWidget.count():
                if self.optFile.isChecked():
                    if self.cboXField.currentText() == ' ':
                        self.lblXField.setStyleSheet('color:red')
                        errorList.append(self.tr("Select an x field"))
                    else:
                        self.lblXField.setStyleSheet('color:black')

                    if self.cboYField.currentText() == ' ':
                        self.lblYField.setStyleSheet('color:red')
                        errorList.append(self.tr("Select an y field"))
                    else:
                        self.lblYField.setStyleSheet('color:black')

                    if self.qgsCRScsv.crs().isValid():
                        self.lblInCRSTitle.setStyleSheet('color:black')
                    else:
                        self.lblInCRSTitle.setStyleSheet('color:red')
                        errorList.append(self.tr("Select coordinate system for geometry fields"))

            if widget_page == 'pgeOutput' or widget_idx == self.stackedWidget.count() :
                if self.mCRSoutput.crs().isValid():
                    if self.mCRSoutput.crs().isGeographic():
                        self.lblOutCRSTitle.setStyleSheet('color:red')
                        self.mCRSoutput.setStyleSheet('color:red')
                        errorList.append(self.tr("Select output projected coordinate system (not geographic)"))
                    else:
                        self.lblOutCRSTitle.setStyleSheet('color:black')
                        self.mCRSoutput.setStyleSheet('color:black')
                else:
                    self.lblOutCRSTitle.setStyleSheet('color:red')
                    self.mCRSoutput.setStyleSheet('color:red')
                    errorList.append(self.tr("Select output projected coordinate system"))

                if self.lneSavePolyFile.text() == '':
                    self.lneSavePolyFile.setStyleSheet('color:red')
                    errorList.append(self.tr("Enter output polygon shapefile"))
                elif not os.path.exists(os.path.dirname(self.lneSavePolyFile.text())):
                    self.lneSavePolyFile.setStyleSheet('color:red')
                    errorList.append(self.tr("Output shapefile folder cannot be found"))
                elif os.path.exists(self.lneSavePolyFile.text()) and file_in_use(self.lneSavePolyFile.text(), False):
                    self.lneSavePolyFile.setStyleSheet('color:red')
                    self.lblSavePolyFile.setStyleSheet('color:red')
                    errorList.append(self.tr("Output file {} is open in QGIS or another application".format(
                        os.path.basename(self.lneSavePolyFile.text()))))
                else:
                    self.lblSavePolyFile.setStyleSheet('color:black')
                    self.lneSavePolyFile.setStyleSheet('color:black')

                if self.lneSavePointsFile.text() == '':
                    self.lblSavePointsFile.setStyleSheet('color:red')
                    errorList.append(self.tr("Enter output points shapefile file"))
                elif not os.path.exists(os.path.dirname(self.lneSavePointsFile.text())):
                    self.lneSavePointsFile.setStyleSheet('color:red')
                    errorList.append(self.tr("Output shapefile folder cannot be found"))
                elif os.path.exists(self.lneSavePointsFile.text()) and file_in_use(self.lneSavePointsFile.text(), False):
                    self.lneSaveCSVFile.setStyleSheet('color:red')
                    self.lblSaveCSVFile.setStyleSheet('color:red')
                    errorList.append(self.tr("Output file {} is open in QGIS or another application".format(
                        os.path.basename(self.lneSaveCSVFile.text()))))
                else:
                    self.lblSavePointsFile.setStyleSheet('color:black')
                    self.lneSavePointsFile.setStyleSheet('color:black')


            if len(errorList) > 0:
                raise ValueError(errorList)

            return True

        except ValueError as e:
            self.cleanMessageBars(True)
            if len(errorList) > 0:
                for i, ea in enumerate(errorList):
                    self.send_to_messagebar(str(ea), level=Qgis.Warning, duration=(i + 1) * 5)

                return False