def createBuffers(point, outLayer, distances, units): """ Create a multi-ring buffer from an point layer""" try: # Create a multi-ring buffer of point # See http://pro.arcgis.com/en/pro-app/tool-reference/analysis/multiple-ring-buffer.htm # assign geoprocessing tool to a variable to access messages from tool result = arcpy.MultipleRingBuffer_analysis(point, outLayer, distances, units) # capture geoprocessing results message # delay writing results until geoprocessing tool gets the completed code while result.status < 4: time.sleep(0.2) # See http://pro.arcgis.com/en/pro-app/arcpy/functions/getmessages.htm resultValue = result.getMessages() # add results message to ArcGIS dialog window arcpy.AddMessage(resultValue + '\n \n') # Add Message addMessage( 'Created buffer(s) around location latitude: {}; longitude: {}.'. format(lat, lon)) # if an error occured, write this to dialog window except Exception as e: # line of error tbE = sys.exc_info()[2] # See http://pro.arcgis.com/en/pro-app/arcpy/functions/adderror.htm arcpy.AddError("Failed at Line %i \n\n" % tbE.tb_lineno) arcpy.AddError('Error: {} \n\n'.format(e.message)) # Add generic error message about tool arcpy.AddError('There was an error running this tool \n\n') # exit script sys.exit()
def makeringbuffer(layers, field, bufferoutputs, distances): """图层,图层检索字段,缓冲区目录,多环缓冲距离""" cursor = arcpy.da.SearchCursor(layers, field) counter = 0 for row in cursor: getvalue_field = row[0] # 创建feature class,这一步可要可不要 outFeatureName = 'feature_class' print counter arcpy.MakeFeatureLayer_management(layers, outFeatureName) # 选中各个乡镇级图斑 arcpy.SelectLayerByAttribute_management( outFeatureName, 'NEW_SELECTION', "\"XJQYMC\" = \'" + getvalue_field + "'") # make buffer inFeatures = outFeatureName outBufferName = 'buffer' bufferunit = 'meters' arcpy.MultipleRingBuffer_analysis(inFeatures, outBufferName, distances, bufferunit, '', '', 'OUTSIDE_ONLY') # 输出缓冲区 # outdata1 = os.path.join(bufferoutputs, getvalue_field + 'buffer') arcpy.CopyFeatures_management( outBufferName, os.path.join(bufferoutputs, getvalue_field + 'buffer')) counter += 1 del cursor
def make_buffer_ring(self): num = int(self.times) inputfile = self.in_f distance = [_*num for _ in self.distance] arcpy.MultipleRingBuffer_analysis(inputfile, self.output, distance, "Meters", Outside_Polygons_Only=True) # set symbol and add layer to ArcMap self.res_lyr = arcpy.mapping.Layer(self.output)
def multiple_ring_buffer(in_fc, out_fc, distances, buffer_unit): # Creates a multi ring buffer output feature class from input feature class. # Reference: https://pro.arcgis.com/en/pro-app/latest/tool-reference/analysis/multiple-ring-buffer.htm arcpy.AddMessage('\nStarting multiple_ring_buffer') try: result = arcpy.MultipleRingBuffer_analysis(in_fc, out_fc, distances, buffer_unit, "", "ALL") check_status(result) except arcpy.ExecuteError: arcpy.AddError(arcpy.GetMessages(2)) arcpy.AddMessage('multiple_ring_buffer complete\n')
fieldAlias2 = "Area (Acres)" fieldAlias4 = "Subject Category" expression2 = "int(!shape.area@acres!)" pDist = [] for x in Distances: pDist.append(round(x * mult, 2)) arcpy.AddMessage("Units = " + bufferUnit) arcpy.AddMessage(pDist) while row: # you need to insert correct field names in your getvalue function arcpy.MultipleRingBuffer_analysis(fc3, IPPBuffer, pDist, bufferUnit, "DistFrmIPP", dissolve_option, "FULL") row = rows.next() del rows del row del where arcpy.AddMessage('Completed multi-ring buffer') arcpy.AddField_management(inFeatures, fieldName1, "TEXT", "", "", "25", fieldAlias1, "NULLABLE", "", "PrtRange") arcpy.AddField_management(inFeatures, fieldName2, "DOUBLE", "", "", "", fieldAlias2, "NULLABLE") arcpy.AddField_management(inFeatures, fieldName3, "DOUBLE", "", "", "", fieldAlias3, "NULLABLE")
def geoprocessing(currentcity): """ Fist step is defining local variables for the geoprocessing function""" # Local variables for function: freeways_Clip = 'freeways_clip' walmarts_Clip = 'walmarts_clip' Hospitals_Clip = 'hospitals_clip' airports_Clip = 'airports_clip' airports_buffer = 'airports_buffer' hospitals_buffer = 'hospitals_buffer' walmarts_buffer = 'walmarts_buffer' freeways_buffer = 'freeways_buffer' airports_raster = 'airports_raster' hospitals_raster = 'hospitals_raster' walmarts_raster = 'walmarts_raster' freeways_raster = 'freeways_raster' cellsize = .002 """ Editing and cleaning up of geoprocessing functions """ """the first variable is the freeway as the best place to live in needs to be far from a freeway but not two far. this function clips the nationwide shapefile according to the city's citybound shapefile. Same process was done to the three other variables (Hospitals, Walmarts, and airports) as we want to be close but not too close to a walmart and far but not too far from an airport and a hospital. THE FUNCTION USED TO FOR ClIPPING IS arcpy.Clip_analysis (input shape file, feature used to clip input, output shapefile)""" # Process: Clip freeways arcpy.AddMessage("For " + city + " clip freeways") arcpy.Clip_analysis(freeways, citybound, freeways_Clip, "") """The clipped freeway variable was then buffered to distances of 0.5 miles and 3 miles. Same thing was done to the other variables. Airports had buffered distances of 3 and 25 miles Hospitals had buffered distances of 0.5 and 25 miles Walmarts had buffered distances of 0.5 and 3 miles THE FUNCTION USED FOR BUFFERING IS arcpy.MultipleRingBuffer_analysis(input, output, buffered distance, unit of distance , and other optional stuff here )""" # Process: Buffer Freeway arcpy.AddMessage("For " + city + " buffer freeways") arcpy.MultipleRingBuffer_analysis(freeways_Clip, freeways_buffer, [0.5, 3], "miles", "", "ALL", "FULL") # Process: Clip airports arcpy.AddMessage("For " + city + " clip airports") arcpy.Clip_analysis(airports, citybound, airports_Clip) # Process: Buffer airports arcpy.AddMessage("For " + city + " buffer airports") arcpy.MultipleRingBuffer_analysis(airports_Clip, airports_buffer, [3.0, 25], "miles", "", "ALL","FULL") # Process: Clip Hospitals arcpy.AddMessage("For " + city + " clip hospitals") arcpy.Clip_analysis(hospitals, citybound, Hospitals_Clip, "") # Process: Buffer Hospitals arcpy.AddMessage("For " + city + " buffer hospitals") arcpy.MultipleRingBuffer_analysis(Hospitals_Clip, hospitals_buffer, [0.5, 25], "miles", "","ALL","FULL") # Process: Clip Walmarts arcpy.Clip_analysis(walmarts, citybound, walmarts_Clip, "") # Process: Buffer Walmarts arcpy.MultipleRingBuffer_analysis(walmarts_Clip, walmarts_buffer, [0.5, 3], "miles", "", "ALL","FULL") # Convert Polygons to Raster """Takes the vector shapefiles created by the clip and multi-ring buffer and converts them to a raster. Written by Elise""" arcpy.AddMessage("Convert " + city + " buffered shapefiles to raster") arcpy.PolygonToRaster_conversion(airports_buffer, "distance", airports_raster, "CELL_CENTER", "NONE", cellsize) arcpy.PolygonToRaster_conversion(walmarts_buffer, "distance", walmarts_raster, "CELL_CENTER", "NONE", cellsize) arcpy.PolygonToRaster_conversion(hospitals_buffer, "distance", hospitals_raster, "CELL_CENTER", "NONE", cellsize) arcpy.PolygonToRaster_conversion(freeways_buffer, "distance", freeways_raster, "CELL_CENTER", "NONE", cellsize) """The different rasters created were then multiplied together to obtain a final raster that combines all the previous conditions together THE FUNCTION USED HERE IS THE Times function that multiplies 2 rasters together The final step in the geoprocessing function is adding the final raster to the map""" # Raster Calculator arcpy.AddMessage('Combine all rasters') raster_calc1 = Times(walmarts_raster, hospitals_raster) raster_calc2 = Times(freeways_raster, airports_raster) raster_calc3 = Times(raster_calc1, raster_calc2) raster_calc3.save("raster_calc")
#print query File_output = file_workspace + '\\' 'Buffer_' + str(row[0]) # print File_output # Select Feature using the reference number from holdings layer arcpy.SelectLayerByAttribute_management('Holdings_Layer', 'NEW_SELECTION', "Holding_Reference_Number = " + str(row[0])) # Export holding to geodatabase Holding_Boundary = file_workspace + '\\' 'Holding_' + str(row[0]) arcpy.management.CopyFeatures('Holdings_Layer', Holding_Boundary) # Mutliple ring Buffer using Selected Features arcpy.MultipleRingBuffer_analysis('Holdings_Layer', File_output, distances, unit, "", "ALL") arcpy.MakeFeatureLayer_management(File_output, 'Buffer_Layer') # arcpy.Buffer_analysis("Holdings_Layer", ofc, var_Buffer, "FULL", "ROUND", "ALL", "") #Clip Holdings Buffer # Intersect Features Intersect_out_features = file_workspace + '\\' 'Intersect_' + str(row[0]) arcpy.Intersect_analysis([Holdings_clip, File_output], Intersect_out_features, "", "", "INPUT") Dissolved_output_intersect = file_workspace + '\\' 'Intersect_Dissolve_' + str(row[0]) Dissolve_fields_intersect = ['Holding_Name', 'distance'] arcpy.Dissolve_management(Intersect_out_features, Dissolved_output_intersect, Dissolve_fields_intersect) #print "intersect Complete"
# create flow direction raster dir_ras = 'dir_ras' FlowDirection(surface) flowDirection.save(dir_ras) # Calculate flow accumulation flow_accum = 'flow_accum' flowAccumulation = FlowAccumulation(dir_ras, "", "FLOAT") flowAccumulation.save(flow_accum) #create buffer around water bodies distance = [5, 10, 20, 50] rivers_all = "river_florida.shp" river_buf = "river_buffer.shp" arcpy.MultipleRingBuffer_analysis(rivers_all, river_buf, distance, "miles", "", "ALL") # clip waterbodies to extent rivers = "riversbuf_clip.shp" arcpy.Clip_analysis(river_buf, project_area, rivers) #convert buffer distance to raster data river_raster = "river_raster.tif" field = "distance" arcpy.FeatureToRaster_conversion(rivers, field, river_raster) #clip precipitation to study area precip_fl = "precip1981_2010_a_fl.shp" precip = "precip_clip.shp" arcpy.Clip_analysis(precip_fl, project_area, precip)
#Creation polygone Poly = arcpy.Polygon(arcpy.Array(points), SRS) resultat.append( [Poly, Pas_A[id] * 180 / pi, Pas_A[id + 1] * 180 / pi]) #"SHAPE@","ANGLE_D","ANGLE_F" secteurs_angles = arcpy.CreateUniqueName("sectangle", "in_memory") arcpy.CreateFeatureclass_management(os.path.dirname(secteurs_angles), os.path.basename(secteurs_angles), "POLYGON") arcpy.AddField_management(secteurs_angles, "ANGLE_D", "SHORT") arcpy.AddField_management(secteurs_angles, "ANGLE_F", "SHORT") with arcpy.da.InsertCursor(secteurs_angles, ("SHAPE@", "ANGLE_D", "ANGLE_F")) as cursor: for poly in resultat: cursor.insertRow(poly) #Creation cercles concentriques secteurs_dist = arcpy.CreateUniqueName("sectdist", "in_memory") if 0 in Pas_D: del Pas_D[Pas_D.index(0)] #supprime valeur 0 arcpy.MultipleRingBuffer_analysis(geom, secteurs_dist, Pas_D, "Meters", "DIST_KM") #Intersection des deux couches arcpy.Intersect_analysis([secteurs_dist, secteurs_angles], output, "ALL") #Suppression des champs inutiles arcpy.DeleteField_management(output, [ f.name for f in arcpy.ListFields(output) if not f.required and f.name not in ("ANGLE_D", "ANGLE_F", "DIST_KM") ])
wd = r"C:\LocalGIS\LatentDemand2020\DemandCenterline_Inputs.gdb" temp_wd = os.path.dirname(wd) arcpy.env.workspace = wd arcpy.env.overwriteOutput = True # list feature classes fclist = arcpy.ListFeatureClasses() print(fclist) # Buffers bufferslist1 = [ "RailStations", "K12Schools", "ParksTrailheads", "RetailCenters" ] for i in bufferslist1: arcpy.MultipleRingBuffer_analysis(i, i + "buffer", [330, 660, 1320, 2640, 150000], "feet", i + "dist", "ALL") print(i + "Complete!") arcpy.MultipleRingBuffer_analysis("Colleges", "CollegesBuffer", [1, 2, 4, 100], "miles", "collegedist", "ALL") # prep bus data for buffer bus_distances = [330, 660, 1320, 2640, 100000] bus_distances_meters = [distance * 0.3048 for distance in bus_distances] arcpy.FeatureClassToFeatureClass_conversion("BusStops", temp_wd, "bus_stops.shp") bus_buffer = MultiRing_Buffer(os.path.join(temp_wd, "bus_stops.shp"), os.path.join(temp_wd, "BusStopsBuffer.shp"), bus_distances_meters, "busdistm") arcpy.FeatureClassToFeatureClass_conversion(bus_buffer, wd, "BusStopsBuffer")
SingleRingWidth = arcpy.GetParameterAsText(1) OutputFeature = arcpy.GetParameterAsText(2) # Some Predefined Parameters distances = [] level = 9 bufferUnit = "meters" NewField = "Percent" # My Easy Feathering function for i in range(level): distances.append(int(SingleRingWidth) * (i + 1)) i = i + 1 arcpy.AddMessage("Step1 Distance list Complete!") arcpy.MultipleRingBuffer_analysis(InputFeature, OutputFeature, distances, bufferUnit, "", "ALL", "OUTSIDE_ONLY") arcpy.AddMessage("Step2 Success to execute Multi Ring Buffer.") arcpy.AddField_management(OutputFeature, NewField, "double") arcpy.AddMessage("Step3 Success to add Transparency Percent Field.") arcpy.CalculateField_management(OutputFeature, NewField, "!OBJECTID! *10", "PYTHON", "") OutputFeatureCount = int(arcpy.GetCount_management(OutputFeature).getOutput(0)) if OutputFeatureCount == 0: arcpy.AddWarning("{0} has no features.".format(OutputFeature)) else: arcpy.AddMessage("Step4 Success to Calculate Transparency Percent Field.")
def createRiskRadii(lat,lon,patts_id,mrb_distances,mrb_units,out_gbd,text_file): """Creates a multi-ring buffer for a SARA facility""" try: # allow data to be ovewritten arcpy.env.overwriteOutput = True # Variables for Project tool # WGS 1984 geographic coordinate system sr_wgs_84 = arcpy.SpatialReference(4326) # PA State Plane South (feet) NAD 1983 projected coordinate system sr_spc = arcpy.SpatialReference(2272) # reprojected point output name output_spc_name = 'Input_Point_SPC_PATTS_{}'.format(patts_id) # output layer output_spc = os.path.join(out_gbd,output_spc_name) # create point from user entered latitude and longitude point = arcpy.Point(lon, lat) # create geometry point for use in buffer tool - WGS 1984 geometry_point = arcpy.PointGeometry(point, sr_wgs_84) # Convert WGS 1984 layer to a NAD 1983 PA State Plane South layer arcpy.Project_management(geometry_point, output_spc, sr_spc, "NAD_1983_To_WGS_1984_1", preserve_shape = "PRESERVE_SHAPE") # Multi-ring Buffer tool # Output layer mrb_output = os.path.join(out_gbd, 'RiskRadii_PATTS_{}'.format(patts_id)) # Field name in output layer to store buffer distance mrb_distance_field = 'BUFFDIST' # Dissolve option mrb_dissolve_option = 'NONE' # Run tool arcpy.MultipleRingBuffer_analysis(output_spc,mrb_output,mrb_distances,mrb_units,mrb_distance_field,mrb_dissolve_option) # Add message that Multiple Ring Buffer tool complete # Add field to output layer with PATTS ID field_name_patts = 'PATTS' field_type = 'TEXT' field_expression_patts = '"{}"'.format(patts_id) # Execut Add Field Management tool arcpy.AddField_management(mrb_output,field_name_patts,field_type) # Calculate PATTS ID to field arcpy.CalculateField_management(mrb_output, field_name_patts, field_expression_patts, 'PYTHON_9.3') # Add field to output layer with buffer distance units field_name_units = 'UNITS' field_expression_units = '"{}"'.format(mrb_units) # Execut Add Field Management tool arcpy.AddField_management(mrb_output,field_name_units,field_type) # Calculate buffer distance units arcpy.CalculateField_management(mrb_output, field_name_units, field_expression_units, 'PYTHON_9.3') # Add message that buffer distance units added to Units field arcpy.AddMessage('\nCompleted adding fields to Risk Radius/Radii map layer') # run floodplain analysis module arcpy.AddMessage('\nPerforming analysis to see if SARA facility is within a floodplain') floodplainAnalysis.intersectFloodplainTest(output_spc,lon,lat,text_file) # make projected sara site and sara risk radii layer available as input to other tools return output_spc, mrb_output # If an error occurs running geoprocessing tool(s) capture error and write message # handle error outside of Python system except EnvironmentError as e: arcpy.AddError('\nAn error occured running this tool. Please provide the GIS Department the following error messages:') # call error logger method errorLogger.PrintException(e) # handle exception error except Exception as e: arcpy.AddError('\nAn error occured running this tool. Please provide the GIS Department the following error messages:') # call error logger method errorLogger.PrintException(e)
NotifiedParcels = r"K:\Community Development\GIS\CommDevGDB.gdb\NotifiedParcels" fields = ("PageNo", "BufferArea", "BufferAcres","SHAPE_Area") mxd = arcpy.mapping.MapDocument("CURRENT") df = arcpy.mapping.ListDataFrames(mxd, "Layers") [0] #Check to make sure something was selected count = int (arcpy.GetCount_management(input).getOutput(0)) if count > 100: arcpy.AddMessage("NO PARCELS SELECTED") sys.exit(0) else: arcpy.Dissolve_management(input, AreaOfRequest) #Run buffer arcpy.MultipleRingBuffer_analysis(AreaOfRequest,'in_memory/tmpBuf',[200,300],"Feet","","ALL","FULL") #Check if buffer extends beyond city limit arcpy.MakeFeatureLayer_management('in_memory/tmpBuf', "tmpLyr") arcpy.SelectLayerByLocation_management("tmpLyr", "CROSSED_BY_THE_OUTLINE_OF","City Limit","","NEW_SELECTION") count = str(arcpy.Describe("tmpLyr").FIDset) if count == "1" or count == "2" or count == "1; 2": arcpy.Clip_analysis('in_memory/tmpBuf',"City Limit",'in_memory/tmpBuf2') else: arcpy.CopyFeatures_management('in_memory/tmpBuf', 'in_memory/tmpBuf2') #Export parcels within 300ft arcpy.SelectLayerByLocation_management("Parcels","INTERSECT",'in_memory/tmpBuf2',"","NEW_SELECTION") arcpy.CopyFeatures_management("Parcels", NotifiedParcels)
def Wanderungssalden_schaetzen(self): parameters = self.par projektname = self.projectname cursor = self.parent_tbx.query_table( table_name='Chronik_Nutzung', columns=['Arbeitsschritt', 'Letzte_Nutzung'], workspace='FGDB_Einnahmen.gdb') salden_berechnet = True for row in cursor: if row[0] == "Wanderung Einwohner" and row[1] is None: salden_berechnet = False if self.par.aktualisieren.value == True or salden_berechnet == False: lib_einnahmen.create_gemeindebilanzen(self, projektname) workspace_projekt_definition = self.folders.get_db( 'FGDB_Definition_Projekt.gdb', projektname) workspace_projekt_einnahmen = self.folders.get_db( 'FGDB_Einnahmen.gdb', projektname) wanderungssalden = os.path.join(workspace_projekt_einnahmen, "Gemeindebilanzen") projektflaechen = join(workspace_projekt_definition, 'Teilflaechen_Plangebiet') if arcpy.Exists("projektflaechen_lyr"): arcpy.Delete_management("projektflaechen_lyr") arcpy.MakeFeatureLayer_management(projektflaechen, "projektflaechen_lyr") fields = [ "Einw_Zuzug", "Einw_Fortzug", "Einw_Saldo", "Wanderungsanteil_Ew", "Gewichtete_Ew", "SvB_Zuzug", "SvB_Fortzug", "SvB_Saldo" ] cursor = arcpy.da.UpdateCursor(wanderungssalden, fields) for gemeinde in cursor: gemeinde[0] = 0 gemeinde[1] = 0 gemeinde[2] = 0 gemeinde[3] = 0 gemeinde[4] = 0 gemeinde[5] = 0 gemeinde[6] = 0 gemeinde[7] = 0 cursor.updateRow(gemeinde) #Wichtungsfaktoren auslesen Wichtungen_Gewerbe = {} Wichtungen_Wohnen = {} path_distanzen = self.folders.get_base_table( "FGDB_Einnahmen_Tool.gdb", "Wanderung_Entfernungswichtung") cursor = arcpy.da.SearchCursor( path_distanzen, ["Distance", "Wichtung_Wohnen", "Wichtung_Gewerbe"]) for distanz in cursor: Wichtungen_Wohnen[str(int(distanz[0]))] = distanz[1] Wichtungen_Gewerbe[str(int(distanz[0]))] = distanz[2] #arcpy.AddMessage(Wichtungen_Wohnen) #Randsummen Wanderung auslesen (Anteile innerhalb/außerhalb 25km und Neugründungen [nur Gewerbe]) Randsummen_Gewerbe = {} Randsummen_Wohnen = {} path_randsummen = self.folders.get_base_table( "FGDB_Einnahmen_Tool.gdb", "Wanderung_Randsummen") cursor = arcpy.da.SearchCursor( path_randsummen, ["IDWanderungstyp", "Anteil_Wohnen", "Anteil_Gewerbe"]) for randsumme in cursor: Randsummen_Wohnen[randsumme[0]] = randsumme[1] Randsummen_Gewerbe[randsumme[0]] = randsumme[2] #arcpy.AddMessage(Randsummen_Wohnen) #Anteile der Herkunftsgemeinden an Einwohner bestimmen pfad_buffer = os.path.join(workspace_projekt_einnahmen, "buffer_25km") if arcpy.Exists(pfad_buffer): arcpy.Delete_management(pfad_buffer) pfad_Rasterausschnitt = os.path.join(workspace_projekt_einnahmen, "Rasterausschnitt") if arcpy.Exists(pfad_Rasterausschnitt): arcpy.Delete_management(pfad_Rasterausschnitt) pfad_Rasterausschnitt_25km = os.path.join(workspace_projekt_einnahmen, "Rasterausschnitt_25km") if arcpy.Exists(pfad_Rasterausschnitt_25km): arcpy.Delete_management(pfad_Rasterausschnitt_25km) pfad_Punktlayer_25km_posWerte = os.path.join( workspace_projekt_einnahmen, "Punktlayer_25km_posWerte") if arcpy.Exists(pfad_Punktlayer_25km_posWerte): arcpy.Delete_management(pfad_Punktlayer_25km_posWerte) pfad_Entfernungsringe = os.path.join(workspace_projekt_einnahmen, "Entfernungsringe") if arcpy.Exists(pfad_Entfernungsringe): arcpy.Delete_management(pfad_Entfernungsringe) pfad_Herkunftsraeume = os.path.join(workspace_projekt_einnahmen, "Herkunftsgebiete") if arcpy.Exists(pfad_Herkunftsraeume): arcpy.Delete_management(pfad_Herkunftsraeume) pfad_Herkunftsraeume_mit_Ew = os.path.join(workspace_projekt_einnahmen, "Herkunftsgebiete_mit_Ew") if arcpy.Exists(pfad_Herkunftsraeume_mit_Ew): arcpy.Delete_management(pfad_Herkunftsraeume_mit_Ew) pfad_zensusgrid = self.folders.ZENSUS_RASTER_FILE pfad_bkggemeinden = self.folders.get_base_table( "FGDB_Basisdaten_deutschland.gdb", "bkg_gemeinden") #25km Buffer um Projektflaeche arcpy.Buffer_analysis(projektflaechen, pfad_buffer, "25000 Meters", "FULL", "ROUND", "ALL", "", "PLANAR") #Extent des Buffers auslesen desc = arcpy.Describe(pfad_buffer) xmin = desc.extent.XMin xmax = desc.extent.XMax ymin = desc.extent.YMin ymax = desc.extent.YMax #Verschneidung mit Zensusraster arcpy.Clip_management(pfad_zensusgrid, "%s %s %s %s" % (xmin, ymin, xmax, ymax), pfad_Rasterausschnitt, pfad_buffer, "2147483647", "ClippingGeometry", "NO_MAINTAIN_EXTENT") #Raterausschnitt in Punktlayer konvertieren arcpy.RasterToPoint_conversion(pfad_Rasterausschnitt, pfad_Rasterausschnitt_25km, "Value") #LeereSiedlungszellen entfernen arcpy.Select_analysis(pfad_Rasterausschnitt_25km, pfad_Punktlayer_25km_posWerte, '"grid_code" > 0') #Mehrere Buffer um Projektflaeche erzeugen arcpy.MultipleRingBuffer_analysis( projektflaechen, pfad_Entfernungsringe, "1500;2500;3500;4500;6500;8500;11500;14500;18500;25000", "Meters", "distance", "ALL", "FULL") #Buffer mit Gemeinden verschneiden arcpy.Intersect_analysis([pfad_bkggemeinden, pfad_Entfernungsringe], pfad_Herkunftsraeume, "NO_FID", "", "INPUT") #Verschneiden der Herkunftsraume mit den Summen der jeweiligen Punktfeatures fieldmappings = arcpy.FieldMappings() fieldmappings.addTable(pfad_Herkunftsraeume) fieldmappings.addTable(pfad_Punktlayer_25km_posWerte) gridcode_FieldIndex = fieldmappings.findFieldMapIndex("grid_code") fieldmap = fieldmappings.getFieldMap(gridcode_FieldIndex) field = fieldmap.outputField field.name = "Summe_Ew" field.aliasName = "Summe_Ew" fieldmap.outputField = field fieldmap.mergeRule = "sum" fieldmappings.replaceFieldMap(gridcode_FieldIndex, fieldmap) arcpy.SpatialJoin_analysis(pfad_Herkunftsraeume, pfad_Punktlayer_25km_posWerte, pfad_Herkunftsraeume_mit_Ew, "JOIN_ONE_TO_ONE", "KEEP_ALL", fieldmappings) #SvB_je_EW Summe_Wichtungsfaktoren_Gesamtraum_Wohnen = 0 Summe_Wichtungsfaktoren_Gesamtraum_Gewerbe = 0 Summe_Wichtungsfaktoren_Gemeinde_Wohnen = 0 Summe_Wichtungsfaktoren_Gemeinde_Gewerbe = 0 SvB_je_EW = 0 herkunftsraeume = [] cursor_gemeindebilanz = arcpy.da.SearchCursor(wanderungssalden, ["AGS", "SvB_pro_Ew"]) for gemeinde in cursor_gemeindebilanz: where = '"AGS"' + "='" + gemeinde[0] + "'" cursor_Summe_Ew = arcpy.da.SearchCursor( pfad_Herkunftsraeume_mit_Ew, ["AGS", "Summe_Ew", "distance", "Shape_Area"], where) for gemeindeteil in cursor_Summe_Ew: if gemeindeteil[1] >= 1: Wichtungsfaktor_Wohnen = gemeindeteil[1] * gemeindeteil[ 3] * Wichtungen_Wohnen[str(int(gemeindeteil[2]))] Wichtungsfaktor_Gewerbe = gemeindeteil[1] * gemeinde[ 1] * gemeindeteil[3] * Wichtungen_Gewerbe[str( int(gemeindeteil[2]))] herkunftsraeume.append([ gemeindeteil[0], Wichtungsfaktor_Wohnen, Wichtungsfaktor_Gewerbe ]) Summe_Wichtungsfaktoren_Gesamtraum_Wohnen += Wichtungsfaktor_Wohnen Summe_Wichtungsfaktoren_Gesamtraum_Gewerbe += Wichtungsfaktor_Gewerbe ap = 0 bewohner = 0 teilflaechen = self.folders.get_table("Teilflaechen_Plangebiet", "FGDB_Definition_Projekt.gdb") rahmendaten = self.folders.get_table("Projektrahmendaten", "FGDB_Definition_Projekt.gdb") cursor = arcpy.da.SearchCursor(rahmendaten, ["AGS"]) for row in cursor: ags_projekt = row[0] cursor = arcpy.da.SearchCursor(teilflaechen, ["ew", "AP_gesamt"]) for flaeche in cursor: ap += flaeche[1] bewohner += flaeche[0] #Aufteilung Fortzug (und Zuzug [nur Projektgemeinde]) cursor_gemeindebilanz = arcpy.da.UpdateCursor(wanderungssalden, [ "AGS", "SvB_pro_Ew", "Einw_Fortzug", "SvB_Fortzug", "Einw_Zuzug", "SvB_Zuzug", "SvB_Saldo", "Einw_Saldo", "Wanderungsanteil_Ew", "Wanderungsanteil_SvB" ]) for gemeinde in cursor_gemeindebilanz: Summe_Wichtungsfaktoren_Gemeinde_Wohnen = 0 Summe_Wichtungsfaktoren_Gemeinde_Gewerbe = 0 for raum in herkunftsraeume: if raum[0] == gemeinde[0]: Summe_Wichtungsfaktoren_Gemeinde_Wohnen += raum[1] Summe_Wichtungsfaktoren_Gemeinde_Gewerbe += raum[2] Einw_Fortzug_neu = -1 * (bewohner * Randsummen_Wohnen[1] * Summe_Wichtungsfaktoren_Gemeinde_Wohnen / Summe_Wichtungsfaktoren_Gesamtraum_Wohnen) if Einw_Fortzug_neu != 0: gemeinde[2] = Einw_Fortzug_neu # - 0.5 else: gemeinde[2] = Einw_Fortzug_neu SvB_Fortzug_neu = -1 * (ap * Randsummen_Gewerbe[1] * Summe_Wichtungsfaktoren_Gemeinde_Gewerbe / Summe_Wichtungsfaktoren_Gesamtraum_Gewerbe) if SvB_Fortzug_neu != 0: gemeinde[3] = SvB_Fortzug_neu # - 0.5 else: gemeinde[3] = SvB_Fortzug_neu if gemeinde[0] == ags_projekt: gemeinde[4] = bewohner gemeinde[5] = ap else: gemeinde[ 8] = Summe_Wichtungsfaktoren_Gemeinde_Wohnen / Summe_Wichtungsfaktoren_Gesamtraum_Wohnen gemeinde[ 9] = Summe_Wichtungsfaktoren_Gemeinde_Gewerbe / Summe_Wichtungsfaktoren_Gesamtraum_Gewerbe gemeinde[6] = gemeinde[3] + gemeinde[5] gemeinde[7] = gemeinde[4] + gemeinde[2] cursor_gemeindebilanz.updateRow(gemeinde) #Summe der zugeordneten Fortzüge (innerhalb 25 km) und Zuzüge [jeweils inkl. Rundungseffekte] Summe_Zugeordneter_Fortzug_Ew = 0.0 Summe_Zugeordneter_Zuzug_Ew = 0.0 Summe_Zugeordneter_Fortzug_AP = 0.0 Summe_Zugeordneter_Zuzug_AP = 0.0 cursor_summe = arcpy.da.SearchCursor(wanderungssalden, [ "AGS", "SvB_pro_Ew", "Einw_Fortzug", "SvB_Fortzug", "Einw_Zuzug", "SvB_Zuzug", "SvB_Saldo", "Einw_Saldo" ]) for gemeinde in cursor_summe: Summe_Zugeordneter_Fortzug_Ew += gemeinde[2] Summe_Zugeordneter_Zuzug_Ew += gemeinde[4] Summe_Zugeordneter_Fortzug_AP += gemeinde[3] Summe_Zugeordneter_Zuzug_AP += gemeinde[5] Differenz_Ew = Summe_Zugeordneter_Zuzug_Ew + Summe_Zugeordneter_Fortzug_Ew Differenz_AP = Summe_Zugeordneter_Zuzug_AP + Summe_Zugeordneter_Fortzug_AP #Neugruendungen (nur Gewerbe) Neugruendungen_AP = ap * Randsummen_Gewerbe[3] + 0.5 #Fortzüge aus dem restlichen Bundesgebiet/Welt (hier werden auch die Rundungsverluste ungebracht) Fortzuege_restliches_Bundesgebiet_und_Welt_Ew = -1 * Differenz_Ew Fortzuege_restliches_Bundesgebiet_und_Welt_AP = -1 * ( Differenz_AP - Neugruendungen_AP) #arcpy.AddMessage("Wohnen: Fortzüge restliches Bundesgebiet = {0}".format(Fortzuege_restliches_Bundesgebiet_und_Welt_Ew)) #arcpy.AddMessage("Gewerbe: Fortzüge restliches Bundesgebiet = {0}".format(Fortzuege_restliches_Bundesgebiet_und_Welt_AP)) #arcpy.AddMessage("Gewerbe: Neugründungen = {0}".format(Neugruendungen_AP)) self.parent_tbx.delete_rows_in_table("Zuzugsstatistik_Ew") column_values = { "Kategorie": [u"Projektgemeinde/Region", u"Restliches Bundesgebiet/Ausland"], "Anzahl": [ int(round(Summe_Zugeordneter_Fortzug_Ew * -1)), int(round(Differenz_Ew)) ] } self.parent_tbx.insert_rows_in_table("Zuzugsstatistik_Ew", column_values) self.parent_tbx.delete_rows_in_table("Zuzugsstatistik_SvB") column_values = { "Kategorie": [ u"Projektgemeinde/Region", u"Restliches Bundesgebiet/Ausland", u"Neugründungen" ], "Anzahl": [ int(round(Summe_Zugeordneter_Fortzug_AP * -1)), int(round((Differenz_AP - Neugruendungen_AP))), int(round(Neugruendungen_AP)) ] } self.parent_tbx.insert_rows_in_table("Zuzugsstatistik_SvB", column_values) c.set_chronicle( "Wanderung Einwohner", self.folders.get_table(tablename='Chronik_Nutzung', workspace="FGDB_Einnahmen.gdb", project=projektname)) c.set_chronicle( "Wanderung Beschaeftigte", self.folders.get_table(tablename='Chronik_Nutzung', workspace="FGDB_Einnahmen.gdb", project=projektname))
mxd1.saveACopy(outputclass + '/' + getvalue_XJQYMC + '.mxd') del cursor # 排序列表 namelist.sort() arcpy.env.workspace = bufferoutclass arcpy.AddMessage('设置缓冲区...') for aname in namelist: # 生成缓冲区 inFeatures = tempDB + '/' + aname outFeatureClass = bufferoutclass + '/' + aname distance = [30, 60, 90] bufferunit = 'meters' arcpy.MultipleRingBuffer_analysis(inFeatures, outFeatureClass, distance, bufferunit, '', '', 'OUTSIDE_ONLY') dellayer = arcpy.mapping.ListLayers(mxd1, '', dataframe1)[0] if not dellayer.name == 'XJQY': arcpy.mapping.RemoveLayer(dataframe1, dellayer) print 'buffer complete!' # 让刚刚生成的环形缓冲区文件替换个乡镇mxd中的'缓冲区'图层 # 读取生成的地图文档 # import arcpy,os # outputclass = u'G:\\南江县\\南江分布图\\输出地图文档' # bufferoutclass = u'G:\\南江县\\南江分布图\\缓冲区文件' # tempDB = u'中间处理暂存数据库.gdb' for newfile in os.listdir(outputclass): if newfile[-3:].lower() == 'mxd':
arcpy.Merge_management([Roads_Clipped, Trails_Clipped, pStreams_Clipped, Electric_Clipped], LineTrack,fms) arcpy.Delete_management(Roads_Clipped) arcpy.Delete_management(Trails_Clipped) arcpy.Delete_management(pStreams_Clipped) arcpy.Delete_management(Electric_Clipped) pDist=[] for x in Distances: pDist.append(round(x * mult,2)) arcpy.AddMessage(pDist) ##try: arcpy.MultipleRingBuffer_analysis(LineTrack, TrackBuffer, pDist, "Meters", "TRACKOFFSET", "ALL", "FULL") ## ##except: ## TrackBuf = TrackBuffer ## arcpy.AddMessage("Loop through the distances") ## for x in Distances: ## arcpy.AddMessage(str(x)) ## TrackBuffer = TrackBuf + str(x) ## dist = str(x) + ' Meters' ## arcpy.Buffer_analysis(LineTrack, TrackBuffer, dist, "", "", "ALL", "") arcpy.Delete_management(LineTrack) #Try to erase water polygon if user as Advanced license try:
The buffers are defined using a set of variable distances. The resulting feature class is added to the map beneath the input layer. """ import arcpy, os, sys """ Local Variables """ arcpy.env.workspace = arcpy.GetParameterAsText(0) # path to file geodatabase speed_hump_fc = r"SpeedHump\SpeedHumpAnalysis" # name of speed hump feature class buffer_fc = r"SpeedHumpBuffers" # name of buffer feature class distances = arcpy.GetParameter(1) # buffer distances unit = arcpy.GetParameterAsText(2) # distance unit of measurement try: """ Delete Previous Buffer Feature Class and Execute Multi Ring Buffer Tool """ arcpy.Delete_management(buffer_fc) arcpy.MultipleRingBuffer_analysis(speed_hump_fc, buffer_fc, distances, unit, "", "NONE") aprx = arcpy.mp.ArcGISProject("CURRENT") m = aprx.listMaps("Speed Hump")[0] ref_lyr = m.listLayers("SpeedHumpAnalysis")[0] buf_lyr = m.addDataFromPath(os.path.join(arcpy.env.workspace, buffer_fc)) m.moveLayer(ref_lyr, buf_lyr, "AFTER") arcpy.AddMessage("SUCCESS") except Exception as err: """ Error Handling """ arcpy.AddError(err) sys.exit(1)
# =============================================================== # Zonal statistics: calculte areas for protected areas # =============================================================== ## Creating buffers for Protected areas # Description: Create multiple buffers for the input features # Set local variables inFeatures = "cod_atlas_forestier_DBO_aires_protegees_diss" outFeatureClass = "drc_pa_buffers" distances = [-10000, 1, 10000] bufferUnit = "meters" print "Local variables set" ## Execute MultipleRingBuffer arcpy.MultipleRingBuffer_analysis(inFeatures, outFeatureClass, distances, bufferUnit, "", "ALL") print "Buffer execution successful" ## Execute AddField # Set local variables inTable = outFeatureClass fieldName = "Buff" fieldLength = 10 arcpy.AddField_management(inTable, fieldName, "TEXT", "", "", fieldLength) print "Field added for PA Buf" ## Execute CalculateField expression = "getClass(!distance!)" codeblock = """def getClass(ring): if ring == -10000: return 'Core'
nameSplit = shp.split('\\') ##Checking if it is shp or feature class if nameSplit[-1].split('.')[-1] == 'shp': featherName = nameSplit[-1].split('.')[0] + '_feather.shp' else: featherName = nameSplit[-1] + '_feather' ##Set local variables for feathering inFeatures = shp outFeatureClass = featherPath + '\\' + featherName bufferUnit = "meters" expression = '((100 * !distance!)/!lg_dist!)' # Execute MultipleRingBuffer arcpy.MultipleRingBuffer_analysis(inFeatures, outFeatureClass, distancesList, bufferUnit, "", "ALL", "OUTSIDE_ONLY") print '--------------------------' print '--------------------------' print '--------------------------' print '...adding field for symbology' arcpy.AddField_management(outFeatureClass, "Xpar", "SHORT", "", "", "", "", "", "NON_REQUIRED", "") arcpy.AddField_management(outFeatureClass, "lg_dist", "SHORT", "", "", "", "", "", "NON_REQUIRED", "") arcpy.CalculateField_management(outFeatureClass, "lg_dist", distancesList[-1], "PYTHON_9.3") arcpy.CalculateField_management(outFeatureClass, "Xpar", expression, "PYTHON_9.3") arcpy.DeleteField_management(outFeatureClass, ["lg_dist"])
def execute(self, params, messages): deleteInMemory() Limit = params[14].value strLimit = params[14].ValueAsText arcpy.AddMessage("Target Data Capture = " + strLimit) rawPath = os.path.dirname( params[1].valueAsText) + "\\" + os.path.basename( params[1].valueAsText) + "_Raw_Data" finalPath = os.path.dirname( params[1].valueAsText) + "\\" + os.path.basename( params[1].valueAsText) + "_Final_Data" if not os.path.exists(rawPath): os.mkdir(rawPath) if not os.path.exists(finalPath): os.mkdir(finalPath) poly = arcpy.MakeFeatureLayer_management(params[0].valueAsText) outRaw = rawPath + "\\" + os.path.basename(params[1].valueAsText) outFinal = finalPath + "\\" + os.path.basename(params[1].valueAsText) outMain = params[1].valueAsText arcpy.env.workspace = os.path.dirname(params[1].valueAsText) arcpy.env.scratchWorkspace = os.path.dirname(params[1].valueAsText) DEM = params[5].valueAsText Geology = arcpy.MakeFeatureLayer_management(params[7].valueAsText) geoField = params[8].valueAsText Soils = arcpy.MakeFeatureLayer_management(params[9].valueAsText) soilField = params[10].valueAsText Vegetation = arcpy.MakeFeatureLayer_management(params[11].valueAsText) vegField = params[12].valueAsText Streams = arcpy.MakeFeatureLayer_management(params[13].valueAsText) Sites = arcpy.MakeFeatureLayer_management(params[2].valueAsText) zFactor = params[6].value try: #Multipart Handling lyr = finalPath + "\\" + os.path.basename( params[1].valueAsText) + "_Poly.shp" polyParts = int(arcpy.GetCount_management(poly).getOutput(0)) if polyParts > 1: arcpy.Dissolve_management(poly, lyr) else: arcpy.CopyFeatures_management(poly, lyr) #Create and calcualte POLY_ACRES arcpy.AddField_management(lyr, "POLY_ACRES", 'DOUBLE', 12, 8) arcpy.CalculateField_management(lyr, "POLY_ACRES", "!shape.area@ACRES!", "PYTHON_9.3", "") Desc = arcpy.Describe(lyr) polyAcres = ([ row[0] for row in arcpy.da.SearchCursor(lyr, ["POLY_ACRES"]) ][0]) arcpy.AddMessage("Analysis area = " + str(polyAcres) + " acres") if polyAcres > 50000: arcpy.AddMessage("Target layer overlap will not be calculated") #Clip Sites siteField = params[3].valueAsText siteValue = params[4].valueAsText outPoints = outFinal + "_Data_Points.shp" outSites = outRaw + "_Sites" if siteValue == "ALL SITES": arcpy.MakeFeatureLayer_management(Sites, outSites) else: siteQuery = '"' + siteField + '"' + " = " + "'" + siteValue + "'" arcpy.MakeFeatureLayer_management(Sites, outSites, siteQuery) arcpy.SelectLayerByLocation_management(outSites, "INTERSECT", lyr) siteResult = int(arcpy.GetCount_management(outSites).getOutput(0)) arcpy.AddMessage(siteValue + " Site Count = " + str(siteResult)) if siteResult < 10: arcpy.AddMessage( "There are insufficient site data for analysis") deleteInMemory() SystemExit(0) siteDensity = str(siteResult / polyAcres) arcpy.AddMessage("Site density = " + siteDensity[0:5] + " sites/acre") if siteResult / polyAcres < 0.01: arcpy.AddMessage( "Site density is too low for reliable analysis (0.010 sites/acre minimum), use discretion when interpreting results" ) arcpy.FeatureToPoint_management(outSites, outPoints, "CENTROID") #Clip DEM, Calculate Slope and Aspect, Reclassify outDEM = outRaw + "_Dem" outSlope = outRaw + "_Slp" outAspect = outRaw + "_Asp" arcpy.AddMessage("Clipping DEM") arcpy.Clip_management(DEM, "#", "in_memory\\DEMClip", lyr, "#", "ClippingGeometry") arcpy.Reclassify_3d( "in_memory\\DEMClip", "VALUE", "0 100 100;100 200 200;200 300 300;300 400 400;400 500 500;500 600 600;600 700 700;700 800 800;800 900 900;900 1000 1000;1000 1100 1100;1100 1200 1200;1200 1300 1300;1300 1400 1400;1400 1500 1500;1500 1600 1600;1600 1700 1700;1700 1800 1800;1800 1900 1900;1900 2000 2000;2000 2100 2100;2100 2200 2200;2200 2300 2300;2300 2400 2400;2400 2500 2500;2500 2600 2600;2600 2700 2700;2700 2800 2800;2800 2900 2900;2900 3000 3000;3000 3100 3100;3100 3200 3200;3200 3300 3300;3300 3400 3400;3400 3500 3500;3500 3600 3600;3600 3700 3700;3700 3800 3800;3800 3900 3900;3900 4000 4000;4000 4100 4100;4100 4200 4200;4200 4300 4300;4300 4400 4400;4400 4500 4500;4500 4600 4600;4600 4700 4700;4700 4800 4800;4800 4900 4900;4900 5000 5000;5000 5100 5100;5100 5200 5200;5200 5300 5300;5300 5400 5400;5400 5500 5500;5500 5600 5600;5600 5700 5700;5700 5800 5800;5800 5900 5900;5900 6000 6000;6000 6100 6100;6100 6200 6200;6200 6300 6300;6300 6400 6400;6400 6500 6500;6500 6600 6600;6600 6700 6700;6700 6800 6800;6800 6900 6900;6900 7000 7000;7000 7100 7100;7100 7200 7200;7200 7300 7300;7300 7400 7400;7400 7500 7500;7500 7600 7600;7600 7700 7700;7700 7800 7800;7800 7900 7900;7900 8000 8000;8000 8100 8100;8100 8200 8200;8200 8300 8300;8300 8400 8400;8400 8500 8500;8500 8600 8600;8600 8700 8700;8700 8800 8800;8800 8900 8900;8900 9000 9000;9000 9100 9100;9100 9200 9200;9200 9300 9300;9300 9400 9400;9400 9500 9500;9500 9600 9600;9600 9700 9700;9700 9800 9800;9800 9900 9900;9900 10000 10000;10000 10100 10100;10100 10200 10200;10200 10300 10300;10300 10400 10400;10400 10500 10500;10500 10600 10600;10600 10700 10700;10700 10800 10800;10800 10900 10900;10900 11000 11000;11000 11100 11100;11100 11200 11200;11200 11300 11300;11300 11400 11400;11400 11500 11500;11500 11600 11600;11600 11700 11700;11700 11800 11800;11800 11900 11900;11900 12000 12000;12000 12100 12100;12100 12200 12200;12200 12300 12300;12300 12400 12400;12400 12500 12500;12500 12600 12600;12600 12700 12700;12700 12800 12800;12800 12900 12900;12900 13000 13000;13000 13100 13100;13100 13200 13200;13200 13300 13300;13300 13400 13400;13400 13500 13500;13500 13600 13600;13600 13700 13700;13700 13800 13800;13800 13900 13900;13900 14000 14000;14000 14100 14100;14100 14200 14200;14200 14300 14300;14300 14400 14400;14400 14500 14500;14500 14600 14600;14600 14700 14700;14700 14800 14800;14800 14900 14900;14900 15000 15000", outDEM) arcpy.AddMessage("Calculating Slope") arcpy.Slope_3d("in_memory\\DEMClip", "in_memory\\outSlope", "DEGREE", zFactor) arcpy.Reclassify_3d( "in_memory\\outSlope", "VALUE", "0 5 5;5 10 10;10 15 15;15 20 20;20 25 25;25 30 30;30 35 35;35 40 40;40 45 45;45 90 90", outSlope) arcpy.AddMessage("Calculating Aspect") arcpy.Aspect_3d("in_memory\\DEMClip", "in_memory\\outAspect") arcpy.Reclassify_3d( "in_memory\\outAspect", "VALUE", "-1 22.5 0;22.5 67.5 1;67.5 112.5 2;112.5 157.5 3;157.5 202.5 4;202.5 247.5 5;247.5 292.5 6;292.5 337.5 7;337.5 360 0", outAspect) #Clip Geology arcpy.AddMessage("Clipping Geology") outGeo = outRaw + "_Geo.shp" arcpy.Clip_analysis(Geology, lyr, "in_memory\\outGeo") arcpy.Dissolve_management("in_memory\\outGeo", outGeo, geoField) #Clip Soils arcpy.AddMessage("Clipping Soils") outSoils = outRaw + "_Soil.shp" arcpy.Clip_analysis(Soils, lyr, "in_memory\\outSoil") arcpy.Dissolve_management("in_memory\\outSoil", outSoils, soilField) #Clip Vegetation arcpy.AddMessage("Clipping Vegetation") outVeg = outRaw + "_Veg.shp" arcpy.Clip_analysis(Vegetation, lyr, "in_memory\\outVeg") arcpy.Dissolve_management("in_memory\\outVeg", outVeg, vegField) #Clip Streams arcpy.AddMessage("Clipping and Buffering Streams") outStr = outRaw + "_Str.shp" strLayer = arcpy.MakeFeatureLayer_management( Streams, "in_memory\\streams") arcpy.SelectLayerByLocation_management("in_memory\\streams", "INTERSECT", lyr, "", "NEW_SELECTION") streamResult = int( arcpy.GetCount_management("in_memory\\streams").getOutput(0)) if streamResult == 0: arcpy.AddMessage("There Are No Streams Within This Polygon") else: outStreams = outRaw + "_Str.shp" arcpy.Clip_analysis(Streams, lyr, "in_memory\\outStreams") arcpy.MultipleRingBuffer_analysis("in_memory\\outStreams", outStr, [200, 400, 600, 800, 1000], "meters") deleteInMemory() #DEM demTarget = outFinal + "_Elevation_Target.shp" demFinal = outRaw + "_DEM.shp" arcpy.AddMessage("Processing DEM") ExtractValuesToPoints(outPoints, outDEM, "in_memory\\pointDEM") arcpy.Frequency_analysis("in_memory\\pointDEM", "in_memory\\DEM_Table", "RASTERVALU") arcpy.Sort_management("in_memory\\DEM_Table", "in_memory\\DEM_Sort", [["FREQUENCY", "DESCENDING"]]) Vdem = 0 Xdem = 0 demList = [] with arcpy.da.SearchCursor("in_memory\\DEM_Sort", ["RASTERVALU", "FREQUENCY"]) as cursor: for row in cursor: if Xdem == 0: Vdem = row[1] demList.append(row[0]) else: Vdem = Vdem + row[1] demList.append(row[0]) if float(Vdem) / float(siteResult) < Limit: Xdem = Xdem + 1 else: break arcpy.RasterToPolygon_conversion(outDEM, demFinal, "SIMPLIFY", "VALUE") DEMdesc = arcpy.Describe(demFinal) fields = DEMdesc.fields for field in fields: if field.name == "GRIDCODE": arcpy.AddField_management(demFinal, "ELEV", field.type, field.precision, field.scale, field.length, "", "", "", "") with arcpy.da.UpdateCursor(demFinal, ["GRIDCODE", "ELEV"]) as cursor: for row in cursor: row[1] = row[0] cursor.updateRow(row) arcpy.DeleteField_management(demFinal, "GRIDCODE") qryList = [str(dem) for dem in demList] expr = "ELEV IN (" + ",".join(qryList) + ")" arcpy.MakeFeatureLayer_management(demFinal, "in_memory\\demTarget", expr) arcpy.Dissolve_management("in_memory\\demTarget", demTarget, "ELEV") #arcpy.Delete_management(outDEM) #SLOPE slopeTarget = outFinal + "_Slope_Target.shp" slopeFinal = outRaw + "_Slope.shp" arcpy.AddMessage("Processing Slope") ExtractValuesToPoints(outPoints, outSlope, "in_memory\\pointSlope") arcpy.Frequency_analysis("in_memory\\pointSlope", "in_memory\\Slope_Table", "RASTERVALU") arcpy.Sort_management("in_memory\\Slope_Table", "in_memory\\Slope_Sort", [["FREQUENCY", "DESCENDING"]]) Vslp = 0 Xslp = 0 slpList = [] with arcpy.da.SearchCursor("in_memory\\Slope_Sort", ["RASTERVALU", "FREQUENCY"]) as cursor: for row in cursor: if Xslp == 0: Vslp = row[1] slpList.append(row[0]) else: Vslp = Vslp + row[1] slpList.append(row[0]) if float(Vslp) / float(siteResult) < Limit: Xslp = Xslp + 1 else: break arcpy.RasterToPolygon_conversion(outSlope, slopeFinal, "SIMPLIFY", "VALUE") Slpdesc = arcpy.Describe(slopeFinal) fields = Slpdesc.fields for field in fields: if field.name == "GRIDCODE": arcpy.AddField_management(slopeFinal, "SLOPE", field.type, field.precision, field.scale, field.length, "", "", "", "") with arcpy.da.UpdateCursor( slopeFinal, ["GRIDCODE", "SLOPE"]) as cursor: for row in cursor: row[1] = row[0] cursor.updateRow(row) arcpy.DeleteField_management(slopeFinal, "GRIDCODE") qryList = [str(slp) for slp in slpList] expr = "SLOPE IN (" + ",".join(qryList) + ")" arcpy.MakeFeatureLayer_management(slopeFinal, "in_memory\\slopeTarget", expr) arcpy.Dissolve_management("in_memory\\slopeTarget", slopeTarget, "SLOPE") #arcpy.Delete_management(outSlope) #ASPECT aspectTarget = outFinal + "_Aspect_Target.shp" aspectFinal = outRaw + "_Aspect.shp" arcpy.AddMessage("Processing Aspect") ExtractValuesToPoints(outPoints, outAspect, "in_memory\\pointAspect") arcpy.Frequency_analysis("in_memory\\pointAspect", "in_memory\\aspect_Table", "RASTERVALU") arcpy.Sort_management("in_memory\\aspect_Table", "in_memory\\aspect_Sort", [["FREQUENCY", "DESCENDING"]]) Vasp = 0 Xasp = 0 aspList = [] with arcpy.da.SearchCursor("in_memory\\aspect_Sort", ["RASTERVALU", "FREQUENCY"]) as cursor: for row in cursor: if Xasp == 0: Vasp = row[1] aspList.append(row[0]) else: Vasp = Vasp + row[1] aspList.append(row[0]) if float(Vasp) / float(siteResult) < Limit: Xasp = Xasp + 1 else: break arcpy.RasterToPolygon_conversion(outAspect, aspectFinal, "SIMPLIFY", "VALUE") Aspdesc = arcpy.Describe(aspectFinal) fields = Aspdesc.fields for field in fields: if field.name == "GRIDCODE": arcpy.AddField_management(aspectFinal, "ASPECT", field.type, field.precision, field.scale, field.length, "", "", "", "") with arcpy.da.UpdateCursor( aspectFinal, ["GRIDCODE", "ASPECT"]) as cursor: for row in cursor: row[1] = row[0] cursor.updateRow(row) arcpy.DeleteField_management(aspectFinal, "GRIDCODE") qryList = [str(asp) for asp in aspList] expr = "ASPECT IN (" + ",".join(qryList) + ")" arcpy.MakeFeatureLayer_management(aspectFinal, "in_memory\\aspectTarget", expr) arcpy.Dissolve_management("in_memory\\aspectTarget", aspectTarget, "ASPECT") #arcpy.Delete_management(outAspect) #GEOLOGY GeoTarget = outFinal + "_Geology_Target.shp" arcpy.AddMessage("Processing Geology") arcpy.SpatialJoin_analysis(outPoints, outGeo, "in_memory\\pointGeo") arcpy.Frequency_analysis("in_memory\\pointGeo", "in_memory\\geo_Table", geoField) arcpy.Sort_management("in_memory\\geo_Table", "in_memory\\geo_Sort", [["FREQUENCY", "DESCENDING"]]) Vgeo = 0 Xgeo = 0 geoList = [] with arcpy.da.SearchCursor("in_memory\\geo_Sort", [geoField, "FREQUENCY"]) as cursor: for row in cursor: if Xgeo == 0: Vgeo = row[1] geoList.append(row[0]) else: Vgeo = Vgeo + row[1] geoList.append(row[0]) if float(Vgeo) / float(siteResult) < Limit: Xgeo = Xgeo + 1 else: break qryList = ["'" + geo + "'" for geo in geoList] expr = '"' + geoField + '"' + " IN (" + ",".join(qryList) + ")" arcpy.MakeFeatureLayer_management(outGeo, "in_memory\\geoTarget", expr) GEOdesc = arcpy.Describe("in_memory\\geoTarget") fields = GEOdesc.fields for field in fields: if field.name == geoField: arcpy.AddField_management("in_memory\\geoTarget", "GEO_TYPE", field.type, field.precision, field.scale, field.length, "", "", "", "") with arcpy.da.UpdateCursor( "in_memory\\geoTarget", [geoField, "GEO_TYPE"]) as cursor: for row in cursor: row[1] = row[0] cursor.updateRow(row) arcpy.Dissolve_management("in_memory\\geoTarget", GeoTarget, "GEO_TYPE") #SOILS SoilTarget = outFinal + "_Soil_Target.shp" arcpy.AddMessage("Processing Soils") arcpy.SpatialJoin_analysis(outPoints, outSoils, "in_memory\\pointSoil") arcpy.Frequency_analysis("in_memory\\pointSoil", "in_memory\\soil_Table", soilField) arcpy.Sort_management("in_memory\\soil_Table", "in_memory\\soil_Sort", [["FREQUENCY", "DESCENDING"]]) Vsoil = 0 Xsoil = 0 soilList = [] with arcpy.da.SearchCursor("in_memory\\soil_Sort", [soilField, "FREQUENCY"]) as cursor: for row in cursor: if Xsoil == 0: Vsoil = row[1] soilList.append(row[0]) else: Vsoil = Vsoil + row[1] soilList.append(row[0]) if float(Vsoil) / float(siteResult) < Limit: Xsoil = Xsoil + 1 else: break qryList = ["'" + soil + "'" for soil in soilList] expr = '"' + soilField + '"' + " IN (" + ",".join(qryList) + ")" arcpy.MakeFeatureLayer_management(outSoils, "in_memory\\soilTarget", expr) SOILdesc = arcpy.Describe("in_memory\\soilTarget") fields = SOILdesc.fields for field in fields: if field.name == soilField: arcpy.AddField_management("in_memory\\soilTarget", "SOIL_TYPE", field.type, field.precision, field.scale, field.length, "", "", "", "") with arcpy.da.UpdateCursor( "in_memory\\soilTarget", [soilField, "SOIL_TYPE"]) as cursor: for row in cursor: row[1] = row[0] cursor.updateRow(row) arcpy.Dissolve_management("in_memory\\soilTarget", SoilTarget, "SOIL_TYPE") #VEGETATION VegTarget = outFinal + "_Veg_Target.shp" arcpy.AddMessage("Processing Vegetation") arcpy.SpatialJoin_analysis(outPoints, outVeg, "in_memory\\pointVeg") arcpy.Frequency_analysis("in_memory\\pointVeg", "in_memory\\veg_Table", vegField) arcpy.Sort_management("in_memory\\veg_Table", "in_memory\\veg_Sort", [["FREQUENCY", "DESCENDING"]]) Vveg = 0 Xveg = 0 vegList = [] with arcpy.da.SearchCursor("in_memory\\veg_Sort", [vegField, "FREQUENCY"]) as cursor: for row in cursor: if Xveg == 0: Vveg = row[1] vegList.append(row[0]) else: Vveg = Vveg + row[1] vegList.append(row[0]) if float(Vveg) / float(siteResult) < Limit: Xveg = Xveg + 1 else: break qryList = ["'" + veg + "'" for veg in vegList] expr = '"' + vegField + '"' + " IN (" + ",".join(qryList) + ")" arcpy.MakeFeatureLayer_management(outVeg, "in_memory\\vegTarget", expr) VEGdesc = arcpy.Describe("in_memory\\vegTarget") fields = VEGdesc.fields for field in fields: if field.name == vegField: arcpy.AddField_management("in_memory\\vegTarget", "VEG_TYPE", field.type, field.precision, field.scale, field.length, "", "", "", "") with arcpy.da.UpdateCursor( "in_memory\\vegTarget", [vegField, "VEG_TYPE"]) as cursor: for row in cursor: row[1] = row[0] cursor.updateRow(row) arcpy.Dissolve_management("in_memory\\vegTarget", VegTarget, "VEG_TYPE") #WATER StreamTarget = outFinal + "_Water_Dist_Target.shp" arcpy.AddMessage("Processing Streams") if not streamResult == 0: arcpy.SpatialJoin_analysis(outPoints, outStreams, "in_memory\\pointStream") arcpy.Frequency_analysis("in_memory\\pointStream", "in_memory\\stream_Table", "distance") arcpy.Sort_management("in_memory\\stream_Table", "in_memory\\stream_Sort", [["FREQUENCY", "DESCENDING"]]) Vstr = 0 Xstr = 0 streamList = [] with arcpy.da.SearchCursor( "in_memory\\stream_Sort", ["distance", "FREQUENCY"]) as cursor: for row in cursor: if Xstr == 0: Vstr = row[1] streamList.append(row[0]) else: Vstr = Vstr + row[1] streamList.append(row[0]) if float(Vstr) / float(siteResult) < Limit: Xstr = Xstr + 1 else: break qryList = [str(stream) for stream in streamList] expr = "distance IN (" + ",".join(qryList) + ")" arcpy.MakeFeatureLayer_management(outStreams, "in_memory\\streamTarget", expr) strDesc = arcpy.Describe("in_memory\\streamTarget") fields = strDesc.fields for field in fields: if field.name == "distance": arcpy.AddField_management("in_memory\\streamTarget", "WAT_DIST", field.type, field.precision, field.scale, field.length, "", "", "", "") with arcpy.da.UpdateCursor( "in_memory\\streamTarget", ["distance", "WAT_DIST"]) as cursor: for row in cursor: row[1] = row[0] cursor.updateRow(row) arcpy.Dissolve_management("in_memory\\streamTarget", StreamTarget, "WAT_DIST") #Overlay and count overlaps if params[15].value == 1 and polyAcres < 50000: arcpy.AddMessage("Calculating target layer overlap") layerList = [ demTarget, slopeTarget, aspectTarget, GeoTarget, SoilTarget, VegTarget, StreamTarget ] existsList = [] for layer in layerList: if arcpy.Exists(layer): existsList.append(layer) outMerge = outFinal + "_Merge.shp" outFtoLine = outFinal + "_FtoLine.shp" outFtoPoly = outFinal + "_FtoPoly.shp" outFtoPoint = outFinal + "_FtoPoint.shp" outJoin1 = outFinal + "_Join1.shp" outDiss1 = outFinal + "_Diss1.shp" outJoin2 = outFinal + "_Join2.shp" outDiss2 = outFinal + "_Diss2.shp" rankPoly = outFinal + "_Rank_Poly.shp" arcpy.Merge_management(existsList, outMerge) arcpy.FeatureToLine_management(outMerge, outFtoLine) arcpy.FeatureToPolygon_management(outFtoLine, outFtoPoly, "#", "NO_ATTRIBUTES", "#") arcpy.FeatureToPoint_management(outFtoPoly, outFtoPoint, "INSIDE") arcpy.SpatialJoin_analysis(outFtoPoint, outMerge, outJoin1, "JOIN_ONE_TO_MANY", "KEEP_ALL", "#", "INTERSECT", "#", "#") arcpy.Dissolve_management(outJoin1, outDiss1, "TARGET_FID", "Join_Count SUM", "MULTI_PART", "DISSOLVE_LINES") arcpy.SpatialJoin_analysis(outFtoPoly, outDiss1, outJoin2, "JOIN_ONE_TO_ONE", "KEEP_ALL", "#", "INTERSECT", "#", "#") rankDesc = arcpy.Describe(outJoin2) fields = rankDesc.fields for field in fields: if field.name == "SUM_Join_C": arcpy.AddField_management(outJoin2, "OVERLAP", field.type, field.precision, field.scale, field.length, "", "", "", "") with arcpy.da.UpdateCursor( outJoin2, ["SUM_Join_C", "OVERLAP"]) as cursor: for row in cursor: row[1] = row[0] cursor.updateRow(row) arcpy.Dissolve_management(outJoin2, outDiss2, "OVERLAP", "#", "MULTI_PART", "DISSOLVE_LINES") arcpy.Clip_analysis(outDiss2, lyr, rankPoly) delList = [ outMerge, outFtoLine, outFtoPoly, outFtoPoint, outJoin1, outDiss1, outJoin2, outDiss2 ] for item in delList: arcpy.Delete_management(item) finally: delList2 = [] for item in delList2: arcpy.Delete_management(item) deleteInMemory() return
) newfcs = arcpy.ListFeatureClasses() print("Feature classes contained in Vector_Inputs_NAD83.gdb:\n %s" % (newfcs)) # Merge TRI and Superfund feature classes and then buffer print( "Merging Superfund sites and toxic release sites into Hazardous_Sites") sfundking = "King_County_Superfund_Sites" toxking = "King_County_Toxic_Release_Inventory" outsites = "Hazardous_Sites" arcpy.Merge_management([sfundking, toxking], outsites, "", "ADD_SOURCE_INFO") print("Merge complete") # Create multiring buffer from Hazardous_Sites feature class arcpy.MultipleRingBuffer_analysis(outsites, "Hazardous_Buffers", [1, 2, 3, 4], "kilometers", "", "ALL") # Adding field to calculate minority in census feature class #-----------------------HERE---------------------------------- arcpy.env.workspace = "C:/GIS_Projects/420/Quarterman_ENVS420_Lab4/Vector_Inputs/Vector_Inputs_NAD83.gdb" census = "C:/GIS_Projects/420/Quarterman_ENVS420_Lab4/Vector_Inputs/Vector_Inputs_NAD83.gdb/King_County_2016_Census_Tracts" print("Adding and calculating field for minority population") arcpy.AddField_management('King_County_2016_Census_Tracts', "Minority", "LONG", "", "", "", "", "", "") arcpy.CalculateField_management(census, "Minority", "!total_pop! - !NHWA!", "PYTHON3", "") # Add and calculate poverty field print( "Adding and calculating field for total population with income less than twice the poverty line" ) arcpy.AddField_management('King_County_2016_Census_Tracts', "Poverty",
def execute(self, parameters, messages): """The source code of the tool.""" # local variables and env arcpy.CreateFileGDB_management("E:/gina/poker/gdb", parameters[0].valueAsText) arcpy.env.workspace = "E:/gina/poker/gdb/" + parameters[ 0].valueAsText + ".gdb" arcpy.env.overwriteOutput = True adnr_lo_shp = "E:/gina/poker/shp/wip/land_ownership_data/adnr_gls_dls_merge_20170823_v1.shp" pfrr_popn_places = "E:/gina/poker/shp/wip/popn_places_data/pokerflat_popn_places_gcs_wgs84_to_akalbers_2.shp" afs_known_sites = "E:/gina/poker/shp/asf_data/asf_known_sites_20180629_3338.shp" pipTable = "E:/gina/poker/dbf/predicted_impact_xy.dbf" pip_point_shp = "E:/gina/poker/pip/pip_point.shp" pip_point_3338 = "E:/gina/poker/pip/pip_point_3338.shp" pip_buffer_shp = "E:/gina/poker/pip/pip_buffer.shp" pip_range_rings_shp = "E:/gina/poker/pip/pip_range_rings.shp" pip_lo_in_buffer_shp = "E:/gina/poker/pip/pip_lo_in_buffer.shp" pip_lo_in_buf_sum_dbf = "E:/gina/poker/pip/pip_lo_in_buf_sum.dbf" pip_lo_in_buf_sum_csv = "E:/gina/poker/pip/pip_lo_in_buf_sum.csv" pip_popn_places_in_buffer_shp = "E:/gina/poker/pip/pip_popn_places_in_buffer.shp" pip_known_sites_in_buffer_shp = "E:/gina/poker/pip/pip_known_sites_in_buffer.shp" x = parameters[2].valueAsText y = parameters[3].valueAsText r = parameters[10].valueAsText + " NauticalMiles" rr1 = (float(parameters[10].valueAsText)) / 3 rr2 = (rr1 * 2) rrs = str(rr1) + ";" + str(rr2) + ";" + r.split(" ")[0] pipLayer = "pipLayer1" srs = arcpy.SpatialReference("Alaska Albers Equal Area Conic") intersect_fc1 = [adnr_lo_shp, pip_buffer_shp] intersect_fc2 = [pfrr_popn_places, pip_buffer_shp] intersect_fc3 = [afs_known_sites, pip_buffer_shp] mxd = arcpy.mapping.MapDocument("current") dataframe = arcpy.mapping.ListDataFrames(mxd)[0] sourceLoSymbologyLayer = arcpy.mapping.Layer( "E:/gina/poker/lyr/lo2.lyr") sourcePipSymbologyLayer = arcpy.mapping.Layer( "E:/gina/poker/lyr/pip2.lyr") sourceRrsSymbologyLayer = arcpy.mapping.Layer( "E:/gina/poker/lyr/rrs.lyr") sourcePopSymbologyLayer = arcpy.mapping.Layer( "E:/gina/poker/lyr/pop.lyr") sourceAfsSymbologyLayer = arcpy.mapping.Layer( "E:/gina/poker/lyr/afs2.lyr") # Process: Calculate Lon Field arcpy.CalculateField_management(pipTable, "Lon", x, "PYTHON", "") # Process: Calculate Lat Field arcpy.CalculateField_management(pipTable, "Lat", y, "PYTHON", "") # Process: Make XY Event Layer arcpy.MakeXYEventLayer_management( pipTable, "Lon", "Lat", pipLayer, "GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]];-400 -400 1000000000;-100000 10000;-100000 10000;8.98315284119522E-09;0.001;0.001;IsHighPrecision", "") # Process: Copy Features arcpy.CopyFeatures_management(pipLayer, pip_point_shp, "", "0", "0", "0") # Process: Project pip point arcpy.Project_management(pip_point_shp, pip_point_3338, srs) # Process: Buffer pip point arcpy.Buffer_analysis(pip_point_3338, pip_buffer_shp, r, "FULL", "ROUND", "NONE", "", "PLANAR") # Process: Multiple Ring Buffer arcpy.MultipleRingBuffer_analysis(pip_point_3338, pip_range_rings_shp, rrs, "NauticalMiles", "", "NONE", "FULL") # Process: Intersect pip buffer with land ownership arcpy.Intersect_analysis(intersect_fc1, pip_lo_in_buffer_shp, "ALL", "", "INPUT") # Process: Intersect pip buffer with popn places arcpy.Intersect_analysis(intersect_fc2, pip_popn_places_in_buffer_shp, "ALL", "", "INPUT") # Process: Intersect pip buffer with afs known sites arcpy.Intersect_analysis(intersect_fc3, pip_known_sites_in_buffer_shp, "ALL", "", "INPUT") # Process: Make feature layers and add to the map ## pip feature class list fclist = arcpy.ListFeatureClasses() ## pip layer arcpy.MakeFeatureLayer_management(pip_point_3338, "Predicted Impact Point") ## land ownership layer arcpy.MakeFeatureLayer_management( pip_lo_in_buffer_shp, "Land Ownership within 3sigma of Predicted Impact Point") ## Range Rings arcpy.MakeFeatureLayer_management(pip_range_rings_shp, "Range Rings") ## populated places layer popn_places_records = int( arcpy.GetCount_management(pip_popn_places_in_buffer_shp).getOutput( 0)) if popn_places_records > 0: arcpy.MakeFeatureLayer_management( pip_popn_places_in_buffer_shp, "Populated Places within 3sigma of Predicted Impact Point") addPipPopnPlacesLayer = arcpy.mapping.Layer( "Populated Places within 3sigma of Predicted Impact Point") arcpy.mapping.AddLayer(dataframe, addPipPopnPlacesLayer) ## known sites layer known_sites_records = int( arcpy.GetCount_management(pip_known_sites_in_buffer_shp).getOutput( 0)) if known_sites_records > 0: arcpy.MakeFeatureLayer_management( pip_known_sites_in_buffer_shp, "AFS Known Sites within 3sigma of Predicted Impact Point") addPipKnownSitesLayer = arcpy.mapping.Layer( "AFS Known Sites within 3sigma of Predicted Impact Point") arcpy.mapping.AddLayer(dataframe, addPipKnownSitesLayer) addPipPointLayer = arcpy.mapping.Layer("Predicted Impact Point") arcpy.mapping.AddLayer(dataframe, addPipPointLayer) add3sigmaLoLayer = arcpy.mapping.Layer( "Land Ownership within 3sigma of Predicted Impact Point") arcpy.mapping.AddLayer(dataframe, add3sigmaLoLayer) addRangeRings = arcpy.mapping.Layer("Range Rings") arcpy.mapping.AddLayer(dataframe, addRangeRings) # Add and calc Acres field for intersected Land Ownership arcpy.AddField_management(pip_lo_in_buffer_shp, "Acres", "DOUBLE") arcpy.CalculateField_management(pip_lo_in_buffer_shp, "Acres", "!shape.area@acres!", "PYTHON_9.3", "") # Summarize intersected Land Ownership by Owner and total Acres arcpy.Statistics_analysis(pip_lo_in_buffer_shp, pip_lo_in_buf_sum_dbf, "Acres SUM", "OWNER") arcpy.MakeTableView_management(pip_lo_in_buf_sum_dbf) add3sigmaLoSumTbl = arcpy.mapping.TableView(pip_lo_in_buf_sum_dbf) arcpy.mapping.AddTableView(dataframe, add3sigmaLoSumTbl) # Symbolize and Refresh lo_layer = arcpy.mapping.ListLayers( mxd, "*Land Ownership within 3sigma of Predicted Impact Point*", dataframe)[0] arcpy.mapping.UpdateLayer(dataframe, lo_layer, sourceLoSymbologyLayer, True) lo_layer.symbology.addAllValues() pip_layer = arcpy.mapping.ListLayers(mxd, "*Predicted Impact Point*", dataframe)[0] arcpy.mapping.UpdateLayer(dataframe, pip_layer, sourcePipSymbologyLayer, True) rr_layer = arcpy.mapping.ListLayers(mxd, "*Range Rings*", dataframe)[0] arcpy.mapping.UpdateLayer(dataframe, rr_layer, sourceRrsSymbologyLayer, True) pop_layer = arcpy.mapping.ListLayers(mxd, "*Populated Places*", dataframe)[0] arcpy.mapping.UpdateLayer(dataframe, pop_layer, sourcePopSymbologyLayer, True) afs_layer = arcpy.mapping.ListLayers(mxd, "*Known Sites*", dataframe)[0] arcpy.mapping.UpdateLayer(dataframe, afs_layer, sourceAfsSymbologyLayer, True) arcpy.RefreshTOC() arcpy.RefreshActiveView() # Populate Mission GDB mission_layers = [ pip_point_3338, pip_lo_in_buffer_shp, pip_popn_places_in_buffer_shp, pip_range_rings_shp, pip_known_sites_in_buffer_shp ] arcpy.FeatureClassToGeodatabase_conversion(mission_layers, arcpy.env.workspace) return
fieldAlias2 = "Area (Acres)" fieldAlias4 = "Subject Category" expression2 = "int(!shape.area@acres!)" pDist = [] for x in Distances: pDist.append(round(x * mult, 2)) arcpy.AddMessage("Units = {}".format(bufferUnit)) arcpy.AddMessage(pDist) while row: # you need to insert correct field names in your getvalue function arcpy.MultipleRingBuffer_analysis( fc3, inFeatures, pDist, bufferUnit, "DistFrmIPP") #, dissolve_option, "FULL") row = rows.next() del rows del row del where arcpy.AddMessage('Completed multi-ring buffer') arcpy.AddField_management(inFeatures, fieldName1, "TEXT", "", "", "25", fieldAlias1, "NULLABLE", "", "PrtRange") arcpy.AddField_management(inFeatures, fieldName2, "DOUBLE", "", "", "", fieldAlias2, "NULLABLE") arcpy.AddField_management(inFeatures, fieldName3, "DOUBLE", "", "", "", fieldAlias3, "NULLABLE")
from arcpy import env import time arcpy.env.overwriteOutput = True env.workspace = 'B:\\Breech_Methodology\\Final_Breachdatabase.gdb' filework = 'B:\\Breech_Methodology\\Final_Breachdatabase.gdb' proposed_run = 'B:\\Breech_Methodology\\Final_Breachdatabase.gdb\\NTLLS_NPWS_2017_proposed_FINAL' actual_run = 'B:\\Breech_Methodology\\Final_Breachdatabase.gdb\\Actual_Completed_run_2017' arcpy.Delete_management('in_memory') Buffer_output = 'B:\\Breech_Methodology\\Final_Breachdatabase.gdb\\Buffers\\Buffer_multiring' Buffer_distance = [10, 25, 50, 100] Buffer_unit = 'meters' Field_name = 'Distance_M' Dissolve_option = 'ALL' start = time.time() arcpy.MultipleRingBuffer_analysis(proposed_run, 'in_memory', Buffer_distance, Buffer_unit, Field_name, "", "") arcpy.Dissolve_management('in_memory', Buffer_output, Field_name) print('Time: ' + str(time.time() - start)) # def Buffer(Input, Output, BufferLength): # return arcpy.Buffer_analysis(Input, Output, BufferLength, 'FULL', 'ROUND', 'ALL') # Buffer(proposed_run, buffer_10, Buffer_10width) # Buffer(proposed_run, buffer_25, Buffer_25width) # Buffer(proposed_run, buffer_50, Buffer_50width) # Buffer(proposed_run, buffer_100, Buffer_100width) # clip_output = 'B:\\Breech_Methodology\\Final_Breachdatabase.gdb\\Clip' # clip10 = clip_output + '\\Clip10' # clip25 = clip_output + '\\Clip25' # clip50 = clip_output + '\\Clip50'
import arcpy try: arcpy.env.workspace = r'c:\ArcpyBook\data' vTab = arcpy.ValueTable() vTab.setRow(0, "5") vTab.setRow(1, "10") vTab.setRow(2, "20") inFeature = 'Hospitals.shp' outFeature = 'HospitalMBuff.shp' dist = vTab bufferUnit = "meters" arcpy.MultipleRingBuffer_analysis(inFeature, outFeature, dist, bufferUnit, '', 'ALL') print("Multi-Ring Buffer Complete") except Exception as e: print(e.message)