def testEditingGeometryUsingQgisApi(self): layer =self._getQgisTestLayer() self.assertTrue(layer.startEditing()) features = list(layer.getFeatures()) layer.changeGeometry(features[0].id(), QgsGeometry.fromPoint(QgsPoint(123, 456))) layer.changeAttributeValue(features[0].id(), 1, None) iface.showAttributeTable(layer) self.assertTrue(layer.commitChanges())
def testAddingFeatureUsingQgisApi(self): layer =self._getQgisTestLayer() self.assertTrue(layer.startEditing()) feat = QgsFeature(layer.pendingFields()) feat.setAttributes([5, 5]) layer.addFeatures([feat]) iface.showAttributeTable(layer) feat.setGeometry(QgsGeometry.fromPoint(QgsPoint(123, 456))) self.assertTrue(layer.commitChanges())
def testAddingFeatureUsingQgisApi(self): layer = self._getQgisTestLayer() self.assertTrue(layer.startEditing()) feat = QgsFeature(layer.pendingFields()) feat.setAttributes([5, 5]) layer.addFeatures([feat]) iface.showAttributeTable(layer) feat.setGeometry(QgsGeometry.fromPoint(QgsPoint(123, 456))) self.assertTrue(layer.commitChanges())
def open_count_attribute_table_and_filter(self, count_ids): """Open the attribute table of count filtered on the passed ids""" if not count_ids: push_info("No counts found for this section") return iface.showAttributeTable( self.layers['count'], '"id" in ({})'.format(", ".join(map(str, count_ids))))
def showAttributeTableLayer(self, layer, selected): #Questa funzione chiude tutte le tabelle degli attributi aperte #apre la tabella attributi del layer in input visualizzando i soli elementi selezionati attrTables = [ d for d in QApplication.instance().allWidgets() if d.objectName() == u'QgsAttributeTableDialog' or d.objectName() == u'AttributeTable' ] for x in attrTables: x.close() attDialog = iface.showAttributeTable(layer) QSettings().setValue("/Qgis/dockAttributeTable", True) if selected: attDialog.findChild(QAction, "mActionSelectedFilter").trigger()
def openAttributeTable(layerName=None, typeName=None): # if layerName and typeName: # if layerExists(layerName, typeName): # setActiveLayer(layerName) iface.showAttributeTable(iface.activeLayer())
def run(self): """Run method that performs all the real work""" # Create the dialog with elements (after translation) and keep reference # Only create GUI ONCE in callback, so that it will only load when the plugin is started if self.first_start == True: self.first_start = False self.dlg = CoordListDialog() # Set CRS widget value. self.dlg.mQgsProjectionSelectionWidget.setCrs( self.iface.activeLayer().crs()) # Define sourse layer features - control layer = self.iface.activeLayer() if layer is None: QMessageBox.warning( None, "Warning!", "No selected layer! Select one feature on active layer.") return None if (layer.type() != 0): QMessageBox.warning(None, "Warning!", "Layer selected is not vector!") return None if layer.selectedFeatureCount() == 0: QMessageBox.warning( None, "Warning!", "No feature selected! Select one feature on active layer.") return None if layer.selectedFeatureCount() > 1: QMessageBox.warning(None, "Warning!", "More than one feature is selected!") return None # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. # from qgis.core import * from qgis.PyQt.QtCore import QVariant # Define sourse layer features - control layer = self.iface.activeLayer() crs = layer.crs() destCrs = self.dlg.mQgsProjectionSelectionWidget.crs() # Transform transformContext = QgsProject.instance().transformContext() xform = QgsCoordinateTransform(crs, destCrs, transformContext) # Create layer with destination CRS vl = QgsVectorLayer('Point?crs=' + destCrs.toWkt(), 'Coord_' + destCrs.description(), 'memory') pr = vl.dataProvider() pr.addAttributes([ QgsField("pid", QVariant.Int), QgsField("x", QVariant.Double), QgsField("y", QVariant.Double), QgsField("len", QVariant.Double), QgsField("azmt", QVariant.Double) ]) vl.updateFields() # Define selected obj feat = layer.selectedFeatures() geom = feat[0].geometry() QgsMessageLog.logMessage(str(geom)) # Find out type o geometry # the geometry type can be of single or multi type # We work with Polyline, Polygon, geomSingleType = QgsWkbTypes.isSingleType(geom.wkbType()) if geom.type() == QgsWkbTypes.LineGeometry: if geomSingleType: coords = geom.asPolyline() geomType = 'sLine' # print("Polyline") else: coords = geom.asMultiPolyline() geomType = 'mLine' # print("MultiPolyline") elif geom.type() == QgsWkbTypes.PolygonGeometry: if geomSingleType: coords = geom.asPolygon() geomType = 'sPoly' # print("Polygon") else: coords = geom.asMultiPolygon() geomType = 'mPoly' # print("MultiPolygon") else: QMessageBox.warning(None, "Warning!", "Unknown or invalid geometry") return None # We work only pline or polygon or multy # Make a point list pointId = 0 pointList = [] if geomType == 'sLine': nodes = len(coords) for n, pnt in enumerate(coords): if n == nodes: break pointId += 1 pointList.append([nodes, n, pointId, pnt]) if geomType == 'sPoly': for part in coords: nodes = len(part) - 1 for n, pnt in enumerate(part): if n == nodes: break pointId += 1 pointList.append([nodes, n, pointId, pnt]) if geomType == 'mLine': for part in coords: nodes = len(part) for n, pnt in enumerate(part): if n == nodes: break pointId += 1 pointList.append([nodes, n, pointId, pnt]) if geomType == 'mPoly': for mult in coords: for part in mult: nodes = len(part) - 1 for n, pnt in enumerate(part): if n == nodes: break pointId += 1 pointList.append([nodes, n, pointId, pnt]) # Create layer with geodata for nodes, n, pntId, point in pointList: thisPoint = xform.transform(QgsPointXY(point.x(), point.y())) x = thisPoint if n == 0: firstPoint = thisPoint if n == nodes - 1: nextPoint = firstPoint else: nextItem = pointList[pntId] nextPoint = xform.transform(nextItem[3].x(), nextItem[3].y()) # Create a measure object distance = QgsDistanceArea() # If long/lat set ellipsoid if destCrs.toProj().find('+proj=longlat') >= 0: distance.setEllipsoid(destCrs.ellipsoidAcronym()) lenght = distance.measureLine(thisPoint, nextPoint) azim = distance.bearing(thisPoint, nextPoint) * 180 / math.pi else: # distance.setEllipsoidalMode(True) lenght = distance.measureLine(thisPoint, nextPoint) azim = distance.bearing(thisPoint, nextPoint) * 180 / math.pi #QMessageBox.warning(None, "Warning!", str(thisPoint)) # Insert in layer f = QgsFeature() f.setGeometry(QgsGeometry.fromPointXY(thisPoint)) f.setAttributes( [pntId, thisPoint.x(), thisPoint.y(), lenght, azim]) pr.addFeature(f) # Commit new layer and add to map vl.updateExtents() QgsProject.instance().addMapLayer(vl) # Labeling settings = QgsPalLayerSettings() settings.fieldName = 'pid' labeling = QgsVectorLayerSimpleLabeling(settings) lv = self.iface.activeLayer() lv.setLabeling(labeling) lv.setLabelsEnabled(True) lv.triggerRepaint() # Show attribute Table if self.dlg.checkBox.isChecked(): iface.showAttributeTable(iface.activeLayer()) else: pass
def run(self): #CARREGA A LISTA DOS NOMES DOS LAYER DA TOC layers = self.iface.legendInterface().layers() layer_list = [] i = 0 iObra = 0 iLote = 0 for layer in layers: nomeLayer = layer.name() layer_list.append(nomeLayer) if 'obra' in str(nomeLayer).lower(): iObra = i if 'lote' in str(nomeLayer).lower(): iLote = i i = i + 1 #SELECIONAR O SHP DA OBRA self.dlg.comboBox_obra.clear() self.dlg.comboBox_obra.addItems(layer_list) #SELECIONAR O SHP DOS LOTES self.dlg.comboBox_lote.clear() self.dlg.comboBox_lote.addItems(layer_list) #SELECIONAR OBRA E LOTE AUTOMATICAMENTE self.dlg.comboBox_obra.setCurrentIndex(iObra) self.dlg.comboBox_lote.setCurrentIndex(iLote) """Run method that performs all the real work""" # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. # pass selectedLayerIndex = self.dlg.comboBox_obra.currentIndex() selectedLayerObra = layers[selectedLayerIndex] selectedLayerIndex = self.dlg.comboBox_lote.currentIndex() selectedLayerLote = layers[selectedLayerIndex] #LISTA DOS CAMPOS OBTIDA PELO dataProvider lotes = selectedLayerLote.dataProvider() #CRIACAO DE NOVO CAMPOS EM LOTES field_dista1_index = lotes.fields().indexFromName("area") if field_dista1_index == -1: #CRIAR O CAMPO AREA, POIS ELE NAO EXISTE lotes.addAttributes( [QgsField("area", QVariant.Double, 'double', 20, 2)]) selectedLayerLote.updateFields() field_dista1_index = lotes.fields().indexFromName("distobra") if field_dista1_index == -1: #CRIAR O CAMPO DISTOBRA, POIS ELE NAO EXISTE lotes.addAttributes( [QgsField("distobra", QVariant.Double, 'double', 20, 2)]) selectedLayerLote.updateFields() field_valor_index = lotes.fields().indexFromName("valor") if field_valor_index == -1: #CRIAR O CAMPO VALOR, POIS ELE NAO EXISTE lotes.addAttributes( [QgsField("valor", QVariant.Double, 'double', 20, 2)]) selectedLayerLote.updateFields() field_valtot_index = lotes.fields().indexFromName("valtot") if field_valtot_index == -1: #CRIAR O CAMPO VALTOT, POIS ELE NAO EXISTE lotes.addAttributes( [QgsField("valtot", QVariant.Double, 'double', 20, 2)]) selectedLayerLote.updateFields() #DETECTA OS IDs DOS NOVOS CAMPOS CRIADOS id_field_area = lotes.fields().indexFromName('area') id_field_distObra = lotes.fields().indexFromName('distobra') id_field_valor = lotes.fields().indexFromName('valor') id_field_valtot = lotes.fields().indexFromName('valtot') #PARAMETRO PARA O CALCULO DE VALOR1 if self.dlg.radioButton_pav.isChecked(): #radioButton_pavimentacao_via localmin1 = 0.00 localmax1 = 100.00 valor1 = 10.00 localmin2 = 100.00 localmax2 = 200.00 valor2 = 5.00 localmin3 = 200.00 localmax3 = 300.00 valor3 = 2.50 #LE AS COORDENADA DA OBRA for fObra in selectedLayerObra.getFeatures(): geomObra = fObra.geometry() #INICIO DA EDICAO DOS DADOS selectedLayerLote.startEditing() #LE AS COORDENADA DOS LOTES val_tot_geral = 0.00 val_tot_area = 0.00 tot_lotes = 0 for fLote in selectedLayerLote.getFeatures(): id = fLote.id() geomLote = fLote.geometry() #CALCULO DA DISTANCIA ENTRE POLIGONOS E AREA DO LOTE distobra = QgsGeometry.distance(geomLote, geomObra) val_area = QgsGeometry.area(geomLote) valor = 0.0 if localmin1 <= distobra < localmax1: valor = valor1 elif localmin2 <= distobra < localmax2: valor = valor2 elif localmin3 <= distobra < localmax3: valor = valor3 #TOTALIZA VALOR POR LOTE val_tot_lot = val_area * valor #TOTALIZA POR LOTE AFETADO if valor > 0: val_tot_area = val_tot_area + val_area val_tot_geral = val_tot_geral + val_tot_lot tot_lotes = tot_lotes + 1 #GRAVA OS VALORES NA CAMADA DE LOTES selectedLayerLote.changeAttributeValue(id, id_field_area, geomLote.area()) selectedLayerLote.changeAttributeValue(id, id_field_distObra, distobra) selectedLayerLote.changeAttributeValue(id, id_field_valor, valor) selectedLayerLote.changeAttributeValue(id, id_field_valtot, val_tot_lot) #COMITA AS MUDANCAS selectedLayerLote.commitChanges() iface.messageBar().pushMessage("BID - VALORIZA SOLO URBANO", "Calculo realizado com sucesso!", level=QgsMessageBar.INFO, duration=5) #ABRE A TABELA DE ATRIBUTOS DOS LOTES iface.showAttributeTable(selectedLayerLote) #FORMATA A MENSAGEM tot_tributo_geral = val_tot_geral * 0.02 tot_valor = round(val_tot_geral, 2) tot_area = round(val_tot_area, 2) tot_tributo = round(tot_tributo_geral, 2) tot_valor_formatado = '{0:,}'.format(tot_valor).replace(',', '.') tot_tributo_formatado = '{0:,}'.format(tot_tributo).replace( ',', '.') tot_area_formatado = '{0:,}'.format(tot_area).replace(',', '.') tot_lotes_formatado = '{0:,}'.format(tot_lotes).replace(',', '.') txt1 = '%s' % ("VALORIZA SOLO URBANO\n\n\n") txt2 = 'Total Lotes......................= %s\n\n' % ( tot_lotes_formatado) txt3 = 'Total Area (m2)..............= %s\n\n' % ( tot_area_formatado) txt4 = 'Total Incremento ($).....= %s\n\n' % (tot_valor_formatado) txt5 = 'Total Aliquota a 2 ($).....= %s\n' % ( tot_tributo_formatado) txt6 = '%s%s%s%s%s' % (txt1, txt2, txt3, txt4, txt5) import ctypes MessageBox = ctypes.windll.user32.MessageBoxA MessageBox(None, txt6, ' B I D / A B R A S F', 0)
def saveinfo(self): tree = ET.parse( urllib.request.urlopen( "https://ratings.food.gov.uk/authorities/en-GB/xml")) root = tree.getroot() # open a file for writing if not os.path.exists('C:/FHR_data'): os.makedirs('C:/FHR_data') path = 'C:/FHR_data/LA_codes.csv' test_data = open(path, 'w') # create the csv writer object cswwriter = csv.writer(test_data, delimiter='|') estabilishment_head = [] count = 0 for member in root.findall('WebLocalAuthorityAPI'): estabilishment = [] if count == 0: estabilishment_head.append('Name') estabilishment_head.append('Code') estabilishment_head.append('Creation') estabilishment_head.append('Updated') estabilishment_head.append('Count') w = csv.writer(test_data, delimiter='|') w.writerow(estabilishment_head) count = count + 1 if member.find('Name') is not None: Name = member.find('Name').text estabilishment.append(Name) else: estabilishment.append('') if member.find('LocalAuthorityIdCode') is not None: LocalAuthorityIdCode = member.find('LocalAuthorityIdCode').text estabilishment.append(LocalAuthorityIdCode) else: estabilishment.append('') if member.find('CreationDate') is not None: CreationDate = member.find('CreationDate').text estabilishment.append(CreationDate) else: estabilishment.append('') if member.find('LastPublishedDate') is not None: LastPublishedDate = member.find('LastPublishedDate').text estabilishment.append(LastPublishedDate) else: estabilishment.append('') if member.find('EstablishmentCount') is not None: EstablishmentCount = member.find('EstablishmentCount').text estabilishment.append(EstablishmentCount) else: estabilishment.append('') w = csv.writer(test_data, delimiter='|') w.writerow(estabilishment) test_data.close() uri = "file:///C:/FHR_data/LA_codes.csv?delimiter=|" layer_csv = QgsVectorLayer(uri, "LA_codes", "delimitedtext") if not layer_csv.isValid(): print("Layer failed to load!") QgsProject.instance().addMapLayer(layer_csv) iface.showAttributeTable(iface.activeLayer()) datafile = open('C:/FHR_data/LA_codes.csv', 'r') myreader = csv.reader(datafile) '''
def processAlgorithm(self, parameters, context, feedback): """ Here is where the processing itself takes place. """ ### RETRIEVE PARAMETERS ### # Retrieve the input vector layer = study area study_area = self.parameterAsSource(parameters, self.STUDY_AREA, context) # Retrieve the output PostGIS layer name and format it layer_name = self.parameterAsString(parameters, self.OUTPUT_NAME, context) ts = datetime.now() format_name = "{} {}".format(layer_name, str(ts.strftime('%Y%m%d_%H%M%S'))) # Retrieve the taxonomic rank taxonomic_ranks_labels = [ "Groupe taxo", "Règne", "Phylum", "Classe", "Ordre", "Famille", "Groupe 1 INPN", "Groupe 2 INPN" ] taxonomic_ranks_db = [ "groupe_taxo", "regne", "phylum", "classe", "ordre", "famille", "obs.group1_inpn", "obs.group2_inpn" ] taxonomic_rank_label = taxonomic_ranks_labels[self.parameterAsEnum( parameters, self.TAXONOMIC_RANK, context)] taxonomic_rank_db = taxonomic_ranks_db[self.parameterAsEnum( parameters, self.TAXONOMIC_RANK, context)] # Retrieve the taxons filters groupe_taxo = [ self.db_variables.value('groupe_taxo')[i] for i in ( self.parameterAsEnums(parameters, self.GROUPE_TAXO, context)) ] regne = [ self.db_variables.value('regne')[i] for i in (self.parameterAsEnums(parameters, self.REGNE, context)) ] phylum = [ self.db_variables.value('phylum')[i] for i in (self.parameterAsEnums(parameters, self.PHYLUM, context)) ] classe = [ self.db_variables.value('classe')[i] for i in (self.parameterAsEnums(parameters, self.CLASSE, context)) ] ordre = [ self.db_variables.value('ordre')[i] for i in (self.parameterAsEnums(parameters, self.ORDRE, context)) ] famille = [ self.db_variables.value('famille')[i] for i in (self.parameterAsEnums(parameters, self.FAMILLE, context)) ] group1_inpn = [ self.db_variables.value('group1_inpn')[i] for i in ( self.parameterAsEnums(parameters, self.GROUP1_INPN, context)) ] group2_inpn = [ self.db_variables.value('group2_inpn')[i] for i in ( self.parameterAsEnums(parameters, self.GROUP2_INPN, context)) ] # Retrieve the datetime filter period = self.period_variables[self.parameterAsEnum( parameters, self.PERIOD, context)] # Retrieve the extra "where" conditions extra_where = self.parameterAsString(parameters, self.EXTRA_WHERE, context) # Retrieve the histogram parameter histogram_variables = [ "Pas d'histogramme", "Nb de données", "Nb d'espèces", "Nb d'observateurs", "Nb de dates", "Nb de données de mortalité" ] histogram_option = histogram_variables[self.parameterAsEnum( parameters, self.HISTOGRAM_OPTIONS, context)] if histogram_option != "Pas d'histogramme": output_histogram = self.parameterAsFileOutput( parameters, self.OUTPUT_HISTOGRAM, context) if output_histogram == "": raise QgsProcessingException( "Veuillez renseigner un emplacement pour enregistrer votre histogramme !" ) ### CONSTRUCT "WHERE" CLAUSE (SQL) ### # Construct the sql array containing the study area's features geometry array_polygons = construct_sql_array_polygons(study_area) # Define the "where" clause of the SQL query, aiming to retrieve the output PostGIS layer = summary table where = "is_valid and is_present and ST_within(obs.geom, ST_union({}))".format( array_polygons) # Define a dictionnary with the aggregated taxons filters and complete the "where" clause thanks to it taxons_filters = { "groupe_taxo": groupe_taxo, "regne": regne, "phylum": phylum, "classe": classe, "ordre": ordre, "famille": famille, "obs.group1_inpn": group1_inpn, "obs.group2_inpn": group2_inpn } taxons_where = construct_sql_taxons_filter(taxons_filters) where += taxons_where # Complete the "where" clause with the datetime filter datetime_where = construct_sql_datetime_filter(self, period, ts, parameters, context) where += datetime_where # Complete the "where" clause with the extra conditions where += " " + extra_where ### EXECUTE THE SQL QUERY ### # Retrieve the data base connection name connection = self.parameterAsString(parameters, self.DATABASE, context) # URI --> Configures connection to database and the SQL query uri = postgis.uri_from_name(connection) # Define the SQL query query = """WITH obs AS ( SELECT obs.* FROM src_lpodatas.v_c_observations obs LEFT JOIN taxonomie.taxref t ON obs.taxref_cdnom = t.cd_nom WHERE {}), communes AS ( SELECT DISTINCT obs.id_synthese, la.area_name FROM obs LEFT JOIN gn_synthese.cor_area_synthese cor ON obs.id_synthese = cor.id_synthese JOIN ref_geo.l_areas la ON cor.id_area = la.id_area WHERE la.id_type = (SELECT id_type FROM ref_geo.bib_areas_types WHERE type_code = 'COM')), total_count AS ( SELECT COUNT(*) AS total_count FROM obs) SELECT row_number() OVER () AS id, COALESCE({}, 'Pas de correspondance taxref') AS "{}", {} COUNT(*) AS "Nb de données", ROUND(COUNT(*)::decimal/total_count, 4)*100 AS "Nb données / Nb données TOTAL (%)", COUNT(DISTINCT t.cd_ref) FILTER (WHERE t.id_rang='ES') AS "Nb d'espèces", COUNT(DISTINCT observateur) AS "Nb d'observateurs", COUNT(DISTINCT date) AS "Nb de dates", SUM(CASE WHEN mortalite THEN 1 ELSE 0 END) AS "Nb de données de mortalité", max(nombre_total) AS "Nb d'individus max", min (date_an) AS "Année première obs", max(date_an) AS "Année dernière obs", string_agg(DISTINCT obs.nom_vern,', ') FILTER (WHERE t.id_rang='ES') AS "Liste des espèces", string_agg(DISTINCT com.area_name,', ') AS "Communes", string_agg(DISTINCT obs.source,', ') AS "Sources" FROM total_count, obs LEFT JOIN taxonomie.taxref t ON obs.taxref_cdnom=t.cd_nom LEFT JOIN communes com ON obs.id_synthese = com.id_synthese GROUP BY {}{}, total_count ORDER BY {}{}""".format( where, taxonomic_rank_db, taxonomic_rank_label, 'groupe_taxo AS "Groupe taxo", ' if taxonomic_rank_label in ['Ordre', 'Famille'] else "", "groupe_taxo, " if taxonomic_rank_label in ['Ordre', 'Famille'] else "", taxonomic_rank_db, "groupe_taxo, " if taxonomic_rank_label in ['Ordre', 'Famille'] else "", taxonomic_rank_db) #feedback.pushInfo(query) # Retrieve the boolean add_table add_table = self.parameterAsBool(parameters, self.ADD_TABLE, context) if add_table: # Define the name of the PostGIS summary table which will be created in the DB table_name = simplify_name(format_name) # Define the SQL queries queries = construct_queries_list(table_name, query) # Execute the SQL queries execute_sql_queries(context, feedback, connection, queries) # Format the URI uri.setDataSource(None, table_name, None, "", "id") else: # Format the URI with the query uri.setDataSource("", "(" + query + ")", None, "", "id") ### GET THE OUTPUT LAYER ### # Retrieve the output PostGIS layer = summary table layer_summary = QgsVectorLayer(uri.uri(), format_name, "postgres") # Check if the PostGIS layer is valid check_layer_is_valid(feedback, layer_summary) # Load the PostGIS layer load_layer(context, layer_summary) # Open the attribute table of the PostGIS layer iface.showAttributeTable(layer_summary) iface.setActiveLayer(layer_summary) ### CONSTRUCT THE HISTOGRAM ### if histogram_option != "Pas d'histogramme": plt.close() x_var = [ (feature[taxonomic_rank_label] if feature[taxonomic_rank_label] != 'Pas de correspondance taxref' else 'Aucune correspondance') for feature in layer_summary.getFeatures() ] y_var = [ int(feature[histogram_option]) for feature in layer_summary.getFeatures() ] if len(x_var) <= 20: plt.subplots_adjust(bottom=0.5) elif len(x_var) <= 80: plt.figure(figsize=(20, 8)) plt.subplots_adjust(bottom=0.3, left=0.05, right=0.95) else: plt.figure(figsize=(40, 16)) plt.subplots_adjust(bottom=0.2, left=0.03, right=0.97) plt.bar(range(len(x_var)), y_var, tick_label=x_var) plt.xticks(rotation='vertical') plt.xlabel(self.taxonomic_ranks_variables[self.parameterAsEnum( parameters, self.TAXONOMIC_RANK, context)]) plt.ylabel(histogram_option.replace("Nb", "Nombre")) plt.title('{} par {}'.format( histogram_option.replace("Nb", "Nombre"), taxonomic_rank_label[0].lower() + taxonomic_rank_label[1:].replace("taxo", "taxonomique"))) if output_histogram[-4:] != ".png": output_histogram += ".png" plt.savefig(output_histogram) #plt.show() return {self.OUTPUT: layer_summary.id()}
def processAlgorithm(self, parameters, context, feedback): """ Here is where the processing itself takes place. """ ### RETRIEVE PARAMETERS ### # Retrieve the input vector layer = study area study_area = self.parameterAsSource(parameters, self.STUDY_AREA, context) # Retrieve the output PostGIS layer name and format it layer_name = self.parameterAsString(parameters, self.OUTPUT_NAME, context) ts = datetime.now() format_name = "{} {}".format(layer_name, str(ts.strftime('%Y%m%d_%H%M%S'))) # Retrieve the taxons filters groupe_taxo = [self.db_variables.value('groupe_taxo')[i] for i in (self.parameterAsEnums(parameters, self.GROUPE_TAXO, context))] regne = [self.db_variables.value('regne')[i] for i in (self.parameterAsEnums(parameters, self.REGNE, context))] phylum = [self.db_variables.value('phylum')[i] for i in (self.parameterAsEnums(parameters, self.PHYLUM, context))] classe = [self.db_variables.value('classe')[i] for i in (self.parameterAsEnums(parameters, self.CLASSE, context))] ordre = [self.db_variables.value('ordre')[i] for i in (self.parameterAsEnums(parameters, self.ORDRE, context))] famille = [self.db_variables.value('famille')[i] for i in (self.parameterAsEnums(parameters, self.FAMILLE, context))] group1_inpn = [self.db_variables.value('group1_inpn')[i] for i in (self.parameterAsEnums(parameters, self.GROUP1_INPN, context))] group2_inpn = [self.db_variables.value('group2_inpn')[i] for i in (self.parameterAsEnums(parameters, self.GROUP2_INPN, context))] # Retrieve the datetime filter period_type = self.period_variables[self.parameterAsEnum(parameters, self.PERIOD, context)] # Retrieve the extra "where" conditions extra_where = self.parameterAsString(parameters, self.EXTRA_WHERE, context) ### CONSTRUCT "WHERE" CLAUSE (SQL) ### # Construct the sql array containing the study area's features geometry array_polygons = construct_sql_array_polygons(study_area) # Define the "where" clause of the SQL query, aiming to retrieve the output PostGIS layer = summary table where = """is_valid and is_present and ST_within(obs.geom, ST_union({}))""".format(array_polygons) # Define a dictionnary with the aggregated taxons filters and complete the "where" clause thanks to it taxons_filters = { "groupe_taxo": groupe_taxo, "regne": regne, "phylum": phylum, "classe": classe, "ordre": ordre, "famille": famille, "obs.group1_inpn": group1_inpn, "obs.group2_inpn": group2_inpn } taxons_where = construct_sql_taxons_filter(taxons_filters) where += taxons_where # Complete the "where" clause with the datetime filter datetime_where = construct_sql_datetime_filter(self, period_type, ts, parameters, context) where += datetime_where # Complete the "where" clause with the extra conditions where += " " + extra_where ### EXECUTE THE SQL QUERY ### # Retrieve the data base connection name connection = self.parameterAsString(parameters, self.DATABASE, context) # URI --> Configures connection to database and the SQL query uri = postgis.uri_from_name(connection) # Define the SQL query query = """WITH obs AS ( SELECT obs.* FROM src_lpodatas.v_c_observations obs LEFT JOIN taxonomie.taxref t ON obs.taxref_cdnom = t.cd_nom WHERE {}), communes AS ( SELECT DISTINCT obs.id_synthese, la.area_name FROM obs LEFT JOIN gn_synthese.cor_area_synthese cor ON obs.id_synthese = cor.id_synthese JOIN ref_geo.l_areas la ON cor.id_area = la.id_area WHERE la.id_type = (SELECT id_type FROM ref_geo.bib_areas_types WHERE type_code = 'COM')), total_count AS ( SELECT COUNT(*) AS total_count FROM obs), data AS ( SELECT /*obs.source_id_sp , */obs.taxref_cdnom AS cd_nom , t.cd_ref , r.nom_rang , obs.groupe_taxo , obs.nom_vern , obs.nom_sci , COUNT(*) AS nb_donnees , COUNT(DISTINCT obs.observateur) AS nb_observateurs , COUNT(DISTINCT obs.date) AS nb_dates , SUM(CASE WHEN mortalite THEN 1 ELSE 0 END) AS nb_mortalite , lr.lr_france , lr.lrra , lr.lrauv , p.dir_hab , p.dir_ois , p.protection_nat , p.conv_berne , p.conv_bonn , max(sn.code_nidif) AS max_atlas_code , max(obs.nombre_total) AS nb_individus_max , min(obs.date_an) AS premiere_observation , max(obs.date_an) AS derniere_observation , string_agg(DISTINCT com.area_name, ', ') /*FILTER (WHERE bib.type_code = 'COM')*/ AS communes , string_agg(DISTINCT obs.source, ', ') AS sources FROM obs LEFT JOIN referentiel.statut_nidif sn ON obs.oiso_code_nidif = sn.code_repro LEFT JOIN taxonomie.taxref t ON obs.taxref_cdnom = t.cd_nom LEFT JOIN taxonomie.bib_taxref_rangs r ON t.id_rang = r.id_rang LEFT JOIN communes com ON obs.id_synthese = com.id_synthese LEFT JOIN taxonomie.vm_statut_lr lr ON (obs.taxref_cdnom, obs.nom_sci) = (lr.cd_nom, lr.vn_nom_sci) LEFT JOIN taxonomie.vm_statut_protection p ON (obs.taxref_cdnom, obs.nom_sci) = (p.cd_nom, p.vn_nom_sci) GROUP BY /*obs.source_id_sp , */obs.taxref_cdnom , obs.groupe_taxo , obs.nom_vern , obs.nom_sci , t.cd_ref , r.nom_rang , lr.lr_france , lr.lrra , lr.lrauv , p.dir_hab , p.dir_ois , p.protection_nat , p.conv_berne , p.conv_bonn), synthese AS ( SELECT DISTINCT /*source_id_sp ,*/ cd_nom , cd_ref , nom_rang AS "Rang" , groupe_taxo AS "Groupe taxo" , nom_vern AS "Nom vernaculaire" , nom_sci AS "Nom scientifique" , nb_donnees AS "Nb de données" , ROUND(nb_donnees::DECIMAL / total_count, 4) * 100 AS "Nb données / nb données total (%)" , nb_observateurs AS "Nb d'observateurs" , nb_dates AS "Nb de dates" , nb_mortalite AS "Nb de données de mortalité" , lr_france AS "LR France" , lrra AS "LR Rhône-Alpes" , lrauv AS "LR Auvergne" , dir_hab AS "Directive Habitats" , dir_ois AS "Directive Oiseaux" , protection_nat AS "Protection nationale" , conv_berne AS "Convention de Berne" , conv_bonn AS "Convention de Bonn" , sn2.statut_nidif AS "Statut nidif" , nb_individus_max AS "Nb d'individus max" , premiere_observation AS "Année première obs" , derniere_observation AS "Année dernière obs" , communes AS "Liste de communes" , sources AS "Sources" FROM total_count, data d LEFT JOIN referentiel.statut_nidif sn2 ON d.max_atlas_code = sn2.code_nidif ORDER BY groupe_taxo, nom_vern) SELECT row_number() OVER () AS id, * FROM synthese""".format(where) #feedback.pushInfo(query) # Retrieve the boolean add_table add_table = self.parameterAsBool(parameters, self.ADD_TABLE, context) if add_table: # Define the name of the PostGIS summary table which will be created in the DB table_name = simplify_name(format_name) # Define the SQL queries queries = construct_queries_list(table_name, query) # Execute the SQL queries execute_sql_queries(context, feedback, connection, queries) # Format the URI uri.setDataSource(None, table_name, None, "", "id") else: # Format the URI with the query uri.setDataSource("", "("+query+")", None, "", "id") ### GET THE OUTPUT LAYER ### # Retrieve the output PostGIS layer = summary table layer_summary = QgsVectorLayer(uri.uri(), format_name, "postgres") # Check if the PostGIS layer is valid check_layer_is_valid(feedback, layer_summary) # Load the PostGIS layer load_layer(context, layer_summary) # Open the attribute table of the PostGIS layer iface.showAttributeTable(layer_summary) iface.setActiveLayer(layer_summary) return {self.OUTPUT: layer_summary.id()}
from PyQt4.QtGui import * from PyQt4.QtCore import * from qgis.core import * from qgis.utils import iface wb = QgsVectorLayer('/data/world_borders.shp', 'world_borders', 'ogr') QgsMapLayerRegistry.instance().addMapLayer(wb) active_layer = iface.activeLayer() renderer = active_layer.rendererV2() symbol = renderer.symbol() symbol.setColor(QColor(Qt.red)) iface.mapCanvas().refresh() iface.legendInterface().refreshLayerSymbology(active_layer) iface.showAttributeTable(iface.activeLayer())
def processAlgorithm(self, parameters, context, feedback): """ Here is where the processing itself takes place. """ ### RETRIEVE PARAMETERS ### # Retrieve the input vector layer = study area study_area = self.parameterAsSource(parameters, self.STUDY_AREA, context) # Retrieve the output PostGIS layer name and format it layer_name = self.parameterAsString(parameters, self.OUTPUT_NAME, context) format_name = "{} {}".format(layer_name, str(self.ts.strftime('%Y%m%d_%H%M%S'))) # Retrieve the time interval time_interval = self.interval_variables[self.parameterAsEnum( parameters, self.TIME_INTERVAL, context)] # Retrieve the period start_year = self.parameterAsInt(parameters, self.START_YEAR, context) end_year = self.parameterAsInt(parameters, self.END_YEAR, context) if end_year < start_year: raise QgsProcessingException( "Veuillez renseigner une année de fin postérieure à l'année de début !" ) # Retrieve the taxonomic rank taxonomic_rank = self.taxonomic_ranks_variables[self.parameterAsEnum( parameters, self.TAXONOMIC_RANK, context)] # Retrieve the aggregation type aggregation_type = 'Nombre de données' if taxonomic_rank == 'Groupes taxonomiques': aggregation_type = self.agg_variables[self.parameterAsEnum( parameters, self.AGG, context)] # Retrieve the taxons filters groupe_taxo = [ self.db_variables.value('groupe_taxo')[i] for i in ( self.parameterAsEnums(parameters, self.GROUPE_TAXO, context)) ] regne = [ self.db_variables.value('regne')[i] for i in (self.parameterAsEnums(parameters, self.REGNE, context)) ] phylum = [ self.db_variables.value('phylum')[i] for i in (self.parameterAsEnums(parameters, self.PHYLUM, context)) ] classe = [ self.db_variables.value('classe')[i] for i in (self.parameterAsEnums(parameters, self.CLASSE, context)) ] ordre = [ self.db_variables.value('ordre')[i] for i in (self.parameterAsEnums(parameters, self.ORDRE, context)) ] famille = [ self.db_variables.value('famille')[i] for i in (self.parameterAsEnums(parameters, self.FAMILLE, context)) ] group1_inpn = [ self.db_variables.value('group1_inpn')[i] for i in ( self.parameterAsEnums(parameters, self.GROUP1_INPN, context)) ] group2_inpn = [ self.db_variables.value('group2_inpn')[i] for i in ( self.parameterAsEnums(parameters, self.GROUP2_INPN, context)) ] # Retrieve the extra "where" conditions extra_where = self.parameterAsString(parameters, self.EXTRA_WHERE, context) # Retrieve the histogram parameter add_histogram = self.parameterAsEnums(parameters, self.ADD_HISTOGRAM, context) if len(add_histogram) > 0: output_histogram = self.parameterAsFileOutput( parameters, self.OUTPUT_HISTOGRAM, context) if output_histogram == "": raise QgsProcessingException( "Veuillez renseigner un emplacement pour enregistrer votre histogramme !" ) ### CONSTRUCT "SELECT" CLAUSE (SQL) ### # Select data according to the time interval and the period select_data, x_var = construct_sql_select_data_per_time_interval( self, time_interval, start_year, end_year, aggregation_type, parameters, context) # Select species info (optional) select_species_info = """/*source_id_sp, */taxref_cdnom AS cd_nom, cd_ref, nom_rang as "Rang", groupe_taxo AS "Groupe taxo", obs.nom_vern AS "Nom vernaculaire", nom_sci AS "Nom scientifique\"""" # Select taxonomic groups info (optional) select_taxo_groups_info = 'groupe_taxo AS "Groupe taxo"' ### CONSTRUCT "WHERE" CLAUSE (SQL) ### # Construct the sql array containing the study area's features geometry array_polygons = construct_sql_array_polygons(study_area) # Define the "where" clause of the SQL query, aiming to retrieve the output PostGIS layer = summary table where = "is_valid and is_present and ST_within(obs.geom, ST_union({}))".format( array_polygons) # Define a dictionnary with the aggregated taxons filters and complete the "where" clause thanks to it taxons_filters = { "groupe_taxo": groupe_taxo, "regne": regne, "phylum": phylum, "classe": classe, "ordre": ordre, "famille": famille, "obs.group1_inpn": group1_inpn, "obs.group2_inpn": group2_inpn } taxons_where = construct_sql_taxons_filter(taxons_filters) where += taxons_where # Complete the "where" clause with the extra conditions where += " " + extra_where ### CONSTRUCT "GROUP BY" CLAUSE (SQL) ### # Group by species (optional) group_by_species = "/*source_id_sp, */taxref_cdnom, cd_ref, nom_rang, nom_sci, obs.nom_vern, " if taxonomic_rank == 'Espèces' else "" ### EXECUTE THE SQL QUERY ### # Retrieve the data base connection name connection = self.parameterAsString(parameters, self.DATABASE, context) # URI --> Configures connection to database and the SQL query uri = postgis.uri_from_name(connection) # Define the SQL query query = """SELECT row_number() OVER () AS id, {}{} FROM src_lpodatas.v_c_observations obs LEFT JOIN taxonomie.taxref t ON obs.taxref_cdnom = t.cd_nom LEFT JOIN taxonomie.bib_taxref_rangs r ON t.id_rang = r.id_rang WHERE {} GROUP BY {}groupe_taxo ORDER BY groupe_taxo{}""".format( select_species_info if taxonomic_rank == 'Espèces' else select_taxo_groups_info, select_data, where, group_by_species, ", obs.nom_vern" if taxonomic_rank == 'Espèces' else "") #feedback.pushInfo(query) # Retrieve the boolean add_table add_table = self.parameterAsBool(parameters, self.ADD_TABLE, context) if add_table: # Define the name of the PostGIS summary table which will be created in the DB table_name = simplify_name(format_name) # Define the SQL queries queries = construct_queries_list(table_name, query) # Execute the SQL queries execute_sql_queries(context, feedback, connection, queries) # Format the URI uri.setDataSource(None, table_name, None, "", "id") else: # Format the URI with the query uri.setDataSource("", "(" + query + ")", None, "", "id") ### GET THE OUTPUT LAYER ### # Retrieve the output PostGIS layer = summary table layer_summary = QgsVectorLayer(uri.uri(), format_name, "postgres") # Check if the PostGIS layer is valid check_layer_is_valid(feedback, layer_summary) # Load the PostGIS layer load_layer(context, layer_summary) # Open the attribute table of the PostGIS layer iface.showAttributeTable(layer_summary) iface.setActiveLayer(layer_summary) ### CONSTRUCT THE HISTOGRAM ### if len(add_histogram) > 0: plt.close() y_var = [] for x in x_var: y = 0 for feature in layer_summary.getFeatures(): y += feature[x] y_var.append(y) if len(x_var) <= 20: plt.subplots_adjust(bottom=0.4) elif len(x_var) <= 80: plt.figure(figsize=(20, 8)) plt.subplots_adjust(bottom=0.3, left=0.05, right=0.95) else: plt.figure(figsize=(40, 16)) plt.subplots_adjust(bottom=0.2, left=0.03, right=0.97) plt.bar(range(len(x_var)), y_var, tick_label=x_var) plt.xticks(rotation='vertical') x_label = time_interval.split(' ')[1].title() if x_label[-1] != 's': x_label += 's' plt.xlabel(x_label) plt.ylabel(aggregation_type) plt.title('{} {}'.format( aggregation_type, time_interval[0].lower() + time_interval[1:])) if output_histogram[-4:] != ".png": output_histogram += ".png" plt.savefig(output_histogram) #plt.show() return {self.OUTPUT: layer_summary.id()}
def _openAttributesTable(): layer = _layerFromName("2525") iface.showAttributeTable(layer)
def table(tablename): if not tablename.strip(): layer = iface.activeLayer() else: layer = layer_by_name(tablename) iface.showAttributeTable(layer)
def processAlgorithm(self, parameters, context, feedback): """ Here is where the processing itself takes place. """ ### RETRIEVE PARAMETERS ### # Retrieve the input vector layer = study area study_area = self.parameterAsSource(parameters, self.STUDY_AREA, context) # Retrieve the output PostGIS layer name and format it layer_name = self.parameterAsString(parameters, self.OUTPUT_NAME, context) ts = datetime.now() format_name = "{} {}".format(layer_name, str(ts.strftime('%Y%m%d_%H%M%S'))) # Retrieve the areas type areas_type = self.areas_variables[self.parameterAsEnum(parameters, self.AREAS_TYPE, context)] # Retrieve the taxons filters groupe_taxo = [self.db_variables.value('groupe_taxo')[i] for i in (self.parameterAsEnums(parameters, self.GROUPE_TAXO, context))] regne = [self.db_variables.value('regne')[i] for i in (self.parameterAsEnums(parameters, self.REGNE, context))] phylum = [self.db_variables.value('phylum')[i] for i in (self.parameterAsEnums(parameters, self.PHYLUM, context))] classe = [self.db_variables.value('classe')[i] for i in (self.parameterAsEnums(parameters, self.CLASSE, context))] ordre = [self.db_variables.value('ordre')[i] for i in (self.parameterAsEnums(parameters, self.ORDRE, context))] famille = [self.db_variables.value('famille')[i] for i in (self.parameterAsEnums(parameters, self.FAMILLE, context))] group1_inpn = [self.db_variables.value('group1_inpn')[i] for i in (self.parameterAsEnums(parameters, self.GROUP1_INPN, context))] group2_inpn = [self.db_variables.value('group2_inpn')[i] for i in (self.parameterAsEnums(parameters, self.GROUP2_INPN, context))] # Retrieve the datetime filter period_type = self.period_variables[self.parameterAsEnum(parameters, self.PERIOD, context)] # Retrieve the extra "where" conditions extra_where = self.parameterAsString(parameters, self.EXTRA_WHERE, context) ### CONSTRUCT "WHERE" CLAUSE (SQL) ### # Construct the sql array containing the study area's features geometry array_polygons = construct_sql_array_polygons(study_area) # Define the "where" clause of the SQL query, aiming to retrieve the output PostGIS layer = map data where = "ST_intersects(la.geom, ST_union({}))".format(array_polygons) # Define the "where" filter for selected data where_filter = "is_valid and is_present" # Define a dictionnary with the aggregated taxons filters and complete the "where" clause thanks to it taxons_filters = { "groupe_taxo": groupe_taxo, "regne": regne, "phylum": phylum, "classe": classe, "ordre": ordre, "famille": famille, "obs.group1_inpn": group1_inpn, "obs.group2_inpn": group2_inpn } taxons_where = construct_sql_taxons_filter(taxons_filters) where_filter += taxons_where # Complete the "where" filter with the datetime filter datetime_where = construct_sql_datetime_filter(self, period_type, ts, parameters, context) where_filter += datetime_where # Complete the "where" filter with the extra conditions where_filter += " " + extra_where ### EXECUTE THE SQL QUERY ### # Retrieve the data base connection name connection = self.parameterAsString(parameters, self.DATABASE, context) # URI --> Configures connection to database and the SQL query uri = postgis.uri_from_name(connection) # Define the SQL query query = """SELECT row_number() OVER () AS id, area_name AS "Nom", area_code AS "Code", la.geom, ROUND(ST_area(la.geom)::decimal/1000000, 2) AS "Surface (km2)", COUNT(*) filter (where {}) AS "Nb de données", ROUND((COUNT(*) filter (where {})) / ROUND(ST_area(la.geom)::decimal/1000000, 2), 2) AS "Densité (Nb de données/km2)", COUNT(DISTINCT t.cd_ref) filter (where t.id_rang='ES' and {}) AS "Nb d'espèces", COUNT(DISTINCT observateur) filter (where {}) AS "Nb d'observateurs", COUNT(DISTINCT date) filter (where {}) AS "Nb de dates", SUM(CASE WHEN mortalite THEN 1 ELSE 0 END) filter (where {}) AS "Nb de données de mortalité", string_agg(DISTINCT obs.nom_vern,', ') filter (where t.id_rang='ES' and {}) AS "Liste des espèces observées" FROM ref_geo.l_areas la LEFT JOIN gn_synthese.cor_area_synthese cor on la.id_area=cor.id_area LEFT JOIN src_lpodatas.v_c_observations obs on cor.id_synthese=obs.id_synthese LEFT JOIN taxonomie.taxref t ON obs.taxref_cdnom = t.cd_nom WHERE la.id_type=(SELECT id_type FROM ref_geo.bib_areas_types WHERE type_name = '{}') and {} GROUP BY area_name, area_code, la.geom ORDER BY area_code""".format(where_filter, where_filter, where_filter, where_filter, where_filter, where_filter, where_filter, areas_type, where) #feedback.pushInfo(query) # Retrieve the boolean add_table add_table = self.parameterAsBool(parameters, self.ADD_TABLE, context) if add_table: # Define the name of the PostGIS summary table which will be created in the DB table_name = simplify_name(format_name) # Define the SQL queries queries = construct_queries_list(table_name, query) # Execute the SQL queries execute_sql_queries(context, feedback, connection, queries) # Format the URI uri.setDataSource(None, table_name, "geom", "", "id") else: # Format the URI with the query uri.setDataSource("", "("+query+")", "geom", "", "id") ### GET THE OUTPUT LAYER ### # Retrieve the output PostGIS layer = map data layer_map = QgsVectorLayer(uri.uri(), format_name, "postgres") # Check if the PostGIS layer is valid check_layer_is_valid(feedback, layer_map) # Load the PostGIS layer load_layer(context, layer_map) # Open the attribute table of the PostGIS layer iface.showAttributeTable(layer_map) iface.setActiveLayer(layer_map) ### MANAGE EXPORT ### # Create new valid fields for the sink new_fields = format_layer_export(layer_map) # Retrieve the sink for the export (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context, new_fields, layer_map.wkbType(), layer_map.sourceCrs()) if sink is None: # Return the PostGIS layer return {self.OUTPUT: layer_map.id()} else: # Fill the sink and return it for feature in layer_map.getFeatures(): sink.addFeature(feature) return {self.OUTPUT: dest_id} return {self.OUTPUT: layer_map.id()}
def open_attribute_table(): iface.showAttributeTable(iface.activeLayer())
def openAttributeTable(layer): try: iface.showAttributeTable(layer) return True except: return False