def create_fishnet(): #delete previous fishnet feature class arcpy.Delete_management(yxc.out_fishnet) #acquire parameters for creatfisnet function XMin = yxc.in_raster.extent.XMin YMin = yxc.in_raster.extent.YMin XMax = yxc.in_raster.extent.XMax YMax = yxc.in_raster.extent.YMax origCord = "{} {}".format(XMin, YMin) YAxisCord = "{} {}".format(XMin, YMax) cornerCord = "{} {}".format(XMax, YMax) cellSizeW = "0" cellSizeH = "0" numRows = 7 numCols = 7 geotype = "POLYGON" arcpy.env.outputCoordinateSystem = yxc.in_raster.spatialReference print yxc.in_raster.spatialReference.name #call CreateFishnet_management function arcpy.CreateFishnet_management(yxc.out_fishnet, origCord, YAxisCord, cellSizeW, cellSizeH, numRows, numCols, cornerCord, "NO_LABELS", "", geotype)
def handle_fishnet(lasd, base_dir, grid_dim): print('Creating Buffered Fishnet & Clipping') # Create Path for Fishnet fishnet_path = os.path.join(base_dir, 'FISHNET') os.mkdir(fishnet_path) # Build Fishnet From Input LASD desc = arcpy.Describe(lasd) extent = desc.extent origin_point = str(extent.XMin) + ' ' + str(extent.YMin) y_axis = str(extent.XMin) + ' ' + str(extent.YMax) fishnet_name = os.path.join(fishnet_path, 'fishnet.shp') grid = arcpy.CreateFishnet_management( fishnet_name, origin_point, y_axis, '0', '0', grid_dim, grid_dim, '#', 'False', lasd, 'POLYGON' ) # Buffer Fishnet To Ensure Grid Cells Overlap fish_buff = os.path.join(fishnet_path, 'fishnet_buff.shp') buff_grid = arcpy.Buffer_analysis(grid, fish_buff, '2 Meters', 'FULL', 'FLAT', 'NONE', '#', 'PLANAR') # Clip Buffered Fishnet With Originial To Exclude Outer Buffers clip_name = os.path.join(fishnet_path, D04_FINAL) arcpy.Clip_analysis(buff_grid, fishnet_name, clip_name)
def downsample(city_id): log('Downsampling points for %s', city_id) output_dir = join(DOWNSAMPLE_DIR, str(city_id)) if not exists(output_dir): os.makedirs(output_dir) log('Created %s', output_dir) else: log('%s already exists!', output_dir) samples_shp = join(LATLNGS_SHP_DIR, '%s.shp' % city_id) downsampling_fishnet_poly_shp = join(output_dir, 'downsampling_fishnet.shp') downsampling_fishnet_label_shp = join(output_dir, 'downsampling_fishnet_label.shp') if not exists(downsampling_fishnet_poly_shp): log('Creating fishnet...') desc = arcpy.Describe(samples_shp) arcpy.CreateFishnet_management( downsampling_fishnet_poly_shp, str(desc.extent.lowerLeft), str(desc.extent.XMin) + ' ' + str(desc.extent.YMax + 10), '0.0012', '0.0012', '0', '0', str(desc.extent.upperRight), 'LABELS', '#', 'POLYGON') log('Fishnet creation complete') samples_identity_shp = join(output_dir, 'samples_identity.shp') if not exists(samples_identity_shp): log('Computing identity...') arcpy.Identity_analysis(samples_shp, downsampling_fishnet_poly_shp, samples_identity_shp) log('Identity complete') samples_stats = join(output_dir, 'samples_stats') if not exists(join(output_dir, 'info')): log('Starting summary statistics...') arcpy.Statistics_analysis(samples_identity_shp, samples_stats, [['price', 'MEAN']], 'FID_downsa') log('Summary statistics complete') log('Detecting if join has already been done...') join_done = False fields = arcpy.ListFields(downsampling_fishnet_label_shp) for field in fields: if field.name == 'MEAN_PRICE': join_done = True if not join_done: log('Performing table join on FID:FID_DOWNSA...') arcpy.JoinField_management(downsampling_fishnet_label_shp, 'FID', samples_stats, 'FID_DOWNSA', ['MEAN_PRICE']) log('Table join on FID:FID_DOWNSA done.') log('Defining projection...') arcpy.DefineProjection_management(downsampling_fishnet_label_shp, PROJECTION_FILE) log('FINISHED downsampling %s', city_id) return downsampling_fishnet_label_shp log('======================END==========================')
def Create_Fishnet(): ''' Create fishnets for basemap_cleaned :return: ''' try: origin_coord = "800976.4051000001 801661.3544999994" axis_coord = "800976.4051000001 801671.3544999994" arcpy.CreateFishnet_management( "basemap_Fishnet", cell_height=250, cell_width=250, origin_coord=origin_coord, y_axis_coord=axis_coord, # labels="LABELS", template="basemap_cleaned", geometry_type="POLYGON") arcpy.AddField_management("basemap_Fishnet", "Types", "INTEGER") cursor = arcpy.UpdateCursor("basemap_Fishnet") for row in cursor: row.setValue("Types", 0) cursor.updateRow(row) del row, cursor print("Complete creating basemap fishnets!") except: print(arcpy.GetMessages())
def pointGrid(fc, outDir, unitCoversionRatio, gridSize): #dissolved_urban_extent=outDir+"/dissolved_urban_extent.shp" #arcpy.Dissolve_management(fc,dissolved_urban_extent,"#","#","MULTI_PART") fileName = os.path.basename(fc) dscObj = arcpy.Describe(fc) refExtent = dscObj.extent Y_Max = refExtent.YMax X_Max = refExtent.XMax Y_Min = refExtent.YMin X_Min = refExtent.XMin Y_length = (Y_Max - Y_Min) X_length = (X_Max - X_Min) No_Cols = X_length / gridSize No_Rows = Y_length / gridSize dsc = arcpy.Describe(outDir) if dsc.dataType == "Workspace": fishnet = outDir + "/fishnet" fishnet_label = outDir + "/fishnet_label" sample_point = outDir + "/{0}_sample_point".format(fileName) elif dsc.dataType == "Folder": fishnet = outDir + "/fishnet.shp" fishnet_label = outDir + "/fishnet_label.shp" sample_point = outDir + "/{0}_sample_point.shp".format(fileName) arcpy.CreateFishnet_management(fishnet,"{0} {1}".format(X_Min,Y_Min),\ "{0} {1}".format(X_Min,Y_Max),(gridSize),(gridSize),\ No_Rows,No_Cols,"#","LABELS","#","POLYGON") spReference = dscObj.spatialReference arcpy.DefineProjection_management(fishnet_label, spReference) arcpy.Clip_analysis(fishnet_label, fc, sample_point)
def create_fishnet(in_raster_path, out_fc_path): #create raster object from in_raster_path ras1 = arcpy.Raster(in_raster_path) #specify input parameters to fishnet tool XMin = ras1.extent.XMin XMax = ras1.extent.XMax YMin = ras1.extent.YMin YMax = ras1.extent.YMax origCord = "{} {}".format(XMin, YMin) YAxisCord = "{} {}".format(XMin, YMax) CornerCord = "{} {}".format(XMax, YMax) cellSizeW = '0' cellSizeH = '0' """modify the numRows and numCols to control how the input raster is chunked for parallel processing For example, if numRows = 4 & numCols = 4, total number of chunks = 4*4 = 16. """ numRows = 4 numCols = 4 geo_type = "POLYGON" #Run fishnet tool logger.info("Running fishnet creator: {} with PID {}".format( current_process().name, os.getpid())) arcpy.env.outputCoordinateSystem = ras1.spatialReference arcpy.CreateFishnet_management(out_fc_path, origCord, YAxisCord, cellSizeW, cellSizeH, numRows, numCols, CornerCord, "NO_LABELS", "", geo_type) arcpy.ClearEnvironment("outputCoordinateSystem")
def createFishnet(self): arcpy.env.workspace = self.inventory.getWorkspace() arcpy.env.overwriteOutput = True self.inventory.refreshBoundingBox() oCorner = self.inventory.getBottomLeftCorner() tCorner = self.inventory.getTopRightCorner() self.blc_x, self.blc_y = self.roundCorner(oCorner[0], oCorner[1], -1, self.resolution_degrees) self.trc_x, self.trc_y = self.roundCorner(tCorner[0], tCorner[1], 1, self.resolution_degrees) self.inventory_template = self.inventory.getLayerName() self.origin_coord = "{} {}".format(self.blc_x, self.blc_y) self.y_axis_coord = "{} {}".format(self.blc_x, self.blc_y + 1) self.corner_coord = "{} {}".format(self.trc_x, self.trc_y) tasks = [ lambda: arcpy.CreateFishnet_management( self.XYgrid, self.origin_coord, self.y_axis_coord, self. resolution_degrees, self.resolution_degrees, "", "", self. corner_coord, "NO_LABELS", self.inventory_template, "POLYGON"), lambda: self._createFields(), lambda: self._calculateFields() ] pp = self.ProgressPrinter.newProcess(inspect.stack()[0][3], len(tasks)).start() for t in tasks: t() pp.updateProgressV() pp.finish()
def create_records(install_folder, fgdb_name): """ :param install_folder: the folder to install the test data in :type install_folder: basestring :param fgdb_name: the name of the fgdb, no path, with the .gdb extension :type fgdb_name: basestring """ env.workspace = os.path.join(install_folder, fgdb_name) env.outputCoordinateSystem = arcpy.SpatialReference(28356) # MGA Zone 56 env.overwriteOutput = True # Typical Case, 602 records log.info("Creating polyline FC with 602 records") fgdb_path = os.path.join(install_folder, fgdb_name, "MGAZ56_602_rec_polyline") arcpy.CreateFishnet_management(out_feature_class=fgdb_path, origin_coord='500000 6950000', y_axis_coord='500000 6950100', cell_width=100, cell_height=100, number_rows=300, number_columns=300, labels="NO_LABELS", geometry_type="POLYLINE") # Edge Case, 5 million records log.info( "Creating polygon and point FCs with 5 million records (can take 15 minutes" ) fgdb_path = os.path.join(install_folder, fgdb_name, "MGAZ56_5_million_rec_polygon") arcpy.CreateFishnet_management(out_feature_class=fgdb_path, origin_coord='500000 6950000', y_axis_coord='500000 6950100', cell_width=100, cell_height=100, number_rows=2000, number_columns=2500, labels="LABELS", geometry_type="POLYGON") # rename the label points arcpy.Rename_management(in_data="MGAZ56_5_million_rec_polygon_label", out_data="MGAZ56_5_million_rec_point", data_type="FeatureClass")
def checkandrepair3(path_result): path_match = sys.path[0] + '/match.config' dictionary = read_match(path_match) arcpy.env.workspace = path_result GDBs_result = arcpy.ListFiles('*.gdb') while 1: needrepair = 0 for GDB_result in GDBs_result: arcpy.env.workspace = path_result+'\\' + GDB_result layers = arcpy.ListFeatureClasses() if 'LCA_intersect' not in layers: needrepair = 1 if needrepair == 1: for GDB_result in GDBs_result: arcpy.env.workspace = path_result+'\\' + GDB_result layers = arcpy.ListFeatureClasses() if 'LCA_intersect' not in layers: print GDB_result+':lack of LCA_intersect' f = open(sys.path[0]+'/log/'+GDB_result[0:6]+'.txt','a') start = time.clock() time_start = time.strftime("%Y-%m-%d#%H:%M:%S",time.localtime()) AlterField('LCA_old','CC','CC_old','CC_old') #create fishnet extent = getMinXY('LCA_new') fishnet_out = 'grid' originCoordinate = str(extent[0] - 0.025) + " " + str(extent[1] - 0.025) yAxisCoordinate = str(extent[0]) + " " + str(extent[1] + 10) numRows = math.ceil((extent[3] - extent[1])/0.05) + 1 numColumns= math.ceil((extent[2] - extent[0])/0.05) + 1 arcpy.CreateFishnet_management(fishnet_out, originCoordinate, yAxisCoordinate, '0.05', '0.05', numRows, numColumns, '#', 'NO_LABELS', 'LCA_new', 'POLYGON') #PAC_old intersect grid intersectOutput = 'LCA_old_grid' intersect(['LCA_old','grid'],intersectOutput) #PAC_old intersect grid intersectOutput = 'LCA_new_grid' intersect(['LCA_new','grid'],intersectOutput) #PAC_old_grid intersect PAC_new_grid inFeatures = ['LCA_old_grid','LCA_new_grid'] intersectOutput ='LCA_intersect' intersect(inFeatures,intersectOutput) print GDB_result+':intersect finished' end = time.clock() time_end = time.strftime("%Y-%m-%d#%H:%M:%S",time.localtime()) f.write('R2,'+time_start+','+time_end+','+str(end-start)+'\n') f.close() else: break print "check3 finished"
def grid(self, code_block, numrows, tempfishnet): """Set up the fishnet tool from arcpy and calculate an id number for each cell of the fishnet.""" origin = self.origin() yaxis = self.yaxis() opp_corner = self.opp_corner() numcolumns = numrows arcpy.CreateFishnet_management(tempfishnet, origin, yaxis, "0", "0", numrows, numcolumns, opp_corner, "NO_LABELS", "#", "POLYGON") arcpy.CalculateField_management(tempfishnet, "Id", "autoIncrement()", "PYTHON_9.3", code_block) print("grid ", numcolumns, "by", numrows, "complete")
def background(self,Output_path,resolution,raster_list,env_workspace): """This uses the defined resolution and creates the background grid""" OutGrid = os.path.join(Output_path,"background.shp") res = str(resolution) for raster in raster_list: raster = raster r = os.path.join(env_workspace,raster) break ################################################################################ YMAX = arcpy.GetRasterProperties_management(r,"TOP") YMIN = arcpy.GetRasterProperties_management(r,"BOTTOM") XMIN = arcpy.GetRasterProperties_management(r,"LEFT") XMAX = arcpy.GetRasterProperties_management(r,"RIGHT") YOrient = float(str(YMIN)) + 10 OriginCoord = str(XMIN)+" "+str(YMIN) OrientCoord = str(XMIN)+" "+str(YOrient) OppositeCoord = str(XMAX)+" "+str(YMAX) try: arcpy.CreateFishnet_management(OutGrid,OriginCoord,OrientCoord,res, res,"0","0",OppositeCoord,"LABELS", raster,"POLYGON") except: print arcpy.GetMessages() arcpy.Delete_management(OutGrid) ################################################################################ self.background_points = os.path.join(Output_path, "background_label.shp") Fields = "" for raster in raster_list: in_raster = os.path.join(env_workspace, raster) fieldname = str(raster) item = str(in_raster+" "+fieldname+";") Fields += item Fields = Fields[:-1] ################################################################################ arcpy.CheckOutExtension("Spatial") ExtractMultiValuesToPoints(self.background_points,Fields,"NONE") arcpy.AddXY_management(self.background_points) arcpy.CheckInExtension("Spatial") ################################################################################ return(self.background_points)
def collect_extents(lasd, base_dir, row, col): print('Collecting Task Extents') fishnet_path = os.path.join(base_dir, 'FISHNET') os.mkdir(fishnet_path) # Build Fishnet From Input LASD desc = arcpy.Describe(lasd) extent = desc.extent origin_point = str(extent.XMin) + ' ' + str(extent.YMin) y_axis = str(extent.XMin) + ' ' + str(extent.YMax) grid = arcpy.CreateFishnet_management( os.path.join(fishnet_path, 'fishnet.shp'), origin_point, y_axis, '0', '0', row, col, '#', 'False', lasd, 'POLYGON') # Buffer Fishnet To Ensure Grid Cells Overlap fish_buff = os.path.join(fishnet_path, 'fishnet_buff.shp') buff_grid = arcpy.Buffer_analysis(grid, fish_buff, '5 Meters', 'FULL', 'FLAT', 'NONE', '#', 'PLANAR') # Polygon Neighbors neighbor_table = os.path.join(fishnet_path, 'neigbor_table.dbf') neighbor_poly = arcpy.PolygonNeighbors_analysis(fish_buff, neighbor_table, 'FID') # Summarize Table summary_name = os.path.join(fishnet_path, 'summary.dbf') summary_table = arcpy.Statistics_analysis(neighbor_poly, summary_name, [['src_FID', 'COUNT']], 'src_FID') # Join Summary To Fishnet Buffer arcpy.JoinField_management(buff_grid, 'FID', summary_table, 'src_FID') # Populate Dictionary With Grid Cell Extents # Append Underscore To Inner Grid Cells (if row[1] == 8) ext_dict = {} for r in arcpy.da.SearchCursor(buff_grid, ['FID', 'COUNT_src_', 'SHAPE@']): ext = r[2].extent box = [ext.XMin, ext.YMin, ext.XMax, ext.YMax] if r[1] == 8: id = ''.join((str(r[0]), '_')) else: id = str(r[0]) ext_dict[id] = box print('Tasks: ', len(ext_dict)) return ext_dict
def fishnet(a): # run fishnet 804.67m (1/2 mi) grids, bounds defined by places polygon # project the layers to utm env.workspace = "C:/Users/Noah/Desktop/grids/scripts/folders/{0}".format(a) # # Get a list of the feature classes in the input folder # feature_classes = arcpy.ListFeatureClasses('') inFC = '{0}_utm.shp'.format(a) desc = arcpy.Describe(inFC) outFC = '{0}_fishnet.shp'.format(a) arcpy.CreateFishnet_management(outFC, str(desc.extent.lowerLeft), str(desc.extent.XMin) + " " + str( desc.extent.YMax + 10), "804.67", "804.67", "", "", str(desc.extent.upperRight), "NO_LABELS", "#", "POLYGON") sr = arcpy.SpatialReference("NAD 1983 UTM Zone 10N") arcpy.DefineProjection_management(outFC, sr)
def create_grid(out_shp, datum, projection): print "...Deleting the output if it exists" delete_if_exists(out_shp) print "...Setting intermediate files" fishnet_shp = "fishnet.shp" print "...Creating a fishnet" arcpy.CreateFishnet_management(fishnet_shp, "46 39", "46 49", "0.5", "0.5", "", "", "47 40.5", "NO_LABELS", "46 39 47 40.5", "POLYLINE") print "...Defining datum" arcpy.DefineProjection_management(fishnet_shp, datum) print "...Projecting" project4karabakh(fishnet_shp, out_shp, projection) print "...Deleting intermediate files" arcpy.Delete_management(fishnet_shp)
def createFishNet(): arcpy.AddMessage("Creating fishnet in study areas...") desc = arcpy.Describe("StudyAreas") arcpy.CreateFishnet_management( out_feature_class=makeFullPath(tempGDB, "Fishnet"), origin_coord=str(desc.extent.lowerLeft), y_axis_coord=str(desc.extent.XMin) + " " + str(desc.extent.YMax + 10), cell_width="35", cell_height="35", number_rows="0", number_columns="0", corner_coord=str(desc.extent.upperRight), labels="LABELS", template="#", geometry_type="POLYLINE") return makeFullPath(tempGDB, "Fishnet_label")
def create_fishnet(number_columns, number_rows): '''(str,str) -> output shapefile "fishnet.shp" Inputs: number_columns (str) = Takes any integer as a string number_rows (str) = Takes any integer as a string Creates 'fishnet' shapefile in the directory where the workspace is located. Adds 'Name' field populated with the value 'Tile_#', where # = the OID of each fishnet polygon. Returns the full file path. ''' arcpy.CreateFishnet_management(fishnet_out, origin_coord, y_coord, cell_width, cell_height, number_rows, number_columns, opposite_corner_coord, labels, template, geometry_type) arcpy.AddField_management(fishnet_out, 'Name', 'TEXT') with arcpy.da.UpdateCursor(fishnet_out, ['OID@', 'Name']) as cursor: for oid, name in cursor: row = (oid, 'Tile_{0:02d}'.format(oid)) cursor.updateRow(row) return fishnet_out
def fishnet(output, templateExtent, geomType='POLYGON', numRows=None, numColumns=None, cellWidth=None, cellHeight=None, labeling="NO_LABELS"): """ Create a fishnet - rectangular cells Use fc or raster to assign a extent to the new fishnet """ import os from gasp.prop.ext import rst_ext, get_extent from gasp.prop.ff import vector_formats, raster_formats from gasp.oss import get_fileformat templateFormat = get_fileformat(templateExtent) if templateFormat in vector_formats(): xmin, xmax, ymin, ymax = get_extent(templateExtent, gisApi='arcpy') elif templateFormat in raster_formats(): xmin, xmax, ymin, ymax = rst_ext(templateExtent, gisApi='arcpy') else: raise ValueError(('Could not identify if observerDataset ' 'is a raster or a feature class')) arcpy.CreateFishnet_management( out_feature_class=output, origin_coord=' '.join([str(xmin), str(ymin)]), y_axis_coord=' '.join([str(xmin), str(ymin + 10.0)]), cell_width=cellWidth, cell_height=cellHeight, number_rows=numRows, number_columns=numColumns, labels=labeling, template=templateExtent, geometry_type=geomType) return output
def pointGrid(polygon, outDir, unitCoversionRation, gridSize, total_population, type): dscObj = arcpy.Describe(polygon) refExtent = dscObj.extent Y_Max = refExtent.YMax X_Max = refExtent.XMax Y_Min = refExtent.YMin X_Min = refExtent.XMin Y_length = unitCoversionRation * (Y_Max - Y_Min) X_length = unitCoversionRation * (X_Max - X_Min) No_Cols = X_length / gridSize No_Rows = Y_length / gridSize dsc = arcpy.Describe(outDir) if dsc.dataType == "Workspace": fishnet = outDir + "/fishnet" fishnet_label = outDir + "/fishnet_label" reference_point = outDir + "/reference_point_{0}".format(type) elif dsc.dataType == "Folder": fishnet = outDir + "/fishnet.shp" fishnet_label = outDir + "/fishnet_label.shp" reference_point = outDir + "/reference_point_{0}.shp".format(type) arcpy.CreateFishnet_management(fishnet,"{0} {1}".format(X_Min,Y_Min),\ "{0} {1}".format(X_Min,Y_Max),(gridSize/unitCoversionRation),(gridSize/unitCoversionRation),\ No_Rows,No_Cols,"#","LABELS","#","POLYGON") spReference = dscObj.spatialReference arcpy.DefineProjection_management(fishnet_label, spReference) arcpy.Clip_analysis(fishnet_label, polygon, reference_point) fields = arcpy.ListFields(reference_point) if "population" not in fields: arcpy.AddField_management(reference_point, "population", "DOUBLE") number_of_points = int( arcpy.GetCount_management(reference_point).getOutput(0)) arcpy.CalculateField_management(reference_point, "population", total_population / number_of_points, 'PYTHON')
def fishNet(): arcpy.env.outputCoordinateSystem = ArcPySpatialReferenceName() XMin = arcpy.Raster(annualRainRunoff).extent.XMin YMin = arcpy.Raster(annualRainRunoff).extent.YMin XMax = arcpy.Raster(annualRainRunoff).extent.XMax YMax = arcpy.Raster(annualRainRunoff).extent.YMax # Set the origin of the fishnet originCoordinate = str(XMin) + " " + str(YMin) # Set the orientation yAxisCoordinate = str(XMin) + " " + str(YMin + 10) cornerCoordinat = str(XMax) + " " + str(YMax) cellsize = 250 # 正方形,所以只需要一个参数 outfishnet = 'fishnet.shp' arcpy.CreateFishnet_management(out_feature_class=outfishnet, origin_coord=originCoordinate, y_axis_coord=yAxisCoordinate, corner_coord=cornerCoordinat, cell_height=cellsize, cell_width=cellsize, geometry_type='POLYGON')
def create_fishnet(polygon, polyline, output_points, output_fishnet, size, valueField): arcpy.AddMessage("...creating fishnet from polygon.") # Create fishnet. desc = arcpy.Describe(polygon) temp_fishnet = "temp_fishnet" temp_points = "temp_points" arcpy.CreateFishnet_management(temp_fishnet, str(desc.extent.lowerLeft), str(desc.extent.XMin) + " " + str(desc.extent.YMax), size, size, "0", "0", str(desc.extent.upperRight), "", polygon, geometry_type='POLYGON') # Select points near streets. nearStreet = arcpy.SelectLayerByLocation_management( temp_fishnet + '_label', 'WITHIN_A_DISTANCE', polyline, '200 Meters') # Intersect with polygon arcpy.Intersect_analysis([nearStreet, polygon], output_points) selected = arcpy.SelectLayerByLocation_management( temp_fishnet, 'INTERSECT', output_points) arcpy.CopyFeatures_management(selected, output_fishnet) arcpy.Delete_management(selected) arcpy.Delete_management(temp_fishnet) arcpy.Delete_management(temp_fishnet + '_label') arcpy.Delete_management(temp_points) # Distribute value from each polygon to points distribute_value(output_points, arcpy.ListFields(output_points)[3].name, valueField)
def build_fishnet_func(hru_polygon_path, hru_point_path, extent, cs, sr): """""" # Remove existing if arcpy.Exists(hru_polygon_path): arcpy.Delete_management(hru_polygon_path) if arcpy.Exists(hru_point_path): arcpy.Delete_management(hru_point_path) # Calculate LL/UR corner points origin_pnt = (extent.XMin, extent.YMin) yaxis_pnt = (extent.XMin, extent.YMin + cs) corner_pnt = (extent.XMax, extent.YMax) origin_str = ' '.join(map(str, origin_pnt)) yaxis_str = ' '.join(map(str, yaxis_pnt)) corner_str = ' '.join(map(str, corner_pnt)) logging.debug(' Origin: {}'.format(origin_str)) logging.debug(' Y-Axis: {}'.format(yaxis_str)) logging.debug(' Corner: {}'.format(corner_str)) # Build fishnet & labels arcpy.CreateFishnet_management( hru_polygon_path, origin_str, yaxis_str, cs, cs, '0', '0', corner_str, 'LABELS', '#', 'POLYGON') arcpy.DefineProjection_management(hru_polygon_path, sr) arcpy.DefineProjection_management(hru_point_path, sr)
def makeGrids(extents, cell_size): xmax, xmin, ymax, ymin = extents # 计算经纬方向一公里的经纬距离 midLat = (ymin + ymax) / 2 * (math.pi / 180) X1Km = 1 / (math.cos(midLat) * 111) Y1Km = 1.0 / 111 cell_size = int(cell_size) # 网格大小 XWidth = X1Km * cell_size YHeight = Y1Km * cell_size # 范围 Left = xmin - XWidth Right = xmax + XWidth Bottom = ymin - YHeight Top = ymax + YHeight # Set the extent of the fishnet originCoordinate = ''.join([str(Left), " ", str(Bottom)]) oppositeCoorner = ''.join([str(Right), " ", str(Top)]) # Set the orientation yAxisCoordinate = ''.join([str(Left), " ", str(Bottom + 1)]) # Enter 0 for width and height - these values will be calculated by the tool cellSizeWidth = str(XWidth) cellSizeHeight = str(YHeight) outputGrids = ''.join(["GRID", str(cell_size)]) arcpy.CreateFishnet_management(outputGrids, originCoordinate, yAxisCoordinate, cellSizeWidth, cellSizeHeight, '0', '0', oppositeCoorner, 'NO_LABELS', '#', 'POLYGON') return outputGrids
# output cellneigborstxt = "DYA_cellneighbors.txt" cell05cent2txt = "DYA_cellcents.txt" celllakestxt = "DYA_celllakes.txt" cell05acttxt = "DYA_cellact.txt" ############################## Geoprocessing ########################## #################################### # 1) create 0.5 x 0.5 cells #################################### # Process: Create Fishnet print "Creating 0.5x0.5 cells" arcpy.CreateFishnet_management(fishnet05, "-180 -65", "-180 -55", "0,5", "0,5", "0", "0", "180 85", "NO_LABELS", "-180 -65 180 85", "POLYGON") # Process: Define Projection print "Defining projection for cells to WGS 1984" arcpy.DefineProjection_management(fishnet05, wgs84) # Process: Add Field print "Adding unique cell-id to fishnet" arcpy.AddField_management(fishnet05, "cell05_id", "LONG", "", "", "", "", "NON_NULLABLE", "NON_REQUIRED", "") # Process: Calculate Field print "populating the cell-id" arcpy.CalculateField_management(fishnet05, "cell05_id", "!FID!+1", "PYTHON_9.3", "")
#Create the grid from the county boundary dateTag = datetime.datetime.today().strftime( '%Y%m%d' ) # we'll tag our output with this. looks somethin like this 20181213 fishnetFileName = "FishnetGrid_" + dateTag # create a filename for the fishnet grid CountyProjDesc = arcpy.Describe( CountyProj) # get the details of the county data arcpy.AddMessage( 'Creating the square mile Fishnet Grid: {}'.format(fishnetFileName)) arcpy.CreateFishnet_management( out_feature_class=os.path.join(FinalData_OutputGeodatabase, fishnetFileName), origin_coord=str(CountyProjDesc.extent.lowerLeft), y_axis_coord=str(CountyProjDesc.extent.XMin) + " " + str(CountyProjDesc.extent.YMax), cell_width=Cell_Size_Width, cell_height=Cell_Size_Height, number_rows="", number_columns="", corner_coord=str(CountyProjDesc.extent.upperRight), labels="NO_LABELS", template=CountyProj, geometry_type="POLYGON") time.sleep(1) # gives a .5 second pause before going to the next step ##add a field to the fishnet grid called GRID_FID Grid_FID = "Grid_FID" arcpy.AddMessage( 'Adding a GRID_FID field to the fishnet grid. Field Name: {}'.format( Grid_FID)) arcpy.AddField_management(in_table=fishnetFileName, field_name=Grid_FID, field_type="LONG",
def main(infc, Width, outfc, radius): if 'shp' in outfc: arcpy.AddError('Output parameter must be saved in a geodatabase') sys.exit() extent = arcpy.Describe(infc).extent orig = "%s %s" % (extent.XMin, extent.YMin) add = extent.YMin * 0.00001 if extent.YMin < 0: yaxis = "%s %s" % (extent.XMin, extent.YMin - add) else: yaxis = "%s %s " % (extent.XMin, extent.YMin + add) arcpy.CreateFishnet_management("in_memory\\fishnet", orig, yaxis, Width, Width, "", "", "", "", infc, "POLYGON") arcpy.MakeFeatureLayer_management("in_memory\\fishnet", "in_memory\\layer") arcpy.SelectLayerByLocation_management("in_memory\\layer", "COMPLETELY_WITHIN", infc) arcpy.CopyFeatures_management("in_memory\\layer", outfc) if radius: fields = ['Area', 'Circumfere'] arcpy.AddField_management(outfc, 'Area', "DOUBLE") arcpy.AddField_management(outfc, 'Circumfere', "DOUBLE", "", "", "", "Circumference") arcpy.AddField_management(outfc, 'S_Radius', "TEXT") arcpy.FeatureToPoint_management(outfc, "in_memory\\fishnet_points") arcpy.Buffer_analysis("in_memory\\fishnet_points", "in_memory\\buffer", radius, "FULL", "ROUND") radius_v = radius.split(' ') data = {} cursorm = [ m_data for m_data in arcpy.da.SearchCursor(infc, ['SHAPE@']) ] count = arcpy.GetCount_management("in_memory\\buffer").getOutput(0) arcpy.SetProgressor("step", "Reading Buffer Parameters", 0, eval(count), 1) R1 = 1 with arcpy.da.SearchCursor("in_memory\\buffer", ['OID@', 'SHAPE@']) as cursor: for row in cursor: for m in cursorm: inter = row[1].intersect(m[0], 4) if inter.length != 0.0: data[row[0]] = (inter.getLength('PLANAR', radius_v[1]), inter.getArea('PLANAR', radius_v[1])) break arcpy.SetProgressorPosition() with arcpy.da.SearchCursor(outfc, ['OID@']) as cursor: for row in cursor: if row[0] < R1: R1 = row[0] fields.extend(['S_Radius', 'OID@']) with arcpy.da.UpdateCursor(outfc, fields) as cursor: for row in cursor: values = data[row[-1] + (1 - R1)] row[0] = values[1] row[1] = values[0] row[2] = radius cursor.updateRow(row)
numCols = math.ceil(width) else: numCols = math.floor(width) # Tile AOI (each tile should be 10km x 10km) prefishnet = os.path.join("in_memory", "prefishnet") fishnet = os.path.join("in_memory", "fishnet") originPoint = str(extAOI.XMin) + " " + str(extAOI.YMin) axisPoint = str(extAOI.XMin) + " " + str(extAOI.YMax) #TODO: check w/ GP, why does this guy not take an arcpy.Point??? if debug == True: arcpy.AddMessage( "fishnet: " + str(time.strftime("%m/%d/%Y %H:%M:%S", time.localtime()))) arcpy.CreateFishnet_management(prefishnet, originPoint, axisPoint, 10000, 10000, numRows, numCols, "#", "#", "#", "POLYGON") deleteme.append(prefishnet) if debug == True: arcpy.AddMessage( "intersect fishnet & AOI: " + str(time.strftime("%m/%d/%Y %H:%M:%S", time.localtime()))) arcpy.Intersect_analysis([inputAOI, prefishnet], fishnet) deleteme.append(fishnet) numTiles = int(arcpy.GetCount_management(fishnet).getOutput(0)) arcpy.AddMessage("AOI has " + str(numTiles) + " 10km square tiles.") fishnetBoundary = os.path.join("in_memory", "fishnetBoundary") if debug == True: arcpy.AddMessage(
"tempCensusDissolve", "", "", "") #Step 2: Add field and calculate area of census blocks. arcpy.AddField_management("tempCensusDissolve.shp", "AcresOrig", "DOUBLE", "", "", "", "", "", "") arcpy.CalculateField_management("tempCensusDissolve.shp", "AcresOrig", "!shape.area@acres!", "PYTHON_9.3", "#") #Step 3: Create Fishnet desc = arcpy.Describe(boundary) arcpy.CreateFishnet_management( "tempFishnet", str(desc.extent.lowerLeft), str(desc.extent.XMin) + " " + str(desc.extent.YMax + 10), fishnetSize, fishnetSize, 0, 0, str(desc.extent.upperRight), "NO_LABELS", boundary, "POLYGON") #Step 4: Select just the Grid Cells that touch the boundaries or interior. #The layer needs to be added to the dataframe first for the selection tool to work. mxd = arcpy.mapping.MapDocument("CURRENT") df = arcpy.mapping.ListDataFrames(mxd, "*")[0] fishnetLayer = arcpy.mapping.Layer("tempFishnet.shp") arcpy.mapping.AddLayer(df, fishnetLayer, "TOP") #Select fishnet grids that overlap with boundary and export to new shapefile. arcpy.SelectLayerByLocation_management(fishnetLayer, "", boundary, "", "NEW_SELECTION", "") arcpy.FeatureClassToFeatureClass_conversion(fishnetLayer, outputPath,
arcpy.env.cellSize = template ## Setup parameters for fishnet xcellSize = arcpy.GetRasterProperties_management(template, 'CELLSIZEX') cellSizeWidth = xcellSize.getOutput(0) ycellSize = arcpy.GetRasterProperties_management(template, 'CELLSIZEY') cellSizeHeight = ycellSize.getOutput(0) outFishnet = os.path.join(fishnetGDB, 'NGA_fishnet') if not arcpy.Exists(outFishnet): arcpy.CreateFishnet_management( outFishnet, origin_coord="2.675 4.25000000386", y_axis_coord="2.675 14.25000000386", cell_width=xcellSize, cell_height=ycellSize, number_rows="", number_columns="", corner_coord="14.6999999999993 13.9000000038595", labels="NO_LABELS", template=template, geometry_type="POLYGON") arcpy.AddField_management(outFishnet, 'UBID', 'LONG') arcpy.CalculateField_management( outFishnet, 'UBID', '!OID!', 'PYTHON') ## Added a uniqueID to the fishnet print(' 0 - Fishnet created') # Add GPW population estimates to fishnet fishPoints = os.path.join(fishnetGDB, 'NGA_fishnet_points') if not arcpy.Exists(fishPoints): arcpy.FeatureToPoint_management(outFishnet, fishPoints, "CENTROID")
LOGGER.debug("XMin: %s, YMin: %s, XMax: %s, YMax: %s", extent.XMin, extent.YMin, extent.XMax, extent.YMax) lowerleft = str(extent.XMin) + " " + str(extent.YMin) upperright = str(extent.XMax) + " " + str(extent.YMax) # Add 0.1 degree on the Y axis to generate the Y axis coordinate Y_AXIS_COORDINATE = str(extent.XMin) + " " + str(extent.YMin + 0.1) # Corners: ORIGIN_COORDINATE = lowerleft OPPOSITE_CORNER = upperright LOGGER.info("Creating the feature's fishnet") # Create 3 x 3 fishnet over the current hazard area arcpy.CreateFishnet_management(FISHNET_FC, ORIGIN_COORDINATE, Y_AXIS_COORDINATE, None, None, NUM_ROWS, NUM_COLUMNS, OPPOSITE_CORNER, LABELS, None, GEOMETRY_TYPE) # Build dictionary of fishnet cells and hazard count per cell. # The 3x3 Fishnet is generated from bottom left to top right, i.e # SW, S, SE, W, CENTER, E, NW, N and lastly NE. See the grid # below, generated at http://www.tablesgenerator.com/text_tables # +----+--------+----+ # | NW | N | NE | # +----+--------+----+ # | W | CENTER | E | # +----+--------+----+ # | SW | S | SE | # +----+--------+----+ # Create a dictionary to hold the predefined keys and values
if ponto: x_max = max(x_max, ponto.X) y_max = max(y_max, ponto.Y) x_min = min(x_min, ponto.X) y_min = min(y_min, ponto.Y) # Cria a grade originCoordinate = ("{} {}".format(x_min, y_min)) yAxisCoordinate = ("{} {}".format(x_min, y_max)) oppositeCoorner = ("{} {}".format(x_max, y_max)) templateExtent = ("{} {} {} {}".format(x_max, x_min, y_min, y_max)) celula = float(Densidade) * (100) tamanho = str(celula) arcpy.CreateFishnet_management("in_memory/grids", originCoordinate, yAxisCoordinate, tamanho, tamanho, "0", "0", oppositeCoorner, "NO_LABELS", "#", "POLYGON") # Recorta a grade com o contorno arcpy.Intersect_analysis(["in_memory/grids", arquivo_projetado], saida_um, "ALL") # Define o sistema de coordenadas para projetar arcpy.DefineProjection_management(saida_um, srid) # Projeta novamente para Coordenadas Geográficas arcpy.Project_management(saida_um, Saida, arcpy.SpatialReference(4326)) # Caso o arquivo seja em coordenadas planas else: # Inicializa a extenssão da grade