示例#1
0
    def on_cmdInVesperCtrlFile_clicked(self):
        self.lneInVesperCtrlFile.clear()

        inFolder = read_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastInFolder")
        if inFolder is None or not os.path.exists(inFolder):
            inFolder = read_setting(PLUGIN_NAME + '/BASE_IN_FOLDER')

        s,_f = QFileDialog.getOpenFileName(
            self,
            caption=self.tr("Select a vesper control file to import"),
            directory=inFolder,
            filter=self.tr("Vesper Control File") + " (*control*.txt);;"
                   + self.tr("All Files") + " (*.*);;")

        if s == '':
            self.lblInVesperCtrlFile.setStyleSheet('color:red')
            return
        else:
            s = os.path.normpath(s)
            self.lblInVesperCtrlFile.setStyleSheet('color:black')
            self.lneInVesperCtrlFile.setText(s)
            write_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastInFolder", os.path.dirname(s))

        with open(s) as f:
            for line in f:
                if "epsg=" in line:
                    epsg = int(line.strip().split('=')[-1])
                    self.mCRSinput.setCrs(QgsCoordinateReferenceSystem().fromEpsgId(epsg))
                    break
示例#2
0
    def on_cmdSaveRasterFile_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")

        pixel_size_str = numeric_pixelsize_to_string(self.dsbPixelSize.value())
        filename = '{}_BlockGrid_{}'.format(self.mcboTargetLayer.currentText(),
                                            pixel_size_str)
        filename = re.sub('[^A-Za-z0-9_-]+', '', 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

        write_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastOutFolder",
                      os.path.dirname(s))
        self.lneSaveRasterFile.setText(s)
        self.lneSaveRasterFile.setStyleSheet('color:black')
    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")

        filename = self.mcboTargetLayer.currentLayer().name() + '_{}randompts'.format(int(self.dsbSize.value()))

        # 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.
        filename = re.sub(r"_+", "_", filename)

        s = save_as_dialog(self, self.tr("Save 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)
        write_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastOutFolder", os.path.dirname(s))

        self.lneSaveFile.setText(s)
        self.lblSaveFile.setStyleSheet('color:black')
        self.lneSaveFile.setStyleSheet('color:black')
    def on_cmdOutputFolder_clicked(self):
        self.messageBar.clearWidgets()
        if self.lneOutputFolder.text() is None:
            outFolder = ''
        else:
            outFolder = self.lneOutputFolder.text()

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

        s = QtGui.QFileDialog.getExistingDirectory(
            self,
            self.
            tr("Save output files to a folder. A sub-folder will be created from the image name"
               ), outFolder, QtGui.QFileDialog.ShowDirsOnly)

        self.cleanMessageBars(self)
        if s == '' or s is None:
            return

        s = os.path.normpath(s)

        self.lblOutputFolder.setStyleSheet('color:black')
        self.lneOutputFolder.setStyleSheet('color:black')
        self.lneOutputFolder.setText(s)
        write_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastOutFolder", s)
示例#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')

        # 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))
    def on_cmdSavePointsFile_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.optLayer.isChecked():
            lyrTarget = self.mcboTargetLayer.currentLayer()
            filename = lyrTarget.name() + '_points.shp'
        else:
            filename = os.path.splitext(self.lneInCSVFile.text())[0] + '_points.shp'

        # 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("ESRI Shapefile") + " (*.shp);;",
                           default_name=os.path.join(lastFolder, filename))

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

        s = os.path.normpath(s)

        self.lneSavePointsFile.setText(s)
        self.lneSavePointsFile.setEnabled(True)
        self.lblSavePointsFile.setStyleSheet('color:black')

        self.lblSavePolyFile.setStyleSheet('color:black')

        write_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastOutFolder", os.path.dirname(s))
    def on_cmdInFile_clicked(self):
        self.resetFormToDefaults()

        inFolder = read_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastInFolder")
        if inFolder is None or not os.path.exists(inFolder):
            inFolder = read_setting(PLUGIN_NAME + '/BASE_IN_FOLDER')

        """Click Button Event."""
        self.optFile.setChecked(True)
        s = QFileDialog.getOpenFileName(
            self,
            caption=self.tr("Choose a file to open"),
            directory=inFolder,
            filter=self.tr("Delimited files") + " (*.csv *.txt);;")
                   # + self.tr("Spreadsheet files") + " (*.ods *.xls *.xlsx);;"
                   # + self.tr("GDAL Virtual Format") + " (*.vrt);;")

        if type(s) == tuple:
            s = s[0]

        if s == '':
            return

        self.lneInCSVFile.setText(s)

        write_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastInFolder", os.path.dirname(s))
    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))
    def on_cmdSaveRasterFile_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")

        filename = self.mcboTargetLayer.currentLayer().name(
        ) + '_' + self.cboMethod.currentText()
        if self.cboMethod.currentText() == 'Rescale':
            filename = self.mcboTargetLayer.currentLayer().name(
            ) + '_{}{}-{}'.format(self.cboMethod.currentText(),
                                  int(self.dsbRescaleLower.value()),
                                  int(self.dsbRescaleUpper.value()))

        filename = re.sub('[^A-Za-z0-9_-]+', '', 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)

        write_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastOutFolder",
                      os.path.dirname(s))
        self.lneSaveRasterFile.setText(s)
        self.lblOutputFile.setStyleSheet('color:black')
        self.lneSaveRasterFile.setStyleSheet('color:black')
    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))
def check_pip_for_update(package):
    """ Check a package against online pip via json get the most current release
    version number

    source: https://stackoverflow.com/a/40745656
    """

    # only check once a month for pyprecag updates.
    last_pip_check = read_setting(PLUGIN_NAME + "/LAST_PIP_CHECK")
    if last_pip_check is not None:
        last_pip_check = datetime.strptime(last_pip_check, '%Y-%m-%d')

    if last_pip_check is None or (datetime.now() - last_pip_check).days > 30:
        url = 'https://pypi.python.org/pypi/{}/json'.format(package)
        try:
            releases = requests.get(url).json()['releases']
            current_version = sorted(releases, key=parse_version,
                                     reverse=True)[0]

            write_setting(PLUGIN_NAME + '/LAST_PIP_CHECK',
                          datetime.now().strftime('%Y-%m-%d'))

            return current_version
        except requests.ConnectionError:
            LOGGER.info(
                'Skipping pyprecag version check. Cannot reach {}'.format(url))
    return
def check_pat_symbols():
    pat_xml = os.path.join(PLUGIN_DIR, 'PAT_Symbols.xml')
    if not os.path.exists(pat_xml):
        return

    loaded_date = read_setting(PLUGIN_NAME + "/PAT_SYMBOLOGY")
    if loaded_date is not None:
        loaded_date = datetime.strptime(loaded_date, '%Y-%m-%d %H:%M:%S')

    xml_date = datetime.fromtimestamp(
        os.path.getmtime(pat_xml)).replace(microsecond=0)

    styles = QgsStyle().defaultStyle()

    if 'PAT' not in styles.tags() or (loaded_date is None
                                      or xml_date > loaded_date):
        if styles.isXmlStyleFile(pat_xml):
            if styles.importXml(pat_xml):
                LOGGER.info('Loaded PAT Symbology')
                write_setting(PLUGIN_NAME + '/PAT_SYMBOLOGY',
                              xml_date.strftime('%Y-%m-%d %H:%M:%S'))
            else:
                LOGGER.warning('Loading PAT Symbology failed')
        else:
            LOGGER.debug('Could not open file {}'.format(pat_xml))

    return
示例#13
0
    def on_cmdSavePointsFile_clicked(self):
        self.messageBar.clearWidgets()

        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")

        filename = self.mcboLineLayer.currentLayer().name(
        ) + '_strip-trial-points'

        s = save_as_dialog(self,
                           self.tr("Save 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)
        write_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastOutFolder",
                      os.path.dirname(s))

        self.lneSavePointsFile.setText(s)
        self.lblSavePointsFile.setStyleSheet('color:black')
        self.lneSavePointsFile.setStyleSheet('color:black')
示例#14
0
    def on_cmdVesperFold_clicked(self):
        self.messageBar.clearWidgets()

        if self.lneVesperFold.text() is None:
            outFolder = ''
        else:
            outFolder = self.lneVesperFold.text()

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

        s = QtGui.QFileDialog.getExistingDirectory(self, self.tr(
            "Vesper processing folder. A Vesper sub-folder will be created."), outFolder,
                                                   QtGui.QFileDialog.ShowDirsOnly)

        self.cleanMessageBars(self)
        if s == '' or s is None:
            return

        s = os.path.normpath(s)
        self.lblVesperFold.setStyleSheet('color:black')
        self.lneVesperFold.setStyleSheet('color:black')
        self.lneVesperFold.setText(s)
        write_setting(PLUGIN_NAME + "/" + self.toolKey +
                      "/LastVesperOutFolder", s)
示例#15
0
    def on_cmdInVesperCtrlFile_clicked(self):
        self.lneInVesperCtrlFile.clear()

        inFolder = read_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastInFolder")
        if inFolder is None or not os.path.exists(inFolder):
            inFolder = read_setting(PLUGIN_NAME + '/BASE_IN_FOLDER')

        s = QtGui.QFileDialog.getOpenFileName(
            self,
            caption=self.tr("Select a vesper control file to import"),
            directory=inFolder,
            filter=self.tr("Vesper Control File") + " (*control*.txt);;"
                   + self.tr("All Files") + " (*.*);;")

        if s == '':
            self.lblInVesperCtrlFile.setStyleSheet('color:red')
            return
        else:
            s = os.path.normpath(s)
            self.lblInVesperCtrlFile.setStyleSheet('color:black')
            self.lneInVesperCtrlFile.setText(s)
            write_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastInFolder", os.path.dirname(s))

        with open(s) as f:
            for line in f:
                if "epsg=" in line:
                    if line.strip().split('=') > 2:
                        epsg = line.strip().replace("'", '').split('=')[-1]
                        self.vesper_qgscrs = QgsCoordinateReferenceSystem("EPSG:{}".format(epsg))
                        self.vesper_qgscrs.validate()
                        self.lneInCRS.setText('{}  -  {}'.format(self.vesper_qgscrs.description(),
                                                                 self.vesper_qgscrs.authid()))
                    break
def check_R_dependency():
    updated = False
    r_installfold = read_setting('Processing/Configuration/R_FOLDER')
    if platform.system() == 'Windows':
        try:
            aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
            aKey = OpenKey(aReg, r"SOFTWARE\R-core\R")
            aVal = os.path.normpath(QueryValueEx(aKey, "InstallPath")[0])

            if os.path.exists(aVal):
                if r_installfold is not None and r_installfold != aVal:
                    r_installfold = aVal
                    write_setting('Processing/Configuration/R_FOLDER', aVal)
                    LOGGER.info(
                        'Setting ... R Install folder: {}'.format(aVal))
            r_installed = True

        except EnvironmentError:
            r_installed = False
            write_setting('Processing/Configuration/R_FOLDER', '')
            write_setting('Processing/Configuration/ACTIVATE_R', False)
            return 'R is not installed or not configured for QGIS.\n See "Configuring QGIS to use R" in help documentation'

    else:
        # Linux/OSX - https://stackoverflow.com/a/25330049
        try:
            subprocess.check_call(['which', 'R'])
        except subprocess.CalledProcessError:
            r_installed = False
        else:
            r_installed = True

    if not r_installed:
        write_setting('Processing/Configuration/R_FOLDER', '')
        write_setting('Processing/Configuration/ACTIVATE_R', False)
        return 'R is not installed or not configured for QGIS.\n See "Configuring QGIS to use R" in help documentation'

    # Get the users R script folder - returns none if not set.
    r_scripts_fold = read_setting('Processing/Configuration/R_SCRIPTS_FOLDER')

    if r_scripts_fold is None:
        return 'R is not installed or not configured for QGIS.\n See "Configuring QGIS to use R" in help documentation'

    files = glob.glob(os.path.join(PLUGIN_DIR, "R-Scripts", "Whole*.rsx"))

    for src_file in files:
        dest_file = os.path.join(r_scripts_fold, os.path.basename(src_file))

        # update flag will only update if file doesnt exist or is newer and returns a tuple of
        # all files with a 1 if the file was copied
        if file_util.copy_file(src_file, dest_file, update=True)[-1]:
            LOGGER.info('Installing or Updating Whole-of-block analysis tool.')

        # # only copy if it doesn't exist or it is newer by 1 second.
        # if not os.path.exists(dest_file) or os.stat(src_file).st_mtime - os.stat(
        #         dest_file).st_mtime > 1:
        #     shutil.copy2(src_file, dest_file)

    return True
示例#17
0
    def on_cmdInBrowse_clicked(self):
        s = QtGui.QFileDialog.getExistingDirectory(self, self.tr("Open Source Data From"),
                                                   self.lneInDataDirectory.text(),
                                                   QtGui.QFileDialog.ShowDirsOnly)

        if s == '':
            return

        s = os.path.normpath(s)

        self.lneInDataDirectory.setText(s)
        write_setting(PLUGIN_NAME + '/BASE_IN_FOLDER', s)
示例#18
0
    def on_cmdOutBrowse_clicked(self):
        s = QtGui.QFileDialog.getExistingDirectory(self, self.tr("Save Output Data To"),
                                                   self.lneOutDataDirectory.text(),
                                                   QtGui.QFileDialog.ShowDirsOnly)

        if s == '':
            return

        s = os.path.normpath(s)

        self.lneOutDataDirectory.setText(s)
        write_setting(PLUGIN_NAME + '/BASE_OUT_FOLDER', s)
示例#19
0
    def on_cmdInGridFile_clicked(self):
        self.lneInGridFile.clear()
        self.messageBar.clearWidgets()

        inFolder = read_setting(PLUGIN_NAME + "/" + self.toolKey +
                                "/LastInFolder_VesperGrid")

        if inFolder is None or not os.path.exists(inFolder):

            inFolder = read_setting(PLUGIN_NAME + "/" + self.toolKey +
                                    "/LastInFolder_CSV")

            if inFolder is None or not os.path.exists(inFolder):
                inFolder = read_setting(PLUGIN_NAME + '/BASE_IN_FOLDER')

        s, _f = QFileDialog.getOpenFileName(
            self,
            caption=self.tr("Choose the Vesper Grid File"),
            directory=inFolder,
            filter='{}  (*_v.txt);;{}  (*.*);;'.format(
                self.tr("Vesper Grid File(s)"), self.tr("All Files")))

        self.cleanMessageBars(self)
        s = os.path.normpath(s)

        self.lneInGridFile.clear()
        self.lneInGridFile.setStyleSheet('color:red')
        self.lblInGridFile.setStyleSheet('color:red')

        overlaps, message = self.validate_csv_grid_files(
            self.lneInCSVFile.text(), s)

        if overlaps or message is None:
            self.lneInGridFile.setStyleSheet('color:black')
            self.lblInGridFile.setStyleSheet('color:black')
            if overlaps:
                self.lneInGridFile.setText(s)
                write_setting(
                    PLUGIN_NAME + "/" + self.toolKey +
                    "/LastInFolder_VesperGrid", os.path.dirname(s))
        else:
            self.send_to_messagebar(message,
                                    level=Qgis.Critical,
                                    duration=0,
                                    addToLog=True,
                                    showLogPanel=True,
                                    exc_info=sys.exc_info())
示例#20
0
    def on_cmdVariogramFile_clicked(self):
        self.lneVariogramFile.clear()
        self.messageBar.clearWidgets()

        inFolder = read_setting(PLUGIN_NAME + "/" + self.toolKey +
                                "/LastInFolder_Variogram")

        if inFolder is None or not os.path.exists(inFolder):
            inFolder = read_setting(PLUGIN_NAME + "/" + self.toolKey +
                                    "/LastInFolder_Variogram")

            if inFolder is None or not os.path.exists(inFolder):
                inFolder = read_setting(PLUGIN_NAME + '/BASE_IN_FOLDER')

        s, _f = QFileDialog.getOpenFileName(
            self,
            caption=self.tr("Choose the Vesper Variogram File"),
            directory=inFolder,
            filter='{}  (*.txt);;{}  (*.*);;'.format(
                self.tr("Variogram Text File(s)"), self.tr("All Files")))

        self.cleanMessageBars(self)

        if s == '':
            self.lneVariogramFile.setStyleSheet('color:red')
            self.lblVariogramFile.setStyleSheet('color:red')
            return

        if 'Variogram Model' not in open(s).read():
            self.lneVariogramFile.setStyleSheet('color:red')
            self.lblVariogramFile.setStyleSheet('color:red')
            self.send_to_messagebar("Invalid Variogram File",
                                    level=Qgis.Critical,
                                    duration=0,
                                    addToLog=True,
                                    showLogPanel=True,
                                    exc_info=sys.exc_info())
            # self.lneVariogramFile.clear()
            return

        s = os.path.normpath(s)
        self.lblVariogramFile.setStyleSheet('color:black')
        self.lneVariogramFile.setStyleSheet('color:black')
        self.lneVariogramFile.setText(s)
        write_setting(
            PLUGIN_NAME + "/" + self.toolKey + "/LastInFolder_Variogram",
            os.path.dirname(s))
示例#21
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 check_vesper_dependency(iface=None):
    """ Check for the vesper exe as specified in the pyprecag config.json file. If the exe string is invalid, or does
    not exist it will return None.

    It will check in the default installed location for VESPER and notify user if missing. If it is
    missing the user can still use PAT tools but not run the VESPER kriging.

    Args:
        :param iface: A QGIS interface instance.
        :type iface: QgsInterface
    Returns:
        str() : String containing vesper exe.

    """
    vesper_exe = ''
    message = ''
    if platform.system() == 'Windows':
        vesper_exe = read_setting(PLUGIN_NAME + '/VESPER_EXE')
        if vesper_exe is None or vesper_exe == '' or not os.path.exists(
                vesper_exe):
            # Update if Vesper is installed.
            if os.path.exists(r'C:/Program Files (x86)/Vesper/Vesper1.6.exe'):
                vesper_exe = r'C:/Program Files (x86)/Vesper/Vesper1.6.exe'

            else:  # Otherwise report it.
                if vesper_exe == '' or vesper_exe == None:
                    message = 'Vesper*.exe not found. Please install and configure to allow for kriging to occur'
                elif not os.path.exists(vesper_exe):
                    message = 'Vesper*.exe at "{}" does not exist. Please install and configure to allow for kriging to occur'.format(
                        vesper_exe)

                vesper_exe = ''
            write_setting(PLUGIN_NAME + '/VESPER_EXE', vesper_exe)
    else:
        message = 'VESPER is only supported on Windows.'

    if message != '':
        if iface:
            iface.messageBar().pushMessage("WARNING",
                                           message,
                                           level=Qgis.Warning,
                                           duration=15)
        else:
            LOGGER.warn(message)

    return vesper_exe
示例#23
0
    def accept(self, *args, **kwargs):
        if not self.validate():
            return False
        try:
            QtGui.qApp.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor))

            write_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastSize", self.dsbSize.value())

            LOGGER.info('{st}\nProcessing {}'.format(self.windowTitle(), st='*' * 50))
            self.iface.mainWindow().statusBar().showMessage('Processing {}'.format(self.windowTitle()))

            # Add settings to log
            settingsStr = 'Parameters:---------------------------------------'
            settingsStr += '\n    {:30}\t{}'.format('Sample Size:', self.dsbSize.value())
            settingsStr += '\n    {:30}\t{}'.format('Layer:', self.mcboTargetLayer.currentLayer().name())
            settingsStr += '\n    {:30}\t{}'.format('Output Shapefile:', self.lneSaveFile.text())

            LOGGER.info(settingsStr)

            lyrTarget = self.mcboTargetLayer.currentLayer()
            removeFileFromQGIS(self.lneSaveFile.text())

            raster_file = lyrTarget.source()
            rasterCRS = pyprecag_crs.getCRSfromRasterFile(raster_file)

            if rasterCRS.epsg is None:
                rasterCRS.getFromEPSG(lyrTarget.crs().authid())

            with rasterio.open(os.path.normpath(raster_file)) as src:
                processing.random_pixel_selection(src, rasterCRS, int(self.dsbSize.value()), self.lneSaveFile.text())

            lyrPts = addVectorFileToQGIS(self.lneSaveFile.text(), atTop=True,
                                         layer_name=os.path.splitext(os.path.basename(self.lneSaveFile.text()))[0])

            QtGui.qApp.restoreOverrideCursor()
            self.iface.mainWindow().statusBar().clearMessage()
            return super(RandomPixelSelectionDialog, self).accept(*args, **kwargs)

        except Exception as err:
            QtGui.qApp.restoreOverrideCursor()
            self.iface.mainWindow().statusBar().clearMessage()
            self.cleanMessageBars(True)
            self.send_to_messagebar(str(err), level=QgsMessageBar.CRITICAL, duration=0, addToLog=True,
                                    exc_info=sys.exc_info())
            return False  # leave dialog open
示例#24
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")

        filename = self.mcboTargetLayer.currentText() + '_{}randompts'.format(int(self.dsbSize.value()))

        s = save_as_dialog(self, self.tr("Save 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)
        write_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastOutFolder", os.path.dirname(s))

        self.lneSaveFile.setText(s)
        self.lblSaveFile.setStyleSheet('color:black')
        self.lneSaveFile.setStyleSheet('color:black')
示例#25
0
    def on_cmdVesperExe_clicked(self):
        default_dir = os.path.dirname(self.lneVesperExe.text())
        if default_dir == '' or default_dir is None:
            default_dir = r'C:\Program Files (x86)'
        s = QtGui.QFileDialog.getOpenFileName(self, self.tr("Select Vesper Executable"),
                                              directory=default_dir,
                                              filter=self.tr("Vesper Executable") + " (Vesper*.exe);;"
                                                     + self.tr("All Exe Files") + " (*.exe);;")

        if s == '':  # ie nothing entered
            return
        s = os.path.normpath(s)
        self.lneVesperExe.setText(s)
        try:
            config.set_config_key('vesperEXE', s)
        except:
            LOGGER.warning('Could not write to config.json')

        self.vesper_exe = s
        write_setting(PLUGIN_NAME + '/VESPER_EXE', s)
示例#26
0
    def on_cmdSaveLinesFile_clicked(self):
        self.messageBar.clearWidgets()

        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.lneSaveLinesFile.text() != '':
            filename = self.lneSaveLinesFile.text()
        elif self.lneSavePointsFile.text() == '':
            filename = os.path.join(
                lastFolder,
                self.mcboLineLayer.currentText() + '_strip-trial-lines')
        else:
            path, file = os.path.split(self.lneSavePointsFile.text())
            file, ext = os.path.splitext(file)
            filename = os.path.join(
                path,
                file.replace('-points', '') + '-lines' + ext)

        s = save_as_dialog(self,
                           self.tr("Save 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)
        write_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastOutFolder",
                      os.path.dirname(s))

        self.chkSaveLinesFile.setChecked(True)
        self.lneSaveLinesFile.setText(s)
        self.chkSaveLinesFile.setStyleSheet('color:black')
        self.lneSaveLinesFile.setStyleSheet('color:black')
示例#27
0
 def on_chkDisplayTempLayers_stateChanged(self, state):
     if read_setting(PLUGIN_NAME + '/DISP_TEMP_LAYERS', bool) != self.chkDisplayTempLayers.isChecked():
         write_setting(PLUGIN_NAME + '/DISP_TEMP_LAYERS', self.chkDisplayTempLayers.isChecked())
def check_python_dependencies(plugin_path, iface):
    """ Check for extra python modules which the plugin requires.

    If they are not installed, a windows batch file will be created on the users desktop.
    Run this as administrator to install relevant packages

    Args:
         iface (): The QGIs gui interface required to add messagebar too.
         plugin_path (): The path to the users plugin directory.

    Returns (bool): Passed Check or Not.
    """

    try:
        # comes from metadata.txt
        from qgis.utils import pluginMetadata
        meta_version = '{} {} '.format(pluginMetadata('pat', 'version'),
                                       pluginMetadata('pat', 'update_date'))

        # # get the list of wheels matching the gdal version
        # if not os.environ.get('GDAL_VERSION', None):
        #     gdal_ver = osgeo.gdal.__version__
        #     LOGGER.warning(
        #         'Environment Variable GDAL_VERSION does not exist. Setting to {}'.format(gdal_ver))
        #     os.environ['GDAL_VERSION'] = gdal_ver

        # the name of the install file.
        title = 'Install_PAT3_Extras'
        if platform.system() == 'Windows':
            user_path = os.path.join(os.path.expanduser('~'))
            shortcutPath = os.path.join(user_path, 'Desktop',
                                        title.replace('_', ' ') + '.lnk')
            osgeo_path = os.path.abspath(
                win32api.GetLongPathName(os.environ['OSGEO4W_ROOT']))

            if os.path.exists(shortcutPath):
                # Copy logs into PAT plugin folder
                pass
        else:
            osgeo_path = os.path.abspath(os.environ['OSGEO4W_ROOT'])

        qgis_prefix_path = os.path.abspath(QgsApplication.prefixPath())

        packCheck = {}
        pip_packs = []
        osgeo_packs = []

        #packCheck['gdal300dll']={'Action': '', 'Version': ''}
        if not os.path.exists(os.path.join(osgeo_path, 'bin', 'gdal300.dll')):
            packCheck['gdal300dll'] = {'Action': 'Install', 'Version': ''}
            osgeo_packs += ['gdal300dll']

        # Check for the listed modules.
        for argCheck in ['fiona', 'geopandas', 'rasterio']:
            packCheck[argCheck] = check_package(argCheck)
            if packCheck[argCheck]['Action'] == 'Install':
                osgeo_packs += [argCheck]

        packCheck['pyprecag'] = check_package('pyprecag')
        cur_pyprecag_ver = check_pip_for_update('pyprecag')
        if cur_pyprecag_ver is not None:
            if parse_version(packCheck['pyprecag']['Version']) < parse_version(
                    cur_pyprecag_ver):
                packCheck['pyprecag']['Action'] = 'Upgrade'

        if packCheck['fiona']['Action'] == 'Install':
            message = ''

            if 'ltr' in os.path.basename(QgsApplication.prefixPath()).lower():
                if Qgis.QGIS_VERSION_INT < 31011:
                    message = 'PAT is no longer supported by QGIS LTR {}\nPlease upgrade to the current QGIS release.'.format(
                        Qgis.QGIS_VERSION)

            elif Qgis.QGIS_VERSION_INT < 31600:
                message = 'PAT is no longer supported by QGIS {}\nPlease upgrade to the current QGIS release.'.format(
                    Qgis.QGIS_VERSION)

            if message != '':
                iface.messageBar().pushMessage(message,
                                               level=Qgis.Critical,
                                               duration=30)
                LOGGER.info(message)
                QMessageBox.critical(None, 'QGIS Upgrade required', message)
                return (message)

        # Install via a tar wheel file prior to publishing via pip to test pyprecag bug fixes
        # otherwise just use a standard pip install.
        local_wheel = glob.glob1(os.path.join(plugin_path, 'install_files'),
                                 "pyprecag*")
        if len(local_wheel) == 1 and 'installed' not in local_wheel[0]:
            packCheck['pyprecag']['Action'] = 'Upgrade'
            pip_packs += [local_wheel[0]]
        elif packCheck['pyprecag']['Action'] in ['Install', 'Upgrade']:
            pip_packs += ['{}'.format('pyprecag')]

        failDependencyCheck = [
            key for key, val in packCheck.items()
            if val['Action'] in ['Install', 'Upgrade']
        ]

        osgeo_packs = [
            '-P ' + p if 'gdal' in p else '-P python3-' + p
            for p in osgeo_packs
        ]

        # create a dictionary to use with the template file.
        d = {
            'dependency_log':
            os.path.join(
                plugin_path, 'install_files',
                'dependency_{}.log'.format(date.today().strftime("%Y-%m-%d"))),
            'QGIS_PATH':
            osgeo_path,
            'QGIS_VERSION':
            Qgis.QGIS_VERSION,
            'osgeo_message':
            'Installing {}'.format(', '.join(osgeo_packs)),
            'osgeo_packs':
            '' if len(osgeo_packs) == 0 else ' '.join(osgeo_packs),
            'pip_func':
            'install',
            'pip_packs':
            '' if len(pip_packs) == 0 else ' '.join(pip_packs),
            'py_version':
            struct.calcsize("P") * 8
        }  # this will return 64 or 32

        # 'osgeo_uninst': ' -x python3-'.join(['fiona', 'geopandas', 'rasterio'])
        temp_file = os.path.join(plugin_path, 'util',
                                 'Install_PAT3_Extras.template')
        install_file = os.path.join(
            plugin_path, 'install_files',
            '{}_4_qgis{}.bat'.format(title,
                                     str(Qgis.QGIS_VERSION_INT)[:-2]))
        uninstall_file = os.path.join(
            plugin_path, 'install_files',
            'Un{}_4_qgis{}.bat'.format(title,
                                       str(Qgis.QGIS_VERSION_INT)[:-2]))
        python_version = struct.calcsize("P") * 8  # this will return 64 or 32

        if not os.path.exists(os.path.dirname(install_file)):
            os.mkdir(os.path.dirname(install_file))

        if len(failDependencyCheck) > 0:

            create_file_from_template(temp_file, d, install_file)

            # Create a shortcut on desktop with admin privileges.
            if platform.system() == 'Windows':
                try:
                    aReg = ConnectRegistry(None, HKEY_CURRENT_USER)
                    aKey = OpenKey(
                        aReg,
                        r"Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
                    )
                    aVal = os.path.normpath(QueryValueEx(aKey, "Desktop")[0])
                    LOGGER.info(
                        'Desktop path from registry is {}'.format(aVal))
                except:
                    pass

                LOGGER.critical(
                    "Failed Dependency Check. Please run the shortcut {} "
                    "or the following bat file as administrator {}".format(
                        shortcutPath, install_file))

                create_link(shortcutPath, install_file,
                            "Install setup for QGIS PAT Plugin", user_path,
                            True)

            message = 'Installation or updates are required for {}.\n\nPlease quit QGIS and run {} ' \
                      'located on your desktop.'.format(', '.join(failDependencyCheck), title)
            iface.messageBar().pushMessage("ERROR Failed Dependency Check",
                                           message,
                                           level=Qgis.Critical,
                                           duration=0)
            QMessageBox.critical(None, 'Failed Dependency Check', message)
            return (message)
        else:

            settings_version = read_setting(PLUGIN_NAME + "/PAT_VERSION")

            if settings_version is None:
                LOGGER.info('Successfully installed and setup PAT {}'.format(
                    meta_version))
            else:
                if parse_version(meta_version) > parse_version(
                        settings_version):
                    LOGGER.info(
                        'Successfully upgraded and setup PAT from {} to {})'.
                        format(settings_version, meta_version))

                elif parse_version(meta_version) < parse_version(
                        settings_version):
                    LOGGER.info(
                        'Successfully downgraded and setup PAT from {} to {})'.
                        format(settings_version, meta_version))

            write_setting(PLUGIN_NAME + '/PAT_VERSION', meta_version)

            if os.path.exists(shortcutPath):
                os.remove(shortcutPath)

            if len(osgeo_packs) == 0:
                osgeo_packs = ['geopandas', 'rasterio']

            if len(pip_packs) == 0:
                pip_packs = ["pyprecag"]

            d.update({
                'osgeo_message':
                'Installing {}'.format(', '.join(osgeo_packs)),
                'osgeo_packs':
                '' if len(osgeo_packs) == 0 else '-P python3-' +
                ' -P python3-'.join(osgeo_packs),
                'pip_packs':
                '' if len(pip_packs) == 0 else ' '.join(pip_packs),
            })

            # Create master un&install files
            create_file_from_template(temp_file, d, install_file)

            d.update({
                'osgeo_message':
                'Uninstalling {}'.format(', '.join(osgeo_packs)),
                'osgeo_packs':
                '-o -x python3-' + ' -x python3-'.join(osgeo_packs),
                'pip_func':
                'uninstall'
            })

            create_file_from_template(temp_file, d, uninstall_file)

    except Exception as err:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        mess = str(traceback.format_exc())

        setup = get_plugin_state()
        LOGGER.info(setup + '\n\n')
        LOGGER.error('\n' + mess)

        message = (
            'An error occurred during setup, please report this error to [email protected] '
            'and attach the following files \n\t {} \n\t{}'.format(
                get_logger_file(), install_file))

        QMessageBox.critical(None, 'Failed setup', message)

        sys.exit(message + '\n\n' + mess)

    return failDependencyCheck
示例#29
0
 def on_chkDebug_stateChanged(self, state):
     if config.get_debug_mode() != self.chkDebug.isChecked():
         write_setting(PLUGIN_NAME + '/DEBUG',  self.chkDebug.isChecked())
         config.set_debug_mode( self.chkDebug.isChecked())
示例#30
0
# -*- coding: utf-8 -*-