def create_texture_map(in_soil): arcpy.MakeRasterLayer_management(in_raster=in_soil, out_rasterlayer='soil_raster_layer', band_index="1") fields = [field.name for field in arcpy.ListFields('soil_raster_layer')] if 'texcl' not in [field.lower() for field in fields]: component = str(Path(in_soil).parents[0] / 'component') arcpy.JoinField_management(in_data='soil_raster_layer', in_field='MUKEY', join_table=component, join_field='mukey', fields='cokey') chorizon = str(Path(in_soil).parents[0] / 'chorizon') arcpy.MakeRasterLayer_management(in_raster=in_soil, out_rasterlayer='soil_raster_layer', band_index="1") soil_raster_layer = arcpy.JoinField_management(in_data='soil_raster_layer', in_field='cokey', join_table=chorizon, join_field='cokey', fields='chkey') chtexturegrp = str(Path(in_soil).parents[0] / 'chtexturegrp') arcpy.MakeRasterLayer_management(in_raster=in_soil, out_rasterlayer='soil_raster_layer', band_index="1") soil_raster_layer = arcpy.JoinField_management(in_data='soil_raster_layer', in_field='chkey', join_table=chtexturegrp, join_field='chkey', fields='chtgkey') chtexture = str(Path(in_soil).parents[0] / 'chtexture') arcpy.MakeRasterLayer_management(in_raster=in_soil, out_rasterlayer='soil_raster_layer', band_index="1") soil_raster_layer = arcpy.JoinField_management(in_data='soil_raster_layer', in_field='chtgkey', join_table=chtexture, join_field='chtgkey')
def mapPop(inMap, outMap, hdGrid, urbGrid, hdStyle, urbStyle, extents, extentsSymbology): mxd = arcpy.mapping.MapDocument(inMap) mxd.saveACopy(outMap) mxd = arcpy.mapping.MapDocument(outMap) df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0] #Add the urban grid to the map result = arcpy.MakeRasterLayer_management(urbGrid) urbLyr = result.getOutput(0) arcpy.ApplySymbologyFromLayer_management(urbLyr, urbStyle) arcpy.mapping.AddLayer(df, urbLyr) #Add the high density urban grid to the map resultHD = arcpy.MakeRasterLayer_management(hdGrid) hdLyr = resultHD.getOutput(0) arcpy.ApplySymbologyFromLayer_management(hdLyr, hdStyle) arcpy.mapping.AddLayer(df, hdLyr) #Add the extents to the map extentLyr = arcpy.mapping.Layer(extents) extentLyr.definitionQuery = 'NOT "ExtentName" = \'0\'' arcpy.ApplySymbologyFromLayer_management(extentLyr, extentsSymbology) arcpy.mapping.AddLayer(df, extentLyr) mxd.save()
def inverso_topografico(dem, outrst): """ Inverso do �ndice Topogr�fico """ import arcpy, os, shutil workspace = "C:\\temporario" os.mkdir(workspace) arcpy.env.workspace = workspace arcpy.gp.Slope_sa(mdt, "slope.tif", "DEGREE") arcpy.gp.Fill_sa(mdt, "fill.tif", "") arcpy.gp.FlowDirection_sa(workspace + "\\fill.tif", "direcao.tif", "NORMAL", "") arcpy.gp.FlowAccumulation_sa(workspace + "\\direcao.tif", "rst_acumulacao.tif", "", "FLOAT") declv = arcpy.MakeRasterLayer_management(workspace + "\\slope.tif", "declv", "", "", "1") acumu = arcpy.MakeRasterLayer_management( workspace + "\\rst_acumulacao.tif", "acum", "", "", "1") expressao = "(" + "\"declv\"" + " / " + "\"acum\")" tempEnvironment0 = arcpy.env.extent arcpy.env.extent = mdt arcpy.gp.RasterCalculator_sa(expressao, "calculadora.tif") arcpy.env.extent = tempEnvironment0 tempEnvironment0 = arcpy.env.extent arcpy.env.extent = mdt arcpy.gp.Reclassify_sa( workspace + "\\calculadora.tif", "Value", "0 1;0 0,001 2;0,001 0,01 3;0,01 0,10000000000000001 4;0,10000000000000001 70 5;NODATA 5", "reclss.tif", "DATA") arcpy.env.extent = tempEnvironment0 tempEnvironment0 = arcpy.env.extent arcpy.env.extent = mdt arcpy.gp.Reclassify_sa(workspace + "\\slope.tif", "Value", "0 70 0", "mascara.tif", "DATA") arcpy.env.extent = tempEnvironment0 mascara = arcpy.MakeRasterLayer_managemnet(workspace + + "\\mascara.tif", "mascara", "", "", "1") inverso_topo = arcpy.MakeRasterLayer_managemnet( workspace + + "\\reclss.tif", "inverso_temp", "", "", "1") tempEnvironment0 = arcpy.env.extent arcpy.env.extent = mdt arcpy.gp.RasterCalculator_sa("\"mascara\" + \"inverso_temp\"", saida + ".tif") arcpy.env.extent = tempEnvironment0 lyr = arcpy.MakeRasterLayer_management(workspace + "\\" + saida + ".tif", "final", "", "", "1") arcpy.AddField_management(layer, "classe", "TEXT", "50", "", "", "", "NULLABLE", "NON_REQUIRED", "") dic = {1: "0", 2: "0a0,001", 3: "0,001a0,01", 4: "0,01a0,1", 5: "maior0,1"} cs = arcpy.UpdateCursor(layer) for linha in cs: value = int(linha.getValue("Value")) for chave in dic.keys(): if value == chave: linha.setValue("classe", dc_exposicoes[chave]) cs.updateRow(linha) shutil.rmtree(workspace)
def zonal_hist(in_zone, in_value_raster, set_raster_symbology, region_c, use_name, temp_table, final_folder, snap): # In paths path_fc, in_species = os.path.split(in_zone) sp_group = in_species.split("_")[1] # out paths break_use = use_path.split("_") break_bool = False use_nm_folder = region_c # starting point that will be used for use_nm_folder for v in break_use: if v != region_c: pass else: break_bool = True if break_bool: if v == region_c: continue else: use_nm_folder = use_nm_folder + "_" + v use_nm_folder = use_nm_folder.split(".")[0] print use_nm_folder if not os.path.exists(final_folder + os.sep + use_nm_folder): os.mkdir(final_folder + os.sep + use_nm_folder) out_tables = final_folder + os.sep + use_nm_folder run_id = in_species + "_" + use_nm_folder out_path_final = out_tables csv = run_id + '.csv' if os.path.exists(out_path_final + os.sep + csv): print("Already completed run for {0}".format(run_id)) elif not os.path.exists(out_path_final + os.sep + csv): print( "Running Statistics...for species group {0} and raster {1}".format( sp_group, use_name)) arcpy.CheckOutExtension("Spatial") arcpy.MakeRasterLayer_management(Raster(in_zone), "zone") arcpy.MakeRasterLayer_management(Raster(in_value_raster), "rd_lyr") arcpy.ApplySymbologyFromLayer_management("rd_lyr", set_raster_symbology) temp_return, zone_time = zone("zone", "rd_lyr", temp_table, snap) list_fields = [f.name for f in arcpy.ListFields(temp_return)] att_array = arcpy.da.TableToNumPyArray((temp_return), list_fields) att_df = pd.DataFrame(data=att_array) att_df['LABEL'] = att_df['LABEL'].map(lambda x: x).astype(str) att_df.to_csv(out_path_final + os.sep + csv) print 'Final file can be found at {0}'.format(out_path_final + os.sep + csv) print "Completed in {0}\n".format( (datetime.datetime.now() - zone_time))
def remove_low_slope(): outSlope = arcpy.sa.Slope("DSM_50cm_clipped_shifted", "DEGREE") outSlope.save(main_data_path + "\\Slope_clipped_shifted") arcpy.MakeRasterLayer_management( main_data_path + "\\Slope_clipped_shifted", "Slope_clipped_shifted") outCon = arcpy.sa.Con("Slope_clipped_shifted", "Avg_SR_for_buildings", "", "VALUE <= 45") outCon.save("Avg_SR_for_buildings_low_slope") arcpy.MakeRasterLayer_management( main_data_path + "\\Avg_SR_for_buildings_low_slope", "Avg_SR_for_buildings_low_slope")
def ZonalHist(rasterLocation, raster, outpath_final, infc, FullFile): dem = rasterLocation + os.sep + str(raster) path, fc = os.path.split(infc) out = outpath_final arcpy.env.overwriteOutput = True start_loop = datetime.datetime.now() arcpy.MakeFeatureLayer_management(infc, "fc_lyr") if FullFile: runID = fc dbf = outpath_final + os.sep + str(runID) print dbf arcpy.MakeRasterLayer_management(dem, "rdlayer") symbologyLayer = "J:\Workspace\ESA_Species\Step3\ZonalHis_GAP\GAP.lyr" arcpy.ApplySymbologyFromLayer_management("rdlayer", symbologyLayer) codezone = functions.ZonalHist("fc_lyr", zoneField, "rdlayer", dbf, outpath_final) print "Full region completed in: {0}".format(datetime.datetime.now() - start_loop) else: for row in arcpy.da.SearchCursor("fc_lyr", [zoneField, "SHAPE@"]): entid = row[0] #whereclause = "EntityID = '%s'" % (id) whereclause = "\"OBJECTID\"=" + str( entid) #TODO Make this dyanmic to zon field lyr = "lyr" arcpy.MakeFeatureLayer_management("fc_lyr", lyr, whereclause) runID = str(raster[:-4]) + "_" + str(entid) print runID extent = row[1].extent Xmin = extent.XMin Ymin = extent.YMin Xmax = extent.XMax Ymax = extent.YMax extent_layer = str(Xmin) + " " + str(Ymin) + " " + str( Xmax) + " " + str(Ymax) dbf = outpath_final + os.sep + str(runID) print dbf if arcpy.Exists(dbf): continue else: arcpy.env.extent = extent_layer print extent_layer arcpy.MakeRasterLayer_management(dem, "rdlayer") symbologyLayer = "J:\Workspace\ESA_Species\Step3\ZonalHis_GAP\GAP.lyr" arcpy.ApplySymbologyFromLayer_management( "rdlayer", symbologyLayer) functions.ZonalHist(lyr, zoneField, "rdlayer", dbf, outpath_final, scratchpath) del lyr print "Loop completed in: {0}".format(datetime.datetime.now() - start_loop)
def ZonalHist(inZoneData, inValueRaster, scratchpath, set_raster_sybbology, snap_raster_dict): start_zone = datetime.datetime.now() # extract spatial reference from inraster to determine the correct snap raster ORGdsc = arcpy.Describe(inValueRaster) ORGsr = ORGdsc.spatialReference ORGprj = ORGsr.name() snapRaster = snap_raster_dict[ORGprj] arcpy.Delete_management("snap") arcpy.MakeRasterLayer_management(snapRaster, "snap") arcpy.env.snapRaster = "snap" # In paths path, use_raster = os.path.split(inValueRaster) path_fc, in_species = os.path.split(inZoneData) # out paths outgdb = use_raster + '.gdb' runID = use_raster + "_" + in_species outpath_final = out_results + os.sep + outgdb create_gdb(out_results, outgdb, outpath_final) # HARD CODE TO FIELD TO BE USE AS ZONEID zoneField = "Value" arcpy.env.scratchWorkspace = scratchpath arcpy.env.workspace = outpath_final arcpy.CheckOutExtension("Spatial") # arcpy.env.overwriteOutput = True # Results table dbf = outpath_final + os.sep + str(runID) if not arcpy.Exists(dbf): print dbf arcpy.MakeRasterLayer_management(inValueRaster, "rdlayer") arcpy.MakeRasterLayer_management(inZoneData, "fc_lyr") symbologyLayer = set_raster_sybbology arcpy.ApplySymbologyFromLayer_management("rdlayer", symbologyLayer) try: print("Running Statistics...for species group {0} and raster {1}". format(in_species, use_raster)) ZonalHistogram("fc_lyr", zoneField, "rdlayer", dbf) print "Completed in {0}\n".format( (datetime.datetime.now() - start_zone)) except Exception as error: print(error.args[0]) arcpy.Delete_management( dbf) # delete partial results if a run results in a error arcpy.Delete_management("rdlayer") arcpy.Delete_management("fc_lyr") else: print("Already completed run for {0}".format(runID))
def prep_obesity_dataset(): obesity_ras = orig_datasets_path + "\\Pre_Processed.gdb\\Obesity_PA_normalized_ras" # Display the raster arcpy.MakeRasterLayer_management(obesity_ras, "obesity_ras1") # reclassify the raster to 1-to-20 score using the Jenks natural breaks classification arcpy.CheckOutExtension("Spatial") outslice = arcpy.sa.Slice("obesity_ras1", 20, "NATURAL_BREAKS") outslice.save("obesity_score_ras") # Display the resulting raster (note that the tool demands a slightly different name for the layer) arcpy.MakeRasterLayer_management("obesity_score_ras", "obesity_score_ras1") # Cleanup remove_intermediary_layers(["obesity_ras1"])
def onClick(self): folder_path = pythonaddins.OpenDialog('Select Folder', False, r'C:\Program Files (x86)\ArcGIS','Add') #Ext = [".shp"] Ext = [".tif",".img",".pix",".dat"] if folder_path == None: pythonaddins.MessageBox("请选择一个文件夹",'消息',0) exit else: shpsList = [] for root,dirs,files in os.walk(folder_path): for file in files: filepath = os.path.join(root,file) if os.path.splitext(filepath)[1] in Ext: shpsList.append(filepath) mxd = arcpy.mapping.MapDocument('current') df = arcpy.mapping.ListDataFrames(mxd)[0] i = 1 for fc in shpsList: layer_name = os.path.splitext(os.path.basename(fc))[0] + str(i) print layer_name arcpy.MakeRasterLayer_management(fc, layer_name) del layer_name i = i + 1 arcpy.RefreshTOC() pythonaddins.MessageBox("栅格影像数据加载完成",'消息',0)
def polygon_to_raster(infc, outlocation, snapRaster, inlocation): start_conversion = datetime.datetime.now() # set environmental variables arcpy.env.workspace = outlocation arcpy.Delete_management("snap") arcpy.MakeRasterLayer_management(snapRaster, "snap") arcpy.env.snapRaster = "snap" # Set local variables inFeatures = inlocation + os.sep + infc valField = "Zone" outRaster = outlocation + os.sep + infc assignmentType = "CELL_CENTER" cellSize = snapRaster print inFeatures arcpy.Delete_management("fc_lyr") arcpy.MakeFeatureLayer_management(inFeatures, "fc_lyr") # Execute PolygonToRaster if not arcpy.Exists(outRaster): arcpy.PolygonToRaster_conversion("fc_lyr", valField, outRaster, assignmentType, "NONE", cellSize) print "\nCompleted conversion of {0} in {1}".format(outRaster, (datetime.datetime.now() - start_conversion)) else: print "\nAlready completed conversion {0}".format(outRaster) arcpy.Delete_management("snap")
def export_to_jpg(env, imagepath, outputImage_jpg, order_geometry, auid): mxd = arcpy.mapping.MapDocument(mxdexport_template) df = arcpy.mapping.ListDataFrames(mxd, '*')[0] sr_wgs84 = arcpy.SpatialReference(4326) df.SpatialReference = sr_wgs84 lyrpath = os.path.join(arcpy.env.scratchFolder, auid + '.lyr') arcpy.MakeRasterLayer_management(imagepath, lyrpath) image_lyr = arcpy.mapping.Layer(lyrpath) geo_lyr = arcpy.mapping.Layer(order_geometry) arcpy.mapping.AddLayer(df, image_lyr, 'TOP') arcpy.mapping.AddLayer(df, geo_lyr, 'TOP') geometry_layer = arcpy.mapping.ListLayers(mxd, 'OrderGeometry', df)[0] geometry_layer.visible = False geo_extent = geometry_layer.getExtent(True) image_extent = geo_lyr.getExtent(True) df.extent = image_extent if df.scale <= MapScale: df.scale = MapScale export_width = 5100 export_height = 6600 elif df.scale > MapScale: df.scale = ((int(df.scale) / 100) + 1) * 100 export_width = int(5100 * 1.4) export_height = int(6600 * 1.4) arcpy.RefreshActiveView() message_return = None try: image_extents = str({ "PROCEDURE": Oracle.erisapi_procedures['passclipextent'], "ORDER_NUM": order_num, "AUI_ID": auid, "SWLAT": str(df.extent.YMin), "SWLONG": str(df.extent.XMin), "NELAT": (df.extent.XMax), "NELONG": str(df.extent.XMax) }) message_return = Oracle(env).call_erisapi(image_extents) if message_return[3] != 'Y': raise OracleBadReturn except OracleBadReturn: arcpy.AddError('status: ' + message_return[3] + ' - ' + message_return[2]) mxd.saveACopy(os.path.join(arcpy.env.scratchFolder, auid + '_export.mxd')) arcpy.mapping.ExportToJPEG(mxd, outputImage_jpg, df, df_export_width=export_width, df_export_height=export_height, world_file=False, color_mode='24-BIT_TRUE_COLOR', jpeg_quality=50) del mxd
def add_naip_tiles_for_gt(gtpoints): ''' This function adds NAIP imagery where a ground truthing point is located into an arcgis project. Imagery is saved as a temporary layer. Functional in both ArcMap & ArcGIS Pro. gtpoints: name of ground truthing points shapefile to add NAIP based off of ''' naipqq_layer = canopy_config.naipqq_layer naip_path = canopy_config.naip_path arcpy.SelectLayerByAttribute_management(naipqq_layer, 'CLEAR_SELECTION') arcpy.SelectLayerByLocation_management(naipqq_layer, 'INTERSECT', gtpoints) with arcpy.da.SearchCursor(naipqq_layer, ['FileName']) as cur: for row in sorted(cur): filename = '%s.tif' % row[0][:-13] folder = filename[2:7] infile_path = '%s/%s/%s' % (naip_path, folder, filename) tmp = 'in_memory/%s' % filename arcpy.MakeRasterLayer_management(infile_path, tmp) arcpy.SelectLayerByAttribute_management(naipqq_layer, 'CLEAR_SELECTION') print('Completed')
def get_SR_for_buildings(): outExtractByMask = arcpy.sa.ExtractByMask("Avg_Solar_Radiation_Shifted", "Building_Footprints_Large") outExtractByMask.save("Avg_SR_for_buildings") # Load the raster into the MXD arcpy.MakeRasterLayer_management(main_data_path + "\\Avg_SR_for_buildings", "Avg_SR_for_buildings")
def zone(zone, raster, temp_table, outpath_final, dbf): start_zone = datetime.datetime.now() arcpy.MakeRasterLayer_management( r'L:\Workspace\ESA_Species\Step3\Step3_Proposal\GAP\layerfiles_use_to_change_legend_in _ArcMap\6EcolSys_landuse.lyr', "snap") arcpy.env.snapRaster = "snap" arcpy.CreateTable_management("in_memory", temp_table) temp = "in_memory" + os.sep + temp_table arcpy.env.overwriteOutput = True arcpy.gp.ZonalHistogram_sa(zone, "Value", raster, temp) try: arcpy.AddField_management(temp, 'TableID', "TEXT", "", "", "100", "", "NULLABLE", "NON_REQUIRED", "") arcpy.CalculateField_management(temp, "TableID", "!OBJECTID!", "PYTHON_9.3", "") except: pass print "Completed Zonal Histogram" try: arcpy.TableToTable_conversion(temp, outpath_final, dbf) except: pass list_fields = [f.name for f in arcpy.ListFields(temp)] att_array = arcpy.da.TableToNumPyArray((temp), list_fields) att_df = pd.DataFrame(data=att_array) return att_df, start_zone
def vertente_profile(dem, outrst, reclass=None): """ Cria Perfil Vertente """ arcpy.gp.Curvature_sa(mdt, "curvatura.tif", "1", "", "") saida = workspace + "\\" + str(saida) + ".tif" tempEnvironment0 = arcpy.env.extent arcpy.env.extent = mdt arcpy.gp.Reclassify_sa( workspace + "\\curvatura.tif", "Value", "-72 -0,025000000000000001 1;-0,025000000000000001 -0,0025000000000000001 2;-0,0025000000000000001 0,0025000000000000001 3;0,0025000000000000001 0,025000000000000001 4;0,025000000000000001 70 5", saida, "DATA") arcpy.env.extent = tempEnvironment0 layer = arcpy.MakeRasterLayer_management(saida, "lyr", "", "", "1") arcpy.AddField_management(layer, "classe", "TEXT", "50", "", "", "", "NULLABLE", "NON_REQUIRED", "") dic = { 1: "DoMenoraneg0.025", 2: "neg0.25aneg0.0025", 3: "neg0.0025apos0.0025", 4: "0.0025a0.025", 5: "0.025aMaior" } cs = arcpy.UpdateCursor(layer) for linha in cs: value = int(linha.getValue("Value")) for chave in dic.keys(): if value == chave: linha.setValue("classe", dc_exposicoes[chave]) cs.updateRow(linha) shutil.rmtree(workspace)
def makeLayer(output_folder, layer_base, new_layer_name, symbology_layer, isRaster, description="Made Up Description"): """ Creates a layer and applies a symbology to it :param output_folder: Where we want to put the folder :param layer_base: What we should base the layer off of :param new_layer_name: What the layer should be called :param symbology_layer: The symbology that we will import :param isRaster: Tells us if it's a raster or not :param description: The discription to give to the layer file :return: The path to the new layer """ new_layer = new_layer_name + "_lyr" new_layer_save = os.path.join(output_folder, new_layer_name + ".lyr") if isRaster: arcpy.MakeRasterLayer_management(layer_base, new_layer) else: arcpy.MakeFeatureLayer_management(layer_base, new_layer) arcpy.ApplySymbologyFromLayer_management(new_layer, symbology_layer) arcpy.SaveToLayerFile_management(new_layer, new_layer_save) new_layer_instance = arcpy.mapping.Layer(new_layer_save) new_layer_instance.description = description new_layer_instance.save() return new_layer_save
def load_main_data(): # Load the CII score raster arcpy.MakeRasterLayer_management(cii_overall_score_ras, "cii_overall_score_ras1") symbolize_rasters(["cii_overall_score_ras1"], recalc_stats = "no") turn_off_layers(["cii_overall_score_ras1"]) # Either we generate all the layers from scratch: if COMPUTE_FROM_SCRATCH_OPTION == "yes": # Convert the non-circuit trails from kml arcpy.KMLToLayer_conversion (trails_orig, trails_converted_path, "trails_converted") # Reproject the converted non-circuit trails feature class target_spatial_reference = arcpy.SpatialReference('NAD 1983 UTM Zone 18N') arcpy.Project_management("trails_converted\\Polylines", "trails_proj", target_spatial_reference, "WGS_1984_(ITRF00)_To_NAD_1983") # Load the LTS1-2 Islands feature class, and reproject it arcpy.MakeFeatureLayer_management(islands_orig, "islands_orig") arcpy.Project_management("islands_orig", "islands_proj", target_spatial_reference, "WGS_1984_(ITRF00)_To_NAD_1983") # Clean up remove_intermediary_layers(["trails_converted", "islands_orig"]) # Or we can load the layers already preprocessed: else: arcpy.MakeFeatureLayer_management("islands_with_score", "islands_with_score") arcpy.MakeFeatureLayer_management("trails", "trails") arcpy.MakeFeatureLayer_management("trails_intersecting", "trails_intersecting") arcpy.MakeFeatureLayer_management("trails_intersecting_gte_2", "trails_intersecting_gte_2") # Clean up turn_off_layers(["islands_with_score", "trails", "trails_intersecting", "trails_intersecting_gte_2"])
def compute_health_scores(): # Compute score raster for health / environment total_ras = (arcpy.Raster("obesity_score_ras1")*0.5 + arcpy.Raster("nata_resp_score_ras1")*0.5) total_ras.save("health_score_ras") # Display the new raster arcpy.MakeRasterLayer_management("health_score_ras", "health_score_ras1")
def rst_lyr(r): import os lyr = arcpy.MakeRasterLayer_management( r, os.path.splitext(os.path.basename(r))[0], "", "", "1") return lyr
def heatMapGen(radius, cellSize): print "Setting database and workspace..." + str(time.ctime()) arcpy.env.workspace = "D:/GD/WGiSR/_Konferencje/Plener 2018/heatMap/data.gdb" print " Database and workspace set! " + str(time.ctime()) print "Setting local variables..." + str(time.ctime()) mxd = arcpy.mapping.MapDocument( "D:/GD/WGiSR/_Konferencje/Plener 2018/heatMap/HeatMap.mxd") df = arcpy.mapping.ListDataFrames(mxd)[0] template = "D:/GD/WGiSR/_Konferencje/Plener 2018/heatMap/kd_temp_hypso.lyr" inData = "OSM_STOPS_2180" print " Local variables set! " + str(time.ctime()) print " Generating Heat Map..." + str(time.ctime()) arcpy.Delete_management("kd") arcpy.CheckOutExtension("Spatial") kd = arcpy.sa.KernelDensity(inData, "NONE", cellSize, radius, "SQUARE_KILOMETERS") kd.save("kd") arcpy.BuildPyramids_management("kd") arcpy.MakeRasterLayer_management("kd") layer = arcpy.mapping.Layer("kd") tempLyr = arcpy.mapping.Layer(template) arcpy.ApplySymbologyFromLayer_management(layer, tempLyr) arcpy.mapping.AddLayer(df, layer) mxd.save() print " Heat Map generated! " + str(time.ctime()) print " Exporting map..." + str(time.ctime()) arcpy.mapping.ExportToJPEG( mxd, "D:/GD/WGiSR/_Konferencje/Plener 2018/heatMap/_genMaps/HeatMap_radius_" + str(radius) + ".jpg") print " Map exported! " + str(time.ctime())
def compute_density_scores(): # Compute score raster for density total_ras = (arcpy.Raster("pop_density_score_ras1")*0.67 + arcpy.Raster("employment_score_ras1")*0.33) total_ras.save("density_score_ras") # Display the new raster arcpy.MakeRasterLayer_management("density_score_ras", "density_score_ras1")
def prep_idp_dataset(): # Local variables ipd = orig_datasets_path + "\\CII\\DVRPC_2016_Indicators_of_Potential_Disadvantage\\DVRPC_2016_Indicators_of_Potential_Disadvantage.shp" ipd_clipped = "ipd_clipped" ipd_ras = "ipd_ras" ipd_score_ras = "ipd_score_ras" # Load the feature class into the MXD arcpy.MakeFeatureLayer_management(ipd, "idp") # NO need to reproject (already in NAD 1983 UTM Zone 18N) # Clip to the boundaries of 4_counties_dissolved arcpy.SpatialJoin_analysis(ipd, "extent_4_counties", ipd_clipped, "JOIN_ONE_TO_ONE", "KEEP_COMMON", match_option="HAVE_THEIR_CENTER_IN") # Convert into a raster arcpy.PolygonToRaster_conversion (ipd_clipped, "IPD_Score", ipd_ras) # reclassify the raster to 1-to-20 score using the Jenks natural breaks classification arcpy.CheckOutExtension("Spatial") outslice = arcpy.sa.Slice(ipd_ras, 20, "NATURAL_BREAKS") outslice.save(ipd_score_ras) # Display the resulting raster (note that the tool demands a slightly different name for the layer) arcpy.MakeRasterLayer_management(ipd_score_ras, "ipd_score_ras1") # Cleanup remove_intermediary_layers(["idp","ipd_clipped", "ipd_ras"])
def runFeatToRast(tracts, projectGDBPath): # arcpy.AddMessage("\nGenerating cancer rate raster...") # Set local variables for Feature to Raster inFeatures = tracts field = "canrate" canrateRasterPath = os.path.join(projectGDBPath, "canrateRaster") # cellSize = # Execute Feature to Raster arcpy.FeatureToRaster_conversion(inFeatures, field, canrateRasterPath, "") # Get Feature to Raster Messages arcpy.AddMessage("\n" + arcpy.GetMessages()) # Create a raster layer to add to the MXD canrateRasterLyr = arcpy.MakeRasterLayer_management( canrateRasterPath, "canrateRaster") # Add the output to the MXD arcpy.SetParameterAsText(6, canrateRasterLyr) # arcpy.AddMessage("\nCancer rate raster generated:\n" + canrateRasterPath) # Delete local variables del inFeatures, field, canrateRasterPath # Return canrateRaster to global scope return canrateRasterLyr
def save_to_layer_file(data_location, include_mxd_layers=True): """Saves all data from the data location to layer files. :param data_location: folder containing data to be saved as layer files :param include_mxd_layers: save layers in mxd's to layer files - default is True """ import arcpy file_gdbs = glob.glob(os.path.join(data_location, '*.gdb')) for file_gdb in file_gdbs: arcpy.env.workspace = file_gdb feature_datasets = arcpy.ListDatasets('*', 'Feature') if feature_datasets: for fds in feature_datasets: arcpy.env.workspace = fds for fc in arcpy.ListFeatureClasses(): fl = arcpy.management.MakeFeatureLayer(fc, '{0}_'.format(fc)) arcpy.management.SaveToLayerFile(fl, os.path.join(data_location, '{0}.lyr'.format(fc))) arcpy.env.workspace = file_gdb for fc in arcpy.ListFeatureClasses(): fl = arcpy.management.MakeFeatureLayer(fc, '{0}_'.format(fc)) arcpy.management.SaveToLayerFile(fl, os.path.join(data_location, '{0}.lyr'.format(fc))) for raster in arcpy.ListRasters(): rl = arcpy.MakeRasterLayer_management(raster, '{0}_'.format(raster)) arcpy.management.SaveToLayerFile(rl, os.path.join(data_location, '{0}.lyr'.format(raster))) if include_mxd_layers: mxd_files = glob.glob(os.path.join(data_location, '*.mxd')) for mxd_file in mxd_files: mxd = arcpy.mapping.MapDocument(mxd_file) layers = arcpy.mapping.ListLayers(mxd) for layer in layers: if layer.description == '': layer.description = layer.name arcpy.management.SaveToLayerFile(layer, os.path.join(data_location, '{0}.lyr'.format(layer.name)))
def addGHSL(urbanLayer, curMap, ghslFolder, datamaskFolder, lyrSymbology, extentsSymbology, ghslOutline): inputGHSLMap = r"S:\GLOBAL\Global_Human_Settlement_Layer\GHSL_Footprint_Maps.mxd" outlinesFL = "GHSLOut2" shapeFL = "InShape" arcpy.MakeFeatureLayer_management(ghslOutline, outlinesFL) #Open map and add urban layer mxd = arcpy.mapping.MapDocument(inputGHSLMap) mxd.saveACopy(curMap) mxd = arcpy.mapping.MapDocument(curMap) df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0] urbLyr = arcpy.mapping.Layer(urbanLayer) urbLyr.definitionQuery = 'NOT "ExtentName" = \'0\'' arcpy.ApplySymbologyFromLayer_management(urbLyr, extentsSymbology) arcpy.mapping.AddLayer(df, urbLyr) #Find intersecting curTitles = selectGHSLtiles(urbanLayer, ghslOutline, 'Path', False) lyrCnt = 0 for c in curTitles: c = os.path.join(ghslFolder, c) #Add MT layer outLayer = "%s_%s" % (os.path.basename(c), "mt") #if not outLayer in [l.name for l in arcpy.mapping.ListLayers(mxd)]: result = arcpy.MakeRasterLayer_management(c, outLayer) layer = result.getOutput(0) arcpy.ApplySymbologyFromLayer_management(layer, lyrSymbology) arcpy.mapping.AddLayer(df, layer) df.extent = arcpy.Describe(urbanLayer).extent mxd.save()
def addGUF(gufMap, curTiles, urbanLayer, curMap, gufFolder, gufSymbology, extentsSymbology): outlinesFL = "GHSLOut2" shapeFL = "InShape" #Open map and add urban layer mxd = arcpy.mapping.MapDocument(gufMap) mxd.saveACopy(curMap) mxd = arcpy.mapping.MapDocument(curMap) df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0] urbLyr = arcpy.mapping.Layer(urbanLayer) urbLyr.definitionQuery = 'NOT "ExtentName" = \'0\'' arcpy.ApplySymbologyFromLayer_management(urbLyr, extentsSymbology) arcpy.mapping.AddLayer(df, urbLyr) lyrCnt = 0 for c in curTiles: c = os.path.join(gufFolder, c) outLayer = "GHSL_%s" % lyrCnt #if not outLayer in [l.name for l in arcpy.mapping.ListLayers(mxd)]: result = arcpy.MakeRasterLayer_management(c, outLayer) layer = result.getOutput(0) arcpy.ApplySymbologyFromLayer_management(layer, gufSymbology) arcpy.mapping.AddLayer(df, layer) lyrCnt = lyrCnt + 1 df.extent = arcpy.Describe(urbanLayer).extent mxd.save()
def mergePhotosNoText( inlist, outPath, year, poly, scale, document=r"C:\Workspace\Topo_work\mopoMerger_minimalist.mxd", site=True): """""" outname = os.path.join(outPath, '{0}_{1}.jpg'.format(year, scale)) mxd = arcpy.mapping.MapDocument(document) df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0] ### change some text around ## mydict = {x.name: x for x in arcpy.mapping.ListLayoutElements(mxd)} ## mydict['year'].text = str(year) ## basequadtext = "{quad}, {state}\n" ## quadtext = "" ## for i in inlist: ## name = os.path.split(i)[1][:-4] ## stateusps = name[:2] ## state = statedict[stateusps.upper()] ## quad = ' '.join(x.capitalize() for x in name.split('_')[1].split(' ')) ## print quad ## quadtext += basequadtext.format(state=state, quad=quad) ## mydict["quadname"].text = quadtext ## ## if scale == '24k': ## mydict['minute'].text = mydict['minute'].text.format('7.5') ## elif scale == '62k': ## mydict['minute'].text = mydict['minute'].text.format('15') ## else: ## print 'wrong scale bitch' ## print 'here' for i, raster in enumerate(inlist): name = os.path.split(raster)[1][:-4] templayer = arcpy.MakeRasterLayer_management(raster, name) layerondisk = arcpy.SaveToLayerFile_management( templayer, r'C:\temp\temp{}.lyr'.format(name)) a = arcpy.mapping.Layer(r'C:\temp\temp{}.lyr'.format(name)) arcpy.mapping.AddLayer(df, a, 'AUTO_ARRANGE') df.displayUnits = "inches" #templayer = arcpy.MakeFeatureLayer_management(r'C:\temp2\temp_feature.shp',"test") #layerondisk = arcpy.SaveToLayerFile_management(templayer, r'C:\temp\site.lyr') # this will be an if clause to see what shape it is and what layer works best if site == True: a = arcpy.mapping.Layer(r'C:\temp\point_test.lyr') a.transparency = 10 #print a.symbologyType #a.transparency = 0 #a.replaceDataSource(r'C:\Workspace\topo_work\terracon_example.gdb\tester') arcpy.mapping.AddLayer(df, a, "TOP") arcpy.SelectLayerByAttribute_management(a, 'CLEAR_SELECTION') #df.elementHeight = 9 #df.elementWidth = 8 df.spatialReference = poly.spatialReference df.extent = poly.extent arcpy.mapping.ExportToJPEG( mxd, outname, resolution=300 ) #df,df_export_width=2400,df_export_height=2700,resolution=300 )
def remove_low_performance_areas(): outCon = arcpy.sa.Con("Avg_SR_for_buildings_low_slope", "Avg_SR_for_buildings_low_slope", "", "VALUE >= 2200") outCon.save("Avg_SR_for_buildings_high_performance") arcpy.MakeRasterLayer_management( main_data_path + "\\Avg_SR_for_buildings_high_performance", "Avg_SR_for_buildings_high_performance")
def dci(fdr, out_patch, gdb_path, uttl, config_file): result_folder = os.path.dirname(gdb_path) arcpy.env.workspace = result_folder arcpy.env.overwriteOutput = True downstream = os.path.join(result_folder, 'temp', 'downstream.tif') upstream = os.path.join(result_folder, 'temp', 'upstream.tif') arcpy.gp.FlowLength_sa(fdr, downstream, "DOWNSTREAM", "") arcpy.gp.FlowLength_sa(fdr, upstream, "UPSTREAM", "") arcpy.MakeRasterLayer_management(downstream, 'downstream') arcpy.MakeRasterLayer_management(upstream, 'upstream') arcpy.gp.RasterCalculator_sa('"upstream" / ("upstream" + "downstream")', os.path.join(gdb_path, out_patch)) arcpy.gp.MakeRasterLayer_management(os.path.join(gdb_path, out_patch), 'dci') xls_file = pd.ExcelFile(config_file) df_criteria = xls_file.parse('Conectividad', index_col='Conectividad') very_high_low_input = df_criteria.ix['Muy Alta', 'Rango Inferior'] high_low_input = df_criteria.ix['Alta', 'Rango Inferior'] medium_low_input = df_criteria.ix['Media', 'Rango Inferior'] low_low_input = df_criteria.ix['Baja', 'Rango Inferior'] very_high_value = df_criteria.ix['Muy Alta', 'Value'] high_value = df_criteria.ix['Alta', 'Value'] medium_value = df_criteria.ix['Media', 'Value'] low_value = df_criteria.ix['Baja', 'Value'] very_low_value = df_criteria.ix['Muy Baja', 'Value'] arcpy.gp.RasterCalculator_sa('Con("dci" <= {}, {}, Con(("dci" > {}) & ("dci" <= {}), {}, Con(("dci" > {}) & ("dci" <= {}),{}, Con(("dci" > {}) & ("dci" <= {}),{}, {}))))'.format(low_low_input, very_low_value, low_low_input, medium_low_input, low_value, medium_low_input, high_low_input, medium_value, high_low_input, very_high_low_input, high_value, very_high_value), os.path.join(gdb_path, 'dci_reclass')) arcpy.gp.RasterCalculator_sa('Con("dci" <= 0.005, 1.0, Con(("dci" > 0.005) & ("dci" <= 0.01), 1.5, Con(("dci" > 0.01) & ("dci" <= 0.1),2.0, Con(("dci" > 0.1) & ("dci" <= 0.3),2.5, 3.0))))', os.path.join(gdb_path, 'dci_reclass')) zonal_stats(uttl, os.path.join(gdb_path, 'dci_reclass'), 'dci', 'MAXIMUM') table = {val: key for (key, val) in df_criteria['Value'].to_dict().items()} classify_data(uttl, 'dci', 'conec_class', table)
def zonal_hist(in_zone, in_raster, set_raster_symbology, use_nm, temp_table, current_use): use_nm_folder = current_use if not os.path.exists(out_results + os.sep + use_nm_folder): os.mkdir(out_results + os.sep + use_nm_folder) symbology_loop = sy_path + os.sep + use_nm + '.lyr' out_tables = out_results + os.sep + use_nm_folder run_id = str(current_use) + "_" + str(use_nm) out_path_final = out_tables csv = run_id + '.csv' dbf = csv.replace('csv', 'dbf') if os.path.exists(out_path_final + os.sep + csv): print("Already completed run for {0}".format(run_id)) elif not os.path.exists(out_path_final + os.sep + dbf): print("Running Statistics...for {0} v raster {1}".format( current_use, use_nm)) arcpy.CheckOutExtension("Spatial") arcpy.MakeRasterLayer_management(Raster(in_zone), "zone") arcpy.ApplySymbologyFromLayer_management("zone", set_raster_symbology) arcpy.MakeRasterLayer_management(Raster(in_raster), "rd_lyr") arcpy.ApplySymbologyFromLayer_management("rd_lyr", symbology_loop) temp_return, start_loop = zone("zone", "rd_lyr", temp_table) list_fields = [f.name for f in arcpy.ListFields(temp_return)] att_array = arcpy.da.TableToNumPyArray(temp_return, list_fields) att_df = pd.DataFrame(data=att_array) att_df.to_csv(out_path_final + os.sep + csv) # arcpy.TableToTable_conversion(temp_return, out_path_final, dbf) print 'Final file can be found at {0}'.format(out_path_final + os.sep + csv) print "Completed in {0}\n".format( (datetime.datetime.now() - start_time)) elif not os.path.exists(out_path_final + os.sep + csv): list_fields = [ f.name for f in arcpy.ListFields(out_path_final + os.sep + dbf) ] att_array = arcpy.da.TableToNumPyArray((out_path_final + os.sep + dbf), list_fields) att_df = pd.DataFrame(data=att_array) att_df['LABEL'] = att_df['LABEL'].map(lambda x: x).astype(str) att_df.to_csv(out_path_final + os.sep + csv)