def evaluate(individual): individual = individual[0] prod_MWsel = sum(x * y for x, y in zip(prod, individual)) #check if the total production is witin boundaries, if not return a penalty vector if up_targ >= prod_MWsel >= low_targ: # goal 1 mean_enerdsel = sum(x * y for x, y in zip(enerd, individual)) / sum(individual) # goal 2 count_WTsel = sum(individual) # goal 3 (subset the input points by the WT_IDs which are in the ini pop (=1) WT_pop = np.column_stack((id, individual)) WT_sel = WT_pop[WT_pop[:, [1]] == 1] WT_sel = WT_sel.astype(int) qry = '"WT_ID" IN ' + str(tuple(WT_sel)) subset = arcpy.MakeFeatureLayer_management(all_pts, "tmp", qry) nn_output = arcpy.AverageNearestNeighbor_stats(subset, "EUCLIDEAN_DISTANCE", "NO_REPORT", "41290790000") clus = float(nn_output.getOutput(0)) res = (clus, count_WTsel, mean_enerdsel) ## delete the feature tmp since otherwise it will not work in a loop arcpy.Delete_management("tmp") arcpy.Delete_management("subset") else: res = (10e20, 10e20, 0) return res #def feasible(individual): individual = individual[0] prod_MWsel = sum(x * y for x, y in zip(prod, individual)) if (prod_MWsel <= up_targ and prod_MWsel >= low_targ): return True return False
def NearestNeighbor(fc, i, locationType): distanceTable = 'nnDistance' #Create table for output tableExists = arcpy.ListTables(distanceTable) #Check for existing table before creating if tableExists == []: arcpy.CreateTable_management(workspacePath, distanceTable) arcpy.AddField_management(distanceTable, 'StateName', 'TEXT') arcpy.AddField_management(distanceTable, 'NNdistance', 'FLOAT') #Location stats arcpy.AddField_management(distanceTable, 'LOCATION_COUNT', 'SHORT') arcpy.AddField_management(distanceTable, 'LOCATION_DENSITY', 'FLOAT') #Table variables fields = ['OBJECTID', 'StateName', 'NNdistance'] #Open cursor to distanceTable for inserting cursor = arcpy.da.InsertCursor(distanceTable, fields) #Calculate average nearest neighbor stats nn_output = arcpy.AverageNearestNeighbor_stats( fc, "EUCLIDEAN_DISTANCE", "NO_REPORT") #Grab observed distance and convert from meters to miles obsDistance = round((float(nn_output[4]) * 0.000621371), 2) #Add space back to name for those states that should have one (required for joining purposes); Index of -1 returned for those not found if fc.find('New') != -1: fc = fc.replace('New', 'New ') elif fc.find('North') != -1: fc = fc.replace('North', 'North ') elif fc.find('South') != -1: fc = fc.replace('South', 'South ') elif fc.find('West') != -1: fc = fc.replace('West', 'West ') elif fc.find('Rhode') != -1: fc = fc.replace('Rhode', 'Rhode ') #Remove activity from stateName stateName = fc.replace(locationType + 'Filtered', '') #Add values to table row = [i, stateName, obsDistance] cursor.insertRow(row) #i+=1 del cursor
def Nearest_Neighbour_Index_Analysis(facilityName): ''' To conduct Nearest Neighbour Index Analysis :param facilityName: feature class name to be analyzed :return: ''' try: nn_output = arcpy.AverageNearestNeighbor_stats(facilityName, "EUCLIDEAN_DISTANCE", "GENERATE_REPORT", "#") # Create list of Average Nearest Neighbor output values by splitting the result object # print("The nearest neighbor index is: " + nn_output[0]) # print("The z-score of the nearest neighbor index is: " + nn_output[1]) # print("The p-value of the nearest neighbor index is: " + nn_output[2]) # print("The expected mean distance is: " + nn_output[3]) # print("The observed mean distance is: " + nn_output[4]) # print("The path of the HTML report: " + nn_output[5]) print "Complete Nearest Neighbour Analysis" except: print(arcpy.GetMessages())
def evaluate(individual): individual = individual[0] #first check if the production of the seleced WT's is in the range between 4.31 and 4.29 TWH # goal 1 mean_enerdsel = sum(x * y for x, y in zip(enerd, individual)) / sum(individual) # goal 2 count_WTsel = sum(individual) # goal 3 (subset the input points by the WT_IDs which are in the ini pop (=1) WT_pop = np.column_stack((id, individual)) WT_sel = WT_pop[WT_pop[:, [1]] == 1] WT_sel = WT_sel.astype(int) qry = '"WT_ID" IN ' + str(tuple(WT_sel)) subset = arcpy.MakeFeatureLayer_management(all_pts, "tmp", qry) nn_output = arcpy.AverageNearestNeighbor_stats(subset, "EUCLIDEAN_DISTANCE", "NO_REPORT", "41290790000") clus = float(nn_output.getOutput(0)) res = (clus, count_WTsel, mean_enerdsel) ## delete the feature tmp since otherwise it will not work in a loop arcpy.Delete_management("tmp") arcpy.Delete_management("subset") return (res)
# print("The nearest neighbor index is: " + nn_output[0]) # print("The z-score of the nearest neighbor index is: " + nn_output[1]) # print("The p-value of the nearest neighbor index is: " + nn_output[2]) # print("The expected mean distance is: " + nn_output[3]) # print("The observed mean distance is: " + nn_output[4]) # print("The path of the HTML report: " + nn_output[5]) workPath = r"C:\Users\chenpipy\Desktop\xian" try: # Set the current workspace (to avoid having to specify the full path to the feature classes each time) arcpy.env.workspace = workPath files = arcpy.ListFeatureClasses() for file in files: try: nn_output = arcpy.AverageNearestNeighbor_stats( file, "EUCLIDEAN_DISTANCE", "NO_REPORT", "#") rows = arcpy.UpdateCursor(file) for row in rows: row.setValue("ave_dis", nn_output[4]) row.setValue("exp_dis", nn_output[3]) row.setValue("index", nn_output[0]) row.setValue("p", nn_output[2]) row.setValue("z", nn_output[1]) rows.updateRow(row) except arcpy.ExecuteError: print("跳过") except arcpy.ExecuteError: # If an error occurred when running the tool, print out the error message. print(arcpy.GetMessages())
# JSON library lets us convert strings to and from json format import json # Declare the bounding rectangle area as float variable given_bounding_rect = 1760000000.0 # From the resulting bounding rectangle when performing Nearest Neighbor Analysis in ArcMap calc_bounding_rect = 747896332.677655 """ USING ARCPY """ data = "INSERT PATH TO FILE" # Prints the five average nearest neighbor analysis values # from the given bounding rectangle area arcpy.AverageNearestNeighbor_stats(data, "EUCLIDEAN_DISTANCE", "NO_REPORT", given_bounding_rect) # if no area is provided, ArcPy will calculate its own bounding rectangle area arcpy.AverageNearestNeighbor_stats(data, "EUCLIDEAN_DISTANCE") """ USING PLAIN PYTHON """ def get_distance(p, p_list): """ :param p: reference point :param p_list: list of points :return: list of distances from that point to all other points in the list """ d_list = [
# --------------------------------------------------------------------------- # Cluster.py # Created on: 2017-09-14 04:49:18.00000 # (generated by ArcGIS/ModelBuilder) # Usage: Cluster <Input_Feature_Class> <Output_Standard_Distance_Feature_Class> # Description: # --------------------------------------------------------------------------- # Import arcpy module import arcpy # Script arguments Input_Feature_Class = arcpy.GetParameterAsText(0) Output_Standard_Distance_Feature_Class = arcpy.GetParameterAsText(1) # Local variables: NNRatio = "0" NNZScore = "0" PValue = "0" NNExpected = "0" NNObserved = "0" Report_File = "" # Process: Average Nearest Neighbor arcpy.AverageNearestNeighbor_stats(Input_Feature_Class, "EUCLIDEAN_DISTANCE", "GENERATE_REPORT", "") # Process: Standard Distance arcpy.StandardDistance_stats(Input_Feature_Class, Output_Standard_Distance_Feature_Class, "1_STANDARD_DEVIATION", "", "")
def wildFireAnalysis(): try: work = raw_input(r"Enter the full path of WildlandFires.gdb: ") if arcpy.Exists(work): y = raw_input ("WARNING! This file exists! Overwrite? (Y or N):") if y == 'N' or y!= 'Y': raise overwriteError('Program Ended... No Feature Class Created') else: raise existsError('Path does not exist!') arcpy.env.workspace = work # Set the workspace to the geodatabase iFile = raw_input(r"Enter the full path of wildfire text file: ") if not os.path.exists(iFile): raise existsError('Path does not exist!') f = open(iFile, 'r') line = f.readline() newConfid= line.split(',') confidName = newConfid[2] setConfidVal = confidName.strip("\n") lstFires = f.readlines() f.close() featName = raw_input("Enter the name of the output feature class: ") if arcpy.Exists(featName): y = raw_input ("WARNING! This file exists! Overwrite? (Y or N):") if y == 'N' or y!= 'Y': raise overwriteError('Program Ended... No Feature Class Created') int_a = input("Specify the minimum confidence threshold (0-100):") arcpy.CreateFeatureclass_management(work, featName, "Point") arcpy.AddField_management(featName, setConfidVal, "LONG", 4) fields = ["SHAPE@", setConfidVal] cur = arcpy.da.InsertCursor(featName, fields) cntr = 0 counter = 0 while True: int_a = int(int_a) if (0 <= int_a <= 100): # Correct number, break the while loop break # Wrong number int_a = input("Warning...Threshold must be between 0 and 100...Re-enter:") # Here int_a is in the correct range fc = 'C:\Users\Thoma\Desktop\Lab5GEOG656\Lab 8 Data\WildlandFires.gdb\NationalParks' counter = 0 with arcpy.da.SearchCursor(fc, ['Name','SHAPE@']) as cursor: for row in cursor: name = row[0] geom = row[1] for fire in lstFires: if 'Latitude' in fire: # Skip the header continue pnt = arcpy.Point() pointGeom = fire.split(',') lstValues = pointGeom latitude = pointGeom[0] longitude = pointGeom[1] confidence = pointGeom[2] confid = int(confidence) pnt.X = float(longitude) pnt.Y = float(latitude) if confid > int_a: row = [pnt, confid] cur.insertRow(row) cntr = cntr + 1 print "Record # " + str(cntr) + " written to feature class" if pnt.within(geom) is True: counter = counter + 1 print('There were {} fires in {}'.format(counter, name)) del cur nn_output = arcpy.AverageNearestNeighbor_stats(featName, "EUCLIDEAN_DISTANCE", "NO_REPORT", "#") zScore=float((nn_output.getOutput(1))) roundZscore = (round(zScore, 2)) if roundZscore < -1.65: print('The fire incidents are *significantly clustered* (z-score = {})'.format(roundZscore)) elif roundZscore > 1.65: print('The fire incidents are *significantly dispersed* (z-score = {})'.format(roundZscore)) elif roundZscore > -1.65 and roundZscore < 1.65: print('The fire incidents are * spatially random* (z-score = {})'.format(roundZscore)) except overwriteError as e: print "Error: " + str(e) # Prints Python-related errors except existsError as e: print "Error: " + str(e) # Prints Python-related errors
longitude = listValues[1] confid = listValues[2] pnt.X = longitude pnt.Y = latitude #if the point is in the polygon, insert it into new feature class and increment record count and number in polygon count row = [pnt, confid] cur.insertRow(row) cntr = cntr + 1 print "Record # " + str(cntr) + " written to feature class" if pnt.within(polygon): inNationalPark +=1 del cur, searchCurs #delete both cursors print 'The were {num} fires within {name}'.format(num = inNationalPark, name = name) #Analyze Clustering of Fire Points nn_output = arcpy.AverageNearestNeighbor_stats(newOutputFeatureClass, "EUCLIDEAN_DISTANCE", "NO_REPORT",'#') zscoreval = round(float(nn_output[1]),2) if nn_output[1] < -1.65: print "The fire incidents are *signifiantly clustered* (z-score= ({score})".format(score=zscoreval) elif nn_output[1] > 1.65: print "The fire incidents are *significantly disperesed* (z-score= {score})".format(score=zscoreval) else: print "The fire incidents are *sptially random* (z-score= {score})".format(score=zscoreval) except overwriteError: print "Program Ended... No Feature Class Created" except existsError: print "Program Ended... Path Does Not Exist" except Exception as e: print "Error: " + str(e) # Prints Python-related errors print arcpy.GetMessages() # Prints ArcPy-related errors