def processAlgorithm(self, parameters, context, feedback): layer = self.parameterAsMeshLayer(parameters, self.INPUT_LAYER, context) dataset = parameters[self.INPUT_DATASET_GROUP] timestep = parameters[self.INPUT_TIMESTEP] mupp = self.parameterAsDouble(parameters, self.MAP_UNITS_PER_PIXEL, context) extent = self.parameterAsExtent(parameters, self.INPUT_EXTENT, context) output_layer = self.parameterAsOutputLayer(parameters, self.OUTPUT, context) if dataset is None: raise QgsProcessingException(u'No dataset group selected') width = extent.width() / mupp height = extent.height() / mupp map_settings = qgis.utils.iface.mapCanvas().mapSettings() crs = map_settings.destinationCrs() transform_context = QgsProject.instance().transformContext() output_format = QgsRasterFileWriter.driverForExtension( os.path.splitext(output_layer)[1]) rfw = QgsRasterFileWriter(output_layer) rfw.setOutputProviderKey('gdal') rfw.setOutputFormat(output_format) rdp = rfw.createOneBandRaster(Qgis.Float64, width, height, extent, crs) if rdp is None: raise QgsProcessingException( self.tr("Could not create raster output: {}").format( output_layer)) if not rdp.isValid(): raise QgsProcessingException( self.tr("Could not create raster output {}: {}").format( output_layer, rdp.error().message(QgsErrorMessage.Text))) rdp.setEditable(True) nr_timesteps = layer.dataProvider().datasetCount( QgsMeshDatasetIndex(dataset)) if nr_timesteps == 1: timestep = 0 dataset_index = QgsMeshDatasetIndex(dataset, timestep) block = QgsMeshUtils.exportRasterBlock(layer, dataset_index, crs, transform_context, mupp, extent) rdp.writeBlock(block, 1) rdp.setNoDataValue(1, block.noDataValue()) rdp.setEditable(False) feedback.setProgress(100) return {self.OUTPUT: output_layer}
def on_change(self, wrapper): mesh_layer = wrapper.widgetValue() if mesh_layer: if type(mesh_layer) == str: mesh_layer = QgsProcessingUtils.mapLayerFromString( mesh_layer, self.context) dp = mesh_layer.dataProvider() datasetCount = 0 groupWithMaximumDatasets = -1 for i in range(dp.datasetGroupCount()): currentCount = dp.datasetCount(i) if currentCount > datasetCount: datasetCount = currentCount groupWithMaximumDatasets = i options = [] if groupWithMaximumDatasets > -1: for i in range(datasetCount): index = QgsMeshDatasetIndex(groupWithMaximumDatasets, i) meta = dp.datasetMetadata(index) time = meta.time() options.append((mesh_layer.formatTime(time), i)) else: options = [] self.parameterDefinition().setOptions([t for t, v in options]) self.widget.clear() for text, data in options: self.widget.addItem(text, data)
def _export_polys(self, levels, runner, dp, datasets, timestep, i, total, sink, feedback): for groupIndex in datasets: meta = dp.datasetGroupMetadata(groupIndex) name = meta.name() index = QgsMeshDatasetIndex(groupIndex, timestep) datasetMeta = dp.datasetMetadata(index) time = datasetMeta.time() for j in range(len(levels) - 1): lower_val = levels[j] upper_val = levels[j + 1] # fetch values geom = runner.exportPolygons( index, lower_val, upper_val, QgsMeshRendererScalarSettings.NeighbourAverage, feedback) if geom: attrs = [] attrs.append(name) attrs.append(time) attrs.append(lower_val) attrs.append(upper_val) f = QgsFeature() f.setGeometry(geom) f.setAttributes(attrs) sink.addFeature(f) feedback.setProgress(100 * i / total) i += 1 return i
def _export_lines(self, levels, runner, dp, datasets, timestep, i, total, sink, feedback): for groupIndex in datasets: meta = dp.datasetGroupMetadata(groupIndex) name = meta.name() index = QgsMeshDatasetIndex(groupIndex, timestep) datasetMeta = dp.datasetMetadata(index) time = datasetMeta.time() for value in levels: # fetch values geom = runner.exportLines( index, value, QgsMeshRendererScalarSettings.NeighbourAverage, feedback) if geom: attrs = [] attrs.append(name) attrs.append(time) attrs.append(value) f = QgsFeature() f.setGeometry(geom) f.setAttributes(attrs) sink.addFeature(f) feedback.setProgress(100 * i / total) i += 1 return i
def on_datasets_changed(self, lst): self.datasets = lst if len(lst) == 0: self.setText("Time: [current]") elif len(lst) == 1: meta = self.menu_datasets.layer.dataProvider().datasetMetadata( QgsMeshDatasetIndex(self.menu_datasets.dataset_group, lst[0]) ) self.setText("Time: " + time_to_string(meta.time())) else: self.setText("Time: [multiple]") self.datasets_changed.emit(lst)
def exportRaster(parameters): # Open layer from inputFile inputFile = 'Ugrid:' + '"' + parameters['INPUT_LAYER'] + '"' meshfile = inputFile.strip().split('/')[-1] meshlayer = meshfile.split('.')[0] layer = QgsMeshLayer(inputFile, meshlayer, 'mdal') # Check if layer is valid if layer.isValid() is True: # Get parameters for processing dataset = parameters['INPUT_GROUP'] timestep = parameters['INPUT_TIMESTEP'] mupp = parameters['MAP_UNITS_PER_PIXEL'] extent = layer.extent() output_layer = parameters['OUTPUT_RASTER'] width = extent.width() / mupp height = extent.height() / mupp crs = layer.crs() crs.createFromSrid(4326) transform_context = QgsProject.instance().transformContext() output_format = QgsRasterFileWriter.driverForExtension( os.path.splitext(output_layer)[1]) # Open output file for writing rfw = QgsRasterFileWriter(output_layer) rfw.setOutputProviderKey('gdal') rfw.setOutputFormat(output_format) # Create one band raster rdp = rfw.createOneBandRaster(Qgis.Float64, width, height, extent, crs) # Get dataset index dataset_index = QgsMeshDatasetIndex(dataset, timestep) # Regred mesh layer to raster block = QgsMeshUtils.exportRasterBlock(layer, dataset_index, crs, transform_context, mupp, extent) # Write raster to GeoTiff file rdp.writeBlock(block, 1) rdp.setNoDataValue(1, block.noDataValue()) rdp.setEditable(False) logger.info('Regridded mesh data in ' + meshfile.split('"')[0] + ' to float64 grid, and saved to tiff (' + output_layer.split('/')[-1] + ') file.') return (output_layer) if layer.isValid() is False: raise Exception('Invalid mesh')
def interpolate_from_mesh(self, pt_feat, mesh_layer_id, group, dataset, above_existing): """Interpolate from mesh.""" mesh_layer = self.project.mapLayer(mesh_layer_id) ptxy = pt_feat.geometry().asPoint() dataset_val = mesh_layer.datasetValue(QgsMeshDatasetIndex(group, dataset), ptxy) val = dataset_val.scalar() if math.isnan(val): return val if above_existing: ident_vals = self.handler.provider.identify(ptxy, QgsRaster.IdentifyFormatValue).results() org_val = list(ident_vals.values())[0] if org_val == self.handler.nodata_values[0]: return val return max(org_val, val) else: return val
def populate_actions(self, dataset_group_index): # populate timesteps self.clear() if dataset_group_index is None or dataset_group_index < 0 or self.layer is None or self.layer.dataProvider() is None: return self.action_current = self.addAction("[current]") self.action_current.setCheckable(True) self.action_current.setChecked(True) self.action_current.triggered.connect(self.on_action_current) self.addSeparator() for i in range(self.layer.dataProvider().datasetCount(dataset_group_index)): meta = self.layer.dataProvider().datasetMetadata(QgsMeshDatasetIndex(dataset_group_index, i)) a = self.addAction(time_to_string(meta.time())) a.dataset_index = i a.setCheckable(True) a.triggered.connect(self.on_action)
def processAlgorithm(self, parameters, context, feedback): layer = self.parameterAsMeshLayer(parameters, self.INPUT_LAYER, context) dp = layer.dataProvider() # parameterAsEnums doesn't work with updated options # datasets = self.parameterAsEnums(parameters, self.INPUT_DATASETS, context) datasets = parameters[self.INPUT_DATASETS] timestep = parameters[self.INPUT_TIMESTEP] groups_meta = {} fields = QgsFields() fields.append(QgsField('fid', QVariant.Int)) for groupIndex in datasets: meta = dp.datasetGroupMetadata(groupIndex) groups_meta[groupIndex] = meta name = meta.name() fields.append(QgsField(name, QVariant.Double)) if meta.isVector(): fields.append(QgsField('{}_x'.format(name), QVariant.Double)) fields.append(QgsField('{}_y'.format(name), QVariant.Double)) (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context, fields, self.export_geometry_type(), layer.crs()) if sink is None: raise QgsProcessingException( self.invalidSinkError(parameters, self.OUTPUT)) mesh = QgsMesh() dp.populateMesh(mesh) count = self.export_objects_count(mesh) offset = 0 batch_size = 100 while offset < count: iterations = min(batch_size, count - offset) # fetch values datasets_values = {} for groupIndex in datasets: datasets_values[groupIndex] = dp.datasetValues( QgsMeshDatasetIndex(groupIndex, timestep), offset, iterations) for i in range(iterations): attrs = [offset + i] for groupIndex in datasets: value = datasets_values[groupIndex].value(i) meta = groups_meta[groupIndex] attrs.append(value.scalar()) if meta.isVector(): attrs.append(value.x()) attrs.append(value.y()) f = QgsFeature() f.setGeometry(self.get_mesh_geometry(mesh, offset + i)) f.setAttributes(attrs) sink.addFeature(f) feedback.setProgress(100 * ((offset + i + 1) / count)) offset += iterations feedback.setProgress(100) return {self.OUTPUT: dest_id}