Ejemplo n.º 1
0
    def handlerDialogHelp(self, dialogName):
        """Slot method for opening the dialog html help document.
        
        Args:
            dialogName (str): the name of the dialog.
        """
        helpDialogFile = None

        if dialogName == 'PUR':
            helpDialogFile = 'helpDialogPURFile'
        elif dialogName == 'QUES':
            helpDialogFile = 'helpDialogQUESFile'
        elif dialogName == 'TA':
            helpDialogFile = 'helpDialogTAFile'
        elif dialogName == 'SCIENDO':
            helpDialogFile = 'helpDialogSCIENDOFile'
        else:
            helpDialogFile = 'helpLUMENSFile'

        filePath = os.path.join(self.main.appSettings['appDir'],
                                self.main.appSettings['folderHelp'],
                                self.main.appSettings[helpDialogFile])

        if os.path.exists(filePath):
            dialog = DialogLumensViewer(self,
                                        'LUMENS Help - {0}'.format(dialogName),
                                        'html', filePath)
            dialog.exec_()
        else:
            QtGui.QMessageBox.critical(
                self, 'LUMENS Help Not Found',
                "Unable to open '{0}'.".format(filePath))
Ejemplo n.º 2
0
 def handlerDialogHelp(self, dialogName):
     """Slot method for opening the dialog html help document.
     
     Args:
         dialogName (str): the name of the dialog.
     """
     helpDialogFile = None
     
     if dialogName == 'PUR':
         helpDialogFile = 'helpDialogPURFile'
     elif dialogName == 'QUES':
         helpDialogFile = 'helpDialogQUESFile'
     elif dialogName == 'TA':
         helpDialogFile = 'helpDialogTAFile'
     elif dialogName == 'SCIENDO':
         helpDialogFile = 'helpDialogSCIENDOFile'
     else:
         helpDialogFile = 'helpLUMENSFile'
     
     filePath = os.path.join(self.main.appSettings['appDir'], self.main.appSettings['folderHelp'], self.main.appSettings[helpDialogFile])
     
     if os.path.exists(filePath):
         dialog = DialogLumensViewer(self, 'LUMENS Help - {0}'.format(dialogName), 'html', filePath)
         dialog.exec_()
     else:
         QtGui.QMessageBox.critical(self, 'LUMENS Help Not Found', "Unable to open '{0}'.".format(filePath))
    def handlerProcessImportDatabase(self):
        """Slot method to pass the form values and execute the "Import Database" R algorithm.
        
        Upon successful completion of the algorithms the imported project database will be opened
        and the dialog will close. The "Import Database" process calls the following algorithms:
        1. modeler:lumens_import_database
        """
        self.setAppSettings()

        if self.validForm():
            logging.getLogger(type(self).__name__).info('start: %s' %
                                                        self.dialogTitle)
            self.buttonProcessImportDatabase.setDisabled(True)

            algName = 'modeler:lumens_import_database'

            # WORKAROUND: minimize LUMENS so MessageBarProgress does not show under LUMENS
            self.main.setWindowState(QtCore.Qt.WindowMinimized)

            outputs = general.runalg(
                algName,
                self.main.appSettings[type(self).__name__]['workingDir'],
                self.main.appSettings[type(self).__name__]['projectFile'],
            )

            # Display ROut file in debug mode
            if self.main.appSettings['debug']:
                dialog = DialogLumensViewer(
                    self,
                    'DEBUG "{0}" ({1})'.format(algName,
                                               'processing_script.r.Rout'),
                    'text', self.main.appSettings['ROutFile'])
                dialog.exec_()

            # WORKAROUND: once MessageBarProgress is done, activate LUMENS window again
            self.main.setWindowState(QtCore.Qt.WindowActive)

            algSuccess = self.outputsMessageBox(algName, outputs, '', '')

            self.buttonProcessImportDatabase.setEnabled(True)
            logging.getLogger(type(self).__name__).info('end: %s' %
                                                        self.dialogTitle)

            projectName = os.path.basename(
                os.path.splitext(self.main.appSettings[type(self).__name__]
                                 ['projectFile'])[0])

            lumensDatabase = os.path.join(
                self.main.appSettings[type(self).__name__]['workingDir'],
                projectName,
                os.path.basename(
                    self.main.appSettings[type(self).__name__]['projectFile']))

            # if LUMENS database file exists, open it and close dialog
            if os.path.exists(lumensDatabase):
                self.main.lumensOpenDatabase(lumensDatabase)
                self.close()
            else:
                logging.getLogger(type(self).__name__).error(
                    'modeler:lumens_import_database failed...')
Ejemplo n.º 4
0
 def handlerProcessImportDatabase(self):
     """Slot method to pass the form values and execute the "Import Database" R algorithm.
     
     Upon successful completion of the algorithms the imported project database will be opened
     and the dialog will close. The "Import Database" process calls the following algorithms:
     1. modeler:lumens_import_database
     """
     self.setAppSettings()
     
     if self.validForm():
         logging.getLogger(type(self).__name__).info('start: %s' % self.dialogTitle)
         self.buttonProcessImportDatabase.setDisabled(True)
         
         algName = 'modeler:lumens_import_database'
         
         # WORKAROUND: minimize LUMENS so MessageBarProgress does not show under LUMENS
         self.main.setWindowState(QtCore.Qt.WindowMinimized)
         
         outputs = general.runalg(
             algName,
             self.main.appSettings[type(self).__name__]['workingDir'],
             self.main.appSettings[type(self).__name__]['projectFile'],
         )
         
         # Display ROut file in debug mode
         if self.main.appSettings['debug']:
             dialog = DialogLumensViewer(self, 'DEBUG "{0}" ({1})'.format(algName, 'processing_script.r.Rout'), 'text', self.main.appSettings['ROutFile'])
             dialog.exec_()
         
         # WORKAROUND: once MessageBarProgress is done, activate LUMENS window again
         self.main.setWindowState(QtCore.Qt.WindowActive)
         
         algSuccess = self.outputsMessageBox(algName, outputs, '', '')
         
         self.buttonProcessImportDatabase.setEnabled(True)
         logging.getLogger(type(self).__name__).info('end: %s' % self.dialogTitle)
         
         projectName = os.path.basename(os.path.splitext(self.main.appSettings[type(self).__name__]['projectFile'])[0])
         
         lumensDatabase = os.path.join(
             self.main.appSettings[type(self).__name__]['workingDir'],
             projectName,
             os.path.basename(self.main.appSettings[type(self).__name__]['projectFile'])
         )
         
         # if LUMENS database file exists, open it and close dialog
         if os.path.exists(lumensDatabase):
             self.main.lumensOpenDatabase(lumensDatabase)
             self.close()
         else:
             logging.getLogger(type(self).__name__).error('modeler:lumens_import_database failed...')
 def handlerProcessDissolve(self):
     """Slot method to pass the form values and execute the "Dissolve" R algorithm.
     
     The "Dissolve" process calls the following algorithm:
     1. r:lumensdissolve
     """
     self.setFormFields()
     
     if self.validDissolved():
         logging.getLogger(type(self).__name__).info('start: %s' % 'LUMENS Dissolve')
         self.buttonProcessDissolve.setDisabled(True)
             
         algName = 'r:lumensdissolve'
         
         outputs = general.runalg(
             algName,
             self.dataFile,
             self.dataFieldAttribute,
             None,
         )
         
         # Display ROut file in debug mode
         if self.parent.main.appSettings['debug']:
             dialog = DialogLumensViewer(self, 'DEBUG "{0}" ({1})'.format(algName, 'processing_script.r.Rout'), 'text', self.parent.main.appSettings['ROutFile'])
             dialog.exec_()
         
         outputsKey = 'admin_output'
         
         if outputs and outputsKey in outputs and os.path.exists(outputs[outputsKey]):
             self.dataDissolvedShapefile = outputs[outputsKey]
             
             registry = QgsProviderRegistry.instance()
             provider = registry.provider('ogr', outputs[outputsKey])
             
             if not provider.isValid():
                 logging.getLogger(type(self).__name__).error('LUMENS Dissolve: invalid shapefile')
                 return
             
             attributes = []
             for field in provider.fields():
                 attributes.append(field.name())
             
             # Additional columns ('Legend', 'Classified' only for Land Use/Cover types)
             if self.dataType == 'Land Use/Cover':
                 attributes.append('Legend')
                 attributes.append('Classified')
             
             features = provider.getFeatures()
             
             if features:
                 self.dataTable.setEnabled(True)
                 self.dataTable.setRowCount(provider.featureCount())
                 self.dataTable.setColumnCount(len(attributes))
                 self.dataTable.verticalHeader().setVisible(False)
                 self.dataTable.setHorizontalHeaderLabels(attributes)
                 
                 # Need a nicer way than manual looping
                 tableRow = 0
                 for feature in features:
                     tableColumn = 0
                     for attribute in attributes:
                         if attribute == 'Legend' or attribute == 'Classified': # Skip the additional column
                             continue
                         attributeValue = str(feature.attribute(attribute))
                         attributeValueTableItem = QtGui.QTableWidgetItem(attributeValue)
                         if tableColumn == 1 and self.dataType == 'Planning Unit': # Editable second column for Vector Planning Units
                             pass
                         else:
                             attributeValueTableItem.setFlags(attributeValueTableItem.flags() & ~QtCore.Qt.ItemIsEnabled)
                         self.dataTable.setItem(tableRow, tableColumn, attributeValueTableItem)
                         self.dataTable.horizontalHeader().setResizeMode(tableColumn, QtGui.QHeaderView.ResizeToContents)
                         tableColumn += 1
                     
                     # Additional columns ('Legend', 'Classified' only for Land Use/Cover types)
                     if self.dataType == 'Land Use/Cover':
                         fieldLegend = QtGui.QTableWidgetItem('Unidentified Landuse {0}'.format(tableRow + 1))
                         columnLegend = tableColumn
                         self.dataTable.setItem(tableRow, tableColumn, fieldLegend)
                         self.dataTable.horizontalHeader().setResizeMode(columnLegend, QtGui.QHeaderView.ResizeToContents)
                         
                         tableColumn += 1
                         columnClassified = tableColumn
                         comboBoxClassified = QtGui.QComboBox()
                         for key, val in self.classifiedOptions.iteritems():
                             comboBoxClassified.addItem(val, key)
                         self.dataTable.setCellWidget(tableRow, tableColumn, comboBoxClassified)
                         self.dataTable.horizontalHeader().setResizeMode(columnClassified, QtGui.QHeaderView.ResizeToContents)
                     
                     tableRow += 1
                 
                 self.dataTable.resizeColumnsToContents()
                 self.buttonProcessSave.setEnabled(True)
         
         self.buttonSelectDataMapping.setEnabled(True)
         self.buttonProcessDissolve.setEnabled(True)
         logging.getLogger(type(self).__name__).info('end: %s' % 'LUMENS Dissolve')
Ejemplo n.º 6
0
    def handlerProcessCreateDatabase(self):
        """Slot method to pass the form values and execute the "Create Database" R algorithms.
        
        Upon successful completion of the algorithms the new project database will be opened
        and the dialog will close. The "Create Database" process calls the following algorithm:
        1. modeler:lumens_create_database
        """
        self.setAppSettings()

        dissolvedTableCsv = self.getDissolvedTableCsv(True)

        if self.validForm() and dissolvedTableCsv:
            logging.getLogger(type(self).__name__).info("start: %s" % self.dialogTitle)

            self.buttonProcessCreateDatabase.setDisabled(True)

            algName = "r:lumenscreatedatabase"

            # WORKAROUND: minimize LUMENS so MessageBarProgress does not show under LUMENS
            self.main.setWindowState(QtCore.Qt.WindowMinimized)

            outputs = general.runalg(
                algName,
                self.main.appSettings[type(self).__name__]["projectName"],
                self.main.appSettings[type(self).__name__]["outputFolder"],
                self.main.appSettings[type(self).__name__]["projectDescription"],
                self.main.appSettings[type(self).__name__]["projectLocation"],
                self.main.appSettings[type(self).__name__]["projectProvince"],
                self.main.appSettings[type(self).__name__]["projectCountry"],
                self.main.appSettings[type(self).__name__]["dissolvedShapefile"],
                self.main.appSettings[type(self).__name__]["shapefileAttr"],
                self.main.appSettings[type(self).__name__]["projectSpatialRes"],
                dissolvedTableCsv,
                None,
            )

            # Display ROut file in debug mode
            if self.main.appSettings["debug"]:
                dialog = DialogLumensViewer(
                    self,
                    'DEBUG "{0}" ({1})'.format(algName, "processing_script.r.Rout"),
                    "text",
                    self.main.appSettings["ROutFile"],
                )
                dialog.exec_()

            # Construct the project .lpj filepath
            lumensDatabase = os.path.join(
                self.main.appSettings[type(self).__name__]["outputFolder"],
                self.main.appSettings[type(self).__name__]["projectName"],
                "{0}{1}".format(
                    self.main.appSettings[type(self).__name__]["projectName"],
                    self.main.appSettings["selectProjectfileExt"],
                ),
            )

            # WORKAROUND: once MessageBarProgress is done, activate LUMENS window again
            self.main.setWindowState(QtCore.Qt.WindowActive)

            algSuccess = self.outputsMessageBox(
                algName,
                outputs,
                "LUMENS database successfully created!\nClick OK to open the database.",
                "Failed to create the LUMENS database.",
            )

            self.buttonProcessCreateDatabase.setEnabled(True)
            logging.getLogger(type(self).__name__).info("end: %s" % self.dialogTitle)

            lumensHTMLReport = os.path.join(
                self.main.appSettings[type(self).__name__]["outputFolder"],
                self.main.appSettings[type(self).__name__]["projectName"],
                "DATA",
                "{0}{1}".format(
                    self.main.appSettings[type(self).__name__]["projectName"],
                    self.main.appSettings["selectHTMLfileExt"],
                ),
            ).replace(os.path.sep, "/")

            # If LUMENS database file exists, open it and close this dialog
            if algSuccess and os.path.exists(lumensDatabase):
                self.main.lumensOpenDatabase(lumensDatabase)
                self.close()

                if os.path.exists(lumensHTMLReport):
                    dialog = DialogLumensViewer(self, "LUMENS Create Database Report", "html", lumensHTMLReport)
                    dialog.exec_()
            else:
                logging.getLogger(type(self).__name__).error("modeler:lumens_create_database failed...")
Ejemplo n.º 7
0
    def handlerProcessDissolve(self):
        """Slot method to pass the form values and execute the "Dissolve" R algorithm.
        
        The "Dissolve" process calls the following algorithm:
        1. r:lumensdissolve
        """
        self.setAppSettings()

        if self.validForm():
            logging.getLogger(type(self).__name__).info("start: %s" % "LUMENS Dissolve")

            self.buttonProcessDissolve.setDisabled(True)

            algName = "r:lumensdissolve"

            # WORKAROUND: minimize LUMENS so MessageBarProgress does not show under LUMENS
            self.main.setWindowState(QtCore.Qt.WindowMinimized)

            outputs = general.runalg(
                algName,
                self.main.appSettings[type(self).__name__]["shapefile"],
                self.main.appSettings[type(self).__name__]["shapefileAttr"],
                None,
            )

            # Display ROut file in debug mode
            if self.main.appSettings["debug"]:
                dialog = DialogLumensViewer(
                    self,
                    'DEBUG "{0}" ({1})'.format(algName, "processing_script.r.Rout"),
                    "text",
                    self.main.appSettings["ROutFile"],
                )
                dialog.exec_()

            if outputs and os.path.exists(outputs["admin_output"]):
                self.dissolvedShapefile = outputs["admin_output"]  # To be processed in setAppSettings()

                registry = QgsProviderRegistry.instance()
                provider = registry.provider("ogr", outputs["admin_output"])

                if not provider.isValid():
                    logging.getLogger(type(self).__name__).error("LUMENS Dissolve: invalid shapefile")
                    return

                attributes = []
                for field in provider.fields():
                    attributes.append(field.name())

                features = provider.getFeatures()

                if features:
                    self.tableDissolved.setEnabled(True)
                    self.tableDissolved.setRowCount(provider.featureCount())
                    self.tableDissolved.setColumnCount(len(attributes))
                    self.tableDissolved.verticalHeader().setVisible(False)
                    self.tableDissolved.setHorizontalHeaderLabels(attributes)

                    # Need a nicer way than manual looping
                    tableRow = 0
                    for feature in features:
                        tableColumn = 0
                        for attribute in attributes:
                            attributeValue = str(feature.attribute(attribute))
                            attributeValueTableItem = QtGui.QTableWidgetItem(attributeValue)
                            self.tableDissolved.setItem(tableRow, tableColumn, attributeValueTableItem)
                            self.tableDissolved.horizontalHeader().setResizeMode(
                                tableColumn, QtGui.QHeaderView.ResizeToContents
                            )
                            tableColumn += 1
                        tableRow += 1

                    self.buttonProcessCreateDatabase.setEnabled(True)

            # WORKAROUND: once MessageBarProgress is done, activate LUMENS window again
            self.main.setWindowState(QtCore.Qt.WindowActive)

            self.buttonProcessDissolve.setEnabled(True)
            logging.getLogger(type(self).__name__).info("end: %s" % "LUMENS Dissolve")
 def handlerProcessCreateDatabase(self):
     """Slot method to pass the form values and execute the "Create Database" R algorithms.
     
     Upon successful completion of the algorithms the new project database will be opened
     and the dialog will close. The "Create Database" process calls the following algorithm:
     1. modeler:lumens_create_database
     """
     self.setAppSettings()
     
     dissolvedTableCsv = self.getDissolvedTableCsv(True)
     
     if self.validForm() and dissolvedTableCsv:
         logging.getLogger(type(self).__name__).info('start: %s' % self.dialogTitle)
         
         self.buttonProcessCreateDatabase.setDisabled(True)
         
         algName = 'modeler:lumens_create_database'
         
         # WORKAROUND: minimize LUMENS so MessageBarProgress does not show under LUMENS
         self.main.setWindowState(QtCore.Qt.WindowMinimized)
         
         outputs = general.runalg(
             algName,
             self.main.appSettings[type(self).__name__]['projectName'],
             self.main.appSettings[type(self).__name__]['outputFolder'],
             self.main.appSettings[type(self).__name__]['projectDescription'],
             self.main.appSettings[type(self).__name__]['projectLocation'],
             self.main.appSettings[type(self).__name__]['projectProvince'],
             self.main.appSettings[type(self).__name__]['projectCountry'],
             self.main.appSettings[type(self).__name__]['dissolvedShapefile'],
             self.main.appSettings[type(self).__name__]['shapefileAttr'],
             self.main.appSettings[type(self).__name__]['projectSpatialRes'],
             dissolvedTableCsv,
             None,
         )
         
         # Display ROut file in debug mode
         if self.main.appSettings['debug']:
             dialog = DialogLumensViewer(self, 'DEBUG "{0}" ({1})'.format(algName, 'processing_script.r.Rout'), 'text', self.main.appSettings['ROutFile'])
             dialog.exec_()
         
         # Construct the project .lpj filepath
         lumensDatabase = os.path.join(
             self.main.appSettings[type(self).__name__]['outputFolder'],
             self.main.appSettings[type(self).__name__]['projectName'],
             "{0}{1}".format(self.main.appSettings[type(self).__name__]['projectName'], self.main.appSettings['selectProjectfileExt'])
         )
         
         # WORKAROUND: once MessageBarProgress is done, activate LUMENS window again
         self.main.setWindowState(QtCore.Qt.WindowActive)
         
         algSuccess = self.outputsMessageBox(algName, outputs, 'LUMENS database successfully created!', 'Failed to create the LUMENS database.')
         
         self.buttonProcessCreateDatabase.setEnabled(True)
         logging.getLogger(type(self).__name__).info('end: %s' % self.dialogTitle)
         
         # If LUMENS database file exists, open it and close this dialog
         if os.path.exists(lumensDatabase):
             self.main.lumensOpenDatabase(lumensDatabase)
             self.close()
         else:
             logging.getLogger(type(self).__name__).error('modeler:lumens_create_database failed...')
    def handlerProcessDissolve(self):
        """Slot method to pass the form values and execute the "Dissolve" R algorithm.
        
        The "Dissolve" process calls the following algorithm:
        1. r:lumensdissolve
        """
        self.setFormFields()

        if self.validDissolved():
            logging.getLogger(type(self).__name__).info('start: %s' %
                                                        'LUMENS Dissolve')
            self.buttonProcessDissolve.setDisabled(True)

            algName = 'r:lumensdissolve'

            outputs = general.runalg(
                algName,
                self.dataFile,
                self.dataFieldAttribute,
                None,
            )

            # Display ROut file in debug mode
            if self.parent.main.appSettings['debug']:
                dialog = DialogLumensViewer(
                    self,
                    'DEBUG "{0}" ({1})'.format(algName,
                                               'processing_script.r.Rout'),
                    'text', self.parent.main.appSettings['ROutFile'])
                dialog.exec_()

            outputsKey = 'admin_output'

            if outputs and outputsKey in outputs and os.path.exists(
                    outputs[outputsKey]):
                self.dataDissolvedShapefile = outputs[outputsKey]

                registry = QgsProviderRegistry.instance()
                provider = registry.provider('ogr', outputs[outputsKey])

                if not provider.isValid():
                    logging.getLogger(type(self).__name__).error(
                        'LUMENS Dissolve: invalid shapefile')
                    return

                attributes = []
                for field in provider.fields():
                    attributes.append(field.name())

                # Additional columns ('Legend', 'Classified' only for Land Use/Cover types)
                if self.dataType == 'Land Use/Cover':
                    attributes.append('Legend')
                    attributes.append('Classified')

                features = provider.getFeatures()

                if features:
                    self.dataTable.setEnabled(True)
                    self.dataTable.setRowCount(provider.featureCount())
                    self.dataTable.setColumnCount(len(attributes))
                    self.dataTable.verticalHeader().setVisible(False)
                    self.dataTable.setHorizontalHeaderLabels(attributes)

                    # Need a nicer way than manual looping
                    tableRow = 0
                    for feature in features:
                        tableColumn = 0
                        for attribute in attributes:
                            if attribute == 'Legend' or attribute == 'Classified':  # Skip the additional column
                                continue
                            attributeValue = str(feature.attribute(attribute))
                            attributeValueTableItem = QtGui.QTableWidgetItem(
                                attributeValue)
                            if tableColumn == 1 and self.dataType == 'Planning Unit':  # Editable second column for Vector Planning Units
                                pass
                            else:
                                attributeValueTableItem.setFlags(
                                    attributeValueTableItem.flags()
                                    & ~QtCore.Qt.ItemIsEnabled)
                            self.dataTable.setItem(tableRow, tableColumn,
                                                   attributeValueTableItem)
                            self.dataTable.horizontalHeader().setResizeMode(
                                tableColumn,
                                QtGui.QHeaderView.ResizeToContents)
                            tableColumn += 1

                        # Additional columns ('Legend', 'Classified' only for Land Use/Cover types)
                        if self.dataType == 'Land Use/Cover':
                            fieldLegend = QtGui.QTableWidgetItem(
                                'Unidentified Landuse {0}'.format(tableRow +
                                                                  1))
                            columnLegend = tableColumn
                            self.dataTable.setItem(tableRow, tableColumn,
                                                   fieldLegend)
                            self.dataTable.horizontalHeader().setResizeMode(
                                columnLegend,
                                QtGui.QHeaderView.ResizeToContents)

                            tableColumn += 1
                            columnClassified = tableColumn
                            comboBoxClassified = QtGui.QComboBox()
                            for key, val in self.classifiedOptions.iteritems():
                                comboBoxClassified.addItem(val, key)
                            self.dataTable.setCellWidget(
                                tableRow, tableColumn, comboBoxClassified)
                            self.dataTable.horizontalHeader().setResizeMode(
                                columnClassified,
                                QtGui.QHeaderView.ResizeToContents)

                        tableRow += 1

                    self.dataTable.resizeColumnsToContents()
                    self.buttonProcessSave.setEnabled(True)

            self.buttonSelectDataMapping.setEnabled(True)
            self.buttonProcessDissolve.setEnabled(True)
            logging.getLogger(type(self).__name__).info('end: %s' %
                                                        'LUMENS Dissolve')
Ejemplo n.º 10
0
    def handlerProcessCreateDatabase(self):
        """Slot method to pass the form values and execute the "Create Database" R algorithms.
        
        Upon successful completion of the algorithms the new project database will be opened
        and the dialog will close. The "Create Database" process calls the following algorithm:
        1. modeler:lumens_create_database
        """
        self.setAppSettings()

        dissolvedTableCsv = self.getDissolvedTableCsv(True)

        if self.validForm() and dissolvedTableCsv:
            logging.getLogger(type(self).__name__).info('start: %s' %
                                                        self.dialogTitle)

            self.buttonProcessCreateDatabase.setDisabled(True)

            algName = 'r:lumenscreatedatabase'

            # WORKAROUND: minimize LUMENS so MessageBarProgress does not show under LUMENS
            self.main.setWindowState(QtCore.Qt.WindowMinimized)

            outputs = general.runalg(
                algName,
                self.main.appSettings[type(self).__name__]['projectName'],
                self.main.appSettings[type(self).__name__]['outputFolder'],
                self.main.appSettings[type(
                    self).__name__]['projectDescription'],
                self.main.appSettings[type(self).__name__]['projectLocation'],
                self.main.appSettings[type(self).__name__]['projectProvince'],
                self.main.appSettings[type(self).__name__]['projectCountry'],
                self.main.appSettings[type(
                    self).__name__]['dissolvedShapefile'],
                self.main.appSettings[type(self).__name__]['shapefileAttr'],
                self.main.appSettings[type(self).__name__]
                ['projectSpatialRes'],
                dissolvedTableCsv,
                None,
            )

            # Display ROut file in debug mode
            if self.main.appSettings['debug']:
                dialog = DialogLumensViewer(
                    self,
                    'DEBUG "{0}" ({1})'.format(algName,
                                               'processing_script.r.Rout'),
                    'text', self.main.appSettings['ROutFile'])
                dialog.exec_()

            # Construct the project .lpj filepath
            lumensDatabase = os.path.join(
                self.main.appSettings[type(self).__name__]['outputFolder'],
                self.main.appSettings[type(self).__name__]['projectName'],
                "{0}{1}".format(
                    self.main.appSettings[type(self).__name__]['projectName'],
                    self.main.appSettings['selectProjectfileExt']))

            # WORKAROUND: once MessageBarProgress is done, activate LUMENS window again
            self.main.setWindowState(QtCore.Qt.WindowActive)

            algSuccess = self.outputsMessageBox(
                algName, outputs,
                'LUMENS database successfully created!\nClick OK to open the database.',
                'Failed to create the LUMENS database.')

            self.buttonProcessCreateDatabase.setEnabled(True)
            logging.getLogger(type(self).__name__).info('end: %s' %
                                                        self.dialogTitle)

            lumensHTMLReport = os.path.join(
                self.main.appSettings[type(self).__name__]['outputFolder'],
                self.main.appSettings[type(self).__name__]['projectName'],
                "DATA", "{0}{1}".format(
                    self.main.appSettings[type(self).__name__]['projectName'],
                    self.main.appSettings['selectHTMLfileExt'])).replace(
                        os.path.sep, '/')

            # If LUMENS database file exists, open it and close this dialog
            if algSuccess and os.path.exists(lumensDatabase):
                self.main.lumensOpenDatabase(lumensDatabase)
                self.close()

                if os.path.exists(lumensHTMLReport):
                    dialog = DialogLumensViewer(
                        self, 'LUMENS Create Database Report', 'html',
                        lumensHTMLReport)
                    dialog.exec_()
            else:
                logging.getLogger(type(self).__name__).error(
                    'modeler:lumens_create_database failed...')
Ejemplo n.º 11
0
    def handlerProcessDissolve(self):
        """Slot method to pass the form values and execute the "Dissolve" R algorithm.
        
        The "Dissolve" process calls the following algorithm:
        1. r:lumensdissolve
        """
        self.setAppSettings()

        if self.validForm():
            logging.getLogger(type(self).__name__).info('start: %s' %
                                                        'LUMENS Dissolve')

            self.buttonProcessDissolve.setDisabled(True)

            algName = 'r:lumensdissolve'

            # WORKAROUND: minimize LUMENS so MessageBarProgress does not show under LUMENS
            self.main.setWindowState(QtCore.Qt.WindowMinimized)

            outputs = general.runalg(
                algName,
                self.main.appSettings[type(self).__name__]['shapefile'],
                self.main.appSettings[type(self).__name__]['shapefileAttr'],
                None,
            )

            # Display ROut file in debug mode
            if self.main.appSettings['debug']:
                dialog = DialogLumensViewer(
                    self,
                    'DEBUG "{0}" ({1})'.format(algName,
                                               'processing_script.r.Rout'),
                    'text', self.main.appSettings['ROutFile'])
                dialog.exec_()

            if outputs and os.path.exists(outputs['admin_output']):
                self.dissolvedShapefile = outputs[
                    'admin_output']  # To be processed in setAppSettings()

                registry = QgsProviderRegistry.instance()
                provider = registry.provider('ogr', outputs['admin_output'])

                if not provider.isValid():
                    logging.getLogger(type(self).__name__).error(
                        'LUMENS Dissolve: invalid shapefile')
                    return

                attributes = []
                for field in provider.fields():
                    attributes.append(field.name())

                features = provider.getFeatures()

                if features:
                    self.tableDissolved.setEnabled(True)
                    self.tableDissolved.setRowCount(provider.featureCount())
                    self.tableDissolved.setColumnCount(len(attributes))
                    self.tableDissolved.verticalHeader().setVisible(False)
                    self.tableDissolved.setHorizontalHeaderLabels(attributes)

                    # Need a nicer way than manual looping
                    tableRow = 0
                    for feature in features:
                        tableColumn = 0
                        for attribute in attributes:
                            attributeValue = str(feature.attribute(attribute))
                            attributeValueTableItem = QtGui.QTableWidgetItem(
                                attributeValue)
                            self.tableDissolved.setItem(
                                tableRow, tableColumn, attributeValueTableItem)
                            self.tableDissolved.horizontalHeader(
                            ).setResizeMode(tableColumn,
                                            QtGui.QHeaderView.ResizeToContents)
                            tableColumn += 1
                        tableRow += 1

                    self.buttonProcessCreateDatabase.setEnabled(True)

            # WORKAROUND: once MessageBarProgress is done, activate LUMENS window again
            self.main.setWindowState(QtCore.Qt.WindowActive)

            self.buttonProcessDissolve.setEnabled(True)
            logging.getLogger(type(self).__name__).info('end: %s' %
                                                        'LUMENS Dissolve')
Ejemplo n.º 12
0
    def handlerProcessAddData(self):
        """
        """
        self.setAppSettings()

        if self.checkBoxAddLandUseCoverData.isChecked():
            formName = 'DialogLumensAddLandcoverRaster'
            algName = 'modeler:lumens_add_landcover_raster'

            if self.validForm(formName):
                logging.getLogger(type(self).__name__).info('alg start: %s' %
                                                            formName)
                self.buttonProcessAddData.setDisabled(True)

                # WORKAROUND: minimize LUMENS so MessageBarProgress does not show under LUMENS
                self.main.setWindowState(QtCore.Qt.WindowMinimized)

                outputs = general.runalg(
                    algName,
                    self.main.appSettings[formName]['rasterfile'],
                    self.main.appSettings[formName]['period'],
                    self.main.appSettings[formName]['description'],
                )

                # Display ROut file in debug mode
                if self.main.appSettings['debug']:
                    dialog = DialogLumensViewer(
                        self,
                        'DEBUG "{0}" ({1})'.format(algName,
                                                   'processing_script.r.Rout'),
                        'text', self.main.appSettings['ROutFile'])
                    dialog.exec_()

                ##print outputs

                # WORKAROUND: once MessageBarProgress is done, activate LUMENS window again
                self.main.setWindowState(QtCore.Qt.WindowActive)

                self.outputsMessageBox(algName, outputs, '', '')

                self.buttonProcessAddData.setEnabled(True)
                logging.getLogger(type(self).__name__).info('alg end: %s' %
                                                            formName)

        if self.checkBoxAddPeatData.isChecked():
            formName = 'DialogLumensAddPeatData'
            algName = 'modeler:lumens_add_peat'

            if self.validForm(formName):
                logging.getLogger(type(self).__name__).info('alg start: %s' %
                                                            formName)
                self.buttonProcessAddData.setDisabled(True)

                # WORKAROUND: minimize LUMENS so MessageBarProgress does not show under LUMENS
                self.main.setWindowState(QtCore.Qt.WindowMinimized)

                outputs = general.runalg(
                    algName,
                    self.main.appSettings[formName]['rasterfile'],
                    self.main.appSettings[formName]['description'],
                )

                # Display ROut file in debug mode
                if self.main.appSettings['debug']:
                    dialog = DialogLumensViewer(
                        self,
                        'DEBUG "{0}" ({1})'.format(algName,
                                                   'processing_script.r.Rout'),
                        'text', self.main.appSettings['ROutFile'])
                    dialog.exec_()

                ##print outputs

                # WORKAROUND: once MessageBarProgress is done, activate LUMENS window again
                self.main.setWindowState(QtCore.Qt.WindowActive)

                self.outputsMessageBox(algName, outputs, '', '')

                self.buttonProcessAddData.setEnabled(True)
                logging.getLogger(type(self).__name__).info('alg end: %s' %
                                                            formName)

        if self.checkBoxAddFactorData.isChecked():
            formName = 'DialogLumensAddFactorData'
            algName = 'modeler:lumens_add_factor_data'

            if self.validForm(formName):
                logging.getLogger(type(self).__name__).info('alg start: %s' %
                                                            formName)
                self.buttonProcessAddData.setDisabled(True)

                # WORKAROUND: minimize LUMENS so MessageBarProgress does not show under LUMENS
                self.main.setWindowState(QtCore.Qt.WindowMinimized)

                outputs = general.runalg(
                    algName,
                    self.main.appSettings[formName]['rasterfile'],
                    self.main.appSettings[formName]['description'],
                )

                # Display ROut file in debug mode
                if self.main.appSettings['debug']:
                    dialog = DialogLumensViewer(
                        self,
                        'DEBUG "{0}" ({1})'.format(algName,
                                                   'processing_script.r.Rout'),
                        'text', self.main.appSettings['ROutFile'])
                    dialog.exec_()

                ##print outputs

                # WORKAROUND: once MessageBarProgress is done, activate LUMENS window again
                self.main.setWindowState(QtCore.Qt.WindowActive)

                self.outputsMessageBox(algName, outputs, '', '')

                self.buttonProcessAddData.setEnabled(True)
                logging.getLogger(type(self).__name__).info('alg end: %s' %
                                                            formName)

        if self.checkBoxAddPlanningUnitData.isChecked():
            formName = 'DialogLumensAddPlanningUnitData'
            algName = 'modeler:lumens_add_planning_unit'

            if self.validForm(formName):
                logging.getLogger(type(self).__name__).info('alg start: %s' %
                                                            formName)
                self.buttonProcessAddData.setDisabled(True)

                # WORKAROUND: minimize LUMENS so MessageBarProgress does not show under LUMENS
                self.main.setWindowState(QtCore.Qt.WindowMinimized)

                outputs = general.runalg(
                    algName,
                    self.main.appSettings[formName]['rasterfile'],
                    self.main.appSettings[formName]['csvfile'],
                    self.main.appSettings[formName]['description'],
                )

                # Display ROut file in debug mode
                if self.main.appSettings['debug']:
                    dialog = DialogLumensViewer(
                        self,
                        'DEBUG "{0}" ({1})'.format(algName,
                                                   'processing_script.r.Rout'),
                        'text', self.main.appSettings['ROutFile'])
                    dialog.exec_()

                ##print outputs

                # WORKAROUND: once MessageBarProgress is done, activate LUMENS window again
                self.main.setWindowState(QtCore.Qt.WindowActive)

                self.outputsMessageBox(algName, outputs, '', '')

                self.buttonProcessAddData.setEnabled(True)
                logging.getLogger(type(self).__name__).info('alg end: %s' %
                                                            formName)
Ejemplo n.º 13
0
 def handlerProcessAddData(self):
     """Slot method to pass the form values and execute the "Add Data" R algorithms.
     
     Depending on the type of the added data file (vector or raster) the appropriate
     R algorithm is called.
     
     The "Add Data" process calls the following algorithms:
     1. r:lumensaddrasterdata
     2. r:lumensaddvectordata
     """
     self.setAppSettings()
     
     if self.validForm():
         logging.getLogger(type(self).__name__).info('start: %s' % self.dialogTitle)
         self.buttonProcessAddData.setDisabled(True)
         
         algName = None
         outputs = None
         
         # WORKAROUND: minimize LUMENS so MessageBarProgress does not show under LUMENS
         self.main.setWindowState(QtCore.Qt.WindowMinimized)
         
         for tableRowData in self.tableAddData:
             # The algName to be used depends on the type of the dataFile (vector or raster)
             
             if tableRowData['dataFile'].lower().endswith(self.main.appSettings['selectRasterfileExt']):
                 algName = 'r:lumensaddrasterdata'
                 
                 outputs = general.runalg(
                     algName,
                     tableRowData['dataType'],
                     tableRowData['dataFile'].replace(os.path.sep, '/'),
                     tableRowData['dataPeriod'],
                     tableRowData['dataDescription'],
                     tableRowData['dataTableCsv'],
                     None,
                 )
             elif tableRowData['dataFile'].lower().endswith(self.main.appSettings['selectShapefileExt']):
                 algName = 'r:lumensaddvectordata'
                 
                 print 'DEBUG'
                 print tableRowData
                 
                 outputs = general.runalg(
                     algName,
                     tableRowData['dataType'],
                     tableRowData['dataDissolvedShapefile'].replace(os.path.sep, '/'),
                     tableRowData['dataFieldAttribute'],
                     tableRowData['dataPeriod'],
                     tableRowData['dataDescription'],
                     tableRowData['dataTableCsv'],
                     None,
                 )
             elif tableRowData['dataFile'].lower().endswith(self.main.appSettings['selectCsvfileExt']):
                 algName = 'r:lumensaddlookuptable'
                 
                 outputs = general.runalg(
                     algName,
                     tableRowData['dataDescription'],
                     tableRowData['dataFile'].replace(os.path.sep, '/'),
                     tableRowData['dataTableCsv'],
                     None,
                 )
             
             # Display ROut file in debug mode
             if self.main.appSettings['debug']:
                 dialog = DialogLumensViewer(self, 'DEBUG "{0}" ({1})'.format(algName, 'processing_script.r.Rout'), 'text', self.main.appSettings['ROutFile'])
                 dialog.exec_()
         
         # WORKAROUND: once MessageBarProgress is done, activate LUMENS window again
         self.main.setWindowState(QtCore.Qt.WindowActive)
         
         algSuccess = self.outputsMessageBox(algName, outputs, 'Data successfully added to LUMENS database!', 'Failed to add data to LUMENS database.')
         
         self.buttonProcessAddData.setEnabled(True)
         logging.getLogger(type(self).__name__).info('end: %s' % self.dialogTitle)
         
         if algSuccess:
             self.close()
Ejemplo n.º 14
0
 def handlerProcessAddData(self):
     """
     """
     self.setAppSettings()
     
     if self.checkBoxAddLandUseCoverData.isChecked():
         formName = 'DialogLumensAddLandcoverRaster'
         algName = 'modeler:lumens_add_landcover_raster'
         
         if self.validForm(formName):
             logging.getLogger(type(self).__name__).info('alg start: %s' % formName)
             self.buttonProcessAddData.setDisabled(True)
             
             # WORKAROUND: minimize LUMENS so MessageBarProgress does not show under LUMENS
             self.main.setWindowState(QtCore.Qt.WindowMinimized)
             
             outputs = general.runalg(
                 algName,
                 self.main.appSettings[formName]['rasterfile'],
                 self.main.appSettings[formName]['period'],
                 self.main.appSettings[formName]['description'],
             )
             
             # Display ROut file in debug mode
             if self.main.appSettings['debug']:
                 dialog = DialogLumensViewer(self, 'DEBUG "{0}" ({1})'.format(algName, 'processing_script.r.Rout'), 'text', self.main.appSettings['ROutFile'])
                 dialog.exec_()
             
             ##print outputs
             
             # WORKAROUND: once MessageBarProgress is done, activate LUMENS window again
             self.main.setWindowState(QtCore.Qt.WindowActive)
             
             self.outputsMessageBox(algName, outputs, '', '')
             
             self.buttonProcessAddData.setEnabled(True)
             logging.getLogger(type(self).__name__).info('alg end: %s' % formName)
     
     if self.checkBoxAddPeatData.isChecked():
         formName = 'DialogLumensAddPeatData'
         algName = 'modeler:lumens_add_peat'
         
         if self.validForm(formName):
             logging.getLogger(type(self).__name__).info('alg start: %s' % formName)
             self.buttonProcessAddData.setDisabled(True)
             
             # WORKAROUND: minimize LUMENS so MessageBarProgress does not show under LUMENS
             self.main.setWindowState(QtCore.Qt.WindowMinimized)
             
             outputs = general.runalg(
                 algName,
                 self.main.appSettings[formName]['rasterfile'],
                 self.main.appSettings[formName]['description'],
             )
             
             # Display ROut file in debug mode
             if self.main.appSettings['debug']:
                 dialog = DialogLumensViewer(self, 'DEBUG "{0}" ({1})'.format(algName, 'processing_script.r.Rout'), 'text', self.main.appSettings['ROutFile'])
                 dialog.exec_()
             
             ##print outputs
             
             # WORKAROUND: once MessageBarProgress is done, activate LUMENS window again
             self.main.setWindowState(QtCore.Qt.WindowActive)
             
             self.outputsMessageBox(algName, outputs, '', '')
             
             self.buttonProcessAddData.setEnabled(True)
             logging.getLogger(type(self).__name__).info('alg end: %s' % formName)
     
     if self.checkBoxAddFactorData.isChecked():
         formName = 'DialogLumensAddFactorData'
         algName = 'modeler:lumens_add_factor_data'
         
         if self.validForm(formName):
             logging.getLogger(type(self).__name__).info('alg start: %s' % formName)
             self.buttonProcessAddData.setDisabled(True)
             
             # WORKAROUND: minimize LUMENS so MessageBarProgress does not show under LUMENS
             self.main.setWindowState(QtCore.Qt.WindowMinimized)
             
             outputs = general.runalg(
                 algName,
                 self.main.appSettings[formName]['rasterfile'],
                 self.main.appSettings[formName]['description'],
             )
             
             # Display ROut file in debug mode
             if self.main.appSettings['debug']:
                 dialog = DialogLumensViewer(self, 'DEBUG "{0}" ({1})'.format(algName, 'processing_script.r.Rout'), 'text', self.main.appSettings['ROutFile'])
                 dialog.exec_()
             
             ##print outputs
             
             # WORKAROUND: once MessageBarProgress is done, activate LUMENS window again
             self.main.setWindowState(QtCore.Qt.WindowActive)
             
             self.outputsMessageBox(algName, outputs, '', '')
             
             self.buttonProcessAddData.setEnabled(True)
             logging.getLogger(type(self).__name__).info('alg end: %s' % formName)
     
     if self.checkBoxAddPlanningUnitData.isChecked():
         formName = 'DialogLumensAddPlanningUnitData'
         algName = 'modeler:lumens_add_planning_unit'
         
         if self.validForm(formName):
             logging.getLogger(type(self).__name__).info('alg start: %s' % formName)
             self.buttonProcessAddData.setDisabled(True)
             
             # WORKAROUND: minimize LUMENS so MessageBarProgress does not show under LUMENS
             self.main.setWindowState(QtCore.Qt.WindowMinimized)
             
             outputs = general.runalg(
                 algName,
                 self.main.appSettings[formName]['rasterfile'],
                 self.main.appSettings[formName]['csvfile'],
                 self.main.appSettings[formName]['description'],
             )
             
             # Display ROut file in debug mode
             if self.main.appSettings['debug']:
                 dialog = DialogLumensViewer(self, 'DEBUG "{0}" ({1})'.format(algName, 'processing_script.r.Rout'), 'text', self.main.appSettings['ROutFile'])
                 dialog.exec_()
             
             ##print outputs
             
             # WORKAROUND: once MessageBarProgress is done, activate LUMENS window again
             self.main.setWindowState(QtCore.Qt.WindowActive)
             
             self.outputsMessageBox(algName, outputs, '', '')
             
             self.buttonProcessAddData.setEnabled(True)
             logging.getLogger(type(self).__name__).info('alg end: %s' % formName)