def getTestApp(): """ Start one QGis application to test agaist. If QGis is already running the handle to that app will be returned """ global QGISAPP # pylint: disable=W0603 if QGISAPP is None: myGuiFlag = True # All test will run qgis in safe_qgis mode QGISAPP = QgsApplication(sys.argv, myGuiFlag) QGISAPP.initQgis() # print QGISAPP.showSettings() global PARENT # pylint: disable=W0603 if PARENT is None: PARENT = QtGui.QWidget() global CANVAS # pylint: disable=W0603 if CANVAS is None: CANVAS = QgsMapCanvas(PARENT) CANVAS.resize(QtCore.QSize(400, 400)) global IFACE # pylint: disable=W0603 if IFACE is None: # QgisInterface is a stub implementation of the QGIS plugin interface IFACE = QgisInterface(CANVAS) return QGISAPP, CANVAS, IFACE, PARENT
def testImportCSVFile(self): QgsApplication.setPrefixPath("/usr/share/qgis", True) qgs = QgsApplication([], False) # load providers qgs.initQgis() # shapefile aroundtheblockPath = os.path.join(os.path.abspath("../../sampledata/aroundtheblock/"), "aroundtheblock.csv") logger = mockLogger() messageBar = MockMessageBar(logger) messageBox = MockMessageBox layer = loadCSVLayer( dateFormat='mm/dd/yyyy', gpsPath=aroundtheblockPath, logger=logger, mainWindow=None, messageBar=messageBar, messageBox=messageBox ) self.assertIsNotNone(layer) self.assertIsInstance(layer, QgsVectorLayer) self.assertTrue(layer.isValid()) featuresCount = sum(1 for _ in layer.getFeatures()) self.assertEqual(featuresCount, 587)
def globalQgis(): """Singleton implementation for a global QGIS app instance. Args: None Returns: A QGIS Application instance Raises: None """ global QGISAPP if QGISAPP is None: myGuiFlag = True # All test will run qgis in gui mode QGISAPP = QgsApplication(sys.argv, myGuiFlag) if 'QGISPATH' in os.environ: myPath = os.environ['QGISPATH'] myUseDefaultPathFlag = True QGISAPP.setPrefixPath(myPath, myUseDefaultPathFlag) QGISAPP.initQgis() s = QGISAPP.showSettings() print s return QGISAPP
def main(argv): # create Qt application app = QtGui.QApplication(argv, True) # Set the app style mySplashPix = QtGui.QPixmap(QtCore.QString(DATA_DIR + '/OCEAN.png')) mySplashPixScaled = mySplashPix.scaled(500, 300, Qt.Qt.KeepAspectRatio) mySplash = QtGui.QSplashScreen(mySplashPixScaled) mySplash.show() # initialize qgis libraries QgsApplication.setPrefixPath(QGIS_PREFIX, True) QgsApplication.initQgis() # create main window wnd = MainWindow(mySplash) wnd.show() # Create signal for app finish app.connect( app, QtCore.SIGNAL('lastWindowClosed()'), app, QtCore.SLOT('quit()')) # Start the app up retval = app.exec_() # We got an exit signal so time to clean up QgsApplication.exitQgis() sys.exit(retval)
def set_up_interface(): """ Sets up a QGIS pseudo-application which enables calling methods as if when calling them from QGIS-console. :return qgis_app: Pseudo QGIS-instance :rtype: QgsApplication :return canvas: The map canvas :rtype: QgsMapCanvas :return iface: A dummy interface, giving access to needed method-calls :rtype: QgisInterface """ gui_flag = True # All test will run qgis in gui mode qgis_app = QgsApplication(sys.argv, gui_flag) prefix_path = config.qgis_prefix_path() qgis_app.setPrefixPath(prefix_path, True) qgis_app.initQgis() QCoreApplication.setOrganizationName('QGIS') QCoreApplication.setApplicationName('QGIS2') # parent = QWidget() # canvas = QgsMapCanvas(parent) # canvas.resize(QSize(400, 400)) canvas = MyMapCanvas() iface = QgisInterface(canvas) return qgis_app, canvas, iface
def init(self, logo, title): from qgis.core import QgsApplication from PyQt4.QtGui import QApplication, QFont, QIcon from PyQt4.QtCore import QLocale, QTranslator try: import PyQt4.QtSql except ImportError: pass self.app = QgsApplication(self.sysargv, True) import roam.roam_style self.app.setStyleSheet(roam.roam_style.appstyle) QgsApplication.setPrefixPath(self.prefixpath, True) QgsApplication.initQgis() locale = QLocale.system().name() self.translationFile = os.path.join(self.i18npath, '{0}.qm'.format(locale)) translator = QTranslator() translator.load(self.translationFile, "i18n") self.app.installTranslator(translator) QApplication.setStyle("Plastique") QApplication.setFont(QFont('Segoe UI')) QApplication.setWindowIcon(QIcon(logo)) QApplication.setApplicationName(title) import roam.editorwidgets.core roam.editorwidgets.core.registerallwidgets() return self
def qgisapp(args=None, guienabled=True, configpath=None, sysexit=True): """ Create a new QGIS Qt application. You should use this before creating any Qt widgets or QGIS objects for your custom QGIS based application. usage: from qgis.core.contextmanagers import qgisapp def main(app): # Run your main code block with qgisapp(sys.argv) as app: main(app) args - args passed to the underlying QApplication. guienabled - True by default will create a QApplication with a GUI. Pass False if you wish to create no GUI based app, e.g a server app. configpath - Custom config path QGIS will use to load settings. sysexit - Call sys.exit on app exit. True by default. """ if not args: args = [] app = QgsApplication(args, guienabled, configpath) QgsApplication.initQgis() yield app if guienabled: exitcode = app.exec_() else: exitcode = 0 QgsApplication.exitQgis() if sysexit: sys.exit(exitcode)
def __init__(self): """ """ # Folder icon QgsApplication.initQgis() style = QgsApplication.style() self.folder_icon = QtGui.QIcon() self.folder_icon.addPixmap(style.standardPixmap(QtGui.QStyle.SP_DirClosedIcon), QtGui.QIcon.Normal, QtGui.QIcon.Off) warn_icon_path = os.path.join(GpicGlobals.Instance().images_dir_path, GpicGlobals.Instance().ICON_WARN_FILE_NAME) self.warn_icon = QtGui.QIcon(warn_icon_path) wms_layer_icon_path = os.path.join(GpicGlobals.Instance().images_dir_path, GpicGlobals.Instance().ICON_WMS_LAYER_FILE_NAME) self.wms_layer_icon = QtGui.QIcon(wms_layer_icon_path) wms_style_icon_path = os.path.join(GpicGlobals.Instance().images_dir_path, GpicGlobals.Instance().ICON_WMS_STYLE_FILE_NAME) self.wms_style_icon = QtGui.QIcon(wms_style_icon_path) wfs_layer_icon_path = os.path.join(GpicGlobals.Instance().images_dir_path, GpicGlobals.Instance().ICON_WFS_LAYER_FILE_NAME) self.wfs_layer_icon = QtGui.QIcon(wfs_layer_icon_path) raster_layer_icon_path = os.path.join(GpicGlobals.Instance().images_dir_path, GpicGlobals.Instance().ICON_RASTER_LAYER_FILE_NAME) self.raster_layer_icon = QtGui.QIcon(raster_layer_icon_path)
def start_app(cleanup=True): """ Will start a QgsApplication and call all initialization code like registering the providers and other infrastructure. It will not load any plugins. You can always get the reference to a running app by calling `QgsApplication.instance()`. The initialization will only happen once, so it is safe to call this method repeatedly. Parameters ---------- cleanup: Do cleanup on exit. Defaults to true. Returns ------- QgsApplication A QgsApplication singleton """ global QGISAPP try: QGISAPP except NameError: myGuiFlag = True # All test will run qgis in gui mode try: sys.argv except: sys.argv = [''] # In python3 we need to convert to a bytes object (or should # QgsApplication accept a QString instead of const char* ?) try: argvb = list(map(os.fsencode, sys.argv)) except AttributeError: argvb = sys.argv # Note: QGIS_PREFIX_PATH is evaluated in QgsApplication - # no need to mess with it here. QGISAPP = QgsApplication(argvb, myGuiFlag) QGISAPP.initQgis() print(QGISAPP.showSettings()) def debug_log_message(message, tag, level): print('{}({}): {}'.format(tag, level, message)) QgsApplication.instance().messageLog().messageReceived.connect(debug_log_message) if cleanup: import atexit @atexit.register def exitQgis(): QGISAPP.exitQgis() return QGISAPP
def qgis_app(): """ Start QGIS application to test against. Based on code from Inasafe plugin. :return: Reference to QGIS application, canvas and parent widget. :rtype:(QgsApplication, QWidget, QgsMapCanvas) """ global QGIS_APP if QGIS_APP is None: gui_flag = True QCoreApplication.setOrganizationName('QGIS') QCoreApplication.setOrganizationDomain('qgis.org') QCoreApplication.setApplicationName('STDM_Testing') QGIS_APP = QgsApplication(sys.argv, gui_flag) QGIS_APP.initQgis() global PARENT if PARENT is None: PARENT = QWidget() global CANVAS if CANVAS is None: CANVAS = QgsMapCanvas(PARENT) CANVAS.resize(QSize(400, 400)) return QGIS_APP, CANVAS, PARENT
def init_qgis(verbose=False): """ Initialize qgis application """ from qgis.core import Qgis, QgsApplication global qgis_application qgisPrefixPath = os.environ.get('QGIS_PREFIX_PATH','/usr/') sys.path.append(os.path.join(qgisPrefixPath, "share/qgis/python/plugins/")) # Set offscreen mode when no display # This will prevent Qt tryning to connect to display if os.environ.get('DISPLAY') is None: os.environ['QT_QPA_PLATFORM'] = 'offscreen' qgis_application = QgsApplication([], False ) qgis_application.setPrefixPath(qgisPrefixPath, True) qgis_application.initQgis() os.environ['QGIS_PREFIX_PATH'] = qgisPrefixPath # Auto cleanup @atexit.register def extQgis(): global qgis_application if qgis_application: qgis_application.exitQgis() del qgis_application if verbose: print(qgis_application.showSettings(),file=sys.stderr) # Install logging hook install_message_hook( verbose )
def init(args=None, guienabled=True, configpath=None, sysexit=True): """ Create a new QGIS Qt application. You should use this before creating any Qt widgets or QGIS objects for your custom QGIS based application. usage: from wrappers import QGIS QGIS.init() args - args passed to the underlying QApplication. guienabled - True by default will create a QApplication with a GUI. Pass False if you wish to create no GUI based app, e.g a server app. configpath - Custom config path QGIS will use to load settings. sysexit - Call sys.exit on app exit. True by default. """ if not args: args = [] if not configpath: configpath = '' app = QgsApplication(args, guienabled, configpath) QgsApplication.initQgis() return app
def get_qgis_app(): """ Start one QGIS application to test against. :returns: Handle to QGIS app, canvas, iface and parent. If there are any errors the tuple members will be returned as None. :rtype: (QgsApplication, CANVAS, IFACE, PARENT) If QGIS is already running the handle to that app will be returned. """ global QGIS_APP, PARENT, IFACE, CANVAS # pylint: disable=W0603 if iface: from qgis.core import QgsApplication QGIS_APP = QgsApplication CANVAS = iface.mapCanvas() PARENT = iface.mainWindow() IFACE = iface return QGIS_APP, CANVAS, IFACE, PARENT try: from PyQt4 import QtGui, QtCore from qgis.core import QgsApplication from qgis.gui import QgsMapCanvas except ImportError: return None, None, None, None global QGIS_APP # pylint: disable=W0603 if QGIS_APP is None: gui_flag = True # All test will run qgis in gui mode # noinspection PyPep8Naming QGIS_APP = QgsApplication(sys.argv, gui_flag) # Make sure QGIS_PREFIX_PATH is set in your env if needed! QGIS_APP.initQgis() s = QGIS_APP.showSettings() LOGGER.debug(s) global PARENT # pylint: disable=W0603 if PARENT is None: # noinspection PyPep8Naming PARENT = QtGui.QWidget() global CANVAS # pylint: disable=W0603 if CANVAS is None: # noinspection PyPep8Naming CANVAS = QgsMapCanvas(PARENT) CANVAS.resize(QtCore.QSize(400, 400)) global IFACE # pylint: disable=W0603 if IFACE is None: # QgisInterface is a stub implementation of the QGIS plugin interface # noinspection PyPep8Naming # IFACE = QgisInterface(CANVAS) IFACE = None return QGIS_APP, CANVAS, IFACE, PARENT
def testExportToFileWithModel(self): QgsApplication.setPrefixPath("/usr/share/qgis", True) qgs = QgsApplication([], False) # load providers qgs.initQgis() # shapefile aroundtheblockPath = os.path.join(os.path.abspath("../../sampledata/"), "amsterdam-yymmdd.csv") logger = test_MMImport.mockLogger() messageBar = test_MMImport.MockMessageBar(logger) messageBox = test_MMImport.MockMessageBox layer = loadCSVLayer( dateFormat='yyyy/mm/dd', gpsPath=aroundtheblockPath, logger=logger, mainWindow=None, messageBar=messageBar, messageBox=messageBox ) self.assertTrue(layer.isValid()) # reset the flag messageBar.gotSuccess = False fields = test_MMImport.field_indices(layer) # if model data should be included modelTemplate = {'link': None, 'longitude': None, 'latitude': None, 'altitude' : None, 'scale': None} layer.startEditing() layer.beginEditCommand("Rendering Editing") for feature in layer.getFeatures(): attributes = feature.attributes() model = modelTemplate model['link'] = 'files/red_sphereC.dae' model['longitude'] = attributes[fields['x']] model['latitude'] = attributes[fields['y']] model['scale'] = 1 model['altitude'] = attributes[fields['altitude']] layer.changeAttributeValue(feature.id(), fields['model'], str(model)) layer.endEditCommand() loggerPath = "" exportToFile( activeLayer=layer, audioHREF="", audioOffset=0, exportPath="amsterdam-yymmdd-model.kml", fields=fields, lastDirectory=".", logger=logger, loggerPath=loggerPath, messageBar=messageBar ) self.assertTrue(messageBar.gotSuccess)
def init(): a = QgsApplication(sys.argv, True) a.setApplicationName("Teste PyCharm") QgsApplication.setPrefixPath("C:\\PROGRA~2\\QGISWI~1\\apps\\qgis", True) print QgsApplication.showSettings() QgsApplication.initQgis() # providers = QgsProviderRegistry.instance().providerList() # for provider in providers: # print provider return a
def main(): QgsApplication.setPrefixPath('/usr/local', True) QgsApplication.initQgis() layer = QgsVectorLayer("/home/cfarmer/Downloads/qgis_sample_data/vmap0_shapefiles/majrivers.shp", "majrivers", "ogr") provider = layer.dataProvider() if not robjects.r.require('sp')[0]: raise Exception("Error: missing 'sp' package: classes and methods for spatial data") if not robjects.r.require('rgdal')[0]: raise Exception("Error: missing 'rgdal' package: classes and methods for spatial data") output = qOGRVectorDataFrame(layer, True) robjects.r.plot(robjects.r.get("majrivers")) s = raw_input('Waiting for input... (Return)')
def main(argv): # load plugins if os.path.exists(PLUGIN_FILE): imp.load_source('hmtk.plugin', PLUGIN_FILE) # create Qt application # Claim to be QGIS2 so that used plugins that tries to access # QSettings will get the QGIS2 settings QtGui.QApplication.setApplicationName('QGIS2') QtGui.QApplication.setOrganizationDomain('qgis.org') if QtCore.QSettings().value('locale/userLocale') is None: QtGui.QApplication.setOrganizationDomain('QGIS') app = QtGui.QApplication(argv, True) # setup QGIS QgsApplication.setPrefixPath(os.environ['QGIS_PREFIX_PATH'], True) QgsApplication.initQgis() # Install a custom exception hook that prints exception into a # MessageBox sys.excepthook = excepthook # create main window wnd = MainWindow() # classname wnd.show() if sys.platform == "darwin": wnd.raise_() if len(argv) > 1: wnd.change_model(CatalogueModel.from_csv_file(argv[1])) if len(argv) > 2: wnd.load_fault_source(argv[2]) else: wnd.load_catalogue() # Connect signal for app finish def on_quit(): QgsApplication.exitQgis() app.quit() app.lastWindowClosed.connect(on_quit) # Start the app up ret = app.exec_() sys.exit(ret)
def init(self): self.app = QgsApplication(self.sysargv, True) QgsApplication.setPrefixPath(self.prefixpath, True) QgsApplication.initQgis() locale = QLocale.system().name() self.translationFile = os.path.join(self.i18npath, '{0}.qm'.format(locale)) translator = QTranslator() translator.load(self.translationFile, "i18n") self.app.installTranslator(translator) QApplication.setStyle("Plastique") QApplication.setFont(QFont('Segoe UI')) return self
def main(): app = QtGui.QApplication(sys.argv, True) # supply path to where is your qgis installed QgsApplication.setPrefixPath("/usr", True) # load providers QgsApplication.initQgis() # print QgsApplication.showSettings() mw = MainWindow() try: mw.create_layer(DATA) mw.show() app.exec_() finally: QgsApplication.exitQgis()
def get_qgis_app(): """ Start one QGis application to test against Input NIL Output handle to qgis app If QGis is already running the handle to that app will be returned """ global QGIS_APP # pylint: disable=W0603 if QGIS_APP is None: gui_flag = True # All test will run qgis in safe_qgis mode # noinspection PyPep8Naming QGIS_APP = QgsApplication(sys.argv, gui_flag) # Note: This block is not needed for QGIS > 1.8 which will # automatically check the QGIS_PREFIX_PATH var so it is here # for backwards compatibility only if "QGIS_PREFIX_PATH" in os.environ: path = os.environ["QGIS_PREFIX_PATH"] use_default_path_flag = True QGIS_APP.setPrefixPath(path, use_default_path_flag) QGIS_APP.initQgis() s = QGIS_APP.showSettings() LOGGER.debug(s) global PARENT # pylint: disable=W0603 if PARENT is None: # noinspection PyPep8Naming PARENT = QtGui.QWidget() global CANVAS # pylint: disable=W0603 if CANVAS is None: # noinspection PyPep8Naming CANVAS = QgsMapCanvas(PARENT) CANVAS.resize(QtCore.QSize(400, 400)) global IFACE # pylint: disable=W0603 if IFACE is None: # QgisInterface is a stub implementation of the QGIS plugin interface # noinspection PyPep8Naming IFACE = QgisInterface(CANVAS) return QGIS_APP, CANVAS, IFACE, PARENT
def get_qgis_app(): """Start one QGIS application to test against. This method has been copied from PluginBuilder generated code by Gary Sherman: https://github.com/g-sherman/Qgis-Plugin-Builder :returns: Handle to QGIS app, canvas, iface and parent. If there are any errors the tuple members will be returned as None. :rtype: (QgsApplication, CANVAS, IFACE, PARENT) If QGIS is already running the handle to that app will be returned. """ try: from PyQt4 import QtGui, QtCore from qgis.core import QgsApplication from qgis.gui import QgsMapCanvas from qgis_interface import QgisInterface except ImportError: return None, None, None, None global QGIS_APP # pylint: disable=W0603 if QGIS_APP is None: gui_flag = True # All test will run qgis in gui mode #noinspection PyPep8Naming QGIS_APP = QgsApplication(sys.argv, gui_flag) # Make sure QGIS_PREFIX_PATH is set in your env if needed! QGIS_APP.initQgis() s = QGIS_APP.showSettings() LOGGER.debug(s) global PARENT # pylint: disable=W0603 if PARENT is None: #noinspection PyPep8Naming PARENT = QtGui.QWidget() global CANVAS # pylint: disable=W0603 if CANVAS is None: #noinspection PyPep8Naming CANVAS = QgsMapCanvas(PARENT) CANVAS.resize(QtCore.QSize(400, 400)) global IFACE # pylint: disable=W0603 if IFACE is None: # QgisInterface is a stub implementation of the QGIS plugin interface #noinspection PyPep8Naming IFACE = QgisInterface(CANVAS) return QGIS_APP, CANVAS, IFACE, PARENT
def main(): QgsApplication.setPrefixPath('/usr/local', True) QgsApplication.initQgis() layer = QgsVectorLayer('/path/to/layer.shp', 'layer', 'ogr') provider = layer.dataProvider() layer.select(provider.attributeIndexes()) values = [] for feat in layer: values.append(feat.attributeMap()[1].toDouble()[0]) print "Quantile: ", quantile(values, 5) print "Equal Interval: ", equal(values, 5) print "R's Pretty: ", pretty(values, 5) print "Standard Deviation: ", std_dev(values, 5) print "Natural Breaks (Jenks): ", jenks(values, classes=5) print "Sampled Jenks: ", jenks_sample(values, classes=5)
def getQgisTestApp(): """ Start one QGis application to test agaist Input NIL Output handle to qgis app If QGis is already running the handle to that app will be returned """ global QGISAPP # pylint: disable=W0603 if QGISAPP is None: myGuiFlag = True # All test will run qgis in gui mode # In python3 we need to conver to a bytes object (or should # QgsApplication accept a QString instead of const char* ?) try: argvb = list(map(os.fsencode, sys.argv)) except AttributeError: argvb = sys.argv # Note: QGIS_PREFIX_PATH is evaluated in QgsApplication - # no need to mess with it here. QGISAPP = QgsApplication(argvb, myGuiFlag) QGISAPP.initQgis() s = QGISAPP.showSettings() print(s) global PARENT # pylint: disable=W0603 if PARENT is None: PARENT = QWidget() global CANVAS # pylint: disable=W0603 if CANVAS is None: CANVAS = QgsMapCanvas(PARENT) CANVAS.resize(QSize(400, 400)) global IFACE # pylint: disable=W0603 if IFACE is None: # QgisInterface is a stub implementation of the QGIS plugin interface IFACE = QgisInterface(CANVAS) return QGISAPP, CANVAS, IFACE, PARENT
def getQgisTestApp(): """ Start one QGis application to test agaist Input NIL Output handle to qgis app If QGis is already running the handle to that app will be returned """ global QGISAPP if QGISAPP is None: myGuiFlag = True # All test will run qgis in gui mode QGISAPP = QgsApplication(sys.argv, myGuiFlag) if 'QGISPATH' in os.environ: myPath = os.environ['QGISPATH'] myUseDefaultPathFlag = True QGISAPP.setPrefixPath(myPath, myUseDefaultPathFlag) else: print 'Warning: QGISPATH is not set' QGISAPP.initQgis() s = QGISAPP.showSettings() print s global PARENT if PARENT is None: PARENT = QtGui.QWidget() global CANVAS if CANVAS is None: CANVAS = QgsMapCanvas(PARENT) CANVAS.resize(QtCore.QSize(400, 400)) global IFACE if IFACE is None: # QgisInterface is a stub implementation of the QGIS plugin # interface IFACE = QgisInterface(CANVAS) return (QGISAPP, CANVAS, IFACE, PARENT)
def init_qgis(): """Set up a global QGIS instance. :returns: A QGIS application (for global use). :rtype: QgsApplication """ print 'Instantiating QGIS' QCoreApplication.setOrganizationName('InaSAFE') QCoreApplication.setOrganizationDomain('inasafe.org') QCoreApplication.setApplicationName('InaSAFEWeb') #noinspection PyPep8Naming gui_flag = True # app = QApplication([], gui_flag) app = QgsApplication(sys.argv, gui_flag) # Make sure QGIS_PREFIX_PATH is set in your env if needed! app.initQgis() return app
def getQgisTestApp(): """ Start one QGis application to test agaist Input NIL Output handle to qgis app If QGis is already running the handle to that app will be returned """ global QGISAPP # pylint: disable=W0603 if QGISAPP is None: myGuiFlag = True # All test will run qgis in gui mode # Note: QGIS_PREFIX_PATH is evaluated in QgsApplication - # no need to mess with it here. QGISAPP = QgsApplication(sys.argv, myGuiFlag) QGISAPP.initQgis() s = QGISAPP.showSettings() print s global PARENT # pylint: disable=W0603 if PARENT is None: PARENT = QWidget() global CANVAS # pylint: disable=W0603 if CANVAS is None: CANVAS = QgsMapCanvas(PARENT) CANVAS.resize(QSize(400, 400)) global IFACE # pylint: disable=W0603 if IFACE is None: # QgisInterface is a stub implementation of the QGIS plugin interface IFACE = QgisInterface(CANVAS) return QGISAPP, CANVAS, IFACE, PARENT
def setUpClass( self ): self.msg = MessageManager( 'debug', None ) self.msg.show( "Info! SetUp started", 'info', True ) #Initialize QGIS app app = QgsApplication([], True) QgsApplication.setPrefixPath("/usr", True) QgsApplication.initQgis() #Configure QSettings (organization and application name) self.settings = QSettings("GeoTux", "QGIS-Plugin-Test") #Load layer, add field f1, and add layer to Registry baseDir = os.path.dirname( os.path.realpath( __file__ ) ) self.layerPath = os.path.join( baseDir, 'test_data', 'test_points.shp' ) self.layer = QgsVectorLayer( self.layerPath, 'puntos', 'ogr' ) self.layer.dataProvider().addAttributes([QgsField('f1', QVariant.Double)]) self.layer.updateFields() QgsMapLayerRegistry.instance().addMapLayer( self.layer ) #Instantiate AutoFieldManager self.autoFieldManager = AutoFieldManager( self.msg, None, '/AutoFieldsTest', 'GeoTux', 'QGIS-Plugin-Test' )
def main(argv): # create Qt application app = QtGui.QApplication(argv, True) # Set the app style # initialize qgis libraries QgsApplication.setPrefixPath(QGIS_PREFIX_PATH, True) QgsApplication.initQgis() # create main window wnd = MainWindow() wnd.show() # Start the app up retval = app.exec_() # We got an exit signal so time to clean up QgsApplication.exitQgis() sys.exit(retval)
def start_app(): """ Will start a QgsApplication and call all initialization code like registering the providers and other infrastructure. It will not load any plugins. You can always get the reference to a running app by calling `QgsApplication.instance()`. The initialization will only happen once, so it is safe to call this method repeatedly. Returns ------- QgsApplication A QgsApplication singleton """ global QGISAPP try: QGISAPP except NameError: myGuiFlag = True # All test will run qgis in gui mode # In python3 we need to convert to a bytes object (or should # QgsApplication accept a QString instead of const char* ?) try: argvb = list(map(os.fsencode, sys.argv)) except AttributeError: argvb = sys.argv # Note: QGIS_PREFIX_PATH is evaluated in QgsApplication - # no need to mess with it here. QGISAPP = QgsApplication(argvb, myGuiFlag) QGISAPP.initQgis() s = QGISAPP.showSettings() print(s) return QGISAPP
def writeMapbox(cls, iface, feedback, folder, layer_list, visible, cluster, json, getFeatureInfo, params, popup): outputProjectFileName = folder QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) legends = {} mapUnitLayers = [] canvas = iface.mapCanvas() project = QgsProject.instance() mapSettings = canvas.mapSettings() title = project.title() pluginDir = os.path.dirname(os.path.realpath(__file__)) stamp = datetime.now().strftime("%Y_%m_%d-%H_%M_%S_%f") outputProjectFileName = os.path.join(outputProjectFileName, 'qgis2web_' + unicode(stamp)) outputIndex = os.path.join(outputProjectFileName, 'index.html') minify = params["Data export"]["Minify GeoJSON files"] precision = params["Data export"]["Precision"] extent = params["Scale/Zoom"]["Extent"] minZoom = params["Scale/Zoom"]["Min zoom level"] maxZoom = params["Scale/Zoom"]["Max zoom level"] restrictToExtent = params["Scale/Zoom"]["Restrict to extent"] matchCRS = params["Appearance"]["Match project CRS"] addressSearch = params["Appearance"]["Add address search"] locate = params["Appearance"]["Geolocate user"] measure = params["Appearance"]["Measure tool"] highlight = params["Appearance"]["Highlight on hover"] layerSearch = params["Appearance"]["Layer search"] popupsOnHover = params["Appearance"]["Show popups on hover"] template = params["Appearance"]["Template"] widgetAccent = params["Appearance"]["Widget Icon"] widgetBackground = params["Appearance"]["Widget Background"] usedFields = [ALL_ATTRIBUTES] * len(popup) QgsApplication.initQgis() crsSrc = mapSettings.destinationCrs() crs = QgsCoordinateReferenceSystem.EpsgCrsId crsDest = QgsCoordinateReferenceSystem(4326, crs) xform = QgsCoordinateTransform(crsSrc, crsDest, project) dataStore, cssStore = writeFoldersAndFiles(pluginDir, feedback, outputProjectFileName, cluster, measure, matchCRS, layerSearch, canvas, addressSearch, locate) writeCSS(cssStore, mapSettings.backgroundColor().name(), feedback, widgetAccent, widgetBackground) wfsLayers = "" labelCode = "" vtLabels = {} vtStyles = {} useMultiStyle = False useHeat = False useVT = False useShapes = False useOSMB = False useWMS = False useWMTS = False useRaster = False vtSources = [] layers = [ """ { "id": "background", "type": "background", "layout": {}, "paint": { "background-color": "%s" } }""" % mapSettings.backgroundColor().name() ] scaleDependentLayers = "" labelVisibility = "" new_src = "" jsons = "" sources = [] crs = QgsCoordinateReferenceSystem.EpsgCrsId exp_crs = QgsCoordinateReferenceSystem(4326, crs) lyrCount = 0 for layer, jsonEncode, eachPopup, clst in zip(layer_list, json, popup, cluster): rawLayerName = layer.name() safeLayerName = safeName(rawLayerName) + "_" + unicode(lyrCount) vts = layer.customProperty("VectorTilesReader/vector_tile_url") if layer.providerType() != 'WFS' or jsonEncode is True: if layer.type() == QgsMapLayer.VectorLayer and vts is None: feedback.showFeedback('Exporting %s to JSON...' % layer.name()) exportVector(layer, safeLayerName, dataStore, restrictToExtent, iface, extent, precision, exp_crs, minify) jsons += jsonScript(safeLayerName) sources.append(""" "%s": { "type": "geojson", "data": json_%s } """ % (safeLayerName, safeLayerName)) scaleDependentLabels = \ scaleDependentLabelScript(layer, safeLayerName) labelVisibility += scaleDependentLabels feedback.completeStep() elif layer.type() == QgsMapLayer.RasterLayer: if layer.dataProvider().name() != "wms": layersFolder = os.path.join(outputProjectFileName, "data") exportRaster(layer, lyrCount, layersFolder, feedback, iface, matchCRS) rasterPath = './data/' + safeLayerName + '.png' extent = layer.extent() bbox = xform.transformBoundingBox(extent) sources.append(""" "%s": { "type": "image", "url": "%s", "coordinates": [ [%f, %f], [%f, %f], [%f, %f], [%f, %f] ] }""" % (safeLayerName, rasterPath, bbox.xMinimum(), bbox.yMinimum(), bbox.xMaximum(), bbox.yMinimum(), bbox.xMaximum(), bbox.yMaximum(), bbox.xMinimum(), bbox.yMaximum())) else: tileProps = parse_qs(layer.source()) if ('type' in tileProps and tileProps['type'][0] == "xyz"): sources.append(""" "%s": { "type": "raster", "tiles": ["%s"], "tileSize": 256 }""" % (safeLayerName, tileProps['url'][0])) else: url = "%s&%s" % (tileProps['url'][0], layer.source()) sources.append(""" "%s": { "type": "raster", "tiles": ["%s"], "tileSize": 256 }""" % (safeLayerName, url)) lyrCount += 1 popupCode = "" for count, layer in enumerate(layer_list): rawLayerName = layer.name() safeLayerName = safeName(rawLayerName) + "_" + unicode(count) if layer.type() == QgsMapLayer.VectorLayer: (new_src, legends, wfsLayers, labelCode, vtLabels, vtStyles, useMapUnits, useMultiStyle, useHeat, useVT, useShapes, useOSMB, vtSources, layers, popups) = writeVectorLayer( layer, safeLayerName, usedFields[count], highlight, popupsOnHover, popup[count], outputProjectFileName, wfsLayers, cluster[count], visible[count], json[count], legends, new_src, canvas, count, restrictToExtent, extent, feedback, labelCode, vtLabels, vtStyles, useMultiStyle, useHeat, useVT, useShapes, useOSMB, vtSources, layers) popupCode += popups elif layer.type() == QgsMapLayer.RasterLayer: if layer.dataProvider().name() == "wms": feedback.showFeedback('Writing %s as WMS layer...' % layer.name()) layers.append(wmsScript(layer, safeLayerName, count)) feedback.completeStep() else: feedback.showFeedback('Writing %s as raster layer...' % layer.name()) layers.append(rasterScript(layer, safeLayerName, count)) feedback.completeStep() glyphs = ("https://glfonts.lukasmartinelli.ch/fonts/{fontstack}/" "{range}.pbf") s = """ var styleJSON = { "version": 8, "name": "qgis2web export", "pitch": 0, "light": { "intensity": 0.2 }, "sources": {%s}, "sprite": "", "glyphs": "%s", "layers": [%s], }""" % (",".join(vtSources + sources), glyphs, ",".join(layers)) mbStore = os.path.join(outputProjectFileName, 'mapbox') if not os.path.exists(mbStore): shutil.copytree(os.path.join(os.path.dirname(__file__), "mapbox"), mbStore) with codecs.open(os.path.join(mbStore, "style.js"), 'w', encoding='utf-8') as f: f.write(unicode(s)) f.close() pt0 = canvas.center() pt1 = xform.transform(pt0) center = '[' + str(pt1.x()) + ',' center += str(pt1.y()) + ']' center.replace('nan', '0') bearing = 360 - canvas.rotation() zoom = scaleToZoom(canvas.scale()) attribution = ('<a href=' '"https://github.com/tomchadwin/qgis2web" ' 'target="_blank">qgis2web</a> · ' '<a href="https://github.com/mapbox/mapbox-gl-js" ' 'target="_blank">Mapbox GL JS</a> · ' '<a href="https://qgis.org" target="_blank">QGIS</a>') layersList = "" if (params["Appearance"]["Add layers list"] and params["Appearance"]["Add layers list"] != "" and params["Appearance"]["Add layers list"] != "None"): layersList = addLayersList( [], matchCRS, layer_list, cluster, legends, params["Appearance"]["Add layers list"] == "Expanded") new_src = jsons + """ <script src="./mapbox/style.js"></script> <script src="./js/Autolinker.min.js"></script> <script> var map = new mapboxgl.Map({ container: 'map', style: styleJSON, center: %s, zoom: %s, bearing: %s, attributionControl: false }); map.addControl(new mapboxgl.NavigationControl(), 'top-left'); map.addControl(new mapboxgl.AttributionControl({ customAttribution: '%s', compact: false })); var autolinker = new Autolinker({truncate: {length: 30, location: 'smart'}}); %s %s</script>""" % (center, zoom, bearing, attribution, popupCode, layersList) # try: writeHTMLstart(outputIndex, title, cluster, addressSearch, measure, matchCRS, layerSearch, canvas, locate, new_src, template, feedback, useMultiStyle, useHeat, useShapes, useOSMB, useWMS, useWMTS, useVT) # except Exception as e: # QgsMessageLog.logMessage(traceback.format_exc(), "qgis2web", # level=QgsMessageLog.CRITICAL) # QApplication.restoreOverrideCursor() # finally: # QApplication.restoreOverrideCursor() return outputIndex
def writeLeaflet(cls, iface, feedback, folder, layer_list, visible, cluster, json, getFeatureInfo, params, popup): outputProjectFileName = folder QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) legends = {} mapUnitLayers = [] canvas = iface.mapCanvas() project = QgsProject.instance() mapSettings = canvas.mapSettings() title = project.title() pluginDir = os.path.dirname(os.path.realpath(__file__)) stamp = datetime.now().strftime("%Y_%m_%d-%H_%M_%S_%f") outputProjectFileName = os.path.join(outputProjectFileName, 'qgis2web_' + unicode(stamp)) outputIndex = os.path.join(outputProjectFileName, 'index.html') minify = params["Data export"]["Minify GeoJSON files"] precision = params["Data export"]["Precision"] extent = params["Scale/Zoom"]["Extent"] minZoom = params["Scale/Zoom"]["Min zoom level"] maxZoom = params["Scale/Zoom"]["Max zoom level"] restrictToExtent = params["Scale/Zoom"]["Restrict to extent"] matchCRS = params["Appearance"]["Match project CRS"] addressSearch = params["Appearance"]["Add address search"] locate = params["Appearance"]["Geolocate user"] measure = params["Appearance"]["Measure tool"] highlight = params["Appearance"]["Highlight on hover"] layerSearch = params["Appearance"]["Layer search"] popupsOnHover = params["Appearance"]["Show popups on hover"] template = params["Appearance"]["Template"] widgetAccent = params["Appearance"]["Widget Icon"] widgetBackground = params["Appearance"]["Widget Background"] usedFields = [ALL_ATTRIBUTES] * len(popup) QgsApplication.initQgis() dataStore, cssStore = writeFoldersAndFiles(pluginDir, feedback, outputProjectFileName, cluster, measure, matchCRS, layerSearch, canvas, addressSearch, locate) writeCSS(cssStore, mapSettings.backgroundColor().name(), feedback, widgetAccent, widgetBackground) wfsLayers = "" labelCode = "" vtLabels = {} vtStyles = {} useMultiStyle = False useHeat = False useVT = False useShapes = False useOSMB = False useWMS = False useWMTS = False useRaster = False scaleDependentLayers = "" labelVisibility = "" new_src = "" jsons = "" crs = QgsCoordinateReferenceSystem.EpsgCrsId exp_crs = QgsCoordinateReferenceSystem(4326, crs) lyrCount = 0 for layer, jsonEncode, eachPopup, clst in zip(layer_list, json, popup, cluster): rawLayerName = layer.name() safeLayerName = safeName(rawLayerName) + "_" + unicode(lyrCount) vts = layer.customProperty("VectorTilesReader/vector_tile_url") if layer.providerType() != 'WFS' or jsonEncode is True: if layer.type() == QgsMapLayer.VectorLayer and vts is None: feedback.showFeedback('Exporting %s to JSON...' % layer.name()) exportVector(layer, safeLayerName, dataStore, restrictToExtent, iface, extent, precision, exp_crs, minify) jsons += jsonScript(safeLayerName) scaleDependentLabels = \ scaleDependentLabelScript(layer, safeLayerName) labelVisibility += scaleDependentLabels feedback.completeStep() elif layer.type() == QgsMapLayer.RasterLayer: if layer.dataProvider().name() != "wms": layersFolder = os.path.join(outputProjectFileName, "data") exportRaster(layer, lyrCount, layersFolder, feedback, iface, matchCRS) if layer.hasScaleBasedVisibility(): scaleDependentLayers += scaleDependentLayerScript( layer, safeLayerName, clst) lyrCount += 1 if scaleDependentLayers != "": scaleDependentLayers = scaleDependentScript(scaleDependentLayers) crsSrc = mapSettings.destinationCrs() crsAuthId = crsSrc.authid() crsProj4 = crsSrc.toProj4() middle = """ """ if highlight or popupsOnHover: selectionColor = mapSettings.selectionColor().name() middle += highlightScript(highlight, popupsOnHover, selectionColor) if extent == "Canvas extent": pt0 = canvas.extent() crsDest = QgsCoordinateReferenceSystem(4326) try: xform = QgsCoordinateTransform(crsSrc, crsDest, QgsProject.instance()) except: xform = QgsCoordinateTransform(crsSrc, crsDest) pt1 = xform.transformBoundingBox(pt0) bbox_canvas = [ pt1.yMinimum(), pt1.yMaximum(), pt1.xMinimum(), pt1.xMaximum() ] bounds = '[[' + unicode(pt1.yMinimum()) + ',' bounds += unicode(pt1.xMinimum()) + '],[' bounds += unicode(pt1.yMaximum()) + ',' bounds += unicode(pt1.xMaximum()) + ']]' if matchCRS and crsAuthId != 'EPSG:4326': middle += crsScript(crsAuthId, crsProj4) else: bounds = 0 if matchCRS and crsAuthId != 'EPSG:4326': middle += crsScript(crsAuthId, crsProj4) middle += mapScript(extent, matchCRS, crsAuthId, measure, maxZoom, minZoom, bounds, locate) middle += featureGroupsScript() extentCode = extentScript(extent, restrictToExtent) new_src += middle new_src += extentCode for count, layer in enumerate(layer_list): rawLayerName = layer.name() safeLayerName = safeName(rawLayerName) + "_" + unicode(count) if layer.type() == QgsMapLayer.VectorLayer: (new_src, legends, wfsLayers, labelCode, vtLabels, vtStyles, useMapUnits, useMultiStyle, useHeat, useVT, useShapes, useOSMB) = writeVectorLayer( layer, safeLayerName, usedFields[count], highlight, popupsOnHover, popup[count], outputProjectFileName, wfsLayers, cluster[count], visible[count], json[count], legends, new_src, canvas, count, restrictToExtent, extent, feedback, labelCode, vtLabels, vtStyles, useMultiStyle, useHeat, useVT, useShapes, useOSMB) if useMapUnits: mapUnitLayers.append(safeLayerName) elif layer.type() == QgsMapLayer.RasterLayer: if layer.dataProvider().name() == "wms": feedback.showFeedback('Writing %s as WMS layer...' % layer.name()) new_obj, useWMS, useWMTS = wmsScript( layer, safeLayerName, useWMS, useWMTS, getFeatureInfo[count]) feedback.completeStep() else: useRaster = True feedback.showFeedback('Writing %s as raster layer...' % layer.name()) new_obj = rasterScript(layer, safeLayerName) feedback.completeStep() if visible[count]: new_obj += """ map.addLayer(overlay_""" + safeLayerName + """);""" new_src += new_obj the_src = new_src new_src = jsons + """ <script>""" if len(mapUnitLayers) > 0: new_src += """ var m2px = 1; function newM2px() { var centerLatLng = map.getCenter(); var pointC = map.latLngToContainerPoint(centerLatLng); var pointX = [pointC.x + 100, pointC.y]; var latLngC = map.containerPointToLatLng(pointC); var latLngX = map.containerPointToLatLng(pointX); var distanceX = latLngC.distanceTo(latLngX)/100; reciprocal = 1 / distanceX; m2px = reciprocal; } function geoStyle(m) { return Math.ceil(m * m2px); }""" new_src += getVTStyles(vtStyles) new_src += getVTLabels(vtLabels) new_src += the_src + scaleDependentLayers if title != "": titleStart = unicode(titleSubScript(title)) new_src += unicode(titleStart) if addressSearch: address_text = addressSearchScript() new_src += address_text if (params["Appearance"]["Add layers list"] and params["Appearance"]["Add layers list"] != "" and params["Appearance"]["Add layers list"] != "None"): new_src += addLayersList( [], matchCRS, layer_list, cluster, legends, params["Appearance"]["Add layers list"] == "Expanded") if project.readBoolEntry("ScaleBar", "/Enabled", False)[0]: # placement = project.readNumEntry("ScaleBar", "/Placement", 0)[0] # placement = PLACEMENT[placement] # end = scaleBar(placement) end = scaleBar() else: end = '' layerType = "layer" try: if cluster[count]: layerType = "cluster" except: pass searchLayer = "%s_%s" % (layerType, params["Appearance"]["Search layer"]) labelList = [] for count, layer in enumerate(layer_list): vts = layer.customProperty("VectorTilesReader/vector_tile_url") safeLayerName = re.sub(r'[\W_]+', '', layer.name()) + "_" + unicode(count) if (layer.type() == QgsMapLayer.VectorLayer and vts is None): labelling = layer.labeling() if labelling is not None: palyr = labelling.settings() if palyr.fieldName and palyr.fieldName != "": labelList.append("layer_%s" % safeLayerName) labelsList = ",".join(labelList) end += endHTMLscript(wfsLayers, layerSearch, labelCode, labelVisibility, searchLayer, useHeat, useRaster, labelsList, mapUnitLayers) new_src += end try: writeHTMLstart(outputIndex, title, cluster, addressSearch, measure, matchCRS, layerSearch, canvas, locate, new_src, template, feedback, useMultiStyle, useHeat, useShapes, useOSMB, useWMS, useWMTS, useVT) except Exception as e: QgsMessageLog.logMessage(traceback.format_exc(), "qgis2web", level=QgsMessageLog.CRITICAL) QApplication.restoreOverrideCursor() finally: QApplication.restoreOverrideCursor() return outputIndex
class TestStratigraphy(utils_for_tests.MidvattenTestSpatialiteDbSv): @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def create_and_select_vlayer(self): self.qgs = QgsApplication([], True) self.qgs.initQgis() self.midvatten.ms.settingsdict['secplotdrillstop'] = "%berg%" dbconnection = db_utils.DbConnectionManager() uri = dbconnection.uri uri.setDataSource('', 'obs_points', 'geometry', '', 'rowid') dbtype = db_utils.get_dbtype(dbconnection.dbtype) self.vlayer = QgsVectorLayer(uri.uri(), 'TestLayer', dbtype) features = self.vlayer.getFeatures() feature_ids = [feature.id() for feature in features] self.vlayer.selectByIds(feature_ids) print("1. Valid vlayer '{}'".format(self.vlayer.isValid())) print("2. feature_ids: " + str(feature_ids)) print("3. QgsVectorLayer.selectedFeatureIds: " + str(self.vlayer.selectedFeatureIds())) print("4. QgsVectorLayer.getSelectedFeatures: " + str([x.id() for x in self.vlayer.getSelectedFeatures()])) print("5. QgsVectorLayer.getFeature(): " + str([self.vlayer.getFeature(x).id() for x in feature_ids])) print("6. QgsVectorLayer.getFeature() type: " + str([str(type(self.vlayer.getFeature(x))) for x in feature_ids])) print("7. QgsVectorLayer.getFeatures(): " + str([x.id() for x in self.vlayer.getFeatures(feature_ids)])) @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def test_stratigraphy(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('1', 5, ST_GeomFromText('POINT(633466 711659)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('2', 10, ST_GeomFromText('POINT(6720727 016568)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('3', 20, ST_GeomFromText('POINT(6720728 016569)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('1', 1, 0, 1, 'sand', 'sand', '3', 'j')''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('1', 2, 1, 4.5, 'morän', 'morän', '3', 'j')''' ) self.create_and_select_vlayer() dlg = Stratigraphy(self.iface, self.vlayer, self.ms.settingsdict) dlg.showSurvey() print(str(mock_skippopup.mock_calls)) test = utils.anything_to_string_representation(dlg.data) test_survey = utils.anything_to_string_representation( repr(dlg.data['1'])) test_strata = utils.anything_to_string_representation( utils.returnunicode(dlg.data['1'].strata, keep_containers=True)) assert len(mock_skippopup.mock_calls) == 0 assert len(mock_messagebar.mock_calls) == 0 assert test == """{"1": SURVEY('1', 5.000000, '<QgsPointXY: POINT(633466 711659)>')}""" assert test_survey == '''"SURVEY('1', 5.000000, '<QgsPointXY: POINT(633466 711659)>')"''' print("Test strata " + test_strata) assert test_strata == '''["strata(1, '3', 'sand', 'sand', 0.000000-1.000000)", "strata(2, '3', 'morän', 'moran', 1.000000-4.500000)"]''' @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def test_stratigraphy_with_other_obsid_numbers(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('8', 5, ST_GeomFromText('POINT(633466 711659)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('9', 10, ST_GeomFromText('POINT(6720727 016568)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('10', 20, ST_GeomFromText('POINT(6720728 016569)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('8', 1, 0, 1, 'sand', 'sand', '3', 'j')''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('8', 2, 1, 4.5, 'morän', 'morän', '3', 'j')''' ) self.create_and_select_vlayer() dlg = Stratigraphy(self.iface, self.vlayer, self.ms.settingsdict) dlg.showSurvey() print(str(mock_skippopup.mock_calls)) test = utils.anything_to_string_representation(dlg.data) test_survey = utils.anything_to_string_representation( repr(dlg.data['8'])) test_strata = utils.anything_to_string_representation( utils.returnunicode(dlg.data['8'].strata, keep_containers=True)) assert len(mock_skippopup.mock_calls) == 0 assert len(mock_messagebar.mock_calls) == 0 assert test == """{"8": SURVEY('8', 5.000000, '<QgsPointXY: POINT(633466 711659)>')}""" assert test_survey == '''"SURVEY('8', 5.000000, '<QgsPointXY: POINT(633466 711659)>')"''' print("Test strata " + test_strata) assert test_strata == '''["strata(1, '3', 'sand', 'sand', 0.000000-1.000000)", "strata(2, '3', 'morän', 'moran', 1.000000-4.500000)"]''' @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def test_stratigraphy_with_string_obsid(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('P1', 5, ST_GeomFromText('POINT(633466 711659)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('P2', 10, ST_GeomFromText('POINT(6720727 016568)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('P3', 20, ST_GeomFromText('POINT(6720728 016569)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('P1', 1, 0, 1, 'sand', 'sand', '3', 'j')''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('P1', 2, 1, 4.5, 'morän', 'morän', '3', 'j')''' ) self.create_and_select_vlayer() dlg = Stratigraphy(self.iface, self.vlayer, self.ms.settingsdict) dlg.showSurvey() print(str(mock_skippopup.mock_calls)) test = utils.anything_to_string_representation(dlg.data) test_survey = utils.anything_to_string_representation( repr(dlg.data['P1'])) test_strata = utils.anything_to_string_representation( utils.returnunicode(dlg.data['P1'].strata, keep_containers=True)) assert len(mock_skippopup.mock_calls) == 0 assert len(mock_messagebar.mock_calls) == 0 assert test == """{"P1": SURVEY('P1', 5.000000, '<QgsPointXY: POINT(633466 711659)>')}""" assert test_survey == '''"SURVEY('P1', 5.000000, '<QgsPointXY: POINT(633466 711659)>')"''' print("Test strata " + test_strata) assert test_strata == '''["strata(1, '3', 'sand', 'sand', 0.000000-1.000000)", "strata(2, '3', 'morän', 'moran', 1.000000-4.500000)"]''' @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def test_stratigraphy_gap(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('1', 5, ST_GeomFromText('POINT(633466 711659)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('2', 10, ST_GeomFromText('POINT(6720727 016568)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('3', 20, ST_GeomFromText('POINT(6720728 016569)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('1', 1, 0, 1, 'sand', 'sand', '3', 'j')''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('1', 2, 2, 4.5, 'morän', 'morän', '3', 'j')''' ) self.create_and_select_vlayer() dlg = Stratigraphy(self.iface, self.vlayer, self.ms.settingsdict) dlg.showSurvey() test = utils.anything_to_string_representation(dlg.data) test_survey = utils.anything_to_string_representation( repr(dlg.data['1'])) test_strata = utils.anything_to_string_representation( utils.returnunicode(dlg.data['1'].strata, keep_containers=True)) assert len(mock_skippopup.mock_calls) == 0 assert len(mock_messagebar.mock_calls) == 0 assert test == """{"1": SURVEY('1', 5.000000, '<QgsPointXY: POINT(633466 711659)>')}""" assert test_survey == '''"SURVEY('1', 5.000000, '<QgsPointXY: POINT(633466 711659)>')"''' print("Test strata " + test_strata) assert test_strata == '''["strata(1, '3', 'sand', 'sand', 0.000000-1.000000)", "strata(2, '', '', '', 1.000000-2.000000)", "strata(3, '3', 'morän', 'moran', 2.000000-4.500000)"]''' @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def test_stratigraphy_missing_h_gs_use_h_toc(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('1', 5, ST_GeomFromText('POINT(633466 711659)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, h_gs, h_toc, geometry) VALUES ('2', NULL, 10, ST_GeomFromText('POINT(6720727 016568)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid, geometry) VALUES ('3', ST_GeomFromText('POINT(6720728 016569)', 3006))''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('1', 1, 0, 1, 'sand', 'sand', '3', 'j')''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('1', 2, 1, 4.5, 'morän', 'morän', '3', 'j')''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('2', 1, 0, 1, 'sand', 'sand', '3', 'j')''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('2', 2, 1, 4.5, 'morän', 'morän', '3', 'j')''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('3', 1, 0, 2, 'sand', 'sand', '3', 'j')''' ) db_utils.sql_alter_db( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geology, geoshort, capacity, development) VALUES ('3', 2, 2, 6, 'morän', 'morän', '3', 'j')''' ) self.create_and_select_vlayer() dlg = Stratigraphy(self.iface, self.vlayer, self.ms.settingsdict) dlg.showSurvey() test = utils.anything_to_string_representation(dlg.data) test_survey = utils.anything_to_string_representation( repr(dlg.data['1'])) test_strata = utils.anything_to_string_representation( utils.returnunicode(dlg.data['1'].strata, keep_containers=True)) assert len(mock_skippopup.mock_calls) == 1 print(str(mock_skippopup.mock_calls)) print(str(mock_messagebar.mock_calls)) assert mock_skippopup.mock_calls == [ mock.call('Warning, h_gs is missing. See messagebar.') ] assert mock_messagebar.mock_calls == [ mock.call.warning( bar_msg="Obsid 2: using h_gs '' failed, using 'h_toc' instead.", duration=90, log_msg='False'), mock.call.warning( bar_msg="Obsid 3: using h_gs '' failed, using '-1' instead.", duration=90, log_msg='False') ] print(test) assert test == """{"1": SURVEY('1', 5.000000, '<QgsPointXY: POINT(633466 711659)>'), "2": SURVEY('2', 10.000000, '<QgsPointXY: POINT(6720727 16568)>'), "3": SURVEY('3', -1.000000, '<QgsPointXY: POINT(6720728 16569)>')}""" print("test_survey " + test_survey) assert test_survey == '''"SURVEY('1', 5.000000, '<QgsPointXY: POINT(633466 711659)>')"''' print("Test strata " + test_strata) assert test_strata == '''["strata(1, '3', 'sand', 'sand', 0.000000-1.000000)", "strata(2, '3', 'morän', 'moran', 1.000000-4.500000)"]''' def tearDown(self): QgsProject.instance().addMapLayer(self.vlayer) QgsProject.instance().removeMapLayer(self.vlayer.id()) super(self.__class__, self).tearDown()
class TestVectorlayer(utils_for_tests.MidvattenTestSpatialiteDbSv): @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def create_vlayer(self, no_print=False): self.qgs = QgsApplication([], True) self.qgs.initQgis() dbconnection = db_utils.DbConnectionManager() uri = dbconnection.uri uri.setDataSource('', 'obs_points', 'geometry', '', 'obsid') dbtype = db_utils.get_dbtype(dbconnection.dbtype) self.vlayer = QgsVectorLayer(uri.uri(), 'TestLayer', dbtype) features = self.vlayer.getFeatures() feature_ids = [feature.id() for feature in features] if not no_print: print("1. Valid vlayer '{}'".format(self.vlayer.isValid())) print("2. feature_ids: " + str(feature_ids)) print("5. QgsVectorLayer.getFeature(): " + str([self.vlayer.getFeature(x).id() for x in feature_ids])) print("6. QgsVectorLayer.getFeature() type: " + str( [str(type(self.vlayer.getFeature(x))) for x in feature_ids])) print("7. QgsVectorLayer.getFeatures(): " + str([x.id() for x in self.vlayer.getFeatures(feature_ids)])) print("8. QgsVectorLayer.featureCount(): " + str(self.vlayer.featureCount())) def select_features(self, feature_ids=None, no_print=True): if feature_ids is None: features = self.vlayer.getFeatures() feature_ids = [feature.id() for feature in features] self.vlayer.selectByIds(feature_ids) if not no_print: print("3. QgsVectorLayer.selectedFeatureIds: " + str(self.vlayer.selectedFeatureIds())) print("4. QgsVectorLayer.getSelectedFeatures: " + str([x.id() for x in self.vlayer.getSelectedFeatures()])) @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def test_vlayer(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ for obsid in [1, 2, 3]: db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid) VALUES ({})'''.format( str(obsid))) self.create_vlayer() self.select_features() feature_ids = [feature.id() for feature in self.vlayer.getFeatures()] reference_ids = (1, 2, 3) assert self.vlayer.isValid() assert len(feature_ids) == len(reference_ids) assert tuple(feature_ids) == reference_ids assert tuple(sorted([x for x in self.vlayer.selectedFeatureIds() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getSelectedFeatures() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getFeatures(feature_ids) ])) == reference_ids assert self.vlayer.featureCount() == 3 @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def test_vlayer_other_ints_ids(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ for obsid in [4, 5, 6]: db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid) VALUES ({})'''.format( str(obsid))) self.create_vlayer() self.select_features() feature_ids = [feature.id() for feature in self.vlayer.getFeatures()] reference_ids = (1, 2, 3) assert self.vlayer.isValid() assert len(feature_ids) == len(reference_ids) assert tuple(feature_ids) == reference_ids assert tuple(sorted([x for x in self.vlayer.selectedFeatureIds() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getSelectedFeatures() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getFeatures(feature_ids) ])) == reference_ids assert self.vlayer.featureCount() == 3 @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def test_vlayer_strings(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ for obsid in ['A', 'b', 'c1']: db_utils.sql_alter_db( '''INSERT INTO obs_points (obsid) VALUES ('{}')'''.format( str(obsid))) self.create_vlayer() self.select_features() feature_ids = [feature.id() for feature in self.vlayer.getFeatures()] reference_ids = (1, 2, 3) assert self.vlayer.isValid() assert len(feature_ids) == len(reference_ids) assert tuple(feature_ids) == reference_ids assert tuple(sorted([x for x in self.vlayer.selectedFeatureIds() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getSelectedFeatures() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getFeatures(feature_ids) ])) == reference_ids assert self.vlayer.featureCount() == 3 @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def test_vlayer_1000_features(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ dbconnection = db_utils.DbConnectionManager() cur = dbconnection.cursor cur.execute('''BEGIN TRANSACTION;''') for obsid in range(1000): cur.execute( '''INSERT INTO obs_points (obsid) VALUES ('{}');'''.format( str(obsid))) cur.execute('''END TRANSACTION;''') self.create_vlayer(no_print=True) self.select_features(no_print=True) feature_ids = [feature.id() for feature in self.vlayer.getFeatures()] reference_ids = tuple(range(1, 1001)) print("First 10 ids: " + str(feature_ids[:10])) print("Last 10 ids: " + str(feature_ids[-10:])) print("First 10 reference_ids: " + str(reference_ids[:10])) print("Last 10 reference_ids: " + str(reference_ids[-10:])) assert self.vlayer.isValid() assert len(feature_ids) == len(reference_ids) assert tuple(feature_ids) == reference_ids assert tuple(sorted([x for x in self.vlayer.selectedFeatureIds() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getSelectedFeatures() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getFeatures(feature_ids) ])) == reference_ids assert self.vlayer.featureCount() == len(reference_ids) @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def test_vlayer_2000_ints(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ dbconnection = db_utils.DbConnectionManager() cur = dbconnection.cursor cur.execute('''BEGIN TRANSACTION;''') for obsid in range(2000): cur.execute( '''INSERT INTO obs_points (obsid) VALUES ('{}');'''.format( str(obsid))) cur.execute('''END TRANSACTION;''') self.create_vlayer(no_print=True) self.select_features(no_print=True) feature_ids = [feature.id() for feature in self.vlayer.getFeatures()] reference_ids = tuple(range(1, 2001)) print("First 10 ids: " + str(feature_ids[:10])) print("Last 10 ids: " + str(feature_ids[-10:])) print("First 10 reference_ids: " + str(reference_ids[:10])) print("Last 10 reference_ids: " + str(reference_ids[-10:])) assert self.vlayer.isValid() assert len(feature_ids) == len(reference_ids) assert tuple(feature_ids) == reference_ids assert tuple(sorted([x for x in self.vlayer.selectedFeatureIds() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getSelectedFeatures() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getFeatures(feature_ids) ])) == reference_ids assert self.vlayer.featureCount() == len(reference_ids) @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('stratigraphy.utils.pop_up_info', autospec=True) @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def test_vlayer_2000_strings(self, mock_skippopup, mock_messagebar): """ :param mock_skippopup: :param mock_messagebar: :return: """ dbconnection = db_utils.DbConnectionManager() cur = dbconnection.cursor obsids = [ letter + str(_int) for letter in string.ascii_letters for _int in range(80) ] cur.execute('''BEGIN TRANSACTION;''') for obsid in obsids: cur.execute( '''INSERT INTO obs_points (obsid) VALUES ('{}');'''.format( str(obsid))) cur.execute('''END TRANSACTION;''') dbconnection.commit() self.create_vlayer(no_print=True) self.select_features(no_print=True) feature_ids = [feature.id() for feature in self.vlayer.getFeatures()] reference_ids = tuple(range(1, len(obsids) + 1)) print("First 10 ids: " + str(feature_ids[:10])) print("Last 10 ids: " + str(feature_ids[-10:])) print("First 10 reference_ids: " + str(reference_ids[:10])) print("Last 10 reference_ids: " + str(reference_ids[-10:])) print(str(self.vlayer.featureCount())) assert self.vlayer.isValid() assert len(feature_ids) == len(reference_ids) assert tuple(feature_ids) == reference_ids assert tuple(sorted([x for x in self.vlayer.selectedFeatureIds() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getSelectedFeatures() ])) == reference_ids assert tuple( sorted([x.id() for x in self.vlayer.getFeatures(feature_ids) ])) == reference_ids assert self.vlayer.featureCount() == len(reference_ids) def tearDown(self): QgsProject.instance().addMapLayer(self.vlayer) QgsProject.instance().removeMapLayer(self.vlayer.id()) super(self.__class__, self).tearDown()
def qgs_init(pp): """ PyQGIS initialization. """ QgsApplication.setPrefixPath(pp, True) qgs = QgsApplication([], False) qgs.initQgis() return qgs
def get_qgis_app(cleanup=True): """ Start one QGIS application to test against. :returns: Handle to QGIS app, canvas, iface and parent. If there are any errors the tuple members will be returned as None. :rtype: (QgsApplication, CANVAS, IFACE, PARENT) If QGIS is already running the handle to that app will be returned. """ global QGIS_APP, PARENT, IFACE, CANVAS # pylint: disable=W0603 if iface: from qgis.core import QgsApplication QGIS_APP = QgsApplication CANVAS = iface.mapCanvas() PARENT = iface.mainWindow() IFACE = iface return QGIS_APP, CANVAS, IFACE, PARENT from qgis.core import QgsApplication from qgis.gui import QgsMapCanvas from qgis.PyQt.QtCore import QSize from qgis.PyQt.QtWidgets import QWidget from .qgis_interface import QgisInterface global QGISAPP # pylint: disable=global-variable-undefined try: QGISAPP except NameError: myGuiFlag = True # All test will run qgis in gui mode # In python3 we need to convert to a bytes object (or should # QgsApplication accept a QString instead of const char* ?) try: argvb = list(map(os.fsencode, sys.argv)) except AttributeError: argvb = sys.argv # Note: QGIS_PREFIX_PATH is evaluated in QgsApplication - # no need to mess with it here. QGISAPP = QgsApplication(argvb, myGuiFlag) QGISAPP.initQgis() s = QGISAPP.showSettings() LOGGER.debug(s) def debug_log_message(message, tag, level): """ Prints a debug message to a log :param message: message to print :param tag: log tag :param level: log message level (severity) :return: """ print('{}({}): {}'.format(tag, level, message)) QgsApplication.instance().messageLog().messageReceived.connect( debug_log_message) if cleanup: import atexit @atexit.register def exitQgis(): # pylint: disable=unused-variable """ Gracefully closes the QgsApplication instance """ try: QGISAPP.exitQgis() # pylint: disable=used-before-assignment QGISAPP = None # pylint: disable=redefined-outer-name except NameError: pass if PARENT is None: # noinspection PyPep8Naming PARENT = QWidget() if CANVAS is None: # noinspection PyPep8Naming CANVAS = QgsMapCanvas(PARENT) CANVAS.resize(QSize(400, 400)) if IFACE is None: # QgisInterface is a stub implementation of the QGIS plugin interface # noinspection PyPep8Naming IFACE = QgisInterface(CANVAS) return QGISAPP, CANVAS, IFACE, PARENT
def main(): """reads in a pre-processed groundwater layer, with recharge-discharge (CSV) and returns tif Args: state(str): state for which well elevations must be obtained season(str): e.g. rech-96, disc-96 Returns: None: well elevations with locations stored in CSV as SHP """ state = sys.argv[1] season = sys.argv[2] dataPath = root.joinpath("data","groundwater") metaPath = root.joinpath("outputs","groundwater","csv",state+"_metadata.log") outputsPath = root.joinpath("outputs","groundwater") logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', handlers=[logging.FileHandler(str(metaPath))], ) logging.info("get Recharge-Discharge for '%s' dataset",state) # Initialize QGIS Application QgsApplication.setPrefixPath("G:\\Users\\Craig\\miniconda3\\envs\\geo_env\\Library\\python\\qgis", True) qgs = QgsApplication([], False) qgs.initQgis() # Append the path where QGIS processing plugin can be found sys.path.append('G:\\Users\\Craig\\miniconda3\\envs\\geo_env\\Library\\python\\plugins') import processing from processing.core.Processing import Processing Processing.initialize() feedback = QgsProcessingFeedback() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) # Get file with recharge-discharge values from previous step vectorPath = outputsPath.joinpath("shapefiles",state+"_processed_wRD.shp") print(vectorPath,vectorPath.exists()) vLayer = QgsVectorLayer(str(vectorPath), 'well_rech_disc_layer', 'ogr') #.setSubsetString(season + " IS NOT NULL") print("islayer valid:", vLayer.isValid()) # subset layer for the chosen season and choose only non null values filter = "\"" + season + "\"" + " IS NOT NULL" expr = QgsExpression(filter) subset = vLayer.getFeatures(QgsFeatureRequest(expr)) vLayer.selectByIds([k.id() for k in subset]) # why didn't direct selection work? addFeature (false) print(vLayer.selectedFeatureCount()) # write subsetted layer to shapefile subsetPath = outputsPath.joinpath("shapefiles","noNulls",state+"_"+season+"_noNulls.shp") _writer = QgsVectorFileWriter.writeAsVectorFormat(vLayer, str(subsetPath), "utf-8", vLayer.crs(), "ESRI Shapefile", onlySelected=True) # import subsetted layer subLayer = QgsVectorLayer(str(subsetPath), 'well_rech_disc_layer_nonulls', 'ogr') print("is sub layer valid:", subLayer.isValid()) # declare params for grid layer # https://gdal.org/tutorials/gdal_grid_tut.html params = { 'INPUT':subLayer, 'POWER':2, # FOR gridinversedistance # 'RADIUS':0.25, # FOR gridinversedistancenearestneighbor / gridlinear # 'RADIUS_1':0.25, # FOR gridinversedistance / gridnearestneighbor / gridaverage # 'RADIUS_2':0.25, # FOR gridinversedistance / gridnearestneighbor / gridaverage 'MAX_POINTS':12, # FOR gridinversedistance 'MIN_POINTS':1, # FOR gridinversedistance / gridaverage 'NODATA': -9999, 'Z_FIELD':season, 'OUTPUT':str(outputsPath.joinpath("tif","idw",state+"_"+season+"_grid_id_min_1_max_12_nonulls.tif")) } res = processing.run("gdal:gridinversedistance",params,feedback=feedback) print(res['OUTPUT'])
def init_test(): QgsApplication.setPrefixPath(r'/usr', True) app = QgsApplication.initQgis() QtCore.QCoreApplication.setOrganizationName('QGIS') QtCore.QCoreApplication.setApplicationName('QGIS2') return app
import os from shutil import copyfile from sys import platform import psycopg2 import qgis.utils from qgis.core import QgsApplication from ..config.refactor_fields_mappings import get_refactor_fields_mapping from ..config.table_mapping_config import BOUNDARY_POINT_TABLE from asistente_ladm_col.asistente_ladm_col_plugin import AsistenteLADMCOLPlugin QgsApplication.setPrefixPath('/usr', True) qgs = QgsApplication([], False) qgs.initQgis() import processing from processing.core.Processing import Processing Processing.initialize() # get from https://github.com/qgis/QGIS/blob/master/tests/src/python/test_qgssymbolexpressionvariables.py from qgis.testing.mocked import get_iface from .config.test_config import TEST_SCHEMAS_MAPPING # PostgreSQL connection to schema with a LADM_COL model from ./etl_script_uaecd.py DB_HOSTNAME = "postgres" DB_PORT = "5432" DB_NAME = "ladm_col" DB_USER = "******"
def testInit(self): """ Test calling QgsApplication.initQgis() without QgsApplication instance """ QgsApplication.initQgis()
def start_app(cleanup=True): """ Will start a QgsApplication and call all initialization code like registering the providers and other infrastructure. It will not load any plugins. You can always get the reference to a running app by calling `QgsApplication.instance()`. The initialization will only happen once, so it is safe to call this method repeatedly. Parameters ---------- cleanup: Do cleanup on exit. Defaults to true. Returns ------- QgsApplication A QgsApplication singleton """ global QGISAPP try: QGISAPP except NameError: myGuiFlag = True # All test will run qgis in gui mode try: sys.argv except: sys.argv = [''] # In python3 we need to convert to a bytes object (or should # QgsApplication accept a QString instead of const char* ?) try: argvb = list(map(os.fsencode, sys.argv)) except AttributeError: argvb = sys.argv # Note: QGIS_PREFIX_PATH is evaluated in QgsApplication - # no need to mess with it here. QGISAPP = QgsApplication(argvb, myGuiFlag) os.environ['QGIS_CUSTOM_CONFIG_PATH'] = tempfile.mkdtemp( '', 'QGIS-PythonTestConfigPath') QGISAPP.initQgis() print(QGISAPP.showSettings()) def debug_log_message(message, tag, level): print('{}({}): {}'.format(tag, level, message)) QgsApplication.instance().messageLog().messageReceived.connect( debug_log_message) if cleanup: import atexit @atexit.register def exitQgis(): QGISAPP.exitQgis() return QGISAPP
def get_qgis_app(): """ Start one QGIS application to test against. :returns: Handle to QGIS app, canvas, iface and parent. If there are any errors the tuple members will be returned as None. :rtype: (QgsApplication, CANVAS, IFACE, PARENT) If QGIS is already running the handle to that app will be returned. """ global QGIS_APP, PARENT, IFACE, CANVAS # pylint: disable=W0603 if iface: from qgis.core import QgsApplication QGIS_APP = QgsApplication CANVAS = iface.mapCanvas() PARENT = iface.mainWindow() IFACE = iface return QGIS_APP, CANVAS, IFACE, PARENT try: from qgis.core import QgsApplication from qgis.gui import QgsMapCanvas # pylint: disable=no-name-in-module # noinspection PyPackageRequirements from PyQt4 import QtGui, QtCore # pylint: disable=W0621 # noinspection PyPackageRequirements from PyQt4.QtCore import QCoreApplication, QSettings from safe.test.qgis_interface import QgisInterface except ImportError: return None, None, None, None if QGIS_APP is None: gui_flag = True # All test will run qgis in gui mode # AG: For testing purposes, we use our own configuration file instead # of using the QGIS apps conf of the host # noinspection PyCallByClass,PyArgumentList QCoreApplication.setOrganizationName('QGIS') # noinspection PyCallByClass,PyArgumentList QCoreApplication.setOrganizationDomain('qgis.org') # noinspection PyCallByClass,PyArgumentList QCoreApplication.setApplicationName('QGIS2InaSAFETesting') # noinspection PyPep8Naming if 'argv' in dir(sys): QGIS_APP = QgsApplication(sys.argv, gui_flag) else: QGIS_APP = QgsApplication([], gui_flag) # Make sure QGIS_PREFIX_PATH is set in your env if needed! QGIS_APP.initQgis() s = QGIS_APP.showSettings() LOGGER.debug(s) # Save some settings settings = QSettings() settings.setValue('locale/overrideFlag', True) settings.setValue('locale/userLocale', 'en_US') # We disabled message bars for now for extent selector as # we don't have a main window to show them in TS - version 3.2 settings.setValue('inasafe/show_extent_confirmations', False) settings.setValue('inasafe/show_extent_warnings', False) settings.setValue('inasafe/showRubberBands', True) settings.setValue('inasafe/analysis_extents_mode', HAZARD_EXPOSURE) if PARENT is None: # noinspection PyPep8Naming PARENT = QtGui.QWidget() if CANVAS is None: # noinspection PyPep8Naming CANVAS = QgsMapCanvas(PARENT) CANVAS.resize(QtCore.QSize(400, 400)) if IFACE is None: # QgisInterface is a stub implementation of the QGIS plugin interface # noinspection PyPep8Naming IFACE = QgisInterface(CANVAS) return QGIS_APP, CANVAS, IFACE, PARENT
sub_algo = [ each for each in os.listdir("description") if "-" in each and ".xml" in each ] for key in sub_algo: shutil.copy("description/doc/%s" % key.split("-")[0] + ".html", "description/doc/%s" % key.split(".")[0] + ".html") if __name__ == "__main__": # Prepare the environment from qgis.core import QgsApplication app = QgsApplication([], True) QgsApplication.initQgis() # Prepare processing framework from processing.core.Processing import Processing Processing.initialize() import OTBSpecific_XMLcreation # try: # import processing # except ImportError, e: # raise Exception("Processing must be installed and available in PYTHONPATH") try: import otbApplication except ImportError as e: raise Exception(
# make the output file name _,ext = os.path.splitext(file) # extension of current file basefile,_ = os.path.splitext(intersect_name) # name of the intersection file w/o extension newfile = basefile + ext # new name + old extension # copy copyfile(catchment_path/file, intersect_path/newfile); # --- QGIS analysis # Initialize QGIS os.environ["QT_QPA_PLATFORM"] = "offscreen" # disable QT trying to connect to display; needed on HPC infrastructure qgis_path = which('qgis') # find the QGIS install location QgsApplication.setPrefixPath(qgis_path, True) # supply path to qgis install location qgs = QgsApplication([], False) # create a reference to the QgsApplication, GUI = False qgs.initQgis() # load providers # Convert Path() to string for QGIS catchment_file = str(intersect_path/intersect_name) # needs to be the copied file because output is automatically added to this dem_file = str(dem_path/dem_name) # Load the shape and raster layer_polygon = QgsVectorLayer(catchment_file,'merit_hydro_basin','ogr') layer_raster = QgsRasterLayer(dem_file,'merit_hydro_dem') # Check we loaded the layers correctly if not layer_raster.isValid(): print('Raster layer failed to load') if not layer_polygon.isValid(): print('Polygon layer failed to load')
self.mapCanvas.refresh() # self.set_crs() def set_crs(self): self.moveThread = MoveThread(self) self.moveThread.degreeSignal.connect(self.process_signal) self.moveThread.start() def process_signal(self, d): print(d) crsDest = QgsCoordinateReferenceSystem( f"PROJ:+proj=ortho +lat_0=0 +lon_0={d} +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs" ) self.mapCanvas.setDestinationCrs(crsDest) self.mapCanvas.refresh() if __name__ == '__main__': qgsAPP = QgsApplication([], True) QgsApplication.setPrefixPath("qgis", True) qgsAPP.initQgis() myApp = MyApp() myApp.show() qgsAPP.exec_() qgsAPP.exitQgis()
def start_qgis_application(enable_gui: bool = False, enable_processing: bool = False, verbose: bool = False, cleanup: bool = True, logger: logging.Logger = None, logprefix: str = 'Qgis:') -> 'QgsApplication': """ Start qgis application :param boolean enable_gui: Enable graphical interface, default to False :param boolean enable_processing: Enable processing, default to False :param boolean verbose: Output qgis settings, default to False :param boolean cleanup: Register atexit hook to close qgisapplication on exit(). Note that prevents qgis to segfault when exiting. Default to True. """ os.environ['QGIS_NO_OVERRIDE_IMPORT'] = '1' os.environ['QGIS_DISABLE_MESSAGE_HOOKS'] = '1' logger = logger or logging.getLogger() setup_qgis_paths() from qgis.core import Qgis, QgsApplication logger.info("Starting Qgis application: %s", Qgis.QGIS_VERSION) if QgsApplication.QGIS_APPLICATION_NAME != "QGIS3": raise RuntimeError("You need QGIS3 (found %s)" % QgsApplication.QGIS_APPLICATION_NAME) if not enable_gui: # We MUST set the QT_QPA_PLATFORM to prevent # Qt trying to connect to display in containers if os.environ.get('DISPLAY') is None: logger.info("Setting offscreen mode") os.environ['QT_QPA_PLATFORM'] = 'offscreen' qgis_prefix = os.environ.get('QGIS3_HOME', '/usr') # XXX Set QGIS_PREFIX_PATH, it seems that setPrefixPath # does not do the job correctly os.environ['QGIS_PREFIX_PATH'] = qgis_prefix global qgis_application qgis_application = QgsApplication([], enable_gui) qgis_application.setPrefixPath(qgis_prefix, True) qgis_application.initQgis() if cleanup: # Closing QgsApplication on exit will # prevent our app to segfault on exit() import atexit logger.info("%s Installing cleanup hook" % logprefix) @atexit.register def exitQgis(): global qgis_application if qgis_application: qgis_application.exitQgis() del qgis_application if verbose: print(qgis_application.showSettings()) # Install logger hook install_logger_hook(logger, logprefix, verbose=verbose) logger.info("%s Qgis application initialized......" % logprefix) if enable_processing: init_processing() logger.info("%s QGis processing initialized" % logprefix) return qgis_application
def main(user='', masterpass='', pkidir=''): if not user or not pkidir: print 'Missing parameters for user or pkidir' print ' user: {0}'.format(user) print ' pkidir: {0}'.format(pkidir) sys.exit(1) # Get user's pre-defined QGIS master password. # This can be done in a variety of ways, depending upon user auth # systems (queried from LDAP, etc.), using a variety of Python packages. # As an example, we could hard-code define it as a standard password that # must be changed later by user, OR if we know the user's defined password. #masterpass = some_user_query_function(user) if not masterpass: print 'Master password must be defined' sys.exit(1) print 'Setting authentication config using:' print ' user: {0}'.format(user) print ' master pass: {0}'.format(masterpass) print ' pkidir: {0}'.format(pkidir) # instantiate QGIS qgsapp = QgsApplication(sys.argv, True) # These are for referencing the correct QSettings for the QGIS app QCoreApplication.setOrganizationName('QGIS') QCoreApplication.setOrganizationDomain('qgis.org') QCoreApplication.setApplicationName('QGIS2') # Initialize QGIS qgsapp.initQgis() print qgsapp.showSettings() # Initialize the auth system # noinspection PyArgumentList authm = QgsAuthManager.instance() authm.init() # This will use the standard qgis-auth.db location, but the rest of this # script will not work if qgis-auth.db already exists and you do NOT know # the user's chosen master password already stored in it. # If you want to generate individual qgis-auth.db for a list of users, just # do: # authdbdir = tempfile.mkdtemp() # authm.init(authdbdir) # Note that the saved paths to PKI components in the db will need to be the # same absolute paths as when the auth db is copied to the user's machine. # This means paths with the current user's name in them will not work when # copied to a different user (unless names are the same). print authm.authenticationDbPath() # Define pool of users and loop through them, or use the current user. #users = ["user"] #for user in users: # Set master password for QGIS and (optionally) store it in qgis-auth.db. # This also verifies the set password against by comparing password # against its derived hash stored in auth db. if not authm.setMasterPassword(masterpass, True): print 'Failed to verify or store/verify password' sys.exit(1) # Now that we have a master password set/stored, we can use it to # encrypt and store authentication configurations. # There are 3 configurations that can be stored (as of Nov 2014), and # examples of their initialization are in the unit tests for # QGIS-with-PKI source tree (test_qgsauthsystem_api-sample.py). # Add authentication configuration. # You can add as many auth configs as needed, but only one can be linked # to a given custom server config; although, you can create as many custom # server configs as needed. In this example, we are defining only one auth # config and linking it to multiple custom server configs, representing # different OWS services located at the same domain. # NOTE: PKI file components need to *already* exist on the filesystem in a # location that doesn't change, as their paths are stored in the auth db. # # Basic configuration # configname = 'My Basic Config' # config = QgsAuthConfigBasic() # config.setName(kind) # config.setUri('https://localhost:8443') # config.setUsername('username') # config.setPassword('password') # will need queried or set per user # config.setRealm('Realm') # ^^ OR vv # # PKI-Paths (PEM-based) configuration # configname = 'My PKI Paths Config' # config = QgsAuthConfigPkiPaths() # config.setName(configname) # config.setUri('https://localhost:8443') # config.setCertId(os.path.join(pkidir, '{0}_cert.pem'.format(user))) # config.setKeyId(os.path.join(pkidir, '{0}_key.pem'.format(user))) # config.setKeyPassphrase('') # will need queried and set per user # config.setIssuerId(os.path.join(pkidir, 'ca.pem')) # config.setIssuerSelfSigned(True) # ^^ OR vv # PKI-PKCS#12 (*.p12-based) configuration configname = 'My PKI PKCS#12 Config' config = QgsAuthConfigPkiPkcs12() config.setName(configname) config.setUri('https://localhost:8443') config.setBundlePath(os.path.join(pkidir, '{0}.p12'.format(user))) config.setBundlePassphrase( 'password') # will need queried and set per user config.setIssuerPath(os.path.join(pkidir, 'ca.pem')) config.setIssuerSelfSigned(True) # Securely store the config in database (encrypted with master password) res = authm.storeAuthenticationConfig(config) if not res[0]: print 'Failed to store {0} config'.format(configname) sys.exit(1) # The auth config has been given a unique ID from the auth system when it # was stored; retrieve it, so it can be linked to a custom server config. configid = config.id() # If the user does not have the OWS connection(s) that this auth config is # meant to connect to, define now. # NOTE: this assumes the individual connections do not already exist. If the # connection settings do exist, this will OVERWRITE them. settings = QSettings() # get application's settings object print 'settings.fileName(): {0}'.format(settings.fileName()) print 'settings.organizationName(): {0}'.format( settings.organizationName()) print 'settings.applicationName(): {0}'.format(settings.applicationName()) # WMS connkind = 'WMS' connname = 'My {0} SSL Server'.format(connkind) credskey = '/Qgis/{0}/{1}'.format(connkind, connname) connkey = '/Qgis/connections-{0}/{1}'.format(connkind.lower(), connname) settings.setValue(credskey + '/authid', configid) # link to auth config settings.setValue(credskey + '/username', '') # deprecated; use auth config settings.setValue(credskey + '/password', '') # deprecated; use auth config settings.setValue(connkey + '/url', 'https://localhost:8443/geoserver/wms') # Optional settings for WMS (these are the defaults) # dpiMode: 0=Off, 1=QGIS, 2=UMN, 4=GeoServer, 7=All (default) settings.setValue(connkey + '/dpiMode', 7) settings.setValue(connkey + '/ignoreAxisOrientation', False) settings.setValue(connkey + '/ignoreGetFeatureInfoURI', False) settings.setValue(connkey + '/ignoreGetMapURI', False) settings.setValue(connkey + '/invertAxisOrientation', False) settings.setValue(connkey + '/referer', '') settings.setValue(connkey + '/smoothPixmapTransform', False) # WCS connkind = 'WCS' connname = 'My {0} SSL Server'.format(connkind) credskey = '/Qgis/{0}/{1}'.format(connkind, connname) connkey = '/Qgis/connections-{0}/{1}'.format(connkind.lower(), connname) settings.setValue(credskey + '/authid', configid) # link to auth config settings.setValue(credskey + '/username', '') # deprecated; use auth config settings.setValue(credskey + '/password', '') # deprecated; use auth config settings.setValue(connkey + '/url', 'https://localhost:8443/geoserver/wcs') # Optional settings for WCS (these are the defaults) # dpiMode: 0=Off, 1=QGIS, 2=UMN, 4=GeoServer, 7=All (default) settings.setValue(connkey + '/dpiMode', 7) settings.setValue(connkey + '/ignoreAxisOrientation', False) settings.setValue(connkey + '/ignoreGetMapURI', False) settings.setValue(connkey + '/invertAxisOrientation', False) settings.setValue(connkey + '/referer', '') settings.setValue(connkey + '/smoothPixmapTransform', False) # WFS connkind = 'WFS' connname = 'My {0} SSL Server'.format(connkind) credskey = '/Qgis/{0}/{1}'.format(connkind, connname) connkey = '/Qgis/connections-{0}/{1}'.format(connkind.lower(), connname) settings.setValue(credskey + '/authid', configid) # link to auth config settings.setValue(credskey + '/username', '') # deprecated; use auth config settings.setValue(credskey + '/password', '') # deprecated; use auth config settings.setValue(connkey + '/url', 'https://localhost:8443/geoserver/wfs') # Optional settings for WFS (these are the defaults) settings.setValue(connkey + '/referer', '')
class TestPrepareQgis2Threejs(utils_for_tests.MidvattenTestSpatialiteDbSv): """ This test has conflicts with sectionplot, so its off! """ @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def setUp(self): super(TestPrepareQgis2Threejs, self).setUp() @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) def init_qgis(self): self.qgs = QgsApplication([], True) self.qgs.initQgis() @mock.patch('db_utils.QgsProject.instance', utils_for_tests.MidvattenTestSpatialiteNotCreated. mock_instance_settings_database) @mock.patch('midvatten_utils.MessagebarAndLog') @mock.patch('qgis.utils.iface', autospec=True) def test_prepare_qgis2threejs(self, mock_iface, mock_messagebar): self.init_qgis() dbconnection = db_utils.DbConnectionManager() dbconnection.execute( '''INSERT INTO obs_points (obsid, h_gs, geometry) VALUES ('1', 1, ST_GeomFromText('POINT(1 1)', 3006)); ''' ) dbconnection.execute( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('1', 1, 0, 1, 'torv'); ''' ) dbconnection.execute( '''INSERT INTO stratigraphy (obsid, stratid, depthtop, depthbot, geoshort) VALUES ('1', 2, 1, 2, 'fyll'); ''' ) dbconnection.commit_and_closedb() #print(str(db_utils.sql_load_fr_db('''SELECT * FROM stratigraphy;'''))) canvas = MagicMock() mock_iface.mapCanvas.return_value = canvas self.midvatten.prepare_layers_for_qgis2threejs() layers = [ 'strat_torv', 'strat_fyll', 'strat_lera', 'strat_silt', 'strat_finsand', 'strat_mellansand', 'strat_sand', 'strat_grovsand', 'strat_fingrus', 'strat_mellangrus', 'strat_grus', 'strat_grovgrus', 'strat_morn', 'strat_berg', 'strat_obs_p_for_qgsi2threejs' ] view_contents = [] for l in layers: if l != 'strat_obs_p_for_qgsi2threejs': view_contents.append( db_utils.sql_load_fr_db( '''SELECT rowid, obsid, z_coord, height, ST_AsText(geometry) FROM {};''' .format(l))[1]) view_contents.append( db_utils.sql_load_fr_db( '''SELECT rowid, obsid, ST_AsText(geometry) FROM {};'''.format( 'strat_obs_p_for_qgsi2threejs'))[1]) test = utils.anything_to_string_representation(view_contents) print(str(test)) ref = '''[[(1, "1", 1.0, -1.0, "POINT(1 1)", )], [(2, "1", 0.0, -1.0, "POINT(1 1)", )], [], [], [], [], [], [], [], [], [], [], [], [], [(1, "1", "POINT(1 1)", )]]''' assert test == ref assert not mock_messagebar.mock_calls #print(str(mock_messagebar.mock_calls)) #print(str(canvas.mock_calls)) #assert False def tearDown(self): #QgsProject.instance().addMapLayer(self.vlayer) #QgsProject.instance().removeMapLayer(self.vlayer.id()) super(self.__class__, self).tearDown()
import csv import re import os import processing from processing.core import Processing from qgis.core import QgsApplication, QgsVectorLayer, QgsMapLayerRegistry from qgis.analysis import QgsGeometryAnalyzer, QgsZonalStatistics import GeneralTools qgishome = "C:/OSGeo4W64/apps/qgis-ltr/" app = QgsApplication([], True) app.setPrefixPath(qgishome, True) app.initQgis() os.environ['QGIS_DEBUG'] = '1' Processing.initialize() class predictor_object(): def __init__(self, short_name, full_name, path, resolution): self.full_name = full_name self.short_name = short_name self.path = path self.resolution = resolution def compute_raster_variables(dem_path, output_folder): """ Method for creating Topographic variables. :param dem_path: Path to the input dem :return: object containing the computed variables """
import sys import os from qgis.core import QgsApplication, QgsVectorLayer from tuflow.integrity_tool.DataCollector import DataCollector # initialise QGIS data providers argv = [bytes(x, 'utf-8') for x in sys.argv] qgis = QgsApplication(argv, False) qgis.initQgis() # path to test map layers path_elwood_pipes = r"C:\Users\Ellis.Symons\Desktop\Ash Wright\temporary\1d_nwk_Elwood_Pipe_L.shp" path_elwood_pits = r"C:\Users\Ellis.Symons\Desktop\Ash Wright\temporary\1d_nwk_Elwood_pits_P.shp" # QgsVectorLayers elwood_pipes = QgsVectorLayer(path_elwood_pipes, "1d_nwk_Elwood_Pipe_L") elwood_pits = QgsVectorLayer(path_elwood_pits, "1d_nwk_Elwood_pits_P") if __name__ == '__main__': if elwood_pipes.isValid(): dataCollector = DataCollector() dataCollector.collectData([elwood_pipes])
def start_qgis_application( enable_gui: bool = False, enable_processing: bool = False, verbose: bool = False, cleanup: bool = True, logger: logging.Logger = None, logprefix: str = 'Qgis:', settings: Dict = None) -> 'qgis.core.QgsApplication': """ Start qgis application :param boolean enable_gui: Enable graphical interface, default to False :param boolean enable_processing: Enable processing, default to False :param boolean verbose: Output qgis settings, default to False :param boolean cleanup: Register atexit hook to close qgisapplication on exit(). Note that prevents qgis to segfault when exiting. Default to True. """ os.environ['QGIS_NO_OVERRIDE_IMPORT'] = '1' os.environ['QGIS_DISABLE_MESSAGE_HOOKS'] = '1' logger = logger or logging.getLogger() qgisPrefixPath = setup_qgis_paths() from qgis.PyQt.QtCore import QCoreApplication from qgis.core import Qgis, QgsApplication logger.info("Starting Qgis application: %s", Qgis.QGIS_VERSION) global version_info version_info = tuple( int(n) for n in Qgis.QGIS_VERSION.split('-')[0].split('.')) if QgsApplication.QGIS_APPLICATION_NAME != "QGIS3": raise RuntimeError("You need QGIS3 (found %s)" % QgsApplication.QGIS_APPLICATION_NAME) if not enable_gui: # We MUST set the QT_QPA_PLATFORM to prevent # Qt trying to connect to display in containers if os.environ.get('DISPLAY') is None: logger.info("Setting offscreen mode") os.environ['QT_QPA_PLATFORM'] = 'offscreen' global qgis_application qgis_application = QgsApplication([], enable_gui) qgis_application.setPrefixPath(qgisPrefixPath, True) # From qgis server # Will enable us to read qgis setting file QCoreApplication.setOrganizationName(QgsApplication.QGIS_ORGANIZATION_NAME) QCoreApplication.setOrganizationDomain( QgsApplication.QGIS_ORGANIZATION_DOMAIN) QCoreApplication.setApplicationName(QgsApplication.QGIS_APPLICATION_NAME) qgis_application.initQgis() if cleanup: # Closing QgsApplication on exit will # prevent our app to segfault on exit() import atexit logger.info("%s Installing cleanup hook" % logprefix) @atexit.register def exitQgis(): global qgis_application if qgis_application: qgis_application.exitQgis() del qgis_application optpath = os.getenv('QGIS_OPTIONS_PATH') if optpath: # Log qgis settings load_qgis_settings(optpath, logger, verbose) if settings: # Initialize settings from qgis.core import QgsSettings qgsettings = QgsSettings() for k, v in settings.items(): qgsettings.setValue(k, v) if verbose: print(qgis_application.showSettings()) # Install logger hook install_logger_hook(logger, logprefix, verbose=verbose) logger.info("%s Qgis application initialized......" % logprefix) if enable_processing: init_qgis_processing() logger.info("%s QGis processing initialized" % logprefix) return qgis_application
def get_qgis_app(requested_locale='en_US', qsetting=''): """ Start one QGIS application to test against. :param locale: The locale we want the qgis to launch with. :type locale: str :param qsetting: String to specify the QSettings. By default, use empty string. :type qsetting: str :returns: Handle to QGIS app, canvas, iface and parent. If there are any errors the tuple members will be returned as None. :rtype: (QgsApplication, CANVAS, IFACE, PARENT) If QGIS is already running the handle to that app will be returned. """ global QGIS_APP, PARENT, IFACE, CANVAS # pylint: disable=W0603 from qgis.PyQt.QtCore import QSettings if qsetting: settings = QSettings(qsetting) else: settings = QSettings() default_user_directory = setting('defaultUserDirectory') current_locale = general_setting('locale/userLocale', default='en_US', qsettings=settings) locale_match = current_locale == requested_locale if iface and locale_match: from qgis.core import QgsApplication QGIS_APP = QgsApplication CANVAS = iface.mapCanvas() PARENT = iface.mainWindow() IFACE = iface try: from qgis.core import QgsApplication from qgis.gui import QgsMapCanvas # pylint: disable=no-name-in-module # noinspection PyPackageRequirements from qgis.PyQt import QtWidgets, QtCore # pylint: disable=W0621 # noinspection PyPackageRequirements from qgis.PyQt.QtCore import QCoreApplication, QSettings from safe.test.qgis_interface import QgisInterface except ImportError: return None, None, None, None if qsetting: settings = QSettings(qsetting) else: settings = QSettings() if not QGIS_APP: gui_flag = True # All test will run qgis in gui mode # AG: For testing purposes, we use our own configuration file # instead of using the QGIS apps conf of the host # noinspection PyCallByClass,PyArgumentList QCoreApplication.setOrganizationName('QGIS') # noinspection PyCallByClass,PyArgumentList QCoreApplication.setOrganizationDomain('qgis.org') # noinspection PyCallByClass,PyArgumentList QCoreApplication.setApplicationName('QGIS2InaSAFETesting') # We disabled message bars for now for extent selector as # we don't have a main window to show them in TS - version 3.2 set_setting('show_extent_warnings', False, settings) set_setting('showRubberBands', True, settings) set_setting('show_extent_confirmations', False, settings) set_setting('analysis_extents_mode', HAZARD_EXPOSURE, settings) if default_user_directory: set_setting('defaultUserDirectory', default_user_directory, settings) # noinspection PyPep8Naming if 'argv' in dir(sys): QGIS_APP = QgsApplication([p.encode('utf-8') for p in sys.argv], gui_flag) else: QGIS_APP = QgsApplication([], gui_flag) # Make sure QGIS_PREFIX_PATH is set in your env if needed! QGIS_APP.initQgis() # Initialize processing processing.Processing.initialize() s = QGIS_APP.showSettings() LOGGER.debug(s) if not locale_match: """Setup internationalisation for the plugin.""" # Save some settings set_general_setting('locale/overrideFlag', True, settings) set_general_setting('locale/userLocale', requested_locale, settings) locale_name = str(requested_locale).split('_')[0] # Also set the system locale to the user overridden local # so that the inasafe library functions gettext will work # .. see:: :py:func:`common.utilities` os.environ['LANG'] = str(locale_name) inasafe_translation_path = os.path.join( safe_dir('i18n'), 'inasafe_' + str(locale_name) + '.qm') if os.path.exists(inasafe_translation_path): if isinstance(QGIS_APP, sip.wrappertype): translator = QTranslator() else: translator = QTranslator(QGIS_APP) result = translator.load(inasafe_translation_path) if not result: message = 'Failed to load translation for %s' % locale_name raise Exception(message) # noinspection PyTypeChecker,PyCallByClass QCoreApplication.installTranslator(translator) # at the end, reload InaSAFE modules so it will get translated too reload_inasafe_modules() if PARENT is None: # noinspection PyPep8Naming PARENT = QtWidgets.QWidget() if CANVAS is None: # noinspection PyPep8Naming CANVAS = QgsMapCanvas(PARENT) CANVAS.resize(QtCore.QSize(400, 400)) if IFACE is None: # QgisInterface is a stub implementation of the QGIS plugin interface # noinspection PyPep8Naming IFACE = QgisInterface(CANVAS) return QGIS_APP, CANVAS, IFACE, PARENT
from config_generator.config_generator import ConfigGenerator from qgis.core import QgsApplication # Flask application app = Flask(__name__) config_in_path = os.environ.get('INPUT_CONFIG_PATH', 'config-in/').rstrip('/') + '/' # Load QGIS providers (will be needed for the categozize groups script) # https://gis.stackexchange.com/questions/263852/using-initqgis-on-headless-installation-of-qgis-3 os.environ["QT_QPA_PLATFORM"] = "offscreen" QgsApplication.setPrefixPath("/usr", True) qgsApp = QgsApplication([], False) qgsApp.initQgis() def config_generator(tenant): """Create a ConfigGenerator instance. :param str tenant: Tenant ID """ if tenant is None: msg = "No tenant selected" app.logger.error(msg) raise Exception(msg) # read ConfigGenerator config file try: config_file = os.path.join(config_in_path, tenant, 'tenantConfig.json')
# *************************************************************************** # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU General Public License as published by * # * the Free Software Foundation; either version 2 of the License, or * # * (at your option) any later version. * # * * # *************************************************************************** from qgis.core import QgsApplication, QgsMapLayerRegistry, QgsVectorLayer, QgsProject from qgis.gui import QgsMapCanvas, QgsMapCanvasLayer, QgsLayerTreeMapCanvasBridge from PyQt4.QtCore import QTimer, QSize qgisApp = QgsApplication([], True) qgisApp.setPrefixPath("/usr", True) qgisApp.initQgis() # Required variables with your shapefile paths and names pngsPath = '/tmp/' boundaryLayer = QgsVectorLayer('/docs/geodata/colombia/colombia_wgs84.shp', 'boundary', 'ogr') climitsLayer = QgsVectorLayer( '/docs/geodata/colombia/colombia-geofabrik/railways.shp', 'climits', 'ogr') otherLayers = { 'Div1_Irrig_1956_0': QgsVectorLayer('/docs/geodata/colombia/colombia-geofabrik/points.shp', 'Div1_Irrig_1956_0', 'ogr'), 'Div1_Irrig_1956_1': QgsVectorLayer('/docs/geodata/colombia/colombia-geofabrik/places.shp', 'Div1_Irrig_1956_1', 'ogr'), 'Div1_Irrig_1956_2':
self.__currentQgisProjectFile), open(self.__currentQgisProjectFile, 'rb'), 'application/xml') }) if r.status_code != 200: self.warningLabel.setText( "attempting to send qgis project, the server request returned code {}" .format(r.status_code)) return r = requests.post(self.urlLineEdit.text() + '/config', headers={'content-Type': 'application/json'}, json=self.__config) if r.status_code != 200: self.warningLabel.setText( "attempting to save the config, the server request returned code {}" .format(r.status_code)) return super(ConfigDialog, self).accept() if __name__ == "__main__": from qgis.core import QgsApplication import sys a = QgsApplication([], False) a.initQgis() d = ConfigDialog(sys.argv[1] if len(sys.argv) >= 2 else None) d.show() a.exec()
def convert_qgis_gpkg_to_kml(qgs_file: str, output_kml_path: str, stage_dir: str = None) -> str: app = None driver_name = "libkml" try: from qgis.core import QgsApplication, QgsProject # Load application to load QApplication dependencies. app_directory = stage_dir # hosts various session type files like qgis.db etc... app = QgsApplication([], False, app_directory) app.initQgis() # Application needs to be initialized before importing. from qgis.core import QgsVectorFileWriter # Load project from template output. project = QgsProject.instance() if not project.read(qgs_file): raise Exception(f"Could not read from {qgs_file}") layers = project.mapLayers() symbology_scale = 20000 if stage_dir: output_dir = os.path.join(stage_dir, "kml") else: output_dir = os.path.join(".", "kml") kml_files = [] for layer_name, layer in layers.items(): output_filename = f"{layer.source().partition('layername=')[2].split('|')[0]}.kml" output_filepath = os.path.join(output_dir, output_filename) kml_files.append(output_filename) if not os.path.exists(output_dir): os.mkdir(output_dir) QgsVectorFileWriter.writeAsVectorFormat( layer=layer, fileName=output_filepath, fileEncoding="utf-8", driverName=driver_name, symbologyExport=QgsVectorFileWriter.SymbolLayerSymbology, symbologyScale=symbology_scale, ) out_driver = ogr.GetDriverByName(driver_name) if os.path.exists(output_kml_path): out_driver.DeleteDataSource(output_kml_path) out_driver.CreateDataSource(output_kml_path) # Ensure the land_polygons and boundary layers are at the bottom when the files get merged. try: kml_files.append(kml_files.pop(kml_files.index("land_polygons.kml"))) kml_files.append(kml_files.pop(kml_files.index("boundary.kml"))) except ValueError as ve: logger.warning(ve) # Merge all of the KML files into a single file. for kml_file in kml_files: kml_path = os.path.join(output_dir, kml_file) gdal.VectorTranslate(output_kml_path, kml_path, accessMode="append") return output_kml_path finally: if app: app.exit()
def start_qgis_application(enable_gui: bool = False, enable_processing: bool = True, verbose: bool = False, cleanup: bool = True) -> 'QgsApplication': """ Start qgis application :param boolean enable_gui: Enable graphical interface, default to False :param boolean enable_processing: Enable processing, default to False :param boolean verbose: Output qgis settings, default to False :param boolean cleanup: Register atexit hook to close qgisapplication on exit(). Note that prevents qgis to segfault when exiting. Default to True. """ os.environ['QGIS_NO_OVERRIDE_IMPORT'] = '1' os.environ['QGIS_DISABLE_MESSAGE_HOOKS'] = '1' setup_qgis_paths() from qgis.core import QgsApplication, Qgis if QgsApplication.QGIS_APPLICATION_NAME != "QGIS3": raise RuntimeError("You need QGIS3 (found %s)" % QgsApplication.QGIS_APPLICATION_NAME) if not enable_gui: # We MUST set the QT_QPA_PLATFORM to prevent # Qt trying to connect to display in containers if os.environ.get('DISPLAY') is None: print("Warning: Setting Qt offscreen mode") os.environ['QT_QPA_PLATFORM'] = 'offscreen' qgis_prefix = os.environ.get('QGIS_HOME', '/usr') global _qgis_application if _qgis_application is not None: print("Qgis already initialized", file=sys.stderr, flush=True) return _qgis_application _qgis_application = QgsApplication([], enable_gui) # Install logger hook install_logger_hook(verbose=verbose) _qgis_application.setPrefixPath(qgis_prefix, True) _qgis_application.initQgis() if cleanup: # Closing QgsApplication on exit will # prevent our app to segfault on exit() import atexit @atexit.register def exitQgis(): global _qgis_application if _qgis_application: _qgis_application.exitQgis() del _qgis_application if verbose: print(_qgis_application.showSettings()) if enable_processing: init_processing(verbose) if verbose: print("Qgis %s initialized......" % Qgis.QGIS_VERSION) return _qgis_application
plugins_dir = os.path.dirname(plugin_dir) # python path setting sys.path.append(plugins_dir) # initialize output directory initOutputDir() plugin_name = os.path.basename(plugin_dir) suite = unittest.TestLoader().discover(plugin_name + ".tests") unittest.TextTestRunner(verbosity=2).run(suite) if __name__ == "__main__": gui_mode = True QGISAPP = QgsApplication(sys.argv, gui_mode) QGISAPP.initQgis() print "=" * 70 print QGISAPP.showSettings() print "=" * 70 # set up network disk cache manager = QgsNetworkAccessManager.instance() cache = QNetworkDiskCache(manager) cache.setCacheDirectory(pluginPath(os.path.join("tests", "cache"))) cache.setMaximumCacheSize(50 * 1024 * 1024) manager.setCache(cache) # run test! runTest()
# from QGIS import iface-> symbolic importation of iface object of QGIS # import qgis from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry import processing, os, ogr, csv, sys from processing.core.Processing import Processing from qgis.core import QgsRasterLayer, QgsApplication, QgsVectorFileWriter, QgsVectorLayer from PyQt4.QtCore import QFileInfo #import pandas as pd qgis_prefix = r"C:\Program Files\QGIS 2.18\apps\qgis" # Indicamos donde esta el QGIS QgsApplication.setPrefixPath(qgis_prefix, True) # Configuramos la aplicacion QGIS app = QgsApplication([], True, None) # El True inhabilita la interfaz grafica QgsApplication.initQgis() # Iniciamos la aplicacion QGIS # Indice Diferencial de Vegetacion Normalizado def NDVI(band4, band8, output): entries = [] #define raster 1 (band4) raster1 = QgsRasterCalculatorEntry() raster1.ref = 'band4@1' raster1.raster = band4 raster1.bandNumber = 1 entries.append(raster1) #define raster 2 (band8) raster2 = QgsRasterCalculatorEntry() raster2.ref = 'band8@1' raster2.raster = band8
def getQgisTestApp(): """ Start one QGis application to test agaist Input NIL Output handle to qgis app If QGis is already running the handle to that app will be returned """ global QGISAPP # pylint: disable=W0603 if QGISAPP is None: myGuiFlag = True # All test will run qgis in gui mode QGISAPP = QgsApplication(sys.argv, myGuiFlag) if 'QGIS_PREFIX_PATH' in os.environ: myPath = os.environ['QGIS_PREFIX_PATH'] myUseDefaultPathFlag = True QGISAPP.setPrefixPath(myPath, myUseDefaultPathFlag) if sys.platform.startswith('darwin'): # override resource paths, otherwise looks for Resources in app if 'QGIS_MAC_PKGDATA_DIR' in os.environ: myPkgPath = os.environ['QGIS_MAC_PKGDATA_DIR'] QGISAPP.setPkgDataPath(myPkgPath) if 'QGIS_MAC_SVG_DIR' in os.environ: mySVGPath = os.environ['QGIS_MAC_SVG_DIR'] mySVGPaths = QGISAPP.svgPaths() # doesn't get rid of incorrect path, just adds correct one mySVGPaths.prepend(mySVGPath) QGISAPP.setDefaultSvgPaths(mySVGPaths) QGISAPP.initQgis() s = QGISAPP.showSettings() print s global PARENT # pylint: disable=W0603 if PARENT is None: PARENT = QtGui.QWidget() global CANVAS # pylint: disable=W0603 if CANVAS is None: CANVAS = QgsMapCanvas(PARENT) CANVAS.resize(QtCore.QSize(400, 400)) global IFACE # pylint: disable=W0603 if IFACE is None: # QgisInterface is a stub implementation of the QGIS plugin interface IFACE = QgisInterface(CANVAS) return QGISAPP, CANVAS, IFACE, PARENT