def __init__(self, dlg, rasters_name, lines_name, polygons_name, points_name): # input vectors self.__ignicao_group_entrada_modelo = dlg.ignicao_group_entrada_modelo self.__ignicao_checkbox_lt = dlg.ignicao_checkbox_lt self.__ignicao_combo_lt = dlg.ignicao_combo_lt self.__ignicao_group_grid = dlg.ignicao_group_grid self.__ignicao_checkbox_grid = dlg.ignicao_checkbox_grid self.__ignicao_combo_grid = dlg.ignicao_combo_grid # input rasters self.__ignicao_group_entradas_modelo = dlg.ignicao_group_entradas_modelo self.__ignicao_checkbox_habilitar_entradas = dlg.ignicao_checkbox_habilitar_entradas self.__ignicao_combo_insolacao = dlg.ignicao_combo_insolacao self.__ignicao_combo_temperatura_maxima = dlg.ignicao_combo_temperatura_maxima self.__ignicao_combo_velocidade_vento = dlg.ignicao_combo_velocidade_vento self.__ignicao_combo_censo_ibge = dlg.ignicao_combo_censo_ibge self.__ignicao_combo_uso_solo = dlg.ignicao_combo_uso_solo self.__ignicao_combo_gndvi = dlg.ignicao_combo_gndvi self.__ignicao_combo_ndvi = dlg.ignicao_combo_ndvi self.__ignicao_combo_area_basal = dlg.ignicao_combo_area_basal self.__ignicao_combo_densidade = dlg.ignicao_combo_densidade self.__ignicao_combo_volume = dlg.ignicao_combo_volume self.__ignicao_combo_queimadas = dlg.ignicao_combo_queimadas self.__ignicao_combo_altitude = dlg.ignicao_combo_altitude # formula self.__ignicao_group_formula_saida = dlg.ignicao_group_formula_saida self.__ignicao_checkbox_habilitar_formula = dlg.ignicao_checkbox_habilitar_formula self.__ignicao_btn_entrada_formula = dlg.ignicao_btn_entrada_formula self.__ignicao_line_entrada_formula = dlg.ignicao_line_entrada_formula # output grid self.__ignicao_group_grid_saida = dlg.ignicao_group_grid_saida self.__ignicao_btn_saida_modelo = dlg.ignicao_btn_saida_modelo self.__ignicao_line_saida_modelo = dlg.ignicao_line_saida_modelo self.__create_fill_grid = False self.__fill_grid = False self.__apply_formula = False self.__qt_raster = QtHandler() self.__qt_vector = QtHandler() self.__init_combobox(rasters_name, polygons_name) self.__init_qt(rasters_name, lines_name, polygons_name, points_name) self.logger.info('Ignicao instance create successfully.')
def intersect(plugin_name, progress, line_layer, buffer_pc_layer): dlg, bar = QtHandler.progress_dialog(label='Creating Intersection...') tempfile = tmp_filename_without_extension() bar.setValue(20) line_layer_source = line_layer.source() buffer_pc_layer_source = buffer_pc_layer.source() bar.setValue(40) try: output = intersects(line_layer_source, buffer_pc_layer_source, True, tempfile) bar.setValue(80) except Exception as e: __logger.fatal(u'Fail to intersects buffer with line: {}'.format( str(e))) raise RuntimeError(str(e)) bar.setValue(100) bar.close() dlg.close() del dlg __logger.info(u'Intersection created successfully.') return output
def create_line(plugin_name, progress, layer): dlg, bar = QtHandler.progress_dialog(label='Creating line...') params = __config[plugin_name] tempfile = tmp_filename_without_extension() layer_source = layer.source() bar.setValue(20) try: output = point_to_path(layer_source, params['att_grupo'], params['att_vao_id'], '', tempfile, None) bar.setValue(80) except Exception as e: __logger.fatal(u'Fail to convert point to path: {}'.format(str(e))) raise RuntimeError(str(e)) bar.setValue(100) bar.close() dlg.close() del dlg __logger.info(u'Line created successfully.') return output
def classify_risco(self, layer): _, bar = QtHandler.progress_dialog(label='Classifying Risk...') fields = [str(field.name()) for field in layer.pendingFields()] pr = layer.dataProvider() bar.setValue(20) if self.params['att_cls_criticidade'] not in fields: pr.addAttributes([ QgsField(self.params['att_cls_criticidade'], QVariant.String) ]) layer.updateFields() bar.setValue(50) layer.startEditing() for feature in layer.getFeatures(): criticidade = feature[self.params['att_criticidade']] classificacao = self.classify(criticidade) layer.changeAttributeValue( feature.id(), layer.fieldNameIndex(self.params['att_cls_criticidade']), classificacao) layer.commitChanges() bar.setValue(100) return None, layer
def validate_rasters(objeto, layers, rasters, proj4): combo_by_index = objeto.combo_name_by_layer_index for combo_name, idx in combo_by_index.iteritems(): if idx <= 0: return u'Selecione um raster para o combo box "{}".'.format( combo_name), None current = 0 size = len(combo_by_index) _, bar = QtHandler.progress_dialog(label='Validating rasters...') rasters_selected = [] for combo_name, idx in combo_by_index.iteritems(): raster_name = rasters[idx] layer = find_one_layer_by_name(layers, raster_name) config = objeto.params['raster'][combo_name] if not raster_ok(config, layer, proj4): return u'Raster "{}" selecionado no combo box "{}" e invalido!'.format( layer.name(), combo_name), None rasters_selected.append(layer) current += 1 progress = (float(current) / float(size)) * 100 bar.setValue(progress) return None, rasters_selected
def clip_vectors(vao_layer, line_layer, plugin_name): dlg, bar = QtHandler.progress_dialog(label='Clipping Vectors...') params = __config[plugin_name] success = True new_features = [] lines = {} bar.setValue(20) writer = VectorWriter('memory:', None, vao_layer.pendingFields().toList(), QGis.WKBLineString, vao_layer.crs(), None) vl = writer.layer pr = writer.writer bar.setValue(30) vl.startEditing() for feat_line in line_layer.getFeatures(): key = int(feat_line[params['att_line_id']]) lines[key] = feat_line bar.setValue(40) for feat_vao in vao_layer.getFeatures(): idx = feat_vao.fieldNameIndex(params['att_vao_id']) attr = int(feat_vao.attributes()[idx]) attributes = feat_vao.attributes() try: line = lines[attr] geom = feat_vao.geometry() geom_line = line.geometry() fet = QgsFeature() fet.setGeometry(geom.intersection(geom_line)) fet.setAttributes(attributes) new_features.append(fet) except Exception as e: __logger.error(str(e)) bar.setValue(80) pr.addFeatures(new_features) vl.updateFields() vl.commitChanges() if len(new_features) > 0: QgsMapLayerRegistry.instance().addMapLayer(vl) bar.setValue(100) bar.close() dlg.close() del dlg __logger.info(u'All vectors clipped successfully.') return success, vl
def buffering(plugin_name, progress, layer, destination='memory:', open_output_layer=True): dlg, bar = QtHandler.progress_dialog(label='Buffering...') name = layer.name() __logger.info(u'Buffering layer "{}"...'.format(name)) if not is_vector_layer(layer): __logger.warn( u'Layer "{}" is not QVectorLayer, got layer type {}'.format( name, layer.type())) return bar.setValue(10) writer = VectorWriter(destination, None, layer.pendingFields().toList(), QGis.WKBPolygon, layer.crs(), None) bar.setValue(20) params = __config[plugin_name] __logger.info( u'Running buffering algorithm for "{}"...'.format(destination)) __logger.info(params['dissolve']) buff.buffering(progress, writer, params['distance'], None, False, layer, params['dissolve'], params['segments']) bar.setValue(60) output = writer.layer output_layer_name = u'{}_buffer'.format(name) if output: output.setName(output_layer_name) else: output = QgsVectorLayer(destination, output_layer_name, 'ogr') bar.setValue(80) if output.isValid(): if open_output_layer: QgsMapLayerRegistry.instance().addMapLayers([output]) __logger.info(u'Buffer created with success.') else: __logger.fatal(u'Layer created is invalid.') bar.setValue(100) bar.close() dlg.close() del dlg return output
def clip_rasters(buffer_layer, raster_layers): success = True tempfile = None new_layers = [] buffer_source = buffer_layer.source() current = 0 last_progress = 0 size = len(raster_layers) total = 100 / size if size > 0 else 1 dlg, bar = QtHandler.progress_dialog(label='Clipping rasters...') __logger.info(u'Clip {} rasters with buffer "{}"'.format( str(size), buffer_layer.name())) for layer in raster_layers: name = layer.name() source = layer.source() datatype, datatype_name = raster_data_type(source) datatype = datatype - 1 __logger.info( u'Clipping raster "{}" with source "{}", datatype: "{}" and datatype_name: "{}"...' .format(name, source, str(datatype), str(datatype_name))) try: output = clip_raster_by_mask(source, buffer_source, tempfile, raster_type=datatype) new_layers.append(output) except Exception as e: success = False __logger.fatal(u'Fail to clip raster "{}": {} => {}'.format( name, e.message, str(traceback.format_exc()))) current += 1 percentage = int(current * total) __logger.info(u'Clipping status: {}%...'.format(str(percentage))) bar.setValue(percentage) last_progress = percentage if last_progress < 100: bar.setValue(100) bar.close() dlg.close() del dlg if success: __logger.info(u'All rasters clipped successfully.') return success, new_layers
def __init__(self, vectors_vao_name, vectors_name, combo_vao, combo_ponto_critico, combo_torre): self.logger.error('Init vulnerabilidade') self.__qt = QtHandler() self.__combo_vao = combo_vao self.__combo_ponto_critico = combo_ponto_critico self.__combo_torre = combo_torre self.__init_combobox(vectors_name) QtHandler.set_combobox(combo_vao, vectors_vao_name, self.on_vao_change) QtHandler.set_combobox(combo_ponto_critico, vectors_name, self.on_ponto_critico_change) QtHandler.set_combobox(combo_torre, vectors_name, self.on_torre_change)
def apply_model(self, vegetacao, clinografia, orientacao_vertente, proximidade_estradas, hipsometria, output_raster): """ Apply propagacao model. :param vegetacao: A QgsRasterLayer layer. :param clinografia: A QgsRasterLayer layer. :param orientacao_vertente: A QgsRasterLayer layer. :param proximidade_estradas: A QgsRasterLayer layer. :param hipsometria: A QgsRasterLayer layer. :param output_raster: A string with the layer output path. :return: QgsRasterLayer """ dlg, bar = QtHandler.progress_dialog(label='Applying model...') expression_template = self.params['expression'] default_band = self.params['expression_default_band'] expression_base_layer = self.params['expression_base_layer'] qgs_raster_layers = [vegetacao, clinografia, orientacao_vertente, proximidade_estradas, hipsometria] expression_alias = findall(r'\{(.*?)\}', expression_template) bar.setValue(10) idx = expression_alias.index(expression_base_layer) qgs_raster_base_layer = qgs_raster_layers[idx] tmp_output_raster = tmp_filename_without_extension() + '.tif' bar.setValue(20) code, msg = raster_calculator_from_config(qgs_raster_layers, expression_alias, expression_template, qgs_raster_base_layer, tmp_output_raster, default_band) bar.setValue(80) if code == 0: propagacao = PropagacaoModelReclass(tmp_output_raster, output_raster) re = Reclassify(propagacao) re.apply() layer = import_layer_qgis(output_raster) set_layer_style(layer, PLUGIN_PROPAGACAO, PLUGIN_PROPAGACAO) else: self.logger.fatal(msg) bar.setValue(100) bar.close() dlg.close() del dlg return code, msg
def reclassify(self, layers, rasters): suffix = '_clipped' sources = {} layers_by_name = {} combo_by_index = self.__qt.combo_name_by_layer_index current = 0 size = len(combo_by_index) total = 100 / size last_progress = 0 dlg, bar = QtHandler.progress_dialog(label='Reclassifying rasters...') for combo_name, idx in combo_by_index.iteritems(): raster_name = rasters[idx] raster_name = raster_name + suffix self.logger.info('Searching raster to reclassify, index {} ({})...'.format(idx, raster_name)) layer = find_one_layer_by_name(layers, raster_name) if not layer: self.logger.warn('Layer "{}" not found to reclassify...'.format(raster_name)) return input_raster = layer.source() output_raster = tmp_filename_without_extension() + '.tif' algorithm = self.reclass_algorithms[combo_name] reclass = algorithm(input_raster, output_raster) re = Reclassify(reclass) re.apply() sources[combo_name] = output_raster current += 1 percentage = int(current * total) self.logger.info('Reclassify status: {}%...'.format(str(percentage))) bar.setValue(percentage) last_progress = percentage if last_progress < 100: bar.setValue(100) bar.close() dlg.close() del dlg for combo_name, source in sources.iteritems(): output = import_layer_qgis(source, suffix='reclass', base_layer=combo_name, add_map_layer=False) layers_by_name[combo_name] = output return layers_by_name
def buffer_line(plugin_name, progress, layer, output): dlg, bar = QtHandler.progress_dialog(label='Buffering Line...') layer_source = layer.source() bar.setValue(20) params = __config[plugin_name] extent = layer.extent() xmin = extent.xMinimum() xmax = extent.xMaximum() ymin = extent.yMinimum() ymax = extent.yMaximum() vector = str(xmin) + ',' + str(xmax) + ',' + str(ymin) + ',' + str(ymax) bar.setValue(40) try: output_temp = buffer_by_column(layer_source, params['att_buffer_dist'], params['scale'], params['max_distance'], params['straight_corners'], params['caps_ends'], vector, params['tolerance'], params['min_area'], params['output_type'], output) bar.setValue(80) except Exception as e: __logger.fatal(u'Fail to create buffer: {}'.format(str(e))) raise RuntimeError(str(e)) output_layer = QgsVectorLayer(output, 'area_manutencao', 'ogr') QgsMapLayerRegistry.instance().addMapLayers([output_layer]) style = params['style'] set_layer_style(output_layer, plugin_name, style['faixa_manutencao']) bar.setValue(100) bar.close() dlg.close() del dlg __logger.info(u'Buffer created successfully.') return output_temp
class RiscoFogo(object): cqfs_config = load_config() logger = logging.getLogger(PLUGIN_RISCO_FOGO) proj4 = cqfs_config['global']['crs_proj4'] params = cqfs_config[PLUGIN_RISCO_FOGO] def __init__(self, dlg, vectors_name, rasters_name): self.__qt = QtHandler() self.__combo_risco_fogo_raster_propagacao = dlg.combo_risco_fogo_raster_propagacao self.__combo_risco_fogo_grid_ignicao = dlg.combo_risco_fogo_grid_ignicao self.__line_saida_risco_tecnico = dlg.line_saida_risco_tecnico self.__btn_saida_risco_tecnico = dlg.btn_saida_risco_tecnico QtHandler.set_combobox(self.__combo_risco_fogo_raster_propagacao, rasters_name, self.on_raster_propagacao_change) QtHandler.set_combobox(self.__combo_risco_fogo_grid_ignicao, vectors_name, self.on_grid_ignicao_change) combo = { PLUGIN_RISCO_FOGO_PROPAGACAO: self.__combo_risco_fogo_raster_propagacao } self.__qt.init_combobox(rasters_name, **combo) def destroy(self): self.__combo_risco_fogo_raster_propagacao.clear() self.__combo_risco_fogo_grid_ignicao.clear() self.__line_saida_risco_tecnico.clear() self.__qt.clear_combobox() self.__qt = None self.__combo_risco_fogo_raster_propagacao = None self.__combo_risco_fogo_grid_ignicao = None self.__line_saida_risco_tecnico = None self.__btn_saida_risco_tecnico = None @property def combo_name_by_layer_index(self): return self.__qt.combo_name_by_layer_index def on_raster_propagacao_change(self, combo, index): self.__qt.on_combobox_change(PLUGIN_RISCO_FOGO_PROPAGACAO, combo, index) @staticmethod def on_grid_ignicao_change(combo, index): if index == 0: return
def __init__(self, rasters_name, vectors_name, combo_vulnerabilidade, combo_risco_fogo): self.logger.error('Init criticidade') self.__qt = QtHandler() self.__qt.init_combobox(rasters_name, risco_fogo=combo_risco_fogo) QtHandler.set_combobox(combo_vulnerabilidade, vectors_name, self.on_vulnerabilidade_change) QtHandler.set_combobox(combo_risco_fogo, rasters_name, self.on_risco_fogo_change) self.__combo_vulnerabilidade = combo_vulnerabilidade self.__combo_risco_fogo = combo_risco_fogo
def __init__(self, dlg, vectors_name, rasters_name): self.__qt = QtHandler() self.__combo_risco_fogo_raster_propagacao = dlg.combo_risco_fogo_raster_propagacao self.__combo_risco_fogo_grid_ignicao = dlg.combo_risco_fogo_grid_ignicao self.__line_saida_risco_tecnico = dlg.line_saida_risco_tecnico self.__btn_saida_risco_tecnico = dlg.btn_saida_risco_tecnico QtHandler.set_combobox(self.__combo_risco_fogo_raster_propagacao, rasters_name, self.on_raster_propagacao_change) QtHandler.set_combobox(self.__combo_risco_fogo_grid_ignicao, vectors_name, self.on_grid_ignicao_change) combo = { PLUGIN_RISCO_FOGO_PROPAGACAO: self.__combo_risco_fogo_raster_propagacao } self.__qt.init_combobox(rasters_name, **combo)
def create_grid(input_gridfn, output_gridfn, xmin, xmax, ymin, ymax, grid_height, grid_width): """ Creates a grid using a buffer. This method uses pure GDAL python. :param input_gridfn: A string with base buffer source. :param output_gridfn: A string with output source. :param xmin: float :param xmax: float :param ymin: float :param ymax: float :param grid_height: Cell size :param grid_width: Cell size :return: void """ xmin = float(xmin) xmax = float(xmax) ymin = float(ymin) ymax = float(ymax) grid_width = float(grid_width) grid_height = float(grid_height) assert (not isnan(xmin)) and (not isinf(xmin)) assert (not isnan(xmax)) and (not isinf(xmax)) assert (not isnan(ymin)) and (not isinf(ymin)) assert (not isnan(ymax)) and (not isinf(ymax)) assert (not isnan(grid_width)) and (not isinf(grid_width)) assert (not isnan(grid_height)) and (not isinf(grid_height)) if not os.path.isfile(input_gridfn): raise RuntimeError( u'Base layer does not exist in filesystem, got "{}".'.format( input_gridfn)) # get rows rows = ceil((ymax - ymin) / grid_height) # get columns cols = ceil((xmax - xmin) / grid_width) label = u'Creating a grid with {} rows and {} cols ({} cells)...'.format( rows, cols, rows * cols) __logger.info(label) dlg, bar = QtHandler.progress_dialog(label=label) # start grid cell envelope ring_xleft_origin = xmin ring_xright_origin = xmin + grid_width ring_ytop_origin = ymax ring_ybottom_origin = ymax - grid_height # create output file if os.path.exists(output_gridfn): os.remove(output_gridfn) ogr_driver = ogr.GetDriverByName(__OGR_DRIVER_NAME) base_data_source = ogr.Open(input_gridfn, 0) if not base_data_source: raise RuntimeError( u'Fail to open base layer "{}".'.format(input_gridfn)) bbox_layer = base_data_source.GetLayer() bbox_feature = bbox_layer.GetNextFeature() bbox_geom = bbox_feature.GetGeometryRef() bbox_srs = bbox_layer.GetSpatialRef() out_data_source = ogr_driver.CreateDataSource(output_gridfn) out_layer = out_data_source.CreateLayer(output_gridfn, bbox_srs, ogr.wkbPolygon) feature_defn = out_layer.GetLayerDefn() current = 0 last_progress = 0 total = 100.0 / cols if cols > 0 else 1 # create grid cells countcols = 0 while countcols < cols: countcols += 1 # reset envelope for rows ring_ytop = ring_ytop_origin ring_ybottom = ring_ybottom_origin countrows = 0 while countrows < rows: countrows += 1 geom = __create_polygon(ring_xleft_origin, ring_xright_origin, ring_ybottom, ring_ytop) if geom.Intersects(bbox_geom): # add new geom to layer __add_geom_to_layer(feature_defn, out_layer, geom) # new envelope for next geom ring_ytop = ring_ytop - grid_height ring_ybottom = ring_ybottom - grid_height # new envelope for next geom ring_xleft_origin = ring_xleft_origin + grid_width ring_xright_origin = ring_xright_origin + grid_width current += 1 progress = int(current * total) if progress != last_progress and progress % 10 == 0: __logger.info('Grid status: {}%...'.format(str(progress))) bar.setValue(progress) last_progress = progress # Save and close DataSources del feature_defn del out_layer del out_data_source del bbox_feature del bbox_layer del base_data_source if last_progress < 100: bar.setValue(100) bar.close() dlg.close() del dlg
def __init_qt(self, rasters_name, lines_names, polygons_name, points_name): self.__initial_components_states() QtHandler.set_combobox(self.__ignicao_combo_insolacao, rasters_name, self.on_insolacao_change) QtHandler.set_combobox(self.__ignicao_combo_temperatura_maxima, rasters_name, self.on_temperatura_change) QtHandler.set_combobox(self.__ignicao_combo_velocidade_vento, rasters_name, self.on_velocidade_change) QtHandler.set_combobox(self.__ignicao_combo_gndvi, rasters_name, self.on_gndvi_change) QtHandler.set_combobox(self.__ignicao_combo_ndvi, rasters_name, self.on_indvi_change) QtHandler.set_combobox(self.__ignicao_combo_area_basal, rasters_name, self.on_area_basal_change) QtHandler.set_combobox(self.__ignicao_combo_densidade, rasters_name, self.on_densidade_change) QtHandler.set_combobox(self.__ignicao_combo_volume, rasters_name, self.on_volume_change) QtHandler.set_combobox(self.__ignicao_combo_altitude, rasters_name, self.on_altitude_change) QtHandler.set_combobox(self.__ignicao_combo_lt, lines_names, self.on_linha_transmissao_change) QtHandler.set_combobox(self.__ignicao_combo_queimadas, points_name, self.on_queimadas_change) QtHandler.set_combobox(self.__ignicao_combo_grid, polygons_name, self.on_grid_change) QtHandler.set_combobox(self.__ignicao_combo_censo_ibge, polygons_name, self.on_censo_ibge_change) QtHandler.set_combobox(self.__ignicao_combo_uso_solo, polygons_name, self.on_uso_solo_change) QtHandler.set_radio(self.__ignicao_checkbox_lt, self.on_lt_toggled) QtHandler.set_radio(self.__ignicao_checkbox_grid, self.on_grid_toggled) QtHandler.set_radio(self.__ignicao_checkbox_habilitar_entradas, self.on_entradas_toggled) QtHandler.set_radio(self.__ignicao_checkbox_habilitar_formula, self.on_formula_toggled)
class Ignicao(object): logger = logging.getLogger(PLUGIN_IGNICAO) pt_br_format = '%d/%m/%Y %H:%M' params = config[PLUGIN_IGNICAO] proj4 = config['global']['crs_proj4'] def __init__(self, dlg, rasters_name, lines_name, polygons_name, points_name): # input vectors self.__ignicao_group_entrada_modelo = dlg.ignicao_group_entrada_modelo self.__ignicao_checkbox_lt = dlg.ignicao_checkbox_lt self.__ignicao_combo_lt = dlg.ignicao_combo_lt self.__ignicao_group_grid = dlg.ignicao_group_grid self.__ignicao_checkbox_grid = dlg.ignicao_checkbox_grid self.__ignicao_combo_grid = dlg.ignicao_combo_grid # input rasters self.__ignicao_group_entradas_modelo = dlg.ignicao_group_entradas_modelo self.__ignicao_checkbox_habilitar_entradas = dlg.ignicao_checkbox_habilitar_entradas self.__ignicao_combo_insolacao = dlg.ignicao_combo_insolacao self.__ignicao_combo_temperatura_maxima = dlg.ignicao_combo_temperatura_maxima self.__ignicao_combo_velocidade_vento = dlg.ignicao_combo_velocidade_vento self.__ignicao_combo_censo_ibge = dlg.ignicao_combo_censo_ibge self.__ignicao_combo_uso_solo = dlg.ignicao_combo_uso_solo self.__ignicao_combo_gndvi = dlg.ignicao_combo_gndvi self.__ignicao_combo_ndvi = dlg.ignicao_combo_ndvi self.__ignicao_combo_area_basal = dlg.ignicao_combo_area_basal self.__ignicao_combo_densidade = dlg.ignicao_combo_densidade self.__ignicao_combo_volume = dlg.ignicao_combo_volume self.__ignicao_combo_queimadas = dlg.ignicao_combo_queimadas self.__ignicao_combo_altitude = dlg.ignicao_combo_altitude # formula self.__ignicao_group_formula_saida = dlg.ignicao_group_formula_saida self.__ignicao_checkbox_habilitar_formula = dlg.ignicao_checkbox_habilitar_formula self.__ignicao_btn_entrada_formula = dlg.ignicao_btn_entrada_formula self.__ignicao_line_entrada_formula = dlg.ignicao_line_entrada_formula # output grid self.__ignicao_group_grid_saida = dlg.ignicao_group_grid_saida self.__ignicao_btn_saida_modelo = dlg.ignicao_btn_saida_modelo self.__ignicao_line_saida_modelo = dlg.ignicao_line_saida_modelo self.__create_fill_grid = False self.__fill_grid = False self.__apply_formula = False self.__qt_raster = QtHandler() self.__qt_vector = QtHandler() self.__init_combobox(rasters_name, polygons_name) self.__init_qt(rasters_name, lines_name, polygons_name, points_name) self.logger.info('Ignicao instance create successfully.') def destroy(self): self.__ignicao_combo_lt.clear() self.__ignicao_combo_queimadas.clear() self.__ignicao_combo_grid.clear() self.__ignicao_combo_insolacao.clear() self.__ignicao_combo_temperatura_maxima.clear() self.__ignicao_combo_velocidade_vento.clear() self.__ignicao_combo_censo_ibge.clear() self.__ignicao_combo_uso_solo.clear() self.__ignicao_combo_gndvi.clear() self.__ignicao_combo_ndvi.clear() self.__ignicao_combo_area_basal.clear() self.__ignicao_combo_densidade.clear() self.__ignicao_combo_volume.clear() self.__ignicao_combo_altitude.clear() self.__qt_raster.clear_combobox() self.__qt_vector.clear_combobox() QtHandler.disconnect(self.__ignicao_combo_lt.currentIndexChanged) QtHandler.disconnect( self.__ignicao_combo_queimadas.currentIndexChanged) QtHandler.disconnect(self.__ignicao_checkbox_lt.toggled) QtHandler.disconnect(self.__ignicao_checkbox_grid.toggled) QtHandler.disconnect( self.__ignicao_checkbox_habilitar_entradas.toggled) QtHandler.disconnect(self.__ignicao_checkbox_habilitar_formula.toggled) self.__qt_raster = None self.__qt_vector = None self.__ignicao_combo_lt = None self.__ignicao_combo_grid = None self.__ignicao_combo_insolacao = None self.__ignicao_combo_temperatura_maxima = None self.__ignicao_combo_velocidade_vento = None self.__ignicao_combo_censo_ibge = None self.__ignicao_combo_uso_solo = None self.__ignicao_combo_gndvi = None self.__ignicao_combo_ndvi = None self.__ignicao_combo_area_basal = None self.__ignicao_combo_densidade = None self.__ignicao_combo_volume = None self.__ignicao_combo_queimadas = None self.__ignicao_combo_altitude = None @property def is_create(self): return self.__create_fill_grid @property def is_fill(self): return self.__create_fill_grid or self.__fill_grid @property def is_formula(self): return self.__apply_formula @property def combo_name_by_raster_index(self): return self.__qt_raster.combo_name_by_layer_index @property def combo_name_by_vector_index(self): return self.__qt_vector.combo_name_by_layer_index @property def combo_queimadas_layer_name(self): idx = self.__ignicao_combo_queimadas.currentIndex() if idx == 0: return None else: return self.__ignicao_combo_queimadas.itemText(idx) def apply_model(self, layer, weight): start_time = datetime.now() str_start_time = start_time.strftime(self.pt_br_format) self.logger.info( 'Running Ignicao model at {}...'.format(str_start_time)) field_name = self.params['equation_field'] writer = layer.dataProvider() idx = layer.fieldNameIndex(field_name) if idx != -1: writer.deleteAttributes([idx]) layer.updateFields() writer.addAttributes( [QgsField(field_name, QVariant.Double, '', 24, 15)]) layer.updateFields() last_progress = 0 total = 100.0 / layer.featureCount() if layer.featureCount() > 0 else 1 dlg, bar = QtHandler.progress_dialog(label='Applying model Ignicao...') constant = float(weight['constant']) weight_queima = float(weight['queima']) weight_energia = float(weight['energia']) weight_enterra = float(weight['enterra']) weight_altitude = float(weight['altitude']) weight_insolacao = float(weight['insolacao']) weight_tmax = float(weight['tmax']) weight_vven = float(weight['vven']) weight_lsat_gndvi = float(weight['lsat_gndvi']) weight_lsat_ndvi = float(weight['lsat_ndvi']) weight_ab_med = float(weight['ab_med']) weight_ab_dif = float(weight['ab_dif']) weight_dens_med = float(weight['dens_med']) weight_vol_med = float(weight['vol_med']) weight_uso_c01_p = float(weight['uso_c01_p']) weight_uso_c02_p = float(weight['uso_c02_p']) weight_uso_c03_p = float(weight['uso_c03_p']) weight_uso_c04_p = float(weight['uso_c04_p']) weight_uso_c05_p = float(weight['uso_c05_p']) weight_uso_c06_p = float(weight['uso_c06_p']) weight_uso_c07_p = float(weight['uso_c07_p']) weight_uso_c08_p = float(weight['uso_c08_p']) weight_uso_c09_p = float(weight['uso_c09_p']) weight_uso_c10_p = float(weight['uso_c10_p']) weight_uso_c11_p = float(weight['uso_c11_p']) weight_uso_c12_p = float(weight['uso_c12_p']) weight_uso_c13_p = float(weight['uso_c13_p']) weight_uso_c14_p = float(weight['uso_c14_p']) weight_uso_c15_p = float(weight['uso_c15_p']) weight_uso_c16_p = float(weight['uso_c16_p']) weight_uso_c17_p = float(weight['uso_c17_p']) weight_uso_c18_p = float(weight['uso_c18_p']) weight_uso_c19_p = float(weight['uso_c19_p']) weight_uso_c20_p = float(weight['uso_c20_p']) weight_uso_c21_p = float(weight['uso_c21_p']) weight_uso_c22_p = float(weight['uso_c22_p']) layer.startEditing() bar.setValue(1) for current, ft in enumerate(layer.getFeatures()): ft[field_name] = self.__get_equation_value( ft, constant, weight_queima, weight_energia, weight_enterra, weight_altitude, weight_insolacao, weight_tmax, weight_vven, weight_lsat_gndvi, weight_lsat_ndvi, weight_ab_med, weight_ab_dif, weight_dens_med, weight_vol_med, weight_uso_c01_p, weight_uso_c02_p, weight_uso_c03_p, weight_uso_c04_p, weight_uso_c05_p, weight_uso_c06_p, weight_uso_c07_p, weight_uso_c08_p, weight_uso_c09_p, weight_uso_c10_p, weight_uso_c11_p, weight_uso_c12_p, weight_uso_c13_p, weight_uso_c14_p, weight_uso_c15_p, weight_uso_c16_p, weight_uso_c17_p, weight_uso_c18_p, weight_uso_c19_p, weight_uso_c20_p, weight_uso_c21_p, weight_uso_c22_p) layer.updateFeature(ft) progress = int(current * total) if progress != last_progress and progress % 10 == 0: self.logger.debug('{}%'.format(str(progress))) bar.setValue(progress) last_progress = progress layer.commitChanges() if last_progress != 100: bar.setValue(100) bar.close() dlg.close() del dlg end_time = datetime.now() time_elapsed = end_time - start_time str_end_time = end_time.strftime(self.pt_br_format) self.logger.info( 'Summing up, done at {}! Time elapsed {}(hh:mm:ss.ms)'.format( str_end_time, time_elapsed)) def __initial_components_states(self): # disable combo self.__ignicao_combo_lt.setEnabled(False) self.__ignicao_combo_grid.setEnabled(False) self.__ignicao_group_entradas_modelo.setEnabled(False) self.__ignicao_group_formula_saida.setEnabled(False) self.__ignicao_group_grid_saida.setEnabled(False) # uncheck radio self.__ignicao_checkbox_lt.setChecked(False) self.__ignicao_checkbox_grid.setChecked(False) self.__ignicao_checkbox_habilitar_entradas.setChecked(False) self.__ignicao_checkbox_habilitar_formula.setChecked(False) self.__create_fill_grid = False self.__fill_grid = False self.__apply_formula = False def __init_combobox(self, rasters_name, polygons_name): rasters_combo = { PLUGIN_IGNICAO_INSOLACAO: self.__ignicao_combo_insolacao, PLUGIN_IGNICAO_TEMPERATURA_MAXIMA: self.__ignicao_combo_temperatura_maxima, PLUGIN_IGNICAO_VELOCIDADE_VENTO: self.__ignicao_combo_velocidade_vento, PLUGIN_IGNICAO_GNDVI: self.__ignicao_combo_gndvi, PLUGIN_IGNICAO_NDVI: self.__ignicao_combo_ndvi, PLUGIN_IGNICAO_AREA_BASAL: self.__ignicao_combo_area_basal, PLUGIN_IGNICAO_DENSIDADE: self.__ignicao_combo_densidade, PLUGIN_IGNICAO_VOLUME: self.__ignicao_combo_volume, PLUGIN_IGNICAO_ALTITUDE: self.__ignicao_combo_altitude } polygons_combo = { PLUGIN_IGNICAO_CENSO_IBGE: self.__ignicao_combo_censo_ibge, PLUGIN_IGNICAO_USO_SOLO: self.__ignicao_combo_uso_solo, PLUGIN_IGNICAO_GRID: self.__ignicao_combo_grid } self.__qt_raster.init_combobox(rasters_name, **rasters_combo) self.__qt_vector.init_combobox(polygons_name, **polygons_combo) def __init_qt(self, rasters_name, lines_names, polygons_name, points_name): self.__initial_components_states() QtHandler.set_combobox(self.__ignicao_combo_insolacao, rasters_name, self.on_insolacao_change) QtHandler.set_combobox(self.__ignicao_combo_temperatura_maxima, rasters_name, self.on_temperatura_change) QtHandler.set_combobox(self.__ignicao_combo_velocidade_vento, rasters_name, self.on_velocidade_change) QtHandler.set_combobox(self.__ignicao_combo_gndvi, rasters_name, self.on_gndvi_change) QtHandler.set_combobox(self.__ignicao_combo_ndvi, rasters_name, self.on_indvi_change) QtHandler.set_combobox(self.__ignicao_combo_area_basal, rasters_name, self.on_area_basal_change) QtHandler.set_combobox(self.__ignicao_combo_densidade, rasters_name, self.on_densidade_change) QtHandler.set_combobox(self.__ignicao_combo_volume, rasters_name, self.on_volume_change) QtHandler.set_combobox(self.__ignicao_combo_altitude, rasters_name, self.on_altitude_change) QtHandler.set_combobox(self.__ignicao_combo_lt, lines_names, self.on_linha_transmissao_change) QtHandler.set_combobox(self.__ignicao_combo_queimadas, points_name, self.on_queimadas_change) QtHandler.set_combobox(self.__ignicao_combo_grid, polygons_name, self.on_grid_change) QtHandler.set_combobox(self.__ignicao_combo_censo_ibge, polygons_name, self.on_censo_ibge_change) QtHandler.set_combobox(self.__ignicao_combo_uso_solo, polygons_name, self.on_uso_solo_change) QtHandler.set_radio(self.__ignicao_checkbox_lt, self.on_lt_toggled) QtHandler.set_radio(self.__ignicao_checkbox_grid, self.on_grid_toggled) QtHandler.set_radio(self.__ignicao_checkbox_habilitar_entradas, self.on_entradas_toggled) QtHandler.set_radio(self.__ignicao_checkbox_habilitar_formula, self.on_formula_toggled) def on_insolacao_change(self, combo, index): self.__qt_raster.on_combobox_change(PLUGIN_IGNICAO_INSOLACAO, combo, index) def on_temperatura_change(self, combo, index): self.__qt_raster.on_combobox_change(PLUGIN_IGNICAO_TEMPERATURA_MAXIMA, combo, index) def on_velocidade_change(self, combo, index): self.__qt_raster.on_combobox_change(PLUGIN_IGNICAO_VELOCIDADE_VENTO, combo, index) def on_censo_ibge_change(self, combo, index): self.__qt_vector.on_combobox_change(PLUGIN_IGNICAO_CENSO_IBGE, combo, index) def on_uso_solo_change(self, combo, index): self.__qt_vector.on_combobox_change(PLUGIN_IGNICAO_USO_SOLO, combo, index) def on_gndvi_change(self, combo, index): self.__qt_raster.on_combobox_change(PLUGIN_IGNICAO_GNDVI, combo, index) def on_indvi_change(self, combo, index): self.__qt_raster.on_combobox_change(PLUGIN_IGNICAO_NDVI, combo, index) def on_area_basal_change(self, combo, index): self.__qt_raster.on_combobox_change(PLUGIN_IGNICAO_AREA_BASAL, combo, index) def on_densidade_change(self, combo, index): self.__qt_raster.on_combobox_change(PLUGIN_IGNICAO_DENSIDADE, combo, index) def on_volume_change(self, combo, index): self.__qt_raster.on_combobox_change(PLUGIN_IGNICAO_VOLUME, combo, index) def on_altitude_change(self, combo, index): self.__qt_raster.on_combobox_change(PLUGIN_IGNICAO_ALTITUDE, combo, index) def on_grid_change(self, combo, index): self.__qt_vector.on_combobox_change(PLUGIN_IGNICAO_GRID, combo, index) def on_lt_toggled(self, enabled): if enabled: self.__ignicao_combo_grid.setEnabled(False) self.__ignicao_checkbox_habilitar_formula.setEnabled(False) self.__ignicao_checkbox_grid.setChecked(False) self.__ignicao_combo_lt.setEnabled(True) self.__ignicao_group_entradas_modelo.setEnabled(False) self.__ignicao_group_grid_saida.setEnabled(True) self.__ignicao_checkbox_lt.setChecked(True) self.__ignicao_checkbox_habilitar_entradas.setChecked(False) self.__ignicao_checkbox_habilitar_entradas.setEnabled(False) self.__create_fill_grid = True else: self.__initial_components_states() def on_grid_toggled(self, enabled): if enabled: self.__ignicao_checkbox_lt.setChecked(False) self.__ignicao_combo_lt.setEnabled(False) self.__ignicao_group_entradas_modelo.setEnabled(False) self.__ignicao_group_grid_saida.setEnabled(True) self.__ignicao_combo_grid.setEnabled(True) self.__ignicao_group_grid_saida.setEnabled(False) self.__ignicao_checkbox_grid.setChecked(True) self.__ignicao_checkbox_habilitar_formula.setEnabled(True) self.__ignicao_checkbox_habilitar_formula.setChecked(False) self.__ignicao_checkbox_habilitar_entradas.setChecked(False) self.__ignicao_checkbox_habilitar_entradas.setEnabled(True) self.__fill_grid = True else: self.__initial_components_states() def on_entradas_toggled(self, enabled): if enabled: self.__ignicao_checkbox_habilitar_formula.setChecked(False) self.__ignicao_checkbox_habilitar_formula.setEnabled(False) self.__ignicao_group_formula_saida.setEnabled(False) self.__ignicao_group_entradas_modelo.setEnabled(True) self.__ignicao_group_grid_saida.setEnabled(False) else: self.__ignicao_checkbox_habilitar_formula.setChecked(False) self.__ignicao_checkbox_habilitar_formula.setEnabled(True) self.__ignicao_group_formula_saida.setEnabled(False) self.__ignicao_group_entradas_modelo.setEnabled(False) self.__ignicao_group_grid_saida.setEnabled(True) self.__apply_formula = False def on_formula_toggled(self, enabled): if enabled: self.__ignicao_checkbox_habilitar_formula.setChecked(True) self.__ignicao_checkbox_habilitar_formula.setEnabled(True) self.__ignicao_group_formula_saida.setEnabled(True) self.__ignicao_group_entradas_modelo.setEnabled(False) self.__apply_formula = True else: self.__ignicao_checkbox_habilitar_formula.setChecked(False) self.__ignicao_checkbox_habilitar_formula.setEnabled(True) self.__ignicao_group_formula_saida.setEnabled(False) self.__ignicao_group_entradas_modelo.setEnabled(True) self.__apply_formula = False def get_field_value(self, ft, field_name): field_value = 0.0 try: if ft[field_name] != NULL: field_value = float(ft[field_name]) except Exception: pass return field_value def __get_equation_value( self, ft, constant, weight_queima, weight_energia, weight_enterra, weight_altitude, weight_insolacao, weight_tmax, weight_vven, weight_lsat_gndvi, weight_lsat_ndvi, weight_ab_med, weight_ab_dif, weight_dens_med, weight_vol_med, weight_uso_c01_p, weight_uso_c02_p, weight_uso_c03_p, weight_uso_c04_p, weight_uso_c05_p, weight_uso_c06_p, weight_uso_c07_p, weight_uso_c08_p, weight_uso_c09_p, weight_uso_c10_p, weight_uso_c11_p, weight_uso_c12_p, weight_uso_c13_p, weight_uso_c14_p, weight_uso_c15_p, weight_uso_c16_p, weight_uso_c17_p, weight_uso_c18_p, weight_uso_c19_p, weight_uso_c20_p, weight_uso_c21_p, weight_uso_c22_p): try: queima = float(ft['queima']) energia = float(ft['energia']) enterra = float(ft['enterra']) altitude = float(ft['altitude']) insolacao = float(ft['insolacao']) tmax = float(ft['tmax']) vven = float(ft['vven']) lsat_gndvi = float(ft['lsat_gndvi']) lsat_ndvi = float(ft['lsat_ndvi']) ab_med = float(ft['ab_med']) ab_dif = float(ft['ab_dif']) dens_med = float(ft['dens_med']) vol_med = float(ft['vol_med']) uso_c01_p = self.get_field_value(ft, 'uso_c01_p') uso_c02_p = self.get_field_value(ft, 'uso_c02_p') uso_c03_p = self.get_field_value(ft, 'uso_c03_p') uso_c04_p = self.get_field_value(ft, 'uso_c04_p') uso_c05_p = self.get_field_value(ft, 'uso_c05_p') uso_c06_p = self.get_field_value(ft, 'uso_c06_p') uso_c07_p = self.get_field_value(ft, 'uso_c07_p') uso_c08_p = self.get_field_value(ft, 'uso_c08_p') uso_c09_p = self.get_field_value(ft, 'uso_c09_p') uso_c10_p = self.get_field_value(ft, 'uso_c10_p') uso_c11_p = self.get_field_value(ft, 'uso_c11_p') uso_c12_p = self.get_field_value(ft, 'uso_c12_p') uso_c13_p = self.get_field_value(ft, 'uso_c13_p') uso_c14_p = self.get_field_value(ft, 'uso_c14_p') uso_c15_p = self.get_field_value(ft, 'uso_c15_p') uso_c16_p = self.get_field_value(ft, 'uso_c16_p') uso_c17_p = self.get_field_value(ft, 'uso_c17_p') uso_c18_p = self.get_field_value(ft, 'uso_c18_p') uso_c19_p = self.get_field_value(ft, 'uso_c19_p') uso_c20_p = self.get_field_value(ft, 'uso_c20_p') uso_c21_p = self.get_field_value(ft, 'uso_c21_p') uso_c22_p = self.get_field_value(ft, 'uso_c22_p') x = ((constant) + (queima * (weight_queima)) + (energia * (weight_energia)) + (enterra * (weight_enterra)) + (altitude * weight_altitude) + (insolacao * (weight_insolacao)) + (tmax * (weight_tmax)) + (vven * (weight_vven)) + (lsat_gndvi * weight_lsat_gndvi) + (lsat_ndvi * (weight_lsat_ndvi)) + (ab_med * (weight_ab_med)) + (ab_dif * (weight_ab_dif)) + (dens_med * weight_dens_med) + (vol_med * (weight_vol_med)) + (uso_c01_p * (weight_uso_c01_p)) + (uso_c02_p * (weight_uso_c02_p)) + (uso_c03_p * (weight_uso_c03_p)) + (uso_c04_p * (weight_uso_c04_p)) + (uso_c05_p * (weight_uso_c05_p)) + (uso_c06_p * (weight_uso_c06_p)) + (uso_c07_p * (weight_uso_c07_p)) + (uso_c08_p * (weight_uso_c08_p)) + (uso_c09_p * (weight_uso_c09_p)) + (uso_c10_p * (weight_uso_c10_p)) + (uso_c11_p * (weight_uso_c11_p)) + (uso_c12_p * (weight_uso_c12_p)) + (uso_c13_p * (weight_uso_c13_p)) + (uso_c14_p * (weight_uso_c14_p)) + (uso_c15_p * (weight_uso_c15_p)) + (uso_c16_p * (weight_uso_c16_p)) + (uso_c17_p * (weight_uso_c17_p)) + (uso_c18_p * (weight_uso_c18_p)) + (uso_c19_p * (weight_uso_c19_p)) + (uso_c20_p * (weight_uso_c20_p)) + (uso_c21_p * (weight_uso_c21_p)) + (uso_c22_p * (weight_uso_c22_p))) value = 1 / (1 + (exp(-1 * x))) except Exception as e: value = NULL self.logger.debug('Fail to calculate cell fid {}: {}'.format( str(ft.id()), str(e))) return value @staticmethod def on_linha_transmissao_change(combo, index): if index == 0: return @staticmethod def on_queimadas_change(combo, index): if index == 0: return
class Criticidade(object): logger = logging.getLogger(PLUGIN_CRITICIDADE) cqfs_config = load_config() params = cqfs_config[PLUGIN_CRITICIDADE] proj4 = cqfs_config['global']['crs_proj4'] def __init__(self, rasters_name, vectors_name, combo_vulnerabilidade, combo_risco_fogo): self.logger.error('Init criticidade') self.__qt = QtHandler() self.__qt.init_combobox(rasters_name, risco_fogo=combo_risco_fogo) QtHandler.set_combobox(combo_vulnerabilidade, vectors_name, self.on_vulnerabilidade_change) QtHandler.set_combobox(combo_risco_fogo, rasters_name, self.on_risco_fogo_change) self.__combo_vulnerabilidade = combo_vulnerabilidade self.__combo_risco_fogo = combo_risco_fogo def validate_vulnerabilidade(self, layers, combo_vulnerabilidade): vulnerabilidade_index = combo_vulnerabilidade.currentIndex() if combo_vulnerabilidade <= 0: return 'Selecione o shape de Vulnerabilidade.', None # validação de atributos layer_vulnerabilidade = self.validate_attributes( layers, combo_vulnerabilidade, vulnerabilidade_index, 'attributes_vulnerabilidade') return None, layer_vulnerabilidade def validate_attributes(self, layers, combo, index, attributes_name): name = combo.itemText(index) layer = find_one_layer_by_name(layers, name) attributes = self.params[attributes_name] fields = [str(field.name()) for field in layer.pendingFields()] for attr in attributes: if str(attr) not in fields: self.logger.error( 'Layer Attributes "{}" error on validation attributes...'. format(str(attr))) return 'Erro na validacao de atributos.', None return layer def destroy(self): self.__combo_vulnerabilidade.clear() self.__combo_risco_fogo.clear() self.__qt.clear_combobox() self.__qt = None self.__combo_vulnerabilidade = None self.__combo_risco_fogo = None @property def combo_name_by_layer_index(self): return self.__qt.combo_name_by_layer_index def generate_zonal(self, vao, risco_fogo, output): zs = ZonalStatisticsNewLayer(vao.source(), risco_fogo.source(), output, operations=('max', ), fields_alias=('CRIT', )) zs.perform() output_layer = QgsVectorLayer(output, 'risco_zs', 'ogr') QgsMapLayerRegistry.instance().addMapLayers([output_layer]) return None, output_layer def classify_risco(self, layer): _, bar = QtHandler.progress_dialog(label='Classifying Risk...') fields = [str(field.name()) for field in layer.pendingFields()] pr = layer.dataProvider() bar.setValue(20) if self.params['att_cls_criticidade'] not in fields: pr.addAttributes([ QgsField(self.params['att_cls_criticidade'], QVariant.String) ]) layer.updateFields() bar.setValue(50) layer.startEditing() for feature in layer.getFeatures(): criticidade = feature[self.params['att_criticidade']] classificacao = self.classify(criticidade) layer.changeAttributeValue( feature.id(), layer.fieldNameIndex(self.params['att_cls_criticidade']), classificacao) layer.commitChanges() bar.setValue(100) return None, layer def classify(self, criticidade): if criticidade <= 0.2: return self.params['classif_muito_baixa'] elif 0.2 < criticidade < 0.4: return self.params['classif_baixa'] elif 0.4 < criticidade < 0.6: return self.params['classif_media'] elif 0.6 < criticidade < 0.8: return self.params['classif_alta'] elif criticidade >= 0.8: return self.params['classif_muito_alta'] @staticmethod def on_vulnerabilidade_change(combo, index): if index == 0: return def on_risco_fogo_change(self, combo, index): self.__qt.on_combobox_change('risco_fogo', combo, index)
class Vulnerabilidade(object): logger = logging.getLogger(PLUGIN_VULNERABILIDADE) cqfs_config = load_config() params = cqfs_config[PLUGIN_VULNERABILIDADE] proj4 = cqfs_config['global']['crs_proj4'] def __init__(self, vectors_vao_name, vectors_name, combo_vao, combo_ponto_critico, combo_torre): self.logger.error('Init vulnerabilidade') self.__qt = QtHandler() self.__combo_vao = combo_vao self.__combo_ponto_critico = combo_ponto_critico self.__combo_torre = combo_torre self.__init_combobox(vectors_name) QtHandler.set_combobox(combo_vao, vectors_vao_name, self.on_vao_change) QtHandler.set_combobox(combo_ponto_critico, vectors_name, self.on_ponto_critico_change) QtHandler.set_combobox(combo_torre, vectors_name, self.on_torre_change) def destroy(self): self.__combo_vao.clear() self.__combo_ponto_critico.clear() self.__combo_torre.clear() self.__qt.clear_combobox() self.__qt = None self.__combo_vao = None self.__combo_ponto_critico = None self.__combo_torre = None def validate(self, layers, combo_vao, combo_ponto_critico, combo_torres): vao_index = combo_vao.currentIndex() ponto_critico_index = combo_ponto_critico.currentIndex() torres_index = combo_torres.currentIndex() if vao_index <= 0: return 'Selecione o vão.', None if ponto_critico_index <= 0: return 'Selecione o ponto critico.', None if torres_index <= 0: return 'Selecione as torres.', None # validação de atributos layer_vao = self.validate_attributes(layers, combo_vao, vao_index, 'attributes_vao') layer_pc = self.validate_attributes(layers, combo_ponto_critico, ponto_critico_index, 'attributes_ponto_critico') layer_torres = self.validate_attributes(layers, combo_torres, torres_index, 'attributes_torres') self.verify_group_attribute(layer_vao) self.verify_group_attribute(layer_torres) validate_vectors(layers, combo_vao, self.proj4) validate_vectors(layers, combo_ponto_critico, self.proj4) validate_vectors(layers, combo_torres, self.proj4) prov = layer_vao.dataProvider() attr_type = prov.fields().field(self.params['att_vao_id']).type() if attr_type not in (QVariant.Int, QVariant.Double): return 'A coluna "{}" deve ser numerica.'.format(self.params['att_vao_id']), None, None, None return None, layer_vao, layer_pc, layer_torres def validate_attributes(self, layers, combo, index, attributes_name): name = combo.itemText(index) layer = find_one_layer_by_name(layers, name) attributes = load_config()['vulnerabilidade'][attributes_name] fields = [str(field.name()) for field in layer.pendingFields()] for attr in attributes: if str(attr) not in fields: self.logger.error('Layer Attributes "{}" error on validation attributes...'.format(str(attr))) return 'Erro na validacao do atributo "{}".'.format(str(attr)), None break return layer def verify_group_attribute(self, layer): fields = [str(field.name()) for field in layer.pendingFields()] grupo = self.params['att_grupo'] if grupo not in fields: pr = layer.dataProvider() pr.addAttributes([QgsField(self.params['att_grupo'], QVariant.Int)]) layer.updateFields() return def __init_combobox(self, vectors_name): combo = { PLUGIN_VULNERABILIDADE_PC: self.__combo_ponto_critico, PLUGIN_VULNERABILIDADE_TORRE: self.__combo_torre, } self.__qt.init_combobox(vectors_name, **combo) def on_vao_change(self, combo, index): if index == 0: return def on_ponto_critico_change(self, combo, index): self.__qt.on_combobox_change(PLUGIN_VULNERABILIDADE_PC, combo, index) def on_torre_change(self, combo, index): self.__qt.on_combobox_change(PLUGIN_VULNERABILIDADE_TORRE, combo, index)
class Propagacao(object): logger = logging.getLogger(PLUGIN_PROPAGACAO) params = config[PLUGIN_PROPAGACAO] proj4 = config['global']['crs_proj4'] reclass_algorithms = { PLUGIN_PROPAGACAO_HIPSOMETRIA: PropagacaoHipsometriaReclass, PLUGIN_PROPAGACAO_CLINOGRAFIA: PropagacaoClinografiaReclass, PLUGIN_PROPAGACAO_ORIENTACAO_VERTENTE: PropagacaoOrientacaoVertenteReclass, PLUGIN_PROPAGACAO_PROXIMIDADE_ESTRADAS: PropagacaoProximidadeEstradasReclass, PLUGIN_PROPAGACAO_VEGETACAO: PropagacaoVegetacaoReclass } def __init__(self, vectors_name, rasters_name, combo_linha_transmissao, combo_vegetacao, combo_clinografia, combo_orientacao_vertente, combo_proximidade_estradas, combo_hipsometria): self.__qt = QtHandler() self.__qt.init_combobox( rasters_name, vegetacao=combo_vegetacao, clinografia=combo_clinografia, orientacao_vertente=combo_orientacao_vertente, proximidade_estradas=combo_proximidade_estradas, hipsometria=combo_hipsometria ) QtHandler.set_combobox(combo_vegetacao, rasters_name, self.on_vegetacao_change) QtHandler.set_combobox(combo_clinografia, rasters_name, self.on_clinografia_change) QtHandler.set_combobox(combo_orientacao_vertente, rasters_name, self.on_orientacao_vertente_change) QtHandler.set_combobox(combo_proximidade_estradas, rasters_name, self.on_proximidade_estradas_change) QtHandler.set_combobox(combo_hipsometria, rasters_name, self.on_hipsometria_change) QtHandler.set_combobox(combo_linha_transmissao, vectors_name, self.on_linha_transmissao_change) self.__combo_vegetacao = combo_vegetacao self.__combo_clinografia = combo_clinografia self.__combo_orientacao_vertente = combo_orientacao_vertente self.__combo_proximidade_estradas = combo_proximidade_estradas self.__combo_hipsometria = combo_hipsometria self.__combo_linha_transmissao = combo_linha_transmissao def destroy(self): self.__combo_vegetacao.clear() self.__combo_clinografia.clear() self.__combo_orientacao_vertente.clear() self.__combo_proximidade_estradas.clear() self.__combo_hipsometria.clear() self.__combo_linha_transmissao.clear() self.__qt.clear_combobox() self.__qt = None self.__combo_vegetacao = None self.__combo_clinografia = None self.__combo_orientacao_vertente = None self.__combo_proximidade_estradas = None self.__combo_hipsometria = None self.__combo_linha_transmissao = None @property def combo_name_by_layer_index(self): return self.__qt.combo_name_by_layer_index def reclassify(self, layers, rasters): suffix = '_clipped' sources = {} layers_by_name = {} combo_by_index = self.__qt.combo_name_by_layer_index current = 0 size = len(combo_by_index) total = 100 / size last_progress = 0 dlg, bar = QtHandler.progress_dialog(label='Reclassifying rasters...') for combo_name, idx in combo_by_index.iteritems(): raster_name = rasters[idx] raster_name = raster_name + suffix self.logger.info('Searching raster to reclassify, index {} ({})...'.format(idx, raster_name)) layer = find_one_layer_by_name(layers, raster_name) if not layer: self.logger.warn('Layer "{}" not found to reclassify...'.format(raster_name)) return input_raster = layer.source() output_raster = tmp_filename_without_extension() + '.tif' algorithm = self.reclass_algorithms[combo_name] reclass = algorithm(input_raster, output_raster) re = Reclassify(reclass) re.apply() sources[combo_name] = output_raster current += 1 percentage = int(current * total) self.logger.info('Reclassify status: {}%...'.format(str(percentage))) bar.setValue(percentage) last_progress = percentage if last_progress < 100: bar.setValue(100) bar.close() dlg.close() del dlg for combo_name, source in sources.iteritems(): output = import_layer_qgis(source, suffix='reclass', base_layer=combo_name, add_map_layer=False) layers_by_name[combo_name] = output return layers_by_name def apply_model(self, vegetacao, clinografia, orientacao_vertente, proximidade_estradas, hipsometria, output_raster): """ Apply propagacao model. :param vegetacao: A QgsRasterLayer layer. :param clinografia: A QgsRasterLayer layer. :param orientacao_vertente: A QgsRasterLayer layer. :param proximidade_estradas: A QgsRasterLayer layer. :param hipsometria: A QgsRasterLayer layer. :param output_raster: A string with the layer output path. :return: QgsRasterLayer """ dlg, bar = QtHandler.progress_dialog(label='Applying model...') expression_template = self.params['expression'] default_band = self.params['expression_default_band'] expression_base_layer = self.params['expression_base_layer'] qgs_raster_layers = [vegetacao, clinografia, orientacao_vertente, proximidade_estradas, hipsometria] expression_alias = findall(r'\{(.*?)\}', expression_template) bar.setValue(10) idx = expression_alias.index(expression_base_layer) qgs_raster_base_layer = qgs_raster_layers[idx] tmp_output_raster = tmp_filename_without_extension() + '.tif' bar.setValue(20) code, msg = raster_calculator_from_config(qgs_raster_layers, expression_alias, expression_template, qgs_raster_base_layer, tmp_output_raster, default_band) bar.setValue(80) if code == 0: propagacao = PropagacaoModelReclass(tmp_output_raster, output_raster) re = Reclassify(propagacao) re.apply() layer = import_layer_qgis(output_raster) set_layer_style(layer, PLUGIN_PROPAGACAO, PLUGIN_PROPAGACAO) else: self.logger.fatal(msg) bar.setValue(100) bar.close() dlg.close() del dlg return code, msg def on_vegetacao_change(self, combo, index): self.__qt.on_combobox_change(PLUGIN_PROPAGACAO_VEGETACAO, combo, index) def on_clinografia_change(self, combo, index): self.__qt.on_combobox_change(PLUGIN_PROPAGACAO_CLINOGRAFIA, combo, index) def on_orientacao_vertente_change(self, combo, index): self.__qt.on_combobox_change(PLUGIN_PROPAGACAO_ORIENTACAO_VERTENTE, combo, index) def on_proximidade_estradas_change(self, combo, index): self.__qt.on_combobox_change(PLUGIN_PROPAGACAO_PROXIMIDADE_ESTRADAS, combo, index) def on_hipsometria_change(self, combo, index): self.__qt.on_combobox_change(PLUGIN_PROPAGACAO_HIPSOMETRIA, combo, index) @staticmethod def on_linha_transmissao_change(combo, index): if index == 0: return
def apply_model(self, layer, weight): start_time = datetime.now() str_start_time = start_time.strftime(self.pt_br_format) self.logger.info( 'Running Ignicao model at {}...'.format(str_start_time)) field_name = self.params['equation_field'] writer = layer.dataProvider() idx = layer.fieldNameIndex(field_name) if idx != -1: writer.deleteAttributes([idx]) layer.updateFields() writer.addAttributes( [QgsField(field_name, QVariant.Double, '', 24, 15)]) layer.updateFields() last_progress = 0 total = 100.0 / layer.featureCount() if layer.featureCount() > 0 else 1 dlg, bar = QtHandler.progress_dialog(label='Applying model Ignicao...') constant = float(weight['constant']) weight_queima = float(weight['queima']) weight_energia = float(weight['energia']) weight_enterra = float(weight['enterra']) weight_altitude = float(weight['altitude']) weight_insolacao = float(weight['insolacao']) weight_tmax = float(weight['tmax']) weight_vven = float(weight['vven']) weight_lsat_gndvi = float(weight['lsat_gndvi']) weight_lsat_ndvi = float(weight['lsat_ndvi']) weight_ab_med = float(weight['ab_med']) weight_ab_dif = float(weight['ab_dif']) weight_dens_med = float(weight['dens_med']) weight_vol_med = float(weight['vol_med']) weight_uso_c01_p = float(weight['uso_c01_p']) weight_uso_c02_p = float(weight['uso_c02_p']) weight_uso_c03_p = float(weight['uso_c03_p']) weight_uso_c04_p = float(weight['uso_c04_p']) weight_uso_c05_p = float(weight['uso_c05_p']) weight_uso_c06_p = float(weight['uso_c06_p']) weight_uso_c07_p = float(weight['uso_c07_p']) weight_uso_c08_p = float(weight['uso_c08_p']) weight_uso_c09_p = float(weight['uso_c09_p']) weight_uso_c10_p = float(weight['uso_c10_p']) weight_uso_c11_p = float(weight['uso_c11_p']) weight_uso_c12_p = float(weight['uso_c12_p']) weight_uso_c13_p = float(weight['uso_c13_p']) weight_uso_c14_p = float(weight['uso_c14_p']) weight_uso_c15_p = float(weight['uso_c15_p']) weight_uso_c16_p = float(weight['uso_c16_p']) weight_uso_c17_p = float(weight['uso_c17_p']) weight_uso_c18_p = float(weight['uso_c18_p']) weight_uso_c19_p = float(weight['uso_c19_p']) weight_uso_c20_p = float(weight['uso_c20_p']) weight_uso_c21_p = float(weight['uso_c21_p']) weight_uso_c22_p = float(weight['uso_c22_p']) layer.startEditing() bar.setValue(1) for current, ft in enumerate(layer.getFeatures()): ft[field_name] = self.__get_equation_value( ft, constant, weight_queima, weight_energia, weight_enterra, weight_altitude, weight_insolacao, weight_tmax, weight_vven, weight_lsat_gndvi, weight_lsat_ndvi, weight_ab_med, weight_ab_dif, weight_dens_med, weight_vol_med, weight_uso_c01_p, weight_uso_c02_p, weight_uso_c03_p, weight_uso_c04_p, weight_uso_c05_p, weight_uso_c06_p, weight_uso_c07_p, weight_uso_c08_p, weight_uso_c09_p, weight_uso_c10_p, weight_uso_c11_p, weight_uso_c12_p, weight_uso_c13_p, weight_uso_c14_p, weight_uso_c15_p, weight_uso_c16_p, weight_uso_c17_p, weight_uso_c18_p, weight_uso_c19_p, weight_uso_c20_p, weight_uso_c21_p, weight_uso_c22_p) layer.updateFeature(ft) progress = int(current * total) if progress != last_progress and progress % 10 == 0: self.logger.debug('{}%'.format(str(progress))) bar.setValue(progress) last_progress = progress layer.commitChanges() if last_progress != 100: bar.setValue(100) bar.close() dlg.close() del dlg end_time = datetime.now() time_elapsed = end_time - start_time str_end_time = end_time.strftime(self.pt_br_format) self.logger.info( 'Summing up, done at {}! Time elapsed {}(hh:mm:ss.ms)'.format( str_end_time, time_elapsed))
def __init__(self, vectors_name, rasters_name, combo_linha_transmissao, combo_vegetacao, combo_clinografia, combo_orientacao_vertente, combo_proximidade_estradas, combo_hipsometria): self.__qt = QtHandler() self.__qt.init_combobox( rasters_name, vegetacao=combo_vegetacao, clinografia=combo_clinografia, orientacao_vertente=combo_orientacao_vertente, proximidade_estradas=combo_proximidade_estradas, hipsometria=combo_hipsometria ) QtHandler.set_combobox(combo_vegetacao, rasters_name, self.on_vegetacao_change) QtHandler.set_combobox(combo_clinografia, rasters_name, self.on_clinografia_change) QtHandler.set_combobox(combo_orientacao_vertente, rasters_name, self.on_orientacao_vertente_change) QtHandler.set_combobox(combo_proximidade_estradas, rasters_name, self.on_proximidade_estradas_change) QtHandler.set_combobox(combo_hipsometria, rasters_name, self.on_hipsometria_change) QtHandler.set_combobox(combo_linha_transmissao, vectors_name, self.on_linha_transmissao_change) self.__combo_vegetacao = combo_vegetacao self.__combo_clinografia = combo_clinografia self.__combo_orientacao_vertente = combo_orientacao_vertente self.__combo_proximidade_estradas = combo_proximidade_estradas self.__combo_hipsometria = combo_hipsometria self.__combo_linha_transmissao = combo_linha_transmissao
def destroy(self): self.__ignicao_combo_lt.clear() self.__ignicao_combo_queimadas.clear() self.__ignicao_combo_grid.clear() self.__ignicao_combo_insolacao.clear() self.__ignicao_combo_temperatura_maxima.clear() self.__ignicao_combo_velocidade_vento.clear() self.__ignicao_combo_censo_ibge.clear() self.__ignicao_combo_uso_solo.clear() self.__ignicao_combo_gndvi.clear() self.__ignicao_combo_ndvi.clear() self.__ignicao_combo_area_basal.clear() self.__ignicao_combo_densidade.clear() self.__ignicao_combo_volume.clear() self.__ignicao_combo_altitude.clear() self.__qt_raster.clear_combobox() self.__qt_vector.clear_combobox() QtHandler.disconnect(self.__ignicao_combo_lt.currentIndexChanged) QtHandler.disconnect( self.__ignicao_combo_queimadas.currentIndexChanged) QtHandler.disconnect(self.__ignicao_checkbox_lt.toggled) QtHandler.disconnect(self.__ignicao_checkbox_grid.toggled) QtHandler.disconnect( self.__ignicao_checkbox_habilitar_entradas.toggled) QtHandler.disconnect(self.__ignicao_checkbox_habilitar_formula.toggled) self.__qt_raster = None self.__qt_vector = None self.__ignicao_combo_lt = None self.__ignicao_combo_grid = None self.__ignicao_combo_insolacao = None self.__ignicao_combo_temperatura_maxima = None self.__ignicao_combo_velocidade_vento = None self.__ignicao_combo_censo_ibge = None self.__ignicao_combo_uso_solo = None self.__ignicao_combo_gndvi = None self.__ignicao_combo_ndvi = None self.__ignicao_combo_area_basal = None self.__ignicao_combo_densidade = None self.__ignicao_combo_volume = None self.__ignicao_combo_queimadas = None self.__ignicao_combo_altitude = None