def define_layer(self, layer_path): """Create QGIS layer (either vector or raster) from file path input. :param layer_path: Full path to layer file. :type layer_path: str :return: QGIS layer. :rtype: QgsMapLayer """ scenario_dir = self.source_directory.text() joined_path = os.path.join(scenario_dir, layer_path) full_path = os.path.normpath(joined_path) file_name = os.path.split(layer_path)[-1] # get extension and basename to create layer base_name, extension = os.path.splitext(file_name) # load layer in scenario layer = QgsRasterLayer(full_path, base_name) if layer.isValid(): return layer else: layer = QgsVectorLayer(full_path, base_name, 'ogr') if layer.isValid(): return layer # if layer is not vector nor raster else: LOGGER.warning('Input in scenario is not recognized/supported') return
def testImportIntoGpkg(self): # init target file test_gpkg = tempfile.mktemp(suffix='.gpkg', dir=self.testDataDir) gdal.GetDriverByName('GPKG').Create(test_gpkg, 1, 1, 1) source = QgsRasterLayer(os.path.join(self.testDataDir, 'raster', 'band3_byte_noct_epsg4326.tif'), 'my', 'gdal') self.assertTrue(source.isValid()) provider = source.dataProvider() fw = QgsRasterFileWriter(test_gpkg) fw.setOutputFormat('gpkg') fw.setCreateOptions(['RASTER_TABLE=imported_table', 'APPEND_SUBDATASET=YES']) pipe = QgsRasterPipe() self.assertTrue(pipe.set(provider.clone())) projector = QgsRasterProjector() projector.setCrs(provider.crs(), provider.crs()) self.assertTrue(pipe.insert(2, projector)) self.assertEqual(fw.writeRaster(pipe, provider.xSize(), provider.ySize(), provider.extent(), provider.crs()), 0) # Check that the test geopackage contains the raster layer and compare rlayer = QgsRasterLayer('GPKG:%s:imported_table' % test_gpkg) self.assertTrue(rlayer.isValid()) out_provider = rlayer.dataProvider() self.assertEqual(provider.block(1, provider.extent(), source.width(), source.height()).data(), out_provider.block(1, out_provider.extent(), rlayer.width(), rlayer.height()).data()) # remove result file os.unlink(test_gpkg)
def load_layer(layer_path): """Helper to load and return a single QGIS layer. :param layer_path: Path name to raster or vector file. :type layer_path: str :returns: Layer instance. :rtype: QgsMapLayer """ # Extract basename and absolute path file_name = os.path.split(layer_path)[-1] # In case path was absolute base_name, extension = os.path.splitext(file_name) # Create QGis Layer Instance if extension in ['.asc', '.tif']: layer = QgsRasterLayer(layer_path, base_name) elif extension in ['.shp']: layer = QgsVectorLayer(layer_path, base_name, 'ogr') else: message = 'File %s had illegal extension' % layer_path raise Exception(message) # noinspection PyUnresolvedReferences message = 'Layer "%s" is not valid' % layer.source() # noinspection PyUnresolvedReferences if not layer.isValid(): print message # noinspection PyUnresolvedReferences if not layer.isValid(): raise Exception(message) return layer
def testSetDataSource(self): """Test change data source""" temp_dir = QTemporaryDir() options = QgsDataProvider.ProviderOptions() myPath = os.path.join(unitTestDataPath('raster'), 'band1_float32_noct_epsg4326.tif') myFileInfo = QFileInfo(myPath) myBaseName = myFileInfo.baseName() layer = QgsRasterLayer(myPath, myBaseName) renderer = QgsSingleBandGrayRenderer(layer.dataProvider(), 2) image = layer.previewAsImage(QSize(400, 400)) self.assertFalse(image.isNull()) self.assertTrue(image.save(os.path.join(temp_dir.path(), 'expected.png'), "PNG")) layer.setDataSource(myPath.replace('4326.tif', '4326-BAD_SOURCE.tif'), 'bad_layer', 'gdal', options) self.assertFalse(layer.isValid()) image = layer.previewAsImage(QSize(400, 400)) self.assertTrue(image.isNull()) layer.setDataSource(myPath.replace('4326-BAD_SOURCE.tif', '4326.tif'), 'bad_layer', 'gdal', options) self.assertTrue(layer.isValid()) image = layer.previewAsImage(QSize(400, 400)) self.assertFalse(image.isNull()) self.assertTrue(image.save(os.path.join(temp_dir.path(), 'actual.png'), "PNG")) self.assertTrue(filecmp.cmp(os.path.join(temp_dir.path(), 'actual.png'), os.path.join(temp_dir.path(), 'expected.png')), False)
def load(fileName, name=None, crs=None, style=None, isRaster=False): """ Loads a layer/table into the current project, given its file. .. deprecated:: 3.0 Do not use, will be removed in QGIS 4.0 """ from warnings import warn warn("processing.load is deprecated and will be removed in QGIS 4.0", DeprecationWarning) if fileName is None: return prjSetting = None settings = QgsSettings() if crs is not None: prjSetting = settings.value('/Projections/defaultBehavior') settings.setValue('/Projections/defaultBehavior', '') if name is None: name = os.path.split(fileName)[1] if isRaster: qgslayer = QgsRasterLayer(fileName, name) if qgslayer.isValid(): if crs is not None and qgslayer.crs() is None: qgslayer.setCrs(crs, False) if style is None: style = ProcessingConfig.getSetting(ProcessingConfig.RASTER_STYLE) qgslayer.loadNamedStyle(style) QgsProject.instance().addMapLayers([qgslayer]) else: if prjSetting: settings.setValue('/Projections/defaultBehavior', prjSetting) raise RuntimeError(QCoreApplication.translate('dataobject', 'Could not load layer: {0}\nCheck the processing framework log to look for errors.').format( fileName)) else: qgslayer = QgsVectorLayer(fileName, name, 'ogr') if qgslayer.isValid(): if crs is not None and qgslayer.crs() is None: qgslayer.setCrs(crs, False) if style is None: if qgslayer.geometryType() == QgsWkbTypes.PointGeometry: style = ProcessingConfig.getSetting(ProcessingConfig.VECTOR_POINT_STYLE) elif qgslayer.geometryType() == QgsWkbTypes.LineGeometry: style = ProcessingConfig.getSetting(ProcessingConfig.VECTOR_LINE_STYLE) else: style = ProcessingConfig.getSetting(ProcessingConfig.VECTOR_POLYGON_STYLE) qgslayer.loadNamedStyle(style) QgsProject.instance().addMapLayers([qgslayer]) if prjSetting: settings.setValue('/Projections/defaultBehavior', prjSetting) return qgslayer
def load_layer(layer_file, directory=TESTDATA): """Helper to load and return a single QGIS layer :param layer_file: Path name to raster or vector file. :type layer_file: str :param directory: Optional parent dir. If None, path name is assumed to be absolute. :type directory: str, None :returns: tuple containing layer and its category. :rtype: (QgsMapLayer, str) """ # Extract basename and absolute path file_path = os.path.split(layer_file)[-1] # In case path was absolute base_name, extension = os.path.splitext(file_path) if directory is None: path = layer_file else: path = os.path.join(directory, layer_file) keyword_path = path[:-4] + '.keywords' # Determine if layer is hazard or exposure keywords = read_file_keywords(keyword_path) category = 'undefined' if 'category' in keywords: category = keywords['category'] message = 'Could not read %s' % keyword_path assert keywords is not None, message # Create QGis Layer Instance if extension in ['.asc', '.tif']: layer = QgsRasterLayer(path, base_name) elif extension in ['.shp']: layer = QgsVectorLayer(path, base_name, 'ogr') else: message = 'File %s had illegal extension' % path raise Exception(message) # noinspection PyUnresolvedReferences message = 'Layer "%s" is not valid' % str(layer.source()) # noinspection PyUnresolvedReferences if not layer.isValid(): print message # noinspection PyUnresolvedReferences assert layer.isValid(), message return layer, category
def load_layer(layer_path): """Helper to load and return a single QGIS layer :param layer_path: Path name to raster or vector file. :type layer_path: str :returns: tuple containing layer and its layer_purpose. :rtype: (QgsMapLayer, str) """ # Extract basename and absolute path file_name = os.path.split(layer_path)[-1] # In case path was absolute base_name, extension = os.path.splitext(file_name) # Determine if layer is hazard or exposure layer_purpose = 'undefined' try: try: keywords = read_iso19115_metadata(layer_path) except: try: keywords = read_file_keywords(layer_path) keywords = write_read_iso_19115_metadata(layer_path, keywords) except NoKeywordsFoundError: keywords = {} if 'layer_purpose' in keywords: layer_purpose = keywords['layer_purpose'] except NoKeywordsFoundError: pass # Create QGis Layer Instance if extension in ['.asc', '.tif']: layer = QgsRasterLayer(layer_path, base_name) elif extension in ['.shp']: layer = QgsVectorLayer(layer_path, base_name, 'ogr') else: message = 'File %s had illegal extension' % layer_path raise Exception(message) # noinspection PyUnresolvedReferences message = 'Layer "%s" is not valid' % layer.source() # noinspection PyUnresolvedReferences if not layer.isValid(): print message # noinspection PyUnresolvedReferences if not layer.isValid(): raise Exception(message) return layer, layer_purpose
def load(fileName, name=None, crs=None, style=None, isRaster=False): """Loads a layer/table into the current project, given its file. """ if fileName is None: return prjSetting = None settings = QSettings() if crs is not None: prjSetting = settings.value('/Projections/defaultBehaviour') settings.setValue('/Projections/defaultBehaviour', '') if name is None: name = os.path.split(fileName)[1] if isRaster: qgslayer = QgsRasterLayer(fileName, name) if qgslayer.isValid(): if crs is not None and qgslayer.crs() is None: qgslayer.setCrs(crs, False) if style is None: style = ProcessingConfig.getSetting(ProcessingConfig.RASTER_STYLE) qgslayer.loadNamedStyle(style) QgsMapLayerRegistry.instance().addMapLayers([qgslayer]) iface.legendInterface().refreshLayerSymbology(qgslayer) else: if prjSetting: settings.setValue('/Projections/defaultBehaviour', prjSetting) raise RuntimeError('Could not load layer: ' + unicode(fileName) + '\nCheck the processing framework log to look for errors') else: qgslayer = QgsVectorLayer(fileName, name, 'ogr') if qgslayer.isValid(): if crs is not None and qgslayer.crs() is None: qgslayer.setCrs(crs, False) if style is None: if qgslayer.geometryType() == QGis.Point: style = ProcessingConfig.getSetting(ProcessingConfig.VECTOR_POINT_STYLE) elif qgslayer.geometryType() == QGis.Line: style = ProcessingConfig.getSetting(ProcessingConfig.VECTOR_LINE_STYLE) else: style = ProcessingConfig.getSetting(ProcessingConfig.VECTOR_POLYGON_STYLE) qgslayer.loadNamedStyle(style) QgsMapLayerRegistry.instance().addMapLayers([qgslayer]) if prjSetting: settings.setValue('/Projections/defaultBehaviour', prjSetting) return qgslayer
def addToCanvas(self, roles): if self.canOpen(roles): if not oauth2_supported: iface.messageBar().pushMessage( "Cannot load basemap", "OAuth support is not available", QgsMessageBar.WARNING) else: authcfg = get_oauth_authcfg() if authcfg is None: iface.messageBar().pushMessage( "Cannot load basemap", "Cannot find a valid authentication configuration", QgsMessageBar.WARNING) else: authId = authcfg.id() layer = QgsRasterLayer('authcfg={authcfg}&type=xyz&url={url}'.format(url=urllib2.quote("{}?version={}".format(self.url, pluginSetting("apiVersion"))), authcfg=authId), self.name, "wms") if layer.isValid(): QgsMapLayerRegistry.instance().addMapLayer(layer) else: iface.messageBar().pushMessage( "Cannot load basemap", "Cannot create basemap layer", QgsMessageBar.WARNING) else: webbrowser.open_new(SUBSCRIBE_URL)
def accept(self): input_path = str(self.leInputPath.text()) output_path = str(self.leOutputPath.text()) if not output_path.endswith('.tif'): QMessageBox.warning( self.parent, self.tr('InaSAFE'), (self.tr('Output file name must be tif file'))) if not os.path.exists(input_path): QMessageBox.warning( self.parent, self.tr('InaSAFE'), (self.tr('Input file is not exist'))) return my_algorithm = str(self.cboAlgorithm.currentText()).lower() fileName = convert_mmi_data(input_path, output_path, the_algorithm=my_algorithm, algorithm_name=False) if self.cBLoadLayer.isChecked(): fileInfo = QFileInfo(fileName) baseName = fileInfo.baseName() my_raster_layer = QgsRasterLayer(fileName, baseName) if not my_raster_layer.isValid(): LOGGER.debug("Failed to load") else: QgsMapLayerRegistry.instance().addMapLayer(my_raster_layer) self.done(self.Accepted) if not self.test_mode: QMessageBox.warning( self.parent, self.tr('InaSAFE'), (self.tr('Success to convert %1 to %2'). arg(input_path).arg(output_path)))
def testPalettedColorTableToClassData(self): entries = [QgsColorRampShader.ColorRampItem(5, QColor(255, 0, 0), 'item1'), QgsColorRampShader.ColorRampItem(3, QColor(0, 255, 0), 'item2'), QgsColorRampShader.ColorRampItem(6, QColor(0, 0, 255), 'item3'), ] classes = QgsPalettedRasterRenderer.colorTableToClassData(entries) self.assertEqual(classes[0].value, 5) self.assertEqual(classes[1].value, 3) self.assertEqual(classes[2].value, 6) self.assertEqual(classes[0].label, 'item1') self.assertEqual(classes[1].label, 'item2') self.assertEqual(classes[2].label, 'item3') self.assertEqual(classes[0].color.name(), '#ff0000') self.assertEqual(classes[1].color.name(), '#00ff00') self.assertEqual(classes[2].color.name(), '#0000ff') # test #13263 path = os.path.join(unitTestDataPath('raster'), 'hub13263.vrt') info = QFileInfo(path) base_name = info.baseName() layer = QgsRasterLayer(path, base_name) self.assertTrue(layer.isValid(), 'Raster not loaded: {}'.format(path)) classes = QgsPalettedRasterRenderer.colorTableToClassData(layer.dataProvider().colorTable(1)) self.assertEqual(len(classes), 4) classes = QgsPalettedRasterRenderer.colorTableToClassData(layer.dataProvider().colorTable(15)) self.assertEqual(len(classes), 256)
def testLayerRemovalBeforeRun(self): """test behavior when layer is removed before task begins""" path = os.path.join(unitTestDataPath(), 'raster', 'with_color_table.tif') raster_layer = QgsRasterLayer(path, "test") self.assertTrue(raster_layer.isValid()) pipe = QgsRasterPipe() self.assertTrue(pipe.set(raster_layer.dataProvider().clone())) tmp = create_temp_filename('remove_layer.tif') writer = QgsRasterFileWriter(tmp) task = QgsRasterFileWriterTask(writer, pipe, 100, 100, raster_layer.extent(), raster_layer.crs()) task.writeComplete.connect(self.onSuccess) task.errorOccurred.connect(self.onFail) # remove layer raster_layer = None QgsApplication.taskManager().addTask(task) while not self.success and not self.fail: QCoreApplication.processEvents() # in this case will still get a positive result - since the pipe is cloned before the task # begins the task is no longer dependent on the original layer self.assertTrue(self.success) self.assertFalse(self.fail) self.assertTrue(os.path.exists(tmp))
def loadLayer(theLayerFile): """Helper to load and return a single QGIS layer""" # Extract basename and absolute path myBaseName, myExt = os.path.splitext(theLayerFile) myPath = os.path.join(TESTDATA, theLayerFile) myKeywordPath = myPath[:-4] + '.keywords' # Determine if layer is hazard or exposure myKeywords = read_keywords(myKeywordPath) myType = 'undefined' if 'category' in myKeywords: myType = myKeywords['category'] msg = 'Could not read %s' % myKeywordPath assert myKeywords is not None, msg # Create QGis Layer Instance if myExt in ['.asc', '.tif']: myLayer = QgsRasterLayer(myPath, myBaseName) elif myExt in ['.shp']: myLayer = QgsVectorLayer(myPath, myBaseName, 'ogr') else: myMessage = 'File %s had illegal extension' % myPath raise Exception(myMessage) myMessage = 'Layer "%s" is not valid' % str(myLayer.source()) assert myLayer.isValid(), myMessage return myLayer, myType
def testIdentify(self): myPath = os.path.join(unitTestDataPath(), 'landsat.tif') myFileInfo = QFileInfo(myPath) myBaseName = myFileInfo.baseName() myRasterLayer = QgsRasterLayer(myPath, myBaseName) myMessage = 'Raster not loaded: %s' % myPath assert myRasterLayer.isValid(), myMessage myPoint = QgsPoint(786690, 3345803) #print 'Extents: %s' % myRasterLayer.extent().toString() #myResult, myRasterValues = myRasterLayer.identify(myPoint) #assert myResult myRasterValues = myRasterLayer.dataProvider().identify(myPoint, QgsRasterDataProvider.IdentifyFormatValue ) assert len( myRasterValues ) > 0 # Get the name of the first band myBand = myRasterValues.keys()[0] #myExpectedName = QString('Band 1') myExpectedBand = 1 myMessage = 'Expected "%s" got "%s" for first raster band name' % ( myExpectedBand, myBand) assert myExpectedBand == myBand, myMessage # Convert each band value to a list of ints then to a string myValues = myRasterValues.values() myIntValues = [] for myValue in myValues: #myIntValues.append(int(str(myValue))) myIntValues.append( myValue.toInt()[0] ) myValues = str(myIntValues) myExpectedValues = '[127, 141, 112, 72, 86, 126, 156, 211, 170]' myMessage = 'Expected: %s\nGot: %s' % (myValues, myExpectedValues) self.assertEquals(myValues, myExpectedValues, myMessage)
def generateLayer(self, nameCoverage, coverageTime, boundingBox=None): """Generates a raster layer for QGIS. :param nameCoverage: the name identifier of the coverage we want to retrieve. :type nameCoverage: str :param coverageTime: the time dimension of the coverage we want. :type coverageTime: str :returns: a QGIS-compatible raster layer object for the coverage and times provided. :rtype: QgsRasterLayer """ url = self.generateURLForGeoTIFF(nameCoverage, coverageTime, boundingBox) layerName = "{ct}_{nc}-{id}".format(ct=coverageTime, nc=nameCoverage, id=uuid.uuid4()) if Utilities.is_linux(): import requests with tempfile.NamedTemporaryFile(suffix=".tiff", delete=False) as f: r = requests.get(url, stream=True) with open(f.name, "wb") as g: for chunk in r.iter_content(): g.write(chunk) layer = QgsRasterLayer(f.name, layerName) else: layer = QgsRasterLayer(url, layerName) if layer.isValid(): return layer else: msg = "Couldn't create a valid layer." self.standardMessage.emit(msg)
def test_read_existing_geopackage(self): """Test we can read an existing geopackage.""" path = standard_data_path('other', 'jakarta.gpkg') import os path = os.path.normpath(os.path.normcase(os.path.abspath(path))) geopackage = QFileInfo(path) data_store = GeoPackage(geopackage) # We should have 3 layers in this geopackage. self.assertEqual(len(data_store.layers()), 3) # Test we can load a vector layer. roads = QgsVectorLayer( data_store.layer_uri('roads'), 'Test', 'ogr' ) self.assertTrue(roads.isValid()) # Test we can load a raster layers. # This currently fails on windows... # So we have decorated it with expected fail on windows # Should pass on other platforms. path = data_store.layer_uri('flood') flood = QgsRasterLayer(path, 'flood') self.assertTrue(flood.isValid())
def toMapLayer(self): from qgis.core import QgsRasterLayer, QgsContrastEnhancement rl = QgsRasterLayer(self.gdalUri(), self.name) if rl.isValid(): rl.setContrastEnhancement(QgsContrastEnhancement.StretchToMinimumMaximum) return rl
def testIdentify(self): myPath = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'testdata', 'landsat.tif')) myFileInfo = QFileInfo(myPath) myBaseName = myFileInfo.baseName() myRasterLayer = QgsRasterLayer(myPath, myBaseName) myMessage = 'Raster not loaded: %s' % myPath assert myRasterLayer.isValid(), myMessage myPoint = QgsPoint(786690, 3345803) #print 'Extents: %s' % myRasterLayer.extent().toString() myResult, myRasterValues = myRasterLayer.identify(myPoint) assert myResult # Get the name of the first band myBandName = myRasterValues.keys()[0] myExpectedName = QString('Band 1') myMessage = 'Expected "%s" got "%s" for first raster band name' % ( myExpectedName, myBandName) assert myExpectedName == myBandName, myMessage # Convert each band value to a list of ints then to a string myValues = myRasterValues.values() myIntValues = [] for myValue in myValues: myIntValues.append(int(str(myValue))) myValues = str(myIntValues) myExpectedValues = '[127, 141, 112, 72, 86, 126, 156, 211, 170]' myMessage = 'Expected: %s\nGot: %s' % (myValues, myExpectedValues) self.assertEquals(myValues, myExpectedValues, myMessage)
def generateLayerFromGeoTIFFURL(self, geoTiffUrl, layerName): """Generates a new layer based on the GeoTIFF URL provided for the WCS service. This method also appends to the name an UUID so the uniqueness of it's name and ID is guaranteed to avoid problems when managing asynchronous generation of layers between different processes. :param geoTiffUrl: the download URL for this image. :type geoTiffUrl: str :param layerName: the name to give to this layer. The resultant layer will have an UUID appended. :type layerName: str """ tiff_string = "{ln}{id}".format(ln=layerName, id=uuid.uuid4()) layer = QgsRasterLayer(geoTiffUrl, tiff_string) if Utilities.is_linux(): import requests with tempfile.NamedTemporaryFile(suffix=".tiff", delete=False) as f: r = requests.get(geoTiffUrl, stream=True) with open(f.name, "wb") as g: for chunk in r.iter_content(): g.write(chunk) layer = QgsRasterLayer(f.name, layerName) else: layer = QgsRasterLayer(geoTiffUrl, layerName) if layer.isValid(): return layer else: msg = "Couldn't create a valid layer." self.standardMessage.emit(msg)
def test_clip_raster_small(self): """Raster layers can be clipped in small and precise size. For #710.""" # Create a raster layer layer_name = 'shake' raster_layer = QgsRasterLayer(RASTERPATH, layer_name) message = ( 'Did not find layer "%s" in path "%s"' % (layer_name, RASTERPATH)) assert raster_layer is not None, message # Create a bounding box bounding_box = [97, -3, 104, 1] # Clip the vector to the bbox result = clip_layer(raster_layer, bounding_box) # Check the output is valid assert os.path.exists(result.source()) # Clip and give a desired resolution for the output # small pixel size and high precision # based on pixel size of Flood_Current_Depth_Jakarta_geographic.asc size = 0.00045228819716 result = clip_layer(raster_layer, bounding_box, size) new_raster_layer = QgsRasterLayer(result.source(), layer_name) assert new_raster_layer.isValid(), 'Resampled raster is not valid' message = ( 'Resampled raster has incorrect pixel size. Expected: %.14f, ' 'Actual: %.14f' % ( size, new_raster_layer.rasterUnitsPerPixelX())) result_size = new_raster_layer.rasterUnitsPerPixelX() self.assertAlmostEqual(result_size, size, places=13, msg=message)
def accept(self): """Creates and loads the WMS layer.""" self.close() currentIndex = self.comboBoxLayer.currentIndex() currentLayerId, unused_dataType = self.comboBoxLayer.itemData(currentIndex) currentLayerName = unicode(self.comboBoxLayer.currentText()) mapId = self.labelMapId.text() # Create the WMS layer token = oauth2_utils.getToken() url = 'https://mapsengine.google.com/%s-4/wms/%s/' wmsUrl = url % (mapId, token.access_token) currentFormatIndex = self.comboBoxFormat.currentIndex() imageFormat = unicode(self.comboBoxFormat.itemData(currentFormatIndex)) crs = self.comboBoxCrs.currentText() uri = QgsDataSourceURI() uri.setParam('url', wmsUrl) uri.setParam('layers', currentLayerId) uri.setParam('format', imageFormat) uri.setParam('crs', crs) uri.setParam('styles', '') rlayer = QgsRasterLayer(str(uri.encodedUri()), currentLayerName, 'wms') if rlayer.isValid(): QgsMapLayerRegistry.instance().addMapLayer(rlayer) else: logText = 'Failed to add WMS layer %s with URI %s' % ( currentLayerName, str(uri.encodedUri())) warnText = 'Failed to add WMS layer %s' % currentLayerName QgsMessageLog.logMessage(logText, 'GMEConnector', QgsMessageLog.CRITICAL) self.iface.messageBar().pushMessage( 'Google Maps Engine Connector', warnText, level=QgsMessageBar.CRITICAL, duration=3)
def test_clip_raster(self): """Raster layers can be clipped.""" # Create a raster layer layer_name = 'shake' raster_layer = QgsRasterLayer(RASTERPATH, layer_name) message = ( 'Did not find layer "%s" in path "%s"' % (layer_name, RASTERPATH)) assert raster_layer is not None, message # Create a bounding box bounding_box = [97, -3, 104, 1] # Clip the vector to the bbox result = clip_layer(raster_layer, bounding_box) # Check the output is valid assert os.path.exists(result.source()) # Clip and give a desired resolution for the output # big pixel size size = 0.05 result = clip_layer(raster_layer, bounding_box, size) new_raster_layer = QgsRasterLayer(result.source(), layer_name) assert new_raster_layer.isValid(), 'Resampled raster is not valid' message = ( 'Resampled raster has incorrect pixel size. Expected: %5f, ' 'Actual: %5f' % (size, new_raster_layer.rasterUnitsPerPixelX())) assert new_raster_layer.rasterUnitsPerPixelX() == size, message
def test_clipRaster(self): """Raster layers can be clipped """ # Create a raster layer myName = 'shake' myRasterLayer = QgsRasterLayer(RASTERPATH, myName) myMessage = 'Did not find layer "%s" in path "%s"' % \ (myName, RASTERPATH) assert myRasterLayer is not None, myMessage # Create a bounding box myRect = [97, -3, 104, 1] # Clip the vector to the bbox myResult = clip_layer(myRasterLayer, myRect) # Check the output is valid assert os.path.exists(myResult.source()) # Clip and give a desired resolution for the output mySize = 0.05 myResult = clip_layer(myRasterLayer, myRect, mySize) myNewRasterLayer = QgsRasterLayer(myResult.source(), myName) assert myNewRasterLayer.isValid(), 'Resampled raster is not valid' myMessage = ('Resampled raster has incorrect pixel size.' 'Expected: %f, Actual: %f' % (mySize, myNewRasterLayer.rasterUnitsPerPixelX())) assert myNewRasterLayer.rasterUnitsPerPixelX() == mySize, myMessage
def test_invalidFilenamesCaught(self): """Invalid filenames raise appropriate exceptions Wrote this test because test_clipBoth raised the wrong error when file was missing. Instead of reporting that, it gave Western boundary must be less than eastern. I got [0.0, 0.0, 0.0, 0.0] See issue #170 """ # Try to create a vector layer from non-existing filename myName = 'stnhaoeu_78oeukqjkrcgA' myPath = 'OEk_tnshoeu_439_kstnhoe' with RedirectStreams(stdout=DEVNULL, stderr=DEVNULL): myVectorLayer = QgsVectorLayer(myPath, myName, 'ogr') myMessage = ('QgsVectorLayer reported "valid" for non ' 'existent path "%s" and name "%s".' % (myPath, myName)) assert not myVectorLayer.isValid(), myMessage # Create a raster layer with RedirectStreams(stdout=DEVNULL, stderr=DEVNULL): myRasterLayer = QgsRasterLayer(myPath, myName) myMessage = ('QgsRasterLayer reported "valid" for non ' 'existent path "%s" and name "%s".' % (myPath, myName)) assert not myRasterLayer.isValid(), myMessage
def add_layer( self, layer_source, layer_name): layer = QgsRasterLayer(layer_source,self.tr(layer_name),"wms") if not layer.isValid(): # Test if string is valid QMessageBox.information(self.iface.mainWindow(),self.tr(u"Error!"), self.tr(u"Layer has no valid token... Try again!")) QSettings().setValue('lmopendata/token', '') # if layer is incorrect clear token key QgsMapLayerRegistry.instance().addMapLayer(layer)
def toMapLayer(self): from qgis.core import QgsRasterLayer, QgsContrastEnhancement # QGIS has no provider to load rasters, let's use GDAL uri = self.gpkgGdalUri() rl = QgsRasterLayer(uri, self.name) if rl.isValid(): rl.setContrastEnhancement(QgsContrastEnhancement.StretchToMinimumMaximum) return rl
def test_get_raster_layer_list(self): wms_url_with_parameters = self.valid_wms_url # use this list for proper testing... visibility = [True, False, True, True, True, False] # when debugging, use the list below instead # visibility = [True] for i, visible in enumerate(visibility): layer_name = layer_interaction.biuniquify_layer_name('r{}_visible:{}'.format(i, visible)) rlayer = QgsRasterLayer(wms_url_with_parameters, layer_name, 'wms') self.assertTrue(rlayer.isValid(), layer_name.join(' is not a valid raster layer')) QgsMapLayerRegistry.instance().addMapLayer(rlayer) self.iface.legendInterface().setLayerVisible(rlayer, visible) self.layer_list.append(layer_name) # get a list of all visible wms layers expected_layers = {} actual_layers = {} visible_raster_layers = layer_interaction.get_raster_layer_list(self.iface, 'visible') for i, visible in enumerate(visibility): if visible: expected_layers[self.layer_list[i]] = True for layer in visible_raster_layers: if '_visible:' in layer.name(): actual_layers[str(layer.name())] = True self.assertDictEqual(expected_layers, actual_layers, 'The returned layers do not match the expected layers.\n\t Expected: {0}\n\t received: {1}.'.format(expected_layers, actual_layers)) # get a list of all invisible wms layers expected_layers = {} actual_layers = {} invisible_raster_layers = layer_interaction.get_raster_layer_list(self.iface, 'invisible') for i, visible in enumerate(visibility): if not visible: expected_layers[self.layer_list[i]] = False for layer in invisible_raster_layers: if '_visible:' in layer.name(): actual_layers[str(layer.name())] = True if layer.name().endswith('True') else False self.assertDictEqual(expected_layers, actual_layers, 'The returned layers do not match the expected layers.\n\t Expected: {0}\n\t received: {1}.'.format(expected_layers, actual_layers)) # get a list of wms layers expected_layers = {} actual_layers = {} invisible_raster_layers = layer_interaction.get_raster_layer_list(self.iface, 'all') for i, visible in enumerate(visibility): expected_layers[self.layer_list[i]] = visible for layer in invisible_raster_layers: if '_visible:' in layer.name(): actual_layers[str(layer.name())] = True if layer.name().endswith('True') else False self.assertDictEqual(expected_layers, actual_layers, 'The returned layers do not match the expected layers.\n\t Expected: {0}\n\t received: {1}.'.format(expected_layers, actual_layers))
def testIssue7023(self): """Check if converting a raster from 1.8 to 2 works.""" myPath = os.path.join(unitTestDataPath("raster"), "raster-pallette-crash2.tif") myFileInfo = QFileInfo(myPath) myBaseName = myFileInfo.baseName() myRasterLayer = QgsRasterLayer(myPath, myBaseName) myMessage = "Raster not loaded: %s" % myPath assert myRasterLayer.isValid(), myMessage # crash on next line QgsMapLayerRegistry.instance().addMapLayers([myRasterLayer])
def loadLayers(theLayerList, theClearFlag=True): """Helper function to load layers as defined in a python list.""" # First unload any layers that may already be loaded if theClearFlag: for myLayer in QgsMapLayerRegistry.instance().mapLayers(): QgsMapLayerRegistry.instance().removeMapLayer(myLayer) # Now go ahead and load our layers myExposureLayerCount = 0 myHazardLayerCount = 0 myCanvasLayers = [] # Now create our new layers for myFile in theLayerList: # Extract basename and absolute path myBaseName, myExt = os.path.splitext(myFile) myPath = os.path.join(TESTDATA, myFile) myKeywordPath = myPath[:-4] + '.keywords' # Determine if layer is hazard or exposure myKeywords = read_keywords(myKeywordPath) msg = 'Could not read %s' % myKeywordPath assert myKeywords is not None, msg if myKeywords['category'] == 'hazard': myHazardLayerCount += 1 elif myKeywords['category'] == 'exposure': myExposureLayerCount += 1 # Create QGis Layer Instance if myExt in ['.asc', '.tif']: myLayer = QgsRasterLayer(myPath, myBaseName) elif myExt in ['.shp']: myLayer = QgsVectorLayer(myPath, myBaseName, 'ogr') else: myMessage = 'File %s had illegal extension' % myPath raise Exception(myMessage) myMessage = 'Layer "%s" is not valid' % str(myLayer.source()) assert myLayer.isValid(), myMessage # Add layer to the registry (that QGis knows about) QgsMapLayerRegistry.instance().addMapLayer(myLayer) # Create Map Canvas Layer Instance and add to list myCanvasLayers.append(QgsMapCanvasLayer(myLayer)) # Quickly add any existing CANVAS layers to our list first for myLayer in CANVAS.layers(): myCanvasLayers.append(QgsMapCanvasLayer(myLayer)) # now load all these layers in the CANVAS CANVAS.setLayerSet(myCanvasLayers) DOCK.getLayers() # Add MCL's to the CANVAS return myHazardLayerCount, myExposureLayerCount
def create_keyword_file(self, algorithm): """Create keyword file for the raster file created. Basically copy a template from keyword file in converter data and add extra keyword (usually a title) :param algorithm: Which re-sampling algorithm to use. valid options are 'nearest' (for nearest neighbour), 'invdist' (for inverse distance), 'average' (for moving average). Defaults to 'nearest' if not specified. Note that passing re-sampling alg parameters is currently not supported. If None is passed it will be replaced with 'nearest'. :type algorithm: str """ keyword_io = KeywordIO() classes = {} for item in earthquake_mmi_scale['classes']: classes[item['key']] = [ item['numeric_default_min'], item['numeric_default_max']] keywords = { 'hazard': hazard_earthquake['key'], 'hazard_category': hazard_category_single_event['key'], 'keyword_version': inasafe_keyword_version, 'layer_geometry': layer_geometry_raster['key'], 'layer_mode': layer_mode_continuous['key'], 'layer_purpose': layer_purpose_hazard['key'], 'continuous_hazard_unit': unit_mmi['key'], 'classification': earthquake_mmi_scale['key'], 'thresholds': classes } if self.algorithm_name: layer_path = os.path.join( self.output_dir, '%s-%s.tif' % ( self.output_basename, algorithm)) else: layer_path = os.path.join( self.output_dir, '%s.tif' % self.output_basename) # append title and source to the keywords file if len(self.title.strip()) == 0: keyword_title = self.output_basename else: keyword_title = self.title keywords['title'] = keyword_title hazard_layer = QgsRasterLayer(layer_path, keyword_title) if not hazard_layer.isValid(): raise InvalidLayerError() keyword_io.write_keywords(hazard_layer, keywords)
def CrossTab(raster1, raster2, vector1, diretorioOut, resolucao, campoID, weight111, weight112, weight121, weight122, weight199, weight299, weight399, weight499599): fileInfo1 = QFileInfo(raster1) path1 = fileInfo1.filePath() baseName1 = fileInfo1.baseName() layer1 = QgsRasterLayer(path1, baseName1) QgsMapLayerRegistry.instance().addMapLayer(layer1) if layer1.isValid() is True: print "Layer1 was loaded successfully!" else: print "Unable to read basename and file path - Your string is probably invalid" provider1 = layer1.dataProvider() extent1 = provider1.extent() rows1 = layer1.height() cols1 = layer1.width() block1 = provider1.block(1, extent1, cols1, rows1) fileInfo2 = QFileInfo(raster2) path2 = fileInfo2.filePath() baseName2 = fileInfo2.baseName() layer2 = QgsRasterLayer(path2, baseName2) QgsMapLayerRegistry.instance().addMapLayer(layer2) if layer2.isValid() is True: print "Layer2 was loaded successfully!" else: print "Unable to read basename and file path - Your string is probably invalid" provider2 = layer2.dataProvider() extent2 = provider2.extent() rows2 = layer2.height() cols2 = layer2.width() block2 = provider2.block(1, extent2, cols2, rows2) fileInfo3 = QFileInfo(vector1) path3 = fileInfo3.filePath() baseName3 = fileInfo3.baseName() layer3 = QgsVectorLayer("%s" % (vector1), "vector1", "ogr") QgsMapLayerRegistry.instance().addMapLayer(layer3) feats_count = layer3.featureCount() if layer3.isValid() is True: print "Layer3 was loaded successfully!" else: print "Unable to read basename and file path - Your string is probably invalid" valoresBGRI = [] valoresBGRIunicos = [] # lista de valores BGRI unicos for feature in layer3.getFeatures(): objectid = feature.attributes()[layer3.fieldNameIndex(campoID)] valoresBGRI.append(objectid) for v in valoresBGRI: if v not in valoresBGRIunicos: valoresBGRIunicos.append(v) a = len(valoresBGRIunicos) print a feats_count = layer3.featureCount() print feats_count valoresCLCunicos = [111, 112, 121, 122, 199, 299, 399, 499, 599] b = len(valoresCLCunicos) print b crossTabMatrix = [[0 for y in range(b + 1)] for x in range(a + 1)] for y in range(b): crossTabMatrix[0][y + 1] = valoresCLCunicos[y] for x in range(a): crossTabMatrix[x + 1][0] = valoresBGRIunicos[x] #print crossTabMatrix #crosstab for i in range(rows1): for j in range(cols1): cell_value1 = int(block1.value(i, j)) cell_value2 = int(block2.value(i, j)) for y in range(b): for x in range(a): if cell_value1 == crossTabMatrix[ x + 1][0] and cell_value2 == crossTabMatrix[0][y + 1]: crossTabMatrix[x + 1][y + 1] += 1 #print crossTabMatrix #exportar a tabulacao para csv csvfile = diretorioOut + r"\crosstab.csv" print csvfile with open(csvfile, "w") as output: writer = csv.writer(output, lineterminator='\n') writer.writerows(crossTabMatrix) # Adicionar campos para calculo (Campo1, Campo 2) shp_uri = vector1 shp = QgsVectorLayer(shp_uri, 'bgri', 'ogr') caps = shp.dataProvider().capabilities() if caps & QgsVectorDataProvider.AddAttributes: res = shp.dataProvider().addAttributes([ QgsField("E", QVariant.Double), QgsField("TOTAL", QVariant.Double) ]) #if caps & QgsVectorDataProvider.DeleteAttributes: # res = shp.dataProvider().deleteAttributes([0]) shp.updateFields() QgsMapLayerRegistry.instance().addMapLayer(shp) # Get input (csv) and target (Shapefile) layers csv_uri = 'file:///' + diretorioOut + r'/crosstab.csv?delimiter=,' print csv_uri csvlayer = QgsVectorLayer(csv_uri, "crosstab", "delimitedtext") QgsMapLayerRegistry.instance().addMapLayer(csvlayer) # Set properties for the join shpField = campoID csvField = '0_1' joinObject = QgsVectorJoinInfo() joinObject.joinLayerId = csvlayer.id() joinObject.joinFieldName = csvField joinObject.targetFieldName = shpField joinObject.memoryCache = True shp.addJoin(joinObject) # Calcular pesos, TOTAL e E # Update do campo TOTAL no shapefile resolucao2 = int(resolucao) * int(resolucao) expressionT = QgsExpression( "(crosstab_111_1+crosstab_112_1+crosstab_121_1+crosstab_122_1+crosstab_199_1+crosstab_299_1+crosstab_399_1+crosstab_499_1+crosstab_599_1)*{}" .format(resolucao2)) indexT = shp.fieldNameIndex("TOTAL") expressionT.prepare(shp.pendingFields()) shp.startEditing() for feature in shp.getFeatures(): valueT = expressionT.evaluate(feature) shp.changeAttributeValue(feature.id(), indexT, valueT) shp.commitChanges() # Update do campo E no shapefile expressionE = QgsExpression( "((crosstab_111_1*{})/TOTAL)*{}+((crosstab_112_1*{})/TOTAL)*{}+((crosstab_121_1*{})/TOTAL)*{}+((crosstab_122_1*{})/TOTAL)*{}+((crosstab_199_1*{})/TOTAL)*{}+((crosstab_299_1*{})/TOTAL)*{}+((crosstab_399_1*{})/TOTAL)*{}" .format(resolucao2, weight111, resolucao2, weight112, resolucao2, weight121, resolucao2, weight122, resolucao2, weight199, resolucao2, weight299, resolucao2, weight399)) indexE = shp.fieldNameIndex("E") expressionE.prepare(shp.pendingFields()) shp.startEditing() for feature in shp.getFeatures(): valueE = expressionE.evaluate(feature) shp.changeAttributeValue(feature.id(), indexE, valueE) shp.commitChanges()
def __add_images(images, description, outdir, msgbar, check, vrt=True, shown=True): if check.isChecked() and vrt: pan = images.pop('pan', None) # take out pan if len(images) > 1: # stack images in a VRT file if there are more than one image left vrtfile = os.path.join(outdir, description + '.vrt') # to sort in r/g/b/nir order here sort(images.keys, key=lambda k: rgbn[k]) _RGBN = {'red': 1, 'green': 2, 'blue': 3, 'nir': 4} images_keys_ordered = sorted(images.keys(), key=lambda k: _RGBN.get(k, 5)) filenames = [images[k] for k in images_keys_ordered ] # filenames list in RGBN order ds = gdal.BuildVRT( vrtfile, filenames, options=gdal.BuildVRTOptions(separate=True, resolution='highest')) for i, bn in enumerate(images_keys_ordered): b = ds.GetRasterBand(i + 1) b.SetDescription(bn) ds.FlushCache() ds = None if pan is None: # nothing to do anymore, add VRT file __add_images({'vrt': vrtfile}, description, outdir, msgbar, check, vrt=False) else: # VERY SLOW TO DO HERE (perhaps as ProcessingProvider?) # nbands = len(images) # if nbands > 2: # may be a setting here for pansharpening choice # pan_ds = gdal.Open(pan) # pansharpened_ds = gdal.CreatePansharpenedVRT(__pszXML(nbands), pan_ds.GetRasterBand(1), # [ds.GetRasterBand(i + 1) for i in range(nbands)]) # pansharpened_filename = os.path.join(outdir, description + '_pansharpened.vrt') # driver = gdal.GetDriverByName('VRT') # driver.CreateCopy(pansharpened_filename, pansharpened_ds, 0) # # add ALL # __add_images({'pansharpened': pansharpened_filename, # 'pan': pan, 'vrt': vrtfile}, description, outdir, msgbar, check, vrt=False, shown=False) # else: # # just add pan and vrt files __add_images({ 'pan': pan, 'vrt': vrtfile }, description, outdir, msgbar, check, vrt=False) else: # do not stack since there are not enough images assert pan is not None # 'pan' should be not 'None' here images.update({'pan': pan}) # restore pan __add_images(images, description, outdir, msgbar, check, vrt=False) else: for k in images.keys(): fn = images[k] name = os.path.basename(fn).split('.')[0] layer = QgsRasterLayer(fn, name) if layer.isValid(): QgsProject.instance().addMapLayer(layer) if not shown: QgsProject.instance().layerTreeRoot().findLayer( layer.id()).setItemVisibilityChecked(shown) msgbar.dismiss()
def testTransparency(self): myPath = os.path.join(unitTestDataPath('raster'), 'band1_float32_noct_epsg4326.tif') myFileInfo = QFileInfo(myPath) myBaseName = myFileInfo.baseName() myRasterLayer = QgsRasterLayer(myPath, myBaseName) myMessage = 'Raster not loaded: %s' % myPath assert myRasterLayer.isValid(), myMessage renderer = QgsSingleBandGrayRenderer(myRasterLayer.dataProvider(), 1) myRasterLayer.setRenderer(renderer) myRasterLayer.setContrastEnhancement( QgsContrastEnhancement.StretchToMinimumMaximum, QgsRasterMinMaxOrigin.MinMax) myContrastEnhancement = myRasterLayer.renderer().contrastEnhancement() # print ("myContrastEnhancement.minimumValue = %.17g" % # myContrastEnhancement.minimumValue()) # print ("myContrastEnhancement.maximumValue = %.17g" % # myContrastEnhancement.maximumValue()) # Unfortunately the minimum/maximum values calculated in C++ and Python # are slightly different (e.g. 3.3999999521443642e+38 x # 3.3999999521444001e+38) # It is not clear where the precision is lost. # We set the same values as C++. myContrastEnhancement.setMinimumValue(-3.3319999287625854e+38) myContrastEnhancement.setMaximumValue(3.3999999521443642e+38) #myType = myRasterLayer.dataProvider().dataType(1); #myEnhancement = QgsContrastEnhancement(myType); myTransparentSingleValuePixelList = [] rasterTransparency = QgsRasterTransparency() myTransparentPixel1 = \ QgsRasterTransparency.TransparentSingleValuePixel() myTransparentPixel1.min = -2.5840000772112106e+38 myTransparentPixel1.max = -1.0879999684602689e+38 myTransparentPixel1.percentTransparent = 50 myTransparentSingleValuePixelList.append(myTransparentPixel1) myTransparentPixel2 = \ QgsRasterTransparency.TransparentSingleValuePixel() myTransparentPixel2.min = 1.359999960575336e+37 myTransparentPixel2.max = 9.520000231087593e+37 myTransparentPixel2.percentTransparent = 70 myTransparentSingleValuePixelList.append(myTransparentPixel2) rasterTransparency.setTransparentSingleValuePixelList( myTransparentSingleValuePixelList) rasterRenderer = myRasterLayer.renderer() assert rasterRenderer rasterRenderer.setRasterTransparency(rasterTransparency) QgsProject.instance().addMapLayers([ myRasterLayer, ]) myMapSettings = QgsMapSettings() myMapSettings.setLayers([myRasterLayer]) myMapSettings.setExtent(myRasterLayer.extent()) myChecker = QgsRenderChecker() myChecker.setControlName("expected_raster_transparency") myChecker.setMapSettings(myMapSettings) myResultFlag = myChecker.runTest("raster_transparency_python") assert myResultFlag, "Raster transparency rendering test failed"
def exposed_people_stats(hazard, exposure, aggregation, fatality_rate): """Calculate the number of exposed people per MMI level per aggregation. Calculate the number of exposed people per MMI level per aggregation zone and prepare raster layer outputs. :param hazard: The earthquake raster layer. :type hazard: QgsRasterLayer :param exposure: The population raster layer. :type exposure: QgsVectorLayer :param aggregation: The aggregation layer. :type aggregation: QgsVectorLayer :param fatality_rate: The fatality rate to use. :type fatality_rate: function :return: A tuble with the exposed per MMI level par aggregation and the exposed raster. Tuple (mmi, agg_zone), value: number of exposed people :rtype: (dict, QgsRasterLayer) """ output_layer_name = earthquake_displaced['output_layer_name'] processing_step = earthquake_displaced['step_name'] exposed_raster_filename = unique_filename( prefix=output_layer_name, suffix='.tif') hazard_provider = hazard.dataProvider() extent = hazard.extent() width, height = hazard_provider.xSize(), hazard_provider.ySize() hazard_block = hazard_provider.block(1, extent, width, height) exposure_provider = exposure.dataProvider() exposure_block = exposure_provider.block(1, extent, width, height) agg_provider = aggregation.dataProvider() agg_block = agg_provider.block(1, extent, width, height) exposed = {} # key: tuple (mmi, agg_zone), value: number of exposed people exposed_array = make_array(width, height) classification_key = hazard.keywords['classification'] # walk through the rasters pixel by pixel and aggregate numbers # of people in the combination of hazard zones and aggregation zones for i in xrange(width * height): hazard_mmi = hazard_block.value(long(i)) people_count = exposure_block.value(long(i)) agg_zone_index = int(agg_block.value(long(i))) if hazard_mmi >= 2.0 and people_count >= 0.0: hazard_mmi = int(round(hazard_mmi)) mmi_fatalities = ( int(hazard_mmi * fatality_rate[hazard_mmi])) # rounding down mmi_displaced = ( (people_count - mmi_fatalities) * displacement_rate(hazard_mmi, classification_key)) key = (hazard_mmi, agg_zone_index) if key not in exposed: exposed[key] = 0 exposed[key] += people_count else: # If hazard is less than 2 or population is less than 0 mmi_displaced = -1 # We build a raster only for the aggregation area. if agg_zone_index > 0: exposed_array[i / width, i % width] = mmi_displaced else: exposed_array[i / width, i % width] = -1 # output raster data - e.g. displaced people array_to_raster(exposed_array, exposed_raster_filename, hazard) # I didn't find a way to do that with the QGIS API. data = gdal.Open(exposed_raster_filename, gdalconst.GA_Update) data.GetRasterBand(1).SetNoDataValue(-1) del data exposed_raster = QgsRasterLayer(exposed_raster_filename, 'exposed', 'gdal') assert exposed_raster.isValid() exposed_raster.keywords = dict(exposure.keywords) exposed_raster.keywords['layer_purpose'] = ( layer_purpose_exposure_summary['key']) exposed_raster.keywords['title'] = processing_step exposed_raster.keywords['exposure_keywords'] = dict(exposure.keywords) exposed_raster.keywords['hazard_keywords'] = dict(hazard.keywords) exposed_raster.keywords['aggregation_keywords'] = dict( aggregation.keywords) return exposed, exposed_raster
def add_layer_to_map(ds): layers4add = [] if ds.type.lower() == KNOWN_DRIVERS.TMS.lower(): if ds.alt_tms_urls: tms_url = ds.alt_tms_urls[random.randint(0, len(ds.alt_tms_urls) - 1)] else: tms_url = ds.tms_url if PluginSettings.use_native_tms(): # add version check service_url = tms_url.replace("=", "%3D").replace("&", "%26") if ds.tms_y_origin_top is not None and ds.tms_y_origin_top == False: service_url = service_url.replace('{y}', '{-y}') qgis_tms_uri = 'type=xyz&zmin={0}&zmax={1}&url={2}'.format( ds.tms_zmin or TileDefaultSettings.ZMIN, ds.tms_zmax or TileDefaultSettings.ZMAX, service_url) layer = QgsRasterLayer(qgis_tms_uri, tr(ds.alias), KNOWN_DRIVERS.WMS.lower()) ProjectionHelper.set_tile_layer_proj(layer, ds.tms_epsg_crs_id, ds.tms_postgis_crs_id, ds.tms_custom_proj) layers4add.append(layer) else: service_info = TileServiceInfo(tr(ds.alias), ds.copyright_text, tms_url) service_info.zmin = ds.tms_zmin or service_info.zmin service_info.zmax = ds.tms_zmax or service_info.zmax if ds.tms_y_origin_top is not None: service_info.yOriginTop = ds.tms_y_origin_top service_info.epsg_crs_id = ds.tms_epsg_crs_id service_info.postgis_crs_id = ds.tms_postgis_crs_id service_info.custom_proj = ds.tms_custom_proj if ds.tms_tile_ranges is not None: # needs try block & checks that keys are integers etc.. service_info.tile_ranges = ast.literal_eval(ds.tms_tile_ranges) if ds.tms_tsize1 is not None: service_info.tsize1 = ds.tms_tsize1 if ds.tms_origin_x is not None: service_info.originX = ds.tms_origin_x if ds.tms_origin_y is not None: service_info.originY = ds.tms_origin_y layer = TileLayer(service_info, False) layers4add.append(layer) if ds.type.lower() == KNOWN_DRIVERS.GDAL.lower(): layer = QgsRasterLayer(ds.gdal_source_file, tr(ds.alias)) layers4add.append(layer) if ds.type.lower() == KNOWN_DRIVERS.WMS.lower(): qgis_wms_uri = u'' if ds.wms_params: qgis_wms_uri += ds.wms_params if ds.wms_layers: layers = ds.wms_layers.split(',') if layers: if ds.wms_turn_over: layers.reverse() qgis_wms_uri += '&layers=' + '&layers='.join( layers) + '&styles=' * len(layers) qgis_wms_uri += '&url=' + ds.wms_url + "?" + ds.wms_url_params.replace( "=", "%3D").replace("&", "%26") layer = QgsRasterLayer(qgis_wms_uri, tr(ds.alias), KNOWN_DRIVERS.WMS.lower()) layers4add.append(layer) if ds.type.lower() == KNOWN_DRIVERS.WFS.lower(): qgis_wfs_uri_base = ds.wfs_url if ds.wfs_params is not None: qgis_wfs_uri_base += ds.wfs_params o = urlparse.urlparse(qgis_wfs_uri_base) request_attrs = dict(urlparse.parse_qsl(o.query)) new_request_attrs = {} for k, v in request_attrs.items(): new_request_attrs[k.upper()] = v if ds.wfs_epsg is not None: new_request_attrs['SRSNAME'] = "EPSG:{0}".format(ds.wfs_epsg) layers = [] if len(ds.wfs_layers) > 0: layers.extend(ds.wfs_layers) else: layers_str = request_attrs.get('TYPENAME', '') layers.extend(layers_str.split()) for layer_name in layers: new_request_attrs['TYPENAME'] = layer_name url_parts = list(o) url_parts[4] = "&".join( ["%s=%s" % (k, v) for k, v in new_request_attrs.items()]) qgis_wfs_uri = urlparse.urlunparse(url_parts) layer = QgsVectorLayer(qgis_wfs_uri, "%s - %s" % (tr(ds.alias), layer_name), "WFS") layers4add.append(layer) if ds.type.lower() == KNOWN_DRIVERS.GEOJSON.lower(): layer = QgsVectorLayer(ds.geojson_url, tr(ds.alias), "ogr") layers4add.append(layer) for layer in layers4add: if not layer.isValid(): error_message = tr( 'Layer %s can\'t be added to the map!') % ds.alias iface.messageBar().pushMessage(tr('Error'), error_message, level=QGisMessageBarLevel.Critical) QgsMessageLog.logMessage(error_message, level=QGisMessageLogLevel.Critical) else: # Set attribs layer.setAttribution(ds.copyright_text) layer.setAttributionUrl(ds.copyright_link) # Insert layer toc_root = QgsProject.instance().layerTreeRoot() selected_node = iface.layerTreeView().currentNode() if selected_node.nodeType() == selected_node.NodeGroup: toc_root = selected_node if ds.type.lower() in (KNOWN_DRIVERS.WMS.lower(), KNOWN_DRIVERS.TMS.lower()): position = len( toc_root.children()) # Insert to bottom if wms\tms else: position = 0 # insert to top addMapLayer(layer, False) toc_root.insertLayer(position, layer) # Save link service_layers.append(layer) # Set OTF CRS Transform for map if PluginSettings.enable_otf_3857( ) and ds.type == KNOWN_DRIVERS.TMS: if hasattr(iface.mapCanvas(), "setCrsTransformEnabled"): # Need for QGIS2. In QGIS3 CRS transformation is always enabled iface.mapCanvas().setCrsTransformEnabled(True) iface.mapCanvas().setDestinationCrs(TileLayer.CRS_3857)
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') # Create a zonal statistics object, automatically saved to file band = 1 # raster band with the data we are after zonalstats = QgsZonalStatistics(layer_polygon, # shapefile layer_raster, # .tif 'elev_', # prefix for the new column added to the shapefile band, # raster band we're interested in stats=QgsZonalStatistics.Mean).calculateStatistics(None) # Clean memory qgs.exitQgis()
def testBilinearResample(self): with tempfile.TemporaryDirectory() as dest_dir: path = os.path.join(unitTestDataPath(), 'landsat.tif') dest_path = shutil.copy(path, os.path.join(dest_dir, 'landsat.tif')) raster_layer = QgsRasterLayer(dest_path, 'test') raster_layer.dataProvider().setNoDataValue(1, -9999) self.assertTrue(raster_layer.isValid()) extent = QgsRectangle(785994.37761193525511771, 3346249.2209800467826426, 786108.49096253968309611, 3346362.94137834152206779) renderer = QgsSingleBandGrayRenderer(raster_layer.dataProvider(), 1) filter = QgsRasterResampleFilter(renderer) # default (nearest neighbour) resampling block = filter.block(1, extent, 2, 2) self.checkBlockContents(block, [[124, 127], [125, 126]]) block = filter.block(1, extent, 4, 4) self.checkBlockContents(block, [[124, 124, 127, 127], [124, 124, 127, 127], [125, 125, 126, 126], [125, 125, 126, 126]] ) block = filter.block(1, extent, 8, 8) self.checkBlockContents(block, [[124, 124, 124, 124, 127, 127, 127, 127], [124, 124, 124, 124, 127, 127, 127, 127], [124, 124, 124, 124, 127, 127, 127, 127], [124, 124, 124, 124, 127, 127, 127, 127], [125, 125, 125, 125, 126, 126, 126, 126], [125, 125, 125, 125, 126, 126, 126, 126], [125, 125, 125, 125, 126, 126, 126, 126], [125, 125, 125, 125, 126, 126, 126, 126]]) # with resampling filter.setZoomedInResampler(QgsBilinearRasterResampler()) block = filter.block(1, extent, 2, 2) self.checkBlockContents(block, [[124, 127], [125, 126]]) block = filter.block(1, extent, 4, 4) self.checkBlockContents(block, [[124, 124, 126, 126], [124, 124, 125, 126], [124, 124, 125, 126], [125, 125, 125, 126]] ) block = filter.block(1, extent, 8, 8) self.checkBlockContents(block, [[124, 124, 124, 125, 125, 126, 126, 126], [124, 124, 124, 125, 125, 126, 126, 126], [124, 124, 124, 124, 125, 125, 126, 126], [124, 124, 124, 124, 125, 125, 126, 126], [124, 124, 124, 124, 125, 125, 126, 126], [124, 124, 124, 124, 125, 125, 126, 126], [125, 125, 125, 125, 125, 125, 126, 126], [125, 125, 125, 125, 125, 125, 126, 126]] ) # with oversampling extent = QgsRectangle(785878.92593475803732872, 3346136.27493690419942141, 786223.56509550288319588, 3346477.7564090033993125) block = filter.block(1, extent, 2, 2) self.checkBlockContents(block, [[127, 126], [125, 126]]) block = filter.block(1, extent, 4, 4) self.checkBlockContents(block, [[125, 127, 127, 127], [126, 127, 127, 126], [125, 126, 126, 126], [127, 125, 125, 125]] ) block = filter.block(1, extent, 8, 8) self.checkBlockContents(block, [[126, 126, 126, 126, 125, 125, 125, 126], [126, 126, 125, 125, 125, 126, 126, 126], [126, 125, 124, 124, 125, 126, 126, 126], [126, 125, 124, 124, 125, 126, 126, 126], [125, 125, 124, 124, 124, 126, 126, 126], [125, 125, 125, 125, 125, 126, 126, 126], [125, 125, 125, 125, 125, 126, 126, 126], [125, 125, 126, 126, 125, 125, 125, 125]] ) filter.setMaxOversampling(2) block = filter.block(1, extent, 2, 2) self.checkBlockContents(block, [[127, 126], [125, 126]]) block = filter.block(1, extent, 4, 4) self.checkBlockContents(block, [[125, 127, 127, 127], [126, 127, 127, 126], [125, 126, 126, 126], [127, 125, 125, 125]] ) block = filter.block(1, extent, 8, 8) self.checkBlockContents(block, [[126, 126, 126, 126, 125, 125, 125, 126], [126, 126, 125, 125, 125, 126, 126, 126], [126, 125, 124, 124, 125, 126, 126, 126], [126, 125, 124, 124, 125, 126, 126, 126], [125, 125, 124, 124, 124, 126, 126, 126], [125, 125, 125, 125, 125, 126, 126, 126], [125, 125, 125, 125, 125, 126, 126, 126], [125, 125, 126, 126, 125, 125, 125, 125]] ) filter.setMaxOversampling(4) block = filter.block(1, extent, 2, 2) self.checkBlockContents(block, [[127, 126], [125, 126]]) block = filter.block(1, extent, 4, 4) self.checkBlockContents(block, [[125, 127, 127, 127], [126, 127, 127, 126], [125, 126, 126, 126], [127, 125, 125, 125]] ) block = filter.block(1, extent, 8, 8) self.checkBlockContents(block, [[126, 126, 126, 126, 125, 125, 125, 126], [126, 126, 125, 125, 125, 126, 126, 126], [126, 125, 124, 124, 125, 126, 126, 126], [126, 125, 124, 124, 125, 126, 126, 126], [125, 125, 124, 124, 124, 126, 126, 126], [125, 125, 125, 125, 125, 126, 126, 126], [125, 125, 125, 125, 125, 126, 126, 126], [125, 125, 126, 126, 125, 125, 125, 125]] )
def test_project_roundtrip(self): """Tests that a project with bad layers can be saved and restored""" p = QgsProject.instance() temp_dir = QTemporaryDir() for ext in ('shp', 'dbf', 'shx', 'prj'): copyfile(os.path.join(TEST_DATA_DIR, 'lines.%s' % ext), os.path.join(temp_dir.path(), 'lines.%s' % ext)) copyfile( os.path.join(TEST_DATA_DIR, 'raster', 'band1_byte_ct_epsg4326.tif'), os.path.join(temp_dir.path(), 'band1_byte_ct_epsg4326.tif')) copyfile( os.path.join(TEST_DATA_DIR, 'raster', 'band1_byte_ct_epsg4326.tif'), os.path.join(temp_dir.path(), 'band1_byte_ct_epsg4326_copy.tif')) l = QgsVectorLayer(os.path.join(temp_dir.path(), 'lines.shp'), 'lines', 'ogr') self.assertTrue(l.isValid()) rl = QgsRasterLayer( os.path.join(temp_dir.path(), 'band1_byte_ct_epsg4326.tif'), 'raster', 'gdal') self.assertTrue(rl.isValid()) rl_copy = QgsRasterLayer( os.path.join(temp_dir.path(), 'band1_byte_ct_epsg4326_copy.tif'), 'raster_copy', 'gdal') self.assertTrue(rl_copy.isValid()) self.assertTrue(p.addMapLayers([l, rl, rl_copy])) # Save project project_path = os.path.join(temp_dir.path(), 'project.qgs') self.assertTrue(p.write(project_path)) # Re-load the project, checking for the XML properties p.removeAllMapLayers() self.assertTrue(p.read(project_path)) vector = list(p.mapLayersByName('lines'))[0] raster = list(p.mapLayersByName('raster'))[0] raster_copy = list(p.mapLayersByName('raster_copy'))[0] self.assertTrue(vector.originalXmlProperties() != '') self.assertTrue(raster.originalXmlProperties() != '') self.assertTrue(raster_copy.originalXmlProperties() != '') # Test setter raster.setOriginalXmlProperties('pippo') self.assertEqual(raster.originalXmlProperties(), 'pippo') # Now create and invalid project: bad_project_path = os.path.join(temp_dir.path(), 'project_bad.qgs') with open(project_path, 'r') as infile: with open(bad_project_path, 'w+') as outfile: outfile.write(infile.read().replace( './lines.shp', './lines-BAD_SOURCE.shp').replace( 'band1_byte_ct_epsg4326_copy.tif', 'band1_byte_ct_epsg4326_copy-BAD_SOURCE.tif')) # Load the bad project p.removeAllMapLayers() self.assertTrue(p.read(bad_project_path)) # Check layer is invalid vector = list(p.mapLayersByName('lines'))[0] raster = list(p.mapLayersByName('raster'))[0] raster_copy = list(p.mapLayersByName('raster_copy'))[0] self.assertIsNotNone(vector.dataProvider()) self.assertIsNotNone(raster.dataProvider()) self.assertIsNotNone(raster_copy.dataProvider()) self.assertFalse(vector.isValid()) self.assertFalse(raster_copy.isValid()) # Try a getFeatures self.assertEqual([f for f in vector.getFeatures()], []) self.assertTrue(raster.isValid()) self.assertEqual(vector.providerType(), 'ogr') # Save the project bad_project_path2 = os.path.join(temp_dir.path(), 'project_bad2.qgs') p.write(bad_project_path2) # Re-save the project, with fixed paths good_project_path = os.path.join(temp_dir.path(), 'project_good.qgs') with open(bad_project_path2, 'r') as infile: with open(good_project_path, 'w+') as outfile: outfile.write(infile.read().replace( './lines-BAD_SOURCE.shp', './lines.shp').replace( 'band1_byte_ct_epsg4326_copy-BAD_SOURCE.tif', 'band1_byte_ct_epsg4326_copy.tif')) # Load the good project p.removeAllMapLayers() self.assertTrue(p.read(good_project_path)) # Check layer is valid vector = list(p.mapLayersByName('lines'))[0] raster = list(p.mapLayersByName('raster'))[0] raster_copy = list(p.mapLayersByName('raster_copy'))[0] self.assertTrue(vector.isValid()) self.assertTrue(raster.isValid()) self.assertTrue(raster_copy.isValid())
class TestQgsMapLayerAction(unittest.TestCase): def __init__(self, methodName): """Run once on class initialization.""" unittest.TestCase.__init__(self, methodName) self.vector_layer = QgsVectorLayer( "Point?field=fldtxt:string&field=fldint:integer&field=flddate:datetime", "test_layer", "memory") assert self.vector_layer.isValid() self.vector_layer2 = QgsVectorLayer( "Point?field=fldtxt:string&field=fldint:integer&field=flddate:datetime", "test_layer", "memory") assert self.vector_layer2.isValid() raster_path = os.path.join(unitTestDataPath(), 'landsat.tif') self.raster_layer = QgsRasterLayer(raster_path, 'raster') assert self.raster_layer.isValid() def testCanRunUsingLayer(self): """ Test that actions correctly indicate when they can run for a layer """ action_all_layers = QgsMapLayerAction('action1', None) self.assertTrue(action_all_layers.canRunUsingLayer(None)) self.assertTrue(action_all_layers.canRunUsingLayer(self.vector_layer)) self.assertTrue(action_all_layers.canRunUsingLayer(self.raster_layer)) action_vector_layers_only = QgsMapLayerAction('action2', None, QgsMapLayer.VectorLayer) self.assertFalse(action_vector_layers_only.canRunUsingLayer(None)) self.assertTrue( action_vector_layers_only.canRunUsingLayer(self.vector_layer)) self.assertFalse( action_vector_layers_only.canRunUsingLayer(self.raster_layer)) action_raster_layers_only = QgsMapLayerAction('action3', None, QgsMapLayer.RasterLayer) self.assertFalse(action_raster_layers_only.canRunUsingLayer(None)) self.assertFalse( action_raster_layers_only.canRunUsingLayer(self.vector_layer)) self.assertTrue( action_raster_layers_only.canRunUsingLayer(self.raster_layer)) action_specific_layer_only = QgsMapLayerAction('action4', None, self.vector_layer) self.assertFalse(action_specific_layer_only.canRunUsingLayer(None)) self.assertTrue( action_specific_layer_only.canRunUsingLayer(self.vector_layer)) self.assertFalse( action_specific_layer_only.canRunUsingLayer(self.vector_layer2)) self.assertFalse( action_specific_layer_only.canRunUsingLayer(self.raster_layer)) action_specific_raster_layer_only = QgsMapLayerAction( 'action4', None, self.raster_layer) self.assertFalse( action_specific_raster_layer_only.canRunUsingLayer(None)) self.assertFalse( action_specific_raster_layer_only.canRunUsingLayer( self.vector_layer)) self.assertFalse( action_specific_raster_layer_only.canRunUsingLayer( self.vector_layer2)) self.assertTrue( action_specific_raster_layer_only.canRunUsingLayer( self.raster_layer)) action_editable_layer_only = QgsMapLayerAction( 'action1', None, flags=QgsMapLayerAction.EnabledOnlyWhenEditable) self.assertFalse(action_editable_layer_only.canRunUsingLayer(None)) self.assertFalse( action_editable_layer_only.canRunUsingLayer(self.vector_layer)) self.assertFalse( action_editable_layer_only.canRunUsingLayer(self.vector_layer2)) self.assertFalse( action_editable_layer_only.canRunUsingLayer(self.raster_layer)) self.vector_layer.startEditing() self.assertFalse(action_editable_layer_only.canRunUsingLayer(None)) self.assertTrue( action_editable_layer_only.canRunUsingLayer(self.vector_layer)) self.assertFalse( action_editable_layer_only.canRunUsingLayer(self.vector_layer2)) self.assertFalse( action_editable_layer_only.canRunUsingLayer(self.raster_layer)) self.vector_layer.commitChanges() self.assertFalse(action_editable_layer_only.canRunUsingLayer(None)) self.assertFalse( action_editable_layer_only.canRunUsingLayer(self.vector_layer)) self.assertFalse( action_editable_layer_only.canRunUsingLayer(self.vector_layer2)) self.assertFalse( action_editable_layer_only.canRunUsingLayer(self.raster_layer))
class ShakemapConverterDialog(QDialog, FORM_CLASS): """Importer for shakemap grid.xml files.""" def __init__(self, parent=None, iface=None, dock_widget=None): """Constructor for the dialog. Show the grid converter dialog. :param parent: parent - widget to use as parent. :type parent: QWidget :param iface: QGIS QGisAppInterface instance. :type iface: QGisAppInterface :param dock_widget: Dock widget instance. :type dock_widget: Dock """ QDialog.__init__(self, parent) self.parent = parent self.iface = iface self.dock_widget = dock_widget self.setupUi(self) self.setWindowTitle( self.tr('InaSAFE %s Shakemap Converter' % get_version())) self.warning_text = set() self.on_input_path_textChanged() self.on_output_path_textChanged() self.update_warning() self.output_layer = None # Event register # noinspection PyUnresolvedReferences self.use_output_default.toggled.connect(self.get_output_from_input) # noinspection PyUnresolvedReferences self.input_path.textChanged.connect(self.on_input_path_textChanged) # noinspection PyUnresolvedReferences self.output_path.textChanged.connect(self.on_output_path_textChanged) self.load_result.clicked.connect(self.load_result_toggled) # Set up things for context help self.help_button = self.button_box.button(QtGui.QDialogButtonBox.Help) # Allow toggling the help button self.help_button.setCheckable(True) self.help_button.toggled.connect(self.help_toggled) self.main_stacked_widget.setCurrentIndex(1) self.update_warning() # noinspection PyPep8Naming def on_output_path_textChanged(self): """Action when output file name is changed.""" output_path = self.output_path.text() output_not_xml_msg = self.tr('output file is not .tif') if output_path and not output_path.endswith('.tif'): self.warning_text.add(output_not_xml_msg) elif output_path and output_not_xml_msg in self.warning_text: self.warning_text.remove(output_not_xml_msg) self.update_warning() # noinspection PyPep8Naming def on_input_path_textChanged(self): """Action when input file name is changed.""" input_path = self.input_path.text() input_not_grid_msg = self.tr('input file is not .xml') if input_path and not input_path.endswith('.xml'): self.warning_text.add(input_not_grid_msg) elif input_path and input_not_grid_msg in self.warning_text: self.warning_text.remove(input_not_grid_msg) if self.use_output_default.isChecked(): self.get_output_from_input() self.update_warning() def update_warning(self): """Update warning message and enable/disable Ok button.""" if len(self.warning_text) == 0: self.button_box.button(QDialogButtonBox.Ok).setEnabled(True) else: self.button_box.button(QDialogButtonBox.Ok).setEnabled(False) header = html_header() footer = html_footer() string = header heading = m.Heading(self.tr('Shakemap Grid Importer'), **INFO_STYLE) tips = m.BulletedList() message = m.Message() message.add(heading) for warning in self.warning_text: tips.add(warning) message.add(tips) string += message.to_html() string += footer self.info_web_view.setHtml(string) def get_output_from_input(self): """Create default output location based on input location.""" input_path = self.input_path.text() if input_path.endswith('.xml'): output_path = input_path[:-3] + 'tif' elif input_path == '': output_path = '' else: last_dot = input_path.rfind('.') if last_dot == -1: output_path = '' else: output_path = input_path[:last_dot + 1] + 'tif' self.output_path.setText(output_path) def accept(self): """Handler for when OK is clicked.""" input_path = self.input_path.text() input_title = self.line_edit_title.text() input_source = self.line_edit_source.text() output_path = self.output_path.text() if not output_path.endswith('.tif'): # noinspection PyArgumentList,PyCallByClass,PyTypeChecker QMessageBox.warning(self, self.tr('InaSAFE'), (self.tr('Output file name must be tif file'))) if not os.path.exists(input_path): # noinspection PyArgumentList,PyCallByClass,PyTypeChecker QMessageBox.warning(self, self.tr('InaSAFE'), (self.tr('Input file does not exist'))) return if self.nearest_mode.isChecked(): algorithm = 'nearest' else: algorithm = 'invdist' QtGui.qApp.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor)) file_name = convert_mmi_data(input_path, input_title, input_source, output_path, algorithm=algorithm, algorithm_filename_flag=True) # reclassify raster file_info = QFileInfo(file_name) base_name = file_info.baseName() self.output_layer = QgsRasterLayer(file_name, base_name) self.output_layer.keywords = KeywordIO.read_keywords(self.output_layer) self.output_layer.keywords['classification'] = ( earthquake_mmi_scale['key']) keywords = self.output_layer.keywords if self.output_layer.isValid(): self.output_layer = reclassify(self.output_layer, overwrite_input=True) KeywordIO.write_keywords(self.output_layer, keywords) else: LOGGER.debug("Failed to load") QtGui.qApp.restoreOverrideCursor() if self.load_result.isChecked(): # noinspection PyTypeChecker mmi_ramp_roman(self.output_layer) self.output_layer.saveDefaultStyle() if not self.output_layer.isValid(): LOGGER.debug("Failed to load") else: # noinspection PyArgumentList QgsMapLayerRegistry.instance().addMapLayer(self.output_layer) iface.zoomToActiveLayer() if (self.keyword_wizard_checkbox.isChecked() and self.keyword_wizard_checkbox.isEnabled()): self.launch_keyword_wizard() self.done(self.Accepted) @pyqtSignature('') # prevents actions being handled twice def on_open_input_tool_clicked(self): """Autoconnect slot activated when open input tool button is clicked. """ # noinspection PyCallByClass,PyTypeChecker filename = QFileDialog.getOpenFileName( self, self.tr('Input file'), 'grid.xml', self.tr('Raw grid file (*.xml)')) self.input_path.setText(filename) @pyqtSignature('') # prevents actions being handled twice def on_open_output_tool_clicked(self): """Autoconnect slot activated when open output tool button is clicked. """ # noinspection PyCallByClass,PyTypeChecker filename = QFileDialog.getSaveFileName(self, self.tr('Output file'), 'grid.tif', self.tr('Raster file (*.tif)')) self.output_path.setText(filename) def load_result_toggled(self): """Function that perform action when load_result checkbox is clicked. """ self.keyword_wizard_checkbox.setEnabled(self.load_result.isChecked()) @pyqtSlot() @pyqtSignature('bool') # prevents actions being handled twice def help_toggled(self, flag): """Show or hide the help tab in the stacked widget. .. versionadded: 3.2.1 :param flag: Flag indicating whether help should be shown or hidden. :type flag: bool """ if flag: self.help_button.setText(self.tr('Hide Help')) self.show_help() else: self.help_button.setText(self.tr('Show Help')) self.hide_help() def hide_help(self): """Hide the usage info from the user. .. versionadded: 3.2.1 """ self.main_stacked_widget.setCurrentIndex(1) def show_help(self): """Show usage info to the user.""" # Read the header and footer html snippets self.main_stacked_widget.setCurrentIndex(0) header = html_header() footer = html_footer() string = header message = shakemap_converter_help() string += message.to_html() string += footer self.help_web_view.setHtml(string) def launch_keyword_wizard(self): """Launch keyword creation wizard.""" # make sure selected layer is the output layer if self.iface.activeLayer() != self.output_layer: return # launch wizard dialog keyword_wizard = WizardDialog(self.iface.mainWindow(), self.iface, self.dock_widget) keyword_wizard.set_keywords_creation_mode(self.output_layer) keyword_wizard.exec_() # modal
def testPaletted(self): """ test paletted raster renderer with raster with color table""" path = os.path.join(unitTestDataPath('raster'), 'with_color_table.tif') info = QFileInfo(path) base_name = info.baseName() layer = QgsRasterLayer(path, base_name) self.assertTrue(layer.isValid(), 'Raster not loaded: {}'.format(path)) renderer = QgsPalettedRasterRenderer(layer.dataProvider(), 1, [ QgsPalettedRasterRenderer.Class(1, QColor(0, 255, 0), 'class 2'), QgsPalettedRasterRenderer.Class(3, QColor(255, 0, 0), 'class 1') ]) self.assertEqual(renderer.nColors(), 2) self.assertEqual(renderer.usesBands(), [1]) # test labels self.assertEqual(renderer.label(1), 'class 2') self.assertEqual(renderer.label(3), 'class 1') self.assertFalse(renderer.label(101)) # test legend symbology - should be sorted by value legend = renderer.legendSymbologyItems() self.assertEqual(legend[0][0], 'class 2') self.assertEqual(legend[1][0], 'class 1') self.assertEqual(legend[0][1].name(), '#00ff00') self.assertEqual(legend[1][1].name(), '#ff0000') # test retrieving classes classes = renderer.classes() self.assertEqual(classes[0].value, 1) self.assertEqual(classes[1].value, 3) self.assertEqual(classes[0].label, 'class 2') self.assertEqual(classes[1].label, 'class 1') self.assertEqual(classes[0].color.name(), '#00ff00') self.assertEqual(classes[1].color.name(), '#ff0000') # test set label # bad index renderer.setLabel(1212, 'bad') renderer.setLabel(3, 'new class') self.assertEqual(renderer.label(3), 'new class') # color ramp r = QgsLimitedRandomColorRamp(5) renderer.setSourceColorRamp(r) self.assertEqual(renderer.sourceColorRamp().type(), 'random') self.assertEqual(renderer.sourceColorRamp().count(), 5) # clone new_renderer = renderer.clone() classes = new_renderer.classes() self.assertEqual(classes[0].value, 1) self.assertEqual(classes[1].value, 3) self.assertEqual(classes[0].label, 'class 2') self.assertEqual(classes[1].label, 'new class') self.assertEqual(classes[0].color.name(), '#00ff00') self.assertEqual(classes[1].color.name(), '#ff0000') self.assertEqual(new_renderer.sourceColorRamp().type(), 'random') self.assertEqual(new_renderer.sourceColorRamp().count(), 5) # write to xml and read doc = QDomDocument('testdoc') elem = doc.createElement('qgis') renderer.writeXml(doc, elem) restored = QgsPalettedRasterRenderer.create( elem.firstChild().toElement(), layer.dataProvider()) self.assertTrue(restored) self.assertEqual(restored.usesBands(), [1]) classes = restored.classes() self.assertTrue(classes) self.assertEqual(classes[0].value, 1) self.assertEqual(classes[1].value, 3) self.assertEqual(classes[0].label, 'class 2') self.assertEqual(classes[1].label, 'new class') self.assertEqual(classes[0].color.name(), '#00ff00') self.assertEqual(classes[1].color.name(), '#ff0000') self.assertEqual(restored.sourceColorRamp().type(), 'random') self.assertEqual(restored.sourceColorRamp().count(), 5) # render test layer.setRenderer(renderer) ms = QgsMapSettings() ms.setLayers([layer]) ms.setExtent(layer.extent()) checker = QgsRenderChecker() checker.setControlName("expected_paletted_renderer") checker.setMapSettings(ms) self.assertTrue(checker.runTest("expected_paletted_renderer"), "Paletted rendering test failed")
def testWriteSld(self): """Test SLD generation for the XMLS fields geneerated at RasterLayer level and not to the deeper renderer level.""" myPath = os.path.join(unitTestDataPath(), 'landsat.tif') myFileInfo = QFileInfo(myPath) myBaseName = myFileInfo.baseName() myRasterLayer = QgsRasterLayer(myPath, myBaseName) myMessage = 'Raster not loaded: %s' % myPath assert myRasterLayer.isValid(), myMessage # do generic export with default layer values dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = root.elementsByTagName('sld:LayerFeatureConstraints') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() elements = element.elementsByTagName('sld:FeatureTypeConstraint') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() elements = root.elementsByTagName('sld:UserStyle') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() name = element.firstChildElement('sld:Name') self.assertFalse(name.isNull()) self.assertEqual(name.text(), 'landsat') abstract = element.firstChildElement('sld:Abstract') self.assertTrue(abstract.isNull()) title = element.firstChildElement('sld:Title') self.assertTrue(title.isNull()) featureTypeStyle = element.firstChildElement('sld:FeatureTypeStyle') self.assertFalse(featureTypeStyle.isNull()) rule = featureTypeStyle.firstChildElement('sld:Rule') self.assertFalse(rule.isNull()) temp = rule.firstChildElement('sld:MinScaleDenominator') self.assertTrue(temp.isNull()) temp = rule.firstChildElement('sld:MaxScaleDenominator') self.assertTrue(temp.isNull()) rasterSymbolizer = rule.firstChildElement('sld:RasterSymbolizer') self.assertFalse(rule.isNull()) vendorOptions = rasterSymbolizer.elementsByTagName('sld:VendorOption') self.assertTrue(vendorOptions.size() == 0) # set no default values and check exported sld myRasterLayer.setName('') myRasterLayer.setAbstract('fake') myRasterLayer.setTitle('fake') dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = root.elementsByTagName('sld:LayerFeatureConstraints') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() elements = element.elementsByTagName('sld:FeatureTypeConstraint') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() elements = root.elementsByTagName('sld:UserStyle') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() # no generated if empty name = element.firstChildElement('sld:Name') self.assertTrue(name.isNull()) # generated if not empty abstract = element.firstChildElement('sld:Abstract') self.assertFalse(abstract.isNull()) self.assertEqual(abstract.text(), 'fake') title = element.firstChildElement('sld:Title') self.assertFalse(title.isNull()) self.assertEqual(title.text(), 'fake') # if setScaleBasedVisibility is true print scales myRasterLayer.setScaleBasedVisibility(True) myRasterLayer.setMaximumScale(0.0001) myRasterLayer.setMinimumScale(0.01) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:Rule') self.assertEqual(len(elements), 1) rule = elements.at(0).toElement() self.assertFalse(rule.isNull()) temp = rule.firstChildElement('sld:MinScaleDenominator') self.assertFalse(temp.isNull()) self.assertEqual(temp.text(), '0.0001') temp = rule.firstChildElement('sld:MaxScaleDenominator') self.assertFalse(temp.isNull()) self.assertEqual(temp.text(), '0.01') # check non default hueSaturationFilter values hue = myRasterLayer.hueSaturationFilter() hue.setGrayscaleMode(QgsHueSaturationFilter.GrayscaleLightness) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'grayScale', 'lightness') hue = myRasterLayer.hueSaturationFilter() hue.setGrayscaleMode(QgsHueSaturationFilter.GrayscaleLuminosity) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'grayScale', 'luminosity') hue = myRasterLayer.hueSaturationFilter() hue.setGrayscaleMode(QgsHueSaturationFilter.GrayscaleAverage) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'grayScale', 'average') hue = myRasterLayer.hueSaturationFilter() hue.setGrayscaleMode(QgsHueSaturationFilter.GrayscaleOff) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'grayScale', None) # manage colorize vendorOption tags hue = myRasterLayer.hueSaturationFilter() hue.setColorizeOn(True) hue.setColorizeStrength(50) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'colorizeOn', '1') self.assertVendorOption(element, 'colorizeRed', '255') self.assertVendorOption(element, 'colorizeGreen', '128') self.assertVendorOption(element, 'colorizeBlue', '128') self.assertVendorOption(element, 'colorizeStrength', '0.5') self.assertVendorOption(element, 'saturation', '0.498039') # other hue non default values, no colorize and saturation = 0 hue = myRasterLayer.hueSaturationFilter() hue.setColorizeOn(False) hue.setSaturation(0) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'colorizeOn', None) self.assertVendorOption(element, 'colorizeRed', None) self.assertVendorOption(element, 'colorizeGreen', None) self.assertVendorOption(element, 'colorizeBlue', None) self.assertVendorOption(element, 'colorizeStrength', None) self.assertVendorOption(element, 'saturation', None) self.assertVendorOption(element, 'brightness', None) self.assertVendorOption(element, 'contrast', None) # other hue non default values, no colorize and saturation = 100 hue = myRasterLayer.hueSaturationFilter() hue.setColorizeOn(False) hue.setSaturation(100) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'colorizeOn', None) self.assertVendorOption(element, 'colorizeRed', None) self.assertVendorOption(element, 'colorizeGreen', None) self.assertVendorOption(element, 'colorizeBlue', None) self.assertVendorOption(element, 'colorizeStrength', None) self.assertVendorOption(element, 'saturation', '1') hue.setSaturation(-100) dom, root, errorMessage = self.layerToSld(myRasterLayer) self.assertVendorOption(root, 'saturation', '0') # brightness filter default values dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertTrue(myRasterLayer.brightnessFilter().brightness() == 0) self.assertTrue(myRasterLayer.brightnessFilter().contrast() == 0) self.assertVendorOption(element, 'brightness', None) self.assertVendorOption(element, 'contrast', None) # brightness filter no default values bf = myRasterLayer.brightnessFilter() bf.setBrightness(-255) bf.setContrast(-100) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'brightness', '0') self.assertVendorOption(element, 'contrast', '0') bf.setBrightness(255) bf.setContrast(100) dom, root, errorMessage = self.layerToSld(myRasterLayer) elements = dom.elementsByTagName('sld:RasterSymbolizer') self.assertEqual(len(elements), 1) element = elements.at(0).toElement() self.assertFalse(element.isNull()) self.assertVendorOption(element, 'brightness', '1') self.assertVendorOption(element, 'contrast', '1')
def addWms(self, wms_name, url, layers, mime_type, epsg_code, protocol): """ # Slot for exposing the same-name function to Javascript. # Adding the WMS to the QGis TOC. :param wms_name: The WMS name to add in TOC as group :type wms_name: str :param url: The WMS URL :type url: str :param layers: The list of the WMS layers to add :type layers: list of str :param mime_type: The image MIME TYPE (e.g. image/png) :type mime_type: str :param epsg_code: The EPSG code (e.g. the number 32632) :type epsg_code: int :param protocol: The protocol (i.e. should be 'ba' for applying basic authentication). Not yet managed. :type protocol: str """ qgs_logger = QgsApplication.messageLog() qgs_logger.logMessage('addWms: wms_name = {}'.format(wms_name), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('addWms: url = {}'.format(url), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('addWms: layers = {}'.format(layers), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('addWms: mime_type = {}'.format(mime_type), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('addWms: epsg_code = {}'.format(epsg_code), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('addWms: protocol = {}'.format(protocol), tag=configuration.LOGGER_TAG, level=Qgis.Info) # For storing the URI data uri = QgsDataSourceUri() # Split the host with the request data pieces = url.split("?") if len(pieces) == 1: qgs_logger.logMessage('len(pieces) == 1', tag=configuration.LOGGER_TAG, level=Qgis.Info) elif len(pieces) == 2: qgs_logger.logMessage('len(pieces) == 2', tag=configuration.LOGGER_TAG, level=Qgis.Info) # Overriding the URL url = "{}{}".format(pieces[0], "?") parameters_values = pieces[1].split("=") if len(parameters_values) == 2: qgs_logger.logMessage('len(parameters) == 2', tag=configuration.LOGGER_TAG, level=Qgis.Info) uri.setParam(parameters_values[0], parameters_values[1]) qgs_logger.logMessage('uri.param({}): {}'.format( parameters_values[0], uri.param(parameters_values[0])), tag=configuration.LOGGER_TAG, level=Qgis.Info) else: qgs_logger.logMessage('len(p) != 2', tag=configuration.LOGGER_TAG, level=Qgis.Info) else: qgs_logger.logMessage('len(pieces) > 2 Not yet managed!', tag=configuration.LOGGER_TAG, level=Qgis.Warning) # Setting the URL to the URI uri.setParam("url", url) # Process the layers accordingly if just an element or a list of elements layers_list = [] if "," in layers: layers_list = layers.split(",") else: layers_list.append(layers) # Setting the parameter 'layers' in the URI for val in layers_list: uri.setParam("layers", val) # Setting the other parameters # Styles seems required: https://gis.stackexchange.com/questions/183485/load-wms-with-pyqgis uri.setParam("styles", "") uri.setParam("format", mime_type) uri.setParam("crs", "EPSG:{}".format(epsg_code)) # https://docs.qgis.org/3.4/en/docs/pyqgis_developer_cookbook/loadlayer.html#raster-layers # Ignore GetCoverage URL advertised by GetCapabilities. May be necessary if a server is not configured properly. uri.setParam("IgnoreGetMapUrl", "1") # Adding the parameters for the basic authentication qgs_logger.logMessage('Applying Basic-Authentication', tag=configuration.LOGGER_TAG, level=Qgis.Info) uri.setParam("username", self.session_user) uri.setParam("password", self.session_password) # Logging the parameters for debugging qgs_logger.logMessage('uri.param(url): {}'.format(uri.param("url")), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('uri.param(layers): {}'.format( uri.param("layers")), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('uri.param(format): {}'.format( uri.param("format")), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('uri.param(crs): {}'.format(uri.param("crs")), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('uri.service(): {}'.format(uri.service()), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('encodedUri: {}'.format(str(uri.encodedUri())), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('uri.uri(): {}'.format(uri.uri()), tag=configuration.LOGGER_TAG, level=Qgis.Info) # Generating the WMS layer wms_layer = QgsRasterLayer(str(uri.encodedUri()), wms_name, 'wms') # If the WMS is correctly generated, add to the QGis TOC if wms_layer.isValid(): QgsProject.instance().addMapLayer(wms_layer) else: qgs_logger.logMessage( 'Impossibile aggiungere il WMS: {}'.format(wms_name), tag=configuration.LOGGER_TAG, level=Qgis.Warning) self.show_message( "Attenzione!", "Impossibile aggiungere il WMS " + wms_name + " al progetto")
def testRelativePaths(self): """ Test whether paths to layer sources are stored as relative to the project path """ tmpDir = QTemporaryDir() tmpFile = "{}/project.qgs".format(tmpDir.path()) copyfile(os.path.join(TEST_DATA_DIR, "points.shp"), os.path.join(tmpDir.path(), "points.shp")) copyfile(os.path.join(TEST_DATA_DIR, "points.dbf"), os.path.join(tmpDir.path(), "points.dbf")) copyfile(os.path.join(TEST_DATA_DIR, "points.shx"), os.path.join(tmpDir.path(), "points.shx")) copyfile(os.path.join(TEST_DATA_DIR, "lines.shp"), os.path.join(tmpDir.path(), "lines.shp")) copyfile(os.path.join(TEST_DATA_DIR, "lines.dbf"), os.path.join(tmpDir.path(), "lines.dbf")) copyfile(os.path.join(TEST_DATA_DIR, "lines.shx"), os.path.join(tmpDir.path(), "lines.shx")) copyfile(os.path.join(TEST_DATA_DIR, "landsat_4326.tif"), os.path.join(tmpDir.path(), "landsat_4326.tif")) project = QgsProject() l0 = QgsVectorLayer(os.path.join(tmpDir.path(), "points.shp"), "points", "ogr") l1 = QgsVectorLayer(os.path.join(tmpDir.path(), "lines.shp"), "lines", "ogr") l2 = QgsRasterLayer(os.path.join(tmpDir.path(), "landsat_4326.tif"), "landsat", "gdal") self.assertTrue(l0.isValid()) self.assertTrue(l1.isValid()) self.assertTrue(l2.isValid()) self.assertTrue(project.addMapLayers([l0, l1, l2])) self.assertTrue(project.write(tmpFile)) del project with open(tmpFile, 'r') as f: content = ''.join(f.readlines()) self.assertTrue('source="./lines.shp"' in content) self.assertTrue('source="./points.shp"' in content) self.assertTrue('source="./landsat_4326.tif"' in content) # Re-read the project and store absolute project = QgsProject() self.assertTrue(project.read(tmpFile)) store = project.layerStore() self.assertEquals(set([l.name() for l in store.mapLayers().values()]), set(['lines', 'landsat', 'points'])) project.writeEntryBool('Paths', '/Absolute', True) tmpFile2 = "{}/project2.qgs".format(tmpDir.path()) self.assertTrue(project.write(tmpFile2)) with open(tmpFile2, 'r') as f: content = ''.join(f.readlines()) self.assertTrue( 'source="{}/lines.shp"'.format(tmpDir.path()) in content) self.assertTrue( 'source="{}/points.shp"'.format(tmpDir.path()) in content) self.assertTrue('source="{}/landsat_4326.tif"'.format( tmpDir.path()) in content) del project
def plugin_code_by_anshul_iitb(trip_number): trip_number = trip_number.upper() import pandas import psycopg2 import pandas.io.sql as psql QgsMessageLog.logMessage(trip_number) try: conn = psycopg2.connect( "dbname='MTP_transportation' user='******' host='localhost' password='******'" ) print "DB connected" except Exception as e: QMessageBox.information(None, "Error", "Database not connected") return print(e) try: cur = conn.cursor() sql = 'DROP TABLE IF EXISTS output;' cur.execute(sql) sql = """ CREATE TABLE output AS ( SELECT * FROM public.abc_july_final where trip_numbe = '""" + trip_number + "')" cur.execute(sql) conn.commit() cur.close() except Exception as e: print(e) #Removing all layer if any present QgsMapLayerRegistry.instance().removeAllMapLayers() #loading BaseLayer as OSM uri = "url=http://a.tile.openstreetmap.org/{z}/{x}/{y}.png&zmax=19&zmin=0&type=xyz" osm_layer = QgsRasterLayer(uri, 'OSM', 'wms') if not osm_layer.isValid(): print("Layer failed to load!") QgsMapLayerRegistry.instance().addMapLayer(osm_layer) print 'Finished' uri = QgsDataSourceURI() uri.setConnection("localhost", "5432", "MTP_transportation", "postgres", "anshuL@iitb") uri.setDataSource("public", "output", "geom") vlayer = QgsVectorLayer(uri.uri(False), 'output', "postgres") QgsMapLayerRegistry.instance().addMapLayer(vlayer) #setting the color of output layer named 'vlayer' vlayer.selectAll() iface.mapCanvas().setSelectionColor(QColor("blue")) iface.mapCanvas().zoomToSelected() print 'color changed' #setting line width of output layer named 'vlayer' symbols = vlayer.rendererV2().symbols() for symbol in symbols: symbol.setWidth(1) print 'Linewidth changed' # Refresh in order the see the changes iface.mapCanvas().refreshAllLayers() print 'Linewidth and color changed' # iface.zoomToActiveLayer() canvas = iface.mapCanvas() extent = vlayer.extent() canvas.setExtent(extent)
#Permet la suppression des doublons Lt = list(set(tab)) Lt.sort() for c_insee, n_couche in Lt: #AMORCES_CAD,LIEUDIT,CP.CadastralParcel,SUBFISCAL,CLOTURE,DETAIL_TOPO,HYDRO,VOIE_COMMUNICATION,BU.Building,BORNE_REPERE urlWithParams = "url=http://inspire.cadastre.gouv.fr/scpc/" + c_insee + ".wms?contextualWMSLegend=0&crs=EPSG:" + Code_EPSG + "&dpiMode=7&featureCount=10&format=image/png&layers=AMORCES_CAD&styles=&maxHeight=1024&maxWidth=1280" rlayer = QgsRasterLayer( urlWithParams, 'Amorces_cadastrales_' + n_couche + '_' + c_insee, 'wms') progress.setText(u'Nom de la commune : ' + n_couche + ' - ' + c_insee) progress.setText(u'Validite du flux : %s' % rlayer.isValid()) QgsMapLayerRegistry.instance().addMapLayer(rlayer) if rlayer.isValid() == True: iface.messageBar().pushMessage( "Information :", "Ajout du flux WMS pour la commune : " + n_couche, QgsMessageBar.INFO, duration=5) iface.mapCanvas().refresh() else: iface.messageBar().pushMessage("Warning :", "WMS invalide pour la commune : " + n_couche,
def test_clip_both(self): """Raster and Vector layers can be clipped.""" # Create a vector layer layer_name = 'padang' vector_layer = QgsVectorLayer(VECTOR_PATH, layer_name, 'ogr') message = ( 'Did not find layer "%s" in path "%s"' % (layer_name, VECTOR_PATH)) assert vector_layer.isValid(), message # Create a raster layer layer_name = 'shake' raster_layer = QgsRasterLayer(RASTERPATH, layer_name) message = ( 'Did not find layer "%s" in path "%s"' % (layer_name, RASTERPATH)) assert raster_layer.isValid(), message # Create a bounding box view_port_geo_extent = [99.53, -1.22, 101.20, -0.36] # Get the Hazard extents as an array in EPSG:4326 hazard_geo_extent = [ raster_layer.extent().xMinimum(), raster_layer.extent().yMinimum(), raster_layer.extent().xMaximum(), raster_layer.extent().yMaximum() ] # Get the Exposure extents as an array in EPSG:4326 exposure_geo_extent = [ vector_layer.extent().xMinimum(), vector_layer.extent().yMinimum(), vector_layer.extent().xMaximum(), vector_layer.extent().yMaximum() ] # Now work out the optimal extent between the two layers and # the current view extent. The optimal extent is the intersection # between the two layers and the viewport. # Extent is returned as an array [xmin,ymin,xmax,ymax] geo_extent = get_optimal_extent( hazard_geo_extent, exposure_geo_extent, view_port_geo_extent) # Clip the vector to the bbox result = clip_layer(vector_layer, geo_extent) # Check the output is valid assert os.path.exists(result.source()) read_safe_layer(result.source()) # Clip the raster to the bbox result = clip_layer(raster_layer, geo_extent) # Check the output is valid assert os.path.exists(result.source()) read_safe_layer(result.source()) # ------------------------------- # Check the extra keywords option # ------------------------------- # Clip the vector to the bbox result = clip_layer( vector_layer, geo_extent, extra_keywords={'title': 'piggy'}) # Check the output is valid assert os.path.exists(result.source()) safe_layer = read_safe_layer(result.source()) keywords = safe_layer.get_keywords() # message = 'Extra keyword was not found in %s: %s' % (myResult, # keywords) assert keywords['title'] == 'piggy' # Clip the raster to the bbox result = clip_layer( raster_layer, geo_extent, extra_keywords={'email': 'animal'}) # Check the output is valid assert os.path.exists(result.source()) safe_layer = read_safe_layer(result.source()) keywords = safe_layer.get_keywords() message = ('Extra keyword was not found in %s: %s' % (result.source(), keywords)) assert keywords['email'] == 'animal', message
def plugin_code_by_anshul_iitb(BusStopFrom, BusStopTo, TimeFrom, TimeTo, Day): #QMessageBox.information(None,"Plugin function by Anshul the great","\nSource: "+ BusStopFrom+"\nDestination: "+ BusStopTo+ "\nTime: " +TimeFrom+" to "+ TimeTo+"\nDay"+ Day) import pandas import psycopg2 import pandas.io.sql as psql QgsMessageLog.logMessage( "\nUser_Input_Source-"+ BusStopFrom+\ "\nUser_Input_Destination-"+ BusStopTo+\ "\nUser_Input_From-"+ TimeFrom+\ "\nUser_Input_To-"+ TimeTo +\ "\nUser_Input_Day-"+ Day ) try: conn = psycopg2.connect( "dbname='MTP_transportation' user='******' host='localhost' password='******'" ) #QMessageBox.information(None,"Plugin stage process","DB connected") print "DB connected" except Exception as e: QMessageBox.information(None, "Error", "Database not connected") return print(e) #The mentioned below file contained the Nashik Bus stop Route Sequence with respective Route no.. This file has been derieved from Nashik All route Master file recieved RouteSequenceFile = psql.read_sql("SELECT * FROM route_seq", conn) #The mentioned below file contains Route no. to Trip No. Mapping. This file has been derieved by Sinnar August 2019 ETIM data with Following query "Select distinct Trip_no, Route_no from ETIM_File" RouteNoToTripNoFile = psql.read_sql('SELECT * FROM route_to_trip', conn) #ABC data of Sinner recieved of July month # ABCSinnarJul19File=pandas.read_csv('/home/anshulgoel031gmailcom/Desktop/MTP2/MTP/ABCJuly19_filtered.csv') ABCSinnarJul19File = psql.read_sql('SELECT * FROM ABCJuly19_filtered', conn) #This mentioned below file contains the Nashik Bus stop Route sequences Master file as recieved by Nashik depot # RouteSequenceMasterFile= pandas.read_csv('/home/anshulgoel031gmailcom/Desktop/MTP2/MTP/All_Routes_Stops_Master_of_Nashik_Division.csv') RouteSequenceMasterFile = psql.read_sql( 'SELECT * FROM All_Routes_Stops_Master_of_Nashik_Division', conn) #Closing the databse conn.close() #Converting Bus Stop code to upper case so that we can comapre with database values with considering case sensitivity BusStopFrom = BusStopFrom.upper() BusStopTo = BusStopTo.upper() #Assuming bus speed to be 30km/hour, We dont have Bus arrrival time and departure time on a particular bus stop, so based on route length and average speed expected time has been calculated Bus_speed = 30 def abc(BusStopFrom, BusStopTo, TimeFrom, TimeTo): #print (BusStopFrom) #print (BusStopTo) Required_Route_Sequence = [] Required_From_KM = [] for i in range(0, len(RouteSequenceFile)): if (RouteSequenceFile['Route_seq'][i].find(BusStopFrom) > -1 and RouteSequenceFile['Route_seq'][i].find(BusStopTo) > -1 and RouteSequenceFile['Route_seq'][i].find(BusStopFrom) < RouteSequenceFile['Route_seq'][i].find(BusStopTo)): Required_Route_Sequence.append( RouteSequenceFile['Route_no'][i]) # Required_From_KM.append(RouteSequenceFile['KM'][i]) print len(Required_Route_Sequence) print Required_Route_Sequence QMessageBox.information( None, "All Possible Routes", "Total No.of all possible routes are " + str(len(Required_Route_Sequence)) + '\n\n Routes are ' + str(Required_Route_Sequence)) return Required_Route_Sequence # In[4]: Required_Route_Sequence = abc(BusStopFrom, BusStopTo, TimeFrom, TimeTo) # In[5]: # This functions return a DataFrame which contains Trip Numbers and Respective Route Numbers which have routes NSKCBS to SNNR without considering time # This Functions required inputs a 'list' which contains all route no. having routes from NSKCBS to SNNR irrespective of time def Route_to_trip(Required_Route_Sequence): Required_Trips = [] Required_Routes = [] for i in range(0, len(Required_Route_Sequence)): for j in range(0, len(RouteNoToTripNoFile)): if (Required_Route_Sequence[i] == RouteNoToTripNoFile['Route_no'][j]): Required_Trips.append(RouteNoToTripNoFile['trip_no'][j]) Required_Routes.append(RouteNoToTripNoFile['Route_no'][j]) # This 'dict' variable contains Trip Numbers and Respective Route Numbers which have routes NSKCBS to SNNR dict = {'Trips': Required_Trips, 'Routes': Required_Routes} # print(len(Required_Trip_Sequence)) # Converting this Dict into DataFrame and returning via function df = pandas.DataFrame(dict) print(len(df)) print(df) QMessageBox.information( None, "All possible Trips", "Total number of all possible Trips are " + str(len(df['Trips'].tolist())) + "\n\nTrips are " + str([str(i) for i in df['Trips'].tolist()])) return df # return Required_Trip_Sequence # In[6]: # This Required_Trip_Route is the 'Dataframe' which contain Trip_no and Route_no having Bus Stops from NSKCBS to SNNR Required_Trip_Route = Route_to_trip(Required_Route_Sequence) # In[7]: # This function return the list containinf "trip no." under Sinnar jurisdiction in month Oct 19 which provide NSKCBS to SNNR irrespective of time #Input of the function are two Dataframe one contians ABC Analysis of Sinnar Taluka For month Oct 2019 #Second Dataframe contains all the (Trips, Route No.) pair under Nashik Jurisdiction which provide NSKCBS TO SNNR Service def ReturnABCTripsIrrespectiveTime(Required_Trip_Route, ABCSinnarJul19File): Trips = [] Routes = [] Trip_start_time = [] for i in Required_Trip_Route.index: for j in ABCSinnarJul19File.index: if (Required_Trip_Route['Trips'][i] == ABCSinnarJul19File['Trip'][j]): Trips.append(Required_Trip_Route['Trips'][i]) Routes.append(Required_Trip_Route['Routes'][i]) Trip_start_time.append(ABCSinnarJul19File['Dept Time'][j]) dict = { 'Trips': Trips, 'Routes': Routes, 'Trip Start Time': Trip_start_time } # for i in Trips: # for j in ABCSinnarJul19File.index: df = pandas.DataFrame(dict) # print len(df) # print df return df # In[8]: ABCTripsIrrespectiveTime = ReturnABCTripsIrrespectiveTime( Required_Trip_Route, ABCSinnarJul19File) print ABCTripsIrrespectiveTime # In[9]: list_Route_no = list( dict.fromkeys(ABCTripsIrrespectiveTime['Routes'].tolist())) print list_Route_no list_Route_KM = [] # for i in ABCTripsIrrespectiveTime.index: # for j in ABCSinnarJul19File.index: # if ABCTripsIrrespectiveTime['Trips'][i].upper()==ABCSinnarJul19File['Trip'][j].upper(): # for k in RouteSequenceMasterFile.index: # if ABCTripsIrrespectiveTime['Routes'][i]==RouteSequenceMasterFile['ROUTE_NO'][k] and RouteSequenceMasterFile['BUS_STOP_CD'][k]==BusStopFrom: # print RouteSequenceMasterFile['KM'][k] # break list_Route_KM2 = [] for i in list_Route_no: for j in RouteSequenceMasterFile.index: if i == RouteSequenceMasterFile['ROUTE_NO'][ j] and RouteSequenceMasterFile['BUS_STOP_CD'][ j] == BusStopFrom: print i, RouteSequenceMasterFile['KM'][j] list_Route_KM.append(RouteSequenceMasterFile['KM'][j]) # break if i == RouteSequenceMasterFile['ROUTE_NO'][ j] and RouteSequenceMasterFile['BUS_STOP_CD'][ j] == BusStopTo: print i, RouteSequenceMasterFile['KM'][j] list_Route_KM2.append(RouteSequenceMasterFile['KM'][j]) break # df_Final=pandas.DataFrame() print list_Route_KM list_km = [] list_km2 = [] for i in ABCTripsIrrespectiveTime['Routes'].tolist(): for j in list_Route_no: if i == j: # df_final=df_final.append({'Route no.':ABCTripsIrrespectiveTime['Routes'][i],'Trip Start time':ABCTripsIrrespectiveTime['Trip Start time '][i],'Trips':ABCTripsIrrespectiveTime['Trips'][i] }) list_km.append(list_Route_KM[list_Route_no.index(j)]) list_km2.append(list_Route_KM2[list_Route_no.index(j)]) print list_km ABCTripsIrrespectiveTime['Start KM'] = list_km ABCTripsIrrespectiveTime['End KM'] = list_km2 ABCTripsIrrespectiveTime['Expected Time in hour'] = ( ABCTripsIrrespectiveTime['End KM'] - ABCTripsIrrespectiveTime['Start KM']) / Bus_speed ABCTripsIrrespectiveTime.sort_values(by='Trip Start Time', ascending=True, inplace=True) ABCTripsIrrespectiveTime.reset_index(drop=True, inplace=True) print ABCTripsIrrespectiveTime # In[10]: #this function has been used to compare time def time_in_hour(t): return float(t.split(':')[0]) + float(t.split(':')[1]) / 60 list_Final_output_index = [] for i in ABCTripsIrrespectiveTime.index: # print i #converting time into hours and then comparing if time_in_hour(ABCTripsIrrespectiveTime['Trip Start Time'] [i]) >= time_in_hour(TimeFrom) and time_in_hour( ABCTripsIrrespectiveTime['Trip Start Time'] [i]) <= time_in_hour(TimeTo): list_Final_output_index.append(i) # In[11]: ABCTripsIrrespectiveTime.iloc[list_Final_output_index] # In[12]: l = ABCTripsIrrespectiveTime['Trips'][list_Final_output_index].tolist() l = str([str(r) for r in l]) l = '(' + l[1:len(l) - 1] + ')' print l ABCTripsIrrespectiveTime['Trips'][list_Final_output_index].tolist() # QMessageBox.information(None,"Final output","No. of Bus Trips are "+str(len(ABCTripsIrrespectiveTime['Trips'][list_Final_output_index].tolist()))+"\n Final Trips betweeen provided bus stops and Time are :"+ l[1:len(l)-1]) try: conn = psycopg2.connect( "dbname='MTP_transportation' user='******' host='localhost' password='******'" ) #QMessageBox.information(None,"Final output","DB connected") print "DB connected" except: QMessageBox.information(None, "Error", "Database not connected") print 'DB Not connected' str1 = '' for i in ABCTripsIrrespectiveTime['Trips'][list_Final_output_index].tolist( ): cur = conn.cursor() sql = "select distinct abc_status from abc_july_final where trip_numbe='" + i + "'" cur.execute(sql) temp = str(cur.fetchone()) str1 = str1 + i + ' , ' + temp[2:len(temp) - 1] + '\n' msg = QMessageBox() msg.setText("Final Number of Bus Trips are " + str( len(ABCTripsIrrespectiveTime['Trips'] [list_Final_output_index].tolist())) + "\n Final Trips betweeen provided bus stops and Time are :" + l[1:len(l) - 1]) msg.setInformativeText("ABC Details of trips") msg.setWindowTitle("Final Output") msg.setDetailedText("ABC details:\n" + str1) retval = msg.exec_() # In[13]: try: conn = psycopg2.connect( "dbname='MTP_transportation' user='******' host='localhost' password='******'" ) #QMessageBox.information(None,"Final output","DB connected") print "DB connected" except: QMessageBox.information(None, "Error", "Database not connected") print 'DB Not connected' try: cur = conn.cursor() sql = 'DROP TABLE IF EXISTS output;' cur.execute(sql) sql = """ CREATE TABLE output AS ( SELECT * FROM public.abc_july_final where trip_numbe in """ + l + ')' # Here variable 'l' above in the above SQL query is the list containing all the required bus trips to be displayed if len(ABCTripsIrrespectiveTime['Trips'] [list_Final_output_index].tolist()) != 0: cur.execute(sql) conn.commit() cur.close() except Exception as e: print(e) #Removing all layer if any present QgsMapLayerRegistry.instance().removeAllMapLayers() #loading BaseLayer as OSM uri = "url=http://a.tile.openstreetmap.org/{z}/{x}/{y}.png&zmax=19&zmin=0&type=xyz" osm_layer = QgsRasterLayer(uri, 'OSM', 'wms') if not osm_layer.isValid(): print("Layer failed to load!") QgsMapLayerRegistry.instance().addMapLayer(osm_layer) print 'Finished' #if len(ABCTripsIrrespectiveTime['Trips'][list_Final_output_index].tolist())!=0: uri = QgsDataSourceURI() uri.setConnection("localhost", "5432", "MTP_transportation", "postgres", "anshuL@iitb") uri.setDataSource("public", "output", "geom") vlayer = QgsVectorLayer(uri.uri(False), 'output', "postgres") QgsMapLayerRegistry.instance().addMapLayer(vlayer) #zooming to the output layer vlayer.selectAll() mCanvas = iface.mapCanvas() mCanvas.zoomToSelected() vlayer.removeSelection() iface.mapCanvas().refreshAllLayers() print 'Linewidth and color changed' #setting the color of output layer named 'vlayer' vlayer.selectAll() iface.mapCanvas().setSelectionColor(QColor("blue")) print 'color changed' #setting line width of output layer named 'vlayer' symbols = vlayer.rendererV2().symbols() for symbol in symbols: symbol.setWidth(1) print 'Linewidth changed' # Refresh in order the see the changes iface.mapCanvas().refreshAllLayers() print 'Linewidth and color changed'
def testNoPk(self): """Read raster with no PK""" rl = QgsRasterLayer(self.dbconn + ' sslmode=disable srid=3035 table="public"."raster_3035_tiled_no_pk"' + 'sql=', 'test', 'postgresraster') self.assertTrue(rl.isValid())
def testPkGuessing(self): """Read raster layer with no pkey in uri""" rl = QgsRasterLayer(self.dbconn + ' sslmode=disable srid=3035 table="public"."raster_tiled_3035" sql=', 'test', 'postgresraster') self.assertTrue(rl.isValid())
def DasimetricCalculator(diretorioOut, resolucao): try: raster1 = diretorioOut + r"\pop.asc" popLayer = QgsRasterLayer(raster1, "pop") raster2 = diretorioOut + r"\rdensity.asc" rdensityLayer = QgsRasterLayer(raster2, "rdensity") raster3 = diretorioOut + r"\outputE.asc" eLayer = QgsRasterLayer(raster3, "e") raster4 = diretorioOut + r"\outputT.asc" tLayer = QgsRasterLayer(raster4, "t") entries = [] pop = QgsRasterCalculatorEntry() pop.ref = 'pop@1' pop.raster = popLayer pop.bandNumber = 1 entries.append(pop) rdensity = QgsRasterCalculatorEntry() rdensity.ref = 'rdensity@1' rdensity.raster = rdensityLayer rdensity.bandNumber = 1 entries.append(rdensity) e = QgsRasterCalculatorEntry() e.ref = 'e@1' e.raster = eLayer e.bandNumber = 1 entries.append(e) t = QgsRasterCalculatorEntry() t.ref = 't@1' t.raster = tLayer t.bandNumber = 1 entries.append(t) resultado = diretorioOut + r"\dasimetric.tif" resolucao2 = int(resolucao) * int(resolucao) expression = '(pop@1 * rdensity@1 *{})/(e@1 * t@1)'.format(resolucao2) print expression calc = QgsRasterCalculator(expression, resultado, 'GTiff', popLayer.extent(), popLayer.width(), popLayer.height(), entries) calc.processCalculation() fileInfo5 = QFileInfo(resultado) path5 = fileInfo5.filePath() baseName5 = fileInfo5.baseName() layer5 = QgsRasterLayer(path5, baseName5) QgsMapLayerRegistry.instance().addMapLayer(layer5) if layer5.isValid() is True: print "Dasimetric result was loaded successfully!" else: print "Unable to read basename and file path - Your string is probably invalid" except CalculationError: print "Dasimetric calculation error!" finally: print "Dasimetric calculation was successfully!"
def create_keyword_file(self, algorithm): """Create keyword file for the raster file created. Basically copy a template from keyword file in converter data and add extra keyword (usually a title) :param algorithm: Which re-sampling algorithm to use. valid options are 'nearest' (for nearest neighbour), 'invdist' (for inverse distance), 'average' (for moving average). Defaults to 'nearest' if not specified. Note that passing re-sampling alg parameters is currently not supported. If None is passed it will be replaced with 'nearest'. :type algorithm: str """ keyword_io = KeywordIO() # Set thresholds for each exposure mmi_default_classes = default_classification_thresholds( earthquake_mmi_scale) mmi_default_threshold = { earthquake_mmi_scale['key']: { 'active': True, 'classes': mmi_default_classes } } generic_default_classes = default_classification_thresholds( generic_hazard_classes) generic_default_threshold = { generic_hazard_classes['key']: { 'active': True, 'classes': generic_default_classes } } threshold_keyword = {} for exposure in exposure_all: # Not all exposure is supported by earthquake_mmi_scale if exposure in earthquake_mmi_scale['exposures']: threshold_keyword[exposure['key']] = mmi_default_threshold else: threshold_keyword[exposure['key']] = generic_default_threshold extra_keywords = { extra_keyword_earthquake_latitude['key']: self.latitude, extra_keyword_earthquake_longitude['key']: self.longitude, extra_keyword_earthquake_magnitude['key']: self.magnitude, extra_keyword_earthquake_depth['key']: self.depth, extra_keyword_earthquake_description['key']: self.description, extra_keyword_earthquake_location['key']: self.location, extra_keyword_earthquake_event_time['key']: self.time.strftime('%Y-%m-%dT%H:%M:%S'), extra_keyword_time_zone['key']: self.time_zone, extra_keyword_earthquake_x_minimum['key']: self.x_minimum, extra_keyword_earthquake_x_maximum['key']: self.x_maximum, extra_keyword_earthquake_y_minimum['key']: self.y_minimum, extra_keyword_earthquake_y_maximum['key']: self.y_maximum, extra_keyword_earthquake_event_id['key']: self.event_id } for key, value in list(self.extra_keywords.items()): extra_keywords[key] = value # Delete empty element. empty_keys = [] for key, value in list(extra_keywords.items()): if value is None: empty_keys.append(key) for empty_key in empty_keys: extra_keywords.pop(empty_key) keywords = { 'hazard': hazard_earthquake['key'], 'hazard_category': hazard_category_single_event['key'], 'keyword_version': inasafe_keyword_version, 'layer_geometry': layer_geometry_raster['key'], 'layer_mode': layer_mode_continuous['key'], 'layer_purpose': layer_purpose_hazard['key'], 'continuous_hazard_unit': unit_mmi['key'], 'classification': earthquake_mmi_scale['key'], 'thresholds': threshold_keyword, 'extra_keywords': extra_keywords, 'active_band': 1 } if self.algorithm_name: layer_path = os.path.join( self.output_dir, '%s-%s.tif' % (self.output_basename, algorithm)) else: layer_path = os.path.join(self.output_dir, '%s.tif' % self.output_basename) # append title and source to the keywords file if len(self.title.strip()) == 0: keyword_title = self.output_basename else: keyword_title = self.title keywords['title'] = keyword_title hazard_layer = QgsRasterLayer(layer_path, keyword_title) if not hazard_layer.isValid(): raise InvalidLayerError() keyword_io.write_keywords(hazard_layer, keywords)
def testNoConstraintRaster(self): """Read unconstrained raster layer""" rl = QgsRasterLayer(self.dbconn + ' sslmode=disable key=\'pk\' srid=3035 table="public"."raster_3035_no_constraints" sql=', 'test', 'postgresraster') self.assertTrue(rl.isValid())
def createMapLayer(self, mapLayerName, layerStyleName, boundingBox, layerTime="", minMaxRange=None): """Will create a QGIS valid raster layer for the parsed map, using the passed parameters to get the layer we need, with the requested style, and optionally a time dimension. The possibility of using WMS-T (Time) is provided by a 'hack' (QGIS does not allow it through its WMS provider API), taken from Anita Graser's Time Manager (GPL2). :param mapLayerName: The name identifier of the coverage we want to retrieve.. :type mapLayerName: str :param layerStyleName: The name identifier of the layer style we want used to paint our layer. :type layerStyleName: str :param layerTime: The time dimension we want (optional). :type layerTime: str :param minMaxRange: A tuple or list containing the min and max values to be used in the request of this map. Used for rendering the proper colors. If none or not provided, it will ask the server for the max-min values of this time-defined map and use them instead. :type minMaxRange: list or tuple with floats (min, max) :returns: A QGIS-compatible raster layer object with the given parameters. :rtype: QgsRasterLayer """ if self.mapInfo is None: self.getMapInfoFromCapabilities() if minMaxRange == None: minMaxRange = self.getMinMaxRasterValuesFromTimeRange( mapLayerName, layerStyleName, [layerTime], boundingBox) rasterMinMaxValues = str(minMaxRange[0]) + "," + str(minMaxRange[1]) print("Raster range for " + mapLayerName + "_" + layerStyleName + ": " + rasterMinMaxValues) finalUrl = self.baseWMSUrl.format(layer=mapLayerName, style=layerStyleName, url=self.mapInfo.getURL()) print("FinalUrl : " + finalUrl) #We add an UUID to guarantee uniqueness in the layer name and id layerName = self.mapInfo.getName() + "-" + str(uuid.uuid4()) print("LayerName :" + layerName) resultLayer = QgsRasterLayer(finalUrl, layerName, 'wms') if resultLayer.isValid(): print "Layer is valid" print resultLayer else: print "Layer is not valid" print("Wms uri : " + resultLayer.dataProvider().dataSourceUri()) ##print (self.qgisWMSThack+resultLayer.dataProvider().dataSourceUri() ## + "?TIME={time}%26COLORSCALERANGE={scale}%26BBOX={bbox}" ## .format(time = layerTime, ## scale=rasterMinMaxValues, ## bbox=str(boundingBox)) ) #HACK taken from Anita Graser's Time Manager: #https://github.com/anitagraser/TimeManager/blob/master/raster/wmstlayer.py #(Under GPL2 license) with an extra added for COLORSCALERANGE ncWMS attribute #and BOUNDINGBOX information (which is removed when constructing layers by qgis #it seems?) #TODO: Bounding box information is not processed by QGIS. QGIS C++ WMS provider #apparently re-creates the request with a previously read bounding box information #from the capabilities.xml file. This needs a workaround, or reature request to QGIS. resultLayer.dataProvider().setDataSourceUri( self.qgisWMSThack + resultLayer.dataProvider().dataSourceUri() + "?TIME={time}%26COLORSCALERANGE={scale}%26BBOX={bbox}".format( time=layerTime, scale=rasterMinMaxValues, bbox=str(boundingBox))) if resultLayer.isValid(): self.mapLayer = resultLayer else: raise StandardError('No se pudo crear una capa válida.')
def load_raster(self, path, name): layer = QgsRasterLayer(path, name) if not layer.isValid(): self.log_message(f"Failed to load raster: {path}") return None return layer