def add_layer(layer: QgsMapLayer, name: str = None, index: int = -1, color: typing.Tuple[int, int, int] = None, size: float = None, file: str = None, parent: QgsLayerTreeNode = None, show_feature_count: bool = True) -> None: if name: layer.setName(name) if isinstance(layer, QgsVectorLayer): if color or size or file: update_symbology(layer, color=color, size=size, file=file) elif isinstance(layer, QgsRasterLayer): # TODO update symbology pass instance = QgsProject.instance() instance.addMapLayer(layer, False) layerTreeNode = QgsLayerTreeLayer(layer) layerTreeNode.setCustomProperty('showFeatureCount', show_feature_count) parent = parent if parent else instance.layerTreeRoot() parent.insertChildNode(index, layerTreeNode)
def writeDBF(pos, pp, pr, save_file, inpname, param, idx): pos.startEditing() for i in range(len(pp)): feat = QgsFeature() feat.setAttributes(pp[i]) pr.addFeatures([feat]) epsgCode = pos.crs().authid() QgsVectorFileWriter.writeAsVectorFormat(pos, save_file + param + '.dbf', "utf-8", QgsCoordinateReferenceSystem(epsgCode), "DBF file") ll = QgsVectorLayer(save_file + param + '.dbf', inpname[:len(inpname) - 4] + param, "ogr") QgsProject.instance().addMapLayer(ll, False) nn = QgsLayerTreeLayer(ll) idx.insertChildNode(0, nn) nn.setCustomProperty("showFeatureCount", True)
def testNodeCustomProperties(self): layer = QgsVectorLayer("Point?field=fldtxt:string", "layer1", "memory") layer1_node = QgsLayerTreeLayer(layer) spy = QSignalSpy(layer1_node.customPropertyChanged) self.assertFalse(layer1_node.customProperty('test')) self.assertNotIn('test', layer1_node.customProperties()) layer1_node.setCustomProperty('test', 'value') self.assertEqual(len(spy), 1) # set to same value, should be no extra signal layer1_node.setCustomProperty('test', 'value') self.assertEqual(len(spy), 1) self.assertIn('test', layer1_node.customProperties()) self.assertEqual(layer1_node.customProperty('test'), 'value') layer1_node.setCustomProperty('test', 'value2') self.assertEqual(len(spy), 2) self.assertIn('test', layer1_node.customProperties()) self.assertEqual(layer1_node.customProperty('test'), 'value2') layer1_node.removeCustomProperty('test') self.assertEqual(len(spy), 3) self.assertFalse(layer1_node.customProperty('test')) self.assertNotIn('test', layer1_node.customProperties()) # already removed, should be no extra signal layer1_node.removeCustomProperty('test') self.assertEqual(len(spy), 3)
def create(self, qgis_project: QgsProject, group=None): if not group: group = qgis_project.layerTreeRoot() existing_layer_source_uris = [ found_layer.layer().dataProvider().dataSourceUri() for found_layer in qgis_project.layerTreeRoot().findLayers() ] static_index = 0 for item in self.items: if isinstance(item, LegendGroup): subgroup = group.findGroup(item.name) if subgroup is None: subgroup = group.addGroup(item.name) item.create(qgis_project, subgroup) subgroup.setExpanded(item.expanded) subgroup.setItemVisibilityChecked(item.checked) subgroup.setIsMutuallyExclusive(item.mutually_exclusive, item.mutually_exclusive_child) else: layer = item.layer if (layer.dataProvider().dataSourceUri() not in existing_layer_source_uris): if self.static_sorting: index = static_index elif layer.isSpatial(): index = get_suggested_index_for_layer( layer, group, self.ignore_node_names) else: index = 0 layernode = QgsLayerTreeLayer(layer) layernode.setExpanded(item.expanded) layernode.setItemVisibilityChecked(item.checked) layernode.setCustomProperty("showFeatureCount", item.featurecount) group.insertChildNode(index, layernode) static_index += 1
def on_click_Inici(self): llistaErrors = self.controlErrorsValida() if len(llistaErrors) != 0: llista = "Llista d'errors:\n\n" for i in range(0, len(llistaErrors)): llista += ("- " + llistaErrors[i] + '\n') QMessageBox.information(None, "Error", llista) return textBox = 'INICI DEL PROCÉS DE VALIDACIÓ:\n' textBox += 'Elminació dels vertex:' self.dlg.text_info.setText(textBox) self.MouText() QApplication.processEvents() conta_errors = 0 self.barraEstat_processant() drop = 'DROP TABLE IF EXISTS "GTC_Update"."UpdateGTC_vertices_pgr";' try: cur.execute(drop) conn.commit() except Exception as e: print("ERROR drop vertexs GTC per actualitzar") self.barraEstat_connectat() print(e.message, e.args) textBox += '...OK\n' textBox += 'Creació d\'una nova topologia' self.dlg.text_info.setText(textBox) self.MouText() QApplication.processEvents() create = 'select pgr_createTopology(\'GTC_Update.UpdateGTC\', 0.001,clean:=true);' try: cur.execute(create) vec = cur.fetchall() conn.commit() if vec[0][0] != 'OK': QMessageBox.information( None, "Error", "No s'ha creat la topologia correctament.") print(vec) return except Exception as e: self.barraEstat_connectat() print("ERROR create vertexs GTC per actualitzar") print(e.message, e.args) textBox += '...OK\n' textBox += 'Comprovació de la nova topologia' self.dlg.text_info.setText(textBox) self.MouText() QApplication.processEvents() create = 'SELECT pgr_analyzeGraph(\'GTC_Update.UpdateGTC\', 0.001);' try: cur.execute(create) vec = cur.fetchall() conn.commit() if vec[0][0] != 'OK': QMessageBox.information( None, "Error", "S'ha detectat un error a la topologia.") self.barraEstat_connectat() return except Exception as e: self.barraEstat_connectat() print("ERROR create vertexs GTC per actualitzar") print(e.message, e.args) textBox += '...OK\n' textBox += 'Comprovació dels punts amb possibles errors: ' self.dlg.text_info.setText(textBox) self.MouText() QApplication.processEvents() select = 'SELECT * FROM "GTC_Update"."UpdateGTC_vertices_pgr" WHERE chk = 1;' try: cur.execute(select) vec = cur.fetchall() conn.commit() if (len(vec) != 0): uri = QgsDataSourceUri() try: uri.setConnection(host1, port1, nomBD1, usuari1, contra1) except: print("Error a la connexio") select = 'SELECT * FROM "GTC_Update"."UpdateGTC_vertices_pgr" WHERE chk = 1' QApplication.processEvents() uri.setDataSource("", "(" + select + ")", "the_geom", "", "id") QApplication.processEvents() ''' # 13.2 Es prepara el titol de la capa que apareixerà a la llegenda ''' titol = "Nodes a revisar" vlayer = QgsVectorLayer(uri.uri(False), titol, "postgres") QApplication.processEvents() if vlayer.isValid(): symbols = vlayer.renderer().symbols(QgsRenderContext()) symbol = symbols[0] '''S'afegeix el color a la nova entitat''' symbol.setColor(QColor.fromRgb(255, 0, 0)) QgsProject.instance().addMapLayer(vlayer, False) root = QgsProject.instance().layerTreeRoot() myLayerNode = QgsLayerTreeLayer(vlayer) root.insertChildNode(0, myLayerNode) myLayerNode.setCustomProperty("showFeatureCount", False) QApplication.processEvents() ''''S'afegeix la capa a la pantalla''' iface.mapCanvas().refresh() #qgis.utils.iface.legendInterface().refreshLayerSymbology(vlayer) else: print("No s'ha carregat la capa de punts") self.barraEstat_connectat() QApplication.processEvents() textBox += 'S\'ha(n) detectat ' + str( len(vec)) + ' punt(s) amb possibles errades.\n' self.dlg.text_info.setText(textBox) self.MouText() QApplication.processEvents() return except Exception as e: self.barraEstat_connectat() print("ERROR create vertexs GTC per actualitzar") print(e.message[0].decode('utf8'), e.args) return textBox += 'No s\'han detectat errades.\n' textBox += 'Detecció de trams aïllats: ' self.dlg.text_info.setText(textBox) self.MouText() QApplication.processEvents() select = 'SELECT a.* FROM "GTC_Update"."UpdateGTC" a, "GTC_Update"."UpdateGTC_vertices_pgr" b, "GTC_Update"."UpdateGTC_vertices_pgr" c WHERE a.source=b.id AND b.cnt=1 AND a.target=c.id AND c.cnt=1;' try: cur.execute(select) vec = cur.fetchall() conn.commit() if (len(vec) != 0): uri = QgsDataSourceUri() try: uri.setConnection(host1, port1, nomBD1, usuari1, contra1) except: print("Error a la connexio") select = 'SELECT a.* FROM "GTC_Update"."UpdateGTC" a, "GTC_Update"."UpdateGTC_vertices_pgr" b, "GTC_Update"."UpdateGTC_vertices_pgr" c WHERE a.source=b.id AND b.cnt=1 AND a.target=c.id AND c.cnt=1' QApplication.processEvents() uri.setDataSource("", "(" + select + ")", "the_geom", "", "id") QApplication.processEvents() ''' # 13.2 Es prepara el titol de la capa que apareixerà a la llegenda ''' titol = "Trams sense connectivitat a revisar" vlayer = QgsVectorLayer(uri.uri(False), titol, "postgres") QApplication.processEvents() if vlayer.isValid(): symbols = vlayer.renderer().symbols(QgsRenderContext()) symbol = symbols[0] '''S'afegeix el color a la nova entitat''' symbol.setColor(QColor.fromRgb(255, 0, 0)) symbol.setWidth(1) QgsProject.instance().addMapLayer(vlayer, False) root = QgsProject.instance().layerTreeRoot() myLayerNode = QgsLayerTreeLayer(vlayer) root.insertChildNode(0, myLayerNode) myLayerNode.setCustomProperty("showFeatureCount", False) QApplication.processEvents() ''''S'afegeix la capa a la pantalla''' iface.mapCanvas().refresh() #qgis.utils.iface.legendInterface().refreshLayerSymbology(vlayer) else: print("No s'ha carregat la capa de segments aïllats") self.barraEstat_connectat() QApplication.processEvents() textBox += 'S\'ha(n) detectat ' + str( len(vec)) + ' tram(s) aïllat(s).\n' self.dlg.text_info.setText(textBox) self.MouText() QApplication.processEvents() return except Exception as e: self.barraEstat_connectat() print("ERROR Segments aillats") print(e.message, e.args) return textBox += 'No s\'han detectat segments aïllats.\n' self.dlg.text_info.setText(textBox) self.MouText() QApplication.processEvents() #============================================== # 1. LINIES AMB DOS PUNTS I CAMP SOURCE #============================================== self.barraEstat_processant() sql_xarxa = 'select distinct(R.id) id,R.source Vertex, camp from (select S."the_geom",S."id",st_x(st_startpoint(S."the_geom")),S."source",\'S\' camp from "GTC_Update"."UpdateGTC" S where (st_x(st_startpoint(S."the_geom")) not in (select st_x("GTC_Update"."UpdateGTC_vertices_pgr"."the_geom") from "GTC_Update"."UpdateGTC_vertices_pgr")) union ' sql_xarxa += 'select S."the_geom",S."id",st_x(st_endpoint(S."the_geom")),S."target", \'T\' camp from "GTC_Update"."UpdateGTC" S where (st_x(st_endpoint(S."the_geom")) not in (select st_x("GTC_Update"."UpdateGTC_vertices_pgr"."the_geom") from "GTC_Update"."UpdateGTC_vertices_pgr" )) union ' sql_xarxa += 'select S."the_geom",S."id",st_y(st_startpoint(S."the_geom")),S."source",\'S\' camp from "GTC_Update"."UpdateGTC" S where (st_y(st_startpoint(S."the_geom")) not in (select st_y("GTC_Update"."UpdateGTC_vertices_pgr"."the_geom") from "GTC_Update"."UpdateGTC_vertices_pgr" )) union ' sql_xarxa += 'select S."the_geom",S."id",st_y(st_endpoint(S."the_geom")),S."target",\'T\' camp from "GTC_Update"."UpdateGTC" S where (st_y(st_endpoint(S."the_geom")) not in (select st_y("GTC_Update"."UpdateGTC_vertices_pgr"."the_geom") from "GTC_Update"."UpdateGTC_vertices_pgr" )))R where (ST_NPoints(R.the_geom)=2 and R.camp=\'S\') order by R.id,R.source;' #print sql_xarxa try: cur.execute(sql_xarxa) vec = cur.fetchall() conta_errors += len(vec) #print str(len(vec)) for x in range(0, len(vec)): sql_1 = 'select "source","target" from "GTC_Update"."UpdateGTC" where "id"=' + str( vec[x][0]) + ';' cur.execute(sql_1) vec2 = cur.fetchall() update = 'UPDATE "GTC_Update"."UpdateGTC" SET the_geom = ST_AddPoint(the_geom, (select "the_geom" from "GTC_Update"."UpdateGTC_vertices_pgr" where id=' + str( vec2[0][1]) + '),1) WHERE "id"=' + str(vec[x][0]) + ';' cur.execute(update) conn.commit() update = 'UPDATE "GTC_Update"."UpdateGTC" SET the_geom = ST_RemovePoint(the_geom, 0) WHERE "id"=' + str( vec[x][0]) + ';' cur.execute(update) conn.commit() update = 'UPDATE "GTC_Update"."UpdateGTC" SET the_geom = ST_AddPoint(the_geom, (select "the_geom" from "GTC_Update"."UpdateGTC_vertices_pgr" where id=' + str( vec2[0][0]) + '),0) WHERE "id"=' + str(vec[x][0]) + ';' cur.execute(update) conn.commit() update = 'UPDATE "GTC_Update"."UpdateGTC" SET the_geom = ST_RemovePoint(the_geom, ST_NPoints(the_geom) - 1) WHERE "id"=' + str( vec[x][0]) + ';' cur.execute(update) conn.commit() except Exception as e: print(e.message, e.args) print("ERROR SQL_XARXA") #============================================== # 2. LINIES AMB DOS PUNTS I CAMP TARGET #============================================== sql_xarxa = 'select distinct(R.id) id,R.source Vertex, camp from (select S."the_geom",S."id",st_x(st_startpoint(S."the_geom")),S."source",\'S\' camp from "GTC_Update"."UpdateGTC" S where (st_x(st_startpoint(S."the_geom")) not in (select st_x("GTC_Update"."UpdateGTC_vertices_pgr"."the_geom") from "GTC_Update"."UpdateGTC_vertices_pgr")) union ' sql_xarxa += 'select S."the_geom",S."id",st_x(st_endpoint(S."the_geom")),S."target", \'T\' camp from "GTC_Update"."UpdateGTC" S where (st_x(st_endpoint(S."the_geom")) not in (select st_x("GTC_Update"."UpdateGTC_vertices_pgr"."the_geom") from "GTC_Update"."UpdateGTC_vertices_pgr" )) union ' sql_xarxa += 'select S."the_geom",S."id",st_y(st_startpoint(S."the_geom")),S."source",\'S\' camp from "GTC_Update"."UpdateGTC" S where (st_y(st_startpoint(S."the_geom")) not in (select st_y("GTC_Update"."UpdateGTC_vertices_pgr"."the_geom") from "GTC_Update"."UpdateGTC_vertices_pgr" )) union ' sql_xarxa += 'select S."the_geom",S."id",st_y(st_endpoint(S."the_geom")),S."target",\'T\' camp from "GTC_Update"."UpdateGTC" S where (st_y(st_endpoint(S."the_geom")) not in (select st_y("GTC_Update"."UpdateGTC_vertices_pgr"."the_geom") from "GTC_Update"."UpdateGTC_vertices_pgr" )))R where (ST_NPoints(R.the_geom)=2 and R.camp=\'T\') order by R.id,R.source;' #print sql_xarxa try: cur.execute(sql_xarxa) vec = cur.fetchall() conta_errors += len(vec) #print str(len(vec)) for x in range(0, len(vec)): sql_1 = 'select "source","target" from "GTC_Update"."UpdateGTC" where "id"=' + str( vec[x][0]) + ';' cur.execute(sql_1) vec2 = cur.fetchall() update = 'UPDATE "GTC_Update"."UpdateGTC" SET the_geom = ST_AddPoint(the_geom, (select "the_geom" from "GTC_Update"."UpdateGTC_vertices_pgr" where id=' + str( vec2[0][0]) + '),0) WHERE "id"=' + str(vec[x][0]) + ';' cur.execute(update) conn.commit() update = 'UPDATE "GTC_Update"."UpdateGTC" SET the_geom = ST_RemovePoint(the_geom, ST_NPoints(the_geom) - 1) WHERE "id"=' + str( vec[x][0]) + ';' cur.execute(update) conn.commit() update = 'UPDATE "GTC_Update"."UpdateGTC" SET the_geom = ST_AddPoint(the_geom, (select "the_geom" from "GTC_Update"."UpdateGTC_vertices_pgr" where id=' + str( vec2[0][1]) + '),ST_NPoints(the_geom)) WHERE "id"=' + str( vec[x][0]) + ';' cur.execute(update) conn.commit() update = 'UPDATE "GTC_Update"."UpdateGTC" SET the_geom = ST_RemovePoint(the_geom, 0) WHERE "id"=' + str( vec[x][0]) + ';' cur.execute(update) conn.commit() except Exception as e: print(e.message, e.args) print("ERROR SQL_XARXA") #============================================== # 3. LINIES AMB MES DE DOS PUNTS I CAMP SOURCE #============================================== sql_xarxa = 'select distinct(R.id) id,R.source Vertex, camp from (select S."the_geom",S."id",st_x(st_startpoint(S."the_geom")),S."source",\'S\' camp from "GTC_Update"."UpdateGTC" S where (st_x(st_startpoint(S."the_geom")) not in (select st_x("GTC_Update"."UpdateGTC_vertices_pgr"."the_geom") from "GTC_Update"."UpdateGTC_vertices_pgr")) union ' sql_xarxa += 'select S."the_geom",S."id",st_x(st_endpoint(S."the_geom")),S."target", \'T\' camp from "GTC_Update"."UpdateGTC" S where (st_x(st_endpoint(S."the_geom")) not in (select st_x("GTC_Update"."UpdateGTC_vertices_pgr"."the_geom") from "GTC_Update"."UpdateGTC_vertices_pgr" )) union ' sql_xarxa += 'select S."the_geom",S."id",st_y(st_startpoint(S."the_geom")),S."source",\'S\' camp from "GTC_Update"."UpdateGTC" S where (st_y(st_startpoint(S."the_geom")) not in (select st_y("GTC_Update"."UpdateGTC_vertices_pgr"."the_geom") from "GTC_Update"."UpdateGTC_vertices_pgr" )) union ' sql_xarxa += 'select S."the_geom",S."id",st_y(st_endpoint(S."the_geom")),S."target",\'T\' camp from "GTC_Update"."UpdateGTC" S where (st_y(st_endpoint(S."the_geom")) not in (select st_y("GTC_Update"."UpdateGTC_vertices_pgr"."the_geom") from "GTC_Update"."UpdateGTC_vertices_pgr" )))R where (ST_NPoints(R.the_geom)<>2 and R.camp=\'S\') order by R.id,R.source;' #print sql_xarxa try: cur.execute(sql_xarxa) vec = cur.fetchall() conta_errors += len(vec) #print str(len(vec)) for x in range(0, len(vec)): sql_1 = 'select "source","target" from "GTC_Update"."UpdateGTC" where "id"=' + str( vec[x][0]) + ';' cur.execute(sql_1) vec2 = cur.fetchall() update = 'UPDATE "GTC_Update"."UpdateGTC" SET the_geom = ST_RemovePoint(the_geom, 0) WHERE "id"=' + str( vec[x][0]) + ';' cur.execute(update) conn.commit() update = 'UPDATE "GTC_Update"."UpdateGTC" SET the_geom = ST_AddPoint(the_geom, (select "the_geom" from "GTC_Update"."UpdateGTC_vertices_pgr" where id=' + str( vec2[0][0]) + '),0) WHERE "id"=' + str(vec[x][0]) + ';' cur.execute(update) conn.commit() except Exception as e: print(e.message, e.args) print("ERROR SQL_XARXA") #============================================== # 4. LINIES AMB MES DE DOS PUNTS I CAMP TARGET #============================================== sql_xarxa = 'select distinct(R.id) id,R.source Vertex, camp from (select S."the_geom",S."id",st_x(st_startpoint(S."the_geom")),S."source",\'S\' camp from "GTC_Update"."UpdateGTC" S where (st_x(st_startpoint(S."the_geom")) not in (select st_x("GTC_Update"."UpdateGTC_vertices_pgr"."the_geom") from "GTC_Update"."UpdateGTC_vertices_pgr")) union ' sql_xarxa += 'select S."the_geom",S."id",st_x(st_endpoint(S."the_geom")),S."target", \'T\' camp from "GTC_Update"."UpdateGTC" S where (st_x(st_endpoint(S."the_geom")) not in (select st_x("GTC_Update"."UpdateGTC_vertices_pgr"."the_geom") from "GTC_Update"."UpdateGTC_vertices_pgr" )) union ' sql_xarxa += 'select S."the_geom",S."id",st_y(st_startpoint(S."the_geom")),S."source",\'S\' camp from "GTC_Update"."UpdateGTC" S where (st_y(st_startpoint(S."the_geom")) not in (select st_y("GTC_Update"."UpdateGTC_vertices_pgr"."the_geom") from "GTC_Update"."UpdateGTC_vertices_pgr" )) union ' sql_xarxa += 'select S."the_geom",S."id",st_y(st_endpoint(S."the_geom")),S."target",\'T\' camp from "GTC_Update"."UpdateGTC" S where (st_y(st_endpoint(S."the_geom")) not in (select st_y("GTC_Update"."UpdateGTC_vertices_pgr"."the_geom") from "GTC_Update"."UpdateGTC_vertices_pgr" )))R where (ST_NPoints(R.the_geom)<>2 and R.camp=\'T\') order by R.id,R.source;' #print sql_xarxa try: cur.execute(sql_xarxa) vec = cur.fetchall() conta_errors += len(vec) #print str(len(vec)) for x in range(0, len(vec)): sql_1 = 'select "source","target" from "GTC_Update"."UpdateGTC" where "id"=' + str( vec[x][0]) + ';' cur.execute(sql_1) vec2 = cur.fetchall() update = 'UPDATE "GTC_Update"."UpdateGTC" SET the_geom = ST_RemovePoint(the_geom, ST_NPoints(the_geom) - 1) WHERE "id"=' + str( vec[x][0]) + ';' cur.execute(update) conn.commit() update = 'UPDATE "GTC_Update"."UpdateGTC" SET the_geom = ST_AddPoint(the_geom, (select "the_geom" from "GTC_Update"."UpdateGTC_vertices_pgr" where id=' + str( vec2[0][1]) + '),ST_NPoints(the_geom)) WHERE "id"=' + str( vec[x][0]) + ';' cur.execute(update) conn.commit() except Exception as e: print(e.message, e.args) print("ERROR SQL_XARXA") if conta_errors != 0: llista = "Errors trobats i reparats:" llista += (' ' + str(conta_errors) + '\n') else: llista = "No s'han detectat errors\n" textBox += llista self.dlg.text_info.setText(textBox) self.MouText() #UPDATE CAMPS DE CONTROL update = 'UPDATE "GTC_Update"."ControlActualitzacio" set modificant = false, modificat=true, "horaModificacio" = NULL, "usuariModificador" = NULL;' try: cur.execute(update) conn.commit() html = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"><html><head><meta name="qrichtext" content="1" /><style type="text/css">p, li { white-space: pre-wrap; }</style></head><body style=" font-family:\'MS Shell Dlg 2\'; font-size:10pt; font-weight:400; font-style:normal;"><div style=\"align:center\"><span style=\"background:#00FF00;font-size:14pt\">GRAF VALIDAT!<\span><\div></body></html>' self.dlg.text_info.insertHtml(html) self.MouText() except Exception as e: print(e.message, e.args) print( "ERROR update Control (modificant,modificat, paraula clau, timestamp" ) self.barraEstat_connectat()
def on_click_Carregar(self): global cur global conn global nomBD1 global contra1 global host1 global port1 global usuari1 llistaErrors = self.controlErrorsCarrega() if len(llistaErrors) != 0: llista = "Llista d'errors:\n\n" for i in range(0, len(llistaErrors)): llista += ("- " + llistaErrors[i] + '\n') QMessageBox.information(None, "Error", llista) return select = 'select * from "GTC_Update"."ControlActualitzacio";' try: cur.execute(select) vec = cur.fetchall() conn.commit() except Exception as e: print(e.message, e.args) print("ERROR select Control") if (vec[0][0]): label = "Actualment s'està modificant el GTC.\nIntrodueix la paraula clau per carregar la capa." val = self.on_click_CarregarAux(label) if val == '': return comprovarParaulaClau = vec[0][3] if (comprovarParaulaClau != val): QMessageBox.information(None, "Error", "La paraula clau no és la correcta.") return else: label = "Actualment NO s'està modificant el GTC.\nIntrodueix la paraula clau per carregar la capa." val = self.on_click_CarregarAux(label) if val == '': return update = 'update "GTC_Update"."ControlActualitzacio" set "modificant" = true;\n' update += 'update "GTC_Update"."ControlActualitzacio" set "usuariModificador" = \'' + val + '\';\n' update += 'update "GTC_Update"."ControlActualitzacio" set "horaModificacio" = CURRENT_TIMESTAMP;' try: cur.execute(update) conn.commit() except Exception as e: print(e.message, e.args) print("ERROR update Control (modificant, paraula clau)") if (not vec[0][1]): create = 'drop table if exists "GTC_Update"."UpdateGTC";\n' create += 'create table "GTC_Update"."UpdateGTC" as (select * from "SegmentsXarxaCarrers" order by id);\n' create += 'ALTER TABLE "GTC_Update"."UpdateGTC" DROP COLUMN id;\n' create += 'ALTER TABLE "GTC_Update"."UpdateGTC" ADD COLUMN id serial;\n' create += 'ALTER TABLE "GTC_Update"."UpdateGTC" ADD PRIMARY KEY (id);\n' try: cur.execute(create) conn.commit() except Exception as e: print("ERROR create GTC per actualitzar") print(e.message.encode('utf8', 'strict'), e.args.encode('utf8', 'strict')) select = 'select to_char("horaModificacio", \'DD/MM/YY HH24:MI\') from "GTC_Update"."ControlActualitzacio";' try: cur.execute(select) vec = cur.fetchall() conn.commit() except Exception as e: print(e.message, e.args) print("ERROR select Control") self.dlg.text_info.setText("Data de l'inici de la modificació: " + vec[0][0]) uri = QgsDataSourceUri() try: uri.setConnection(host1, port1, nomBD1, usuari1, contra1) except Exception as e: print(e.message, e.args) print("Error a la connexió") sql_total = 'select * from "GTC_Update"."UpdateGTC" order by id' QApplication.processEvents() uri.setDataSource("GTC_Update", "UpdateGTC", "the_geom", "", "") QApplication.processEvents() ''' # 13.2 Es prepara el titol de la capa que apareixerà a la llegenda ''' titol = "UpdateGTC" vlayer = QgsVectorLayer(uri.uri(False), titol, "postgres") QApplication.processEvents() if vlayer.isValid(): symbols = vlayer.renderer().symbols(QgsRenderContext()) symbol = symbols[0] '''S'afegeix el color a la nova entitat''' symbol.setColor(QColor.fromRgb(0, 0, 0)) QgsProject.instance().addMapLayer(vlayer, False) root = QgsProject.instance().layerTreeRoot() myLayerNode = QgsLayerTreeLayer(vlayer) root.insertChildNode(0, myLayerNode) myLayerNode.setCustomProperty("showFeatureCount", False) QApplication.processEvents() ''''S'afegeix la capa a la pantalla''' iface.mapCanvas().refresh() #qgis.utils.iface.legendInterface().refreshLayerSymbology(vlayer) else: print("No s'ha carregat la capa")
def epa2gis(inpname): plugin_path = os.path.dirname(__file__) file_extension = os.path.dirname(inpname) inpname = os.path.basename(inpname) inp = file_extension + '/' + inpname if len(file_extension) == 0: inp = inpname newpath = file_extension + '/_shapefiles_' if not os.path.exists(newpath): os.makedirs(newpath) iface = qgis.utils.iface d.LoadFile(inp) d.BinUpdateClass() nlinkCount = d.getBinLinkCount() res = newpath + '\\' saveFile = res + inpname[:len(inpname) - 4] # Get all Sections mixing = d.getMixingSection() reactions = d.getReactionsSection() sources = d.getSourcesSection() rules = d.getRulesSection() quality = d.getQualitySection() curves = d.getCurvesSection() patterns = d.getPatternsSection() controls = d.getControlsSection() emitters = d.getEmittersSection() status = d.getStatusSection() demands = d.getDemandsSection() energy = d.getEnergySection() optReactions = d.getReactionsOptionsSection() times = d.getTimesSection() report = d.getReportSection() options = d.getOptionsSection() # Get all Section lengths allSections = [len(energy), len(optReactions), len(demands), len(status), len(emitters), len(controls), len(patterns), len(curves[0]), len(quality), len(rules), len(sources), len(reactions), len(mixing), len(times), len(report), len(options), d.getBinNodeCount(), d.getBinLinkCount()] ss = max(allSections) root = QgsProject.instance().layerTreeRoot() idx = root.insertGroup(0, inpname[:len(inpname) - 4]) xy = d.getBinNodeCoordinates() x = xy[0] y = xy[1] vertx = xy[2] verty = xy[3] vertxyFinal = [] for i in range(len(vertx)): vertxy = [] for u in range(len(vertx[i])): vertxy.append([float(vertx[i][u]), float(verty[i][u])]) if vertxy: vertxyFinal.append(vertxy) otherDemads = d.getBinNodeBaseDemandsDemSection() ndID = d.getBinNodeNameID() ndBaseD = d.getBinNodeBaseDemands() ndPatID = d.getBinNodeDemandPatternID() otherDemadsIndex = [] otherDemadsPatterns = [] for i, p in enumerate(otherDemads[1]): otherDemadsIndex.append(ndID.index(p)) otherDemadsPatterns.append(otherDemads[2][i]) counter = collections.Counter(otherDemadsIndex) maxCategories = 1 if counter: maxCategories = max(counter.values()) if not ndBaseD: ndBaseD = otherDemads[0] # Get data of Junctions if d.getBinNodeJunctionCount() > 0: ndBaseTmp = np.empty((len(ndBaseD), maxCategories,)) ndPatTmp = [] for t in range(0, maxCategories): for u in range(0, len(ndBaseD)): ndBaseTmp[u][t] = 0 ndPatTmp.append(['None'] * 2) for uu in range(0, len(ndBaseD)): if d.getBinNodeBaseDemands(): ndBaseTmp[uu][0] = ndBaseD[uu] ndPatTmp[uu][0] = ndPatID[uu] t = 0 for i, p in enumerate(otherDemadsIndex): if d.getBinNodeBaseDemands(): ndBaseTmp[p][t] = ndBaseD[otherDemadsIndex[i]] ndPatTmp[p][t] = ndPatID[otherDemadsIndex[i]] else: ndBaseTmp[p][t] = otherDemads[0][i] ndPatTmp[p][t] = otherDemads[2][i] t = t + 1 if t > max(counter.values()) - 1: t = max(counter.values()) - 1 if i > 0: if otherDemadsIndex[i - 1] == p: ndBaseTmp[p][t] = otherDemads[0][i] ndPatTmp[p][t] = otherDemads[2][i] t = t - 1 # Write Junction Shapefile fields = ["ID", "Elevation"] # , "pattern", "demand"] fieldsCode = [0, 1] for u in range(0, maxCategories): fields.append('Demand' + str(u + 1)) fields.append('Pattern' + str(u + 1)) fieldsCode.append(1) fieldsCode.append(0) posJunction = QgsVectorLayer("point?crs=EPSG:4326", "Junctions", "memory") prJunction = posJunction.dataProvider() ndBaseTmp = ndBaseTmp.tolist() createColumnsAttrb(prJunction, fields, fieldsCode) posJunction.startEditing() ndEle = d.getBinNodeJunctionElevations() # Get data of Pipes # Write shapefile pipe if nlinkCount > 0: posPipe = QgsVectorLayer("LineString?crs=EPSG:4326", "Pipes", "memory") prPipe = posPipe.dataProvider() fields = ["ID", "NodeFrom", "NodeTo", "Status", "Length", "Diameter", "Roughness", "MinorLoss"] fieldsCode = [0, 0, 0, 0, 1, 1, 1, 1] createColumnsAttrb(prPipe, fields, fieldsCode) posPipe.startEditing() pIndex = d.getBinLinkPumpIndex() vIndex = d.getBinLinkValveIndex() ndlConn = d.getBinNodesConnectingLinksID() x1 = [] x2 = [] y1 = [] y2 = [] stat = d.getBinLinkInitialStatus() kk = 0 ch = 0 linkID = d.getBinLinkNameID() linkLengths = d.getBinLinkLength() linkDiameters = d.getBinLinkDiameter() linkRough = d.getBinLinkRoughnessCoeff() linkMinorloss = d.getBinLinkMinorLossCoeff() # Write Tank Shapefile and get tank data posTank = QgsVectorLayer("point?crs=EPSG:4326", "Tanks", "memory") prTank = posTank.dataProvider() fields = ["ID", "Elevation", "InitLevel", "MinLevel", "MaxLevel", "Diameter", "MinVolume", "VolumeCurve"] fieldsCode = [0, 1, 1, 1, 1, 1, 1, 0] createColumnsAttrb(prTank, fields, fieldsCode) posTank.startEditing() if d.getBinNodeTankCount() > 0: ndTankelevation = d.getBinNodeTankElevations() initiallev = d.getBinNodeTankInitialLevel() minimumlev = d.getBinNodeTankMinimumWaterLevel() maximumlev = d.getBinNodeTankMaximumWaterLevel() diameter = d.getBinNodeTankDiameter() minimumvol = d.getBinNodeTankMinimumWaterVolume() volumecurv = d.getBinNodeTankVolumeCurveID() ndTankID = d.getBinNodeTankNameID() # Write Reservoir Shapefile posReservoirs = QgsVectorLayer("point?crs=EPSG:4326", "Reservoirs", "memory") prReservoirs = posReservoirs.dataProvider() fields = ["ID", "Head"] fieldsCode = [0, 1] createColumnsAttrb(prReservoirs, fields, fieldsCode) head = d.getBinNodeReservoirElevations() posReservoirs.startEditing() if times: posTimes = QgsVectorLayer("point?crs=EPSG:4326", "Times", "memory") prTimes = posTimes.dataProvider() if energy: posE = QgsVectorLayer("point?crs=EPSG:4326", "Energy", "memory") prE = posE.dataProvider() if report: posRep = QgsVectorLayer("point?crs=EPSG:4326", "Report", "memory") prRep = posRep.dataProvider() if options: posOpt = QgsVectorLayer("point?crs=EPSG:4326", "Options", "memory") prOpt = posOpt.dataProvider() if optReactions: posO = QgsVectorLayer("point?crs=EPSG:4326", "Reactions", "memory") prO = posO.dataProvider() ppE = [] ppO = [] ppTimes = [] ppRep = [] ppOpt = [] ppMix = [] ppReactions = [] ppSourc = [] ppRul = [] ppPat = [] ppQual = [] ppDem = [] ppStat = [] ppEmit = [] ppCont = [] ppCurv = [] for i in range(ss): if i < d.getBinNodeJunctionCount(): featJ = QgsFeature() point = QgsPointXY(float(x[i]), float(y[i])) featJ.initAttributes(2 + len(ndBaseTmp[0]) * 2) featJ.setGeometry(QgsGeometry.fromPointXY(point)) featJ.setAttribute(0, ndID[i]) featJ.setAttribute(1, ndEle[i]) w = 2 for j in range(0, len(ndBaseTmp[0])): featJ.setAttribute(w, ndBaseTmp[i][j]) featJ.setAttribute(w + 1, ndPatTmp[i][j]) w = w + 2 prJunction.addFeatures([featJ]) if i < nlinkCount: if len(stat) == i: ch = 1 if ch == 1: stat.append('OPEN') x1.append(x[ndID.index(d.getBinLinkFromNode()[i])]) y1.append(y[ndID.index(d.getBinLinkFromNode()[i])]) x2.append(x[ndID.index(d.getBinLinkToNode()[i])]) y2.append(y[ndID.index(d.getBinLinkToNode()[i])]) if i in pIndex: pass elif i in vIndex: pass else: point1 = QgsPointXY(float(x1[i]), float(y1[i])) point2 = QgsPointXY(float(x2[i]), float(y2[i])) featPipe = QgsFeature() if vertx[i]: parts = [] parts.append(point1) for mm in range(len(vertxyFinal[kk])): a = vertxyFinal[kk][mm] parts.append(QgsPointXY(a[0], a[1])) parts.append(point2) featPipe.setGeometry((QgsGeometry.fromPolylineXY(parts))) kk = kk + 1 else: featPipe.setGeometry(QgsGeometry.fromPolylineXY([point1, point2])) featPipe.setAttributes( [linkID[i], ndlConn[0][i], ndlConn[1][i], stat[i], linkLengths[i], linkDiameters[i], linkRough[i], linkMinorloss[i]]) prPipe.addFeatures([featPipe]) if i < d.getBinNodeTankCount(): p = d.getBinNodeTankIndex()[i] - 1 featTank = QgsFeature() point = QgsPointXY(float(x[p]), float(y[p])) featTank.setGeometry(QgsGeometry.fromPointXY(point)) featTank.setAttributes( [ndTankID[i], ndTankelevation[i], initiallev[i], minimumlev[i], maximumlev[i], diameter[i], minimumvol[i], volumecurv[i]]) prTank.addFeatures([featTank]) if i < d.getBinNodeReservoirCount(): p = d.getBinNodeReservoirIndex()[i] - 1 feature = QgsFeature() point = QgsPointXY(float(x[p]), float(y[p])) feature.setGeometry(QgsGeometry.fromPointXY(point)) feature.setAttributes([ndID[p], head[i]]) prReservoirs.addFeatures([feature]) if i < allSections[12]: if len(mixing[i]) == 3: ppMix.append([mixing[i][0], mixing[i][1], mixing[i][2]]) else: ppMix.append([mixing[i][0], mixing[i][1]]) if i < allSections[11]: ppReactions.append([reactions[i][0], reactions[i][1], reactions[i][2]]) if i < allSections[10]: if len(sources[i]) == 4: ppSourc.append([sources[i][0], sources[i][1], sources[i][2], sources[i][3]]) elif len(sources[i]) == 3: ppSourc.append([sources[i][0], sources[i][1], sources[i][2]]) else: ppSourc.append([sources[i][0], sources[i][1]]) if i < allSections[9]: if len(rules[i]) > 2: ppRul.append([rules[i][0][1][1], rules[i][1][0] + rules[i][2][0] + rules[i][3][0]]) if i < allSections[8]: ppQual.append([quality[i][0], quality[i][1]]) if i < allSections[7]: ppCurv.append([str(curves[0][i][0]), str(curves[0][i][1]), str(curves[0][i][2]), str(curves[1][i])]) if i < allSections[6]: ppPat.append([patterns[i][0], str(patterns[i][1])]) if i < allSections[5]: ppCont.append([controls[i]]) if i < allSections[4]: ppEmit.append([emitters[i][0], emitters[i][1]]) if i < allSections[3]: ppStat.append([status[i][0], status[i][1]]) if i < allSections[2]: if len(demands[i]) > 2: ppDem.append([demands[i][0], demands[i][1], demands[i][2]]) if i < allSections[0]: mm = energy[i][0] if mm.upper() == "GLOBAL": prE.addAttributes([QgsField("Global" + energy[i][1], QVariant.String)]) if len(energy[i]) > 2: ppE.append(energy[i][2]) else: ppE.append('') if mm.upper() == "PUMP": prE.addAttributes([QgsField("Pump", QVariant.String)]) if len(energy[i]) > 2: ppE.append(energy[i][1] + ' ' + energy[i][2]) else: ppE.append(energy[i][1]) elif mm.upper() == "DEMAND": if energy[i][1].upper() == "CHARGE": prE.addAttributes([QgsField("DemCharge", QVariant.String)]) if len(energy[i]) > 2: ppE.append(energy[i][2]) if i < allSections[1]: mm = optReactions[i][0] if mm.upper() == "ORDER": prO.addAttributes([QgsField("Order" + optReactions[i][1], QVariant.String)]) if len(optReactions[i]) > 2: ppO.append(optReactions[i][2]) else: ppO.append('') elif mm.upper() == "GLOBAL": prO.addAttributes([QgsField("Global" + optReactions[i][1], QVariant.String)]) if len(optReactions[i]) > 2: ppO.append(optReactions[i][2]) else: ppO.append('') elif mm.upper() == "BULK": prO.addAttributes([QgsField("Bulk", QVariant.String)]) if len(optReactions[i]) > 2: ppO.append(optReactions[i][1] + ' ' + optReactions[i][2]) else: ppO.append(optReactions[i][1]) elif mm.upper() == "WALL": prO.addAttributes([QgsField("Wall", QVariant.String)]) if len(optReactions[i]) > 2: ppO.append(optReactions[i][1] + ' ' + optReactions[i][2]) else: ppO.append(optReactions[i][1]) elif mm.upper() == "TANK": prO.addAttributes([QgsField("Tank", QVariant.String)]) if len(optReactions[i]) > 2: ppO.append(optReactions[i][1] + ' ' + optReactions[i][2]) else: ppO.append(optReactions[i][1]) elif mm.upper() == "LIMITING": if optReactions[i][1].upper() == "POTENTIAL": prO.addAttributes([QgsField("LimPotent", QVariant.String)]) if len(optReactions[i]) > 2: ppO.append(optReactions[i][2]) elif mm.upper() == "ROUGHNESS": if optReactions[i][1].upper() == "CORRELATION": prO.addAttributes([QgsField("RoughCorr", QVariant.String)]) if len(optReactions[i]) > 2: ppO.append(optReactions[i][2]) if i < allSections[13]: mm = times[i][0] if mm.upper() == "DURATION": prTimes.addAttributes([QgsField("Duration", QVariant.String)]) ppTimes.append(times[i][1]) if mm.upper() == "HYDRAULIC": prTimes.addAttributes([QgsField("HydStep", QVariant.String)]) ppTimes.append(times[i][2]) elif mm.upper() == "QUALITY": prTimes.addAttributes([QgsField("QualStep", QVariant.String)]) ppTimes.append(times[i][2]) elif mm.upper() == "RULE": prTimes.addAttributes([QgsField("RuleStep", QVariant.String)]) ppTimes.append(times[i][2]) elif mm.upper() == "PATTERN": if times[i][1].upper() == "TIMESTEP": prTimes.addAttributes([QgsField("PatStep", QVariant.String)]) ppTimes.append(times[i][2]) if times[i][1].upper() == "START": prTimes.addAttributes([QgsField("PatStart", QVariant.String)]) ppTimes.append(times[i][2]) elif mm.upper() == "REPORT": if times[i][1].upper() == "TIMESTEP": prTimes.addAttributes([QgsField("RepStep", QVariant.String)]) ppTimes.append(times[i][2]) if times[i][1].upper() == "START": prTimes.addAttributes([QgsField("RepStart", QVariant.String)]) ppTimes.append(times[i][2]) elif mm.upper() == "START": if times[i][1].upper() == "CLOCKTIME": prTimes.addAttributes([QgsField("StartClock", QVariant.String)]) if len(times[i]) > 3: ppTimes.append(times[i][2] + ' ' + times[i][3]) else: ppTimes.append(times[i][2]) elif mm.upper() == "STATISTIC": prTimes.addAttributes([QgsField("Statistic", QVariant.String)]) if times[i][1].upper() == 'NONE' or times[i][1].upper() == 'AVERAGE' or times[i][1].upper() \ == 'MINIMUM' or times[i][1].upper() == 'MAXIMUM' or times[i][1].upper() == 'RANGE': ppTimes.append(times[i][1]) if i < allSections[14]: mm = report[i][0] if mm.upper() == "PAGESIZE": prRep.addAttributes([QgsField("PageSize", QVariant.String)]) ppRep.append(report[i][1]) if mm.upper() == "FILE": prRep.addAttributes([QgsField("FileName", QVariant.String)]) ppRep.append(report[i][1]) elif mm.upper() == "STATUS": prRep.addAttributes([QgsField("Status", QVariant.String)]) ppRep.append(report[i][1]) elif mm.upper() == "SUMMARY": prRep.addAttributes([QgsField("Summary", QVariant.String)]) ppRep.append(report[i][1]) elif mm.upper() == "ENERGY": prRep.addAttributes([QgsField("Energy", QVariant.String)]) ppRep.append(report[i][1]) elif mm.upper() == "NODES": prRep.addAttributes([QgsField("Nodes", QVariant.String)]) if len(report[i]) > 2: ppRep.append(report[i][1] + ' ' + report[i][2]) else: ppRep.append(report[i][1]) elif mm.upper() == "LINKS": prRep.addAttributes([QgsField("Links", QVariant.String)]) if len(report[i]) > 2: ppRep.append(report[i][1] + ' ' + report[i][2]) else: ppRep.append(report[i][1]) else: prRep.addAttributes([QgsField(mm, QVariant.String)]) if len(report[i]) > 2: ppRep.append(report[i][1] + ' ' + report[i][2]) else: ppRep.append(report[i][1]) if i < allSections[15]: mm = options[i][0] if mm.upper() == "UNITS": prOpt.addAttributes([QgsField("Units", QVariant.String)]) ppOpt.append(options[i][1]) if mm.upper() == "HYDRAULICS": prOpt.addAttributes([QgsField("Hydraulics", QVariant.String)]) if len(options[i]) > 2: ppOpt.append(options[i][1] + ' ' + options[i][2]) else: ppOpt.append(options[i][1]) elif mm.upper() == "QUALITY": prOpt.addAttributes([QgsField("Quality", QVariant.String)]) if len(options[i]) > 2: ppOpt.append(options[i][1] + ' ' + options[i][2]) elif len(options[i]) > 3: ppOpt.append(options[i][1] + ' ' + options[i][2] + ' ' + options[i][3]) else: ppOpt.append(options[i][1]) elif mm.upper() == "VISCOSITY": prOpt.addAttributes([QgsField("Viscosity", QVariant.String)]) ppOpt.append(options[i][1]) elif mm.upper() == "DIFFUSIVITY": prOpt.addAttributes([QgsField("Diffusivity", QVariant.String)]) ppOpt.append(options[i][1]) elif mm.upper() == "SPECIFIC": if options[i][1].upper() == "GRAVITY": prOpt.addAttributes([QgsField("SpecGrav", QVariant.String)]) ppOpt.append(options[i][2]) elif mm.upper() == "TRIALS": prOpt.addAttributes([QgsField("Trials", QVariant.String)]) ppOpt.append(options[i][1]) elif mm.upper() == "HEADLOSS": prOpt.addAttributes([QgsField("Headloss", QVariant.String)]) ppOpt.append(options[i][1]) elif mm.upper() == "ACCURACY": prOpt.addAttributes([QgsField("Accuracy", QVariant.String)]) ppOpt.append(options[i][1]) elif mm.upper() == "UNBALANCED": prOpt.addAttributes([QgsField("Unbalanced", QVariant.String)]) if len(options[i]) > 2: ppOpt.append(options[i][1] + ' ' + options[i][2]) else: ppOpt.append(options[i][1]) elif mm.upper() == "PATTERN": prOpt.addAttributes([QgsField("PatID", QVariant.String)]) ppOpt.append(options[i][1]) elif mm.upper() == "TOLERANCE": prOpt.addAttributes([QgsField("Tolerance", QVariant.String)]) ppOpt.append(options[i][1]) elif mm.upper() == "MAP": prOpt.addAttributes([QgsField("Map", QVariant.String)]) ppOpt.append(options[i][1]) elif mm.upper() == "DEMAND": if options[i][1].upper() == "MULTIPLIER": prOpt.addAttributes([QgsField("DemMult", QVariant.String)]) ppOpt.append(options[i][2]) elif mm.upper() == "EMITTER": if options[i][1].upper() == "EXPONENT": prOpt.addAttributes([QgsField("EmitExp", QVariant.String)]) ppOpt.append(options[i][2]) elif mm.upper() == "CHECKFREQ": prOpt.addAttributes([QgsField("CheckFreq", QVariant.String)]) ppOpt.append(options[i][1]) elif mm.upper() == "MAXCHECK": prOpt.addAttributes([QgsField("MaxCheck", QVariant.String)]) ppOpt.append(options[i][1]) elif mm.upper() == "DAMPLIMIT": prOpt.addAttributes([QgsField("DampLimit", QVariant.String)]) ppOpt.append(options[i][1]) writeDBF(posOpt, [ppOpt], prOpt, saveFile, inpname, "_OPTIONS", idx) writeDBF(posRep, [ppRep], prRep, saveFile, inpname, "_REPORT", idx) #if times: writeDBF(posTimes, [ppTimes], prTimes, saveFile, inpname, "_TIMES", idx) #if energy: writeDBF(posE, [ppE], prE, saveFile, inpname, "_ENERGY", idx) #if optReactions: writeDBF(posO, [ppO], prO, saveFile, inpname, "_REACTIONS", idx) posMix = QgsVectorLayer("point?crs=EPSG:4326", "Mixing", "memory") prMix = posMix.dataProvider() fields = ["Tank_ID", "Model", "Fraction"] fieldsCode = [0, 0, 1] # 0 String, 1 Double createColumnsAttrb(prMix, fields, fieldsCode) writeDBF(posMix, ppMix, prMix, saveFile, inpname, "_MIXING", idx) posReact = QgsVectorLayer("point?crs=EPSG:4326", "ReactionsI", "memory") prReact = posReact.dataProvider() fields = ["Type", "Pipe/Tank", "Coeff."] fieldsCode = [0, 0, 1] createColumnsAttrb(prReact, fields, fieldsCode) writeDBF(posReact, ppReactions, prReact, saveFile, inpname, "_REACTIONS_I", idx) posSourc = QgsVectorLayer("point?crs=EPSG:4326", "Sources", "memory") prSourc = posSourc.dataProvider() fields = ["Node_ID", "Type", "Strength", "Pattern"] fieldsCode = [0, 0, 1, 0] createColumnsAttrb(prSourc, fields, fieldsCode) writeDBF(posSourc, ppSourc, prSourc, saveFile, inpname, "_SOURCES", idx) posRul = QgsVectorLayer("point?crs=EPSG:4326", "Rules", "memory") prRul = posRul.dataProvider() fields = ["Rule_ID", "Rule"] fieldsCode = [0, 0] createColumnsAttrb(prRul, fields, fieldsCode) writeDBF(posRul, ppRul, prRul, saveFile, inpname, "_RULES", idx) posQual = QgsVectorLayer("point?crs=EPSG:4326", "Sources", "memory") prQual = posQual.dataProvider() fields = ["Node_ID", "Init_Qual"] fieldsCode = [0, 1] createColumnsAttrb(prQual, fields, fieldsCode) writeDBF(posQual, ppQual, prQual, saveFile, inpname, "_QUALITY", idx) posStat = QgsVectorLayer("point?crs=EPSG:4326", "Status", "memory") prStat = posStat.dataProvider() fields = ["Link_ID", "Status/Setting"] fieldsCode = [0, 0] createColumnsAttrb(prStat, fields, fieldsCode) writeDBF(posStat, ppStat, prStat, saveFile, inpname, "_STATUS", idx) posEmit = QgsVectorLayer("point?crs=EPSG:4326", "Emitters", "memory") prEmit = posEmit.dataProvider() fields = ["Junc_ID", "Coeff."] fieldsCode = [0, 1] createColumnsAttrb(prEmit, fields, fieldsCode) writeDBF(posEmit, ppEmit, prEmit, saveFile, inpname, "_EMITTERS", idx) posCont = QgsVectorLayer("point?crs=EPSG:4326", "Controls", "memory") prCont = posCont.dataProvider() fields = ["Controls"] fieldsCode = [0] createColumnsAttrb(prCont, fields, fieldsCode) writeDBF(posCont, ppCont, prCont, saveFile, inpname, "_CONTROLS", idx) posPat = QgsVectorLayer("point?crs=EPSG:4326", "Patterns", "memory") prPat = posPat.dataProvider() fields = ["Pattern_ID", "Multipliers"] fieldsCode = [0, 0] createColumnsAttrb(prPat, fields, fieldsCode) writeDBF(posPat, ppPat, prPat, saveFile, inpname, "_PATTERNS", idx) posCurv = QgsVectorLayer("point?crs=EPSG:4326", "Curves", "memory") prCurv = posCurv.dataProvider() fields = ["Curve_ID", "X-Value", "Y-Value", "Type"] fieldsCode = [0, 0, 0, 0] createColumnsAttrb(prCurv, fields, fieldsCode) writeDBF(posCurv, ppCurv, prCurv, saveFile, inpname, "_CURVES", idx) # Write Valve Shapefile posValve = QgsVectorLayer("LineString?crs=EPSG:4326", "Valve", "memory") prValve = posValve.dataProvider() fields = ["ID", "NodeFrom", "NodeTo", "Diameter", "Type", "Setting", "MinorLoss"] fieldsCode = [0, 0, 0, 1, 0, 1, 1] createColumnsAttrb(prValve, fields, fieldsCode) posValve.startEditing() if d.getBinLinkValveCount() > 0: linkID = d.getBinLinkValveNameID() linkType = d.getBinLinkValveType() # valve type linkDiameter = d.getBinLinkValveDiameters() linkInitSett = d.getBinLinkValveSetting() # BinLinkValveSetting linkMinorloss = d.getBinLinkValveMinorLoss() for i, p in enumerate(d.getBinLinkValveIndex()): point1 = QgsPointXY(float(x[ndID.index(d.getBinLinkFromNode()[p])]), float(y[ndID.index(d.getBinLinkFromNode()[p])])) point2 = QgsPointXY(float(x[ndID.index(d.getBinLinkToNode()[p])]), float(y[ndID.index(d.getBinLinkToNode()[p])])) feature = QgsFeature() feature.setGeometry(QgsGeometry.fromPolylineXY([point1, point2])) feature.setAttributes( [linkID[i], ndlConn[0][p], ndlConn[1][p], linkDiameter[i], linkType[i], linkInitSett[i], linkMinorloss[i]]) prValve.addFeatures([feature]) QgsVectorFileWriter.writeAsVectorFormat(posValve, saveFile + "_valves" + '.shp', "utf-8", QgsCoordinateReferenceSystem(posValve.crs().authid()), "ESRI Shapefile") ll = QgsVectorLayer(saveFile + "_valves" + '.shp', inpname[:len(inpname) - 4] + "_valves", "ogr") QgsProject.instance().addMapLayer(ll, False) nvalves = QgsLayerTreeLayer(ll) idx.insertChildNode(0, nvalves) nvalves.setCustomProperty("showFeatureCount", True) ll.loadNamedStyle(plugin_path + "/qmls/" + 'valvesline' + ".qml") ll.triggerRepaint() # Write Pump Shapefile posPump = QgsVectorLayer("LineString?crs=EPSG:4326", "Pump", "memory") prPump = posPump.dataProvider() fields = ["ID", "NodeFrom", "NodeTo", "Power", "Pattern", "Curve"] fieldsCode = [0, 0, 0, 0, 0, 0] createColumnsAttrb(prPump, fields, fieldsCode) posPump.startEditing() if d.getBinLinkPumpCount() > 0: curveXY = d.getBinCurvesXY() curvesID = d.getBinCurvesNameID() a = curvesID b = [] for l in a: if l not in b: b.append(l) curvesIDunique = b CurvesTmpIndices = [] for p in range(0, len(curvesIDunique)): CurvesTmpIndices.append(curvesID.count(curvesIDunique[p])) curveIndices = [] Curve = d.getBinLinkPumpCurveNameID() for i in range(len(Curve)): curveIndices.append(curvesIDunique.index(Curve[i])) if d.getBinCurveCount(): CurvesTmpIndicesFinal = [] CurvesTmpIndicesFinal.append([CurvesTmpIndices[index] for index in curveIndices]) CurvesTmp = [] i = 0 for u in range(max(CurvesTmpIndicesFinal[0])): fields.append('Head' + str(u + 1)) fields.append('Flow' + str(u + 1)) fieldsCode.append(1) fieldsCode.append(1) if u < d.getBinCurveCount(): tmp1 = [] for p in range(CurvesTmpIndices[u]): tmp1.append([curveXY[i][0], curveXY[i][1]]) i = i + 1 CurvesTmp.append(tmp1) createColumnsAttrb(prPump, fields, fieldsCode) chPowerPump = d.getBinLinkPumpPower() pumpID = d.getBinLinkPumpNameID() patternsIDs = d.getBinLinkPumpPatterns() ppatt = d.getBinLinkPumpPatternsPumpID() linkID = d.getBinLinkNameID() for i, p in enumerate(d.getBinLinkPumpIndex()): Curve = [] power = [] pattern = [] pumpNameIDPower = d.getBinLinkPumpNameIDPower() if len(pumpNameIDPower) > 0: for uu in range(0, len(pumpNameIDPower)): if pumpNameIDPower[uu] == pumpID[i]: power = chPowerPump[uu] if len(patternsIDs) > 0: for uu in range(0, len(ppatt)): if ppatt[uu] == pumpID[i]: pattern = patternsIDs[uu] point1 = QgsPointXY(float(x[ndID.index(d.getBinLinkFromNode()[p])]), float(y[ndID.index(d.getBinLinkFromNode()[p])])) point2 = QgsPointXY(float(x[ndID.index(d.getBinLinkToNode()[p])]), float(y[ndID.index(d.getBinLinkToNode()[p])])) feature = QgsFeature() feature.setGeometry(QgsGeometry.fromPolylineXY([point1, point2])) if not Curve: Curve = 'NULL' if not power: power = 'NULL' if not pattern: pattern = 'NULL' if d.getBinCurveCount() > 0 and len(pumpNameIDPower) == 0: Curve = d.getBinLinkPumpCurveNameID()[i] curveIndex = curvesIDunique.index(Curve) feature.initAttributes(6 + sum(CurvesTmpIndices) * 2 + 1) feature.setAttribute(0, linkID[p]) feature.setAttribute(1, ndlConn[0][p]) feature.setAttribute(2, ndlConn[1][p]) feature.setAttribute(3, power) feature.setAttribute(4, pattern) feature.setAttribute(5, Curve) if d.getBinCurveCount() == 1: w = 6 for p in range(CurvesTmpIndices[curveIndex]): feature.setAttribute(w, CurvesTmp[curveIndex][p][0]) feature.setAttribute(w + 1, CurvesTmp[curveIndex][p][1]) w = w + 2 for j in range(d.getBinCurveCount() - 1): w = 6 for p in range(CurvesTmpIndices[curveIndex]): feature.setAttribute(w, CurvesTmp[curveIndex][p][0]) feature.setAttribute(w + 1, CurvesTmp[curveIndex][p][1]) w = w + 2 prPump.addFeatures([feature]) QgsVectorFileWriter.writeAsVectorFormat(posPump,saveFile+"_pumps"+'.shp', "utf-8", QgsCoordinateReferenceSystem(posPump.crs().authid()), "ESRI Shapefile") ll = QgsVectorLayer(saveFile + "_pumps" + '.shp', inpname[:len(inpname) - 4] + "_pumps", "ogr") QgsProject.instance().addMapLayer(ll, False) npump = QgsLayerTreeLayer(ll) idx.insertChildNode(0, npump) npump.setCustomProperty("showFeatureCount", True) ll.loadNamedStyle(plugin_path + "/qmls/" + 'pumpsline' + ".qml") ll.triggerRepaint() QgsVectorFileWriter.writeAsVectorFormat(posPipe,saveFile+"_pipes"+'.shp', "utf-8", QgsCoordinateReferenceSystem(posPipe.crs().authid()), "ESRI Shapefile") ll = QgsVectorLayer(saveFile + "_pipes" + '.shp', inpname[:len(inpname) - 4] + "_pipes", "ogr") QgsProject.instance().addMapLayer(ll, False) npipe = QgsLayerTreeLayer(ll) idx.insertChildNode(0, npipe) npipe.setCustomProperty("showFeatureCount", True) ll.loadNamedStyle(plugin_path + "/qmls/" + 'pipes' + ".qml") ll.triggerRepaint() iface.mapCanvas().setExtent(ll.extent()) QgsVectorFileWriter.writeAsVectorFormat(posJunction,saveFile+"_junctions"+'.shp', "utf-8", QgsCoordinateReferenceSystem(posJunction.crs().authid()), "ESRI Shapefile") ll = QgsVectorLayer(saveFile + "_junctions" + '.shp', inpname[:len(inpname) - 4] + "_junctions", "ogr") QgsProject.instance().addMapLayer(ll, False) njunc = QgsLayerTreeLayer(ll) idx.insertChildNode(0, njunc) njunc.setCustomProperty("showFeatureCount", True) ll.loadNamedStyle(plugin_path + "/qmls/" + 'junctions' + ".qml") ll.triggerRepaint() QgsVectorFileWriter.writeAsVectorFormat(posTank, saveFile + "_tanks" + '.shp', "utf-8", QgsCoordinateReferenceSystem(posTank.crs().authid()), "ESRI Shapefile") ll = QgsVectorLayer(saveFile + "_tanks" + '.shp', inpname[:len(inpname) - 4] + "_tanks", "ogr") QgsProject.instance().addMapLayer(ll, False) ntanks = QgsLayerTreeLayer(ll) idx.insertChildNode(0, ntanks) ntanks.setCustomProperty("showFeatureCount", True) ll.loadNamedStyle(plugin_path + "/qmls/" + 'tanks' + ".qml") ll.triggerRepaint() QgsVectorFileWriter.writeAsVectorFormat(posReservoirs, saveFile + "_reservoirs" + '.shp', "utf-8", QgsCoordinateReferenceSystem(posReservoirs.crs().authid()), "ESRI Shapefile") ll = QgsVectorLayer(saveFile + "_reservoirs" + '.shp', inpname[:len(inpname) - 4] + "_reservoirs", "ogr") QgsProject.instance().addMapLayer(ll, False) nres = QgsLayerTreeLayer(ll) idx.insertChildNode(0, nres) nres.setCustomProperty("showFeatureCount", True) ll.loadNamedStyle(plugin_path + "/qmls/" + 'reservoirs' + ".qml") ll.triggerRepaint()
def on_click_Inici(self): global lbl_Cost global data global listFields global urlToLoad global TEMPORARY_PATH self.dlg.setEnabled(False) '''Tratamiento de errores''' llistaErrors = self.controlErrorsInput() if len(llistaErrors) > 0: llista = "Llista d'errors:\n\n" for i in range (0,len(llistaErrors)): llista += ("- "+llistaErrors[i] + '\n') QMessageBox.information(None, "Error", llista) self.dlg.setEnabled(True) return textBox = u'INICI DEL PROCÉS\n\n' self.dlg.text_info.setText(textBox) self.MouText() campNom = '' campGeometria = '' campCod = '' campSrc = '' campLat = '' campLng = '' '''Obtención de Nom y Geometria''' if self.dlg.radio_ws.isChecked(): campNom,campGeometria,campLat, campLng, campCod,campSrc=self.searchNomGeomCodSrcInFile() urlToLoad=self.dlg.combo_ws.currentText() #if(urlToLoad[-4:]=='.csv'): error = self.loadCSV(campNom, campGeometria, campCod,True) if (error=="Error"): self.dlg.setEnabled(True) return else: campNom = self.dlg.combo_nom.currentText() campCod=self.dlg.combo_cod.currentText() campSrc=self.dlg.combo_src.currentText() if self.dlg.radio_geom.isChecked(): campGeometria = self.dlg.combo_geom.currentText() elif self.dlg.radio_latlng.isChecked(): campLat=self.dlg.combo_lat.currentText() campLng=self.dlg.combo_lng.currentText() '''Creación vector layer''' self.dlg.progressBar.setValue(60) textBox += u'Generant capa vectorial...\n' self.dlg.text_info.setText(textBox) self.MouText() if campGeometria != '': file = 'file:///'+TEMPORARY_PATH+'/WS.csv?encoding=%s&delimiter=%s&wktField=%s&crs=%s' % (campCod,",", campGeometria,campSrc) elif campLat != '' and campLng != '': file = 'file:///'+TEMPORARY_PATH+'/WS.csv?encoding=%s&delimiter=%s&xField=%s&yField=%s&crs=%s' % (campCod,",", campLng, campLat,campSrc) else: file = 'file:///'+TEMPORARY_PATH+'/WS.csv?encoding=%s&delimiter=%s' % (campCod,",") vlayergeom = QgsVectorLayer(file, self.dlg.txt_nomTaula.text(),'delimitedtext') try: vlayergeom = self.comprobarValidez(vlayergeom) #Sirve tanto para comprobar la corrección del CSV como para pasar el layer a memoria except Exception as ex: missatge="La geometria seleccionada no és correcte" print (missatge) template = "An exception of type {0} occurred. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) print (message) QMessageBox.information(None, "Error", missatge) self.dlg.text_info.setText('') self.dlg.progressBar.setValue(0) self.dlg.setEnabled(True) return "Error" vlayergeom.setName(self.dlg.txt_nomTaula.text()) self.dlg.progressBar.setValue(80) textBox += u'Adaptant camps...\n' self.dlg.text_info.setText(textBox) self.MouText() '''Se renombra el campo de nombre y se añade un id''' vlayergeom.startEditing() fields = vlayergeom.fields() for x in range(len(fields)): if(campNom in fields[x].displayName()): vlayergeom.renameAttribute(x,'Nom') break; vlayergeom.addAttribute(QgsField('id', QVariant.Int)) vlayergeom.commitChanges() '''Se autonumera el id''' features = vlayergeom.getFeatures() vlayergeom.startEditing() x=1 for feature in features: vlayergeom.changeAttributeValue(feature.id(),self.getIndexOfField(vlayergeom,"id"),x) x=x+1 vlayergeom.commitChanges() '''Se borran los campos no seleccionados''' if not self.dlg.radio_ws.isChecked(): llista_sel=[] if (len(self.dlg.ListaCamps.selectedItems())>0): for item in self.dlg.ListaCamps.selectedItems(): llista_sel.append(item.text()) vlayergeom.startEditing() for elem in listFields: if elem not in llista_sel: vlayergeom.deleteAttribute(self.getIndexOfField(vlayergeom,elem)) vlayergeom.commitChanges() '''Se representa en pantalla''' QgsProject.instance().addMapLayer(vlayergeom,False) root = QgsProject.instance().layerTreeRoot() myLayerNode=QgsLayerTreeLayer(vlayergeom) root.insertChildNode(0,myLayerNode) myLayerNode.setCustomProperty("showFeatureCount", True) if self.dlg.checkBox_save.isChecked(): this_folder = os.path.dirname(os.path.abspath(__file__)) '''UPDATE''' file = open(this_folder+'/default_ws.txt') cont=0 strToWrite = '' for line in file: if (line.split('=',1)[1].replace('\n','')==self.dlg.txt_url.text()): cont+=1 strToWrite+= line elif (cont==1): cont+=1 strToWrite+= 'nom='+campNom+'\n' elif (cont==2): cont+=1 if self.dlg.radio_geom.isChecked(): strToWrite+= 'geom='+campGeometria+'\n' else: strToWrite+='geom=\n' elif (cont==3): cont+=1 if self.dlg.radio_latlng.isChecked(): strToWrite+= 'lat='+campLat+'\n' else: strToWrite+='lat=\n' elif (cont==4): cont+=1 if self.dlg.radio_latlng.isChecked(): strToWrite+= 'lng='+campLng+'\n' else: strToWrite+='lng=\n' elif (cont==5): cont+=1 strToWrite+= 'cod='+campCod+'\n' elif (cont==6): cont+=1 strToWrite+= 'src='+campSrc+'\n' else: strToWrite+=line file.close() file = open(this_folder+'/default_ws.txt', "w") file.write(strToWrite) file.close() '''APEND''' if cont == 0: strToAppend = '\nurl='+self.dlg.txt_url.text() strToAppend += '\nnom='+campNom if self.dlg.radio_geom.isChecked(): strToAppend += '\ngeo='+campGeometria else: strToAppend += '\ngeo=' if self.dlg.radio_latlng.isChecked(): strToAppend += '\nlat='+campLat strToAppend += '\nlng='+campLng else: strToAppend += '\nlat=' strToAppend += '\nlng=' strToAppend += '\ncod='+campCod strToAppend += '\nsrc='+campSrc file = open(this_folder+'/default_ws.txt', "a") file.write(strToAppend) file.close() self.file2Combo("default_ws.txt", self.dlg.combo_ws, 'Selecciona una opció') self.dlg.progressBar.setValue(100) textBox += u'\nProcés finalitzat.\n' self.dlg.text_info.setText(textBox) self.MouText() self.dlg.setEnabled(True)