def execute(self, parameters, messages): """The source code of the tool.""" arcpy.AddMessage("default.gdb_path: %s" % arcpy.env.workspace) probe_path = parameters[0].valueAsText arcpy.AddMessage("probe_path: %s" % probe_path) if not arcpy.Exists(probe_path): arcpy.AddError("Ciao") raise arcpy.ExecuteError check_layer_list = [ r"Connessioni database\VISIO_R_GDBT.sde\SIT.ZONOM\SIT.FCL_ZONEOM", ] area_totale = 0 with arcpy.da.SearchCursor(probe_path, ["SHAPE","SHAPE@area"]) as cursor: for row in cursor: area_totale += row[1] arcpy.AddMessage("area totale: %d" % area_totale) zone = {} for check_layer in check_layer_list: arcpy.AddMessage("check_layer: %s" % check_layer) desc = arcpy.Describe(check_layer) arcpy.AddMessage("check_layer type: %s" % desc.shapeType) if desc.shapeType == 'Polygon': intersect_layer = check_layer else: #intersect_layer = os.path.join(current_workspace,"buffer_%s" % uuid.uuid4().hex) intersect_layer = get_jobfile("memory") arcpy.Buffer_analysis(check_layer, intersect_layer, "0.1") inFeatures = [probe_path, check_layer] #intersectOutput = os.path.join(current_workspace,"IntersectOutputResult_%s" % uuid.uuid4().hex) intersectOutput = get_jobfile("memory") clusterTolerance = 0 arcpy.Intersect_analysis(inFeatures, intersectOutput, "", clusterTolerance, "input") with arcpy.da.SearchCursor(intersectOutput, ["TIPO_OMO", "SHAPE@area" ]) as cursor: arcpy.AddMessage("cursor: %s" % cursor) for row in cursor: zona = row[0] if zona in zone: zone[zona] += row[1] else: zone[zona] = row[1] del cursor arcpy.AddMessage(json.dumps(zone,indent=3)) parameters[1].value = json.dumps(zone)
def execute(self, parameters, messages): """The source code of the tool.""" probe_path = parameters[0].valueAsText tolleranza = float(parameters[1].valueAsText) check_layer_list = [ r"Connessioni database\VISIO_R_GDBT.sde\FERREGUTIE.CS_unitaDiPiano", ] area_totale = calc_area_totale(probe_path) output = [] for check_layer in check_layer_list: arcpy.AddMessage("check_layer: %s" % check_layer) inFeatures = [probe_path, check_layer] #intersectOutput = os.path.join(memory_workspace,"IntersectOutputResult_%s" % uuid.uuid4().hex) intersectOutput = get_jobfile("memory") clusterTolerance = 0 arcpy.Intersect_analysis(inFeatures, intersectOutput, "", clusterTolerance, "input") with arcpy.da.SearchCursor( intersectOutput, ["FULL_ID", "DESPRO", "NORMA1", "DESPRO1", "SHAPE@area" ]) as cursor: for row in cursor: if row[4] > area_totale * tolleranza / 100: arcpy.AddMessage(str(row)) row_desc = { "full_id": row[0], "despro": row[1], "norma1": row[2], "despro1": row[3], "area": row[4] } output.append(row_desc) del cursor arcpy.AddMessage(json.dumps(output, indent=3)) parameters[2].value = json.dumps(output)
def execute(self, parameters, messages): """The source code of the tool.""" arcpy.ImportToolbox(os.path.join(os.path.dirname(__file__), "URB.pyt")) arcpy.gp.toolbox = os.path.join(os.path.dirname(__file__), "URB.pyt") def extentToPoly(extent, srid=3003): clist = arcpy.Array() clist.append(arcpy.Point(extent.XMin, extent.YMin)) clist.append(arcpy.Point(extent.XMin, extent.YMax)) clist.append(arcpy.Point(extent.XMax, extent.YMax)) clist.append(arcpy.Point(extent.XMax, extent.YMin)) return arcpy.Polygon(clist) def get_best_fit_scale(fc, paper, scales=[ 1000, 2000, 2500, 5000, 7500, 10000, 20000 ]): desc = arcpy.Describe(fc) sheet = printOutput_templates[paper]["size"] margin = 10 #mapUnitsPerMillimeter = [0.5,1,2,5,10] cx = (desc.extent.XMin + desc.extent.XMax) / 2 cy = (desc.extent.YMin + desc.extent.YMax) / 2 fc_bound = extentToPoly(desc.extent) for scale in scales: scaleFactor = scale / 1000 wb = sheet[0] * scaleFactor / 2 hb = sheet[1] * scaleFactor / 2 wf = (sheet[0] - margin * 2) * scaleFactor / 2 hf = (sheet[1] - margin * 2) * scaleFactor / 2 #bound = arcpy.Polygon([arcpy.Point(cx-wb,cy-hb), arcpy.Point(cx+wb,cy-hb), arcpy.Point(cx+wb,cy+hb), arcpy.Point(cx-wb,cy+hb)]) #frame = arcpy.Polygon([arcpy.Point(cx-wf,cy-hf), arcpy.Point(cx+wf,cy-hf), arcpy.Point(cx+wf,cy+hf), arcpy.Point(cx-wf,cy+hf)]) bound = extentToPoly( arcpy.Extent(cx - wb, cy - hb, cx + wb, cy + hb)) frame_extent = arcpy.Extent(cx - wf, cy - hf, cx + wf, cy + hf) frame = extentToPoly(frame_extent) #tempfcname = "in_memory/output" + uuid.uuid4().hex #arcpy.Intersect_analysis ([frame, fc_bound], tempfcname) #result = arcpy.GetCount_management(tempfcname) #intersections = int(result.getOutput(0)) #if intersections > 0: if frame_extent.contains(desc.extent): return bound, frame, scale return bound, frame, scaleFactor def get_esri_ring(extent): ring = [ [extent.XMin, extent.YMin], [extent.XMax, extent.YMin], [extent.XMax, extent.YMax], [extent.XMin, extent.YMax], [extent.XMin, extent.YMin], ] return ring probe_path = parameters[0].valueAsText coordinate_catastali = parameters[1].valueAsText paper = parameters[2].valueAsText.replace("'", "") base = parameters[3].valueAsText.replace("'", "") checkboxes = [] #for idx in range(4,12): # if parameters[idx].valueAsText == "true": # checkboxes.append(idx) for param in parameters: #arcpy.AddMessage("param: %s %s" % (str(param.datatype),str(param.valueAsText))) if param.datatype in ("Booleano", "Boolean") and param.valueAsText == "true": checkboxes.append(param.name) arcpy.AddMessage("checkboxes: %s" % str(checkboxes)) with open( os.path.join(os.path.dirname(__file__), "web_map_as_json.json"), "r") as jf: wmaj_template = jf.read() template_engine = Template(wmaj_template) decode_map = [] if coordinate_catastali: CC_result = arcpy.gp.CC2FCtool(coordinate_catastali) probe_path = CC_result.getOutput(0) else: if not probe_path: arcpy.AddError( "Deve essere specificata almeno un contesto, come layer o come coordinate catastali" ) exit(0) arcpy.AddMessage("probe_path: %s paper:" % probe_path) probe = arcpy.mapping.Layer(probe_path) with arcpy.da.SearchCursor(probe_path, ['SHAPE']) as cursor: probe_polygon = next(cursor)[0] #probe_json_path = os.path.join(tempfile.mkdtemp(), "probe.json") probe_json_path = get_jobfile("activity", "json") arcpy.FeaturesToJSON_conversion(probe_path, probe_json_path, "FORMATTED") with open(probe_json_path, "r") as jf: probe_json = jf.read() #arcpy.AddMessage(json.dumps(json.loads(probe_json),indent=3)) json_feats = [] probe_json_dict = json.loads(probe_json) for feat in probe_json_dict["features"]: feat["symbol"] = { "color": [255, 0, 0, 0], "outline": { "color": [255, 0, 0, 255], "width": 1.75, "type": "esriSLS", "style": "esriSLSSolid" }, "type": "esriSFS", "style": "esriSFSSolid" } json_feats.append(feat) result_pdf = [] for tema in temi: if not tema["label"] in checkboxes: continue mapServices = basi[base] + tema["def"] bound, frame, scale = get_best_fit_scale(probe_path, paper) printpar = { "extent": [ frame.extent.XMin, frame.extent.YMin, frame.extent.XMax, frame.extent.YMax ], "scale": scale, "srid": 3003, "esri_poly": json.dumps( json.loads(probe_json)["features"][0]["geometry"] ["rings"]), "esri_style": json.dumps( proto_ESRI_style), #non implementato nel template json "esri_bound": get_esri_ring(bound.extent), "esri_frame": get_esri_ring(frame.extent), "title": tema["label"].upper().replace("_", ""), "dpi": 200, "auth": "Settore urbanistica, Servizi catastali e Mobilita'", "copyright": "Comune di Padova" } web_map_as_json = template_engine.render(printpar=printpar) web_map_as_dict = json.loads(web_map_as_json) web_map_as_dict["operationalLayers"][0]["featureCollection"][ "layers"][0]["featureSet"]["features"] = json_feats web_map_as_dict[ "operationalLayers"] = mapServices + web_map_as_dict[ "operationalLayers"] web_map_as_json = json.dumps(web_map_as_dict) post_parameters = { "f": "json", "Web_Map_as_JSON": web_map_as_json, "Format": "PDF", "Layout_Template": printOutput_templates[paper]["label"] } #arcpy.AddMessage(json.dumps(post_parameters,indent=3)) #pdf_file_path = os.path.join(tempfile.mkdtemp(), tema["label"]+".pdf") pdf_file_path = get_jobfile("output", "pdf") res = urllib.urlopen( base_url + "arcgis/rest/services/Utilities/PrintingTools/GPServer/Export%20Web%20Map%20Task/execute", urllib.urlencode(post_parameters)).read() if "results" in res: remoteFile = json.loads(res)['results'][0]["value"]["url"] #arcpy.AddMessage ("REMOTE: " + remoteFile) urllib.urlretrieve(remoteFile, pdf_file_path) arcpy.AddMessage("OK: %s" % tema["label"]) result_pdf.append(pdf_file_path) else: arcpy.AddMessage("NO") if parameters[-1].valueAsText: pdf_globale = parameters[-1].valueAsText else: #pdf_globale = os.path.join(tempfile.mkdtemp(), "inquadramento.pdf") pdf_globale = get_jobfile("output", "pdf") merger = PdfFileMerger() for file in result_pdf: merger.append(PdfFileReader(file)) merger.write(pdf_globale) parameters[-1].value = pdf_globale arcpy.AddMessage("OK: %s" % pdf_globale)
def execute(self, parameters, messages): """The source code of the tool.""" arcpy.ImportToolbox(os.path.join(os.path.dirname(__file__), "URB.pyt")) arcpy.gp.toolbox = os.path.join(os.path.dirname(__file__), "URB.pyt") # Local variables: contesto = parameters[0].valueAsText coordinate_catastali = parameters[1].valueAsText protocollo_numero = parameters[2].valueAsText protocollo_data = parameters[3].valueAsText richiedente = parameters[4].valueAsText odt_target = parameters[5].valueAsText #json = "" poligono = "" output_json = "" #facoltativo #output_testo_PI = "" #output_json__2_ = "" #output_testo_PAT = "" test = False PI_test = ''' [ {"note": null, "articolo": 0, "layer": 0, "definizione": "Area totale", "nome": "Area totale", "url": "", "gruppo": "cdu", "area": 3978.322295527004, "interno_pe": 0}, {"layer": 39, "definizione": "Area interessata da vincolo aeroportuale disciplinato dalla L. 4 febbraio 1963 n.58", "nome": "Perimetro ricognitivo aeroportuale", "url": "http://www.padovanet.it/allegati/C_1_Allegati_15388_Allegato_0.pdf", "gruppo": "perimetri", "area": 2974.954930029389, "note": null, "articolo": "", "interno_pe": null}, {"layer": 39, "definizione": "Area interessata da vincolo aeroportuale disciplinato dalla L. 4 febbraio 1963 n.58", "nome": "Perimetro ricognitivo aeroportuale", "url": "http://www.padovanet.it/allegati/C_1_Allegati_15388_Allegato_0.pdf", "gruppo": "perimetri", "area": 2974.954930029389, "note": null, "articolo": "", "interno_pe": null}, {"layer": 56, "definizione": "Zona di degrado %", "nome": "Perimetro zone di degrado", "url": "http://www.padovanet.it/allegati/C_1_Allegati_15388_Allegato_0.pdf#92", "gruppo": "centro_storico", "area": 1003.3676370044367, "note": null, "articolo": 41, "interno_pe": 0}, {"layer": 39, "definizione": "Area interessata da vincolo aeroportuale disciplinato dalla L. 4 febbraio 1963 n.58", "nome": "Perimetro ricognitivo aeroportuale", "url": "http://www.padovanet.it/allegati/C_1_Allegati_15388_Allegato_0.pdf", "gruppo": "perimetri", "area": 1003.3676370044367, "note": null, "articolo": "", "interno_pe": null}, {"layer": 39, "definizione": "Area interessata da vincolo aeroportuale disciplinato dalla L. 4 febbraio 1963 n.58", "nome": "Perimetro ricognitivo aeroportuale", "url": "http://www.padovanet.it/allegati/C_1_Allegati_15388_Allegato_0.pdf", "gruppo": "perimetri", "area": 1003.3676370044367, "note": null, "articolo": "", "interno_pe": null}, {"note": null, "articolo": "999.999", "layer": 999, "definizione": "Viabilità", "nome": "Area non zonizzata", "url": "", "gruppo": "cdu", "area": 3978.322295527004, "interno_pe": 0}] ''' CS_test = u''' [{"norma1": "UNITA' DI PIANO DELLA CLASSE E MODALITA' DI TIPO E - RISTRUTTURAZIONE EDILIZIA", "area": 3953.5930837093556, "despro1": "RESIDENZIALE, COMMERCIALE, DIREZIONALE, TURISTICA E ARTIGIANALE", "full_id": "0026500014", "despro": " "}] ''' PAT_test = u''' [ {"nta": 5.1, "layer": "b0101011_vincolo", "fc": "SIT.b0101011_Vincolo_r", "desc": "Vincolo sui beni culturali (D.Lgs. 42/2004, artt.10 e 12)"}, {"nta": "5.6.12", "layer": "b0105021_fascerispetto", "fc": "SIT.b0105021_FasceRispetto_r", "desc": "Servitù o Fasce di rispetto aeroportuale"}, {"nta": "5.5.1", "layer": "b0104011_centrostorico", "fc": "SIT.b0104011_CentroStorico_r", "desc": "Centro Storico (P.R.G., P.T.C.P. art.26 A N.T., P.T.R.C. art.24 N.T.)"}, {"nta": "5.6.8.1", "layer": "b0105051_centriabitati", "fc": "SIT.b0105051_CentriAbitati_r", "desc": "Centri Abitati"} ] ''' arcpy.ImportToolbox(os.path.join(os.path.dirname(__file__), "URB.pyt")) arcpy.gp.toolbox = os.path.join(os.path.dirname(__file__), "URB.pyt") if test: identificazione = "TEST" PI_def = json.loads(PI_test) CS_def = json.loads(CS_test) PAT_def = json.loads(PAT_test) arcpy.AddMessage(str(PAT_def)) for item in PAT_def: arcpy.AddMessage(item['desc']) else: poligono = contesto identificazione = "" if coordinate_catastali: CC_result = arcpy.gp.CC2FCtool(coordinate_catastali) arcpy.AddMessage("CC_result: %s" % CC_result.getOutput(0)) poligono = CC_result.getOutput(0) identificazione = u"così individuata nel Catasto Terreni: %s" % decodificaCatasto( coordinate_catastali) else: if not contesto: arcpy.AddError( "Deve essere specificato almeno un contesto, come layer o come coordinate catastali" ) exit(0) poligono = contesto # Process: CDU_PI PI_result = arcpy.gp.CDUPItool(poligono, output_json) arcpy.AddMessage("PI_result: %s" % PI_result.getOutput(0)) PI_def = json.loads(PI_result.getOutput(0)) checkInCS = False for defin in PI_def: if defin["layer"] == 55: checkInCS = True if checkInCS: # Process: CDU_CS CS_result = arcpy.gp.CDUCStool(poligono, output_json) arcpy.AddMessage("CS_result: %s" % CS_result.getOutput(0)) CS_def = json.loads(CS_result.getOutput(0)) else: CS_def = [] # Process: CDU_PAT PAT_result = arcpy.gp.CDUPATtool(poligono, output_json) arcpy.AddMessage("PAT_result: %s" % PAT_result.getOutput(0)) PAT_def = json.loads(PAT_result.getOutput(0)) PI_desc = '' PI_nta = '' dest_selection = [] for item in PI_def: arcpy.AddMessage("item: %s" % str(item)) if item["layer"] != 0 and not item["layer"] in dest_selection: dest_selection.append(item["layer"]) if '%' in item["definizione"]: definizione = item["definizione"].replace( '%', unicode(item["note"] or "")) else: definizione = item["definizione"] PI_desc += '%s, ' % definizione.upper() PI_nta += '%s, ' % str(item["articolo"]).upper() PI_desc = PI_desc[:-2] + "; " PI_nta = PI_nta[:-2] + "; " CS_udp = '' dest_selection = [] for item in CS_def: if not item["norma1"] + item["despro1"] in dest_selection: dest_selection.append(item["norma1"] + item["despro1"]) CS_udp += '%s con destinazione %s, ' % (item['norma1'], item["despro1"]) CS_udp = CS_udp[:-2] + "; " PAT_desc = '' PAT_nta = '' dest_selection = [] for item in PAT_def: arcpy.AddMessage("dest_selection: %s" % str(dest_selection)) if not item["desc"] in dest_selection: dest_selection.append(item["desc"]) PAT_desc += '%s, ' % item["desc"].upper() PAT_nta += '%s, ' % str(item["nta"]).upper() PAT_desc = PAT_desc[:-2] + "; " PAT_nta = PAT_nta[:-2] + "; " params = { "protocollo": { "numero": str(protocollo_numero), "data": str(protocollo_data) }, "richiedente": richiedente, "pi": { "desc": PI_desc, "nta": PI_nta }, "cs": CS_udp, "pat": { "desc": PAT_desc, "nta": PAT_nta }, } arcpy.AddMessage("PARAMS: %s" % str(params)) engine = Renderer() template2 = os.path.join(os.path.dirname(__file__), "SOMMARIO_template.odt") result2 = engine.render(template2, PI_def=PI_def, CS_def=CS_def, PAT_def=PAT_def) #sommario_target = os.path.join(tempfile.mkdtemp(),"sommario.odt") sommario_target = get_jobfile("output", "odt") with open(sommario_target, 'wb') as output: output.write(result2) output.flush() arcpy.AddMessage("SOMMARIO DESTINAZIONI: %s" % sommario_target) if not odt_target: #odt_target = os.path.join(tempfile.mkdtemp(),"CDU.odt") odt_target = get_jobfile("output", "odt") template1 = os.path.join(os.path.dirname(__file__), "CDU_template.odt") result1 = engine.render(template1, **params) with open(odt_target, 'wb') as output: output.write(result1) output.flush() arcpy.AddMessage("SOMMARIO DESTINAZIONI: %s" % odt_target) parameters[5].value = odt_target
def execute(self, parameters, messages): """The source code of the tool.""" arcpy.AddMessage("default.gdb_path: %s" % arcpy.env.workspace) arcpy.ImportToolbox(os.path.join(os.path.dirname(__file__), "URB.pyt")) arcpy.gp.toolbox = os.path.join(os.path.dirname(__file__), "URB.pyt") probe_path = parameters[0].valueAsText check_layer_list = [ r"Connessioni database\VISIO_R_GDBT.sde\SIT.PI\SIT.PI_zoning", r"Connessioni database\VISIO_R_GDBT.sde\SIT.PI\SIT.PI_perimetri", r"Connessioni database\VISIO_R_GDBT.sde\SIT.PI\SIT.PI_linee", r"Connessioni database\VISIO_R_GDBT.sde\SIT.PI\SIT.PI_limiti", ] area_totale = calc_area_totale(probe_path) area_zonizzata = 0 arcpy.AddMessage("area totale: %d" % area_totale) # Set the workspace (to avoid having to type in the full path to the data every time) #arcpy.env.workspace = r"Connessioni database\VISIO_R_GDBT.sde\SIT.PI" # Process: Find all stream crossings (points) output = [ { "layer": 0, "definizione": "Area totale", "nome": "Area totale", "url": "", "gruppo": "cdu", "area": area_totale, "note": None, "articolo": 0, "interno_pe": 0, "z_omogenea": None }, ] zone_scan = {} layers_scan = [] zone_check = Set() for check_layer in check_layer_list: arcpy.AddMessage("check_layer: %s" % check_layer) desc = arcpy.Describe(check_layer) arcpy.AddMessage("check_layer type: %s" % desc.shapeType) if desc.shapeType == 'Polygon': intersect_layer = check_layer else: intersect_layer = os.path.join(scratch_workspace, "buffer_%s" % uuid.uuid4().hex) arcpy.Buffer_analysis(check_layer, intersect_layer, "0.1") inFeatures = [probe_path, check_layer] #intersectOutput = os.path.join(scratch_workspace,"IntersectOutputResult_%s" % uuid.uuid4().hex) intersectOutput = get_jobfile("memory") clusterTolerance = 0 arcpy.Intersect_analysis(inFeatures, intersectOutput, "", clusterTolerance, "input") check = arcpy.Describe(intersectOutput) field_names = [f.name for f in arcpy.ListFields(intersectOutput)] arcpy.AddMessage("field_check: %s" % str(field_names)) #zone check with arcpy.da.SearchCursor( intersectOutput, ["LAYER", "NOTE", "INTERNO_PER", "SHAPE@area", "OID" ]) as cursor: for row in cursor: if decodifica_pi[str(row[0])]["z_omogenea"]: zone_check.add(row[0]) arcpy.AddMessage("zone_check: %s" % str(zone_check)) if len(zone_check) > 1: parte = True else: parte = False with arcpy.da.SearchCursor( intersectOutput, ["LAYER", "NOTE", "INTERNO_PER", "SHAPE@area", "OID" ]) as cursor: arcpy.AddMessage("cursor: %s" % cursor) for row in cursor: if row[0] == 41 or row[ 0] in layers_scan: # Layer Territorio Comunale!!!! continue layers_scan.append(row[0]) arcpy.AddMessage(str(row)) layer_id = row[0] row_desc = dict(decodifica_pi[str(layer_id)]) if parte and row_desc["z_omogenea"]: parte_suff = "ad " if row_desc["definizione"][0].upper( ) == "A" else "a " parte_txt = "Parte " + parte_suff else: parte_txt = "" row_desc["layer"] = layer_id row_desc[ "definizione"] = parte_txt + row_desc["definizione"] row_desc["note"] = row[1] row_desc["interno_pe"] = row[2] row_desc["area"] = row[3] #arcpy.AddMessage("%s %s %s" % (check_layer,check_layer_list[0], str(check_layer == check_layer_list[0]))) #if check_layer == check_layer_list[0]: if row_desc["z_omogenea"]: area_zonizzata += row[3] if row_desc["z_omogenea"] in ["b", "c"]: check_layer_lyr = arcpy.mapping.Layer(check_layer) arcpy.SelectLayerByAttribute_management( check_layer_lyr, "NEW_SELECTION", ' "OBJECTID" = %d ' % row[4]) #OBJECTID #arcpy.AddMessage(dir(arcpy.gp.toolbox)) with arcpy.da.SearchCursor(check_layer_lyr, [ "SHAPE@", ]) as cursor_zo: for row_zo in cursor_zo: res = arcpy.gp.ZTOSCVOLTool([row_zo[0]]) del cursor_zo arcpy.AddMessage(res.getOutput(0)) zo = json.loads(res.getOutput(0)) if zo["copertura"] > 12.5 and zo["indice"] > 1.5: row_desc["z_omogenea"] = "b" else: row_desc["z_omogenea"] = "c" if row_desc["z_omogenea"]: if row_desc["z_omogenea"].upper() in zone_scan: zone_scan[row_desc["z_omogenea"].upper( )] += row_desc["area"] else: zone_scan[row_desc["z_omogenea"].upper( )] = row_desc["area"] output.append(row_desc) del cursor if int(area_totale) != int(area_zonizzata): output.append({ "layer": 999, "definizione": "Parte a Viabilità" if parte else "Viabilità", "nome": "Area non zonizzata", "url": "", "gruppo": "cdu", "area": area_totale - area_zonizzata, "note": None, "articolo": "999.999", "interno_pe": 0, "z_omogenea": "" }) arcpy.AddMessage(json.dumps(output, indent=3)) parameters[1].value = json.dumps(output) zone2006 = arcpy.gp.ZTO2006Tool(probe_path) zone = { "vigente": zone_scan, "2006": json.loads(zone2006.getOutput(0)) } arcpy.AddMessage(json.dumps(zone, indent=3)) parameters[2].value = json.dumps(zone)
def execute(self, parameters, messages): """The source code of the tool.""" arcpy.AddMessage("default.gdb_path: %s" % arcpy.env.workspace) arcpy.ImportToolbox(os.path.join(os.path.dirname(__file__), "URB.pyt")) arcpy.gp.toolbox = os.path.join(os.path.dirname(__file__), "URB.pyt") extent = parameters[0].value srs = parameters[1].value arcpy.AddMessage("control: %s %s" % (extent, srs)) ext_poly = ext2poly(extent, arcpy.SpatialReference(3003)) sel_fc = create_fc(ws="scratch") ext_fc_cursor = arcpy.da.InsertCursor(sel_fc, ("SHAPE@")) ext_fc_cursor.insertRow([ext_poly]) del ext_fc_cursor sel_lyr = arcpy.mapping.Layer(sel_fc) arcpy.AddMessage("sel_lyr: %s" % str(sel_lyr)) check_layer_list = [ [ r"Connessioni database\VISIO_R_GDBT.sde\SIT.DBTOPOGRAFICO\SIT.UN_VOL", "UN_VOL_AV", 0 ], [ r"Connessioni database\VISIO_R_GDBT.sde\SIT.DBTOPOGRAFICO\SIT.AATT", "", 1 ], [ r"Connessioni database\VISIO_R_GDBT.sde\SIT.DBTOPOGRAFICO\SIT.MN_EDI_NOVOL", "", 2 ], [ r"Connessioni database\VISIO_R_GDBT.sde\SIT.DBTOPOGRAFICO\SIT.MN_UVOL", "MN_UVO_ALT", 3 ], [ r"Connessioni database\VISIO_R_GDBT.sde\SIT.DBTOPOGRAFICO\SIT.AR_VRD", "", 4 ], #[r"Connessioni database\VISIO_R_GDBT.sde\SIT.DBTOPOGRAFICO\SIT.AR_MARC", "", 5], #[r"Connessioni database\VISIO_R_GDBT.sde\SIT.DBTOPOGRAFICO\SIT.AC_VEI", "", 6], [ r"Connessioni database\VISIO_R_GDBT.sde\SIT.DBTOPOGRAFICO\SIT.CL_AGR", "", 7 ], [ r"Connessioni database\VISIO_R_GDBT.sde\SIT.DBTOPOGRAFICO\SIT.A_PED", "", 8 ], [ r"Connessioni database\VISIO_R_GDBT.sde\SIT.DBTOPOGRAFICO\SIT.PS_INC", "", 9 ], ] sel_fc = get_jobfile("memory") sel_fc_fields = ( ("Layer", "TEXT", None, None, 10, "", "NULLABLE", "NON_REQUIRED"), ("Color", "SHORT", None, None, None, "", "NULLABLE", "NON_REQUIRED"), ("TxtValue", "TEXT", None, None, 10, "", "NULLABLE", "NON_REQUIRED"), ) intersectOutput_clean = create_fc("memory", fields=sel_fc_fields) sel_note = get_jobfile("memory") sel_note_fields = ( ("Layer", "TEXT", None, None, 50, "", "NULLABLE", "NON_REQUIRED"), ("Color", "SHORT", None, None, None, "", "NULLABLE", "NON_REQUIRED"), ("TxtValue", "TEXT", None, None, 255, "", "NULLABLE", "NON_REQUIRED"), ("CADType", "TEXT", None, None, 50, "", "NULLABLE", "NON_REQUIRED"), ) intersectOutput_note = create_fc("memory", fields=sel_note_fields, geom_type="POINT") cursor_note = arcpy.da.InsertCursor( intersectOutput_note, ("Layer", "Color", "TxtValue", "CADType", "SHAPE@")) for check_layer_def in check_layer_list: check_layer = check_layer_def[0] arcpy.AddMessage("check_layer: %s" % check_layer) desc = arcpy.Describe(check_layer) inFeatures = [check_layer, sel_lyr] intersectOutput = get_jobfile("memory") clusterTolerance = 0 arcpy.Intersect_analysis(inFeatures, intersectOutput, "", clusterTolerance, "input") if check_layer_def[1]: field_def = ("Layer", "Color", "TxtValue", "SHAPE@") check_def = [check_layer_def[1], "SHAPE@"] else: field_def = ("Layer", "Color", "SHAPE@") check_def = ["SHAPE@"] cursor_clean = arcpy.da.InsertCursor(intersectOutput_clean, field_def) with arcpy.da.SearchCursor(intersectOutput, check_def) as cursor: for row in cursor: if check_layer_def[1]: row_def = [ desc.name.replace("SIT.", ""), check_layer_def[2], str(row[0]), cursor[1] ] note_def = row_def[:-1] + [ "TEXT", arcpy.PointGeometry(cursor[1].centroid) ] cursor_note.insertRow(note_def) else: row_def = [ desc.name.replace("SIT.", ""), check_layer_def[2], cursor[0] ] cursor_clean.insertRow(row_def) del cursor_clean del cursor_note extraction_json_filepath = get_jobfile("output", "json") arcpy.FeaturesToJSON_conversion(intersectOutput_clean, extraction_json_filepath, format_json=True, geoJSON=True) arcpy.AddMessage(extraction_json_filepath) parameters[2].value = extraction_json_filepath extraction_dxf_filepath = get_jobfile("output", "dxf") arcpy.ExportCAD_conversion( [intersectOutput_clean, intersectOutput_note], "DXF_R2004", extraction_dxf_filepath, "USE_FILENAMES_IN_TABLES", "OVERWRITE_EXISTING_FILES", "") parameters[3].value = extraction_dxf_filepath lyr = arcpy.mapping.Layer(intersectOutput_clean) parameters[4].value = intersectOutput_clean
def execute(self, parameters, messages): """The source code of the tool.""" def coordinateCatastaliToWHERE(coordinateCatastali): sqlWhere = "" fogliMappali = coordinateCatastali.split(" ") for foglioMappali in fogliMappali: listaFoglio = foglioMappali.split("/") foglio = listaFoglio[0] if foglio[-1:].isalpha(): foglio = "000"[:3 - len(foglio[:-1] )] + foglio[:-1] + foglio[-1:].upper() else: foglio = "000"[:3 - len(foglio)] + foglio + "0" listaMappali = listaFoglio[1] mappali = listaMappali.split("-") for mappale in mappali: sqlWhere += "(FOGLIO = '%s' AND MAPPALE ='%s') OR " % ( foglio, mappale) return sqlWhere[:-4] # Script arguments try: cc_input = coordinateCatastaliToWHERE(parameters[0].valueAsText) except: arcpy.AddError("Coordinate catastali inserite in modo errato") exit(0) particelle_output = parameters[1].valueAsText arcpy.AddMessage("WHERE: %s" % str(cc_input)) #input_lyr_name = os.path.join(memory_workspace, "filter_" + uuid.uuid4().hex) #output_lyr_name = os.path.join(scratch_workspace, "catasto_" + uuid.uuid4().hex) input_lyr_name = get_jobfile("memory") output_lyr_name = get_jobfile("memory") particelle_cc_layer = r"Connessioni database\VISIO_R_GDBT.sde\SIT.CATASTO\SIT.particelle_cat" arcpy.MakeFeatureLayer_management(particelle_cc_layer, input_lyr_name) lyr = arcpy.mapping.Layer(input_lyr_name) lyr.definitionQuery = cc_input particelle = [ f[0] for f in arcpy.da.SearchCursor(input_lyr_name, "SHAPE@") ] arcpy.AddMessage("particelle: %s" % str(particelle)) if len(particelle) == 1: particella_union = particelle[0] elif len(particelle) > 1: particella_union = particelle[0] arcpy.AddMessage("res %s" % particella_union.WKT) for particella_idx in range(1, len(particelle)): particella = particelle[particella_idx] arcpy.AddMessage("particella %d" % particella_idx) particella_union = particella_union.union(particella) else: arcpy.AddError("Nessuna corrispondenza con il catasto aggiornato") exit(0) out = arcpy.CopyFeatures_management([particella_union], output_lyr_name) #out_lyr = arcpy.mapping.Layer(output_lyr_name) #out_lyr.name = "ricerca catastale %s" % arcpy.GetParameterAsText(0) #esrijson_filepath = os.path.join(tempfile.mkdtemp(),'catasto.json') esrijson_filepath = get_jobfile("output", "json") with open(esrijson_filepath, 'w') as f: f.write(particella_union.JSON) arcpy.AddMessage(esrijson_filepath) parameters[1].value = output_lyr_name parameters[2].value = esrijson_filepath
def execute(self, parameters, messages): """The source code of the tool.""" def clean_fc(name): return name.lower().replace("sit.", "").replace("_rw", "").replace("_r", "") def extract_related(selector, all_list): lyrs = [] for item in all_list: if item["layer"].lower() == selector: item["clean_layer"] = item["layer"].lower() lyrs.append(item) return lyrs arcpy.AddMessage("default.gdb_path: %s" % arcpy.env.workspace) probe_path = parameters[0].valueAsText cleaned_decodifica = [ clean_fc(item["layer"]) for item in decodifica_pat ] arcpy.AddMessage("cleaned_decodifica: %s" % str(cleaned_decodifica)) base_pat_repository = r"Connessioni database\VISIO_R_GDBT.sde\SIT.PAT_r" arcpy.env.workspace = base_pat_repository check_layer_list = arcpy.ListFeatureClasses("*") area_totale = calc_area_totale(probe_path) arcpy.AddMessage("area totale: %d" % area_totale) # Set the workspace (to avoid having to type in the full path to the data every time) #arcpy.env.workspace = r"Connessioni database\VISIO_R_GDBT.sde\SIT.PI" # Process: Find all stream crossings (points) output = [] for check_layer in check_layer_list: arcpy.AddMessage( "check_layer: %s, %s, %s" % (check_layer, clean_fc(check_layer), str(clean_fc(check_layer) in cleaned_decodifica))) desc = arcpy.Describe(check_layer) if clean_fc(check_layer) in cleaned_decodifica: related_list = extract_related(clean_fc(check_layer), decodifica_pat) for related in related_list: arcpy.AddMessage( "cleaned_check_layer: %s, campo: %s, valore: %s" % (clean_fc(check_layer), related["campo"], related["valore"])) arcpy.AddMessage("check_layer type: %s" % desc.shapeType) if desc.shapeType == 'Polygon': intersect_layer = check_layer else: #intersect_layer = os.path.join(memory_workspace,"buffer_%s" % uuid.uuid4().hex) intersect_layer = get_jobfile("memory") arcpy.Buffer_analysis(check_layer, intersect_layer, "0.1") target_lyr = arcpy.mapping.Layer(intersect_layer) if related["campo"]: target_lyr.definitionQuery = "%s = '%s'" % ( related["campo"], related["valore"]) inFeatures = [probe_path, target_lyr] #intersectOutput = os.path.join(memory_workspace,"IntersectOutputResult_%s" % uuid.uuid4().hex) intersectOutput = get_jobfile("memory") clusterTolerance = 0 arcpy.Intersect_analysis(inFeatures, intersectOutput, "", clusterTolerance, "input") result = arcpy.GetCount_management(intersectOutput) intersected_feats = int(result.getOutput(0)) arcpy.AddMessage("check_layer intesected feats: %d" % intersected_feats) if intersected_feats > 0: output.append({ "layer": clean_fc(check_layer), "fc": check_layer, "desc": related["descrizione"], "nta": related["nta"] }) arcpy.AddMessage(json.dumps(output, indent=3)) parameters[1].value = json.dumps(output)
def execute(self, parameters, messages): """The source code of the tool.""" arcpy.AddMessage("default.gdb_path: %s" % arcpy.env.workspace) probe_path = parameters[0].valueAsText arcpy.AddMessage("probe_path: %s" % probe_path) if not arcpy.Exists(probe_path): arcpy.AddError("Ciao") raise arcpy.ExecuteError check_layer_list = [ r"Connessioni database\VISIO_R_GDBT.sde\SIT.DBTOPOGRAFICO\SIT.UN_VOL", ] area_totale = 0 with arcpy.da.SearchCursor(probe_path, ["SHAPE","SHAPE@area"]) as cursor: for row in cursor: area_totale += row[1] arcpy.AddMessage("area totale: %d" % area_totale) # Set the workspace (to avoid having to type in the full path to the data every time) #arcpy.env.workspace = r"Connessioni database\VISIO_R_GDBT.sde\SIT.PI" # Process: Find all stream crossings (points) output = [ { "layer": 0, "definizione": "Area totale", "nome": "Area totale", "url": "", "gruppo": "cdu", "area": area_totale, "note": None, "articolo": 0, "interno_pe": 0 }, ] SC_totale = 0 VOL_totale = 0 probe_list = [] with arcpy.da.SearchCursor(probe_path, 'SHAPE@') as scur: for row in scur: probe_list.append(row[0]) arcpy.AddMessage("PROBELIST: %s" % str(probe_list)) selection = get_jobfile("memory") probe_list_lyr = arcpy.CopyFeatures_management(probe_list, selection) for check_layer in check_layer_list: arcpy.AddMessage("check_layer: %s" % check_layer) desc = arcpy.Describe(check_layer) arcpy.AddMessage("check_layer type: %s" % desc.shapeType) if desc.shapeType == 'Polygon': intersect_layer = check_layer else: #intersect_layer = os.path.join(current_workspace,"buffer_%s" % uuid.uuid4().hex) intersect_layer = get_jobfile("memory") arcpy.Buffer_analysis(check_layer, intersect_layer, "0.1") inFeatures = [probe_list_lyr, check_layer] #intersectOutput = os.path.join(current_workspace,"IntersectOutputResult_%s" % uuid.uuid4().hex) intersectOutput = get_jobfile("memory") clusterTolerance = 0 arcpy.Intersect_analysis(inFeatures, intersectOutput, "", clusterTolerance, "input") with arcpy.da.SearchCursor(intersectOutput, ["UN_VOL_AV", "SHAPE@area" ]) as cursor: arcpy.AddMessage("cursor: %s" % cursor) for row in cursor: VOL_totale += row[0] * row[1] SC_totale += row[1] del cursor arcpy.Delete_management(probe_list_lyr) output = { "area_totale": area_totale, "sc_totale": SC_totale, "vol_totale": VOL_totale, "copertura": SC_totale * 199 / area_totale, "indice": VOL_totale / area_totale } arcpy.AddMessage(json.dumps(output,indent=3)) parameters[1].value = json.dumps(output)