def calcVS(unsnfltpts, bldg_veg_mask, ct, datapath): """ Calculates the cumulative viewshed from remaining unseen flight points. Generates Euclidean distance to mean center table. :param unsnfltpts: List of remaining unseen flight points :param bldg_veg_mask: Binary mask to remove invalid observer surfaces from cumulative VS raster :param ct: Pass number :param datapath: Path to input/output directory """ print('Calculating cumulative viewshed for {} unseen flight points...'. format(len(unsnfltpts))) # Make chunks of flight points usfp_chunks = makechunks(unsnfltpts, 500) print('Flight point chunks generated') print(len(chunk) for chunk in usfp_chunks) chunk_sums = [] chunkpass = 1 # Sum each chunk of single viewshed rasters for chunk in usfp_chunks: print('Chunksum operation {} on {} flight points...'.format( chunkpass, len(chunk))) # Set null values equal to 0 to avoid NoData holes chunkgen = (Con(IsNull(arcpy.Raster(datapath + "vs_" + str(usfp))), 0, 1) for usfp in chunk) chunkstats = arcpy.sa.CellStatistics(chunkgen, 'SUM', 'NODATA') chunk_sums.append((chunkstats)) print('...Done.') chunkpass += 1 # Sum chunks sumrast = arcpy.sa.CellStatistics(chunk_sums, 'SUM', 'NODATA') sumrast.save(datapath + "vs_pass_" + str(ct) + "_unmasked") print('Unmasked cumulative viewshed saved.') # mask out buildings and vegetation # set Bldg_Veg_Mask cells to 0 unmasked = arcpy.Raster(datapath + "vs_pass_" + str(ct) + "_unmasked") cumulative_masked = unmasked * bldg_veg_mask print('Invalid observer surfaces masked.') # set 0 value cells to Null cumulative_masked = SetNull(cumulative_masked == 0, cumulative_masked) print('Setting null values.') # save to .GDB as cumulative raster cumulative_masked.save(datapath + "vs_pass_" + str(ct)) print('Masked cumulative viewshed saved.') # Convert raster to points with number views for VS pass and X Y location vs_total_pts_ = datapath + "vs_pass_" + str(ct) + "_pts" arcpy.RasterToPoint_conversion(cumulative_masked, vs_total_pts_) arcpy.AddGeometryAttributes_management(vs_total_pts_, ['POINT_X_Y_Z_M']) print('Viewshed points for pass {} generated'.format(ct)) # Find mean center of cumulative viewshed for pass, save as feature class vs_center_ = datapath + "vs_pass_" + str(ct) + "_cntr" arcpy.MeanCenter_stats(vs_total_pts_, vs_center_) print('Mean center calculated.') # Calculate distance of each observation from centroid of observer masspoints vs_dist_ = datapath + "vs_pass_" + str(ct) + "_dist" arcpy.PointDistance_analysis(vs_total_pts_, vs_center_, vs_dist_) print('Observer distances table calculated.')
def getDistanceToOthers(curNdx): arcpy.AddMessage("\tCalculating distances...") arcpy.FeatureClassToFeatureClass_conversion(centroids, arcpy.env.workspace, curPoint, '"FID" = {ndx}' .format(ndx = curNdx)) arcpy.PointDistance_analysis(curPoint, centroids, distance) toDistance = [] dists = arcpy.da.SearchCursor(distance, ["NEAR_FID","DISTANCE"]) for row in dists: if parcelDict[row[0]][0] == 0: toDistance.append([row[1], row[0]]) toDistance.sort() return toDistance
def countObservationsWithinDistance(fcPoint, distance, distanceUnit, geodatabase="assignment2.gdb"): import arcpy import os arcpy.env.workspace = geodatabase arcpy.env.overwriteOutput = True #check the existence of a projected coordinate system if arcpy.Describe(fcPoint).spatialReference.PCSCode == 0: print('WARNING: the projection is a geographic coordinate system.') #Generate point distance table in the given unit and the given distance threshold pointDistance = arcpy.PointDistance_analysis( fcPoint, fcPoint, 'PointDis', str(distance) + " " + distanceUnit) #create a list in the length of "fcPoint" and store the count of each point in the list length = int(arcpy.GetCount_management(fcPoint).getOutput(0)) countList = [0] * length searchcursor = arcpy.da.SearchCursor(pointDistance, ['INPUT_FID']) for row in searchcursor: countList[row[0] - 1] = countList[row[0] - 1] + 1 del row del searchcursor #Append the countlist to the attribute table fieldname = 'countOfPoints' arcpy.AddField_management(fcPoint, fieldname, 'SHORT') updatecursor = arcpy.da.UpdateCursor(fcPoint, [fieldname]) i = 0 for row in updatecursor: row[0] = countList[i] updatecursor.updateRow(row) i = i + 1 del row del updatecursor
def getDistanceToOthers(curNdx): #curPoint ="V:\erabrahams\\test_files\RANDOM.shp" #arcpy.AddMessage("CurNdx = {x}" .format(x = curNdx)) arcpy.FeatureClassToFeatureClass_conversion( centroids, arcpy.env.workspace, curPoint, 'FID = {ndx}'.format(ndx=curNdx)) #row = arcpy.da.SearchCursor(curPoint, ["ORIG_FID", "TOTAL"]) #for val in row: # arcpy.AddMessage("Val = " + str(val[0]) + " " + str(val[1])) arcpy.PointDistance_analysis(curPoint, centroids, distance) toDistance = [] dists = arcpy.da.SearchCursor(distance, ["NEAR_FID", "DISTANCE"]) for row in dists: if parcelDict[row[0]][0] == 0: toDistance.append([row[1], row[0]]) toDistance.sort() return toDistance
arcpy.JoinField_management(inventory_layer_CopyFeatures__4_, "AREA", access_points, "AREA", "DIST_MILES") # Process: Add Field (DISTANCE_FINAL) arcpy.AddField_management(inventory_layer_CopyFeatures, "DISTANCE_FINAL", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") # Process: Calculate Field arcpy.CalculateField_management(inventory_layer_CopyFeatures__5_, "DISTANCE_FINAL", "[DIST_MILES]+[DISTANCE]/1609.344 ", "VB", "") # Process: Erase arcpy.Erase_analysis(Inventory_Features, inventory_layer_CopyFeatures__6_, fbks_stands_Erase, "") # Process: Feature To Point arcpy.FeatureToPoint_management(fbks_stands_Erase, inventory_layer_not_accessible_areas_centroid, "CENTROID") # Process: Point Distance arcpy.PointDistance_analysis(inventory_layer_not_accessible_areas_centroid, Destination_Feature, distance_not_accessible, "") # Process: Join Field arcpy.JoinField_management(fbks_stands_Erase, "OBJECTID", distance_not_accessible, "INPUT_FID", "DISTANCE") # Process: Add Field 2 - DISTANCE_FINAL arcpy.AddField_management(inventory_layer_not_accessible_areas__3_, "DISTANCE_FINAL", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") # Process: Collect Values (5) arcpy.CollectValues_mb("10") # Process: Summary Statistics arcpy.Statistics_analysis(inventory_layer_access, statisticssum, "DISTANCE_FINAL MAX", "") # Process: Get Field Value arcpy.GetFieldValue_mb(statisticssum, "MAX_DISTANCE_FINAL", "Double", "0")
################################################ #--Berechnung--# ################################################ for Bezug in Bezuege: if Bezug[2] != "_100": continue for Gelegenheiten in Ziele: Tabelle_E = Gelegenheiten[2] + "_NMIV" + Bezug[2] print Tabelle_E Ziel = Gelegenheiten[0] Raster = Bezug[0] ##--calculation of connections--## Lines = arcpy.PointDistance_analysis(Raster, Ziel, "C:" + f[0] + "Default.gdb/test", 11830) Lines_tab = arcpy.da.FeatureClassToNumPyArray( Lines, ["OBJECTID", "INPUT_FID", "NEAR_FID", "DISTANCE"]) Lines_tab = pandas.DataFrame(Lines_tab) try: arcpy.Delete_management("C:" + f[0] + "Default.gdb\\test") except: pass # field_ziel = [f.name for f in arcpy.ListFields(Ziel)] Ziel_tab = pandas.DataFrame( arcpy.da.FeatureClassToNumPyArray(Ziel, ["OBJECTID", "ID"])) Raster_tab = pandas.DataFrame( arcpy.da.FeatureClassToNumPyArray(Raster, ["OBJECTID", Bezug[1]]))
centroidRaster = sa.ZonalGeometry(patchRaster, "VALUE", "CENTROID") arcpy.RasterToPoint_conversion(centroidRaster, patchCentroids) # Save the centroids, if requested if saveCentroids == 'true': msg("Centroids will be saved to %s" % centroidFC) arcpy.CopyFeatures_management(patchCentroids, centroidFC) arcpy.AddField_management(centroidFC, "PatchID", "LONG", 10) arcpy.CalculateField_management(centroidFC, "PatchID", "[grid_code]") arcpy.DeleteField_management(centroidFC, "pointid") arcpy.DeleteField_management(centroidFC, "grid_code") # Calculate point distance table msg("Calculating point distance") ptDistTbl = "in_memory\PtDistance" result = arcpy.PointDistance_analysis(patchCentroids, patchCentroids, ptDistTbl) # Add attribute indices to point distance table msg("Adding fields") result = arcpy.AddField_management(ptDistTbl, "FromID", "Long", 10) result = arcpy.AddField_management(ptDistTbl, "ToID", "Long", 10) # Create a dictionary of FIDs:GridCodes msg("Updating ID fields") idDict = {} fidFld = arcpy.Describe(patchCentroids).OIDFieldName idFld = "grid_code" rows = arcpy.SearchCursor(patchCentroids) row = rows.next() while row: idDict[row.getValue(fidFld)] = row.getValue(idFld)
def centroid_near_distance(feature_class, near_feature, id_field, search_radius=1000): """ Adaptation of centroid distance code from code library to do a more basic operation by simply getting the centroid of each polygon, and then doing the same for the near features """ if not feature_class or not near_feature: raise ValueError( "missing the feature class or the near feature - both arguments must be defined!" ) centroids = geometry.get_centroids( feature_class, dissolve=False, id_field=id_field) # merge, don't append if not centroids: processing_log.info( "No centroids generated - something probably went wrong") return False processing_log.info("first centroids retrieved") temp_filename = arcpy.CreateScratchName( "temp", workspace=r"C:\Users\dsx.AD3\Documents\ArcGIS\scratch.gdb") processing_log.info("{0:s}".format(temp_filename)) point_file = geometry.write_features_from_list( centroids, "POINT", filename=temp.generate_gdb_filename(), spatial_reference=feature_class, write_ids=True) processing_log.info("first centroids written") near_centroid = geometry.get_centroids( near_feature, dissolve=False) # merge, don't append processing_log.info("second centroids retrieved") if not near_centroid: processing_log.info( "No centroids generated for near feature- something probably went wrong" ) return False near_point_file = geometry.write_features_from_list( near_centroid, "POINT", spatial_reference=near_feature) processing_log.info("second centroids written") processing_log.info("Point File located at {0!s}".format( point_file)) # change back to info out_table = temp.generate_gdb_filename("out_table", return_full=True) processing_log.info("Output Table will be located at {0!s}".format( out_table)) # change back to info try: arcpy.PointDistance_analysis(in_features=point_file, near_features=near_point_file, out_table=out_table, search_radius=search_radius) except: processing_log.error("Couldn't run PointDistance - {0!s}".format( traceback.format_exc())) return False return { "table": out_table, "point_file": point_file, } # start just returning a dictionary instead of positional values
## Find the cell with the highest flow length #outflowlength = FlowLength(outextractmask, "DOWNSTREAM") # Calculer le In_flow_Raster pour chaque bassin ## get X/Y/flowlength of the cell with the max #maxflowLobject = arcpy.GetRasterProperties_management(outflowlength, "MAXIMUM") #maxflow = maxflowLobject.getOutput(0) #outsetnull = SetNull(outflowlength, 1, "VALUE < "+str(maxflow)) #arcpy.RasterToPoint_conversion(outsetnull, path_river+"src_R"+str(i+1)+".shp") ## PROBLEM? IT DOES NOT WORK.... # BE CAREFUll : the value threshold is set to 250, but it can maybe less. # The idea is to find the closest point of the basin boundary ! outsetnull = SetNull(outextractmask, outextractmask, "VALUE < 250") StreamToFeature(outsetnull, outsetnull, tmpf + "tmp.shp", "SIMPLIFY") arcpy.FeatureVerticesToPoints_management(tmpf + "tmp.shp", tmpf + "tmp2.shp", "END") arcpy.PointDistance_analysis(tmpf+"tmp2.shp", path_river+"exu_R"+str(i+1)+".shp", \ env.workspace+"RProfils/R"+str(i+1)+"table_acc_dist"+str(i+1)) # Find FID of the MAX_DISTANCE, arcpy.Statistics_analysis(env.workspace+"/RProfils/R"+str(i+1)+"/table_acc_dist"+str(i+1)+".dbf", \ tmpf+"stats1", [["DISTANCE", "MAX"]]) rows = arcpy.SearchCursor(tmpf + "stats1") row = rows.next() maxd = row.MAX_DISTANCE arcpy.TableSelect_analysis(tmpf + "stats1", tmpf + "select1", "DISTANCE = " + str(maxd)) rows = arcpy.SearchCursor(tmpf + "select1") row = rows.next() fidr = row.INPUT_FID # Extract point with the FID of the MAX_DISTANCE ! arcpy.FeatureClassToFeatureClass_conversion(tmpf + "tmp2.shp", path_river, "src_R" + str(i + 1) + ".shp", "FID = " + str(fidr))
t2 = getTime() msg = 'Time for FeatureToPoint to create {}'.format(os.path.basename(outfile1)) timeDifference(t1, t2, msg) #calculates time taken to find central feature of centroids t1 = getTime() outfile2 = outdir + '/' + os.path.splitext( os.path.basename(infile))[0] + 'Central.shp' arcpy.CentralFeature_stats(outfile1, outfile2, 'EUCLIDEAN_DISTANCE') t2 = getTime() msg = 'Time for CentralFeature to create {}'.format(os.path.basename(outfile2)) timeDifference(t1, t2, msg) #calculates time taken to find the mean centroid t1 = getTime() outfile3 = outdir + '/' + os.path.splitext( os.path.basename(infile))[0] + 'Mean.shp' arcpy.MeanCenter_stats(outfile1, outfile3) t2 = getTime() msg = 'Time for MeanCenter to create {}'.format(os.path.basename(outfile3)) timeDifference(t1, t2, msg) #calculates time taken to estimate distance between central centroid and mean centroid t1 = getTime() outfile4 = outdir + '/' + os.path.splitext( os.path.basename(infile))[0] + 'Mean2Central.dbf' arcpy.PointDistance_analysis(outfile2, outfile3, outfile4) t2 = getTime() msg = 'Time for PointDistance to create {}'.format(os.path.basename(outfile4)) timeDifference(t1, t2, msg)
# -*- coding: utf-8 -*- # --------------------------------------------------------------------------- # disntance_point.py # Created on: 2015-03-23 11:27:20.00000 # (generated by ArcGIS/ModelBuilder) # Description: # --------------------------------------------------------------------------- # Set the necessary product code # import arcinfo # Import arcpy module import arcpy # Local variables: d1_wan_c = "d1_wan_c" d1_wan_c__2_ = "d1_wan_c" d1_wan_c_PointDistance = "C:\\Users\\John\\Documents\\ArcGIS\\Default.gdb\\d1_wan_c_PointDistance" # Process: Point Distance arcpy.PointDistance_analysis(d1_wan_c, d1_wan_c__2_, d1_wan_c_PointDistance, "")
arcpy.env.overwriteOutput=True #fileInQuestion = r"%s\%s\%s" % (out_gdb_path,out_gdb_name,cityname) #if arcpy.Exists(fileInQuestion): #arcpy.Delete_management(fileInQuestion) arcpy.FeatureClassToFeatureClass_conversion(Event_layer,gdb,cityname, "","") print "Centriod done" centriod = r"%s\%s\%s" % (out_gdb_path,out_gdb_name,cityname) # urban_edge_points = r"%s\%s_vertics_points.shp" % (output_WS,cityname) arcpy.FeatureVerticesToPoints_management(input_file, urban_edge_points, "ALL") # Point Distance distance_table = r"%s\%s\%s_distance_table" % (out_gdb_path,out_gdb_name,cityname) arcpy.PointDistance_analysis(centriod, urban_edge_points, distance_table, "") distance_table_max = r"%s\%s\%s_distance_table_max" % (out_gdb_path,out_gdb_name,cityname) arcpy.Statistics_analysis(distance_table, distance_table_max, "DISTANCE MAX", "") print "point distance done" # Join field ID arcpy.AddField_management(Dissolve_urban_edge, "UID", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") arcpy.CalculateField_management(Dissolve_urban_edge, "UID", "[FID]+1", "VB", "") arcpy.JoinField_management(Dissolve_urban_edge, "UID", distance_table_max, "OBJECTID", "MAX_DISTANCE") print "join done"
def flight_interpolation(twopts, singlepoint, sound_station_loc, counter): # initialize note variable note = "" # name the needed shapefiles two_pts = twopts single_point = singlepoint # uncomment to outputthe two selected points for troubleshooting #arcpy.Select_analysis(two_pts,"twopoints.shp") # read the distances from the two points and save to list 'point_distances' point_distances = [] with arcpy.da.SearchCursor(two_pts, ['NEAR_DIST']) as cursor: for row in cursor: point_distances.append(row[0]) # read the altitudes from the two points and save to list altitudes altitudes = [] with arcpy.da.SearchCursor(two_pts, ['altitude']) as cursor: for row in cursor: altitudes.append(row[0]) # read the times from the two points and save to list 'altitudes' times = [] with arcpy.da.SearchCursor(two_pts, ['ltime']) as cursor: for row in cursor: times.append(datetime.datetime.strptime(row[0], "%Y/%m/%d %H:%M:%S" )) # calculate the total distance between the points total_dist = round(point_distances[0] + point_distances[1],0) ###################################### # ALTITUDE CALCULATION - calculates the altitude at the closest approach point ###################################### # calculate the total elevation change alt_change = altitudes[1]-altitudes[0] # eliminate points with total_dist of zero to prevent division by zero; add note if changed if(total_dist == 0): total_dist = 100000 note = note + "Zero distance - duplicate points; " # calculate the altitude change between point 0 and the point of interest alt_change_to_pt = alt_change*(point_distances[0]/float(total_dist)) # calculate the final altitude of the point of interest by adding to the base altitude point_alt = alt_change_to_pt + altitudes[0] # save altitude of closest point to pass to results altatclosestapchm = point_alt ####################################### # CLOSEST APPROACH TIME - determine the time of the closest approach to the sound station ####################################### #total time change time_change = (times[1]-times[0]).total_seconds() # add error message for zero time change, change to high number to ensure removeal by "unrealistic speed" test below if(time_change == 0): time_change = 10000000 note = note + "Zero time change; " #calculate the time change between point 0 and the point of interest time_change_to_pt = datetime.timedelta(seconds = time_change*((point_distances[0]/float(total_dist)))) # calculate the actual closest approach time closest_apch_time = str(time_change_to_pt + times[0]) # remove microseconds from approach time closest_apch_time = closest_apch_time.split('.', 1)[0] ######################################### # average speed between points - average speed of the plane between the two closest point ################################## avg_speed = abs(round(total_dist / time_change,0)) # measure the closest approach distance arcpy.PointDistance_analysis(single_point, sound_station_loc, "in_memory//distance") # read the 2d distance value from the table AND SAVE TO VARIABLE "DISTANCE" with arcpy.da.SearchCursor("in_memory//distance", ['distance']) as cursor: for row in cursor: distance = row[0] # read the altitude of the station from the input file with arcpy.da.SearchCursor(sound_station_loc, ['elevation']) as cursor: for row in cursor: elevation = row[0] # subtract the two elevations and use trig to calculate actual distance ele_diff = point_alt - elevation closest_dist3d = round(np.sqrt((distance*distance)+(ele_diff*ele_diff)),0) # extract the tail number and flight number flight_id = [] with arcpy.da.SearchCursor(two_pts, ['desc_']) as cursor: for row in cursor: flight_id.append(row[0]) # extract the station ID station_id = [] with arcpy.da.SearchCursor(sound_station_loc, ['code']) as cursor: for row in cursor: station_id.append(row[0]) # determine climb or descent climbrate = round(-1*(alt_change_to_pt / int(time_change)),2) ################################################## # measure angle of flight, convert to compass bearing ################################################## # first, read the angle value from the twopts file: with arcpy.da.SearchCursor(twopts, ['NEAR_ANG_H']) as cursor: for row in cursor: angle = row[0] # ensure that angle is on positive side if(angle <0): angle = angle + 180 # convert geometric angle to north angle if(angle <= 90): angle = 90-angle if(angle > 90): angle = 180 - angle # extract x coordinates of the two points xcoord = [] with arcpy.da.SearchCursor(two_pts, ['SHAPE@X']) as cursor: for row in cursor: xcoord.append(row[0]) # orient the vector in the direction of motion based on the time data if(time_change > 0): if(xcoord[0]>xcoord[1]): angle = angle + 180 if(time_change <= 0): if(xcoord[0]<xcoord[1]): angle = angle + 180 # round the final angle value angle = round(angle,1) ######################################################### # extract x and y coordinates of closest approach point ######################################################## # set the output CS (coordinate system) to ensure data will plot in arcmap (alaska albers 2011) outCS = arcpy.SpatialReference(102117) arcpy.Project_management(single_point, "out.shp",outCS) # extract all x coordinates xcoordca = [] with arcpy.da.SearchCursor("out.shp", ['SHAPE@X']) as cursor: for row in cursor: xcoordca.append(row[0]) # extract all y coordinates ycoordca = [] with arcpy.da.SearchCursor("out.shp", ['SHAPE@Y']) as cursor: for row in cursor: ycoordca.append(row[0]) # print the spatial referenc of the output for troubleshooting desc = arcpy.Describe("out.shp") spatialRef = desc.spatialReference # Print the spatial reference name print spatialRef.Name ################################################ # Function output: ################################################ # create a list with all output variables output_list = [str(station_id[0]),str(flight_id[0]),str(counter).zfill(3),str(closest_dist3d),str(closest_apch_time),str(avg_speed*3.6),str(np.abs(time_change)),str(total_dist),str(climbrate),str(angle),note,str(xcoordca[0]),str(ycoordca[0]),altatclosestapchm] # print a summary of the event print("") print("Event Summary:") print("") print("Flight ID : " + str(flight_id[0])) print("Station ID : " + str(station_id[0] )) print("Distance at Closest Approach (m): " + str(closest_dist3d)) print("Time of Closest Approach : " + str(closest_apch_time)) print("Average interval speed (km/hr) : " + str(avg_speed*3.6)) print("Time Between Pts (s) : " + str(np.abs(time_change))) print("Distance Between Pts (m) : " + str(total_dist)) print("Climb Rate (m/s) : " + str(climbrate)) print("Vector (deg) : " + str(angle)) # warn if speed is less than 50 km/hr print("") if np.abs(avg_speed*3.6) < 50: print("Unrealistic speed, please review input tracks.") # add any error codes accomulated while running the function if( note != ""): print("Error codes: " + note) # or not if( note == ""): print("No data validation errors.") return output_list;
os.chdir(r'xxx') fc=arcpy.ListFeatureClasses() #3º # cola o mesmo caminhho do passp 2 env.workspace=r'F:\data\Dani_ramos\join_tabel\shapes_pontos\temp' #daqui pra baixo nao precisa mudar nada for i in fc: inps=i.replace('.shp','') out=inps+'_eucdist.txt' out_final=inps+'_eucdist_joinFinal.txt' arcpy.PointDistance_analysis(inps,inps,out,"") out_inp=out.replace('.txt','') arcpy.JoinField_management(out_inp,"INPUT_FID",inps,"FID") out_final_inp=out.replace('.txt','') fields = arcpy.ListFields(out_final_inp) field_names = [field.name for field in fields] with open(out_final,'w') as f: w = csv.writer(f) #--write all field names to the output file w.writerow(field_names) for row in arcpy.SearchCursor(out_final_inp): field_vals = [row.getValue(field.name) for field in fields] w.writerow(field_vals) del row
max_conf.to_excel(writer) writer.save() # Method 3: Data cursors fc = "C:/SA_Fires/SHP/SA_Fire_Pts_SJ.shp" fields = ['Name', 'confidence'] for row in arcpy.da.SearchCursor(fc, fields, sql_clause=('Select a Country', 'Top 1')): print('{0}, {1}'.format(row[0], row[1])) ################################################################################ #Part 4: For each fire find the average distance to all other fires #Method 1 use point distance analyses arcpy.PointDistance_analysis(in_features="SA_Fire_Pts", near_features="SA_Fire_Pts", out_table="C:/SA_Fires/Tabular/SA_Fire_Pts_PointDistance", # CHANGE search_radius="") # Create pivot table if singular value wanted PtDist_a = "SA_Fire_Pts_PointDistance" Pivot_table = "C:SA_Fires/Tabular/PtDist_Pivot.csv" arcpy.PivotTable_management(PtDist_a, "INPUT_FID", "DISTANCE", Pivot_table) #Method 2: Use Numpy to calculate a distance matrix ################################################################################ # Part 5: Find Fires that are within 5km of a border (near analysis and search or buffer and select) # NA than select feature where NDist <= 5km # Near_analysis (in_features, near_features, {search_radius}, {location}, {angle}, {method})
# Convert north/south point dbf file to x y feature arcpy.MakeXYEventLayer_management(table=OutDirect + "KDEMCentroidLongitudeNSNorth.dbf", in_x_field="X", in_y_field="Y", out_layer="KDEM" + str(Year) + NObskfoldgrppL[LoopCount] + "CentroidLongitudeNSPointNorth", spatial_reference="PROJCS['North_America_Albers_Equal_Area_Conic',GEOGCS['GCS_North_American_1983',DATUM['D_North_American_1983',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Albers'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-96.0],PARAMETER['Standard_Parallel_1',20.0],PARAMETER['Standard_Parallel_2',60.0],PARAMETER['Latitude_Of_Origin',40.0],UNIT['Meter',1.0]];-16688100 -9068200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision", in_z_field="") # Save layer to shapefile arcpy.FeatureClassToShapefile_conversion("KDEM" + str(Year) + NObskfoldgrppL[LoopCount] + "CentroidLongitudeNSPointNorth", OutDirect) ####### ## Calculate distance between "CentNS" and overall centroid and "CentEW" and overall centroid # First calculate east to west shift arcpy.PointDistance_analysis(in_features=OutDirect + "KDEM02_16TSECentroidNorth.shp", near_features=OutDirect + "KDEM" + str(Year) + NObskfoldgrppL[LoopCount] + "CentroidLatitudeEWPointNorth.shp", out_table=OutDirect + "KDEMCentroidEasttoWestDistanceNorth.dbf", search_radius="") # Extract centroid east to west shift distance from dbf file # Create SearchCursor rows = arcpy.SearchCursor(OutDirect + "KDEMCentroidEasttoWestDistanceNorth.dbf") # Get value of distance field = arcpy.ListFields(OutDirect + "KDEMCentroidEasttoWestDistanceNorth.dbf")[3] name = field.name for row in rows: CentroidEWShift = row.getValue(name) ## # Then calculate north to south shift arcpy.PointDistance_analysis(in_features=OutDirect + "KDEM02_16TSECentroidNorth.shp",
else: isOP = False outTable = gdb+'/xxxPlotAtScales' testAndDelete(outTable) mapUnits = 'meters' minSeparationMapUnits = minSeparation_mm/1000.0 searchRadius = minSeparationMapUnits * maxPlotAtScale if not 'meter' in arcpy.Describe(inFc).spatialReference.linearUnitName.lower(): # units are feet of some flavor mapUnits = 'feet' searchRadius = searchRadius * 3.2808 minSeparationMapUnits = minSeparationMapUnits * 3.2808 addMsgAndPrint('Search radius is '+str(searchRadius)+' '+mapUnits) addMsgAndPrint( 'Building near table' ) arcpy.PointDistance_analysis(inFc,inFc,outTable,searchRadius) inPoints = [] outPointDict = {} # read outTable into Python list inPoints, with each list component = [distance, fid1, fid2] fields = ['DISTANCE','INPUT_FID','NEAR_FID'] with arcpy.da.SearchCursor(outTable,fields) as cursor: for row in cursor: inPoints.append([row[0],row[1],row[2]]) addMsgAndPrint(' '+ str(len(inPoints))+' rows in initial near table') # step through inPoints, smallest distance first, and write list of FID, PlotAtScale (outPoints) addMsgAndPrint(' Sorting through near table and calculating PlotAtScale values' ) inPoints.sort() lastLenInPoints = 0
fc = arcpy.GetParameterAsText(0) wrkspace = arcpy.GetParameterAsText(1) fc_out = arcpy.GetParameterAsText(2) radius = arcpy.GetParameterAsText(3) #=====================Declare constant local variables=============================# distance = r"C:\temp\distance.dbf" #spatial_ref = arcpy.Describe(fc).spatialReference.Name prjs = arcpy.Describe(fc).spatialReference.exportToString() #=================Do some analysis==========================# arcpy.CreateFeatureclass_management(wrkspace,fc_out+".shp","POLYLINE",fc,"DISABLED","DISABLED",prjs) arcpy.PointDistance_analysis(fc,fc,distance,radius) #=================Create Pair of FID Points==========================# curSDisnc = arcpy.SearchCursor(distance) Inpt_FID = [row.getValue("INPUT_FID") for row in curSDisnc] curSDisnc = arcpy.SearchCursor(distance) Outpt_FID = [row.getValue("NEAR_FID") for row in curSDisnc] pair = zip(Inpt_FID,Outpt_FID) del curSDisnc #============Insert Cursor=====================================#
### NEED TO CHANGE PARAMTERS before excute. import arcpy from arcpy.sa import * from arcpy import env ## Parameters to change # # input directory where shape files are sDir = "C:/Users/VonFischer/Documents/Methane/CodeForPublic/Shapefiles/" sCity = "BIR" fnRoads = sDir + sCity + "_RoadPoints.shp" # RoadPoints file fnObs = sDir + sCity + "_AllOccasions.shp" # AllOccasions from Part1 Script fnOutTable = sDir + "PD_" + sCity + "_roads_v_occ4.dbf" arcpy.PointDistance_analysis(fnRoads,fnObs,fnOutTable,"20 Meters") # join arcpy.JoinField_management(fnOutTable,"NEAR_FID",fnObs,"FID","Period5Min") print "Calculating number of occasions..." lstOut = [] lstID = [] xOldRoadID = -999 lstV = [] cursor = arcpy.SearchCursor(fnOutTable) for row in cursor: xRoadID = row.getValue("Input_FID") if xRoadID != xOldRoadID: xOldRoadID = xRoadID #print str(xRoadID) + ", " + str(len(set(lstV)))
import arcpy import os arcpy.env.overwriteOutput = True fcparcel = arcpy.GetParameterAsText(0) poilayer = arcpy.GetParameterAsText(1) addfieldname = arcpy.GetParameterAsText(2) tempData = arcpy.env.scratchGDB + os.path.sep + "parcelpoint" temptable = arcpy.env.scratchGDB + os.path.sep + "outtable" temptable2 = arcpy.env.scratchGDB + os.path.sep + "outtable2" arcpy.FeatureToPoint_management(fcparcel, tempData) arcpy.PointDistance_analysis(tempData, poilayer, temptable) arcpy.DeleteField_management(fcparcel, "SUM_ca") arcpy.DeleteField_management(temptable, "ca") arcpy.AddField_management(temptable, "ca", "FLOAT") cur = arcpy.UpdateCursor(temptable) for row in cur: newdistance = row.getValue("DISTANCE") if newdistance != 0: row.setValue("ca", 1.0 / newdistance**2) cur.updateRow(row) else: row.setValue("ca", 0) cur.updateRow(row)
last_ID = last_row[0] # tallennetaan viimeisen pisteen ID first_dist = first_row[1] # ensimmäisen pisteen etäisyystieto #print("1. pisteen etäisyystieto: "+ str(first_dist)) last_dist = last_row[1] # viimeisen pisteen etäisyystieto #print("Viimeisen pisteen etäisyystieto: "+ str(last_dist)) first_point = first_row[2] # ensimmäisen pisteen PointGeometry last_point = last_row[2] # viimeisen pisteen PointGeometry pt_f = first_point pt_l = last_point # Lasketaan alku- ja loppupisteiden välinen etäisyys tablename = os.path.basename(gps_track)+"_alku_loppu" output_table = os.path.join(ws_dir,"GPS_pisteet_kopio.gdb",tablename) arcpy.PointDistance_analysis(in_features=pt_f, near_features=pt_l, out_table=output_table) distance_row = '' # tyhjä muuttuja pisteiden etäisyydelle with arcpy.da.SearchCursor(output_table, "DISTANCE") as cursor: # luetaan cursorin avulla taulukosta distance_row = cursor.next() point_distance = distance_row[0] # tallennetaan etäisyyslukema print("Pisteiden välinen etäisyys: " + str(point_distance)) # Reitin kokonaispituus GPS-pisteistä laskettuna on lopun matkalukema - alun matkalukema reittipituus = float(last_dist) - float(first_dist) print("Reitin kokonaispituus: " + str(reittipituus)) # Lasketaan alku- ja loppupisteen etäisyyden suhde kokonaismatkaan reittisuhde = point_distance/reittipituus print("Pisteiden välinen etäisyys suhteessa kokonaismatkaan: " + str(reittisuhde))
def getSinuosity(shape): ## This functions calculates the sinuosity of a polyline. ## Needs as an input a polyline shapefile. ## And a list of the years that the shapefiles are refering to. ## Also divides the line into section in order to calculate the sinuosity per section. ############################################# # Catching possible Errors - Error handling. ############################################# # Catch the error of using an empty shapefile (i.e. with no features in it) f_count = arcpy.GetCount_management(shape) if int(f_count[0]) > 0: arcpy.AddMessage("The input {0} has {1} features".format( shape.split("\\")[-1], f_count)) else: arcpy.AddError( 'The input {} has no features the execution of the script will fail ... Please check the input shapefiles ...' .format(shape.split("\\")[-1])) sys.exit(0) # Catch the error of having an unknown spatial reference for the input data. spatial_ref = arcpy.Describe(shape).spatialReference if spatial_ref.name != "Unknown": arcpy.AddMessage("The spatial reference of {0} is {1}".format( shape.split("\\")[-1], spatial_ref.name)) else: arcpy.AddError( "Beware ... the used input {0} has Unknown spatial reference ... Please check the Spatial Reference of the input shapefiles ... The execution of the script will be terminated soon ..." .format(shape)) sys.exit(0) # Catch the geometry Type error (of the input shapefiles not being polyline) desc = arcpy.Describe(shape) geometryType = desc.shapeType if str(geometryType) == 'Polyline': pass else: arcpy.AddError( '{} is not a line/polyline ... Please check the input shapefiles ...' .format(shape.split("\\")[-1])) sys.exit(0) ##################### # Calculate Sinuosity ##################### arcpy.AddMessage( "### Calculating sinuosity index for the whole river ###") for year in year_list: # Go through all the different Years the user enter as input (stored in a list). if year in shape: # If the Year input connects to a shapefile input (i.e. the user did not put wrong Year). try: if int( f_count[0] ) > 1: # If the input consits of multiple features dissolve it to 1. arcpy.AddMessage( "{0} has {1} features and it will be dissolved into 1 feature ..." .format(shape.split("\\")[-1], f_count)) shape_dissolve = r'river_dissolved.shp' # Name of the shapefile for the dissolved river arcpy.Dissolve_management( shape, shape_dissolve) # Perform dissolve shape = shape_dissolve # From now on the dissolved shape is going to be the variable shape. arcpy.AddMessage("Adding Geometry field ...") arcpy.AddGeometryAttributes_management( shape, "LENGTH", "METERS" ) # Add a Geometry field to calculate the length of each feature. arcpy.AddMessage("Adding field ...") arcpy.AddField_management( shape, 'TOT_LENGTH', 'DOUBLE' ) # Add another field "TOT_LENGTH" to copy the values ofthe length field - fixing field names to avoid confusions. arcpy.AddMessage("Calculating field ...") arcpy.CalculateField_management( shape, "TOT_LENGTH", "!LENGTH!", "PYTHON" ) # Actually copying the values of "LENGTH" to the new field added above. arcpy.AddMessage("Deleting field ...") arcpy.DeleteField_management( shape, "LENGTH" ) # Delete the geometry field that was just created. arcpy.AddMessage( "Calculating total length of the river ...") cursor = arcpy.da.SearchCursor( shape, ["TOT_LENGTH"] ) # Use a search cursor to go through the "TOT_LENGTH" of the input shapefile. length = 0 for row in cursor: # For all the individual features / lines in a polyline. length += row[0] arcpy.AddMessage( "Extracting the ending point of the river ...") river_end_shp = r'end_' + str( year ) + '.shp' # Variable for the shapefile of the end point of the polyline. arcpy.AddMessage( "Extracting the starting point of the river ...") river_start_shp = r'start_' + str( year ) + '.shp' # Variable for the shapefile of the start point of the polyline. arcpy.AddMessage( "Feature Vertices to Points for the 'start' and 'end' vertices of the river ..." ) arcpy.FeatureVerticesToPoints_management( shape, river_end_shp, "end" ) # Convert the last-end vertex of the polyline (river) to point, output River_end arcpy.FeatureVerticesToPoints_management( shape, river_start_shp, "start" ) # Convert the first-start vertex of the polyline (river) to point, output River_start. arcpy.AddMessage( "Calculating straight distance between start and end vertices of the river ..." ) distance_table = r'distance' + str(year) + '.dbf' arcpy.PointDistance_analysis( river_end_shp, river_start_shp, distance_table, "" ) # Calculate the straight distance between start and end and save it to a table cursor = arcpy.da.SearchCursor( distance_table, "DISTANCE" ) # Use a search cursor to go through the distance collumn in the created distance table. d = 0 # Variable for straight distance - direct distance for rows in cursor: # For the different rows of the distance collumn in the distance_table d = rows[ 0] # Add the different rows (the distance will always in the first row though) arcpy.AddMessage( "The straight distance between the starting and ending point is now computed and stored in the {}" .format(distance_table)) if normalize_sin_bool == 'true': sinuosity = d / length # Defined as Length / d but reverse is used, Max possible sinuosity = 1 . else: sinuosity = length / d # Normalized sinuosity index as used by ESRI toolbox. except: arcpy.AddMessage(arcpy.GetMessages()) arcpy.AddMessage("Adding field ...") arcpy.AddField_management( shape, 'sinuosity', 'DOUBLE' ) # Add a field in the river shapefile to store the sinuosity value arcpy.AddMessage("Calculating field ...") arcpy.CalculateField_management( shape, 'sinuosity', sinuosity, 'VB' ) # Calculate the sinuosity field - actually store the value in the table of the shapefile. ############################### ## Sinuosity per Section Part. ############################### if river_section_bool == 'true': # This condition is satisfied if the user selected to also calculate the Sinuosity Index per section. arcpy.AddMessage( "### Calculating sinuosity index for different parts of the river ####" ) arcpy.AddMessage( "You have selected {0} sections ".format(sections) ) # Need to move in the IF for the section statement arcpy.AddMessage("Creating new shapefiles ...") points_along_shape_shp = r'points_along_shape_' + str( year ) + '.shp' # Variable for the shapefile of the points along the river line. river_section_shp = 'river_sections_year_' + str( year ) + '.shp' # Variable for the shapefile of the river divided into sections. arcpy.AddMessage( "Calculating the length of sections in % of total length ..." ) per = 100 / int( sections ) # Calculate the percentage of each section based on the Number of Sections that the user asked with his input. arcpy.AddMessage( "The percentage of the total length for each section is :{}" .format(per)) arcpy.AddMessage( "Generating points along the river line ...") arcpy.GeneratePointsAlongLines_management( shape, points_along_shape_shp, "PERCENTAGE", Percentage=per, Include_End_Points='NO_END_POINTS' ) # Generate points along the based on the above calculate percentage. ##Added to delete the last point of the points along lines. points_temp = 'points_along_shape' + str( year ) + 'filtered.shp' # Temporary shapefile used to delete the point the the edge of the line from the points along the line. arcpy.MakeFeatureLayer_management(points_along_shape_shp, points_temp) sel_exp = "\"FID\"=" + str( int(sections) - 1 ) # The last one will have FID the number of sections -1 arcpy.SelectLayerByAttribute_management( points_temp, "NEW_SELECTION", sel_exp) if int( arcpy.GetCount_management(points_temp)[0] ) > 0: # If there are any features satisfying this condition - Will be! arcpy.DeleteFeatures_management( points_temp) # Delete them. ## arcpy.AddMessage("Spliting line on points ...") arcpy.SplitLineAtPoint_management( shape, points_along_shape_shp, river_section_shp, "2000 Meters" ) # Splitting the line into sections by using the above generate points. arcpy.AddMessage("Adding Geometry field ...") arcpy.AddGeometryAttributes_management( river_section_shp, "LENGTH", "METERS") # Get the length of each section arcpy.AddMessage("Adding field ...") arcpy.AddField_management( river_section_shp, 'SEC_LENGTH', 'DOUBLE' ) # Store the length in a new field "SEC_LENGTH" to be more clear - avoid confusion. arcpy.AddMessage("Calculating field ...") arcpy.CalculateField_management(river_section_shp, "SEC_LENGTH", "!LENGTH!", "PYTHON") arcpy.AddMessage( "Deleting field ..." ) # Delete the "LENGTH" field in the same logic. arcpy.DeleteField_management(river_section_shp, "LENGTH") arcpy.AddMessage( "The calculation of the length of each section was successful, the values are stored in the field " "\"SEC_LENGTH\"" " ") river_section_shp_lvl2 = 'river_sections_year_' + str( year ) + 'lvl2' + '.shp' # Variable for the shapefile of the river sections that will be used to be sure that the script will delete all the sections # that are substantially 'small' because in such a case the sinuosity values of that sections will be missleading arcpy.CopyFeatures_management(river_section_shp, river_section_shp_lvl2) temp_sec_len_l = [ ] # Create an empty list that will store all the length values of the different sections. cursor = arcpy.da.SearchCursor( river_section_shp_lvl2, "SEC_LENGTH" ) # Use a search cursor to go through the section length field. for row in cursor: temp_sec_len_l.append( int(row[0]) ) # Populate/Append each value of the field to the list we just created. minimum_section_length = min( temp_sec_len_l) # Find the minimum length per section. mean_section_length = sum(temp_sec_len_l) / len( temp_sec_len_l ) # And find the average length per section. arcpy.AddMessage("Minimum section length :{}".format( minimum_section_length)) arcpy.AddMessage("Average section length :{}".format( mean_section_length)) arcpy.AddMessage( "Deleting the substantially small sections ...") temp = 'river_sections_year_' + str( year ) + 'lvl3' + '.shp' # Temporary shapefile used to delete the 'small' sections arcpy.MakeFeatureLayer_management(river_section_shp_lvl2, temp) delete_thres = 0.35 # Threshold of deletion (Small section) is defined as 0.35 of the average length of the sections exp_sec_len = "\"SEC_LENGTH\" <" + str( delete_thres * mean_section_length) arcpy.SelectLayerByAttribute_management( temp, "NEW_SELECTION", exp_sec_len ) # Select the features by attributes based on the above threshold/expression if int( arcpy.GetCount_management(temp)[0] ) > 0: # If there are any features satisfying this condition - arcpy.AddWarning( "{} of the generated sections were substantially smaller than the average section length, and they are being deleted ..." .format(int(arcpy.GetCount_management(temp)[0]))) arcpy.DeleteFeatures_management(temp) # Delete them ###### arcpy.AddMessage("Adding field ...") arcpy.AddField_management( river_section_shp_lvl2, "startx", "DOUBLE" ) # Field that will store the X coordinate of the starting point of each section. arcpy.AddMessage("Adding field ...") arcpy.AddField_management( river_section_shp_lvl2, "starty", "DOUBLE" ) # Field that will store the Y coordinate of the starting point of each section. arcpy.AddMessage("Adding field ...") arcpy.AddField_management( river_section_shp_lvl2, "endx", "DOUBLE" ) # Field that will store the X coordinate of the ending point of each section. arcpy.AddField_management( river_section_shp_lvl2, "endy", "DOUBLE" ) # Field that will store the Y coordinate of the ending point of each section. arcpy.AddMessage("Adding field ...") arcpy.AddField_management( river_section_shp_lvl2, 'dirdis', 'DOUBLE' ) # Field that will store the direct distance for each section of the river from starting to ending vertex. arcpy.AddMessage("Adding field ...") arcpy.AddField_management( river_section_shp_lvl2, "sec_sin", "DOUBLE" ) # Field that will store the sinuosity of EACH Section. #Expressions for the calculations of the new fields. # Create the expressions in order to populate the fields that were just created above. exp_start_X = "!Shape!.positionAlongLine(0.0,True).firstPoint.X" # expression for starting X exp_start_Y = "!Shape!.positionAlongLine(0.0,True).firstPoint.Y" # expression for starting Y exp_end_X = "!Shape!.positionAlongLine(1.0,True).firstPoint.X" # expression for ending X exp_end_Y = "!Shape!.positionAlongLine(1.0,True).firstPoint.Y" # expression for ending Y arcpy.AddMessage("Calculating field ...") # Finally arcpy.CalculateField_management( river_section_shp_lvl2, "startx", exp_start_X, "PYTHON" ) # Populate/Calculate the starting X-coordinate of each section. arcpy.AddMessage("Calculating field ...") arcpy.CalculateField_management( river_section_shp_lvl2, "starty", exp_start_Y, "PYTHON" ) # Populate/Calculate the starting X-coordinate of each section. arcpy.AddMessage("Calculating field ...") arcpy.CalculateField_management( river_section_shp_lvl2, "endx", exp_end_X, "PYTHON" ) # Populate/Calculate the starting X-coordinate of each section arcpy.AddMessage("Calculating field ...") arcpy.CalculateField_management( river_section_shp_lvl2, "endy", exp_end_Y, "PYTHON" ) # Populate/Calculate the starting X-coordinate of each section # Based on the above (Xstart-Xend,Ystart,Yend) and using dd_exp = "math.sqrt((!startx!-!endx!)**2+(!starty!-!endy!)**2)" # The pythagoreum we can now get straight distance. arcpy.AddMessage("Calculating field ...") arcpy.CalculateField_management( river_section_shp_lvl2, "dirdis", dd_exp, "PYTHON" ) # Populate the field based on the pythagoreum expression for each section. if normalize_sin_bool == 'true': sin_exp = "!dirdis!/!SEC_LENGTH!" # Defined as Length / d but reverse is used, Max possible sinuosity = 1 . else: # Expression for Sinuosity Formula (direct distance / Length). sin_exp = "!SEC_LENGTH!/!dirdis!" arcpy.AddMessage("Calculating field ...") arcpy.CalculateField_management( river_section_shp_lvl2, "sec_sin", sin_exp, "PYTHON" ) # Populate/Calculate the sections sinuosity field based on the sinuosity expression for each section. arcpy.AddMessage( "The calculation of the sinuosity per section was successful, the values are stored in a field named " "\"sec_sin\"" " ")
if b == True: fields = ["OBJECTID", Gelegenheiten[1]] else: fields = ["OBJECTID", "ID"] f = Gelegenheiten[1] if f: fields = fields + f Ziel_tab = arcpy.da.FeatureClassToNumPyArray(z, fields) Ziel_tab = pandas.DataFrame(Ziel_tab) Tabelle_A = Gelegenheiten[2] if head == 1: Tabelle_A = Tabelle_A + "_1" print Tabelle_A ##--calculation of connections--## Lines = arcpy.PointDistance_analysis(z, HstBer, "C:" + f[0] + "Default.gdb/test", 1100) Lines_tab = arcpy.da.FeatureClassToNumPyArray( Lines, ["OBJECTID", "INPUT_FID", "NEAR_FID", "DISTANCE"]) Lines_tab = pandas.DataFrame(Lines_tab) try: arcpy.Delete_management("C:" + f[0] + "Default.gdb\\test") except: pass ##--joins--## Relation = pandas.merge(Lines_tab, HstBer_tab, left_on="NEAR_FID", right_on="OBJECTID") Relation = pandas.merge(Relation,
import math arcpy.env.overwriteOutput = True fcparcel = arcpy.GetParameterAsText(0) poilayer = arcpy.GetParameterAsText(1) betavalue = arcpy.GetParameterAsText(2) addfieldname = arcpy.GetParameterAsText(3) tempDatapar = arcpy.env.scratchGDB + os.path.sep + "parpoi" temptable = arcpy.env.scratchGDB + os.path.sep + "out" temptable2 = arcpy.env.scratchGDB + os.path.sep + "outt" tempDatajoin = arcpy.env.scratchGDB + os.path.sep + "join" arcpy.FeatureToPoint_management(fcparcel, tempDatapar) arcpy.PointDistance_analysis(tempDatapar, tempDatapar, temptable) arcpy.SpatialJoin_analysis(fcparcel, poilayer, tempDatajoin, "#", "#", "CONTAINS") arcpy.DeleteField_management(temptable, "Join_Count") arcpy.JoinField_management(temptable, "NEAR_FID", tempDatajoin, "TARGET_FID", ["Join_Count"]) arcpy.Delete_management(tempDatajoin) arcpy.DeleteField_management(temptable, "cal") arcpy.AddField_management(temptable, "cal", "FLOAT") betanum = float(betavalue) cur = arcpy.UpdateCursor(temptable) for row in cur: row.setValue("cal",